Programs & Examples On #Pitch tracking

Pitch tracking is the process of finding the dominant frequency of an audio signal.

Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling

The best answer is not the correct way to do this :(. You actually bound indexPath with model, which is not always good. Imagine that some rows has been added during loading image. Now cell for given indexPath exists on screen, but the image is no longer correct! The situation is kinda unlikely and hard to replicate but it's possible.

It's better to use MVVM approach, bind cell with viewModel in controller and load image in viewModel (assigning ReactiveCocoa signal with switchToLatest method), then subscribe this signal and assign image to cell! ;)

You have to remember to not abuse MVVM. Views have to be dead simple! Whereas ViewModels should be reusable! It's why it's very important to bind View (UITableViewCell) and ViewModel in controller.

rake assets:precompile RAILS_ENV=production not working as required

I found out that my back-up project worked well if I precompile without bundle update. Maybe something went wrong with gem updated but I don't know which gem has an error.

XSS filtering function in PHP

htmlspecialchars() is perfectly adequate for filtering user input that is displayed in html forms.

Changing all files' extensions in a folder with one command on Windows

Rename behavior is sometimes 'less than intuitive'; for example...

ren *.THM *.jpg will rename your THM files to have an extension of .jpg. eg: GEDC003.THM will be GEDC003.jpg

ren *.THM *b.jpg will rename your THM files to *.THMb.jpg. eg: GEDC004.THM will become GEDC004.THMb.jpg

ren *.THM *.b.jpg will rename your THM files to *.b.jpg eg: GEDC005.THM will become GEDC005.b.jpg

How to add bootstrap in angular 6 project?

npm install --save bootstrap

afterwards, inside angular.json (previously .angular-cli.json) inside the project's root folder, find styles and add the bootstrap css file like this:

for angular 6

"styles": [
          "../node_modules/bootstrap/dist/css/bootstrap.min.css",
          "styles.css"
],

for angular 7

"styles": [
          "node_modules/bootstrap/dist/css/bootstrap.min.css",
          "src/styles.css"
],

How to convert a huge list-of-vector to a matrix more efficiently?

I think you want

output <- do.call(rbind,lapply(z,matrix,ncol=10,byrow=TRUE))

i.e. combining @BlueMagister's use of do.call(rbind,...) with an lapply statement to convert the individual list elements into 11*10 matrices ...

Benchmarks (showing @flodel's unlist solution is 5x faster than mine, and 230x faster than the original approach ...)

n <- 1000
z <- replicate(n,matrix(1:110,ncol=10,byrow=TRUE),simplify=FALSE)
library(rbenchmark)
origfn <- function(z) {
    output <- NULL 
    for(i in 1:length(z))
        output<- rbind(output,matrix(z[[i]],ncol=10,byrow=TRUE))
}
rbindfn <- function(z) do.call(rbind,lapply(z,matrix,ncol=10,byrow=TRUE))
unlistfn <- function(z) matrix(unlist(z), ncol = 10, byrow = TRUE)

##          test replications elapsed relative user.self sys.self 
## 1   origfn(z)          100  36.467  230.804    34.834    1.540  
## 2  rbindfn(z)          100   0.713    4.513     0.708    0.012 
## 3 unlistfn(z)          100   0.158    1.000     0.144    0.008 

If this scales appropriately (i.e. you don't run into memory problems), the full problem would take about 130*0.2 seconds = 26 seconds on a comparable machine (I did this on a 2-year-old MacBook Pro).

Does static constexpr variable inside a function make sense?

The short answer is that not only is static useful, it is pretty well always going to be desired.

First, note that static and constexpr are completely independent of each other. static defines the object's lifetime during execution; constexpr specifies that the object should be available during compilation. Compilation and execution are disjoint and discontiguous, both in time and space. So once the program is compiled, constexpr is no longer relevant.

Every variable declared constexpr is implicitly const but const and static are almost orthogonal (except for the interaction with static const integers.)

The C++ object model (§1.9) requires that all objects other than bit-fields occupy at least one byte of memory and have addresses; furthermore all such objects observable in a program at a given moment must have distinct addresses (paragraph 6). This does not quite require the compiler to create a new array on the stack for every invocation of a function with a local non-static const array, because the compiler could take refuge in the as-if principle provided it can prove that no other such object can be observed.

That's not going to be easy to prove, unfortunately, unless the function is trivial (for example, it does not call any other function whose body is not visible within the translation unit) because arrays, more or less by definition, are addresses. So in most cases, the non-static const(expr) array will have to be recreated on the stack at every invocation, which defeats the point of being able to compute it at compile time.

On the other hand, a local static const object is shared by all observers, and furthermore may be initialized even if the function it is defined in is never called. So none of the above applies, and a compiler is free not only to generate only a single instance of it; it is free to generate a single instance of it in read-only storage.

So you should definitely use static constexpr in your example.

However, there is one case where you wouldn't want to use static constexpr. Unless a constexpr declared object is either ODR-used or declared static, the compiler is free to not include it at all. That's pretty useful, because it allows the use of compile-time temporary constexpr arrays without polluting the compiled program with unnecessary bytes. In that case, you would clearly not want to use static, since static is likely to force the object to exist at runtime.

How to convert milliseconds to seconds with precision

Surely you just need:

double seconds = milliseconds / 1000.0;

There's no need to manually do the two parts separately - you just need floating point arithmetic, which the use of 1000.0 (as a double literal) forces. (I'm assuming your milliseconds value is an integer of some form.)

Note that as usual with double, you may not be able to represent the result exactly. Consider using BigDecimal if you want to represent 100ms as 0.1 seconds exactly. (Given that it's a physical quantity, and the 100ms wouldn't be exact in the first place, a double is probably appropriate, but...)

How to locate and insert a value in a text box (input) using Python Selenium?

Assuming your page is available under "http://example.com"

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://example.com")

Select element by id:

inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')

Now you can simulate hitting ENTER:

inputElement.send_keys(Keys.ENTER)

or if it is a form you can submit:

inputElement.submit() 

Good Hash Function for Strings

If it's a security thing, you could use Java crypto:

import java.security.MessageDigest;

MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(stringToHash.getBytes());
String stringHash = new String(messageDigest.digest());

How to get HTML 5 input type="date" working in Firefox and/or IE 10

I had to use bootstrap-datepicker plugin to get the calendar working on Firefox 55 Portable:

https://bootstrap-datepicker.readthedocs.io/en/latest/

Compatible with Bootstrap v2 and v3. It comes with a standalone stylesheet so you don't have to depend on Bootstrap.

Usage:

<input class="datepicker">

$('.datepicker').datepicker({
    format: 'mm/dd/yyyy'
});

Init array of structs in Go

It looks like you are trying to use (almost) straight up C code here. Go has a few differences.

  • First off, you can't initialize arrays and slices as const. The term const has a different meaning in Go, as it does in C. The list should be defined as var instead.
  • Secondly, as a style rule, Go prefers basenameOpts as opposed to basename_opts.
  • There is no char type in Go. You probably want byte (or rune if you intend to allow unicode codepoints).
  • The declaration of the list must have the assignment operator in this case. E.g.: var x = foo.
  • Go's parser requires that each element in a list declaration ends with a comma. This includes the last element. The reason for this is because Go automatically inserts semi-colons where needed. And this requires somewhat stricter syntax in order to work.

For example:

type opt struct {
    shortnm      byte
    longnm, help string
    needArg      bool
}

var basenameOpts = []opt { 
    opt {
        shortnm: 'a', 
        longnm: "multiple", 
        needArg: false, 
        help: "Usage for a",
    },
    opt {
        shortnm: 'b', 
        longnm: "b-option", 
        needArg: false, 
        help: "Usage for b",
    },
}

An alternative is to declare the list with its type and then use an init function to fill it up. This is mostly useful if you intend to use values returned by functions in the data structure. init functions are run when the program is being initialized and are guaranteed to finish before main is executed. You can have multiple init functions in a package, or even in the same source file.

    type opt struct {
        shortnm      byte
        longnm, help string
        needArg      bool
    }

    var basenameOpts []opt

    func init() { 
        basenameOpts = []opt{
            opt {
                shortnm: 'a', 
                longnm: "multiple", 
                needArg: false, 
                help: "Usage for a",
            },
            opt {
                shortnm: 'b', 
                longnm: "b-option", 
                needArg: false, 
               help: "Usage for b",
            },
        }
    }

Since you are new to Go, I strongly recommend reading through the language specification. It is pretty short and very clearly written. It will clear a lot of these little idiosyncrasies up for you.

Format Date/Time in XAML in Silverlight

For me this worked:

<TextBlock Text="{Binding Date , StringFormat=g}" Width="130"/>

If want to show seconds also using G instead of g :

<TextBlock Text="{Binding Date , StringFormat=G}" Width="130"/>

Also if want for changing date type to another like Persian , using Language :

<TextBlock Text="{Binding Date , StringFormat=G}" Width="130" Language="fa-IR"/>

Copy files from one directory into an existing directory

cp dir1/* dir2

Or if you have directories inside dir1 that you'd want to copy as well

cp -r dir1/* dir2

Why is the console window closing immediately once displayed my output?

if your program requires you to press enter to continue like you have to enter a value and continue, then add a new double or int and type write before retunr(0); scanf_s("%lf",&the variable);

Codeigniter - no input file specified

My site is hosted on MochaHost, i had a tough time to setup the .htaccess file so that i can remove the index.php from my urls. However, after some googling, i combined the answer on this thread and other answers. My final working .htaccess file has the following contents:

<IfModule mod_rewrite.c>
    # Turn on URL rewriting
    RewriteEngine On

    # If your website begins from a folder e.g localhost/my_project then 
    # you have to change it to: RewriteBase /my_project/
    # If your site begins from the root e.g. example.local/ then
    # let it as it is
    RewriteBase /

    # Protect application and system files from being viewed when the index.php is missing
    RewriteCond $1 ^(application|system|private|logs)

    # Rewrite to index.php/access_denied/URL
    RewriteRule ^(.*)$ index.php/access_denied/$1 [PT,L]

    # Allow these directories and files to be displayed directly:
    RewriteCond $1 ^(index\.php|robots\.txt|favicon\.ico|public|app_upload|assets|css|js|images)

    # No rewriting
    RewriteRule ^(.*)$ - [PT,L]

    # Rewrite to index.php/URL
    RewriteRule ^(.*)$ index.php?/$1 [PT,L]
</IfModule>

Git refusing to merge unrelated histories on rebase

For Googlers:

If you created a new repo on GitHub and accidentally initialized it with README or .gitignore files.

If you found yourself unable to merge or rebase because .git folder got corrupted.

Then:

  • Create a new folder
  • git clone
  • Paste all your files into this folder

Now the local and remote will have "related histories" and will merge or rebase happily.

Importing packages in Java

Take out the method name from in your import statement. e.g.

import Dan.Vik.disp;

becomes:

import Dan.Vik;

How to make a new List in Java

Let me summarize and add something:

JDK

1. new ArrayList<String>();
2. Arrays.asList("A", "B", "C")

Guava

1. Lists.newArrayList("Mike", "John", "Lesly");
2. Lists.asList("A","B", new String [] {"C", "D"});

Immutable List

1. Collections.unmodifiableList(new ArrayList<String>(Arrays.asList("A","B")));
2. ImmutableList.builder()                                      // Guava
            .add("A")
            .add("B").build();
3. ImmutableList.of("A", "B");                                  // Guava
4. ImmutableList.copyOf(Lists.newArrayList("A", "B", "C"));     // Guava

Empty immutable List

1. Collections.emptyList();
2. Collections.EMPTY_LIST;

List of Characters

1. Lists.charactersOf("String")                                 // Guava
2. Lists.newArrayList(Splitter.fixedLength(1).split("String"))  // Guava

List of Integers

Ints.asList(1,2,3);                                             // Guava

How to declare a variable in a PostgreSQL query

Dynamic Config Settings

you can "abuse" dynamic config settings for this:

-- choose some prefix that is unlikely to be used by postgres
set session my.vars.id = '1';

select *
from person 
where id = current_setting('my.vars.id')::int;

Config settings are always varchar values, so you need to cast them to the correct data type when using them. This works with any SQL client whereas \set only works in psql

The above requires Postgres 9.2 or later.

For previous versions, the variable had to be declared in postgresql.conf prior to being used, so it limited its usability somewhat. Actually not the variable completely, but the config "class" which is essentially the prefix. But once the prefix was defined, any variable could be used without changing postgresql.conf

Remove "Using default security password" on Spring Boot

To remove default user you need to configure authentication menager with no users for example:

@configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication();
    }
}

this will remove default password message and default user because in that case you are configuring InMemoryAuthentication and you will not specify any user in next steps

Convert string to nullable type (int, double, etc...)

What about this:


double? amount = string.IsNullOrEmpty(strAmount) ? (double?)null : Convert.ToDouble(strAmount);

Of course, this doesn't take into account the convert failing.

Can't pickle <type 'instancemethod'> when using multiprocessing Pool.map()

In this simple case, where someClass.f is not inheriting any data from the class and not attaching anything to the class, a possible solution would be to separate out f, so it can be pickled:

import multiprocessing


def f(x):
    return x*x


class someClass(object):
    def __init__(self):
        pass

    def go(self):
        pool = multiprocessing.Pool(processes=4)       
        print pool.map(f, range(10))

Getting all files in directory with ajax

Javascript which runs on the client machine can't access the local disk file system due to security restrictions.

If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.

Send message to specific client with socket.io and node.js

You can do this

On server.

global.io=require("socket.io")(server);

io.on("connection",function(client){
    console.log("client is ",client.id);
    //This is handle by current connected client 
    client.emit('messages',{hello:'world'})
    //This is handle by every client
    io.sockets.emit("data",{data:"This is handle by every client"})
    app1.saveSession(client.id)

    client.on("disconnect",function(){
        app1.deleteSession(client.id)
        console.log("client disconnected",client.id);
    })

})

    //And this is handle by particular client 
    var socketId=req.query.id
    if(io.sockets.connected[socketId]!=null) {
        io.sockets.connected[socketId].emit('particular User', {data: "Event response by particular user "});
    }

And on client, it is very easy to handle.

var socket=io.connect("http://localhost:8080/")
    socket.on("messages",function(data){
        console.log("message is ",data);
        //alert(data)
    })
    socket.on("data",function(data){
        console.log("data is ",data);
        //alert(data)
    })

    socket.on("particular User",function(data){
        console.log("data from server ",data);
        //alert(data)
    })

MVC 5 Access Claims Identity User Data

I make my own extended class to see what I need, so when I need into my controller or my View, I only add the using to my namespace something like this:

public static class UserExtended
{
    public static string GetFullName(this IPrincipal user)
    {
        var claim = ((ClaimsIdentity)user.Identity).FindFirst(ClaimTypes.Name);
        return claim == null ? null : claim.Value;
    }
    public static string GetAddress(this IPrincipal user)
    {
        var claim = ((ClaimsIdentity)user.Identity).FindFirst(ClaimTypes.StreetAddress);
        return claim == null ? null : claim.Value;
    }
    public ....
    {
      .....
    }
}

In my controller:

using XXX.CodeHelpers.Extended;

var claimAddress = User.GetAddress();

In my razor:

@using DinexWebSeller.CodeHelpers.Extended;

@User.GetFullName()

PhoneGap Eclipse Issue - eglCodecCommon glUtilsParamSize: unknow param errors

It's very annoying. I'm not sure why Google places it there - no one needs these trash from emulator at all; we know what we are doing. I'm using pidcat and I modified it a bit
BUG_LINE = re.compile(r'.*nativeGetEnabledTags.*') BUG_LINE2 = re.compile(r'.*glUtilsParamSize.*') BUG_LINE3 = re.compile(r'.*glSizeof.*')

and
bug_line = BUG_LINE.match(line) if bug_line is not None: continue bug_line2 = BUG_LINE2.match(line) if bug_line2 is not None: continue bug_line3 = BUG_LINE3.match(line) if bug_line3 is not None: continue

It's an ugly fix and if you're using the real device you may need those OpenGL errors, but you got the idea.

SQL Column definition : default value and not null redundant?

My SQL teacher said that if you specify both a DEFAULT value and NOT NULLor NULL, DEFAULT should always be expressed before NOT NULL or NULL.

Like this:

ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT "MyDefault" NOT NULL

ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT "MyDefault" NULL

golang why don't we have a set datastructure

One reason is that it is easy to create a set from map:

s := map[int]bool{5: true, 2: true}
_, ok := s[6] // check for existence
s[8] = true // add element 
delete(s, 2) // remove element

Union

s_union := map[int]bool{}
for k, _ := range s1{
    s_union[k] = true
}
for k, _ := range s2{
    s_union[k] = true
}

Intersection

s_intersection := map[int]bool{}
for k,_ := range s1 { 
  if s2[k] {
    s_intersection[k] = true
  }
}

It is not really that hard to implement all other set operations.

Is Constructor Overriding Possible?

What you describe isn't overriding. If you don't specify a default constructor, the compiler will create a default constructor. If it's a subclass, it will call the default parent constructor(super()), it will also initialize all instance variables to a default value determined by the type's default value(0 for numeric types, false for booleans, or null for objects).

Overriding happens when a subclass has the same name, number/type of parameters, and the same return type as an instance method of the superclass. In this case, the subclass will override the superclass's method. Information on overriding here.

Difference Between One-to-Many, Many-to-One and Many-to-Many?

One-to-Many: One Person Has Many Skills, a Skill is not reused between Person(s)

  • Unidirectional: A Person can directly reference Skills via its Set
  • Bidirectional: Each "child" Skill has a single pointer back up to the Person (which is not shown in your code)

Many-to-Many: One Person Has Many Skills, a Skill is reused between Person(s)

  • Unidirectional: A Person can directly reference Skills via its Set
  • Bidirectional: A Skill has a Set of Person(s) which relate to it.

In a One-To-Many relationship, one object is the "parent" and one is the "child". The parent controls the existence of the child. In a Many-To-Many, the existence of either type is dependent on something outside the both of them (in the larger application context).

Your subject matter (domain) should dictate whether or not the relationship is One-To-Many or Many-To-Many -- however, I find that making the relationship unidirectional or bidirectional is an engineering decision that trades off memory, processing, performance, etc.

What can be confusing is that a Many-To-Many Bidirectional relationship does not need to be symmetric! That is, a bunch of People could point to a skill, but the skill need not relate back to just those people. Typically it would, but such symmetry is not a requirement. Take love, for example -- it is bi-directional ("I-Love", "Loves-Me"), but often asymmetric ("I love her, but she doesn't love me")!

All of these are well supported by Hibernate and JPA. Just remember that Hibernate or any other ORM doesn't give a hoot about maintaining symmetry when managing bi-directional many-to-many relationships...thats all up to the application.

Using Java 8 to convert a list of objects into a string obtained from the toString() method

String actual = list.stream().reduce((t, u) -> t + "," + u).get();

Focusable EditText inside ListView

This saved my life--->

  1. set this line

    ListView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);

  2. Then in your manifest in activity tag type this-->

    <activity android:windowSoftInputMode="adjustPan">

Your usual intent

How do I timestamp every ping result?

On OS X you can simply use the --apple-time option:

ping -i 2 --apple-time www.apple.com

Produces results like:

10:09:55.691216 64 bytes from 72.246.225.209: icmp_seq=0 ttl=60 time=34.388 ms
10:09:57.687282 64 bytes from 72.246.225.209: icmp_seq=1 ttl=60 time=25.319 ms
10:09:59.729998 64 bytes from 72.246.225.209: icmp_seq=2 ttl=60 time=64.097 ms

Singleton design pattern vs Singleton beans in Spring container

"singleton" in spring is using bean factory get instance, then cache it; which singleton design pattern is strictly, the instance can only be retrieved from static get method, and the object can never be publicly instantiated.

PHP remove special character from string

preg_replace('#[^\w()/.%\-&]#',"",$string);

How to create relationships in MySQL

CREATE TABLE accounts(
    account_id INT NOT NULL AUTO_INCREMENT,
    customer_id INT( 4 ) NOT NULL ,
    account_type ENUM( 'savings', 'credit' ) NOT NULL,
    balance FLOAT( 9 ) NOT NULL,
    PRIMARY KEY ( account_id )
)

and

CREATE TABLE customers(
    customer_id INT NOT NULL AUTO_INCREMENT,
    name VARCHAR(20) NOT NULL,
    address VARCHAR(20) NOT NULL,
    city VARCHAR(20) NOT NULL,
    state VARCHAR(20) NOT NULL,
)

How do I create a 'relationship' between the two tables? I want each account to be 'assigned' one customer_id (to indicate who owns it).

You have to ask yourself is this a 1 to 1 relationship or a 1 out of many relationship. That is, does every account have a customer and every customer have an account. Or will there be customers without accounts. Your question implies the latter.

If you want to have a strict 1 to 1 relationship, just merge the two tables.

CREATE TABLE customers(
    customer_id INT NOT NULL AUTO_INCREMENT,
    name VARCHAR(20) NOT NULL,
    address VARCHAR(20) NOT NULL,
    city VARCHAR(20) NOT NULL,
    state VARCHAR(20) NOT NULL,
    account_type ENUM( 'savings', 'credit' ) NOT NULL,
    balance FLOAT( 9 ) NOT NULL,
)

In the other case, the correct way to create a relationship between two tables is to create a relationship table.

CREATE TABLE customersaccounts(
    customer_id INT NOT NULL,
    account_id INT NOT NULL,
    PRIMARY KEY (customer_id, account_id)
    FOREIGN KEY customer_id references customers (customer_id) on delete cascade,
    FOREIGN KEY account_id  references accounts  (account_id) on delete cascade
}

Then if you have a customer_id and want the account info, you join on customersaccounts and accounts:

SELECT a.*
    FROM customersaccounts ca
        INNER JOIN accounts a ca.account_id=a.account_id
            AND ca.customer_id=mycustomerid;

Because of indexing this will be blindingly quick.

You could also create a VIEW which gives you the effect of the combined customersaccounts table while keeping them separate

CREATE VIEW customeraccounts AS 
    SELECT a.*, c.* FROM customersaccounts ca
        INNER JOIN accounts a ON ca.account_id=a.account_id
        INNER JOIN customers c ON ca.customer_id=c.customer_id;

How do you debug MySQL stored procedures?

The first and stable debugger for MySQL is in dbForge Studio for MySQL

Google Script to see if text contains a value

Update 2020:

You can now use Modern ECMAScript syntax thanks to V8 Runtime.

You can use includes():

var grade = itemResponse.getResponse();
if(grade.includes("9th")){do something}

How to open an Excel file in C#?

It's easier to help you if you say what's wrong as well, or what fails when you run it.

But from a quick glance you've confused a few things.

The following doesn't work because of a couple of issues.

if (Directory("C:\\csharp\\error report1.xls") = "")

What you are trying to do is creating a new Directory object that should point to a file and then check if there was any errors.

What you are actually doing is trying to call a function named Directory() and then assign a string to the result. This won't work since 1/ you don't have a function named Directory(string str) and you cannot assign to the result from a function (you can only assign a value to a variable).

What you should do (for this line at least) is the following

FileInfo fi = new FileInfo("C:\\csharp\\error report1.xls");
if(!fi.Exists)
{
    // Create the xl file here
}
else
{
    // Open file here
}

As to why the Excel code doesn't work, you have to check the documentation for the Excel library which google should be able to provide for you.

Selecting only first-level elements in jquery

You can also use $("ul li:first-child") to only get the direct children of the UL.

I agree though, you need an ID or something else to identify the main UL otherwise it will just select them all. If you had a div with an ID around the UL the easiest thing to do would be$("#someDiv > ul > li")

how to get html content from a webview?

Actually this question has many answers. Here are 2 of them :

  • This first is almost the same as yours, I guess we got it from the same tutorial.

public class TestActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview);
        final WebView webview = (WebView) findViewById(R.id.browser);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.addJavascriptInterface(new MyJavaScriptInterface(this), "HtmlViewer");

        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                webview.loadUrl("javascript:window.HtmlViewer.showHTML" +
                        "('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
            }
        });

        webview.loadUrl("http://android-in-action.com/index.php?post/" +
                "Common-errors-and-bugs-and-how-to-solve-avoid-them");
    }

    class MyJavaScriptInterface {

        private Context ctx;

        MyJavaScriptInterface(Context ctx) {
            this.ctx = ctx;
        }

        public void showHTML(String html) {
            new AlertDialog.Builder(ctx).setTitle("HTML").setMessage(html)
                    .setPositiveButton(android.R.string.ok, null).setCancelable(false).create().show();
        }

    }
}

This way your grab the html through javascript. Not the prettiest way but when you have your javascript interface, you can add other methods to tinker it.


  • An other way is using an HttpClient like there.

The option you choose also depends, I think, on what you intend to do with the retrieved html...

Clearing localStorage in javascript?

Here is a simple code that will clear localstorage stored in your browser by using javascript

    <script type="text/javascript">

if(localStorage) { // Check if the localStorage object exists

    localStorage.clear()  //clears the localstorage

} else {

    alert("Sorry, no local storage."); //an alert if localstorage is non-existing
}

</script>

To confirm if localstorage is empty use this code:

<script type="text/javascript">

// Check if the localStorage object exists
if(localStorage) {

    alert("Am still here, " + localStorage.getItem("your object name")); //put the object name
} else {
    alert("Sorry, i've been deleted ."); //an alert
}

</script>

if it returns null then your localstorage is cleared.

When is del useful in Python?

To add a few points to above answers: del x

Definition of x indicates r -> o (a reference r pointing to an object o) but del x changes r rather than o. It is an operation on the reference (pointer) to object rather than the object associated with x. Distinguishing between r and o is key here.

  • It removes it from locals().
  • Removes it from globals() if x belongs there.
  • Removes it from the stack frame (removes the reference physically from it, but the object itself resides in object pool and not in the stack frame).
  • Removes it from the current scope. It is very useful to limit the span of definition of a local variable, which otherwise can cause problems.
  • It is more about declaration of the name rather than definition of content.
  • It affects where x belongs to, not where x points to. The only physical change in memory is this. For example if x is in a dictionary or list, it (as a reference) is removed from there(and not necessarily from the object pool). In this example, the dictionary it belongs is the stack frame (locals()), which overlaps with globals().

"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions" error

The ...For extension methods on the HtmlHelper (e.g., DisplayFor, TextBoxFor, ElementFor, etc...) take a property and nothing else. If you don't have a property, use the non-For method (e.g., Display, TextBox, Element, etc...).

The ...For extension methods provides a way of simplifying postback by naming the control after the property. This is why it takes an expression and not simply a value. If you are not interested in this postback facilitation then do not use the ...For methods at all.

Note: You should not be doing things like calling ToString inside the view. This should be done inside the view model. I realize that a lot of demo projects put domain objects straight into the view. In my experience, this rarely works because it assumes that you do not want any formatting on the data in the domain entity. Best practice is to create a view model that wraps the entity into something that can be directly consumed by the view. Most of the properties in this view model should be strings that are already formatted or data for which you have element or display templates created.

Manually Set Value for FormBuilder Control

I know the answer is already given but I want give a bit brief answer how to update value of a form so that other new comers can get a clear idea.

your form structure is so perfect to use it as an example. so, throughout my answer I will denote it as the form.

this.form = this.fb.group({
    'name': ['', Validators.required],
    'dept': ['', Validators.required],
    'description': ['', Validators.required]
  });

so our form is a FormGroup type of object that has three FormControl.

There are two ways to update the model value:

  • Use the setValue() method to set a new value for an individual control. The setValue() method strictly adheres to the structure of the form group and replaces the entire value for the control.

  • Use the patchValue() method to replace any properties defined in the object that have changed in the form model.

The strict checks of the setValue() method help catch nesting errors in complex forms, while patchValue() fails silently on those errors.

From Angular official documentation here

so, When updating the value for a form group instance that contains multiple controls, but you may only want to update parts of the model. patchValue() is the one you are looking for.

lets see example. When you use patchValue()

this.form.patchValue({
    dept: 1 
});
//here we are just updating only dept field and it will work.

but when you use setValue() you need to update the full model as it strictly adheres the structure of the form group. so, if we write

this.form.setValue({
    dept: 1 
});
// it will throw error.

We must pass all the properties of the form group model. like this

this.form.setValue({
      name: 'Mr. Bean'
      dept: 1,
      description: 'spome description'
  });

but I don't use this style frequently. I prefer using the following approach that helps to keep my code cleaner and more understandable.

What I do is, I declare all the controls as a seperate variable and use setValue() to update that specific control.

for the above form, I will do something like this.

get companyIdentifier(): FormControl {
    return this.form.get('name') as FormControl;
}

get dept(): FormControl {
    return this.form.get('dept') as FormControl;
}

get description(): FormControl {
    return this.form.get('description') as FormControl;
}

when you need to update the form control just use that property to update it. In the example the questioner tried to update the dept form control when user select an item from the drop down list.

deptSelected(selected: { id: string; text: string }) {
  console.log(selected) // Shows proper selection!

  // instead of using this.form.controls['dept'].setValue(selected.id), I prefer the following.

  this.dept.setValue(selected.id); // this.dept is the property that returns the 'dept' FormControl of the form.
}

I suggest to have a look FormGroup API to get know how of all the properties and methods of FormGroup.

Additional: to know about getter see here

How to fix C++ error: expected unqualified-id

Semicolon should be at the end of the class definition rather than after the name:

class WordGame
{
};

What is the purpose of class methods?

Alternative constructors are the classic example.

How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

You can just use the + operator!

irb(main):001:0> a = [1,2]
=> [1, 2]
irb(main):002:0> b = [3,4]
=> [3, 4]
irb(main):003:0> a + b
=> [1, 2, 3, 4]

You can read all about the array class here: http://ruby-doc.org/core/classes/Array.html

HTML select dropdown list

Maybe this can help you resolve without JavaScript http://htmlhelp.com/reference/html40/forms/option.html

See DISABLE option

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

Remove YouTube Branding

To date: Seeing a lot of searches and suggestions to disable YouTube logo and branding from an embedded video; I recommend you consider the following:

  1. I guess YouTube don't want you to do this otherwise they would allow that at their front end.
  2. Some brands spending huge efforts to provide the media not for a 5 min. removal.
  3. It's good to have the logo and respects brands rights.
  4. You still have the video and the luxury of embedding it in your site/blog.
  5. Spare some of your time; that is not possible.
  6. Yet! You have the option of having Modest-Branding using this parameters:

    https://www.youtube.com/embed/'+videourl+'?modestbranding=1

And some other parameters for customization:

&showinfo=0 //Turn off Title & Ratings

&showsearch=0 //Turn off Search

&rel=1 //Turn on Related Videos

&iv_load_policy=3 //Turn off Annotations

&cc_load_policy=1 //Force Closed Captions

&autoplay=1 //Turn on AutoPlay (not recommended)

&loop=1 //Loop Playback

&fs=0 //Remove Full Screen Option (not sure why you’d want to)

And here is the general customization window:

How to customize YouTube embed

Disclaimer: I don't work for YouTube; simply I respect the copyrights.

type checking in javascript

A variable will never be an integer type in JavaScript — it doesn't distinguish between different types of Number.

You can test if the variable contains a number, and if that number is an integer.

(typeof foo === "number") && Math.floor(foo) === foo

If the variable might be a string containing an integer and you want to see if that is the case:

foo == parseInt(foo, 10)

How to show imageView full screen on imageView click?

That didn't work for me, I used some code parts from web, what I did:

new activity: FullScreenImage with:

package yourpackagename;
import yourpackagename.R;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class FullScreenImage  extends Activity {


@SuppressLint("NewApi")



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.layout_full);

    Bundle extras = getIntent().getExtras();
    Bitmap bmp = (Bitmap) extras.getParcelable("imagebitmap");

    ImageView imgDisplay;
    Button btnClose;


    imgDisplay = (ImageView) findViewById(R.id.imgDisplay);
    btnClose = (Button) findViewById(R.id.btnClose);


   btnClose.setOnClickListener(new View.OnClickListener() {            
    public void onClick(View v) {
    FullScreenImage.this.finish();
}
});


 imgDisplay.setImageBitmap(bmp );

}   


}

Then create a xml: layout_full

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<ImageView
    android:id="@+id/imgDisplay"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scaleType="fitCenter" />

<Button
    android:id="@+id/btnClose"
    android:layout_width="wrap_content"
    android:layout_height="30dp"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_marginRight="15dp"
    android:layout_marginTop="15dp"
    android:paddingTop="2dp"
    android:paddingBottom="2dp"
    android:textColor="#ffffff"
    android:text="Close" />

   </RelativeLayout>

And finally, send the image name from your mainactivity

   final ImageView im = (ImageView)findViewById(R.id.imageView1) ; 
   im.setBackgroundDrawable(getResources().getDrawable(id1));

   im.setOnClickListener(new OnClickListener() {

      @Override
       public void onClick(View view) {
       Intent intent = new Intent(NAMEOFYOURCURRENTACTIVITY.this, FullScreenImage.class);

       im.buildDrawingCache();
       Bitmap image= im.getDrawingCache();

       Bundle extras = new Bundle();
       extras.putParcelable("imagebitmap", image);
       intent.putExtras(extras);
       startActivity(intent);

                                }
                            });

How do I apply the for-each loop to every character in a String?

For Travers an String you can also use charAt() with the string.

like :

String str = "xyz"; // given String
char st = str.charAt(0); // for example we take 0 index element 
System.out.println(st); // print the char at 0 index 

charAt() is method of string handling in java which help to Travers the string for specific character.

Android Room - simple select query - Cannot access database on the main thread

You have to execute request in background. A simple way could be using an Executors :

Executors.newSingleThreadExecutor().execute { 
   yourDb.yourDao.yourRequest() //Replace this by your request
}

How to extract elements from a list using indices in Python?

Perhaps use this:

[a[i] for i in (1,2,5)]
# [11, 12, 15]

Ansible: How to delete files and folders inside a directory?

While Ansible is still debating to implement state = empty https://github.com/ansible/ansible-modules-core/issues/902

my_folder: "/home/mydata/web/"
empty_path: "/tmp/empty"


- name: "Create empty folder for wiping."
  file:
    path: "{{ empty_path }}" 
    state: directory

- name: "Wipe clean {{ my_folder }} with empty folder hack."
  synchronize:
    mode: push

    #note the backslash here
    src: "{{ empty_path }}/" 

    dest: "{{ nl_code_path }}"
    recursive: yes
    delete: yes
  delegate_to: "{{ inventory_hostname }}"

Note though, with synchronize you should be able to sync your files (with delete) properly anyway.

CSS override rules and specificity

The specificity is calculated based on the amount of id, class and tag selectors in your rule. Id has the highest specificity, then class, then tag. Your first rule is now more specific than the second one, since they both have a class selector, but the first one also has two tag selectors.

To make the second one override the first one, you can make more specific by adding information of it's parents:

table.rule1 tr td.rule2 {
    background-color: #ffff00;
}

Here is a nice article for more information on selector precedence.

Drawing circles with System.Drawing

PictureBox circle = new PictureBox();
circle.Paint += new PaintEventHandler(circle_Paint);        

void circle_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.DrawEllipse(Pens.Red, 0, 0, 30, 30);
        }

How to check that Request.QueryString has a specific value or not in ASP.NET?

What about a more direct approach?

if (Request.QueryString.AllKeys.Contains("mykey")

How to put two divs on the same line with CSS in simple_form in rails?

You can't float or set the width of an inline element. Remove display: inline; from both classes and your markup should present fine.

EDIT: You can set the width, but it will cause the element to be rendered as a block.

Implicit function declarations in C

It should be considered an error. But C is an ancient language, so it's only a warning.
Compiling with -Werror (gcc) fixes this problem.

When C doesn't find a declaration, it assumes this implicit declaration: int f();, which means the function can receive whatever you give it, and returns an integer. If this happens to be close enough (and in case of printf, it is), then things can work. In some cases (e.g. the function actually returns a pointer, and pointers are larger than ints), it may cause real trouble.

Note that this was fixed in newer C standards (C99, C11). In these standards, this is an error. However, gcc doesn't implement these standards by default, so you still get the warning.

How to apply shell command to each line of a command output?

Better result for me:

ls -1 | xargs -L1 -d "\n" CMD

Add alternating row color to SQL Server Reporting services report

My matrix data had missing values in it, so I wasn't able to get ahmad's solution to work, but this solution worked for me

Basic idea is to create a child group and field on your innermost group containing the color. Then set the color for each cell in the row based on that field's value.

How to crop an image using C#?

Assuming you mean that you want to take an image file (JPEG, BMP, TIFF, etc) and crop it then save it out as a smaller image file, I suggest using a third party tool that has a .NET API. Here are a few of the popular ones that I like:

LeadTools
Accusoft Pegasus Snowbound Imaging SDK

Get specific ArrayList item

mainList.get(3);

For future reference, you should refer to the Java API for these types of questions:

http://download.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.html

It's a useful thing!

Convert a string to a datetime

Try converting date like this:

    Dim expenddt as Date = Date.ParseExact(edate, "dd/mm/yyyy", 
System.Globalization.DateTimeFormatInfo.InvariantInfo);

Hope this helps.

Accept function as parameter in PHP

You can also use create_function to create a function as a variable and pass it around. Though, I like the feeling of anonymous functions better. Go zombat.

How to find the .NET framework version of a Visual Studio project?

Simple Right Click and go to Properties Option of any project on your Existing application and see the Application option on Left menu and then click on Application option see target Framework to see current Framework version .

Automatic exit from Bash shell script on error

One point missed in the existing answers is show how to inherit the error traps. The bash shell provides one such option for that using set

-E

If set, any trap on ERR is inherited by shell functions, command substitutions, and commands executed in a subshell environment. The ERR trap is normally not inherited in such cases.


Adam Rosenfield's answer recommendation to use set -e is right in certain cases but it has its own potential pitfalls. See GreyCat's BashFAQ - 105 - Why doesn't set -e (or set -o errexit, or trap ERR) do what I expected?

According to the manual, set -e exits

if a simple commandexits with a non-zero status. The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test in a if statement, part of an && or || list except the command following the final && or ||, any command in a pipeline but the last, or if the command's return value is being inverted via !".

which means, set -e does not work under the following simple cases (detailed explanations can be found on the wiki)

  1. Using the arithmetic operator let or $((..)) ( bash 4.1 onwards) to increment a variable value as

    #!/usr/bin/env bash
    set -e
    i=0
    let i++                   # or ((i++)) on bash 4.1 or later
    echo "i is $i" 
    
  2. If the offending command is not part of the last command executed via && or ||. For e.g. the below trap wouldn't fire when its expected to

    #!/usr/bin/env bash
    set -e
    test -d nosuchdir && echo no dir
    echo survived
    
  3. When used incorrectly in an if statement as, the exit code of the if statement is the exit code of the last executed command. In the example below the last executed command was echo which wouldn't fire the trap, even though the test -d failed

    #!/usr/bin/env bash
    set -e
    f() { if test -d nosuchdir; then echo no dir; fi; }
    f 
    echo survived
    
  4. When used with command-substitution, they are ignored, unless inherit_errexit is set with bash 4.4

    #!/usr/bin/env bash
    set -e
    foo=$(expr 1-1; true)
    echo survived
    
  5. when you use commands that look like assignments but aren't, such as export, declare, typeset or local. Here the function call to f will not exit as local has swept the error code that was set previously.

    set -e
    f() { local var=$(somecommand that fails); }        
    g() { local var; var=$(somecommand that fails); }
    
  6. When used in a pipeline, and the offending command is not part of the last command. For e.g. the below command would still go through. One options is to enable pipefail by returning the exit code of the first failed process:

    set -e
    somecommand that fails | cat -
    echo survived
    

The ideal recommendation is to not use set -e and implement an own version of error checking instead. More information on implementing custom error handling on one of my answers to Raise error in a Bash script

Java: Add elements to arraylist with FOR loop where element name has increasing number

I assume Answer as an Integer data type so in this case, you can easily use Scanner class for adding the multiple elements(say 50).

private static final Scanner obj = new Scanner(System.in);
private static ArrayList<Integer> arrayList = new ArrayList<Integer>(50);
public static void main(String...S){
for (int i=0;i<50;i++) {
  /*Using Scanner class object to take input.*/
  arrayList.add(obj.nextInt());
}
 /*You can also check the elements of your ArrayList.*/
for (int i=0;i<50;i++) {
 /*Using get function for fetching the value present at index 'i'.*/
 System.out.print(arrayList.get(i)+" ");
}}

