Programs & Examples On #Borderless

How to create standard Borderless buttons (like in the design guideline mentioned)?

If you want to achieve the same programmatically :

(this is C# but easily transatable to Java)

Button button = new Button(new ContextThemeWrapper(Context, Resource.Style.Widget_AppCompat_Button_Borderless_Colored), null, Resource.Style.Widget_AppCompat_Button_Borderless_Colored);

Match

    <Button
       style="@style/Widget.AppCompat.Button.Borderless.Colored"
    .../>

Force div element to stay in same place, when page is scrolled

Use position: fixed instead of position: absolute.

See here.

Are (non-void) self-closing tags valid in HTML5?

However -just for the record- this is invalid:

<address class="vcard">
  <svg viewBox="0 0 800 400">
    <rect width="800" height="400" fill="#000">
  </svg>
</address>

And a slash here would make it valid again:

    <rect width="800" height="400" fill="#000"/>

SVN Commit failed, access forbidden

As a new user to these two software packages, I experienced the exact same problem. As was also discovered above, my solution was to use the same case letters as is in the Repository path.

Here's a tip that I find helpful: In VisualSVN, you can right click on the path, then click "Copy URL to Clipboard" for pasting in Tortoise to be sure that the path is the identical case.

Initializing ArrayList with some predefined values

Java 9 allows you to create an unmodifiable list with a single line of code using List.of factory:

public class Main {
    public static void main(String[] args) {
        List<String> examples = List.of("one", "two", "three");
        System.out.println(examples);
    }
}

Output:

[one, two, three]

Must declare the scalar variable

If someone else comes across this question while no solution here made my sql file working, here's what my mistake was:

I have been exporting the contents of my database via the 'Generate Script' command of Microsofts' Server Management Studio and then doing some operations afterwards while inserting the generated data in another instance.

Due to the generated export, there have been a bunch of "GO" statements in the sql file.

What I didn't know was that variables declared at the top of a file aren't accessible as far as a GO statement is executed. Therefore I had to remove the GO statements in my sql file and the error "Must declare the scalar variable xy" was gone!

Laravel Eloquent LEFT JOIN WHERE NULL

You can also specify the columns in a select like so:

$c = Customer::select('*', DB::raw('customers.id AS id, customers.first_name AS first_name, customers.last_name AS last_name'))
->leftJoin('orders', function($join) {
  $join->on('customers.id', '=', 'orders.customer_id') 
})->whereNull('orders.customer_id')->first();

When do you use map vs flatMap in RxJava?

In that scenario use map, you don't need a new Observable for it.

you should use Exceptions.propagate, which is a wrapper so you can send those checked exceptions to the rx mechanism

Observable<String> obs = Observable.from(jsonFile).map(new Func1<File, String>() { 
    @Override public String call(File file) {
        try { 
            return new Gson().toJson(new FileReader(file), Object.class);
        } catch (FileNotFoundException e) {
            throw Exceptions.propagate(t); /will propagate it as error
        } 
    } 
});

You then should handle this error in the subscriber

obs.subscribe(new Subscriber<String>() {
    @Override 
    public void onNext(String s) { //valid result }

    @Override 
    public void onCompleted() { } 

    @Override 
    public void onError(Throwable e) { //e might be the FileNotFoundException you got }
};); 

There is an excellent post for it: http://blog.danlew.net/2015/12/08/error-handling-in-rxjava/

What is the total amount of public IPv4 addresses?

https://www.ripe.net/internet-coordination/press-centre/understanding-ip-addressing

For IPv4, this pool is 32-bits (2³²) in size and contains 4,294,967,296 IPv4 addresses.

In case of IPv6

The IPv6 address space is 128-bits (2¹²8) in size, containing 340,282,366,920,938,463,463,374,607,431,768,211,456 IPv6 addresses.

inclusive of RESERVED IP

 Reserved address blocks
 Range  Description Reference

 0.0.0.0/8  Current network (only valid as source address)  RFC 6890
 10.0.0.0/8 Private network RFC 1918
 100.64.0.0/10  Shared Address Space    RFC 6598
 127.0.0.0/8    Loopback    RFC 6890
 169.254.0.0/16 Link-local  RFC 3927
 172.16.0.0/12  Private network RFC 1918
 192.0.0.0/24   IETF Protocol Assignments   RFC 6890
 192.0.2.0/24   TEST-NET-1, documentation and examples  RFC 5737
 192.88.99.0/24 IPv6 to IPv4 relay (includes 2002::/16) RFC 3068
 192.168.0.0/16 Private network RFC 1918
 198.18.0.0/15  Network benchmark tests RFC 2544
 198.51.100.0/24    TEST-NET-2, documentation and examples  RFC 5737
 203.0.113.0/24 TEST-NET-3, documentation and examples  RFC 5737
 224.0.0.0/4    IP multicast (former Class D network)   RFC 5771
 240.0.0.0/4    Reserved (former Class E network)   RFC 1700
 255.255.255.255    Broadcast   RFC 919

wiki has full details and this has details of IPv6.

Java/Groovy - simple date reformatting

oldDate is not in the format of the SimpleDateFormat you are using to parse it.

Try this format: dd-MMM-yyyy - It matches what you're trying to parse.

jquery change class name

I think he wants to replace a class name.

Something like this would work:

$(document).ready(function(){
    $('.blue').removeClass('blue').addClass('green');
});

from http://monstertut.com/2012/06/use-jquery-to-change-css-class/

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

I was getting from a conflict with join table defined in an association class ( with additional custom fields ) annotation and a join table defined in a many-to-many annotation.

The mapping definitions in two entities with a direct many-to-many relationship appeared to result in the automatic creation of the join table using the 'joinTable' annotation. However the join table was already defined by an annotation in its underlying entity class and I wanted it to use this association entity class's own field definitions so as to extend the join table with additional custom fields.

The explanation and solution is that identified by FMaz008 above. In my situation, it was thanks to this post in the forum 'Doctrine Annotation Question'. This post draws attention to the Doctrine documentation regarding ManyToMany Uni-directional relationships. Look at the note regarding the approach of using an 'association entity class' thus replacing the many-to-many annotation mapping directly between two main entity classes with a one-to-many annotation in the main entity classes and two 'many-to-one' annotations in the associative entity class. There is an example provided in this forum post Association models with extra fields:

public class Person {

  /** @OneToMany(targetEntity="AssignedItems", mappedBy="person") */
  private $assignedItems;

}

public class Items {

    /** @OneToMany(targetEntity="AssignedItems", mappedBy="item") */
    private $assignedPeople;
}

public class AssignedItems {

    /** @ManyToOne(targetEntity="Person")
    * @JoinColumn(name="person_id", referencedColumnName="id")
    */
private $person;

    /** @ManyToOne(targetEntity="Item")
    * @JoinColumn(name="item_id", referencedColumnName="id")
    */
private $item;

}

What does -1 mean in numpy reshape?

It simply means that you are not sure about what number of rows or columns you can give and you are asking numpy to suggest number of column or rows to get reshaped in.

numpy provides last example for -1 https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html

check below code and its output to better understand about (-1):

CODE:-

import numpy
a = numpy.matrix([[1, 2, 3, 4], [5, 6, 7, 8]])
print("Without reshaping  -> ")
print(a)
b = numpy.reshape(a, -1)
print("HERE We don't know about what number we should give to row/col")
print("Reshaping as (a,-1)")
print(b)
c = numpy.reshape(a, (-1,2))
print("HERE We just know about number of columns")
print("Reshaping as (a,(-1,2))")
print(c)
d = numpy.reshape(a, (2,-1))
print("HERE We just know about number of rows")
print("Reshaping as (a,(2,-1))")
print(d)

OUTPUT :-

Without reshaping  -> 
[[1 2 3 4]
 [5 6 7 8]]
HERE We don't know about what number we should give to row/col
Reshaping as (a,-1)
[[1 2 3 4 5 6 7 8]]
HERE We just know about number of columns
Reshaping as (a,(-1,2))
[[1 2]
 [3 4]
 [5 6]
 [7 8]]
HERE We just know about number of rows
Reshaping as (a,(2,-1))
[[1 2 3 4]
 [5 6 7 8]]

How do I fix this "TypeError: 'str' object is not callable" error?

this part :

"Your new price is: $"(float(price)

asks python to call this string:

"Your new price is: $"

just like you would a function: function( some_args) which will ALWAYS trigger the error:

TypeError: 'str' object is not callable

Find indices of elements equal to zero in a NumPy array

You can search for any scalar condition with:

>>> a = np.asarray([0,1,2,3,4])
>>> a == 0 # or whatver
array([ True, False, False, False, False], dtype=bool)

Which will give back the array as an boolean mask of the condition.

How to get a list of column names

Try this sqlite table schema parser, I implemented the sqlite table parser for parsing the table definitions in PHP.

It returns the full definitions (unique, primary key, type, precision, not null, references, table constraints... etc)

https://github.com/maghead/sqlite-parser

How can JavaScript save to a local file?

It all depends on what you are trying to achieve with "saving locally". Do you want to allow the user to download the file? then <a download> is the way to go. Do you want to save it locally, so you can restore your application state? Then you might want to look into the various options of WebStorage. Specifically localStorage or IndexedDB. The FilesystemAPI allows you to create local virtual file systems you can store arbitrary data in.

Push an associative item into an array in JavaScript

Another method for creating a JavaScript associative array

First create an array of objects,

 var arr = {'name': []};

Next, push the value to the object.

  var val = 2;
  arr['name'].push(val);

To read from it:

var val = arr.name[0];

Can you call ko.applyBindings to bind a partial view?

While Niemeyer's answer is a more correct answer to the question, you could also do the following:

<div>
  <input data-bind="value: VMA.name" />
</div>

<div>
  <input data-bind="value: VMB.name" />
</div>

<script type="text/javascript">
  var viewModels = {
     VMA: {name: ko.observable("Bob")},
     VMB: {name: ko.observable("Ted")}
  };

  ko.applyBindings(viewModels);
</script>

This means you don't have to specify the DOM element, and you can even bind multiple models to the same element, like this:

<div>
  <input data-bind="value: VMA.name() + ' and ' + VMB.name()" />
</div>

How do I free memory in C?

You actually can't manually "free" memory in C, in the sense that the memory is released from the process back to the OS ... when you call malloc(), the underlying libc-runtime will request from the OS a memory region. On Linux, this may be done though a relatively "heavy" call like mmap(). Once this memory region is mapped to your program, there is a linked-list setup called the "free store" that manages this allocated memory region. When you call malloc(), it quickly looks though the free-store for a free block of memory at the size requested. It then adjusts the linked list to reflect that there has been a chunk of memory taken out of the originally allocated memory pool. When you call free() the memory block is placed back in the free-store as a linked-list node that indicates its an available chunk of memory.

If you request more memory than what is located in the free-store, the libc-runtime will again request more memory from the OS up to the limit of the OS's ability to allocate memory for running processes. When you free memory though, it's not returned back to the OS ... it's typically recycled back into the free-store where it can be used again by another call to malloc(). Thus, if you make a lot of calls to malloc() and free() with varying memory size requests, it could, in theory, cause a condition called "memory fragmentation", where there is enough space in the free-store to allocate your requested memory block, but not enough contiguous space for the size of the block you've requested. Thus the call to malloc() fails, and you're effectively "out-of-memory" even though there may be plenty of memory available as a total amount of bytes in the free-store.

how to convert a string to date in mysql?

Here's another two examples.

To output the day, month, and year, you can use:

select STR_TO_DATE('14/02/2015', '%d/%m/%Y');

Which produces:

2015-02-14

To also output the time, you can use:

select STR_TO_DATE('14/02/2017 23:38:12', '%d/%m/%Y %T');

Which produces:

2017-02-14 23:38:12

How to force a html5 form validation without submitting it via jQuery

This way works well for me:

  1. Add onSubmit attribute in your form, don't forget to include return in the value.

    <form id='frm-contact' method='POST' action='' onSubmit="return contact()">
    
  2. Define the function.

    function contact(params) {
        $.ajax({
            url: 'sendmail.php',
            type: "POST",
            dataType: "json",
            timeout: 5000,
            data: { params:params },
            success: function (data, textStatus, jqXHR) {
                // callback
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(jqXHR.responseText);
            }
        });
    
        return false;
    }
    

To add server using sp_addlinkedserver

-- check if server exists in table sys.server

select * from sys.servers

-- set database security

    EXEC sp_configure 'show advanced options', 1
    RECONFIGURE
    GO

    EXEC sp_configure 'ad hoc distributed queries', 1
    RECONFIGURE
    GO

-- add the external dbserver

EXEC sp_addlinkedserver @server='#servername#'

-- add login on external server

EXEC sp_addlinkedsrvlogin '#Servername#', 'false', NULL, '#username#', '#password@123"'

-- control query on remote table

select top (1000) * from [#server#].[#database#].[#schema#].[#table#]

Set selected option of select box

This would be another option:

$('.id_100 option[value=val2]').prop('selected', true);

Is there a query language for JSON?

The current Jaql implementation targets large data processing using a Hadoop cluster, so it might be more than you need. However, it runs easily without a Hadoop cluster (but still requires the Hadoop code and its dependencies to get compiled, which are mostly included). A small implementation of Jaql that could be embedded in Javascript and the a browser would be a great addition to the project.

Your examples above are easily written in jaql:

$data = [{"x": 2, "y": 0}, {"x": 3, "y": 1}, {"x": 4, "y": 1}];

$data -> filter $.y > 0 -> transform $.x -> sum(); // 7

$data -> filter $.y > 0 -> transform $.x; // [3,4]

Of course, there's much more too. For example:

// Compute multiple aggregates and change nesting structure:
$data -> group by $y = $.y into { $y, s:sum($[*].x), n:count($), xs:$[*].x}; 
    // [{ "y": 0, "s": 2, "n": 1, "xs": [2]   },
    //  { "y": 1, "s": 7, "n": 2, "xs": [3,4] }]

// Join multiple data sets:
$more = [{ "y": 0, "z": 5 }, { "y": 1, "z": 6 }];
join $data, $more where $data.y == $more.y into {$data, $more};
    // [{ "data": { "x": 2, "y": 0 }, "more": { "y": 0, "z": 5 }},
    //  { "data": { "x": 3, "y": 1 }, "more": { "y": 1, "z": 6 }},
    //  { "data": { "x": 4, "y": 1 }, "more": { "y": 1, "z": 6 }}]

Jaql can be downloaded/discussed at http://code.google.com/p/jaql/

How do I increase the scrollback buffer in a running screen session?

As Already mentioned we have two ways!

 Per screen (session) interactive setting

And it's done interactively! And take effect immediately!

CTRL + A followed by : And we type scrollback 1000000 And hit ENTER

You detach from the screen and come back! It will be always the same.

You open another new screen! And the value is reset again to default! So it's not a global setting!

 And the permanent default setting

Which is done by adding defscrollback 1000000 to .screenrc (in home)

defscrollback and not scrollback (def stand for default)

What you need to know is if the file is not created ! You create it !

> cd ~ && vim .screenrc

And you add defscrollback 1000000 to it!

Or in one command

> echo "defscrollback 1000000" >> .screenrc

(if not created already)

Taking effect

When you add the default to .screenrc! The already running screen at re-attach will not take effect! The .screenrc run at the screen creation! And it make sense! Just as with a normal console and shell launch!

And all the new created screens will have the set value!

Checking the screen effective buffer size

To check type CTRL + A followed by i

And The result will be as

enter image description here

Importantly the buffer size is the number after the + sign
(in the illustration i set it to 1 000 000)

Note too that when you change it interactively! The effect is immediate and take over the default value!

Scrolling

CTRL+ A followed by ESC (to enter the copy mode).

Then navigate with Up,Down or PgUp PgDown

And ESC again to quit that mode.

(Extra info: to copy hit ENTER to start selecting! Then ENTER again to copy! Simple and cool)

Now the buffer is bigger!

And that's sum it up for the important details!

How can I delete derived data in Xcode 8?

In Xcode 8, all the derived data is automatically cleaned. If you want to do it by hand, go to Locations tab from the Preferences, locate project's derived data folder, and delete files related to the project.

In macOS 10.12 and later, Xcode cleans up stale derived data, precompiled headers, and module caches. (23282174)

Xcode 8.0 Release Notes

Credits to @charmingToad

But from what I observed, the same behaviour is typical when using Xcode 8 on OS X 10.11.5/6

AngularJS 1.2 $injector:modulerr

A noob error can be forgetting to include the module js

<script src="app/modules/myModule.js"></script>

files in the index.html at all

jQuery or Javascript - how to disable window scroll without overflow:hidden;

CSS 'fixed' solution (like Facebook does):

body_temp = $("<div class='body_temp' />")
    .append($('body').contents())
    .css('position', 'fixed')
    .css('top', "-" + scrolltop + 'px')
    .width($(window).width())
    .appendTo('body');

to toggle to normal state:

var scrolltop = Math.abs($('.body_temp').position().top);
$('body').append($('.body_temp').contents()).scrollTop(scrolltop);

Maven Installation OSX Error Unsupported major.minor version 51.0

The problem is because you haven't set JAVA_HOME in Mac properly. In order to do that, you should do set it like this:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_40.jdk/Contents/Home

In my case my JDK installation is jdk1.8.0_40, make sure you type yours.

Then you can use maven commands.

Regards!

Java constructor/method with optional parameters?

You can't have optional arguments that default to a certain value in Java. The nearest thing to what you are talking about is java varargs whereby you can pass an arbitrary number of arguments (of the same type) to a method.

How is CountDownLatch used in Java Multithreading?

CoundDownLatch enables you to make a thread wait till all other threads are done with their execution.

Pseudo code can be:

// Main thread starts
// Create CountDownLatch for N threads
// Create and start N threads
// Main thread waits on latch
// N threads completes there tasks are returns
// Main thread resume execution

Java 32-bit vs 64-bit compatibility

I accidentally ran our (largeish) application on a 64bit VM rather than a 32bit VM and didn't notice until some external libraries (called by JNI) started failing.

Data serialized on a 32bit platform was read in on the 64bit platform with no issues at all.

What sort of issues are you getting? Do some things work and not others? Have you tried attaching JConsole etc and have a peak around?

If you have a very big VM you may find that GC issues in 64 bit can affect you.

How can I easily convert DataReader to List<T>?

I would (and have) started to use Dapper. To use your example would be like (written from memory):

public List<CustomerEntity> GetCustomerList()
{
    using (DbConnection connection = CreateConnection())
    {
        return connection.Query<CustomerEntity>("procToReturnCustomers", commandType: CommandType.StoredProcedure).ToList();
    }
}

CreateConnection() would handle accessing your db and returning a connection.

Dapper handles mapping datafields to properties automatically. It also supports multiple types and result sets and is very fast.

Query returns IEnumerable hence the ToList().

Auto-loading lib files in Rails 4

Use config.to_prepare to load you monkey patches/extensions for every request in development mode.

config.to_prepare do |action_dispatcher|
 # More importantly, will run upon every request in development, but only once (during boot-up) in production and test.
 Rails.logger.info "\n--- Loading extensions for #{self.class} "
 Dir.glob("#{Rails.root}/lib/extensions/**/*.rb").sort.each do |entry|
   Rails.logger.info "Loading extension(s): #{entry}"
   require_dependency "#{entry}"
 end
 Rails.logger.info "--- Loaded extensions for #{self.class}\n"

end

how to compare two elements in jquery

Random AirCoded example of testing "set equality" in jQuery:

$.fn.isEqual = function($otherSet) {
  if (this === $otherSet) return true;
  if (this.length != $otherSet.length) return false;
  var ret = true;
  this.each(function(idx) { 
    if (this !== $otherSet[idx]) {
       ret = false; return false;
    }
  });
  return ret;
};

var a=$('#start > div:last-child');
var b=$('#start > div.live')[0];

console.log($(b).isEqual(a));

How to set array length in c# dynamically

If you don't want to use a List, ArrayList, or other dynamically-sized collection and then convert to an array (that's the method I'd recommend, by the way), then you'll have to allocate the array to its maximum possible size, keep track of how many items you put in it, and then create a new array with just those items in it:

private Update BuildMetaData(MetaData[] nvPairs)
{
    Update update = new Update();
    InputProperty[] ip = new InputProperty[20];  // how to make this "dynamic"
    int i;
    for (i = 0; i < nvPairs.Length; i++)
    {
        if (nvPairs[i] == null) break;
        ip[i] = new InputProperty(); 
        ip[i].Name = "udf:" + nvPairs[i].Name;
        ip[i].Val = nvPairs[i].Value;
    }
    if (i < nvPairs.Length)
    {
        // Create new, smaller, array to hold the items we processed.
        update.Items = new InputProperty[i];
        Array.Copy(ip, update.Items, i);
    }
    else
    {
        update.Items = ip;
    }
    return update;
}

An alternate method would be to always assign update.Items = ip; and then resize if necessary:

update.Items = ip;
if (i < nvPairs.Length)
{
    Array.Resize(update.Items, i);
}

It's less code, but will likely end up doing the same amount of work (i.e. creating a new array and copying the old items).

Creating a JavaScript cookie on a domain and reading it across sub domains

Here is a working example :

document.cookie = "testCookie=cookieval; domain=." + 
location.hostname.split('.').reverse()[1] + "." + 
location.hostname.split('.').reverse()[0] + "; path=/"

This is a generic solution that takes the root domain from the location object and sets the cookie. The reversing is because you don't know how many subdomains you have if any.

Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired

While the form has @csrf, it still shows 419 pages has expired

I solved it after update SESSION_SECURE_COOKIE option to false in config/session.php

'secure' => env('SESSION_SECURE_COOKIE', false)

than clear cache

Is it possible to have multiple statements in a python lambda expression?

Yes it is possible. Try below code snippet.

x = [('human', 1), ('i', 2), ('am', 1), ('.', 1), ('love', 1), ('python', 3), ('', 1),
  ('run', 1), ('is', 2), ('robust', 1), ('hello', 1), ('spark', 2), ('to', 1), ('analysis', 2), ('on', 1), ('big', 1), ('data', 1), ('with', 1), ('analysis', 1), ('great', 1)
]

rdd_filter = rdd1_word_cnt_sum.filter(lambda x: 'python' in x or 'human' in x or 'big' in x)
rdd_filter.collect()

Angular JS: What is the need of the directive’s link function when we already had directive’s controller with scope?

The controller function/object represents an abstraction model-view-controller (MVC). While there is nothing new to write about MVC, it is still the most significant advanatage of angular: split the concerns into smaller pieces. And that's it, nothing more, so if you need to react on Model changes coming from View the Controller is the right person to do that job.

The story about link function is different, it is coming from different perspective then MVC. And is really essential, once we want to cross the boundaries of a controller/model/view (template).

Let' start with the parameters which are passed into the link function:

function link(scope, element, attrs) {
  • scope is an Angular scope object.
  • element is the jqLite-wrapped element that this directive matches.
  • attrs is an object with the normalized attribute names and their corresponding values.

To put the link into the context, we should mention that all directives are going through this initialization process steps: Compile, Link. An Extract from Brad Green and Shyam Seshadri book Angular JS:

Compile phase (a sister of link, let's mention it here to get a clear picture):

In this phase, Angular walks the DOM to identify all the registered directives in the template. For each directive, it then transforms the DOM based on the directive’s rules (template, replace, transclude, and so on), and calls the compile function if it exists. The result is a compiled template function,

Link phase:

To make the view dynamic, Angular then runs a link function for each directive. The link functions typically creates listeners on the DOM or the model. These listeners keep the view and the model in sync at all times.

A nice example how to use the link could be found here: Creating Custom Directives. See the example: Creating a Directive that Manipulates the DOM, which inserts a "date-time" into page, refreshed every second.

Just a very short snippet from that rich source above, showing the real manipulation with DOM. There is hooked function to $timeout service, and also it is cleared in its destructor call to avoid memory leaks

.directive('myCurrentTime', function($timeout, dateFilter) {

 function link(scope, element, attrs) {

 ...

 // the not MVC job must be done
 function updateTime() {
   element.text(dateFilter(new Date(), format)); // here we are manipulating the DOM
 }

 function scheduleUpdate() {
   // save the timeoutId for canceling
   timeoutId = $timeout(function() {
     updateTime(); // update DOM
     scheduleUpdate(); // schedule the next update
   }, 1000);
 }

 element.on('$destroy', function() {
   $timeout.cancel(timeoutId);
 });

 ...

Spring JPA selecting specific columns

With the newer Spring versions One can do as follows:

If not using native query this can done as below:

public interface ProjectMini {
    String getProjectId();
    String getProjectName();
}

public interface ProjectRepository extends JpaRepository<Project, String> { 
    @Query("SELECT p FROM Project p")
    List<ProjectMini> findAllProjectsMini();
}

Using native query the same can be done as below:

public interface ProjectRepository extends JpaRepository<Project, String> { 
    @Query(value = "SELECT projectId, projectName FROM project", nativeQuery = true)
    List<ProjectMini> findAllProjectsMini();
}

For detail check the docs

How to get screen width without (minus) scrollbar?

None of these solutions worked for me, however I was able to fix it by taking the width and subtracting the width of the scroll bar. I'm not sure how cross-browser compatible this is.

How do you implement a circular buffer in C?

// Note power of two buffer size
#define kNumPointsInMyBuffer 1024 

typedef struct _ringBuffer {
    UInt32 currentIndex;
    UInt32 sizeOfBuffer;
    double data[kNumPointsInMyBuffer];
} ringBuffer;

// Initialize the ring buffer
ringBuffer *myRingBuffer = (ringBuffer *)calloc(1, sizeof(ringBuffer));
myRingBuffer->sizeOfBuffer = kNumPointsInMyBuffer;
myRingBuffer->currentIndex = 0;

// A little function to write into the buffer
// N.B. First argument of writeIntoBuffer() just happens to have the
// same as the one calloc'ed above. It will only point to the same
// space in memory if the calloc'ed pointer is passed to
// writeIntoBuffer() as an arg when the function is called. Consider
// using another name for clarity
void writeIntoBuffer(ringBuffer *myRingBuffer, double *myData, int numsamples) {
    // -1 for our binary modulo in a moment
    int buffLen = myRingBuffer->sizeOfBuffer - 1;
    int lastWrittenSample = myRingBuffer->currentIndex;

    int idx;
    for (int i=0; i < numsamples; ++i) {
        // modulo will automagically wrap around our index
        idx = (i + lastWrittenSample) & buffLen; 
        myRingBuffer->data[idx] = myData[i];
    }

    // Update the current index of our ring buffer.
    myRingBuffer->currentIndex += numsamples;
    myRingBuffer->currentIndex &= myRingBuffer->sizeOfBuffer - 1;
}

As long as your ring buffer's length is a power of two, the incredibly fast binary "&" operation will wrap around your index for you. For my application, I'm displaying a segment of audio to the user from a ring buffer of audio acquired from a microphone.

I always make sure that the maximum amount of audio that can be displayed on screen is much less than the size of the ring buffer. Otherwise you might be reading and writing from the same chunk. This would likely give you weird display artifacts.

How can I send and receive WebSocket messages on the server side?

C# Implementation

Browser -> Server

    private String DecodeMessage(Byte[] bytes)
    {
        String incomingData = String.Empty;
        Byte secondByte = bytes[1];
        Int32 dataLength = secondByte & 127;
        Int32 indexFirstMask = 2;
        if (dataLength == 126)
            indexFirstMask = 4;
        else if (dataLength == 127)
            indexFirstMask = 10;

        IEnumerable<Byte> keys = bytes.Skip(indexFirstMask).Take(4);
        Int32 indexFirstDataByte = indexFirstMask + 4;

        Byte[] decoded = new Byte[bytes.Length - indexFirstDataByte];
        for (Int32 i = indexFirstDataByte, j = 0; i < bytes.Length; i++, j++)
        {
            decoded[j] = (Byte)(bytes[i] ^ keys.ElementAt(j % 4));
        }

        return incomingData = Encoding.UTF8.GetString(decoded, 0, decoded.Length);
    }

Server -> Browser

    private static Byte[] EncodeMessageToSend(String message)
    {
        Byte[] response;
        Byte[] bytesRaw = Encoding.UTF8.GetBytes(message);
        Byte[] frame = new Byte[10];

        Int32 indexStartRawData = -1;
        Int32 length = bytesRaw.Length;

        frame[0] = (Byte)129;
        if (length <= 125)
        {
            frame[1] = (Byte)length;
            indexStartRawData = 2;
        }
        else if (length >= 126 && length <= 65535)
        {
            frame[1] = (Byte)126;
            frame[2] = (Byte)((length >> 8) & 255);
            frame[3] = (Byte)(length & 255);
            indexStartRawData = 4;
        }
        else
        {
            frame[1] = (Byte)127;
            frame[2] = (Byte)((length >> 56) & 255);
            frame[3] = (Byte)((length >> 48) & 255);
            frame[4] = (Byte)((length >> 40) & 255);
            frame[5] = (Byte)((length >> 32) & 255);
            frame[6] = (Byte)((length >> 24) & 255);
            frame[7] = (Byte)((length >> 16) & 255);
            frame[8] = (Byte)((length >> 8) & 255);
            frame[9] = (Byte)(length & 255);

            indexStartRawData = 10;
        }

        response = new Byte[indexStartRawData + length];

        Int32 i, reponseIdx = 0;

        //Add the frame bytes to the reponse
        for (i = 0; i < indexStartRawData; i++)
        {
            response[reponseIdx] = frame[i];
            reponseIdx++;
        }

        //Add the data bytes to the response
        for (i = 0; i < length; i++)
        {
            response[reponseIdx] = bytesRaw[i];
            reponseIdx++;
        }

        return response;
    }

Service has zero application (non-infrastructure) endpoints

I just worked through this issue on my service. Here is the error I was receiving:

Service 'EmailSender.Wcf.EmailService' has zero application (non-infrastructure) endpoints. This might be because no configuration file was found for your application, or because no service element matching the service name could be found in the configuration file, or because no endpoints were defined in the service element.

Here are the two steps I used to fix it:

  1. Use the correct fully-qualified class name:

    <service behaviorConfiguration="DefaultBehavior" name="EmailSender.Wcf.EmailService">
    
  2. Enable an endpoint with mexHttpBinding, and most importantly, use the IMetadataExchange contract:

    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
    

Where can I find System.Web.Helpers, System.Web.WebPages, and System.Web.Razor?

The issue is a missing or outdated version of MVC. I was running VS 2015Preview and could resolve the issue by installing the latest version of MVC via NuGet.

Just in case anyone is still coming across this one.

How to skip the OPTIONS preflight request?

Preflight is a web security feature implemented by the browser. For Chrome you can disable all web security by adding the --disable-web-security flag.

For example: "C:\Program Files\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="C:\newChromeSettingsWithoutSecurity" . You can first create a new shortcut of chrome, go to its properties and change the target as above. This should help!

How can I use UserDefaults in Swift?

In class A, set value for key:

let text = "hai"  
UserDefaults.standard.setValue(text, forKey: "textValue")

In class B, get the value for the text using the key which declared in class A and assign it to respective variable which you need:

var valueOfText  = UserDefaults.value(forKey: "textValue")

SQL Server: the maximum number of rows in table

I do not know of a row limit, but I know tables with more than 170 million rows. You may speed it up using partitioned tables (2005+) or views that connect multiple tables.

Do conditional INSERT with SQL?

You can do that with a single statement and a subquery in nearly all relational databases.

INSERT INTO targetTable(field1) 
SELECT field1
FROM myTable
WHERE NOT(field1 IN (SELECT field1 FROM targetTable))

Certain relational databases have improved syntax for the above, since what you describe is a fairly common task. SQL Server has a MERGE syntax with all kinds of options, and MySQL has optional INSERT OR IGNORE syntax.

Edit: SmallSQL's documentation is fairly sparse as to which parts of the SQL standard it implements. It may not implement subqueries, and as such you may be unable to follow the advice above, or anywhere else, if you need to stick with SmallSQL.

Best way to convert text files between character sets?

If macOS GUI applications are your bread and butter, SubEthaEdit is the text editor I usually go to for encoding-wrangling — its "conversion preview" allows you to see all invalid characters in the output encoding, and fix/remove them.

And it's open-source now, so yay for them .

Android: How to change the ActionBar "Home" Icon to be something other than the app icon?

The ActionBar will use the android:logo attribute of your manifest, if one is provided. That lets you use separate drawable resources for the icon (Launcher) and the logo (ActionBar, among other things).

Bootstrap 3: How do you align column content to bottom of row

I don't know why but for me the solution proposed by Marius Stanescu is breaking the specificity of col (a col-md-3 followed by a col-md-4 will take all of the twelve row)

I found another working solution :

.bottom-column 
{
   display: inline-block;
   vertical-align: middle;
   float: none;
}

Read file from line 2 or skip header row

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

How do I search for an object by its ObjectId in the mongo console?

To use Objectid method you don't need to import it. It is already on the mongodb object.

_x000D_
_x000D_
var ObjectId = new db.ObjectId('58c85d1b7932a14c7a0a320d');_x000D_
db.yourCollection.findOne({ _id: ObjectId }, function (err, info) {_x000D_
   console.log(info)_x000D_
});_x000D_
               
_x000D_
_x000D_
_x000D_

When to choose mouseover() and hover() function?

You can try it out http://api.jquery.com/mouseover/ on the jQuery doc page. It's a nice little, interactive demo that makes it very clear and you can actually see for yourself.

In short, you'll notice that a mouse over event occurs on an element when you are over it - coming from either its child OR parent element, but a mouse enter event only occurs when the mouse moves from the parent element to the element.

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

This fixed the problem by having it as the first two lines of the script:

!pip install opencv-python
!apt update && apt install -y libsm6 libxext6
!apt-get install -y libxrender-dev

UITableView - scroll to the top

For tables that have a contentInset, setting the content offset to CGPointZero will not work. It'll scroll to the content top vs. scrolling to the table top.

Taking content inset into account produces this instead:

[tableView setContentOffset:CGPointMake(0, -tableView.contentInset.top) animated:NO];

ASP.NET MVC: No parameterless constructor defined for this object

In my case, my class had the [Serializable] attribute.

You are required to have a constructor that takes no parameters if your class is [Serializable]

How can I get the list of files in a directory using C or C++?

This answer should work for Windows users that have had trouble getting this working with Visual Studio with any of the other answers.

  1. Download the dirent.h file from the github page. But is better to just use the Raw dirent.h file and follow my steps below (it is how I got it to work).

    Github page for dirent.h for Windows: Github page for dirent.h

    Raw Dirent File: Raw dirent.h File

  2. Go to your project and Add a new Item (Ctrl+Shift+A). Add a header file (.h) and name it dirent.h.

  3. Paste the Raw dirent.h File code into your header.

  4. Include "dirent.h" in your code.

  5. Put the below void filefinder() method in your code and call it from your main function or edit the function how you want to use it.

    #include <stdio.h>
    #include <string.h>
    #include "dirent.h"
    
    string path = "C:/folder"; //Put a valid path here for folder
    
    void filefinder()
    {
        DIR *directory = opendir(path.c_str());
        struct dirent *direntStruct;
    
        if (directory != NULL) {
            while (direntStruct = readdir(directory)) {
                printf("File Name: %s\n", direntStruct->d_name); //If you are using <stdio.h>
                //std::cout << direntStruct->d_name << std::endl; //If you are using <iostream>
            }
        }
        closedir(directory);
    }
    

Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?

With

with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.

Example:

User > hasMany > Post

$users = User::with('posts')->get();
foreach($users as $user){
    $users->posts; // posts is already loaded and no additional DB query is run
}

Has

has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.

Example:

User > hasMany > Post

$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection

WhereHas

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

Example:

User > hasMany > Post

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned

How can I get the full/absolute URL (with domain) in Django?

There is also ABSOLUTE_URL_OVERRIDES available as a setting

https://docs.djangoproject.com/en/2.1/ref/settings/#absolute-url-overrides

But that overrides get_absolute_url(), which may not be desirable.

Instead of installing sites framework just for this or doing some of the other stuff mentioned here that relies on request object, I think the better solution is to place this in models.py

Define BASE_URL in settings.py, then import it into models.py and make an abstract class (or add it to one you're already using) that defines get_truly_absolute_url(). It could be as simple as:

def get_truly_absolute_url(self):
    return BASE_URL + self.get_absolute_url()

Subclass it and now you can use it everywhere.

What IDE to use for Python?

Results

Spreadsheet version

spreadsheet screenshot

Alternatively, in plain text: (also available as a a screenshot)

                         Bracket Matching -.  .- Line Numbering
                          Smart Indent -.  |  |  .- UML Editing / Viewing
         Source Control Integration -.  |  |  |  |  .- Code Folding
                    Error Markup -.  |  |  |  |  |  |  .- Code Templates
  Integrated Python Debugging -.  |  |  |  |  |  |  |  |  .- Unit Testing
    Multi-Language Support -.  |  |  |  |  |  |  |  |  |  |  .- GUI Designer (Qt, Eric, etc)
   Auto Code Completion -.  |  |  |  |  |  |  |  |  |  |  |  |  .- Integrated DB Support
     Commercial/Free -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  .- Refactoring
   Cross Platform -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom              |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |  |  |  |  |*many plugins
Editra            |Y |F |Y |Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |
Emacs             |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
Eric Ide          |Y |F |Y |  |Y |Y |  |Y |  |Y |  |Y |  |Y |  |  |  |
Geany             |Y |F |Y*|Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |*very limited
Gedit             |Y |F |Y¹|Y |  |  |  |Y |Y |Y |  |  |Y²|  |  |  |  |¹with plugin; ²sort of
Idle              |Y |F |Y |  |Y |  |  |Y |Y |  |  |  |  |  |  |  |  |
IntelliJ          |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit             |Y |F |  |Y |  |  |  |  |Y |Y |  |Y |  |  |  |  |  |
KDevelop          |Y |F |Y*|Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |*no type inference
Komodo            |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |Y |  |
NetBeans*         |Y |F |Y |Y |Y |  |Y |Y |Y |Y |Y |Y |Y |Y |  |  |Y |*pre-v7.0
Notepad++         |W |F |Y |Y |  |Y*|Y*|Y*|Y |Y |  |Y |Y*|  |  |  |  |*with plugin
Pfaide            |W |C |Y |Y |  |  |  |Y |Y |Y |  |Y |Y |  |  |  |  |
PIDA              |LW|F |Y |Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |VIM based
PTVS              |W |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |  |  |Y*|  |Y |*WPF bsed
PyCharm           |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse)   |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
PyScripter        |W |F |Y |  |Y |Y |  |Y |Y |Y |  |Y |Y |Y |  |  |  |
PythonWin         |W |F |Y |  |Y |  |  |Y |Y |  |  |Y |  |  |  |  |  |
SciTE             |Y |F¹|  |Y |  |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |¹Mac version is
ScriptDev         |W |C |Y |Y |Y |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |    commercial
Spyder            |Y |F |Y |  |Y |Y |  |Y |Y |Y |  |  |  |  |  |  |  |
Sublime Text      |Y |CF|Y |Y |  |Y |Y |Y |Y |Y |  |Y |Y |Y*|  |  |  |extensible w/Python,
TextMate          |M |F |  |Y |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |    *PythonTestRunner
UliPad            |Y |F |Y |Y |Y |  |  |Y |Y |  |  |  |Y |Y |  |  |  |
Vim               |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |
Visual Studio     |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde           |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |*support for C
Zeus              |W |C |  |  |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
   Cross Platform -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
     Commercial/Free -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  '- Refactoring
   Auto Code Completion -'  |  |  |  |  |  |  |  |  |  |  |  |  '- Integrated DB Support
    Multi-Language Support -'  |  |  |  |  |  |  |  |  |  |  '- GUI Designer (Qt, Eric, etc)
  Integrated Python Debugging -'  |  |  |  |  |  |  |  |  '- Unit Testing
                    Error Markup -'  |  |  |  |  |  |  '- Code Templates
         Source Control Integration -'  |  |  |  |  '- Code Folding
                          Smart Indent -'  |  |  '- UML Editing / Viewing
                         Bracket Matching -'  '- Line Numbering

Acronyms used:

 L  - Linux
 W  - Windows
 M  - Mac
 C  - Commercial
 F  - Free
 CF - Commercial with Free limited edition
 ?  - To be confirmed

I don't mention basics like syntax highlighting as I expect these by default.


This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.

PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?

We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments

Submit edits to the spreadsheet

How to get the index of an element in an IEnumerable?

The way I'm currently doing this is a bit shorter than those already suggested and as far as I can tell gives the desired result:

 var index = haystack.ToList().IndexOf(needle);

It's a bit clunky, but it does the job and is fairly concise.

How to force JS to do math instead of putting two strings together

its really simple just

var total = (1 * yourFirstVariablehere) + (1 * yourSecondVariablehere)

this forces javascript to multiply because there is no confusion for * sign in javascript.

How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

If you already have material-icons working in your web project, just need to update your reference in the html file and the used class for icons:

html reference:

Before

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />

After

<link href="https://fonts.googleapis.com/css?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp"
rel="stylesheet" />

material icons class:

After that just check wich className are you using:

Before:

<i className="material-icons">weekend</i>

After:

<i className="material-icons-outlined">weekend</i>

that works for me... Pura vida!

PreparedStatement setNull(..)

This guide says:

6.1.5 Sending JDBC NULL as an IN parameter

The setNull method allows a programmer to send a JDBC NULL (a generic SQL NULL) value to the database as an IN parameter. Note, however, that one must still specify the JDBC type of the parameter.

A JDBC NULL will also be sent to the database when a Java null value is passed to a setXXX method (if it takes Java objects as arguments). The method setObject, however, can take a null value only if the JDBC type is specified.

So yes they're equivalent.

What does it mean by select 1 from table?

I see it is always used in SQL injection,such as:

www.urlxxxxx.com/xxxx.asp?id=99 union select 1,2,3,4,5,6,7,8,9 from database;

These numbers can be used to guess where the database exists and guess the column name of the database you specified.And the values of the tables.

remove kernel on jupyter notebook

In jupyter notebook run:

!echo y | jupyter kernelspec uninstall unwanted-kernel 

In anaconda prompt run:

jupyter kernelspec uninstall unwanted-kernel

String to HashMap JAVA

You can also use JSONObject class from json.org to this will convert your HashMap to JSON string which is well formatted

Example:

Map<String,Object> map = new HashMap<>();
map.put("myNumber", 100);
map.put("myString", "String");

JSONObject json= new JSONObject(map);

String result= json.toString();

System.out.print(result);

result:

{'myNumber':100, 'myString':'String'}

Your can also get key from it like

System.out.print(json.get("myNumber"));

result:

100

How to check if a text field is empty or not in swift

As now in swift 3 / xcode 8 text property is optional you can do it like this:

if ((textField.text ?? "").isEmpty) {
    // is empty
}

or:

if (textField.text?.isEmpty ?? true) {
    // is empty
}

Alternatively you could make an extenstion such as below and use it instead:

extension UITextField {
    var isEmpty: Bool {
        return text?.isEmpty ?? true
    }
}

...

if (textField.isEmpty) {
    // is empty
}

should use size_t or ssize_t

ssize_t is used for functions whose return value could either be a valid size, or a negative value to indicate an error. It is guaranteed to be able to store values at least in the range [-1, SSIZE_MAX] (SSIZE_MAX is system-dependent).

So you should use size_t whenever you mean to return a size in bytes, and ssize_t whenever you would return either a size in bytes or a (negative) error value.

See: http://pubs.opengroup.org/onlinepubs/007908775/xsh/systypes.h.html

SQL query question: SELECT ... NOT IN

Sorry if I've missed the point, but wouldn't the following do what you want on it's own?

SELECT distinct idCustomer FROM reservations 
WHERE DATEPART(hour, insertDate) >= 2

How to get value of checked item from CheckedListBox?

To get the all selected Items in a CheckedListBox try this:

In this case ths value is a String but it's run with other type of Object:

for (int i = 0; i < myCheckedListBox.Items.Count; i++)
{
    if (myCheckedListBox.GetItemChecked(i) == true)
    {

        MessageBox.Show("This is the value of ceckhed Item " + myCheckedListBox.Items[i].ToString());

    }

}

How do I add a border to an image in HTML?

Jack,

You can learn a great deal about borders, and how to use them at http://www.w3schools.com/css/css_border.asp. That being said, there are a couple different ways you could accomplish this.

Below is how I generally do it, but reading the documentation on w3schools you may come upon your own desired method.

.addBorder {
  /* Thickness, Style, and Color */
  border: 1px solid #000000;
}

<img src="mypicture.jpg" alt="My Picture" class="addBorder" />

Edit:

I noticed the original question was not "How to add a border to an image," but instead it was "how to add in a box around an image using html?" The question was re-written by others, so I'm not 100% sure you wanted a border on your image.

If you just wanted a box around your images, you could use a DIV, with it's own styles:

.imageBox {
  background-color:#f1f1f1;
  padding:10px;
  border:1px solid #000000;
}

<div class="imageBox">
  <img src="picture.jpg" alt="My Picture" />
</div>

Apache: "AuthType not set!" 500 Error

Alternatively, this solution works with both Apache2 version < 2.4 as well as >= 2.4. Make sure that the "version" module is enabled:

a2enmod version

And then use this code instead:

<IfVersion < 2.4>
    Allow from all
</IfVersion>
<IfVersion >= 2.4>
    Require all granted
</IfVersion>

How to use jquery $.post() method to submit form values

Get the value of your textboxes using val() and store them in a variable. Pass those values through $.post. In using the $.Post Submit button you can actually remove the form.

<script>

    username = $("#username").val(); 
    password = $("#password").val();

    $("#post-btn").click(function(){        
        $.post("process.php", { username:username, password:password } ,function(data){
            alert(data);
        });
    });
</script>

Export table to file with column headers (column names) using the bcp utility and SQL Server 2008

I was having the same issue. I needed to export the column header using SQL server bcp utility.This way I exported table "headers" with data into same exported file in one go.

DECLARE @table_name  VARCHAR(50) ='mytable'
DECLARE @columnHeader VARCHAR(8000)
SELECT @columnHeader = COALESCE(@columnHeader+',' ,'')+ ''''+column_name +'''' FROM Nal2013.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=@table_name
SELECT @raw_sql = 'bcp "SELECT '+ @columnHeader +' UNION ALL SELECT * FROM mytable" queryout c:\datafile.csv -c -t, -T -S '+ @@servername
EXEC  xp_cmdshell @raw_sql

Happy coding :)

How to compare two dates in Objective-C

..

NSString *date = @"2009-05-11"
NSString *nowDate = [[[NSDate date]description]substringToIndex: 10];
if([date isEqualToString: nowDate])
{
// your code
}

How to see log files in MySQL?

The MySQL logs are determined by the global variables such as:

To see the settings and their location, run this shell command:

mysql -se "SHOW VARIABLES" | grep -e log_error -e general_log -e slow_query_log

To print the value of error log, run this command in the terminal:

mysql -e "SELECT @@GLOBAL.log_error"

To read content of the error log file in real time, run:

sudo tail -f $(mysql -Nse "SELECT @@GLOBAL.log_error")

Note: Hit Control-C when finish

When general log is enabled, try:

sudo tail -f $(mysql -Nse "SELECT CONCAT(@@datadir, @@general_log_file)")

To use mysql with the password access, add -p or -pMYPASS parameter. To to keep it remembered, you can configure it in your ~/.my.cnf, e.g.

[client]
user=root
password=root

So it'll be remembered for the next time.

Why do I get an error instantiating an interface?

It is what it says, you just cannot instantiate an abstract class. You need to implement it first, then instantiate that class.

IUser user = new User();

Move div to new line

What about something like this.

<div id="movie_item">
    <div class="movie_item_poster">
        <img src="..." style="max-width: 100%; max-height: 100%;">
    </div>

     <div id="movie_item_content">
        <div class="movie_item_content_year">year</div>
        <div class="movie_item_content_title">title</div>
        <div class="movie_item_content_plot">plot</div>
    </div>

    <div class="movie_item_toolbar">
        Lorem Ipsum...
    </div>
</div>

You don't have to float both movie_item_poster AND movie_item_content. Just float one of them...

#movie_item {
    position: relative;
    margin-top: 10px;
    height: 175px;
}

.movie_item_poster {
    float: left;
    height: 150px;
    width: 100px;
}

.movie_item_content {
    position: relative;
}

.movie_item_content_title {
}

.movie_item_content_year {
    float: right;
}

.movie_item_content_plot {
}

.movie_item_toolbar {
    clear: both;
    vertical-align: bottom;
    width: 100%;
    height: 25px;
}

Here it is as a JSFiddle.

An item with the same key has already been added

I had this issue on the DBContext. Got the error when I tried run an update-database in Package Manager console to add a migration:

public virtual IDbSet Status { get; set; }

The problem was that the type and the name were the same. I changed it to:

public virtual IDbSet Statuses { get; set; }

PHP foreach change original array values

Try this

function checkForm($fields){
        foreach($fields as $field){
            if($field['required'] && strlen($_POST[$field['name']]) <= 0){
                $field['value'] = "Some error";
            }
        }
        return $field;
    }

HTTP error 403 in Python 3 Web Scraping

Based on previous answers this has worked for me with Python 3.7

from urllib.request import Request, urlopen

req = Request('Url_Link', headers={'User-Agent': 'XYZ/3.0'})
webpage = urlopen(req, timeout=10).read()

print(webpage)

UNIX export command

export is a built-in command of the bash shell and other Bourne shell variants. It is used to mark a shell variable for export to child processes.

How permission can be checked at runtime without throwing SecurityException?

Enable GPS location Android Studio

  1. Add permission entry in AndroidManifest.Xml

  1. MapsActivity.java

    public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
    
    private GoogleMap mMap;
    private Context context;
    private static final int PERMISSION_REQUEST_CODE = 1;
    Activity activity;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        context = getApplicationContext();
        activity = this;
        super.onCreate(savedInstanceState);
        requestPermission();
        checkPermission();
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    
    }
    
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        LatLng location = new LatLng(0, 0);
        mMap.addMarker(new MarkerOptions().position(location).title("Marker in Bangalore"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
        mMap.setMyLocationEnabled(true);
    }
    
    private void requestPermission() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.ACCESS_FINE_LOCATION)) {
            Toast.makeText(context, "GPS permission allows us to access location data. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show();
        } else {
            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_CODE);
        }
    }
    
    private boolean checkPermission() {
        int result = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION);
        if (result == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            return false;
        }
    }
    

Scale iFrame css width 100% like an image

None of these solutions worked for me inside a Weebly "add your own html" box. Not sure what they are doing with their code. But I found this solution at https://benmarshall.me/responsive-iframes/ and it works perfectly.

CSS

.iframe-container {
  overflow: hidden;
  padding-top: 56.25%;
  position: relative;
}

.iframe-container iframe {
   border: 0;
   height: 100%;
   left: 0;
   position: absolute;
   top: 0;
   width: 100%;
}

/* 4x3 Aspect Ratio */
.iframe-container-4x3 {
  padding-top: 75%;
}

HTML

<div class="iframe-container">
  <iframe src="https://player.vimeo.com/video/106466360" allowfullscreen></iframe>
</div>

What does a lazy val do?

This feature helps not only delaying expensive calculations, but is also useful to construct mutual dependent or cyclic structures. E.g. this leads to an stack overflow:

trait Foo { val foo: Foo }
case class Fee extends Foo { val foo = Faa() }
case class Faa extends Foo { val foo = Fee() }

println(Fee().foo)
//StackOverflowException

But with lazy vals it works fine

trait Foo { val foo: Foo }
case class Fee extends Foo { lazy val foo = Faa() }
case class Faa extends Foo { lazy val foo = Fee() }

println(Fee().foo)
//Faa()

Assert a function/method was not called using Mock

You can check the called attribute, but if your assertion fails, the next thing you'll want to know is something about the unexpected call, so you may as well arrange for that information to be displayed from the start. Using unittest, you can check the contents of call_args_list instead:

self.assertItemsEqual(my_var.call_args_list, [])

When it fails, it gives a message like this:

AssertionError: Element counts were not equal:
First has 0, Second has 1:  call('first argument', 4)

docker run <IMAGE> <MULTIPLE COMMANDS>

For anyone else who came here looking to do the same with docker-compose you just need to prepend bash -c and enclose multiple commands in quotes, joined together with &&.

So in the OPs example docker-compose run image bash -c "cd /path/to/somewhere && python a.py"

Simple export and import of a SQLite database on Android

Import and Export of a SQLite database on Android

Here is my function for export database into device storage

private void exportDB(){
    String DatabaseName = "Sycrypter.db";
    File sd = Environment.getExternalStorageDirectory();
    File data = Environment.getDataDirectory();
    FileChannel source=null;
    FileChannel destination=null;
    String currentDBPath = "/data/"+ "com.synnlabz.sycryptr" +"/databases/"+DatabaseName ;
    String backupDBPath = SAMPLE_DB_NAME;
    File currentDB = new File(data, currentDBPath);
    File backupDB = new File(sd, backupDBPath);
    try {
        source = new FileInputStream(currentDB).getChannel();
        destination = new FileOutputStream(backupDB).getChannel();
        destination.transferFrom(source, 0, source.size());
        source.close();
        destination.close();
        Toast.makeText(this, "Your Database is Exported !!", Toast.LENGTH_LONG).show();
    } catch(IOException e) {
        e.printStackTrace();
    }
}

Here is my function for import database from device storage into android application

private void importDB(){
    String dir=Environment.getExternalStorageDirectory().getAbsolutePath();
    File sd = new File(dir);
    File data = Environment.getDataDirectory();
    FileChannel source = null;
    FileChannel destination = null;
    String backupDBPath = "/data/com.synnlabz.sycryptr/databases/Sycrypter.db";
    String currentDBPath = "Sycrypter.db";
    File currentDB = new File(sd, currentDBPath);
    File backupDB = new File(data, backupDBPath);

    try {
        source = new FileInputStream(currentDB).getChannel();
        destination = new FileOutputStream(backupDB).getChannel();
        destination.transferFrom(source, 0, source.size());
        source.close();
        destination.close();
        Toast.makeText(this, "Your Database is Imported !!", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

insert echo into the specific html element like div which has an id or class

there is no way to specifically target an element with php, you can either embed the php code between a div tag or use jquery which would be longer.

'uint32_t' identifier not found error

You can #include <cstdint>. It's part of C++-standard since 2011.

How to Deserialize XML document

try this block of code if your .xml file has been generated somewhere in disk and if you have used List<T>:

//deserialization

XmlSerializer xmlser = new XmlSerializer(typeof(List<Item>));
StreamReader srdr = new StreamReader(@"C:\serialize.xml");
List<Item> p = (List<Item>)xmlser.Deserialize(srdr);
srdr.Close();`

Note: C:\serialize.xml is my .xml file's path. You can change it for your needs.

Install IPA with iTunes 12

iTunes 12.7 ( Xcode needed )

You cannot install a release ipa directly on your device. Ipa generated withAppStore Distribution Profile requires to be distributed from App Store or TestFlight. However, I found that app panel was removed even for installing ad hoc ipa from iTunes 12.7. I found a workaround to install ad-hoc apps which might help to them who cannot install even ad hoc ipa. Please follow the instructions below,

  1. Connect your device
  2. Open Xcode and go to Window -> Devices
  3. Select the connected device from left panel
  4. Brows the IPA from Installed Apps -> + button
  5. Wait few seconds and its done!

enter image description here

Cannot lower case button text in android studio

In your .xml file within Button add this line--

android:textAllCaps="false"

htaccess redirect to https://www

Similar to Amir Forsati's solution htaccess redirect to https://www but for variable domain name, I suggest:

RewriteEngine on
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%2%{REQUEST_URI} [R=301,L]

Perform commands over ssh with Python

First: I'm surprised that no one has mentioned fabric yet.

Second: For exactly those requirements you describe I've implemented an own python module named jk_simpleexec. It's purpose: Making running commands easy.

Let me explain a little bit about it for you.

The 'executing a command locally' problem

My python module jk_simpleexec provides a function named runCmd(..) that can execute a shell (!) command locally or remotely. This is very simple. Here is an example for local execution of a command:

import jk_simpleexec

cmdResult = jk_simpleexec.runCmd(None, "cd / ; ls -la")

NOTE: Be aware that the returned data is trimmed automatically by default to remove excessive empty lines from STDOUT and STDERR. (Of course this behavior can be deactivated, but for the purpose you've in mind exactly that behavior is what you will want.)

The 'processing the result' problem

What you will receive is an object that contains the return code, STDOUT and STDERR. Therefore it's very easy to process the result.

And this is what you want to do as the command you execute might exist and is launched but might fail in doing what it is intended to do. In the most simple case where you're not interested in STDOUT and STDERR your code will likely look something like this:

cmdResult.raiseExceptionOnError("Something went wrong!", bDumpStatusOnError=True)

For debugging purposes you want to output the result to STDOUT at some time, so for this you can do just this:

cmdResult.dump()

If you would want to process STDOUT it's simple as well. Example:

for line in cmdResult.stdOutLines:
    print(line)

The 'executing a command remotely' problem

Now of course we might want to execute this command remotely on another system. For this we can use the same function runCmd(..) in exactly the same way but we need to specify a fabric connection object first. This can be done like this:

from fabric import Connection

REMOTE_HOST = "myhost"
REMOTE_PORT = 22
REMOTE_LOGIN = "mylogin"
REMOTE_PASSWORD = "mypwd"
c = Connection(host=REMOTE_HOST, user=REMOTE_LOGIN, port=REMOTE_PORT, connect_kwargs={"password": REMOTE_PASSWORD})

cmdResult = jk_simpleexec.runCmd(c, "cd / ; ls -la")

# ... process the result stored in cmdResult ...

c.close()

Everything remains exactly the same, but this time we run this command on another host. This is intended: I wanted to have a uniform API where there are no modifications required in the software if you at some time decide to move from the local host to another host.

The password input problem

Now of course there is the password problem. This has been mentioned above by some users: We might want to ask the user executing this python code for a password.

For this problem I have created an own module quite some time ago. jk_pwdinput. The difference to regular password input is that jk_pwdinput will output some stars instead of just printing nothing. So for every password character you type you will see a star. This way it's more easy for you to enter a password.

Here is the code:

import jk_pwdinput

# ... define other 'constants' such as REMOTE_LOGIN, REMOTE_HOST ...

REMOTE_PASSWORD = jk_pwdinput.readpwd("Password for " + REMOTE_LOGIN + "@" + REMOTE_HOST + ": ")

(For completeness: If readpwd(..) returned None the user canceled the password input with Ctrl+C. In a real world scenario you might want to act on this appropriately.)

Full example

Here is a full example:

import jk_simpleexec
import jk_pwdinput
from fabric import Connection

REMOTE_HOST = "myhost"
REMOTE_PORT = 22
REMOTE_LOGIN = "mylogin"
REMOTE_PASSWORD = jk_pwdinput.readpwd("Password for " + REMOTE_LOGIN + "@" + REMOTE_HOST + ": ")
c = Connection(host=REMOTE_HOST, user=REMOTE_LOGIN, port=REMOTE_PORT, connect_kwargs={"password": REMOTE_PASSWORD})

cmdResult = jk_simpleexec.runCmd(
    c = c,
    command = "cd / ; ls -la"
)
cmdResult.raiseExceptionOnError("Something went wrong!", bDumpStatusOnError=True)

c.close()

Final notes

So we have the full set:

  • Executing a command,
  • executing that command remotely via the same API,
  • creating the connection in an easy and secure way with password input.

The code above solves the problem quite well for me (and hopefully for you as well). And everything is open source: Fabric is BSD-2-Clause, and my own modules are provided under Apache-2.

Modules used:

Happy coding! ;-)

JAX-WS client : what's the correct path to access the local WSDL?

One other approach that we have taken successfully is to generate the WS client proxy code using wsimport (from Ant, as an Ant task) and specify the wsdlLocation attribute.

<wsimport debug="true" keep="true" verbose="false" target="2.1" sourcedestdir="${generated.client}" wsdl="${src}${wsdl.file}" wsdlLocation="${wsdl.file}">
</wsimport>

Since we run this for a project w/ multiple WSDLs, the script resolves the $(wsdl.file} value dynamically which is set up to be /META-INF/wsdl/YourWebServiceName.wsdl relative to the JavaSource location (or /src, depending on how you have your project set up). During the build proess, the WSDL and XSDs files are copied to this location and packaged in the JAR file. (similar to the solution described by Bhasakar above)

MyApp.jar
|__META-INF
   |__wsdl
      |__YourWebServiceName.wsdl
      |__YourWebServiceName_schema1.xsd
      |__YourWebServiceName_schmea2.xsd

Note: make sure the WSDL files are using relative refrerences to any imported XSDs and not http URLs:

  <types>
    <xsd:schema>
      <xsd:import namespace="http://valueobject.common.services.xyz.com/" schemaLocation="YourWebService_schema1.xsd"/>
    </xsd:schema>
    <xsd:schema>
      <xsd:import namespace="http://exceptions.util.xyz.com/" schemaLocation="YourWebService_schema2.xsd"/>
    </xsd:schema>
  </types>

In the generated code, we find this:

/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.2-b05-
 * Generated source version: 2.1
 * 
 */
@WebServiceClient(name = "YourService", targetNamespace = "http://test.webservice.services.xyz.com/", wsdlLocation = "/META-INF/wsdl/YourService.wsdl")
public class YourService_Service
    extends Service
{

    private final static URL YOURWEBSERVICE_WSDL_LOCATION;
    private final static WebServiceException YOURWEBSERVICE_EXCEPTION;
    private final static QName YOURWEBSERVICE_QNAME = new QName("http://test.webservice.services.xyz.com/", "YourService");

    static {
        YOURWEBSERVICE_WSDL_LOCATION = com.xyz.services.webservice.test.YourService_Service.class.getResource("/META-INF/wsdl/YourService.wsdl");
        WebServiceException e = null;
        if (YOURWEBSERVICE_WSDL_LOCATION == null) {
            e = new WebServiceException("Cannot find '/META-INF/wsdl/YourService.wsdl' wsdl. Place the resource correctly in the classpath.");
        }
        YOURWEBSERVICE_EXCEPTION = e;
    }

    public YourService_Service() {
        super(__getWsdlLocation(), YOURWEBSERVICE_QNAME);
    }

    public YourService_Service(URL wsdlLocation, QName serviceName) {
        super(wsdlLocation, serviceName);
    }

    /**
     * 
     * @return
     *     returns YourService
     */
    @WebEndpoint(name = "YourServicePort")
    public YourService getYourServicePort() {
        return super.getPort(new QName("http://test.webservice.services.xyz.com/", "YourServicePort"), YourService.class);
    }

    /**
     * 
     * @param features
     *     A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy.  Supported features not in the <code>features</code> parameter will have their default values.
     * @return
     *     returns YourService
     */
    @WebEndpoint(name = "YourServicePort")
    public YourService getYourServicePort(WebServiceFeature... features) {
        return super.getPort(new QName("http://test.webservice.services.xyz.com/", "YourServicePort"), YourService.class, features);
    }

    private static URL __getWsdlLocation() {
        if (YOURWEBSERVICE_EXCEPTION!= null) {
            throw YOURWEBSERVICE_EXCEPTION;
        }
        return YOURWEBSERVICE_WSDL_LOCATION;
    }

}

Perhaps this might help too. It's just a different approach that does not use the "catalog" approach.

Better way to check if a Path is a File or a Directory?

using System;
using System.IO;
namespace FileOrDirectory
{
     class Program
     {
          public static string FileOrDirectory(string path)
          {
               if (File.Exists(path))
                    return "File";
               if (Directory.Exists(path))
                    return "Directory";
               return "Path Not Exists";
          }
          static void Main()
          {
               Console.WriteLine("Enter The Path:");
               string path = Console.ReadLine();
               Console.WriteLine(FileOrDirectory(path));
          }
     }
}

How to send value attribute from radio button in PHP

Should be :

HTML :

<form method="post" action="">
    <input id="name" name="name" type="text" size="40"/>
    <input type="radio" name="radio" value="test"/>Test
    <input type="submit" name="submit" value="submit"/>
</form>

PHP Code :

if(isset($_POST['submit']))
{

    echo $radio_value = $_POST["radio"];
}

Best Free Text Editor Supporting *More Than* 4GB Files?

I have had problems with TextPad on 4G files too. Notepad++ works nicely.

How to get all Errors from ASP.Net MVC modelState?

Anybody looking for asp.net core 3.1. Slightly updated than the above answer. I found that this is what [ApiController] returns

 Dictionary<string, List<string>> errors = new Dictionary<string, List<string>>();

                foreach (KeyValuePair<string, ModelStateEntry> kvp in ViewData.ModelState)
                {
                    string key = kvp.Key;
                    ModelStateEntry entry = kvp.Value;

                    if (entry.Errors.Count > 0)
                    {
                        List<string> errorList = new List<string>();
                        foreach (ModelError error in entry.Errors)
                        {
                            errorList.Add(error.ErrorMessage);
                        }

                        errors[key] = errorList;
                    }
                }

                return  new JsonResult(new {Errors = errors});

SQL query for a carriage return in a string and ultimately removing carriage return

In SQL Server I would use:

WHERE CHARINDEX(CHAR(13), name) <> 0 OR CHARINDEX(CHAR(10), name) <> 0

This will search for both carriage returns and line feeds.

If you want to search for tabs too just add:

OR CHARINDEX(CHAR(9), name) <> 0

Refresh Page C# ASP.NET

Use:

Response.Redirect(Request.RawUrl, true);

Javascript Drag and drop for touch devices

Old thread I know.......

Problem with the answer of @ryuutatsuo is that it blocks also any input or other element that has to react on 'clicks' (for example inputs), so i wrote this solution. This solution made it possible to use any existing drag and drop library that is based upon mousedown, mousemove and mouseup events on any touch device (or cumputer). This is also a cross-browser solution.

I have tested in on several devices and it works fast (in combination with the drag and drop feature of ThreeDubMedia (see also http://threedubmedia.com/code/event/drag)). It is a jQuery solution so you can use it only with jQuery libs. I have used jQuery 1.5.1 for it because some newer functions don't work properly with IE9 and above (not tested with newer versions of jQuery).

Before you add any drag or drop operation to an event you have to call this function first:

simulateTouchEvents(<object>);

You can also block all components/children for input or to speed up event handling by using the following syntax:

simulateTouchEvents(<object>, true); // ignore events on childs

Here is the code i wrote. I used some nice tricks to speed up evaluating things (see code).

function simulateTouchEvents(oo,bIgnoreChilds)
{
 if( !$(oo)[0] )
  { return false; }

 if( !window.__touchTypes )
 {
   window.__touchTypes  = {touchstart:'mousedown',touchmove:'mousemove',touchend:'mouseup'};
   window.__touchInputs = {INPUT:1,TEXTAREA:1,SELECT:1,OPTION:1,'input':1,'textarea':1,'select':1,'option':1};
 }

$(oo).bind('touchstart touchmove touchend', function(ev)
{
    var bSame = (ev.target == this);
    if( bIgnoreChilds && !bSame )
     { return; }

    var b = (!bSame && ev.target.__ajqmeclk), // Get if object is already tested or input type
        e = ev.originalEvent;
    if( b === true || !e.touches || e.touches.length > 1 || !window.__touchTypes[e.type]  )
     { return; } //allow multi-touch gestures to work

    var oEv = ( !bSame && typeof b != 'boolean')?$(ev.target).data('events'):false,
        b = (!bSame)?(ev.target.__ajqmeclk = oEv?(oEv['click'] || oEv['mousedown'] || oEv['mouseup'] || oEv['mousemove']):false ):false;

    if( b || window.__touchInputs[ev.target.tagName] )
     { return; } //allow default clicks to work (and on inputs)

    // https://developer.mozilla.org/en/DOM/event.initMouseEvent for API
    var touch = e.changedTouches[0], newEvent = document.createEvent("MouseEvent");
    newEvent.initMouseEvent(window.__touchTypes[e.type], true, true, window, 1,
            touch.screenX, touch.screenY,
            touch.clientX, touch.clientY, false,
            false, false, false, 0, null);

    touch.target.dispatchEvent(newEvent);
    e.preventDefault();
    ev.stopImmediatePropagation();
    ev.stopPropagation();
    ev.preventDefault();
});
 return true;
}; 

What it does: At first, it translates single touch events into mouse events. It checks if an event is caused by an element on/in the element that must be dragged around. If it is an input element like input, textarea etc, it skips the translation, or if a standard mouse event is attached to it it will also skip a translation.

Result: Every element on a draggable element is still working.

Happy coding, greetz, Erwin Haantjes

"Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python

For me the following approach solved the issue (Python 3.5.2; mysqlclient 1.3.9):

  1. Dowload latest MySQL C Connector http://dev.mysql.com/downloads/connector/c/ (for me was Windows (x86, 64-bit), MSI Installer)
  2. Copy c:\Program Files\MySQL\MySQL Connector C 6.0.2\ directory to c:\Program Files (x86)\MySQL\MySQL Connector C 6.1\
  3. Run pip install mysqlclient
  4. [optional] delete c:\Program Files (x86)\MySQL\MySQL Connector C 6.1\

The issue here is only for x64 bit installation owners, since build script is trying to locate C connector includes in x86 program files directory.

T-SQL: Deleting all duplicate rows but keeping one

Example query:

DELETE FROM Table
WHERE ID NOT IN
(
SELECT MIN(ID)
FROM Table
GROUP BY Field1, Field2, Field3, ...
)

Here fields are column on which you want to group the duplicate rows.

How do I escape a percentage sign in T-SQL?

In MySQL,

WHERE column_name LIKE '%|%%' ESCAPE '|'

How to give a Linux user sudo access?

You need run visudo and in the editor that it opens write:

igor    ALL=(ALL) ALL

That line grants all permissions to user igor.

If you want permit to run only some commands, you need to list them in the line:

igor    ALL=(ALL) /bin/kill, /bin/ps

Filtering a list of strings based on contents

This simple filtering can be achieved in many ways with Python. The best approach is to use "list comprehensions" as follows:

>>> lst = ['a', 'ab', 'abc', 'bac']
>>> [k for k in lst if 'ab' in k]
['ab', 'abc']

Another way is to use the filter function. In Python 2:

>>> filter(lambda k: 'ab' in k, lst)
['ab', 'abc']

In Python 3, it returns an iterator instead of a list, but you can cast it:

>>> list(filter(lambda k: 'ab' in k, lst))
['ab', 'abc']

Though it's better practice to use a comprehension.

javascript change background color on click

You can sets the body's background colour using document.body.style.backgroundColor = "red"; so this can be put into a function that's called when the user clicks. The next part can be done by using document.getElementByID("divID").style.backgroundColor = "red"; window.setTimeout("yourFunction()",10000); which calls yourFunction in 10 seconds to change the colour back.

Safe width in pixels for printing web pages?

A printer doesn't understand pixels, it understand dots (pt in CSS). The best solution is to write an extra CSS for printing, with all of its measures in dots.

Then, in your HTML code, in head section, put:

<link href="style.css" rel="stylesheet" type="text/css" media="screen">
<link href="style_print.css" rel="stylesheet" type="text/css" media="print">

How to maintain page scroll position after a jquery event is carried out?

For all who came here from google and are using an anchor element for firing the event, please make sure to void the click likewise:

<a  
href='javascript:void(0)'  
onclick='javascript:whatever causing the page to scroll to the top'  
></a>

How to remove lines in a Matplotlib plot

I'm showing that a combination of lines.pop(0) l.remove() and del l does the trick.

from matplotlib import pyplot
import numpy, weakref
a = numpy.arange(int(1e3))
fig = pyplot.Figure()
ax  = fig.add_subplot(1, 1, 1)
lines = ax.plot(a)

l = lines.pop(0)
wl = weakref.ref(l)  # create a weak reference to see if references still exist
#                      to this object
print wl  # not dead
l.remove()
print wl  # not dead
del l
print wl  # dead  (remove either of the steps above and this is still live)

I checked your large dataset and the release of the memory is confirmed on the system monitor as well.

Of course the simpler way (when not trouble-shooting) would be to pop it from the list and call remove on the line object without creating a hard reference to it:

lines.pop(0).remove()

How to unpack and pack pkg file?

You might want to look into my fork of pbzx here: https://github.com/NiklasRosenstein/pbzx

It allows you to stream pbzx files that are not wrapped in a XAR archive. I've experienced this with recent XCode Command-Line Tools Disk Images (eg. 10.12 XCode 8).

pbzx -n Payload | cpio -i

How to implement common bash idioms in Python?

One reason I love Python is that it is much better standardized than the POSIX tools. I have to double and triple check that each bit is compatible with other operating systems. A program written on a Linux system might not work the same on a BSD system of OSX. With Python, I just have to check that the target system has a sufficiently modern version of Python.

Even better, a program written in standard Python will even run on Windows!

Delete an element from a dictionary

There're a lot of nice answers, but I want to emphasize one thing.

You can use both dict.pop() method and a more generic del statement to remove items from a dictionary. They both mutate the original dictionary, so you need to make a copy (see details below).

And both of them will raise a KeyError if the key you're providing to them is not present in the dictionary:

key_to_remove = "c"
d = {"a": 1, "b": 2}
del d[key_to_remove]  # Raises `KeyError: 'c'`

and

key_to_remove = "c"
d = {"a": 1, "b": 2}
d.pop(key_to_remove)  # Raises `KeyError: 'c'`

You have to take care of this:

by capturing the exception:

key_to_remove = "c"
d = {"a": 1, "b": 2}
try:
    del d[key_to_remove]
except KeyError as ex:
    print("No such key: '%s'" % ex.message)

and

key_to_remove = "c"
d = {"a": 1, "b": 2}
try:
    d.pop(key_to_remove)
except KeyError as ex:
    print("No such key: '%s'" % ex.message)

by performing a check:

key_to_remove = "c"
d = {"a": 1, "b": 2}
if key_to_remove in d:
    del d[key_to_remove]

and

key_to_remove = "c"
d = {"a": 1, "b": 2}
if key_to_remove in d:
    d.pop(key_to_remove)

but with pop() there's also a much more concise way - provide the default return value:

key_to_remove = "c"
d = {"a": 1, "b": 2}
d.pop(key_to_remove, None)  # No `KeyError` here

Unless you use pop() to get the value of a key being removed you may provide anything, not necessary None. Though it might be that using del with in check is slightly faster due to pop() being a function with its own complications causing overhead. Usually it's not the case, so pop() with default value is good enough.


As for the main question, you'll have to make a copy of your dictionary, to save the original dictionary and have a new one without the key being removed.

Some other people here suggest making a full (deep) copy with copy.deepcopy(), which might be an overkill, a "normal" (shallow) copy, using copy.copy() or dict.copy(), might be enough. The dictionary keeps a reference to the object as a value for a key. So when you remove a key from a dictionary this reference is removed, not the object being referenced. The object itself may be removed later automatically by the garbage collector, if there're no other references for it in the memory. Making a deep copy requires more calculations compared to shallow copy, so it decreases code performance by making the copy, wasting memory and providing more work to the GC, sometimes shallow copy is enough.

However, if you have mutable objects as dictionary values and plan to modify them later in the returned dictionary without the key, you have to make a deep copy.

With shallow copy:

def get_dict_wo_key(dictionary, key):
    """Returns a **shallow** copy of the dictionary without a key."""
    _dict = dictionary.copy()
    _dict.pop(key, None)
    return _dict


d = {"a": [1, 2, 3], "b": 2, "c": 3}
key_to_remove = "c"

new_d = get_dict_wo_key(d, key_to_remove)
print(d)  # {"a": [1, 2, 3], "b": 2, "c": 3}
print(new_d)  # {"a": [1, 2, 3], "b": 2}
new_d["a"].append(100)
print(d)  # {"a": [1, 2, 3, 100], "b": 2, "c": 3}
print(new_d)  # {"a": [1, 2, 3, 100], "b": 2}
new_d["b"] = 2222
print(d)  # {"a": [1, 2, 3, 100], "b": 2, "c": 3}
print(new_d)  # {"a": [1, 2, 3, 100], "b": 2222}

With deep copy:

from copy import deepcopy


def get_dict_wo_key(dictionary, key):
    """Returns a **deep** copy of the dictionary without a key."""
    _dict = deepcopy(dictionary)
    _dict.pop(key, None)
    return _dict


d = {"a": [1, 2, 3], "b": 2, "c": 3}
key_to_remove = "c"

new_d = get_dict_wo_key(d, key_to_remove)
print(d)  # {"a": [1, 2, 3], "b": 2, "c": 3}
print(new_d)  # {"a": [1, 2, 3], "b": 2}
new_d["a"].append(100)
print(d)  # {"a": [1, 2, 3], "b": 2, "c": 3}
print(new_d)  # {"a": [1, 2, 3, 100], "b": 2}
new_d["b"] = 2222
print(d)  # {"a": [1, 2, 3], "b": 2, "c": 3}
print(new_d)  # {"a": [1, 2, 3, 100], "b": 2222}

How to send parameters with jquery $.get()

I got this working : -

$.get('api.php', 'client=mikescafe', function(data) {
...
});

It sends via get the string ?client=mikescafe then collect this variable in api.php, and use it in your mysql statement.

How do I hide javascript code in a webpage?

My solution is inspired from the last comment. This is the code of invisible.html

<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="invisible_debut.js" ></script>
<body>
</body>

The clear code of invisible_debut.js is:

$(document).ready(function () {
var ga = document.createElement("script"); //ga is to remember Google Analytics ;-)
ga.type = 'text/javascript';
ga.src = 'invisible.js';
ga.id = 'invisible';
document.body.appendChild(ga);
$('#invisible').remove();});

Notice that at the end I'm removing the created script. invisible.js is:

$(document).ready(function(){
    alert('try to find in the source the js script which did this alert!');
    document.write('It disappeared, my dear!');});

invisible.js doesn't appear in the console, because it has been removed and never in the source code because created by javascript.

Concerning invisible_debut.js, I obfuscated it, which means that it is very complicated to find the url of invisible.js. Not perfect, but enought hard for a normal hacker.

Cannot construct instance of - Jackson

In your concrete example the problem is that you don't use this construct correctly:

@JsonSubTypes({ @JsonSubTypes.Type(value = MyAbstractClass.class, name = "MyAbstractClass") })

@JsonSubTypes.Type should contain the actual non-abstract subtypes of your abstract class.

Therefore if you have:

abstract class Parent and the concrete subclasses

Ch1 extends Parent and Ch2 extends Parent

Then your annotation should look like:

@JsonSubTypes({ 
          @JsonSubTypes.Type(value = Ch1.class, name = "ch1"),
          @JsonSubTypes.Type(value = Ch2.class, name = "ch2")
})

Here name should match the value of your 'discriminator':

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, 
include = JsonTypeInfo.As.WRAPPER_OBJECT, 
property = "type")

in the property field, here it is equal to type. So type will be the key and the value you set in name will be the value.

Therefore, when the json string comes if it has this form:

{
 "type": "ch1",
 "other":"fields"
}

Jackson will automatically convert this to a Ch1 class.

If you send this:

{
 "type": "ch2",
 "other":"fields"
}

You would get a Ch2 instance.

Struct Constructor in C++?

Yes, but if you have your structure in a union then you cannot. It is the same as a class.

struct Example
{
   unsigned int mTest;
   Example()
   {
   }
};

Unions will not allow constructors in the structs. You can make a constructor on the union though. This question relates to non-trivial constructors in unions.

Yii2 data provider default sorting

Or

       $dataProvider->setSort([
        'defaultOrder' => ['topic_order'=>SORT_DESC],
        'attributes' => [...

Can't compile C program on a Mac after upgrade to Mojave

@JL Peyret is right!

if you macos 10.14.6 Mojave, Xcode 11.0+

then

cd /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs

sudo ln -s MacOSX.sdk/ MacOSX10.14.sdk

Hibernate Delete query

I'm not sure but:

  • If you call the delete method with a non transient object, this means first fetched the object from the DB. So it is normal to see a select statement. Perhaps in the end you see 2 select + 1 delete?

  • If you call the delete method with a transient object, then it is possible that you have a cascade="delete" or something similar which requires to retrieve first the object so that "nested actions" can be performed if it is required.


Edit: Calling delete() with a transient instance means doing something like that:

MyEntity entity = new MyEntity();
entity.setId(1234);
session.delete(entity);

This will delete the row with id 1234, even if the object is a simple pojo not retrieved by Hibernate, not present in its session cache, not managed at all by Hibernate.

If you have an entity association Hibernate probably have to fetch the full entity so that it knows if the delete should be cascaded to associated entities.

syntaxerror: unexpected character after line continuation character in python

The filename should be a string. In other names it should be within quotes.

f = open("D\\python\\HW\\2_1 - Copy.cp","r")
lines = f.readlines()
for i in lines:
    thisline = i.split(" ");

You can also open the file using with

with open("D\\python\\HW\\2_1 - Copy.cp","r") as f:
    lines = f.readlines()
    for i in lines:
        thisline = i.split(" ");

There is no need to add the semicolon(;) in python. It's ugly.

PHP: How to remove specific element from an array?

You can use array filter to remove the items by a specific condition on $v:

$arr = array_filter($arr, function($v){
    return $v != 'some_value';
});

How do you import an Eclipse project into Android Studio now?

According to http://tools.android.com/tech-docs/new-build-system/migrating-from-eclipse-projects, You have a couple of choices
- simply importing
- pre-exporting first from Eclipse.

Pre-exporting from eclipse may be the better choice if your project contains a lot of relationships that are Eclipse-specific. A.S. cannot 'translate' everything Eclipse can produce. If you want to continue using Eclipse as well as A.S. on this project code, this is the better choice. If you choose this method, please read the above link, there are some important pre-requisites.

Simply importing into AS will let AS 'translate' and rearrange the project, and is the recommended method, especially if you have no intention of returning to Eclipse. In this case, you let the A.S. wizard do everything and you dont need to manually generate gradle files.

Get the new record primary key ID from MySQL insert query?

i used return $this->db->insert_id(); for Codeigniter

How to get file extension from string in C++

A NET/CLI version using System::String

   System::String^ GetFileExtension(System::String^ FileName)
   {
       int Ext=FileName->LastIndexOf('.');
       if( Ext != -1 )
           return FileName->Substring(Ext+1);
       return "";
   }

Change Row background color based on cell value DataTable

Since datatables v1.10.18, you should specify the column key instead of index, it should be like this:

rowCallback: function(row, data, index){
            if(data["column_key"] == "ValueHere"){
                $('td', row).css('background-color', 'blue');
            }
        }

How to sort a dataframe by multiple column(s)

In response to a comment added in the OP for how to sort programmatically:

Using dplyr and data.table

library(dplyr)
library(data.table)

dplyr

Just use arrange_, which is the Standard Evaluation version for arrange.

df1 <- tbl_df(iris)
#using strings or formula
arrange_(df1, c('Petal.Length', 'Petal.Width'))
arrange_(df1, ~Petal.Length, ~Petal.Width)
    Source: local data frame [150 x 5]

   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
          (dbl)       (dbl)        (dbl)       (dbl)  (fctr)
1           4.6         3.6          1.0         0.2  setosa
2           4.3         3.0          1.1         0.1  setosa
3           5.8         4.0          1.2         0.2  setosa
4           5.0         3.2          1.2         0.2  setosa
5           4.7         3.2          1.3         0.2  setosa
6           5.4         3.9          1.3         0.4  setosa
7           5.5         3.5          1.3         0.2  setosa
8           4.4         3.0          1.3         0.2  setosa
9           5.0         3.5          1.3         0.3  setosa
10          4.5         2.3          1.3         0.3  setosa
..          ...         ...          ...         ...     ...


#Or using a variable
sortBy <- c('Petal.Length', 'Petal.Width')
arrange_(df1, .dots = sortBy)
    Source: local data frame [150 x 5]

   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
          (dbl)       (dbl)        (dbl)       (dbl)  (fctr)
1           4.6         3.6          1.0         0.2  setosa
2           4.3         3.0          1.1         0.1  setosa
3           5.8         4.0          1.2         0.2  setosa
4           5.0         3.2          1.2         0.2  setosa
5           4.7         3.2          1.3         0.2  setosa
6           5.5         3.5          1.3         0.2  setosa
7           4.4         3.0          1.3         0.2  setosa
8           4.4         3.2          1.3         0.2  setosa
9           5.0         3.5          1.3         0.3  setosa
10          4.5         2.3          1.3         0.3  setosa
..          ...         ...          ...         ...     ...

#Doing the same operation except sorting Petal.Length in descending order
sortByDesc <- c('desc(Petal.Length)', 'Petal.Width')
arrange_(df1, .dots = sortByDesc)

more info here: https://cran.r-project.org/web/packages/dplyr/vignettes/nse.html

It is better to use formula as it also captures the environment to evaluate an expression in

data.table

dt1 <- data.table(iris) #not really required, as you can work directly on your data.frame
sortBy <- c('Petal.Length', 'Petal.Width')
sortType <- c(-1, 1)
setorderv(dt1, sortBy, sortType)
dt1
     Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
  1:          7.7         2.6          6.9         2.3 virginica
  2:          7.7         2.8          6.7         2.0 virginica
  3:          7.7         3.8          6.7         2.2 virginica
  4:          7.6         3.0          6.6         2.1 virginica
  5:          7.9         3.8          6.4         2.0 virginica
 ---                                                            
146:          5.4         3.9          1.3         0.4    setosa
147:          5.8         4.0          1.2         0.2    setosa
148:          5.0         3.2          1.2         0.2    setosa
149:          4.3         3.0          1.1         0.1    setosa
150:          4.6         3.6          1.0         0.2    setosa

Why is my Spring @Autowired field null?

Not entirely related to the question, but if the field injection is null, the constructor based injection will still work fine.

    private OrderingClient orderingClient;
    private Sales2Client sales2Client;
    private Settings2Client settings2Client;

    @Autowired
    public BrinkWebTool(OrderingClient orderingClient, Sales2Client sales2Client, Settings2Client settings2Client) {
        this.orderingClient = orderingClient;
        this.sales2Client = sales2Client;
        this.settings2Client = settings2Client;
    }

Which to use <div class="name"> or <div id="name">?

The object itself will not change. The main difference between these 2 keyword is the use:

  • The ID is usually single in the page
  • The class can have one or many occurences

In the CSS or Javascript files:

  • The ID will be accessed by the character #
  • The class will be accessed by the character .

Create HTML table using Javascript

The problem is that if you try to write a <table> or a <tr> or <td> tag using JS every time you insert a new tag the browser will try to close it as it will think that there is an error on the code.

Instead of writing your table line by line, concatenate your table into a variable and insert it once created:

<script language="javascript" type="text/javascript">
<!--

var myArray    = new Array();
    myArray[0] = 1;
    myArray[1] = 2.218;
    myArray[2] = 33;
    myArray[3] = 114.94;
    myArray[4] = 5;
    myArray[5] = 33;
    myArray[6] = 114.980;
    myArray[7] = 5;

    var myTable= "<table><tr><td style='width: 100px; color: red;'>Col Head 1</td>";
    myTable+= "<td style='width: 100px; color: red; text-align: right;'>Col Head 2</td>";
    myTable+="<td style='width: 100px; color: red; text-align: right;'>Col Head 3</td></tr>";

    myTable+="<tr><td style='width: 100px;                   '>---------------</td>";
    myTable+="<td     style='width: 100px; text-align: right;'>---------------</td>";
    myTable+="<td     style='width: 100px; text-align: right;'>---------------</td></tr>";

  for (var i=0; i<8; i++) {
    myTable+="<tr><td style='width: 100px;'>Number " + i + " is:</td>";
    myArray[i] = myArray[i].toFixed(3);
    myTable+="<td style='width: 100px; text-align: right;'>" + myArray[i] + "</td>";
    myTable+="<td style='width: 100px; text-align: right;'>" + myArray[i] + "</td></tr>";
  }  
   myTable+="</table>";

 document.write( myTable);

//-->
</script> 

If your code is in an external JS file, in HTML create an element with an ID where you want your table to appear:

<div id="tablePrint"> </div>

And in JS instead of document.write(myTable) use the following code:

document.getElementById('tablePrint').innerHTML = myTable;

Check if all values in list are greater than a certain number

...any reason why you can't use min()?

def above(my_list, minimum):
    if min(my_list) >= minimum:
        print "All values are equal or above", minimum
    else:
        print "Not all values are equal or above", minimum

I don't know if this is exactly what you want, but technically, this is what you asked for...

Proper use of const for defining functions in JavaScript

There's no problem with what you've done, but you must remember the difference between function declarations and function expressions.

A function declaration, that is:

function doSomething () {}

Is hoisted entirely to the top of the scope (and like let and const they are block scoped as well).

This means that the following will work:

doSomething() // works!
function doSomething() {}

A function expression, that is:

[const | let | var] = function () {} (or () =>

Is the creation of an anonymous function (function () {}) and the creation of a variable, and then the assignment of that anonymous function to that variable.

So the usual rules around variable hoisting within a scope -- block-scoped variables (let and const) do not hoist as undefined to the top of their block scope.

This means:

if (true) {
    doSomething() // will fail
    const doSomething = function () {}
}

Will fail since doSomething is not defined. (It will throw a ReferenceError)

If you switch to using var you get your hoisting of the variable, but it will be initialized to undefined so that block of code above will still not work. (This will throw a TypeError since doSomething is not a function at the time you call it)

As far as standard practices go, you should always use the proper tool for the job.

Axel Rauschmayer has a great post on scope and hoisting including es6 semantics: Variables and Scoping in ES6

How To Set Up GUI On Amazon EC2 Ubuntu server

So I follow first answer, but my vnc viewer gives me grey screen when I connect to it. And I found this Ask Ubuntu link to solve that.

The only difference with previous answer is you need to install these extra packages:

apt-get install gnome-panel gnome-settings-daemon metacity nautilus gnome-terminal

And use this ~/.vnc/xstartup file:

#!/bin/sh

export XKL_XMODMAP_DISABLE=1
unset SESSION_MANAGER
unset DBUS_SESSION_BUS_ADDRESS

[ -x /etc/vnc/xstartup ] && exec /etc/vnc/xstartup
[ -r $HOME/.Xresources ] && xrdb $HOME/.Xresources
xsetroot -solid grey
vncconfig -iconic &

gnome-panel &
gnome-settings-daemon &
metacity &
nautilus &
gnome-terminal &

Everything else is the same.

Tested on EC2 Ubuntu 14.04 LTS.

How do I delete multiple rows in Entity Framework (without foreach)

You can execute sql queries directly as follows :

    private int DeleteData()
{
    using (var ctx = new MyEntities(this.ConnectionString))
    {
        if (ctx != null)
        {

            //Delete command
            return ctx.ExecuteStoreCommand("DELETE FROM ALARM WHERE AlarmID > 100");

        }
    }
    return 0;
}

For select we may use

using (var context = new MyContext()) 
{ 
    var blogs = context.MyTable.SqlQuery("SELECT * FROM dbo.MyTable").ToList(); 
}

Reading a huge .csv file

what worked for me was and is superfast is

import pandas as pd
import dask.dataframe as dd
import time
t=time.clock()
df_train = dd.read_csv('../data/train.csv', usecols=[col1, col2])
df_train=df_train.compute()
print("load train: " , time.clock()-t)

Another working solution is:

import pandas as pd 
from tqdm import tqdm

PATH = '../data/train.csv'
chunksize = 500000 
traintypes = {
'col1':'category',
'col2':'str'}

cols = list(traintypes.keys())

df_list = [] # list to hold the batch dataframe

for df_chunk in tqdm(pd.read_csv(PATH, usecols=cols, dtype=traintypes, chunksize=chunksize)):
    # Can process each chunk of dataframe here
    # clean_data(), feature_engineer(),fit()

    # Alternatively, append the chunk to list and merge all
    df_list.append(df_chunk) 

# Merge all dataframes into one dataframe
X = pd.concat(df_list)

# Delete the dataframe list to release memory
del df_list
del df_chunk

Android Studio: Where is the Compiler Error Output Window?

Just click on the "Build" node in the Build Output

enter image description here

From some reason the "Compilation failed" node just started being automatically selected and for that the description window is very unhelpful.

How to find index of all occurrences of element in array?

const indexes = cars
    .map((car, i) => car === "Nano" ? i : null)
    .filter(i => i !== null)

Firebase FCM force onTokenRefresh() to be called

The onTokenRefresh() method is going to be called whenever a new token is generated. Upon app install, it will be generated immediately (as you have found to be the case). It will also be called when the token has changed.

According to the FirebaseCloudMessaging guide:

You can target notifications to a single, specific device. On initial startup of your app, the FCM SDK generates a registration token for the client app instance.

Screenshot

Source Link: https://firebase.google.com/docs/notifications/android/console-device#access_the_registration_token

This means that the token registration is per app. It sounds like you would like to utilize the token after a user is logged in. What I would suggest is that you save the token in the onTokenRefresh() method to internal storage or shared preferences. Then, retrieve the token from storage after a user logs in and register the token with your server as needed.

If you would like to manually force the onTokenRefresh(), you can create an IntentService and delete the token instance. Then, when you call getToken, the onTokenRefresh() method will be called again.

Example Code:

public class DeleteTokenService extends IntentService
{
    public static final String TAG = DeleteTokenService.class.getSimpleName();

    public DeleteTokenService()
    {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(Intent intent)
    {
        try
        {
            // Check for current token
            String originalToken = getTokenFromPrefs();
            Log.d(TAG, "Token before deletion: " + originalToken);

            // Resets Instance ID and revokes all tokens.
            FirebaseInstanceId.getInstance().deleteInstanceId();

            // Clear current saved token
            saveTokenToPrefs("");

            // Check for success of empty token
            String tokenCheck = getTokenFromPrefs();
            Log.d(TAG, "Token deleted. Proof: " + tokenCheck);

            // Now manually call onTokenRefresh()
            Log.d(TAG, "Getting new token");
            FirebaseInstanceId.getInstance().getToken();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    private void saveTokenToPrefs(String _token)
    {
        // Access Shared Preferences
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = preferences.edit();

        // Save to SharedPreferences
        editor.putString("registration_id", _token);
        editor.apply();
    }

    private String getTokenFromPrefs()
    {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        return preferences.getString("registration_id", null);
    }
}

EDIT

FirebaseInstanceIdService

public class FirebaseInstanceIdService extends Service

This class is deprecated. In favour of overriding onNewToken in FirebaseMessagingService. Once that has been implemented, this service can be safely removed.

onTokenRefresh() is deprecated. Use onNewToken() in MyFirebaseMessagingService

public class MyFirebaseMessagingService extends FirebaseMessagingService {

@Override
public void onNewToken(String s) {
    super.onNewToken(s);
    Log.e("NEW_TOKEN",s);
    }

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    }
} 

"An access token is required to request this resource" while accessing an album / photo with Facebook php sdk

Well, you are having a valid access token to access your information and not others( this is because you got logged in and you have given permission to access your information). But the picture owner has not done the same (logged in + permission ) and so you are getting a violation error.

To obtain permission see this link and decide what kind of informations you want from any user and decide the permissions. Later on embed this in your code. (In the login function call)

Thanks

How to return a PNG image from Jersey REST service method to the browser

in regard of answer from @Perception, its true to be very memory-consuming when working with byte arrays, but you could also simply write back into the outputstream

@Path("/picture")
public class ProfilePicture {
  @GET
  @Path("/thumbnail")
  @Produces("image/png")
  public StreamingOutput getThumbNail() {
    return new StreamingOutput() {
      @Override
      public void write(OutputStream os) throws IOException, WebApplicationException {
        //... read your stream and write into os
      }
    };
  }
}

How to split string using delimiter char using T-SQL?

It is terrible, but you can try to use

select
SUBSTRING(Table1.Col1,0,PATINDEX('%|%=',Table1.Col1)) as myString
from
Table1

This code is probably not 100% right though. need to be adjusted

Stash just a single file

If you do not want to specify a message with your stashed changes, pass the filename after a double-dash.

$ git stash -- filename.ext

If it's an untracked/new file, you will have to stage it first.

However, if you do want to specify a message, use push.

git stash push -m "describe changes to filename.ext" filename.ext

Both methods work in git versions 2.13+

How do I programmatically get the GUID of an application in .NET 2.0

Another way is to use Marshal.GetTypeLibGuidForAssembly.

According to MSDN:

When assemblies are exported to type libraries, the type library is assigned a LIBID. You can set the LIBID explicitly by applying the System.Runtime.InteropServices.GuidAttribute at the assembly level, or it can be generated automatically. The Tlbimp.exe (Type Library Importer) tool calculates a LIBID value based on the identity of the assembly. GetTypeLibGuid returns the LIBID that is associated with the GuidAttribute, if the attribute is applied. Otherwise, GetTypeLibGuidForAssembly returns the calculated value. Alternatively, you can use the GetTypeLibGuid method to extract the actual LIBID from an existing type library.

htaccess redirect all pages to single page

Add this for pages not currently on your site...

ErrorDocument 404 http://example.com/

Along with your Redirect 301 / http://www.thenewdomain.com/ that should cover all the bases...

Good luck!

text-align: right on <select> or <option>

I think what you want is:

select {
  direction: rtl;
}

fiddled here: http://jsfiddle.net/neilheinrich/XS3yQ/

Chrome extension: accessing localStorage in content script

Sometimes it may be better to use chrome.storage API. It's better then localStorage because you can:

  • store information from your content script without the need for message passing between content script and extension;
  • store your data as JavaScript objects without serializing them to JSON (localStorage only stores strings).

Here's a simple code demonstrating the use of chrome.storage. Content script gets the url of visited page and timestamp and stores it, popup.js gets it from storage area.

content_script.js

(function () {
    var visited = window.location.href;
    var time = +new Date();
    chrome.storage.sync.set({'visitedPages':{pageUrl:visited,time:time}}, function () {
        console.log("Just visited",visited)
    });
})();

popup.js

(function () {
    chrome.storage.onChanged.addListener(function (changes,areaName) {
        console.log("New item in storage",changes.visitedPages.newValue);
    })
})();

"Changes" here is an object that contains old and new value for a given key. "AreaName" argument refers to name of storage area, either 'local', 'sync' or 'managed'.

Remember to declare storage permission in manifest.json.

manifest.json

...
"permissions": [
    "storage"
 ],
...

How can I toggle word wrap in Visual Studio?

  1. Open the output window.

  2. Look for the little icon on the very right-hand side of the toolbar that starts with the text "Show output from:" in it. It looks like a small window with a carriage return icon. When you hover over it Visual Studio should display "Toggle Word Wrap" near your mouse pointer.

  3. Click that icon.

You now have learned something that was so painfully obvious I feel embarrassed for not knowing this long ago and thus have chosen to pay my dues and share my answer with others so they don't suffer the same agony I have.

Seriously, this is really useful for those with small screens. I have a small Lilliput USB monitor that is good for small tool windows, Skype IM, etc. It works great for putting the output window on, except that it sucks having to always sideways scroll. After just putting up with sideways scroll for months I finally decided to see if I could make it word wrap. The answer was so easy but the amount of time/effort it saves is tremendous.

Use latest version of Internet Explorer in the webbrowser control

I know this has been posted but here is a current version for dotnet 4.5 above that I use. I recommend to use the default browser emulation respecting doctype

InternetExplorerFeatureControl.Instance.BrowserEmulation = DocumentMode.DefaultRespectDocType;

internal class InternetExplorerFeatureControl
{
    private static readonly Lazy<InternetExplorerFeatureControl> LazyInstance = new Lazy<InternetExplorerFeatureControl>(() => new InternetExplorerFeatureControl());
    private const string RegistryLocation = @"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl";
    private readonly RegistryView _registryView = Environment.Is64BitOperatingSystem && Environment.Is64BitProcess ? RegistryView.Registry64 : RegistryView.Registry32;
    private readonly string _processName;
    private readonly Version _version;

    #region Feature Control Strings (A)

    private const string FeatureRestrictAboutProtocolIe7 = @"FEATURE_RESTRICT_ABOUT_PROTOCOL_IE7";
    private const string FeatureRestrictAboutProtocol = @"FEATURE_RESTRICT_ABOUT_PROTOCOL";

    #endregion

    #region Feature Control Strings (B)

    private const string FeatureBrowserEmulation = @"FEATURE_BROWSER_EMULATION";

    #endregion

    #region Feature Control Strings (G)

    private const string FeatureGpuRendering = @"FEATURE_GPU_RENDERING";

    #endregion

    #region Feature Control Strings (L)

    private const string FeatureBlockLmzScript = @"FEATURE_BLOCK_LMZ_SCRIPT";

    #endregion

    internal InternetExplorerFeatureControl()
    {
        _processName = $"{Process.GetCurrentProcess().ProcessName}.exe";
        using (var webBrowser = new WebBrowser())
            _version = webBrowser.Version;
    }

    internal static InternetExplorerFeatureControl Instance => LazyInstance.Value;

    internal RegistryHive RegistryHive { get; set; } = RegistryHive.CurrentUser;

    private int GetFeatureControl(string featureControl)
    {
        using (var currentUser = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, _registryView))
        {
            using (var key = currentUser.CreateSubKey($"{RegistryLocation}\\{featureControl}", false))
            {
                if (key.GetValue(_processName) is int value)
                {
                    return value;
                }
                return -1;
            }
        }
    }

    private void SetFeatureControl(string featureControl, int value)
    {
        using (var currentUser = RegistryKey.OpenBaseKey(RegistryHive, _registryView))
        {
            using (var key = currentUser.CreateSubKey($"{RegistryLocation}\\{featureControl}", true))
            {
                key.SetValue(_processName, value, RegistryValueKind.DWord);
            }
        }
    }

    #region Internet Feature Controls (A)

    /// <summary>
    /// Windows Internet Explorer 8 and later. When enabled, feature disables the "about:" protocol. For security reasons, applications that host the WebBrowser Control are strongly encouraged to enable this feature.
    /// By default, this feature is enabled for Windows Internet Explorer and disabled for applications hosting the WebBrowser Control.To enable this feature using the registry, add the name of your executable file to the following setting.
    /// </summary>
    internal bool AboutProtocolRestriction
    {
        get
        {
            if (_version.Major < 8)
                throw new NotSupportedException($"{AboutProtocolRestriction} requires Internet Explorer 8 and Later.");
            var releaseVersion = new Version(8, 0, 6001, 18702);
            return Convert.ToBoolean(GetFeatureControl(_version >= releaseVersion ? FeatureRestrictAboutProtocolIe7 : FeatureRestrictAboutProtocol));
        }
        set
        {
            if (_version.Major < 8)
                throw new NotSupportedException($"{AboutProtocolRestriction} requires Internet Explorer 8 and Later.");
            var releaseVersion = new Version(8, 0, 6001, 18702);
            SetFeatureControl(_version >= releaseVersion ? FeatureRestrictAboutProtocolIe7 : FeatureRestrictAboutProtocol, Convert.ToInt16(value));
        }
    }

    #endregion

    #region Internet Feature Controls (B)

    /// <summary>
    /// Windows Internet Explorer 8 and later. Defines the default emulation mode for Internet Explorer and supports the following values.
    /// </summary>
    internal DocumentMode BrowserEmulation
    {
        get
        {
            if (_version.Major < 8)
                throw new NotSupportedException($"{nameof(BrowserEmulation)} requires Internet Explorer 8 and Later.");
            var value = GetFeatureControl(FeatureBrowserEmulation);
            if (Enum.IsDefined(typeof(DocumentMode), value))
            {
                return (DocumentMode)value;
            }
            return DocumentMode.NotSet;
        }
        set
        {
            if (_version.Major < 8)
                throw new NotSupportedException($"{nameof(BrowserEmulation)} requires Internet Explorer 8 and Later.");
            var tmp = value;
            if (value == DocumentMode.DefaultRespectDocType)
                tmp = DefaultRespectDocType;
            else if (value == DocumentMode.DefaultOverrideDocType)
                tmp = DefaultOverrideDocType;
            SetFeatureControl(FeatureBrowserEmulation, (int)tmp);
        }
    }

    #endregion

    #region Internet Feature Controls (G)

    /// <summary>
    /// Internet Explorer 9. Enables Internet Explorer to use a graphics processing unit (GPU) to render content. This dramatically improves performance for webpages that are rich in graphics.
    /// By default, this feature is enabled for Internet Explorer and disabled for applications hosting the WebBrowser Control.To enable this feature by using the registry, add the name of your executable file to the following setting.
    /// Note: GPU rendering relies heavily on the quality of your video drivers. If you encounter problems running Internet Explorer with GPU rendering enabled, you should verify that your video drivers are up to date and that they support hardware accelerated graphics.
    /// </summary>
    internal bool GpuRendering
    {
        get
        {
            if (_version.Major < 9)
                throw new NotSupportedException($"{nameof(GpuRendering)} requires Internet Explorer 9 and Later.");
            return Convert.ToBoolean(GetFeatureControl(FeatureGpuRendering));
        }
        set
        {
            if (_version.Major < 9)
                throw new NotSupportedException($"{nameof(GpuRendering)} requires Internet Explorer 9 and Later.");
            SetFeatureControl(FeatureGpuRendering, Convert.ToInt16(value));
        }
    }

    #endregion

    #region Internet Feature Controls (L)

    /// <summary>
    /// Internet Explorer 7 and later. When enabled, feature allows scripts stored in the Local Machine zone to be run only in webpages loaded from the Local Machine zone or by webpages hosted by sites in the Trusted Sites list. For more information, see Security and Compatibility in Internet Explorer 7.
    /// By default, this feature is enabled for Internet Explorer and disabled for applications hosting the WebBrowser Control.To enable this feature by using the registry, add the name of your executable file to the following setting.
    /// </summary>
    internal bool LocalScriptBlocking
    {
        get
        {
            if (_version.Major < 7)
                throw new NotSupportedException($"{nameof(LocalScriptBlocking)} requires Internet Explorer 7 and Later.");
            return Convert.ToBoolean(GetFeatureControl(FeatureBlockLmzScript));
        }
        set
        {
            if (_version.Major < 7)
                throw new NotSupportedException($"{nameof(LocalScriptBlocking)} requires Internet Explorer 7 and Later.");
            SetFeatureControl(FeatureBlockLmzScript, Convert.ToInt16(value));
        }
    }

    #endregion


    private DocumentMode DefaultRespectDocType
    {
        get
        {
            if (_version.Major >= 11)
                return DocumentMode.InternetExplorer11RespectDocType;
            switch (_version.Major)
            {
                case 10:
                    return DocumentMode.InternetExplorer10RespectDocType;
                case 9:
                    return DocumentMode.InternetExplorer9RespectDocType;
                case 8:
                    return DocumentMode.InternetExplorer8RespectDocType;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }

    private DocumentMode DefaultOverrideDocType
    {
        get
        {
            if (_version.Major >= 11)
                return DocumentMode.InternetExplorer11OverrideDocType;
            switch (_version.Major)
            {
                case 10:
                    return DocumentMode.InternetExplorer10OverrideDocType;
                case 9:
                    return DocumentMode.InternetExplorer9OverrideDocType;
                case 8:
                    return DocumentMode.InternetExplorer8OverrideDocType;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }
}

internal enum DocumentMode
{
    NotSet = -1,
    [Description("Webpages containing standards-based !DOCTYPE directives are displayed in IE latest installed version mode.")]
    DefaultRespectDocType,
    [Description("Webpages are displayed in IE latest installed version mode, regardless of the declared !DOCTYPE directive.  Failing to declare a !DOCTYPE directive could causes the page to load in Quirks.")]
    DefaultOverrideDocType,
    [Description(
        "Internet Explorer 11. Webpages are displayed in IE11 edge mode, regardless of the declared !DOCTYPE directive. Failing to declare a !DOCTYPE directive causes the page to load in Quirks."
    )] InternetExplorer11OverrideDocType = 11001,

    [Description(
        "IE11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 edge mode. Default value for IE11."
    )] InternetExplorer11RespectDocType = 11000,

    [Description(
        "Internet Explorer 10. Webpages are displayed in IE10 Standards mode, regardless of the !DOCTYPE directive."
    )] InternetExplorer10OverrideDocType = 10001,

    [Description(
        "Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode. Default value for Internet Explorer 10."
    )] InternetExplorer10RespectDocType = 10000,

    [Description(
        "Windows Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the declared !DOCTYPE directive. Failing to declare a !DOCTYPE directive causes the page to load in Quirks."
    )] InternetExplorer9OverrideDocType = 9999,

    [Description(
        "Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode. Default value for Internet Explorer 9.\r\n" +
        "Important  In Internet Explorer 10, Webpages containing standards - based !DOCTYPE directives are displayed in IE10 Standards mode."
    )] InternetExplorer9RespectDocType = 9000,

    [Description(
        "Webpages are displayed in IE8 Standards mode, regardless of the declared !DOCTYPE directive. Failing to declare a !DOCTYPE directive causes the page to load in Quirks."
    )] InternetExplorer8OverrideDocType = 8888,

    [Description(
        "Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode. Default value for Internet Explorer 8\r\n" +
        "Important  In Internet Explorer 10, Webpages containing standards - based !DOCTYPE directives are displayed in IE10 Standards mode."
    )] InternetExplorer8RespectDocType = 8000,

    [Description(
        "Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode. Default value for applications hosting the WebBrowser Control."
    )] InternetExplorer7RespectDocType = 7000
}

DateTime group by date and hour

SQL Server :

SELECT [activity_dt], count(*)
FROM table1
GROUP BY DATEPART(day, [activity_dt]), DATEPART(hour, [activity_dt]);

Oracle :

SELECT [activity_dt], count(*)
FROM table1
GROUP BY TO_CHAR(activity_dt, 'DD'), TO_CHAR(activity_dt, 'hh');

MySQL :

SELECT [activity_dt], count(*)
FROM table1
GROUP BY hour( activity_dt ) , day( activity_dt )

Spring Boot JPA - configuring auto reconnect

Setting spring.datasource.tomcat.testOnBorrow=true in application.properties didn't work.

Programmatically setting like below worked without any issues.

import org.apache.tomcat.jdbc.pool.DataSource;
import org.apache.tomcat.jdbc.pool.PoolProperties;    

@Bean
public DataSource dataSource() {
    PoolProperties poolProperties = new PoolProperties();
    poolProperties.setUrl(this.properties.getDatabase().getUrl());         
    poolProperties.setUsername(this.properties.getDatabase().getUsername());            
    poolProperties.setPassword(this.properties.getDatabase().getPassword());

    //here it is
    poolProperties.setTestOnBorrow(true);
    poolProperties.setValidationQuery("SELECT 1");

    return new DataSource(poolProperties);
}

How to add users to Docker container?

Add this line to your Dockerfile (You can run any linux command this way)

RUN useradd -ms /bin/bash yourNewUserName

Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

Try to add ReactiveFormsModule in your component as well.

import { FormGroup, FormArray, FormBuilder,
          Validators,ReactiveFormsModule  } from '@angular/forms';

Execute a command in command prompt using excel VBA

The S parameter does not do anything on its own.

/S      Modifies the treatment of string after /C or /K (see below) 
/C      Carries out the command specified by string and then terminates  
/K      Carries out the command specified by string but remains  

Try something like this instead

Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)

You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.

Shell("perl a.pl c:\temp")



-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn

OS detecting makefile

Detect the operating system using two simple tricks:

  • First the environment variable OS
  • Then the uname command
ifeq ($(OS),Windows_NT)     # is Windows_NT on XP, 2000, 7, Vista, 10...
    detected_OS := Windows
else
    detected_OS := $(shell uname)  # same as "uname -s"
endif

Or a more safe way, if not on Windows and uname unavailable:

ifeq ($(OS),Windows_NT) 
    detected_OS := Windows
else
    detected_OS := $(shell sh -c 'uname 2>/dev/null || echo Unknown')
endif

Ken Jackson proposes an interesting alternative if you want to distinguish Cygwin/MinGW/MSYS/Windows. See his answer that looks like that:

ifeq '$(findstring ;,$(PATH))' ';'
    detected_OS := Windows
else
    detected_OS := $(shell uname 2>/dev/null || echo Unknown)
    detected_OS := $(patsubst CYGWIN%,Cygwin,$(detected_OS))
    detected_OS := $(patsubst MSYS%,MSYS,$(detected_OS))
    detected_OS := $(patsubst MINGW%,MSYS,$(detected_OS))
endif

Then you can select the relevant stuff depending on detected_OS:

ifeq ($(detected_OS),Windows)
    CFLAGS += -D WIN32
endif
ifeq ($(detected_OS),Darwin)        # Mac OS X
    CFLAGS += -D OSX
endif
ifeq ($(detected_OS),Linux)
    CFLAGS   +=   -D LINUX
endif
ifeq ($(detected_OS),GNU)           # Debian GNU Hurd
    CFLAGS   +=   -D GNU_HURD
endif
ifeq ($(detected_OS),GNU/kFreeBSD)  # Debian kFreeBSD
    CFLAGS   +=   -D GNU_kFreeBSD
endif
ifeq ($(detected_OS),FreeBSD)
    CFLAGS   +=   -D FreeBSD
endif
ifeq ($(detected_OS),NetBSD)
    CFLAGS   +=   -D NetBSD
endif
ifeq ($(detected_OS),DragonFly)
    CFLAGS   +=   -D DragonFly
endif
ifeq ($(detected_OS),Haiku)
    CFLAGS   +=   -D Haiku
endif

Notes:

  • Command uname is same as uname -s because option -s (--kernel-name) is the default. See why uname -s is better than uname -o.

  • The use of OS (instead of uname) simplifies the identification algorithm. You can still use solely uname, but you have to deal with if/else blocks to check all MinGW, Cygwin, etc. variations.

  • The environment variable OS is always set to "Windows_NT" on different Windows versions (see %OS% environment variable on Wikipedia).

  • An alternative of OS is the environment variable MSVC (it checks the presence of MS Visual Studio, see example using Visual C++).


Below I provide a complete example using make and gcc to build a shared library: *.so or *.dll depending on the platform. The example is as simplest as possible to be more understandable.

To install make and gcc on Windows see Cygwin or MinGW.

My example is based on five files

 +-- lib
 ¦   +-- Makefile
 ¦   +-- hello.h
 ¦   +-- hello.c
 +-- app
     +-- Makefile
     +-- main.c

Reminder: Makefile is indented using tabulation. Caution when copy-pasting below sample files.

The two Makefile files

1. lib/Makefile

ifeq ($(OS),Windows_NT)
    uname_S := Windows
else
    uname_S := $(shell uname -s)
endif

ifeq ($(uname_S), Windows)
    target = hello.dll
endif
ifeq ($(uname_S), Linux)
    target = libhello.so
endif
#ifeq ($(uname_S), .....) #See https://stackoverflow.com/a/27776822/938111
#    target = .....
#endif

%.o: %.c
    gcc  -c $<  -fPIC  -o $@
    # -c $<  => $< is first file after ':' => Compile hello.c
    # -fPIC  => Position-Independent Code (required for shared lib)
    # -o $@  => $@ is the target => Output file (-o) is hello.o

$(target): hello.o
    gcc  $^  -shared  -o $@
    # $^      => $^ expand to all prerequisites (after ':') => hello.o
    # -shared => Generate shared library
    # -o $@   => Output file (-o) is $@ (libhello.so or hello.dll)

2. app/Makefile

ifeq ($(OS),Windows_NT)
    uname_S := Windows
else
    uname_S := $(shell uname -s)
endif

ifeq ($(uname_S), Windows)
    target = app.exe
endif
ifeq ($(uname_S), Linux)
    target = app
endif
#ifeq ($(uname_S), .....) #See https://stackoverflow.com/a/27776822/938111
#    target = .....
#endif

%.o: %.c
    gcc  -c $< -I ../lib  -o $@
    # -c $<     => compile (-c) $< (first file after :) = main.c
    # -I ../lib => search headers (*.h) in directory ../lib
    # -o $@     => output file (-o) is $@ (target) = main.o

$(target): main.o
    gcc  $^  -L../lib  -lhello  -o $@
    # $^       => $^ (all files after the :) = main.o (here only one file)
    # -L../lib => look for libraries in directory ../lib
    # -lhello  => use shared library hello (libhello.so or hello.dll)
    # -o $@    => output file (-o) is $@ (target) = "app.exe" or "app"

To learn more, read Automatic Variables documentation as pointed out by cfi.

The source code

- lib/hello.h

#ifndef HELLO_H_
#define HELLO_H_

const char* hello();

#endif

- lib/hello.c

#include "hello.h"

const char* hello()
{
    return "hello";
}

- app/main.c

#include "hello.h" //hello()
#include <stdio.h> //puts()

int main()
{
    const char* str = hello();
    puts(str);
}

The build

Fix the copy-paste of Makefile (replace leading spaces by one tabulation).

> sed  's/^  */\t/'  -i  */Makefile

The make command is the same on both platforms. The given output is on Unix-like OSes:

> make -C lib
make: Entering directory '/tmp/lib'
gcc  -c hello.c  -fPIC  -o hello.o
# -c hello.c  => hello.c is first file after ':' => Compile hello.c
# -fPIC       => Position-Independent Code (required for shared lib)
# -o hello.o  => hello.o is the target => Output file (-o) is hello.o
gcc  hello.o  -shared  -o libhello.so
# hello.o        => hello.o is the first after ':' => Link hello.o
# -shared        => Generate shared library
# -o libhello.so => Output file (-o) is libhello.so (libhello.so or hello.dll)
make: Leaving directory '/tmp/lib'

> make -C app
make: Entering directory '/tmp/app'
gcc  -c main.c -I ../lib  -o main.o
# -c main.c => compile (-c) main.c (first file after :) = main.cpp
# -I ../lib => search headers (*.h) in directory ../lib
# -o main.o => output file (-o) is main.o (target) = main.o
gcc  main.o  -L../lib  -lhello  -o app
# main.o   => main.o (all files after the :) = main.o (here only one file)
# -L../lib => look for libraries in directory ../lib
# -lhello  => use shared library hello (libhello.so or hello.dll)
# -o app   => output file (-o) is app.exe (target) = "app.exe" or "app"
make: Leaving directory '/tmp/app'

The run

The application requires to know where is the shared library.

On Windows, a simple solution is to copy the library where the application is:

> cp -v lib/hello.dll app
`lib/hello.dll' -> `app/hello.dll'

On Unix-like OSes, you can use the LD_LIBRARY_PATH environment variable:

> export LD_LIBRARY_PATH=lib

Run the command on Windows:

> app/app.exe
hello

Run the command on Unix-like OSes:

> app/app
hello

How to fix a header on scroll

Coops answer is a good, simple solution, however, once you apply the fixed class the page becomes that much shorter and content will "jump" up, and if page is of a length where the scroll distance is less than the height of the header element, it will appear to jump and not let you see the bottom of the page.

The answer I found was to add a spacer div above the element that will become fixed (nav element in my case), and set it to the same height as the nav element, and set it to display none.

When adding the .fixed class to the nav, show the .nav-spacer div, and when removing it, hide it. Since the height of the page changes instantly I have set the duration to 0.

HTML

<header>the element above the element that will become fixed</header>
<div class="nav-spacer"></div>
<nav></nav>

CSS

nav {
    position: relative;    
    height: 100px;
}
.nav-spacer{
    position: relative;
    height: 100px;
    display: none;
}
.fixed {
    position: fixed;
    top:0;
    left:0;
    width: 100%;
    /* I like to add a shadow on to the fixed element */
    -webkit-box-shadow: 0px 5px 10px 1px rgba(0,0,0,0.25);
    -moz-box-shadow: 0px 5px 10px 1px rgba(0,0,0,0.25);
    box-shadow: 0px 5px 10px 1px rgba(0,0,0,0.25);
}

JavaScript

var stickyOffset = $('nav').offset().top;

$(window).scroll(function(){
    if ($(window).scrollTop() >= stickyOffset){
        $('nav').addClass('fixed');
        //this makes the page length equal to what it was before fixing nav
        $('.nav-spacer').show(0); 
    }
    else {
        $('nav').removeClass('fixed');
        $('.nav-spacer').hide(0);
    }
});

Where can I find a list of Mac virtual key codes?

Here are the all keycodes.

Here is a table with some keycodes for the three platforms. It is based on a US Extended keyboard layout.

http://web.archive.org/web/20100501161453/http://www.classicteck.com/rbarticles/mackeyboard.php

Or, there is an app in the Mac App Store named "Key Codes". Download it to see the keycodes of the keys you press.

Key Codes:
https://itunes.apple.com/tr/app/key-codes/id414568915?l=tr&mt=12

How to set x axis values in matplotlib python?

The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:

import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square') 
plt.xlabel('x')
plt.ylabel('y') 
plt.xticks(xi, x)
plt.title('compare')
plt.legend() 
plt.show()

How do I find where JDK is installed on my windows machine?

Plain and simple on Windows platforms:

where java

How to decode HTML entities using jQuery?

The easiest way is to set a class selector to your elements an then use following code:

$(function(){
    $('.classSelector').each(function(a, b){
        $(b).html($(b).text());
    });
});

Nothing any more needed!

I had this problem and found this clear solution and it works fine.

python pip - install from local dir

All you need to do is run

pip install /opt/mypackage

and pip will search /opt/mypackage for a setup.py, build a wheel, then install it.

The problem with using the -e flag for pip install as suggested in the comments and this answer is that this requires that the original source directory stay in place for as long as you want to use the module. It's great if you're a developer working on the source, but if you're just trying to install a package, it's the wrong choice.

Alternatively, you don't even need to download the repo from Github at all. pip supports installing directly from git repos using a variety of protocols including HTTP, HTTPS, and SSH, among others. See the docs I linked to for examples.

XML Schema minOccurs / maxOccurs default values

example:

XML

<?xml version="1.0" encoding="UTF-8"?> 
<?xml-stylesheet type="text/xsl" href="country.xsl"?>
<country xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="country.xsd">
    <countryName>Australia</countryName>
    <capital>Canberra</capital>
    <nationalLanguage>English</nationalLanguage>
    <population>21000000</population>
    <currency>Australian Dollar</currency>
    <nationalIdentities>
        <nationalAnthem>Advance Australia Fair</nationalAnthem>
        <nationalDay>Australia Day (26 January)</nationalDay>
        <nationalColour>Green and Gold</nationalColour>
        <nationalGemstone>Opal</nationalGemstone>
        <nationalFlower>Wattle (Acacia pycnantha)</nationalFlower>
    </nationalIdentities>
    <publicHolidays>
        <newYearDay>1 January</newYearDay>
        <australiaDay>26 January</australiaDay>
        <anzacDay>25 April</anzacDay>
        <christmasDay>25 December</christmasDay>
        <boxingDay>26 December</boxingDay>
        <laborDay>Variable Date</laborDay>
        <easter>Variable Date</easter>
        <queenBirthDay>21 April (Variable Date)</queenBirthDay>
    </publicHolidays>
    <states>
        <stateName><Name>NSW -  New South Wales</Name></stateName>
        <stateName><Name>VIC -  Victoria</Name></stateName>
        <stateName><Name>QLD -  Queensland</Name></stateName>
        <stateName><Name>SA -  South Australia</Name></stateName>
        <stateName><Name>WA -  Western Australia</Name></stateName>
        <stateName><Name>TAS -  Tasmania</Name></stateName>
    </states>
    <territories>
        <territoryName>ACT -  Australian Capital Territory</territoryName>
        <territoryName>NT -  Northern Territory</territoryName>
    </territories>
</country>

XSD:

<?xml version="1.0" encoding="UTF-8"?> 
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="country">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="countryName" type="xs:string"/>
                <xs:element name="capital" type="xs:string"/>
                <xs:element name="nationalLanguage" type="xs:string"/>
                <xs:element name="population" type="xs:double"/>
                <xs:element name="currency" type="xs:string"/>
                <xs:element name="nationalIdentities">
                <xs:complexType>
                    <xs:sequence>
                        <xs:element name="nationalAnthem" type="xs:string"/>
                        <xs:element name="nationalDay" type="xs:string"/>
                        <xs:element name="nationalColour" type="xs:string"/>
                        <xs:element name="nationalGemstone" type="xs:string"/>
                        <xs:element name="nationalFlower" type="xs:string"/>
                    </xs:sequence>
                </xs:complexType>
                </xs:element>
                <xs:element name="publicHolidays">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="newYearDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="australiaDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="anzacDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="christmasDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="boxingDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="laborDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="easter" maxOccurs="1" type="xs:string"/>
                            <xs:element name="queenBirthDay" maxOccurs="1" type="xs:string"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
                <xs:element name="states">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="stateName" minOccurs="1" maxOccurs="unbounded">
                                <xs:complexType>
                                    <xs:sequence>
                                        <xs:element name="Name" type="xs:string"/>
                                    </xs:sequence>
                                </xs:complexType>
                            </xs:element>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
                <xs:element name="territories">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="territoryName" maxOccurs="unbounded"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

XSL:

<?xml version="1.0"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="html" indent="yes" version="4.0"/>
    <xsl:template match="/">
        <html>
            <body>          
                <xsl:for-each select="country">         
                    <xsl:value-of select="countryName"/><br/>
                    <xsl:value-of select="capital"/><br/>
                    <xsl:value-of select="nationalLanguage"/><br/>
                    <xsl:value-of select="population"/><br/>
                    <xsl:value-of select="currency"/><br/>              
                    <xsl:for-each select="nationalIdentities">
                        <xsl:value-of select="nationalAnthem"/><br/>
                        <xsl:value-of select="nationalDay"/><br/>
                        <xsl:value-of select="nationalColour"/><br/>
                        <xsl:value-of select="nationalGemstone"/><br/>
                        <xsl:value-of select="nationalFlower"/><br/>
                    </xsl:for-each>
                    <xsl:for-each select="publicHolidays">
                        <xsl:value-of select="newYearDay"/><br/>
                        <xsl:value-of select="australiaDay"/><br/>
                        <xsl:value-of select="anzacDay"/><br/>
                        <xsl:value-of select="christmasDay"/><br/>
                        <xsl:value-of select="boxingDay"/><br/>
                        <xsl:value-of select="laborDay"/><br/>
                        <xsl:value-of select="easter"/><br/>
                        <xsl:value-of select="queenBirthDay"/><br/>
                    </xsl:for-each>
                    <xsl:for-each select="states/stateName">
                        <xsl:value-of select="Name"/><br/>
                    </xsl:for-each>
                </xsl:for-each>
            </body>
        </html>
    </xsl:template>
</xsl:stylesheet>

Result:

Australia
Canberra
English
21000000
Australian Dollar
Advance Australia Fair
Australia Day (26 January)
Green and Gold
Opal
Wattle (Acacia pycnantha)
1 January
26 January
25 April
25 December
26 December
Variable Date
Variable Date
21 April (Variable Date)
NSW - New South Wales
VIC - Victoria
QLD - Queensland
SA - South Australia
WA - Western Australia
TAS - Tasmania

How to Change Font Size in drawString Java

g.setFont(new Font("TimesRoman", Font.PLAIN, fontSize)); 

Where fontSize is a int. The API for drawString states that the x and y parameters are coordinates, and have nothing to do with the size of the text.

CSS: How to align vertically a "label" and "input" inside a "div"?

This works cross-browser, provides more accessibility and comes with less markup. ditch the div. Wrap the label

label{
     display: block; 
     height: 35px; 
     line-height: 35px; 
     border: 1px solid #000; 
}

input{margin-top:15px; height:20px}

<label for="name">Name: <input type="text" id="name" /></label>

Python 3 Building an array of bytes

agf's bytearray solution is workable, but if you find yourself needing to build up more complicated packets using datatypes other than bytes, you can try struct.pack(). http://docs.python.org/release/3.1.3/library/struct.html

Calling @Html.Partial to display a partial view belonging to a different controller

That's no problem.

@Html.Partial("../Controller/View", model)

or

@Html.Partial("~/Views/Controller/View.cshtml", model)

Should do the trick.

If you want to pass through the (other) controller, you can use:

@Html.Action("action", "controller", parameters)

or any of the other overloads

How to modify a text file?

Unfortunately there is no way to insert into the middle of a file without re-writing it. As previous posters have indicated, you can append to a file or overwrite part of it using seek but if you want to add stuff at the beginning or the middle, you'll have to rewrite it.

This is an operating system thing, not a Python thing. It is the same in all languages.

What I usually do is read from the file, make the modifications and write it out to a new file called myfile.txt.tmp or something like that. This is better than reading the whole file into memory because the file may be too large for that. Once the temporary file is completed, I rename it the same as the original file.

This is a good, safe way to do it because if the file write crashes or aborts for any reason, you still have your untouched original file.

Push origin master error on new repository

make sure you are on a branch, at least in master branch

type:

git branch

you should see:

ubuntu-user:~/git/turmeric-releng$ git branch

* (no branch)
master

then type:

git checkout master

then all your changes will fit in master branch (or the branch u choose)

CSS selector for text input fields?

As @Amir posted above, the best way nowadays – cross-browser and leaving behind IE6 – is to use

[type=text] {}

Nobody mentioned lower CSS specificity (why is that important?) so far, [type=text] features 0,0,1,0 instead of 0,0,1,1 with input[type=text].

Performance-wise there's no negative impact at all any more.

normalize v4.0.0 just released with lowered selector specificity.

How to roundup a number to the closest ten?

the second argument in ROUNDUP, eg =ROUNDUP(12345.6789,3) refers to the negative of the base-10 column with that power of 10, that you want rounded up. eg 1000 = 10^3, so to round up to the next highest 1000, use ,-3)

=ROUNDUP(12345.6789,-4) = 20,000
=ROUNDUP(12345.6789,-3) = 13,000
=ROUNDUP(12345.6789,-2) = 12,400
=ROUNDUP(12345.6789,-1) = 12,350
=ROUNDUP(12345.6789,0) = 12,346
=ROUNDUP(12345.6789,1) = 12,345.7
=ROUNDUP(12345.6789,2) = 12,345.68
=ROUNDUP(12345.6789,3) = 12,345.679

So, to answer your question: if your value is in A1, use =ROUNDUP(A1,-1)

How to target only IE (any version) within a stylesheet?

For targeting IE only in my stylesheets, I use this Sass Mixin :

@mixin ie-only {
  @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
    @content;
  }
}

How to revert initial git commit?

You just need to delete the branch you are on. You can't use git branch -D as this has a safety check against doing this. You can use update-ref to do this.

git update-ref -d HEAD

Do not use rm -rf .git or anything like this as this will completely wipe your entire repository including all other branches as well as the branch that you are trying to reset.

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I tested below code with SQL Server 2008 R2 Express and I believe we should have solution for all 6 steps you outlined. Let's take on them one-by-one:

1 - Enable TCP/IP

We can enable TCP/IP protocol with WMI:

set wmiComputer = GetObject( _
    "winmgmts:" _
    & "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProtocols = wmiComputer.ExecQuery( _
    "select * from ServerNetworkProtocol " _
    & "where InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'")

if tcpProtocols.Count = 1 then
    ' set tcpProtocol = tcpProtocols(0)
    ' I wish this worked, but unfortunately 
    ' there's no int-indexed Item property in this type

    ' Doing this instead
    for each tcpProtocol in tcpProtocols
        dim setEnableResult
            setEnableResult = tcpProtocol.SetEnable()
            if setEnableResult <> 0 then 
                Wscript.Echo "Failed!"
            end if
    next
end if

2 - Open the right ports in the firewall

I believe your solution will work, just make sure you specify the right port. I suggest we pick a different port than 1433 and make it a static port SQL Server Express will be listening on. I will be using 3456 in this post, but please pick a different number in the real implementation (I feel that we will see a lot of applications using 3456 soon :-)

3 - Modify TCP/IP properties enable a IP address

We can use WMI again. Since we are using static port 3456, we just need to update two properties in IPAll section: disable dynamic ports and set the listening port to 3456:

set wmiComputer = GetObject( _
    "winmgmts:" _
    & "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProperties = wmiComputer.ExecQuery( _
    "select * from ServerNetworkProtocolProperty " _
    & "where InstanceName='SQLEXPRESS' and " _
    & "ProtocolName='Tcp' and IPAddressName='IPAll'")

for each tcpProperty in tcpProperties
    dim setValueResult, requestedValue

    if tcpProperty.PropertyName = "TcpPort" then
        requestedValue = "3456"
    elseif tcpProperty.PropertyName ="TcpDynamicPorts" then
        requestedValue = ""
    end if

    setValueResult = tcpProperty.SetStringValue(requestedValue)
    if setValueResult = 0 then 
        Wscript.Echo "" & tcpProperty.PropertyName & " set."
    else
        Wscript.Echo "" & tcpProperty.PropertyName & " failed!"
    end if
next

Note that I didn't have to enable any of the individual addresses to make it work, but if it is required in your case, you should be able to extend this script easily to do so.

Just a reminder that when working with WMI, WBEMTest.exe is your best friend!

4 - Enable mixed mode authentication in sql server

I wish we could use WMI again, but unfortunately this setting is not exposed through WMI. There are two other options:

  1. Use LoginMode property of Microsoft.SqlServer.Management.Smo.Server class, as described here.

  2. Use LoginMode value in SQL Server registry, as described in this post. Note that by default the SQL Server Express instance is named SQLEXPRESS, so for my SQL Server 2008 R2 Express instance the right registry key was HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQLServer.

5 - Change user (sa) default password

You got this one covered.

6 - Finally (connect to the instance)

Since we are using a static port assigned to our SQL Server Express instance, there's no need to use instance name in the server address anymore.

SQLCMD -U sa -P newPassword -S 192.168.0.120,3456

Please let me know if this works for you (fingers crossed!).

How to create timer in angular2

You can simply use setInterval utility and use arrow function as callback so that this will point to the component instance.

For ex:

this.interval = setInterval( () => { 
    // call your functions like 
    this.getList();
    this.updateInfo();
});

Inside your ngOnDestroy lifecycle hook, clear the interval.

ngOnDestroy(){
    clearInterval(this.interval);
}

Loop through array of values with Arrow Function

One statement can be written as such:

someValues.forEach(x => console.log(x));

or multiple statements can be enclosed in {} like this:

someValues.forEach(x => { let a = 2 + x; console.log(a); });

How do I create an abstract base class in JavaScript?

Do you mean something like this:

function Animal() {
  //Initialization for all Animals
}

//Function and properties shared by all instances of Animal
Animal.prototype.init=function(name){
  this.name=name;
}
Animal.prototype.say=function(){
    alert(this.name + " who is a " + this.type + " says " + this.whattosay);
}
Animal.prototype.type="unknown";

function Cat(name) {
    this.init(name);

    //Make a cat somewhat unique
    var s="";
    for (var i=Math.ceil(Math.random()*7); i>=0; --i) s+="e";
    this.whattosay="Me" + s +"ow";
}
//Function and properties shared by all instances of Cat    
Cat.prototype=new Animal();
Cat.prototype.type="cat";
Cat.prototype.whattosay="meow";


function Dog() {
    //Call init with same arguments as Dog was called with
    this.init.apply(this,arguments);
}

Dog.prototype=new Animal();
Dog.prototype.type="Dog";
Dog.prototype.whattosay="bark";
//Override say.
Dog.prototype.say = function() {
        this.openMouth();
        //Call the original with the exact same arguments
        Animal.prototype.say.apply(this,arguments);
        //or with other arguments
        //Animal.prototype.say.call(this,"some","other","arguments");
        this.closeMouth();
}

Dog.prototype.openMouth=function() {
   //Code
}
Dog.prototype.closeMouth=function() {
   //Code
}

var dog = new Dog("Fido");
var cat1 = new Cat("Dash");
var cat2 = new Cat("Dot");


dog.say(); // Fido the Dog says bark
cat1.say(); //Dash the Cat says M[e]+ow
cat2.say(); //Dot the Cat says M[e]+ow


alert(cat instanceof Cat) // True
alert(cat instanceof Dog) // False
alert(cat instanceof Animal) // True

Laravel 4: Redirect to a given url

You can also use redirect() method like this:-

return redirect('https://stackoverflow.com/');

How to go to a URL using jQuery?

window.location is just what you need. Other thing you can do is to create anchor element and simulate click on it

$("<a href='your url'></a>").click(); 

How to call stopservice() method of Service class from the calling activity class

In Kotlin you can do this...

Service:

class MyService : Service() {
    init {
        instance = this
    }

    companion object {
        lateinit var instance: MyService

        fun terminateService() {
            instance.stopSelf()
        }
    }
}

In your activity (or anywhere in your app for that matter):

btn_terminate_service.setOnClickListener {
    MyService.terminateService()
}

Note: If you have any pending intents showing a notification in Android's status bar, you may want to terminate that as well.

Python circular importing?

To understand circular dependencies, you need to remember that Python is essentially a scripting language. Execution of statements outside methods occurs at compile time. Import statements are executed just like method calls, and to understand them you should think about them like method calls.

When you do an import, what happens depends on whether the file you are importing already exists in the module table. If it does, Python uses whatever is currently in the symbol table. If not, Python begins reading the module file, compiling/executing/importing whatever it finds there. Symbols referenced at compile time are found or not, depending on whether they have been seen, or are yet to be seen by the compiler.

Imagine you have two source files:

File X.py

def X1:
    return "x1"

from Y import Y2

def X2:
    return "x2"

File Y.py

def Y1:
    return "y1"

from X import X1

def Y2:
    return "y2"

Now suppose you compile file X.py. The compiler begins by defining the method X1, and then hits the import statement in X.py. This causes the compiler to pause compilation of X.py and begin compiling Y.py. Shortly thereafter the compiler hits the import statement in Y.py. Since X.py is already in the module table, Python uses the existing incomplete X.py symbol table to satisfy any references requested. Any symbols appearing before the import statement in X.py are now in the symbol table, but any symbols after are not. Since X1 now appears before the import statement, it is successfully imported. Python then resumes compiling Y.py. In doing so it defines Y2 and finishes compiling Y.py. It then resumes compilation of X.py, and finds Y2 in the Y.py symbol table. Compilation eventually completes w/o error.

Something very different happens if you attempt to compile Y.py from the command line. While compiling Y.py, the compiler hits the import statement before it defines Y2. Then it starts compiling X.py. Soon it hits the import statement in X.py that requires Y2. But Y2 is undefined, so the compile fails.

Please note that if you modify X.py to import Y1, the compile will always succeed, no matter which file you compile. However if you modify file Y.py to import symbol X2, neither file will compile.

Any time when module X, or any module imported by X might import the current module, do NOT use:

from X import Y

Any time you think there may be a circular import you should also avoid compile time references to variables in other modules. Consider the innocent looking code:

import X
z = X.Y

Suppose module X imports this module before this module imports X. Further suppose Y is defined in X after the import statement. Then Y will not be defined when this module is imported, and you will get a compile error. If this module imports Y first, you can get away with it. But when one of your co-workers innocently changes the order of definitions in a third module, the code will break.

In some cases you can resolve circular dependencies by moving an import statement down below symbol definitions needed by other modules. In the examples above, definitions before the import statement never fail. Definitions after the import statement sometimes fail, depending on the order of compilation. You can even put import statements at the end of a file, so long as none of the imported symbols are needed at compile time.

Note that moving import statements down in a module obscures what you are doing. Compensate for this with a comment at the top of your module something like the following:

#import X   (actual import moved down to avoid circular dependency)

In general this is a bad practice, but sometimes it is difficult to avoid.

TypeError : Unhashable type

A list is unhashable because its contents can change over its lifetime. You can update an item contained in the list at any time.

A list doesn't use a hash for indexing, so it isn't restricted to hashable items.

Differences between ConstraintLayout and RelativeLayout

In addition to @dhaval-jivani answer.

I've updated the project github project to latest version of constraint layout v.1.1.0-beta3

I've measured and compared the time of onCreate method and time between a start of onCreate and end of execution of last preformDraw method which visible in CPU monitor. All test were done on Samsung S5 mini with android 6.0.1 Here results:

Fresh start (first screen opening after application launch)

Relative Layout

OnCreate: 123ms

Last preformDraw time - OnCreate time: 311.3ms

Constraint Layout

OnCreate: 120.3ms

Last preformDraw time - OnCreate time: 310ms

Besides that, I've checked performance test from this article , here the code and found that on loop counts less than 100 constraint layout variant is faster during execution of inflating, measure, and layout then variants with Relative Layout. And on old Android devices, like Samsung S3 with Android 4.3, the difference is bigger.

As a conclusion I agree with comments from the article:

Does it worth to refactor old views switch on it from RelativeLayout or LinearLayout?

As always: It depends

I wouldn’t refactor anything unless you either have a performance problem with your current layout hierarchy or you want to make significant changes to the layout anyway. Though I haven’t measured it lately, I haven’t found any performance issues in the last releases. So I think you should be safe to use it. but – as I’v said – don’t just migrate for the sake of migrating. Only do so, if there’s a need for and benefit from it. For new layouts, though, I nearly always use ConstraintLayout. It’s so much better compare to what we had before.

"Object doesn't support this property or method" error in IE11

Add the code snippet in JS file used in master page or used globally.

<script language="javascript">
if (typeof browseris !== 'undefined') {
    browseris.ie = false;
}
</script>

For more information refer blog: http://blogs2share.blogspot.in/2016/11/object-doesnt-support-property-or.html

What is the difference between Hibernate and Spring Data JPA

There are 3 different things we are using here :

  1. JPA : Java persistence api which provide specification for persisting, reading, managing data from your java object to relations in database.
  2. Hibernate: There are various provider which implement jpa. Hibernate is one of them. So we have other provider as well. But if using jpa with spring it allows you to switch to different providers in future.
  3. Spring Data JPA : This is another layer on top of jpa which spring provide to make your life easy.

So lets understand how spring data jpa and spring + hibernate works-


Spring Data JPA:

Let's say you are using spring + hibernate for your application. Now you need to have dao interface and implementation where you will be writing crud operation using SessionFactory of hibernate. Let say you are writing dao class for Employee class, tomorrow in your application you might need to write similiar crud operation for any other entity. So there is lot of boilerplate code we can see here.

Now Spring data jpa allow us to define dao interfaces by extending its repositories(crudrepository, jparepository) so it provide you dao implementation at runtime. You don't need to write dao implementation anymore.Thats how spring data jpa makes your life easy.

How to download a branch with git?

Create a new directory, and do a clone instead.

git clone (address of origin) (name of branch)

How to resize a VirtualBox vmdk file

I have a Windows 7 client on a Mac host and this post was VERY helpful. Thanks.

I would add that I didn't use gparted. I did this:

  1. Launch new enlarged vmdk image.
  2. Go to Start and right click Computer and select Manage.
  3. Click Disk Management
  4. You should see some grayed space on your (in my case) C drive
  5. Right click the C drive and select Extend Volume.
  6. Choose size and go

Sweet! I preferred that to using a 3rd party tool with warnings about data loss.

Cheers!

How do you overcome the svn 'out of date' error?

I manage to solve it by hitting a update button

bootstrap 3 navbar collapse button not working

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

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

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

Additional info:

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

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

How to document a method with parameter(s)?

Building upon the type-hints answer (https://stackoverflow.com/a/9195565/2418922), which provides a better structured way to document types of parameters, there exist also a structured manner to document both type and descriptions of parameters:

def copy_net(
    infile: (str, 'The name of the file to send'),
    host: (str, 'The host to send the file to'),
    port: (int, 'The port to connect to')):

    pass

example adopted from: https://pypi.org/project/autocommand/

Unresolved external symbol on static class members

In my case, I was using wrong linking.
It was managed c++ (cli) but with native exporting. I have added to linker -> input -> assembly link resource the dll of the library from which the function is exported. But native c++ linking requires .lib file to "see" implementations in cpp correctly, so for me helped to add the .lib file to linker -> input -> additional dependencies.
[Usually managed code does not use dll export and import, it uses references, but that was unique situation.]

How can I generate a 6 digit unique number?

I would use an algorithm, brute force could be as follows:

First time through loop: Generate a random number between 100,000 through 999,999 and call that x1

Second time through the loop Generate a random number between 100,000 and x1 call this xt2, then generate a random number between x1 and 999,999 call this xt3, then randomly choose x2 or x3, call this x2

Nth time through the loop Generate random number between 100,000 and x1, x1 and x2, and x2 through 999,999 and so forth...

watch out for endpoints, also watch out for x1

Biggest advantage to using ASP.Net MVC vs web forms

Web forms also gain from greater maturity and support from third party control providers like Telerik.

Install Android App Bundle on device

No, if you are debugging an app without other users use the Build > Build APK(s) menu in Android Studio or execute it in your device/emulator them the debug release apk will install automatically. If you are debugging an app with others use Build > Generate Signed APK... menu. If you want to publish the beta version use the Google Play Store. Your APK(s) will be in app\build\outputs\apk\debug and app\release folders.

Read next word in java

You do not necessarily have to split the line because java.util.Scanner's default delimiter is whitespace.

You can just create a new Scanner object within your while statement.

    Scanner sc2 = null;
    try {
        sc2 = new Scanner(new File("translate.txt"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();  
    }
    while (sc2.hasNextLine()) {
            Scanner s2 = new Scanner(sc2.nextLine());
        while (s2.hasNext()) {
            String s = s2.next();
            System.out.println(s);
        }
    }

What is the difference between tree depth and height?

The “depth” (or equivalently the “level number”) of a node is the number of edges on the “path” from the root node

The “height” of a node is the number of edges on the longest path from the node to a leaf node.