This is a simple and easy method for adding multiple values in an ArrayList using for loop. As in the above code, I presume the Answer as Integer it could be String, Double, Long et Cetra. So, in that case, you can use next(), nextDouble(), and nextLong() respectively.

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

C++ Implementation (not by me) here. Note that when your bytes are over 65535, you need to shift with a long value as shown here.

How to use mongoimport to import csv

I use this on mongoimport shell

mongoimport --db db_name --collection collection_name --type csv --file C:\\Your_file_path\target_file.csv --headerline

type can choose csv/tsv/json But only csv/tsv can use --headerline

You can read more on the offical doc.

How to use WinForms progress bar?

I would suggest you have a look at BackgroundWorker. If you have a loop that large in your WinForm it will block and your app will look like it has hanged.

Look at BackgroundWorker.ReportProgress() to see how to report progress back to the UI thread.

For example:

private void Calculate(int i)
{
    double pow = Math.Pow(i, i);
}

private void button1_Click(object sender, EventArgs e)
{
    progressBar1.Maximum = 100;
    progressBar1.Step = 1;
    progressBar1.Value = 0;
    backgroundWorker.RunWorkerAsync();
}

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    var backgroundWorker = sender as BackgroundWorker;
    for (int j = 0; j < 100000; j++)
    {
        Calculate(j);
        backgroundWorker.ReportProgress((j * 100) / 100000);
    }
}

private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    // TODO: do something with final calculation.
}

How to extract the substring between two markers?

Surprised that nobody has mentioned this which is my quick version for one-off scripts:

>>> x = 'gfgfdAAA1234ZZZuijjk'
>>> x.split('AAA')[1].split('ZZZ')[0]
'1234'

Interface/enum listing standard mime-type constants

There is now also the class org.apache.http.entity.ContentType from package org.apache.httpcomponents.httpcore, starting from 4.2 up.

GCM with PHP (Google Cloud Messaging)

After searching for a long time finally I am able to figure out what I exactly needed, Connecting to the GCM using PHP as a server side scripting language, The following tutorial will give us a clear idea of how to setup everything we need to get started with GCM

Android Push Notifications using Google Cloud Messaging (GCM), PHP and MySQL

Synchronization vs Lock

I am wondering which one of these is better in practice and why?

I've found that Lock and Condition (and other new concurrent classes) are just more tools for the toolbox. I could do most everything I needed with my old claw hammer (the synchronized keyword), but it was awkward to use in some situations. Several of those awkward situations became much simpler once I added more tools to my toolbox: a rubber mallet, a ball-peen hammer, a prybar, and some nail punches. However, my old claw hammer still sees its share of use.

I don't think one is really "better" than the other, but rather each is a better fit for different problems. In a nutshell, the simple model and scope-oriented nature of synchronized helps protect me from bugs in my code, but those same advantages are sometimes hindrances in more complex scenarios. Its these more complex scenarios that the concurrent package was created to help address. But using this higher level constructs requires more explicit and careful management in the code.

===

I think the JavaDoc does a good job of describing the distinction between Lock and synchronized (the emphasis is mine):

Lock implementations provide more extensive locking operations than can be obtained using synchronized methods and statements. They allow more flexible structuring, may have quite different properties, and may support multiple associated Condition objects.

...

The use of synchronized methods or statements provides access to the implicit monitor lock associated with every object, but forces all lock acquisition and release to occur in a block-structured way: when multiple locks are acquired they must be released in the opposite order, and all locks must be released in the same lexical scope in which they were acquired.

While the scoping mechanism for synchronized methods and statements makes it much easier to program with monitor locks, and helps avoid many common programming errors involving locks, there are occasions where you need to work with locks in a more flexible way. For example, **some algorithms* for traversing concurrently accessed data structures require the use of "hand-over-hand" or "chain locking": you acquire the lock of node A, then node B, then release A and acquire C, then release B and acquire D and so on. Implementations of the Lock interface enable the use of such techniques by allowing a lock to be acquired and released in different scopes, and allowing multiple locks to be acquired and released in any order.

With this increased flexibility comes additional responsibility. The absence of block-structured locking removes the automatic release of locks that occurs with synchronized methods and statements. In most cases, the following idiom should be used:

...

When locking and unlocking occur in different scopes, care must be taken to ensure that all code that is executed while the lock is held is protected by try-finally or try-catch to ensure that the lock is released when necessary.

Lock implementations provide additional functionality over the use of synchronized methods and statements by providing a non-blocking attempt to acquire a lock (tryLock()), an attempt to acquire the lock that can be interrupted (lockInterruptibly(), and an attempt to acquire the lock that can timeout (tryLock(long, TimeUnit)).

...

Generate a heatmap in MatPlotLib using a scatter data set

Instead of using np.hist2d, which in general produces quite ugly histograms, I would like to recycle py-sphviewer, a python package for rendering particle simulations using an adaptive smoothing kernel and that can be easily installed from pip (see webpage documentation). Consider the following code, which is based on the example:

import numpy as np
import numpy.random
import matplotlib.pyplot as plt
import sphviewer as sph

def myplot(x, y, nb=32, xsize=500, ysize=500):   
    xmin = np.min(x)
    xmax = np.max(x)
    ymin = np.min(y)
    ymax = np.max(y)

    x0 = (xmin+xmax)/2.
    y0 = (ymin+ymax)/2.

    pos = np.zeros([len(x),3])
    pos[:,0] = x
    pos[:,1] = y
    w = np.ones(len(x))

    P = sph.Particles(pos, w, nb=nb)
    S = sph.Scene(P)
    S.update_camera(r='infinity', x=x0, y=y0, z=0, 
                    xsize=xsize, ysize=ysize)
    R = sph.Render(S)
    R.set_logscale()
    img = R.get_image()
    extent = R.get_extent()
    for i, j in zip(xrange(4), [x0,x0,y0,y0]):
        extent[i] += j
    print extent
    return img, extent
    
fig = plt.figure(1, figsize=(10,10))
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)


# Generate some test data
x = np.random.randn(1000)
y = np.random.randn(1000)

#Plotting a regular scatter plot
ax1.plot(x,y,'k.', markersize=5)
ax1.set_xlim(-3,3)
ax1.set_ylim(-3,3)

heatmap_16, extent_16 = myplot(x,y, nb=16)
heatmap_32, extent_32 = myplot(x,y, nb=32)
heatmap_64, extent_64 = myplot(x,y, nb=64)

ax2.imshow(heatmap_16, extent=extent_16, origin='lower', aspect='auto')
ax2.set_title("Smoothing over 16 neighbors")

ax3.imshow(heatmap_32, extent=extent_32, origin='lower', aspect='auto')
ax3.set_title("Smoothing over 32 neighbors")

#Make the heatmap using a smoothing over 64 neighbors
ax4.imshow(heatmap_64, extent=extent_64, origin='lower', aspect='auto')
ax4.set_title("Smoothing over 64 neighbors")

plt.show()

which produces the following image:

enter image description here

As you see, the images look pretty nice, and we are able to identify different substructures on it. These images are constructed spreading a given weight for every point within a certain domain, defined by the smoothing length, which in turns is given by the distance to the closer nb neighbor (I've chosen 16, 32 and 64 for the examples). So, higher density regions typically are spread over smaller regions compared to lower density regions.

The function myplot is just a very simple function that I've written in order to give the x,y data to py-sphviewer to do the magic.

How can I get table names from an MS Access Database?

To build on Ilya's answer try the following query:

SELECT MSysObjects.Name AS table_name
FROM MSysObjects
WHERE (((Left([Name],1))<>"~") 
        AND ((Left([Name],4))<>"MSys") 
        AND ((MSysObjects.Type) In (1,4,6)))
order by MSysObjects.Name 

(this one works without modification with an MDB)

ACCDB users may need to do something like this

SELECT MSysObjects.Name AS table_name
FROM MSysObjects
WHERE (((Left([Name],1))<>"~") 
        AND ((Left([Name],4))<>"MSys") 
        AND ((MSysObjects.Type) In (1,4,6))
        AND ((MSysObjects.Flags)=0))
order by MSysObjects.Name 

As there is an extra table is included that appears to be a system table of some sort.

How do I make curl ignore the proxy?

In case of windows: use curl --proxy "" ...

MySQL select rows where left join is null

Try following query:-

 SELECT table1.id 
 FROM table1 
 where table1.id 
 NOT IN (SELECT user_one
         FROM Table2
             UNION
         SELECT user_two
         FROM Table2)

Hope this helps you.

How to prevent rm from reporting that a file was not found?

As far as rm -f doing "anything else", it does force (-f is shorthand for --force) silent removal in situations where rm would otherwise ask you for confirmation. For example, when trying to remove a file not writable by you from a directory that is writable by you.

Change the spacing of tick marks on the axis of a plot?

I just discovered the Hmisc package:

Contains many functions useful for data analysis, high-level graphics, utility operations, functions for computing sample size and power, importing and annotating datasets, imputing missing values, advanced table making, variable clustering, character string manipulation, conversion of R objects to LaTeX and html code, and recoding variables.

library(Hmisc)    
plot(...)
minor.tick(nx=10, ny=10) # make minor tick marks (without labels) every 10th

Using sed to mass rename files

 ls F00001-0708-*|sed 's|^F0000\(.*\)|mv & F000\1|' | bash

How to call a Python function from Node.js

Most of previous answers call the success of the promise in the on("data"), it is not the proper way to do it because if you receive a lot of data you will only get the first part. Instead you have to do it on the end event.

const { spawn } = require('child_process');
const pythonDir = (__dirname + "/../pythonCode/"); // Path of python script folder
const python = pythonDir + "pythonEnv/bin/python"; // Path of the Python interpreter

/** remove warning that you don't care about */
function cleanWarning(error) {
    return error.replace(/Detector is not able to detect the language reliably.\n/g,"");
}

function callPython(scriptName, args) {
    return new Promise(function(success, reject) {
        const script = pythonDir + scriptName;
        const pyArgs = [script, JSON.stringify(args) ]
        const pyprog = spawn(python, pyArgs );
        let result = "";
        let resultError = "";
        pyprog.stdout.on('data', function(data) {
            result += data.toString();
        });

        pyprog.stderr.on('data', (data) => {
            resultError += cleanWarning(data.toString());
        });

        pyprog.stdout.on("end", function(){
            if(resultError == "") {
                success(JSON.parse(result));
            }else{
                console.error(`Python error, you can reproduce the error with: \n${python} ${script} ${pyArgs.join(" ")}`);
                const error = new Error(resultError);
                console.error(error);
                reject(resultError);
            }
        })
   });
}
module.exports.callPython = callPython;

Call:

const pythonCaller = require("../core/pythonCaller");
const result = await pythonCaller.callPython("preprocessorSentiment.py", {"thekeyYouwant": value});

python:

try:
    argu = json.loads(sys.argv[1])
except:
    raise Exception("error while loading argument")

pandas: How do I split text in a column into multiple rows?

This splits the Seatblocks by space and gives each its own row.

In [43]: df
Out[43]: 
   CustNum     CustomerName  ItemQty Item                 Seatblocks  ItemExt
0    32363  McCartney, Paul        3  F04               2:218:10:4,6       60
1    31316     Lennon, John       25  F01  1:13:36:1,12 1:13:37:1,13      300

In [44]: s = df['Seatblocks'].str.split(' ').apply(Series, 1).stack()

In [45]: s.index = s.index.droplevel(-1) # to line up with df's index

In [46]: s.name = 'Seatblocks' # needs a name to join

In [47]: s
Out[47]: 
0    2:218:10:4,6
1    1:13:36:1,12
1    1:13:37:1,13
Name: Seatblocks, dtype: object

In [48]: del df['Seatblocks']

In [49]: df.join(s)
Out[49]: 
   CustNum     CustomerName  ItemQty Item  ItemExt    Seatblocks
0    32363  McCartney, Paul        3  F04       60  2:218:10:4,6
1    31316     Lennon, John       25  F01      300  1:13:36:1,12
1    31316     Lennon, John       25  F01      300  1:13:37:1,13

Or, to give each colon-separated string in its own column:

In [50]: df.join(s.apply(lambda x: Series(x.split(':'))))
Out[50]: 
   CustNum     CustomerName  ItemQty Item  ItemExt  0    1   2     3
0    32363  McCartney, Paul        3  F04       60  2  218  10   4,6
1    31316     Lennon, John       25  F01      300  1   13  36  1,12
1    31316     Lennon, John       25  F01      300  1   13  37  1,13

This is a little ugly, but maybe someone will chime in with a prettier solution.

Python: Select subset from list based on index set

You could just use list comprehension:

property_asel = [val for is_good, val in zip(good_objects, property_a) if is_good]

or

property_asel = [property_a[i] for i in good_indices]

The latter one is faster because there are fewer good_indices than the length of property_a, assuming good_indices are precomputed instead of generated on-the-fly.


Edit: The first option is equivalent to itertools.compress available since Python 2.7/3.1. See @Gary Kerr's answer.

property_asel = list(itertools.compress(property_a, good_objects))

JavaScript get clipboard data on paste event (Cross browser)

function myFunct( e ){
    e.preventDefault();

    var pastedText = undefined;
    if( window.clipboardData && window.clipboardData.getData ){
    pastedText = window.clipboardData.getData('Text');
} 
else if( e.clipboardData && e.clipboardData.getData ){
    pastedText = e.clipboardData.getData('text/plain');
}

//work with text

}
document.onpaste = myFunct;

How to implement reCaptcha for ASP.NET MVC?

Simple and Complete Solution working for me. Supports ASP.NET MVC 4 and 5 (Supports ASP.NET 4.0, 4.5, and 4.5.1)

Step 1: Install NuGet Package by "Install-Package reCAPTCH.MVC"

Step 2: Add your Public and Private key to your web.config file in appsettings section

<appSettings>
    <add key="ReCaptchaPrivateKey" value=" -- PRIVATE_KEY -- " />
    <add key="ReCaptchaPublicKey" value=" -- PUBLIC KEY -- " />
</appSettings>  

You can create an API key pair for your site at https://www.google.com/recaptcha/intro/index.html and click on Get reCAPTCHA at top of the page

Step 3: Modify your form to include reCaptcha

@using reCAPTCHA.MVC
@using (Html.BeginForm())
{
    @Html.Recaptcha()
    @Html.ValidationMessage("ReCaptcha")
    <input type="submit" value="Register" />
}

Step 4: Implement the Controller Action that will handle the form submission and Captcha validation

[CaptchaValidator(
PrivateKey = "your private reCaptcha Google Key",
ErrorMessage = "Invalid input captcha.",
RequiredMessage = "The captcha field is required.")]
public ActionResult MyAction(myVM model)
{
    if (ModelState.IsValid) //this will take care of captcha
    {
    }
}

OR

public ActionResult MyAction(myVM model, bool captchaValid)
{
    if (captchaValid) //manually check for captchaValid 
    {
    }
}

Opening Android Settings programmatically

You can try to call:

startActivityForResult(new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS));

for other screen in setting screen, you can go to

https://developer.android.com/reference/android/provider/Settings.html

Hope help you in this case.

MongoDB relationships: embed or reference?

MongoDB gives freedom to be schema-less and this feature can result in pain in the long term if not thought or planned well,

There are 2 options either Embed or Reference. I will not go through definitions as the above answers have well defined them.

When embedding you should answer one question is your embedded document going to grow, if yes then how much (remember there is a limit of 16 MB per document) So if you have something like a comment on a post, what is the limit of comment count, if that post goes viral and people start adding comments. In such cases, reference could be a better option (but even reference can grow and reach 16 MB limit).

So how to balance it, the answer is a combination of different patterns, check these links, and create your own mix and match based on your use case.

https://www.mongodb.com/blog/post/building-with-patterns-a-summary

https://www.mongodb.com/blog/post/6-rules-of-thumb-for-mongodb-schema-design-part-1

How to import a Python class that is in a directory above?

import sys
sys.path.append("..") # Adds higher directory to python modules path.

Update one MySQL table with values from another

UPDATE tobeupdated
INNER JOIN original ON (tobeupdated.value = original.value)
SET tobeupdated.id = original.id

That should do it, and really its doing exactly what yours is. However, I prefer 'JOIN' syntax for joins rather than multiple 'WHERE' conditions, I think its easier to read

As for running slow, how large are the tables? You should have indexes on tobeupdated.value and original.value

EDIT: we can also simplify the query

UPDATE tobeupdated
INNER JOIN original USING (value)
SET tobeupdated.id = original.id

USING is shorthand when both tables of a join have an identical named key such as id. ie an equi-join - http://en.wikipedia.org/wiki/Join_(SQL)#Equi-join

DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled

There are two ways to fix this:

  1. Execute the following in the MySQL console:

    SET GLOBAL log_bin_trust_function_creators = 1;

  2. Add the following to the mysql.ini configuration file:

    log_bin_trust_function_creators = 1;

The setting relaxes the checking for non-deterministic functions. Non-deterministic functions are functions that modify data (i.e. have update, insert or delete statement(s)). For more info, see here.

Please note, if binary logging is NOT enabled, this setting does not apply.

Binary Logging of Stored Programs

If binary logging is not enabled, log_bin_trust_function_creators does not apply.

log_bin_trust_function_creators

This variable applies when binary logging is enabled.

The best approach is a better understanding and use of deterministic declarations for stored functions. These declarations are used by MySQL to optimize the replication and it is a good thing to choose them carefully to have a healthy replication.

DETERMINISTIC A routine is considered “deterministic” if it always produces the same result for the same input parameters and NOT DETERMINISTIC otherwise. This is mostly used with string or math processing, but not limited to that.

NOT DETERMINISTIC Opposite of "DETERMINISTIC". "If neither DETERMINISTIC nor NOT DETERMINISTIC is given in the routine definition, the default is NOT DETERMINISTIC. To declare that a function is deterministic, you must specify DETERMINISTIC explicitly.". So it seems that if no statement is made, MySQl will treat the function as "NOT DETERMINISTIC". This statement from manual is in contradiction with other statement from another area of manual which tells that: " When you create a stored function, you must declare either that it is deterministic or that it does not modify data. Otherwise, it may be unsafe for data recovery or replication. By default, for a CREATE FUNCTION statement to be accepted, at least one of DETERMINISTIC, NO SQL, or READS SQL DATA must be specified explicitly. Otherwise an error occurs"

I personally got error in MySQL 5.5 if there is no declaration, so i always put at least one declaration of "DETERMINISTIC", "NOT DETERMINISTIC", "NO SQL" or "READS SQL DATA" regardless other declarations i may have.

READS SQL DATA This explicitly tells to MySQL that the function will ONLY read data from databases, thus, it does not contain instructions that modify data, but it contains SQL instructions that read data (e.q. SELECT).

MODIFIES SQL DATA This indicates that the routine contains statements that may write data (for example, it contain UPDATE, INSERT, DELETE or ALTER instructions).

NO SQL This indicates that the routine contains no SQL statements.

CONTAINS SQL This indicates that the routine contains SQL instructions, but does not contain statements that read or write data. This is the default if none of these characteristics is given explicitly. Examples of such statements are SELECT NOW(), SELECT 10+@b, SET @x = 1 or DO RELEASE_LOCK('abc'), which execute but neither read nor write data.

Note that there are MySQL functions that are not deterministic safe, such as: NOW(), UUID(), etc, which are likely to produce different results on different machines, so a user function that contains such instructions must be declared as NOT DETERMINISTIC. Also, a function that reads data from an unreplicated schema is clearly NONDETERMINISTIC. *

Assessment of the nature of a routine is based on the “honesty” of the creator: MySQL does not check that a routine declared DETERMINISTIC is free of statements that produce nondeterministic results. However, misdeclaring a routine might affect results or affect performance. Declaring a nondeterministic routine as DETERMINISTIC might lead to unexpected results by causing the optimizer to make incorrect execution plan choices. Declaring a deterministic routine as NONDETERMINISTIC might diminish performance by causing available optimizations not to be used.

Print text in Oracle SQL Developer SQL Worksheet window

enter image description here

for simple comments:

set serveroutput on format wrapped;
begin
    DBMS_OUTPUT.put_line('simple comment');
end;
/

-- do something

begin
    DBMS_OUTPUT.put_line('second simple comment');
end;
/

you should get:

anonymous block completed
simple comment

anonymous block completed
second simple comment

if you want to print out the results of variables, here's another example:

set serveroutput on format wrapped;
declare
a_comment VARCHAR2(200) :='first comment';
begin
    DBMS_OUTPUT.put_line(a_comment);
end;

/

-- do something


declare
a_comment VARCHAR2(200) :='comment';
begin
    DBMS_OUTPUT.put_line(a_comment || 2);
end;

your output should be:

anonymous block completed
first comment

anonymous block completed
comment2

iFrame src change event detection?

The iframe always keeps the parent page, you should use this to detect in which page you are in the iframe:

Html code:

<iframe id="iframe" frameborder="0" scrolling="no" onload="resizeIframe(this)" width="100%" src="www.google.com"></iframe>

Js:

    function resizeIframe(obj) {
        alert(obj.contentWindow.location.pathname);
    }

Injecting Mockito mocks into a Spring bean

I would suggest to migrate your project to Spring Boot 1.4. After that you can use new annotation @MockBean to fake your com.package.Dao

What is console.log?

Places you can view the console! Just to have them all in one answer.

Firefox

http://getfirebug.com/

(you can also now use Firefox's built in developer tools Ctrl+Shift+J (Tools > Web Developer > Error Console), but Firebug is much better; use Firebug)

Safari and Chrome

Basically the same.

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

https://developer.apple.com/technologies/safari/developer-tools.html

Internet Explorer

Don't forget you can use compatibility modes to debug IE7 and IE8 in IE9 or IE10

http://msdn.microsoft.com/en-us/library/ie/gg589507(v=vs.85).aspx

http://msdn.microsoft.com/en-us/library/dd565628(v=vs.85).aspx

If you must access the console in IE6 for IE7 use the Firebug Lite bookmarklet

http://getfirebug.com/firebuglite/ look for stable bookmarklet

http://en.wikipedia.org/wiki/Bookmarklet

Opera

http://www.opera.com/dragonfly/

iOS

Works for all iPhones, iPod touch and iPads.

http://developer.apple.com/library/ios/ipad/#DOCUMENTATION/AppleApplications/Reference/SafariWebContent/DebuggingSafarioniPhoneContent/DebuggingSafarioniPhoneContent.html

Now with iOS 6 you can view the console through Safari in OS X if you plug in your device. Or you can do so with the emulator, simply open a Safari browser window and go to the "Develop" tab. There you will find options to get the Safari inspector to communicate with your device.

Windows Phone, Android

Both of these have no console built in and no bookmarklet ability. So we use http://jsconsole.com/ type :listen and it will give you a script tag to place in your HTML. From then on you can view your console inside the jsconsole website.

iOS and Android

You can also use http://html.adobe.com/edge/inspect/ to access web inspector tools and the console on any device using their convenient browser plugin.


Older browser problems

Lastly older versions of IE will crash if you use console.log in your code and not have the developer tools open at the same time. Luckily it's an easy fix. Use the below code snippet at the top of your code:

 if(!window.console){ window.console = {log: function(){} }; } 

This checks to see if the console is present, and if not it sets it to an object with a blank function called log. This way window.console and window.console.log is never truly undefined.

SQL Server: Filter output of sp_who2

Similar to KyleMit answer, its possible to select directly the tables used by SP_WHO2, although I think it's only need dbo.sysprocesses table.

If someone open this SP, it can understand what it does. This is my best select to have a similar output as SP_WHO2

select convert(char(5),sp.spid) as SPID
        ,  CASE lower(sp.status)
                 When 'sleeping' Then lower(sp.status)
                 Else  upper(sp.status)
              END as Status
        , convert(sysname, rtrim(sp.loginame)) as LOGIN
        , CASE sp.hostname
                 When Null  Then '  .'
                 When ' ' Then '  .'
                 Else    rtrim(sp.hostname)
              END as HostName
        , CASE isnull(convert(char(5),sp.blocked),'0')
                 When '0' Then '  .'
                 Else isnull(convert(char(5),sp.blocked),'0')
              END as BlkBy
        , case when sp.dbid = 0 then null when sp.dbid <> 0 then db_name(sp.dbid) end as DBName
        , sp.cmd as Command
        , sp.cpu as CPUTime
        , sp.physical_io as DiskIO
        , sp.last_batch as LastBatch
        , sp.program_name as ProgramName 
        from master.dbo.sysprocesses sp (nolock)
  ;

Over this select, you can select the fields you need and have the order you want.

How do I make a div full screen?

When you say "full-screen", do you mean like full-screen for the computer, or for taking up the entire space in the browser?

You can't force the user into full-screen F11; however, you can make your div full screen by using the following CSS

div {width: 100%; height: 100%;}

This will of course assume your div is child of the <body> tag. Otherwise, you'd need to add the following in addition to the above code.

div {position: absolute; top: 0; left: 0;}

Error while trying to retrieve text for error ORA-01019

You can refer to this link.

Install ODAC 64 bit driver using CMD after install ODAC 32 bit:

  1. Go to ODAC bit folder where install.bat file is located using CMD.
  2. Type install.bat all c:/oracle odac command and press Enter.

    Installation file will be located at “c:/oracle” folder.

When installing Oracle 11g client 32 and 64 bit, you must change oracle base path: “c:/oracle”

How to prepend a string to a column value in MySQL?

  • UPDATE table_name SET Column1 = CONCAT('newtring', table_name.Column1) where 1
  • UPDATE table_name SET Column1 = CONCAT('newtring', table_name.Column2) where 1
  • UPDATE table_name SET Column1 = CONCAT('newtring', table_name.Column2, 'newtring2') where 1

We can concat same column or also other column of the table.

php - How do I fix this illegal offset type error

Illegal offset type errors occur when you attempt to access an array index using an object or an array as the index key.

Example:

$x = new stdClass();
$arr = array();
echo $arr[$x];
//illegal offset type

Your $xml array contains an object or array at $xml->entry[$i]->source for some value of $i, and when you try to use that as an index key for $s, you get that warning. You'll have to make sure $xml contains what you want it to and that you're accessing it correctly.

Create a tag in a GitHub repository

For creating git tag you can simply run git tag <tagname> command by replacing with the actual name of the tag. Here is a complete tutorial on the basics of managing git tags: https://www.drupixels.com/blog/git-tags-create-push-remote-checkout-and-much-more

Sending email from Azure

Sending from a third party SMTP isn't restricted by or specific to Azure. Using System.Net.Mail, create your message, configure your SMTP client, send the email:

// create the message
var msg = new MailMessage();
msg.From = new MailAddress("[email protected]"); 
msg.To.Add(strTo); 
msg.Subject = strSubject; 
msg.IsBodyHtml = true; 
msg.Body = strMessage;

// configure the smtp server
var smtp = new SmtpClient("YourSMTPServer"); 
var = new System.Net.NetworkCredential("YourSMTPServerUserName", "YourSMTPServerPassword");

// send the message
smtp.Send(msg); 

UPDATE: I added a post on Medium about how to do this with an Azure Function - https://medium.com/@viperguynaz/building-a-serverless-contact-form-f8f0bff46ba9

header('HTTP/1.0 404 Not Found'); not doing anything

You could try specifying an HTTP response code using an optional parameter:

header('HTTP/1.0 404 Not Found', true, 404);

How to BULK INSERT a file into a *temporary* table where the filename is a variable?

You could always construct the #temp table in dynamic SQL. For example, right now I guess you have been trying:

CREATE TABLE #tmp(a INT, b INT, c INT);

DECLARE @sql NVARCHAR(1000);

SET @sql = N'BULK INSERT #tmp ...' + @variables;

EXEC master.sys.sp_executesql @sql;

SELECT * FROM #tmp;

This makes it tougher to maintain (readability) but gets by the scoping issue:

DECLARE @sql NVARCHAR(MAX);

SET @sql = N'CREATE TABLE #tmp(a INT, b INT, c INT);

BULK INSERT #tmp ...' + @variables + ';

SELECT * FROM #tmp;';

EXEC master.sys.sp_executesql @sql;

EDIT 2011-01-12

In light of how my almost 2-year old answer was suddenly deemed incomplete and unacceptable, by someone whose answer was also incomplete, how about:

CREATE TABLE #outer(a INT, b INT, c INT);

DECLARE @sql NVARCHAR(MAX);

SET @sql = N'SET NOCOUNT ON; 

CREATE TABLE #inner(a INT, b INT, c INT);

BULK INSERT #inner ...' + @variables + ';

SELECT * FROM #inner;';

INSERT #outer EXEC master.sys.sp_executesql @sql;

VS Code - Search for text in all files in a directory

I think these official guide should work for your case.

VS Code allows you to quickly search over all files in the currently-opened folder. Press Ctrl+Shift+F and enter in your search term. Search results are grouped into files containing the search term, with an indication of the hits in each file and its location. Expand a file to see a preview of all of the hits within that file. Then single-click on one of the hits to view it in the editor.

How to force page refreshes or reloads in jQuery?

Replace with:

$('#something').click(function() {
    location.reload();
});

How to get a right click mouse event? Changing EventArgs to MouseEventArgs causes an error in Form1Designer?

For me neither the MouseClick or Click event worked, because the events, simply, are not called when you right click. The quick way to do it is:

 private void button1_MouseUp(object sender, MouseEventArgs e)
 {
        if (e.Button == MouseButtons.Right)
        {
            //do something here
        }
        else//left or middle click
        {
            //do something here
        }
 }

You can modify that to do exactly what you want depended on the arguments' values.

WARNING: There is one catch with only using the mouse up event. if you mousedown on the control and then you move the cursor out of the control to release it, you still get the event fired. In order to avoid that, you should also make sure that the mouse up occurs within the control in the event handler. Checking whether the mouse cursor coordinates are within the control's rectangle before you check the buttons will do it properly.

How to post JSON to a server using C#?

Some different and clean way to achieve this is by using HttpClient like this:

public async Task<HttpResponseMessage> PostResult(string url, ResultObject resultObject)
{
    using (var client = new HttpClient())
    {
        HttpResponseMessage response = new HttpResponseMessage();
        try
        {
            response = await client.PostAsJsonAsync(url, resultObject);
        }
        catch (Exception ex)
        {
            throw ex
        }
        return response;
     }
}

Rails: Address already in use - bind(2) (Errno::EADDRINUSE)

you can also try this trick:

ps aux | grep puma

sample output:

myname           77921   0.0  0.0  2433828   1972 s000  R+   11:17AM   0:00.00 grep puma
myname           67661   0.0  2.3  2680504 191204 s002  S+   11:00AM   0:18.38 puma 3.11.2 (tcp://localhost:3000) [my_proj]

then:

kill -9 67661

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

I had a similar use case where I wanted to test a Spring Boot configured repository in isolation (in my case without Spring Security autoconfiguration which was failing my test). @SpringApplicationConfiguration uses SpringApplicationContextLoader and that has a JavaDoc stating

Can be used to test non-web features (like a repository layer) or start an fully-configured embedded servlet container.

However, like yourself, I could not work out how you are meant to configure the test to only test the repository layer using the main configuration entry point i.e. using your approach of @SpringApplicationConfiguration(classes = Application.class).

My solution was to create a completely new application context exclusive for testing. So in src/test/java I have two files in a sub-package called repo

  1. RepoIntegrationTest.java
  2. TestRepoConfig.java

where RepoIntegrationTest.java has

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestRepoConfig.class)
public class RepoIntegrationTest {

and TestRepoConfig.java has

@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class TestRepoConfig {

It got me out of trouble but it would be really useful if anyone from the Spring Boot team could provide an alternative recommended solution

How to install PyQt4 on Windows using pip?

With current latest python 3.6.5

pip3 install PyQt5

works fine

What is a NullReferenceException, and how do I fix it?

If one is getting this message during saving or compiling the build, just close all the files and then open any file to compile and save.

For me the reason was that I had rename the file and old file was still open.

Batch: Remove file extension

Using cygwin bash to do the chopping

  :: e.g. FILE=basename.mp4 => FILE_NO_EXT=basename
  set FILE=%1
  for /f "delims=" %%a in ('bash -c "FILE=%FILE%; echo ${FILE/.*/}" ') do set FILE_NO_EXT=%%a

How do I create a multiline Python string with inline variables?

You can use Python 3.6's f-strings for variables inside multi-line or lengthy single-line strings. You can manually specify newline characters using \n.

Variables in a multi-line string

string1 = "go"
string2 = "now"
string3 = "great"

multiline_string = (f"I will {string1} there\n"
                    f"I will go {string2}.\n"
                    f"{string3}.")

print(multiline_string)

I will go there
I will go now
great

Variables in a lengthy single-line string

string1 = "go"
string2 = "now"
string3 = "great"

singleline_string = (f"I will {string1} there. "
                     f"I will go {string2}. "
                     f"{string3}.")

print(singleline_string)

I will go there. I will go now. great.


Alternatively, you can also create a multiline f-string with triple quotes.

multiline_string = f"""I will {string1} there.
I will go {string2}.
{string3}."""

Hibernate: How to set NULL query-parameter value with HQL?

For an actual HQL query:

FROM Users WHERE Name IS NULL

How to find indices of all occurrences of one string in another in JavaScript?

I would recommend Tim's answer. However, this comment by @blazs states "Suppose searchStr=aaa and that str=aaaaaa. Then instead of finding 4 occurences your code will find only 2 because you're making skips by searchStr.length in the loop.", which is true by looking at Tim's code, specifically this line here: startIndex = index + searchStrLen; Tim's code would not be able to find an instance of the string that's being searched that is within the length of itself. So, I've modified Tim's answer:

_x000D_
_x000D_
function getIndicesOf(searchStr, str, caseSensitive) {
    var startIndex = 0, index, indices = [];
    if (!caseSensitive) {
        str = str.toLowerCase();
        searchStr = searchStr.toLowerCase();
    }
    while ((index = str.indexOf(searchStr, startIndex)) > -1) {
        indices.push(index);
        startIndex = index + 1;
    }
    return indices;
}
var searchStr = prompt("Enter a string.");
var str = prompt("What do you want to search for in the string?");
var indices = getIndicesOf(str, searchStr);

document.getElementById("output").innerHTML = indices + "";
_x000D_
<div id="output"></div>
_x000D_
_x000D_
_x000D_

Changing it to + 1 instead of + searchStrLen will allow the index 1 to be in the indices array if I have an str of aaaaaa and a searchStr of aaa.

P.S. If anyone would like comments in the code to explain how the code works, please say so, and I'll be happy to respond to the request.

How to get anchor text/href on click using jQuery?

Edited to reflect update to question

$(document).ready(function() {
    $(".res a").click(function() {
        alert($(this).attr("href"));
    });
});

Handling ExecuteScalar() when no results are returned

Slight conjecture: if you check the stack for the exception, it is being thrown then the ADO.NET provider for Oracle is reading the underlying rowset to get the first value.

If there is no row, then there is no value to find.

To handle this case execute for a reader and handle Next() returning false for the case of no match.

Replace line break characters with <br /> in ASP.NET MVC Razor view

Use the CSS white-space property instead of opening yourself up to XSS vulnerabilities!

<span style="white-space: pre-line">@Model.CommentText</span>

What is ":-!!" in C code?

It's creating a size 0 bitfield if the condition is false, but a size -1 (-!!1) bitfield if the condition is true/non-zero. In the former case, there is no error and the struct is initialized with an int member. In the latter case, there is a compile error (and no such thing as a size -1 bitfield is created, of course).

Permutations in JavaScript?

This is a very nice use-case for map/reduce:

function permutations(arr) {
    return (arr.length === 1) ? arr :
    arr.reduce((acc, cv, index) => {
        let remaining = [...arr];
        remaining.splice(index, 1);
        return acc.concat(permutations(remaining).map(a => [].concat(cv,a)));
    }, []);
}
  • First, we handle the base case and simply return the array if there is only on item in it
  • In all other cases
    • we create an empty array
    • loop over the input-array
    • and add an array of the current value and all permutations of the remaining array [].concat(cv,a)

What is the maximum length of a URL in different browsers?

Why is the Internet Explorer limit only 2K while IIS has a limit of 16K? I don't think it makes sense.

So I want to start an experiment about Ajax request URL size limits.

I have set my Tomcat HTTP connector's maxHttpHeaderSize="1048576". And prepared a very long URL.

Then I send a request with the long URL like the following:

var url="/ajax/url-length.jsp";
jQuery.ajax(url,{data:{q:"0".repeat(1048000-url.length-4)}});

jQuery reports done. Tomcat reports the URL requested is 1048015 bytes. It was tested with Chrome 50 and Internet Explorer 11.

So web browsers won't truncate or limit your URL intentionally when sending Ajax requests.

Format string to a 3 digit number

If you're just formatting a number, you can just provide the proper custom numeric format to make it a 3 digit string directly:

myString = 3.ToString("000");

Or, alternatively, use the standard D format string:

myString = 3.ToString("D3");

PowerShell: Create Local User Account

Another alternative is the old school NET USER commands:

NET USER username "password" /ADD

OK - you can't set all the options but it's a lot less convoluted for simple user creation & easy to script up in Powershell.

NET LOCALGROUP "group" "user" /add to set group membership.

Truncate Decimal number not Round Off

Try this:

decimal original = GetSomeDecimal(); // 22222.22939393
int number1 = (int)original; // contains only integer value of origina number
decimal temporary = original - number1; // contains only decimal value of original number
int decimalPlaces = GetDecimalPlaces(); // 3
temporary *= (Math.Pow(10, decimalPlaces)); // moves some decimal places to integer
temporary = (int)temporary; // removes all decimal places
temporary /= (Math.Pow(10, decimalPlaces)); // moves integer back to decimal places
decimal result = original + temporary; // add integer and decimal places together

It can be writen shorter, but this is more descriptive.

EDIT: Short way:

decimal original = GetSomeDecimal(); // 22222.22939393
int decimalPlaces = GetDecimalPlaces(); // 3
decimal result = ((int)original) + (((int)(original * Math.Pow(10, decimalPlaces)) / (Math.Pow(10, decimalPlaces));

What is correct media query for IPad Pro?

For those who want to target an iPad Pro 11" the device-width is 834px, device-height is 1194px and the device-pixel-ratio is 2. Source: screen.width, screen.height and devicePixelRatio reported by Safari on iOS Simulator.

Exact media query for portrait: (device-height: 1194px) and (device-width: 834px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)

Using CSS to affect div style inside iframe

The quick answer is: No, sorry.

It's not possible using just CSS. You basically need to have control over the iframe content in order to style it. There are methods using javascript or your web language of choice (which I've read a little about, but am not to familiar with myself) to insert some needed styles dynamically, but you would need direct control over the iframe content, which it sounds like you do not have.

Find Number of CPUs and Cores per CPU using Command Prompt

You can use the environment variable NUMBER_OF_PROCESSORS for the total number of processors:

echo %NUMBER_OF_PROCESSORS%

What does "wrong number of arguments (1 for 0)" mean in Ruby?

If you change from using a lambda with one argument to a function with one argument, you will get this error.

For example:

You had:

foobar = lambda do |baz|
  puts baz
end

and you changed the definition to

def foobar(baz)
  puts baz
end

And you left your invocation as:

foobar.call(baz)

And then you got the message

ArgumentError: wrong number of arguments (0 for 1)

when you really meant:

foobar(baz)

How can I force division to be floating point? Division keeps rounding down to 0?

In Python 2, division of two ints produces an int. In Python 3, it produces a float. We can get the new behaviour by importing from __future__.

>>> from __future__ import division
>>> a = 4
>>> b = 6
>>> c = a / b
>>> c
0.66666666666666663

The most efficient way to implement an integer based power function pow(int, int)

In addition to the answer by Elias, which causes Undefined Behaviour when implemented with signed integers, and incorrect values for high input when implemented with unsigned integers,

here is a modified version of the Exponentiation by Squaring that also works with signed integer types, and doesn't give incorrect values:

#include <stdint.h>

#define SQRT_INT64_MAX (INT64_C(0xB504F333))

int64_t alx_pow_s64 (int64_t base, uint8_t exp)
{
    int_fast64_t    base_;
    int_fast64_t    result;

    base_   = base;

    if (base_ == 1)
        return  1;
    if (!exp)
        return  1;
    if (!base_)
        return  0;

    result  = 1;
    if (exp & 1)
        result *= base_;
    exp >>= 1;
    while (exp) {
        if (base_ > SQRT_INT64_MAX)
            return  0;
        base_ *= base_;
        if (exp & 1)
            result *= base_;
        exp >>= 1;
    }

    return  result;
}

Considerations for this function:

(1 ** N) == 1
(N ** 0) == 1
(0 ** 0) == 1
(0 ** N) == 0

If any overflow or wrapping is going to take place, return 0;

I used int64_t, but any width (signed or unsigned) can be used with little modification. However, if you need to use a non-fixed-width integer type, you will need to change SQRT_INT64_MAX by (int)sqrt(INT_MAX) (in the case of using int) or something similar, which should be optimized, but it is uglier, and not a C constant expression. Also casting the result of sqrt() to an int is not very good because of floating point precission in case of a perfect square, but as I don't know of any implementation where INT_MAX -or the maximum of any type- is a perfect square, you can live with that.

Organizing a multiple-file Go project

Keep the files in the same directory and use package main in all files.

myproj/
   your-program/
      main.go
      lib.go

Then run:

~/myproj/your-program$ go build && ./your-program

How to copy a file along with directory structure/path using python?

To create all intermediate-level destination directories you could use os.makedirs() before copying:

import os
import shutil

srcfile = 'a/long/long/path/to/file.py'
dstroot = '/home/myhome/new_folder'


assert not os.path.isabs(srcfile)
dstdir =  os.path.join(dstroot, os.path.dirname(srcfile))

os.makedirs(dstdir) # create all directories, raise an error if it already exists
shutil.copy(srcfile, dstdir)

How can I add a key/value pair to a JavaScript object?

supported by most of browsers, and it checks if object key available or not you want to add, if available it overides existing key value and it not available it add key with value

example 1

let my_object = {};

// now i want to add something in it  

my_object.red = "this is red color";

// { red : "this is red color"}

example 2

let my_object = { inside_object : { car : "maruti" }}

// now i want to add something inside object of my object 

my_object.inside_object.plane = "JetKing";

// { inside_object : { car : "maruti" , plane : "JetKing"} }

example 3

let my_object = { inside_object : { name : "abhishek" }}

// now i want to add something inside object with new keys birth , gender 

my_object.inside_object.birth = "8 Aug";
my_object.inside_object.gender = "Male";


    // { inside_object : 
//             { name : "abhishek",
//               birth : "8 Aug",
//               gender : "Male" 
//            }   
//       }

Check if a row exists, otherwise insert

Pass updlock, rowlock, holdlock hints when testing for existence of the row.

begin tran /* default read committed isolation level is fine */

if not exists (select * from Table with (updlock, rowlock, holdlock) where ...)
    /* insert */
else
    /* update */

commit /* locks are released here */

The updlock hint forces the query to take an update lock on the row if it already exists, preventing other transactions from modifying it until you commit or roll back.

The holdlock hint forces the query to take a range lock, preventing other transactions from adding a row matching your filter criteria until you commit or roll back.

The rowlock hint forces lock granularity to row level instead of the default page level, so your transaction won't block other transactions trying to update unrelated rows in the same page (but be aware of the trade-off between reduced contention and the increase in locking overhead - you should avoid taking large numbers of row-level locks in a single transaction).

See http://msdn.microsoft.com/en-us/library/ms187373.aspx for more information.

Note that locks are taken as the statements which take them are executed - invoking begin tran doesn't give you immunity against another transaction pinching locks on something before you get to it. You should try and factor your SQL to hold locks for the shortest possible time by committing the transaction as soon as possible (acquire late, release early).

Note that row-level locks may be less effective if your PK is a bigint, as the internal hashing on SQL Server is degenerate for 64-bit values (different key values may hash to the same lock id).

How to print an unsigned char in C?

Declare your ch as

unsigned char ch = 212 ;

And your printf will work.

SQL Query - Using Order By in UNION

Here's an example from Northwind 2007:

SELECT [Product ID], [Order Date], [Company Name], [Transaction], [Quantity]
FROM [Product Orders]
UNION SELECT [Product ID], [Creation Date], [Company Name], [Transaction], [Quantity]
FROM [Product Purchases]
ORDER BY [Order Date] DESC;

The ORDER BY clause just needs to be the last statement, after you've done all your unioning. You can union several sets together, then put an ORDER BY clause after the last set.

milliseconds to time in javascript

Not to reinvent the wheel, here is my favourite one-liner solution:

_x000D_
_x000D_
/**_x000D_
 * Convert milliseconds to time string (hh:mm:ss:mss)._x000D_
 *_x000D_
 * @param Number ms_x000D_
 *_x000D_
 * @return String_x000D_
 */_x000D_
function time(ms) {_x000D_
    return new Date(ms).toISOString().slice(11, -1);_x000D_
}_x000D_
_x000D_
console.log( time(12345 * 1000) );  // "03:25:45.000"
_x000D_
_x000D_
_x000D_

Method Date.prototype.toISOString() returns a string in simplified extended ISO format (ISO 8601), which is always 24 characters long: YYYY-MM-DDTHH:mm:ss.sssZ. This method is supported in all modern browsers (IE9+) and JavaScript engines.


UPDATE: The solution above is always limited to range of one day, which is fine if you use it to format milliseconds up to 24 hours (i.e. ms < 86400000). To make it working with any input value, I have extended it into a nice universal prototype method:

_x000D_
_x000D_
/**_x000D_
 * Convert (milli)seconds to time string (hh:mm:ss[:mss])._x000D_
 *_x000D_
 * @param Boolean isSec_x000D_
 *_x000D_
 * @return String_x000D_
 */_x000D_
Number.prototype.toTime = function(isSec) {_x000D_
    var ms = isSec ? this * 1e3 : this,_x000D_
        lm = ~(4 * !!isSec),  /* limit fraction */_x000D_
        fmt = new Date(ms).toISOString().slice(11, lm);_x000D_
_x000D_
    if (ms >= 8.64e7) {  /* >= 24 hours */_x000D_
        var parts = fmt.split(/:(?=\d{2}:)/);_x000D_
        parts[0] -= -24 * (ms / 8.64e7 | 0);_x000D_
        return parts.join(':');_x000D_
    }_x000D_
_x000D_
    return fmt;_x000D_
};_x000D_
_x000D_
console.log( (12345 * 1000).toTime()     );  // "03:25:45.000"_x000D_
console.log( (123456 * 789).toTime()     );  // "27:03:26.784"_x000D_
console.log(  12345.       .toTime(true) );  // "03:25:45"_x000D_
console.log(  123456789.   .toTime(true) );  // "34293:33:09"
_x000D_
_x000D_
_x000D_

Server did not recognize the value of HTTP Header SOAPAction

I had same problem, it fixed after some checking:

<< Target WebService Exists but called method's not eXXXists. >>

my local service contain methods but target server(connecting server) does not contain specified called method.

Check your program scenario again...

Bootstrap control with multiple "data-toggle"

I use href to load the modal and leave data-toggle for the tooltip:

<a 
    data-toggle="tooltip"
    data-placement="top"
    title="My Tooltip text!"
    href="javascript:$('#id').modal('show');"
>
+
</a>

HTML Table width in percentage, table rows separated equally

you can try this, I would do it with CSS, but i think you want it with tables without CSS.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
   <body leftmargin=0 rightmargin=0>
      <table cellpadding="0" cellspacing="0" width="100%" border="1" height="350px"> 
         <tr>
            <td width="25%">&nbsp;</td>
            <td width="25%">&nbsp;</td>
            <td width="25%">&nbsp;</td>
            <td width="25%">&nbsp;</td>
         </tr>
      </table> 
   </body>
</html>

Cast to generic type in C#

I struggled to solve a similar problem around data table classes instead of messages. The root issue mentioned above of casting a non-generic version of the class to a derived generic version was the same.

In order to allow injection into a portable class library which did not support database libraries, I introduced a set of interface classes, with the intent that I could pass a type and get a matching generic. It ended up needing to implement a generic method.

// Interface for injection
public interface IDatabase
{
    // Original, non-functional signature:
    IDatatable<object> GetDataTable(Type dataType);

    // Functional method using a generic method:
    IDatatable<T> GetDataTable<T>();
}

And this the whole implementation using the generic method above.

The generic class that will be cast from a dictionary.

// Non-generic base class allows listing tables together
abstract class Datatable
{
    Datatable(Type storedClass)
    {
      StoredClass = storedClass;
    }

    Type StoredClass { get; private set; }
}

// Generic inheriting class
abstract class Datatable<T>: Datatable, IDatatable<T>
{
    protected Datatable()
        :base(typeof(T))
    {
    }
}

This is the class that stores the generic class and casts it to satisfy the generic method in the interface

class Database
{
    // Dictionary storing the classes using the non-generic base class
    private Dictionary<Type, Datatable> _tableDictionary;

    protected Database(List<Datatable> tables)
    {
        _tableDictionary = new Dictionary<Type, Datatable>();
        foreach (var table in tables)
        {
            _tableDictionary.Add(table.StoredClass, table);
        }
    }

    // Interface implementation, casts the generic
    public IDatatable<T> GetDataTable<T>()
    {
        Datatable table = null;

        _tableDictionary.TryGetValue(typeof(T), out table);

        return table as IDatatable<T>;
    }
}

And finally the calling of the interface method.

IDatatable<CustomerAccount> table = _database.GetDataTable<CustomerAccount>();

What are the differences between git remote prune, git prune, git fetch --prune, etc

Note that one difference between git remote --prune and git fetch --prune is being fixed, with commit 10a6cc8, by Tom Miller (tmiller) (for git 1.9/2.0, Q1 2014):

When we have a remote-tracking branch named "frotz/nitfol" from a previous fetch, and the upstream now has a branch named "**frotz"**, fetch would fail to remove "frotz/nitfol" with a "git fetch --prune" from the upstream.
git would inform the user to use "git remote prune" to fix the problem.

So: when a upstream repo has a branch ("frotz") with the same name as a branch hierarchy ("frotz/xxx", a possible branch naming convention), git remote --prune was succeeding (in cleaning up the remote tracking branch from your repo), but git fetch --prune was failing.

Not anymore:

Change the way "fetch --prune" works by moving the pruning operation before the fetching operation.
This way, instead of warning the user of a conflict, it automatically fixes it.

How to set timer in android?

ok since this isn't cleared up yet there are 3 simple ways to handle this. Below is an example showing all 3 and at the bottom is an example showing just the method I believe is preferable. Also remember to clean up your tasks in onPause, saving state if necessary.


import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Handler.Callback;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class main extends Activity {
    TextView text, text2, text3;
    long starttime = 0;
    //this  posts a message to the main thread from our timertask
    //and updates the textfield
   final Handler h = new Handler(new Callback() {

        @Override
        public boolean handleMessage(Message msg) {
           long millis = System.currentTimeMillis() - starttime;
           int seconds = (int) (millis / 1000);
           int minutes = seconds / 60;
           seconds     = seconds % 60;

           text.setText(String.format("%d:%02d", minutes, seconds));
            return false;
        }
    });
   //runs without timer be reposting self
   Handler h2 = new Handler();
   Runnable run = new Runnable() {

        @Override
        public void run() {
           long millis = System.currentTimeMillis() - starttime;
           int seconds = (int) (millis / 1000);
           int minutes = seconds / 60;
           seconds     = seconds % 60;

           text3.setText(String.format("%d:%02d", minutes, seconds));

           h2.postDelayed(this, 500);
        }
    };

   //tells handler to send a message
   class firstTask extends TimerTask {

        @Override
        public void run() {
            h.sendEmptyMessage(0);
        }
   };

   //tells activity to run on ui thread
   class secondTask extends TimerTask {

        @Override
        public void run() {
            main.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                   long millis = System.currentTimeMillis() - starttime;
                   int seconds = (int) (millis / 1000);
                   int minutes = seconds / 60;
                   seconds     = seconds % 60;

                   text2.setText(String.format("%d:%02d", minutes, seconds));
                }
            });
        }
   };


   Timer timer = new Timer();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        text = (TextView)findViewById(R.id.text);
        text2 = (TextView)findViewById(R.id.text2);
        text3 = (TextView)findViewById(R.id.text3);

        Button b = (Button)findViewById(R.id.button);
        b.setText("start");
        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Button b = (Button)v;
                if(b.getText().equals("stop")){
                    timer.cancel();
                    timer.purge();
                    h2.removeCallbacks(run);
                    b.setText("start");
                }else{
                    starttime = System.currentTimeMillis();
                    timer = new Timer();
                    timer.schedule(new firstTask(), 0,500);
                    timer.schedule(new secondTask(),  0,500);
                    h2.postDelayed(run, 0);
                    b.setText("stop");
                }
            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
        timer.cancel();
        timer.purge();
        h2.removeCallbacks(run);
        Button b = (Button)findViewById(R.id.button);
        b.setText("start");
    }
}


the main thing to remember is that the UI can only be modified from the main ui thread so use a handler or activity.runOnUIThread(Runnable r);

Here is what I consider to be the preferred method.


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class TestActivity extends Activity {

    TextView timerTextView;
    long startTime = 0;

    //runs without a timer by reposting this handler at the end of the runnable
    Handler timerHandler = new Handler();
    Runnable timerRunnable = new Runnable() {

        @Override
        public void run() {
            long millis = System.currentTimeMillis() - startTime;
            int seconds = (int) (millis / 1000);
            int minutes = seconds / 60;
            seconds = seconds % 60;

            timerTextView.setText(String.format("%d:%02d", minutes, seconds));

            timerHandler.postDelayed(this, 500);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_activity);

        timerTextView = (TextView) findViewById(R.id.timerTextView);

        Button b = (Button) findViewById(R.id.button);
        b.setText("start");
        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Button b = (Button) v;
                if (b.getText().equals("stop")) {
                    timerHandler.removeCallbacks(timerRunnable);
                    b.setText("start");
                } else {
                    startTime = System.currentTimeMillis();
                    timerHandler.postDelayed(timerRunnable, 0);
                    b.setText("stop");
                }
            }
        });
    }

  @Override
    public void onPause() {
        super.onPause();
        timerHandler.removeCallbacks(timerRunnable);
        Button b = (Button)findViewById(R.id.button);
        b.setText("start");
    }

}


What is the difference between a "line feed" and a "carriage return"?

A line feed means moving one line forward. The code is \n.
A carriage return means moving the cursor to the beginning of the line. The code is \r.

Windows editors often still use the combination of both as \r\n in text files. Unix uses mostly only the \n.

The separation comes from typewriter times, when you turned the wheel to move the paper to change the line and moved the carriage to restart typing on the beginning of a line. This was two steps.

How to get on scroll events?

// @HostListener('scroll', ['$event']) // for scroll events of the current element
@HostListener('window:scroll', ['$event']) // for window scroll events
onScroll(event) {
  ...
}

or

<div (scroll)="onScroll($event)"></div>

Hex colors: Numeric representation for "transparent"?

Transparency is a property outside the color itself, also known as alpha component. You can't code it as RGB.

If you want a transparent background, you can do this:

background: transparent;

Additionally, I don't know if it might be helpful or not but, you could set the opacity property:

.half{
  opacity: 0.5;
  filter: alpha(opacity=50);
}

You need both in order to get it working in IE and all other decent browsers.

what are the .map files used for in Bootstrap 3.x?

These are source maps. Provide these alongside compressed source files; developer tools such as those in Firefox and Chrome will use them to allow debugging as if the code was not compressed.

Why does "return list.sort()" return None, not the list?

To understand why it does not return the list:

sort() doesn't return any value while the sort() method just sorts the elements of a given list in a specific order - ascending or descending without returning any value.

So problem is with answer = newList.sort() where answer is none.

Instead you can just do return newList.sort().

The syntax of the sort() method is:

list.sort(key=..., reverse=...)

Alternatively, you can also use Python's in-built function sorted() for the same purpose.

sorted(list, key=..., reverse=...)

Note: The simplest difference between sort() and sorted() is: sort() doesn't return any value while, sorted() returns an iterable list.

So in your case answer = sorted(newList).

Request redirect to /Account/Login?ReturnUrl=%2f since MVC 3 install on server

It's resolved the IIS request auto redirect to default page(default.aspx or login page)

By adding the following lines to the AppSettings section of my web.config file:

<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>

Selecting one row from MySQL using mysql_* API

What you should get as output with this code is:

Array ()

... this is exactly how you get just one row, you don't need a while loop. Are you sure you're printing the right variable?

Browse for a directory in C#

Note: there is no guarantee this code will work in future versions of the .Net framework. Using private .Net framework internals as done here through reflection is probably not good overall. Use the interop solution mentioned at the bottom, as the Windows API is less likely to change.

If you are looking for a Folder picker that looks more like the Windows 7 dialog, with the ability to copy and paste from a textbox at the bottom and the navigation pane on the left with favorites and common locations, then you can get access to that in a very lightweight way.

The FolderBrowserDialog UI is very minimal:

enter image description here

But you can have this instead:

enter image description here

Here's a class that opens a Vista-style folder picker using the .Net private IFileDialog interface, without directly using interop in the code (.Net takes care of that for you). It falls back to the pre-Vista dialog if not in a high enough Windows version. Should work in Windows 7, 8, 9, 10 and higher (theoretically).

using System;
using System.Reflection;
using System.Windows.Forms;

namespace MyCoolCompany.Shuriken {
    /// <summary>
    /// Present the Windows Vista-style open file dialog to select a folder. Fall back for older Windows Versions
    /// </summary>
    public class FolderSelectDialog {
        private string _initialDirectory;
        private string _title;
        private string _fileName = "";

        public string InitialDirectory {
            get { return string.IsNullOrEmpty(_initialDirectory) ? Environment.CurrentDirectory : _initialDirectory; }
            set { _initialDirectory = value; }
        }
        public string Title {
            get { return _title ?? "Select a folder"; }
            set { _title = value; }
        }
        public string FileName { get { return _fileName; } }

        public bool Show() { return Show(IntPtr.Zero); }

        /// <param name="hWndOwner">Handle of the control or window to be the parent of the file dialog</param>
        /// <returns>true if the user clicks OK</returns>
        public bool Show(IntPtr hWndOwner) {
            var result = Environment.OSVersion.Version.Major >= 6
                ? VistaDialog.Show(hWndOwner, InitialDirectory, Title)
                : ShowXpDialog(hWndOwner, InitialDirectory, Title);
            _fileName = result.FileName;
            return result.Result;
        }

        private struct ShowDialogResult {
            public bool Result { get; set; }
            public string FileName { get; set; }
        }

        private static ShowDialogResult ShowXpDialog(IntPtr ownerHandle, string initialDirectory, string title) {
            var folderBrowserDialog = new FolderBrowserDialog {
                Description = title,
                SelectedPath = initialDirectory,
                ShowNewFolderButton = false
            };
            var dialogResult = new ShowDialogResult();
            if (folderBrowserDialog.ShowDialog(new WindowWrapper(ownerHandle)) == DialogResult.OK) {
                dialogResult.Result = true;
                dialogResult.FileName = folderBrowserDialog.SelectedPath;
            }
            return dialogResult;
        }

        private static class VistaDialog {
            private const string c_foldersFilter = "Folders|\n";

            private const BindingFlags c_flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
            private readonly static Assembly s_windowsFormsAssembly = typeof(FileDialog).Assembly;
            private readonly static Type s_iFileDialogType = s_windowsFormsAssembly.GetType("System.Windows.Forms.FileDialogNative+IFileDialog");
            private readonly static MethodInfo s_createVistaDialogMethodInfo = typeof(OpenFileDialog).GetMethod("CreateVistaDialog", c_flags);
            private readonly static MethodInfo s_onBeforeVistaDialogMethodInfo = typeof(OpenFileDialog).GetMethod("OnBeforeVistaDialog", c_flags);
            private readonly static MethodInfo s_getOptionsMethodInfo = typeof(FileDialog).GetMethod("GetOptions", c_flags);
            private readonly static MethodInfo s_setOptionsMethodInfo = s_iFileDialogType.GetMethod("SetOptions", c_flags);
            private readonly static uint s_fosPickFoldersBitFlag = (uint) s_windowsFormsAssembly
                .GetType("System.Windows.Forms.FileDialogNative+FOS")
                .GetField("FOS_PICKFOLDERS")
                .GetValue(null);
            private readonly static ConstructorInfo s_vistaDialogEventsConstructorInfo = s_windowsFormsAssembly
                .GetType("System.Windows.Forms.FileDialog+VistaDialogEvents")
                .GetConstructor(c_flags, null, new[] { typeof(FileDialog) }, null);
            private readonly static MethodInfo s_adviseMethodInfo = s_iFileDialogType.GetMethod("Advise");
            private readonly static MethodInfo s_unAdviseMethodInfo = s_iFileDialogType.GetMethod("Unadvise");
            private readonly static MethodInfo s_showMethodInfo = s_iFileDialogType.GetMethod("Show");

            public static ShowDialogResult Show(IntPtr ownerHandle, string initialDirectory, string title) {
                var openFileDialog = new OpenFileDialog {
                    AddExtension = false,
                    CheckFileExists = false,
                    DereferenceLinks = true,
                    Filter = c_foldersFilter,
                    InitialDirectory = initialDirectory,
                    Multiselect = false,
                    Title = title
                };

                var iFileDialog = s_createVistaDialogMethodInfo.Invoke(openFileDialog, new object[] { });
                s_onBeforeVistaDialogMethodInfo.Invoke(openFileDialog, new[] { iFileDialog });
                s_setOptionsMethodInfo.Invoke(iFileDialog, new object[] { (uint) s_getOptionsMethodInfo.Invoke(openFileDialog, new object[] { }) | s_fosPickFoldersBitFlag });
                var adviseParametersWithOutputConnectionToken = new[] { s_vistaDialogEventsConstructorInfo.Invoke(new object[] { openFileDialog }), 0U };
                s_adviseMethodInfo.Invoke(iFileDialog, adviseParametersWithOutputConnectionToken);

                try {
                    int retVal = (int) s_showMethodInfo.Invoke(iFileDialog, new object[] { ownerHandle });
                    return new ShowDialogResult {
                        Result = retVal == 0,
                        FileName = openFileDialog.FileName
                    };
                }
                finally {
                    s_unAdviseMethodInfo.Invoke(iFileDialog, new[] { adviseParametersWithOutputConnectionToken[1] });
                }
            }
        }

        // Wrap an IWin32Window around an IntPtr
        private class WindowWrapper : IWin32Window {
            private readonly IntPtr _handle;
            public WindowWrapper(IntPtr handle) { _handle = handle; }
            public IntPtr Handle { get { return _handle; } }
        }
    }
}

I developed this as a cleaned up version of .NET Win 7-style folder select dialog by Bill Seddon of lyquidity.com (I have no affiliation). I wrote my own because his solution requires an additional Reflection class that isn't needed for this focused purpose, uses exception-based flow control, doesn't cache the results of its reflection calls. Note that the nested static VistaDialog class is so that its static reflection variables don't try to get populated if the Show method is never called.

It is used like so in a Windows Form:

var dialog = new FolderSelectDialog {
    InitialDirectory = musicFolderTextBox.Text,
    Title = "Select a folder to import music from"
};
if (dialog.Show(Handle)) {
    musicFolderTextBox.Text = dialog.FileName;
}

You can of course play around with its options and what properties it exposes. For example, it allows multiselect in the Vista-style dialog.

Also, please note that Simon Mourier gave an answer that shows how to do the exact same job using interop against the Windows API directly, though his version would have to be supplemented to use the older style dialog if in an older version of Windows. Unfortunately, I hadn't found his post yet when I worked up my solution. Name your poison!

Convert multidimensional array into single array

This simple code you can use

$array = array_column($array, 'value', 'key');

Return a `struct` from a function in C

There is no issue in passing back a struct. It will be passed by value

But, what if the struct contains any member which has a address of a local variable

struct emp {
    int id;
    char *name;
};

struct emp get() {
    char *name = "John";

    struct emp e1 = {100, name};

    return (e1);
}

int main() {

    struct emp e2 = get();

    printf("%s\n", e2.name);
}

Now, here e1.name contains a memory address local to the function get(). Once get() returns, the local address for name would have been freed up. SO, in the caller if we try to access that address, it may cause segmentation fault, as we are trying a freed address. That is bad..

Where as the e1.id will be perfectly valid as its value will be copied to e2.id

So, we should always try to avoid returning local memory addresses of a function.

Anything malloced can be returned as and when wanted

What is output buffering?

UPDATE 2019. If you have dedicated server and SSD or better NVM, 3.5GHZ. You shouldn't use buffering to make faster loaded website in 100ms-150ms.

Becouse network is slowly than proccesing script in the 2019 with performance servers (severs,memory,disk) and with turn on APC PHP :) To generated script sometimes need only 70ms another time is only network takes time, from 10ms up to 150ms from located user-server.

so if you want be fast 150ms, buffering make slowl, becouse need extra collection buffer data it make extra cost. 10 years ago when server make 1s script, it was usefull.

Please becareful output_buffering have limit if you would like using jpg to loading it can flush automate and crash sending.

Cheers.

You can make fast river or You can make safely tama :)

How to alert using jQuery

Don't do this, but this is how you would do it:

$(".overdue").each(function() { 
    alert("Your book is overdue"); 
});

The reason I say "don't do it" is because nothing is more annoying to users, in my opinion, than repeated pop-ups that cannot be stopped. Instead, just use the length property and let them know that "You have X books overdue".

jQuery.getJSON - Access-Control-Allow-Origin Issue

You may well want to use JSON-P instead (see below). First a quick explanation.

The header you've mentioned is from the Cross Origin Resource Sharing standard. Beware that it is not supported by some browsers people actually use, and on other browsers (Microsoft's, sigh) it requires using a special object (XDomainRequest) rather than the standard XMLHttpRequest that jQuery uses. It also requires that you change server-side resources to explicitly allow the other origin (www.xxxx.com).

To get the JSON data you're requesting, you basically have three options:

  1. If possible, you can be maximally-compatible by correcting the location of the files you're loading so they have the same origin as the document you're loading them into. (I assume you must be loading them via Ajax, hence the Same Origin Policy issue showing up.)

  2. Use JSON-P, which isn't subject to the SOP. jQuery has built-in support for it in its ajax call (just set dataType to "jsonp" and jQuery will do all the client-side work). This requires server side changes, but not very big ones; basically whatever you have that's generating the JSON response just looks for a query string parameter called "callback" and wraps the JSON in JavaScript code that would call that function. E.g., if your current JSON response is:

    {"weather": "Dreary start but soon brightening into a fine summer day."}
    

    Your script would look for the "callback" query string parameter (let's say that the parameter's value is "jsop123") and wraps that JSON in the syntax for a JavaScript function call:

    jsonp123({"weather": "Dreary start but soon brightening into a fine summer day."});
    

    That's it. JSON-P is very broadly compatible (because it works via JavaScript script tags). JSON-P is only for GET, though, not POST (again because it works via script tags).

  3. Use CORS (the mechanism related to the header you quoted). Details in the specification linked above, but basically:

    A. The browser will send your server a "preflight" message using the OPTIONS HTTP verb (method). It will contain the various headers it would send with the GET or POST as well as the headers "Origin", "Access-Control-Request-Method" (e.g., GET or POST), and "Access-Control-Request-Headers" (the headers it wants to send).

    B. Your PHP decides, based on that information, whether the request is okay and if so responds with the "Access-Control-Allow-Origin", "Access-Control-Allow-Methods", and "Access-Control-Allow-Headers" headers with the values it will allow. You don't send any body (page) with that response.

    C. The browser will look at your response and see whether it's allowed to send you the actual GET or POST. If so, it will send that request, again with the "Origin" and various "Access-Control-Request-xyz" headers.

    D. Your PHP examines those headers again to make sure they're still okay, and if so responds to the request.

    In pseudo-code (I haven't done much PHP, so I'm not trying to do PHP syntax here):

    // Find out what the request is asking for
    corsOrigin = get_request_header("Origin")
    corsMethod = get_request_header("Access-Control-Request-Method")
    corsHeaders = get_request_header("Access-Control-Request-Headers")
    if corsOrigin is null or "null" {
        // Requests from a `file://` path seem to come through without an
        // origin or with "null" (literally) as the origin.
        // In my case, for testing, I wanted to allow those and so I output
        // "*", but you may want to go another way.
        corsOrigin = "*"
    }
    
    // Decide whether to accept that request with those headers
    // If so:
    
    // Respond with headers saying what's allowed (here we're just echoing what they
    // asked for, except we may be using "*" [all] instead of the actual origin for
    // the "Access-Control-Allow-Origin" one)
    set_response_header("Access-Control-Allow-Origin", corsOrigin)
    set_response_header("Access-Control-Allow-Methods", corsMethod)
    set_response_header("Access-Control-Allow-Headers", corsHeaders)
    if the HTTP request method is "OPTIONS" {
        // Done, no body in response to OPTIONS
        stop
    }
    // Process the GET or POST here; output the body of the response
    

    Again stressing that this is pseudo-code.

force browsers to get latest js and css files in asp.net application

Interestingly, this very site has issues with the approach you describe in connection with some proxy setups, even though it should be fail-safe.

Check this Meta Stack Overflow discussion.

So in light of that, it might make sense not to use a GET parameter to update, but the actual file name:

href="/css/scriptname/versionNumber.css" 

even though this is more work to do, as you'll have to actually create the file, or build a URL rewrite for it.

HTML5 canvas ctx.fillText won't do line breaks?

Here is my function to draw multiple lines of text center in canvas (only break the line, don't break-word)

_x000D_
_x000D_
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

let text = "Hello World \n Hello World 2222 \n AAAAA \n thisisaveryveryveryveryveryverylongword. "
ctx.font = "20px Arial";

fillTextCenter(ctx, text, 0, 0, c.width, c.height)

function fillTextCenter(ctx, text, x, y, width, height) {
    ctx.textBaseline = 'middle';
    ctx.textAlign = "center";

    const lines = text.match(/[^\r\n]+/g);
    for(let i = 0; i < lines.length; i++) {
        let xL = (width - x) / 2
        let yL =  y + (height / (lines.length + 1)) * (i+1)

        ctx.fillText(lines[i], xL, yL)
    }
}
_x000D_
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #000;"></canvas>
_x000D_
_x000D_
_x000D_

If you want to fit text size to canvas, you can also check here

Why can't a text column have a default value in MySQL?

"Support for DEFAULT in TEXT/BLOB columns" is a feature request in the MySQL Bugtracker (Bug #21532).

I see I'm not the only one who would like to put a default value in a TEXT column. I think this feature should be supported in a later version of MySQL.

This can't be fixed in the version 5.0 of MySQL, because apparently it would cause incompatibility and dataloss if anyone tried to transfer a database back and forth between the (current) databases that don't support that feature and any databases that did support that feature.

How to add shortcut keys for java code in eclipse

I've been Eclipse-free for over a year now, but I believe Eclipse calls these "Templates". Look in your settings for them. You invoke a template by typing its abbreviation and pressing the normal code completion hotkey (ctrl+space by default) or using the Tab key. The standard eclipse shortcut for System.out.println() is "sysout", so "sysout" would do what you want.

Here's another stackoverflow question that has some more details about it: How to use the "sysout" snippet in Eclipse with selected text?

Fit image to table cell [Pure HTML]

Inline content leaves space at the bottom for characters that descend (j, y, q):

https://developer.mozilla.org/en-US/docs/Images,_Tables,_and_Mysterious_Gaps

There are a couple fixes:

Use display: block;

<img style="display:block;" width="100%" height="100%" src="http://dummyimage.com/68x68/000/fff" />

or use vertical-align: bottom;

<img style="vertical-align: bottom;" width="100%" height="100%" src="http://dummyimage.com/68x68/000/fff" />

Is "delete this" allowed in C++?

One of the reasons that C++ was designed was to make it easy to reuse code. In general, C++ should be written so that it works whether the class is instantiated on the heap, in an array, or on the stack. "Delete this" is a very bad coding practice because it will only work if a single instance is defined on the heap; and there had better not be another delete statement, which is typically used by most developers to clean up the heap. Doing this also assumes that no maintenance programmer in the future will cure a falsely perceived memory leak by adding a delete statement.

Even if you know in advance that your current plan is to only allocate a single instance on the heap, what if some happy-go-lucky developer comes along in the future and decides to create an instance on the stack? Or, what if he cuts and pastes certain portions of the class to a new class that he intends to use on the stack? When the code reaches "delete this" it will go off and delete it, but then when the object goes out of scope, it will call the destructor. The destructor will then try to delete it again and then you are hosed. In the past, doing something like this would screw up not only the program but the operating system and the computer would need to be rebooted. In any case, this is highly NOT recommended and should almost always be avoided. I would have to be desperate, seriously plastered, or really hate the company I worked for to write code that did this.

Android new Bottom Navigation bar or BottomNavigationView

This library, BottomNavigationViewEx, extends Google's BottomNavigationView. You can easily customise Google's library to have bottom navigation bar the way you want it to be. You can disable the shifting mode, change visibility of the icons and texts and so much more. Definitely try it out.

Padding or margin value in pixels as integer using jQuery

Compare outer and inner height/widths to get the total margin and padding:

var that = $("#myId");
alert(that.outerHeight(true) - that.innerHeight());

Jenkins: Is there any way to cleanup Jenkins workspace?

There is a way to cleanup workspace in Jenkins. You can clean up the workspace before build or after build.

First, install Workspace Cleanup Plugin.

To clean up the workspace before build: Under Build Environment, check the box that says Delete workspace before build starts.

To clean up the workspace after the build: Under the heading Post-build Actions select Delete workspace when build is done from the Add Post-build Actions drop down menu.

No connection could be made because the target machine actively refused it 127.0.0.1:3446

Check if any other program is using that port.

If an instance of the same program is still active, kill that process.

iPhone viewWillAppear not firing

I've run into this same problem. Just send a viewWillAppear message to your view controller before you add it as a subview. (There is one BOOL parameter which tells the view controller if it's being animated to appear or not.)

[myViewController viewWillAppear:NO];

Look at RootViewController.m in the Metronome example.

(I actually found Apple's example projects great. There's a LOT more than HelloWorld ;)

When and Why to use abstract classes/methods?

read the following article http://mycodelines.wordpress.com/2009/09/01/in-which-scenario-we-use-abstract-classes-and-interfaces/

Abstract Classes

–> When you have a requirement where your base class should provide default implementation of certain methods whereas other methods should be open to being overridden by child classes use abstract classes.

For e.g. again take the example of the Vehicle class above. If we want all classes deriving from Vehicle to implement the Drive() method in a fixed way whereas the other methods can be overridden by child classes. In such a scenario we implement the Vehicle class as an abstract class with an implementation of Drive while leave the other methods / properties as abstract so they could be overridden by child classes.

–> The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.

For example a class library may define an abstract class that is used as a parameter to many of its functions and require programmers using that library to provide their own implementation of the class by creating a derived class.

Use an abstract class

When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning. This is the practice used by the Microsoft team which developed the Base Class Library. ( COM was designed around interfaces.) Use an abstract class to define a common base class for a family of types. Use an abstract class to provide default behavior. Subclass only a base class in a hierarchy to which the class logically belongs.

while EOF in JAVA?

Each call to nextLine() moves onto the next line, so when you are actually at the last readable line and the while check passes inspection, the next call to nextLine() will return EOF.


Perhaps you could do one of the following instead:

If fileReader is of type Scanner:

while ((line = fileReader.hasNextLine()) != null) {
    String line = fileReader.nextLine(); 
    System.out.println(line);
}

If fileReader is of type BufferedReader:

String line;
while ((line = fileReader.readLine()) != null) {
    System.out.println(line);
}

So you're reading the current line in the while condition and saving the line in a string for later use.

Private vs Protected - Visibility Good-Practice Concern

No, you're not on the right track. A good rule of thumb is: make everything as private as possible. This makes your class more encapsulated, and allows for changing the internals of the class without affecting the code using your class.

If you design your class to be inheritable, then carefully choose what may be overridden and accessible from subclasses, and make that protected (and final, talking of Java, if you want to make it accessible but not overridable). But be aware that, as soon as you accept to have subclasses of your class, and there is a protected field or method, this field or method is part of the public API of the class, and may not be changed later without breaking subclasses.

A class that is not intended to be inherited should be made final (in Java). You might relax some access rules (private to protected, final to non-final) for the sake of unit-testing, but then document it, and make it clear that although the method is protected, it's not supposed to be overridden.

Python Pandas replicate rows in dataframe

Appending and concatenating is usually slow in Pandas so I recommend just making a new list of the rows and turning that into a dataframe (unless appending a single row or concatenating a few dataframes).

import pandas as pd

df = pd.DataFrame([
[1,1,'2010-02-05',24924.5,False],
[1,1,'2010-02-12',46039.49,True],
[1,1,'2010-02-19',41595.55,False],
[1,1,'2010-02-26',19403.54,False],
[1,1,'2010-03-05',21827.9,False],
[1,1,'2010-03-12',21043.39,False],
[1,1,'2010-03-19',22136.64,False],
[1,1,'2010-03-26',26229.21,False],
[1,1,'2010-04-02',57258.43,False]
], columns=['Store','Dept','Date','Weekly_Sales','IsHoliday'])

temp_df = []
for row in df.itertuples(index=False):
    if row.IsHoliday:
        temp_df.extend([list(row)]*5)
    else:
        temp_df.append(list(row))

df = pd.DataFrame(temp_df, columns=df.columns)

@ViewChild in *ngIf

In my case I needed to load a whole module only when the div existed in the template, meaning the outlet was inside an ngif. This way everytime angular detected the element #geolocalisationOutlet it created the component inside of it. The module only loads once as well.

constructor(
    public wlService: WhitelabelService,
    public lmService: LeftMenuService,
    private loader: NgModuleFactoryLoader,
    private injector: Injector
) {
}

@ViewChild('geolocalisationOutlet', {read: ViewContainerRef}) set geolocalisation(geolocalisationOutlet: ViewContainerRef) {
    const path = 'src/app/components/engine/sections/geolocalisation/geolocalisation.module#GeolocalisationModule';
    this.loader.load(path).then((moduleFactory: NgModuleFactory<any>) => {
        const moduleRef = moduleFactory.create(this.injector);
        const compFactory = moduleRef.componentFactoryResolver
            .resolveComponentFactory(GeolocalisationComponent);
        if (geolocalisationOutlet && geolocalisationOutlet.length === 0) {
            geolocalisationOutlet.createComponent(compFactory);
        }
    });
}

<div *ngIf="section === 'geolocalisation'" id="geolocalisation">
     <div #geolocalisationOutlet></div>
</div>

Visual Studio 2012 Web Publish doesn't copy files

To take this a bit further. You have two files that are created when you create a publish profile.

  • NewProfile.pubxml
  • NewProfile.pubxml.user

When you open a project that has these files in the PublishProfile folder from a source control it only has the .pubxml file and not the .publxml.user file, so it creates the .publxml.user file on the fly when you open the project. When it creates the new .publxml.user on the fly the xml looks like:

<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
</Project>

When you create a new profile it creates xml that looks like:

<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
    <LastUsedPlatform>Any CPU</LastUsedPlatform>
    <TimeStampOfAssociatedLegacyPublishXmlFile />
    <EncryptedPassword />
  </PropertyGroup>
</Project>

If you take the <PropertyGroup> node and put it in the .pubxml.user file your PublishProfiles will start working again.

How to create a sub array from another array in Java?

Arrays.copyOfRange(..) was added in Java 1.6. So perhaps you don't have the latest version. If it's not possible to upgrade, look at System.arraycopy(..)

Loop Through All Subfolders Using VBA

Just a simple folder drill down.

sub sample()
    Dim FileSystem As Object
    Dim HostFolder As String

    HostFolder = "C:\"

    Set FileSystem = CreateObject("Scripting.FileSystemObject")
    DoFolder FileSystem.GetFolder(HostFolder)
end  sub

Sub DoFolder(Folder)
    Dim SubFolder
    For Each SubFolder In Folder.SubFolders
        DoFolder SubFolder
    Next
    Dim File
    For Each File In Folder.Files
        ' Operate on each file
    Next
End Sub

How can I encode a string to Base64 in Swift?

After all struggle I did like this.

func conversion(str:NSString)
{

    if let decodedData = NSData(base64EncodedString: str as String, options:NSDataBase64DecodingOptions(rawValue: 0)),
        let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding) {

        print(decodedString)//Here we are getting decoded string

After I am calling another function for converting decoded string to dictionary

        self .convertStringToDictionary(decodedString as String)
    }


}//function close

//for string to dictionary

func convertStringToDictionary(text: String) -> [String:AnyObject]? {
    if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]

            print(json)
            if let stack = json!["cid"]  //getting key value here
            {
                customerID = stack as! String
                print(customerID)
            }

        } catch let error as NSError {
            print(error)
        }
    }
    return nil
}

How to generate UL Li list from string array using jquery?

It's possible without jQuery too! :)

_x000D_
_x000D_
let countries = ['United States', 'Canada', 'Argentina', 'Armenia', 'Aruba'];_x000D_
_x000D_
// The <ul> that we will add <li> elements to:_x000D_
let myList = document.querySelector('ul.mylist');_x000D_
_x000D_
// Loop over the Array of country names:_x000D_
countries.forEach(function(value, index, array) {_x000D_
  // Create an <li> element:_x000D_
  let li = document.createElement('li');_x000D_
_x000D_
  // Give it the desired classes & attributes:_x000D_
  li.classList.add('ui-menu-item');_x000D_
  li.setAttribute('role', 'menuitem');_x000D_
_x000D_
  // Now create an <a> element:_x000D_
  let a = document.createElement('a');_x000D_
_x000D_
  // Give it the desired classes & attributes:_x000D_
  a.classList.add('ui-all');_x000D_
  a.tabIndex = -1;_x000D_
  a.innerText = value; //  <--- the country name from our Array_x000D_
  a.href = "#"_x000D_
_x000D_
  // Now add the <a> to the <li>, and add the <li> to the <ul>_x000D_
  li.appendChild(a);_x000D_
  myList.appendChild(li);_x000D_
});
_x000D_
<ul class="mylist"></ul>
_x000D_
_x000D_
_x000D_

Detect enter press in JTextField

JTextField function=new JTextField(8);   
function.addActionListener(new ActionListener(){

                public void actionPerformed(ActionEvent e){

                        //statements!!!

                }});

all you need to do is addActionListener to the JTextField like above! After you press Enter the action will performed what you want at the statement!

Java generics - get class?

I'm able to get the Class of the generic type this way:

class MyList<T> {
  Class<T> clazz = (Class<T>) DAOUtil.getTypeArguments(MyList.class, this.getClass()).get(0);
}

You need two functions from this file: http://code.google.com/p/hibernate-generic-dao/source/browse/trunk/dao/src/main/java/com/googlecode/genericdao/dao/DAOUtil.java

For more explanation: http://www.artima.com/weblogs/viewpost.jsp?thread=208860

No Access-Control-Allow-Origin header is present on the requested resource

You are missing 'json' dataType in the $.post() method:

$.post('http://www.example.com:PORT_NUMBER/MYSERVLET',{MyParam: 'value'})
        .done(function(data){
                  alert(data);
         }, "json");
         //-^^^^^^-------here

Updates:

try with this:

response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));

Pass Javascript Variable to PHP POST

Yes you could use an <input type="hidden" /> and set the value of that hidden field in your javascript code so it gets posted with your other form data.

How to get the input from the Tkinter Text Widget?

I faced the problem of gettng entire text from Text widget and following solution worked for me :

txt.get(1.0,END)

Where 1.0 means first line, zeroth character (ie before the first!) is the starting position and END is the ending position.

Thanks to Alan Gauld in this link

An item with the same key has already been added

I had the problem not in my C# model, but in the javascript object I was posting using AJAX. I'm using Angular for binding and had a capitalized Notes field on the page while my C# object was expecting lower-case notes. A more descriptive error would sure be nice.

C#:

class Post {
    public string notes { get; set; }
}

Angular/Javascript:

<input ng-model="post.Notes" type="text">

await is only valid in async function

To use await, its executing context needs to be async in nature

As it said, you need to define the nature of your executing context where you are willing to await a task before anything.

Just put async before the fn declaration in which your async task will execute.

var start = async function(a, b) { 
  // Your async task will execute with await
  await foo()
  console.log('I will execute after foo get either resolved/rejected')
}

Explanation:

In your question, you are importing a method which is asynchronous in nature and will execute in parallel. But where you are trying to execute that async method is inside a different execution context which you need to define async to use await.

 var helper = require('./helper.js');   
 var start = async function(a,b){
     ....
     const result = await helper.myfunction('test','test');
 }
 exports.start = start;

Wondering what's going under the hood

await consumes promise/future / task-returning methods/functions and async marks a method/function as capable of using await.

Also if you are familiar with promises, await is actually doing the same process of promise/resolve. Creating a chain of promise and executes you next task in resolve callback.

For more info you can refer to MDN DOCS.

Axios Delete request with body and headers?

axios.delete is passed a url and an optional configuration.

axios.delete(url[, config])

The fields available to the configuration can include the headers.

This makes it so that the API call can be written as:

const headers = {
  'Authorization': 'Bearer paperboy'
}
const data = {
  foo: 'bar'
}

axios.delete('https://foo.svc/resource', {headers, data})

uint8_t vs unsigned char

Just to be pedantic, some systems may not have an 8 bit type. According to Wikipedia:

An implementation is required to define exact-width integer types for N = 8, 16, 32, or 64 if and only if it has any type that meets the requirements. It is not required to define them for any other N, even if it supports the appropriate types.

So uint8_t isn't guaranteed to exist, though it will for all platforms where 8 bits = 1 byte. Some embedded platforms may be different, but that's getting very rare. Some systems may define char types to be 16 bits, in which case there probably won't be an 8-bit type of any kind.

Other than that (minor) issue, @Mark Ransom's answer is the best in my opinion. Use the one that most clearly shows what you're using the data for.

Also, I'm assuming you meant uint8_t (the standard typedef from C99 provided in the stdint.h header) rather than uint_8 (not part of any standard).

Newline in string attribute

Code behind solution

private void Button1_Click(object sender, RoutedEventArgs e)
{
    System.Text.StringBuilder myStringBuilder = new System.Text.StringBuilder();
    myStringBuilder.Append("Orange").AppendLine();
    myStringBuilder.Append("").AppendLine();
    myStringBuilder.Append("Apple").AppendLine();
    myStringBuilder.Append("Banana").AppendLine();
    myStringBuilder.Append("").AppendLine();
    myStringBuilder.Append("Plum").AppendLine();
    TextBox1.Text = myStringBuilder.ToString();
}

Regex: Specify "space or start of string" and "space or end of string"

\b matches at word boundaries (without actually matching any characters), so the following should do what you want:

\bstackoverflow\b

Getting Cannot read property 'offsetWidth' of undefined with bootstrap carousel script

For me it was because I hadn't set an active class on any of the slides.

How to free memory in Java?

Recommendation from JAVA is to assign to null

From https://docs.oracle.com/cd/E19159-01/819-3681/abebi/index.html

Explicitly assigning a null value to variables that are no longer needed helps the garbage collector to identify the parts of memory that can be safely reclaimed. Although Java provides memory management, it does not prevent memory leaks or using excessive amounts of memory.

An application may induce memory leaks by not releasing object references. Doing so prevents the Java garbage collector from reclaiming those objects, and results in increasing amounts of memory being used. Explicitly nullifying references to variables after their use allows the garbage collector to reclaim memory.

One way to detect memory leaks is to employ profiling tools and take memory snapshots after each transaction. A leak-free application in steady state will show a steady active heap memory after garbage collections.

Access to file download dialog in Firefox

Instead of triggering the native file-download dialog like so:

By DOWNLOAD_ANCHOR = By.partialLinkText("download");
driver.findElement(DOWNLOAD_ANCHOR).click();

I usually do this instead, to bypass the native File Download dialog. This way it works on ALL browsers:

String downloadURL = driver.findElement(DOWNLOAD_ANCHOR).getAttribute("href");
File downloadedFile = getFileFromURL(downloadURL);

This just requires that you implement method getFileFromURL that uses Apache HttpClient to download a file and return a File reference to you.

Similarly, if you happen to be using Selenide, it works the same way using the built-in download() function for handling file downloads.