Programs & Examples On #Lazarus

Lazarus is an open-source multiplatform RAD environment for the Free Pascal compiler, in the spirit of Delphi, with which it has a fairly high degree of compatibility. See http://lazarus.freepascal.org

Making a flex item float right

You can't use float inside flex container and the reason is that float property does not apply to flex-level boxes as you can see here Fiddle.

So if you want to position child element to right of parent element you can use margin-left: auto but now child element will also push other div to the right as you can see here Fiddle.

What you can do now is change order of elements and set order: 2 on child element so it doesn't affect second div

_x000D_
_x000D_
.parent {_x000D_
  display: flex;_x000D_
}_x000D_
.child {_x000D_
  margin-left: auto;_x000D_
  order: 2;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <div class="child">Ignore parent?</div>_x000D_
  <div>another child</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Cast to generic type in C#

The following seems to work as well, and it's a little bit shorter than the other answers:

T result = (T)Convert.ChangeType(otherTypeObject, typeof(T));

Linq style "For Each"

There isn't anything like that in standard Linq, but there is a ForEach operator in MoreLinq.

How to pass the button value into my onclick event function?

You can do like this.

<input type="button" value="mybutton1" onclick="dosomething(this)">

function dosomething(element){
    alert("value is "+element.value); //you can print any value like id,class,value,innerHTML etc.
};

dll missing in JDBC

keep sqljdbc_auth.dll in your windows/system32 folder and it will work.Download sqljdbc driver from this link Unzip it and you will find sqljdbc_auth.dll.Now keep the sqljdbc_auth.dll inside system32 folder and run your program

Differentiate between function overloading and function overriding

Overriding means, giving a different definition of an existing function with same parameters, and overloading means adding a different definition of an existing function with different parameters.

Example:

#include <iostream>

class base{
    public:
    //this needs to be virtual to be overridden in derived class
    virtual void show(){std::cout<<"I am base";}
    //this is overloaded function of the previous one
    void show(int x){std::cout<<"\nI am overloaded";} 
};

class derived:public base{
    public:
    //the base version of this function is being overridden
    void show(){std::cout<<"I am derived (overridden)";}
};


int main(){
    base* b;
    derived d;
    b=&d;
    b->show();  //this will call the derived overriden version
    b->show(6); // this will call the base overloaded function
}

Output:

I am derived (overridden)
I am overloaded

Rails where condition using NOT NIL

It's not a bug in ARel, it's a bug in your logic.

What you want here is:

Foo.includes(:bar).where(Bar.arel_table[:id].not_eq(nil))

await vs Task.Wait - Deadlock?

Some important facts were not given in other answers:

"async await" is more complex at CIL level and thus costs memory and CPU time.

Any task can be canceled if the waiting time is unacceptable.

In the case "async await" we do not have a handler for such a task to cancel it or monitoring it.

Using Task is more flexible then "async await".

Any sync functionality can by wrapped by async.

public async Task<ActionResult> DoAsync(long id) 
{ 
    return await Task.Run(() => { return DoSync(id); } ); 
} 

"async await" generate many problems. We do not now is await statement will be reached without runtime and context debugging. If first await not reached everything is blocked. Some times even await seems to be reached still everything is blocked:

https://github.com/dotnet/runtime/issues/36063

I do not see why I'm must live with the code duplication for sync and async method or using hacks.

Conclusion: Create Task manually and control them is much better. Handler to Task give more control. We can monitor Tasks and manage them:

https://github.com/lsmolinski/MonitoredQueueBackgroundWorkItem

Sorry for my english.

How to use SharedPreferences in Android to store, fetch and edit values

Store in SharedPreferences

SharedPreferences preferences = getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString("name", name);
editor.commit();

Fetch in SharedPreferences

SharedPreferences preferences=getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE);
String name=preferences.getString("name",null);

Note: "temp" is sharedpreferences name and "name" is input value. if value does't exit then return null

Uncaught ReferenceError: React is not defined

Try to add:

import React from 'react'
import { render } from 'react-dom'
window.React = React

before the render() function.

This sometimes prevents error to pop-up returning:

React is not defined

Adding React to the window will solve these problems.

Return Bit Value as 1/0 and NOT True/False in SQL Server

just you pass this things in your select query. using CASE

CASE WHEN  gender=0 then 'Female' WHEN  gender=1 then 'Male' END as Genderdisp

Using VBA to get extended file attributes

I was finally able to get this to work for my needs.

The old voted up code does not run on windows 10 system (at least not mine). The referenced MS library link below provides current examples on how to make this work. My example uses them with late bindings.

https://docs.microsoft.com/en-us/windows/win32/shell/folder-getdetailsof.

The attribute codes were different on my computer and like someone mentioned above most return blank values even if they are not. I used a for loop to cycle through all of them and found out that Title and Subject can still be accessed which is more then enough for my purposes.

Private Sub MySubNamek()
Dim objShell  As Object 'Shell
Dim objFolder As Object 'Folder

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace("E:\MyFolder")

If (Not objFolder Is Nothing) Then
Dim objFolderItem As Object 'FolderItem
Set objFolderItem = objFolder.ParseName("Myfilename.txt")
        For i = 0 To 288
           szItem = objFolder.GetDetailsOf(objFolderItem, i)
           Debug.Print i & " - " & szItem
       Next
Set objFolderItem = Nothing
End If

Set objFolder = Nothing
Set objShell = Nothing
End Sub

How do I get a YouTube video thumbnail from the YouTube API?

YouTube is owned by Google and Google likes to have a reasonable number of images for different screen sizes, hence its images are stored in different sizes. Here is an example of how your thumbnail will be like:

Low quality thumbnail:

http://img.youtube.com/vi/<YouTube_Video_ID_HERE>/sddefault.jpg

Medium quality thumbnail:

http://img.youtube.com/vi/<YouTube_Video_ID_HERE>/mqdefault.jpg

High quality thumbnail:

http://img.youtube.com/vi/<YouTube_Video_ID_HERE>/hqdefault.jpg

Maximum quality thumbnail:

http://img.youtube.com/vi/<YouTube_Video_ID_HERE>/maxresdefault.jpg

How to use Bootstrap 4 in ASP.NET Core

What does the trick for me is:

1) Right click on wwwroot > Add > Client Side Library

2) Typed "bootstrap" on the search box

3) Select "Choose specific files"

4) Scroll down and select a folder. In my case I chose "twitter-bootstrap"

5) Check "css" and "js"

6) Click "Install".

A few seconds later I have all of them wwwroot folder. Do the same for all client side packages that you want to add.

How do I read the first line of a file using cat?

Use the below command to get the first row from a CSV file or any file formats.

head -1 FileName.csv

What does functools.wraps do?

  1. Prerequisite: You must know how to use decorators and specially with wraps. This comment explains it a bit clear or this link also explains it pretty well.

  2. Whenever we use For eg: @wraps followed by our own wrapper function. As per the details given in this link , it says that

functools.wraps is convenience function for invoking update_wrapper() as a function decorator, when defining a wrapper function.

It is equivalent to partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated).

So @wraps decorator actually gives a call to functools.partial(func[,*args][, **keywords]).

The functools.partial() definition says that

The partial() is used for partial function application which “freezes” some portion of a function’s arguments and/or keywords resulting in a new object with a simplified signature. For example, partial() can be used to create a callable that behaves like the int() function where the base argument defaults to two:

>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo.__doc__ = 'Convert base 2 string to an int.'
>>> basetwo('10010')
18

Which brings me to the conclusion that, @wraps gives a call to partial() and it passes your wrapper function as a parameter to it. The partial() in the end returns the simplified version i.e the object of what's inside the wrapper function and not the wrapper function itself.

How to check if the given string is palindrome?

Python:

if s == s[::-1]: return True

Java:

if (s.Equals(s.Reverse())) { return true; }

PHP:

if (s == strrev(s)) return true;

Perl:

if (s == reverse(s)) { return true; }

Erlang:

string:equal(S, lists:reverse(S)).

How do I discard unstaged changes in Git?

2019 update

You can now discard unstaged changes in one tracked file with:

git restore <file>

and in all tracked files in the current directory (recursively) with:

git restore .

If you run the latter from the root of the repo, it will discard unstaged changes in all tracked files.

Notes

  • git restore was introduced in July 2019 and released in version 2.23 as part of a split of the git checkout command into git restore for files and git switch for branches.
  • git checkout still behaves as it used to and the older answers remain perfectly valid.
  • When running git status with unstaged changes in the working tree, this is now what Git suggests to use to discard them (instead of git checkout -- <file> as it used to prior to v2.23).
  • As with git checkout -- ., this only discards changes in tracked files. So Mariusz Nowak's answer still applies and if you want to discard all unstaged changes, including untracked files, you could run, as he suggests, an additional git clean -df.

Date query with ISODate in mongodb doesn't seem to work

I am using robomongo as the mongodb client gui and the below worked for me

db.collectionName.find({"columnWithDateTime" : {
$lt:new ISODate("2016-02-28T00:00:00.000Z")}})

On the app side I am using nodejs based driver mongodb(v1.4.3),the application uses datepicker in the ui which gives date like YYYY-mm-dd, this is then appended with default time like 00:00:00 and then given to the new Date() constructor and then supplied to the mongodb criteria object,I think the driver converts the date to ISO date and the query then works and gives desired output, however the same new Date() constructor does not work or show same output on robo mongo,for the same criteria,which is weird,since I used robomongo to cross check my criteria objects.

Whereas the default cli mongoshell works well with both ISODate and new Date()

What is the maximum length of a Push Notification alert text?

The real limits for the alert text are not documented anywhere. The only thing the documentation says is:

In iOS 8 and later, the maximum size allowed for a notification payload is 2 kilobytes; Apple Push Notification Service refuses any notification that exceeds this limit. (Prior to iOS 8 and in OS X, the maximum payload size is 256 bytes.)

This is what I could find doing some experiments.

  • Alerts: Prior to iOS 7, the alerts display limit was 107 characters. Bigger messages were truncated and you would get a "..." at the end of the displayed message. With iOS 7 the limit seems to be increased to 235 characters. If you go over 8 lines your message will also get truncated.
  • Banners: Banners get truncated around 62 characters or 2 lines.
  • Notification Center: The messages in the notification center get truncated around 110 characters or 4 lines.
  • Lock Screen: Same as a notification center.

Just as a reminder here is a very good note from the official documentation:

If necessary, iOS truncates your message so that it fits well in each notification delivery style; for best results, you shouldn’t truncate your message.

Angular 2 Date Input not binding to date value

Angular 2 , 4 and 5 :

the simplest way : plunker

<input type="date" [ngModel] ="dt | date:'yyyy-MM-dd'" (ngModelChange)="dt = $event">

check if "it's a number" function in Oracle

How is the column defined? If its a varchar field, then its not a number (or stored as one). Oracle may be able to do the conversion for you (eg, select * from someTable where charField = 0), but it will only return rows where the conversion holds true and is possible. This is also far from ideal situation performance wise.

So, if you want to do number comparisons and treat this column as a number, perhaps it should be defined as a number?

That said, here's what you might do:

create or replace function myToNumber(i_val in varchar2) return number is
 v_num number;
begin
 begin
   select to_number(i_val) into v_num from dual;
 exception
   when invalid_number then
   return null;
 end;
 return v_num;
end;

You might also include the other parameters that the regular to_number has. Use as so:

select * from someTable where myToNumber(someCharField) > 0;

It won't return any rows that Oracle sees as an invalid number.

Cheers.

Why can I not push_back a unique_ptr into a vector?

std::unique_ptr has no copy constructor. You create an instance and then ask the std::vector to copy that instance during initialisation.

error: deleted function 'std::unique_ptr<_Tp, _Tp_Deleter>::uniqu
e_ptr(const std::unique_ptr<_Tp, _Tp_Deleter>&) [with _Tp = int, _Tp_D
eleter = std::default_delete<int>, std::unique_ptr<_Tp, _Tp_Deleter> =
 std::unique_ptr<int>]'

The class satisfies the requirements of MoveConstructible and MoveAssignable, but not the requirements of either CopyConstructible or CopyAssignable.

The following works with the new emplace calls.

std::vector< std::unique_ptr< int > > vec;
vec.emplace_back( new int( 1984 ) );

See using unique_ptr with standard library containers for further reading.

ReSharper "Cannot resolve symbol" even when project builds

For me for VS2015, I had to update Resharper to version 2016.2.2 to resolve the issue.

I had already tried (of which none worked for me):

  • suspending / resuming
  • suspending / clearing cach (using tools > options button) / resuming
  • suspending / clearing cach (using Windows file system) / resuming
  • moving cache to solution folder / restarting visual studio
  • many other combinations of all or some of above

I hope that may help someone.

Is there a way to make AngularJS load partials in the beginning and not at when needed?

I just use eco to do the job for me. eco is supported by Sprockets by default. It's a shorthand for Embedded Coffeescript which takes a eco file and compile into a Javascript template file, and the file will be treated like any other js files you have in your assets folder.

All you need to do is to create a template with extension .jst.eco and write some html code in there, and rails will automatically compile and serve the file with the assets pipeline, and the way to access the template is really easy: JST['path/to/file']({var: value}); where path/to/file is based on the logical path, so if you have file in /assets/javascript/path/file.jst.eco, you can access the template at JST['path/file']()

To make it work with angularjs, you can pass it into the template attribute instead of templateDir, and it will start working magically!

Deadly CORS when http://localhost is the origin

Quick and dirty Chrome extension fix:

Moesif Orign & CORS Changer

However, Chrome does support cross-origin requests from localhost. Make sure to add a header for Access-Control-Allow-Origin for localhost.

In a Dockerfile, How to update PATH environment variable?

Although the answer that Gunter posted was correct, it is not different than what I already had posted. The problem was not the ENV directive, but the subsequent instruction RUN export $PATH

There's no need to export the environment variables, once you have declared them via ENV in your Dockerfile.

As soon as the RUN export ... lines were removed, my image was built successfully

Mocha / Chai expect.to.throw not catching thrown errors

This question has many, many duplicates, including questions not mentioning the Chai assertion library. Here are the basics collected together:

The assertion must call the function, instead of it evaluating immediately.

assert.throws(x.y.z);      
   // FAIL.  x.y.z throws an exception, which immediately exits the
   // enclosing block, so assert.throw() not called.
assert.throws(()=>x.y.z);  
   // assert.throw() is called with a function, which only throws
   // when assert.throw executes the function.
assert.throws(function () { x.y.z });   
   // if you cannot use ES6 at work
function badReference() { x.y.z }; assert.throws(badReference);  
   // for the verbose
assert.throws(()=>model.get(z));  
   // the specific example given.
homegrownAssertThrows(model.get, z);
   //  a style common in Python, but not in JavaScript

You can check for specific errors using any assertion library:

Node

  assert.throws(() => x.y.z);
  assert.throws(() => x.y.z, ReferenceError);
  assert.throws(() => x.y.z, ReferenceError, /is not defined/);
  assert.throws(() => x.y.z, /is not defined/);
  assert.doesNotThrow(() => 42);
  assert.throws(() => x.y.z, Error);
  assert.throws(() => model.get.z, /Property does not exist in model schema./)

Should

  should.throws(() => x.y.z);
  should.throws(() => x.y.z, ReferenceError);
  should.throws(() => x.y.z, ReferenceError, /is not defined/);
  should.throws(() => x.y.z, /is not defined/);
  should.doesNotThrow(() => 42);
  should.throws(() => x.y.z, Error);
  should.throws(() => model.get.z, /Property does not exist in model schema./)

Chai Expect

  expect(() => x.y.z).to.throw();
  expect(() => x.y.z).to.throw(ReferenceError);
  expect(() => x.y.z).to.throw(ReferenceError, /is not defined/);
  expect(() => x.y.z).to.throw(/is not defined/);
  expect(() => 42).not.to.throw();
  expect(() => x.y.z).to.throw(Error);
  expect(() => model.get.z).to.throw(/Property does not exist in model schema./);

You must handle exceptions that 'escape' the test

it('should handle escaped errors', function () {
  try {
    expect(() => x.y.z).not.to.throw(RangeError);
  } catch (err) {
    expect(err).to.be.a(ReferenceError);
  }
});

This can look confusing at first. Like riding a bike, it just 'clicks' forever once it clicks.

Ruby optional parameters

It isn't possible to do it the way you've defined ldap_get. However, if you define ldap_get like this:

def ldap_get ( base_dn, filter, attrs=nil, scope=LDAP::LDAP_SCOPE_SUBTREE )

Now you can:

ldap_get( base_dn, filter, X )

But now you have problem that you can't call it with the first two args and the last arg (the same problem as before but now the last arg is different).

The rationale for this is simple: Every argument in Ruby isn't required to have a default value, so you can't call it the way you've specified. In your case, for example, the first two arguments don't have default values.

Sending Arguments To Background Worker?

Even though this is an already answered question, I'd leave another option that IMO is a lot easier to read:

BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (obj, e) => WorkerDoWork(value, text);
worker.RunWorkerAsync();

And on the handler method:

private void WorkerDoWork(int value, string text) {
    ...
}

How to get the last char of a string in PHP?

As of PHP 7.1.0, negative string offsets are also supported. So, if you keep up with the times, you can access the last character in the string like this:

$str[-1]

DEMO

At the request of a @mickmackusa, I supplement my answer with possible ways of application:

<?php

$str='abcdef';
var_dump($str[-2]); // => string(1) "e"

$str[-3]='.';
var_dump($str);     // => string(6) "abc.ef"

var_dump(isset($str[-4]));  // => bool(true)

var_dump(isset($str[-10])); // => bool(false)

How to replace sql field value

You could just use REPLACE:

UPDATE myTable SET emailCol = REPLACE(emailCol, '.com', '.org')`.

But take into account an email address such as [email protected] will be updated to [email protected].

If you want to be on a safer side, you should check for the last 4 characters using RIGHT, and append .org to the SUBSTRING manually instead. Notice the usage of UPPER to make the search for the .com ending case insensitive.

UPDATE myTable 
SET emailCol = SUBSTRING(emailCol, 1, LEN(emailCol)-4) + '.org'
WHERE UPPER(RIGHT(emailCol,4)) = '.COM';

See it working in this SQLFiddle.

What is the bit size of long on 64-bit Windows?

Microsoft has also defined UINT_PTR and INT_PTR for integers that are the same size as a pointer.

Here is a list of Microsoft specific types - it's part of their driver reference, but I believe it's valid for general programming as well.

Ripple effect on Android Lollipop CardView

Add these two like of code work like a charm for any view like Button, Linear Layout, or CardView Just put these two lines and see the magic...

android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"

Waiting on a list of Future

 /**
     * execute suppliers as future tasks then wait / join for getting results
     * @param functors a supplier(s) to execute
     * @return a list of results
     */
    private List getResultsInFuture(Supplier<?>... functors) {
        CompletableFuture[] futures = stream(functors)
                .map(CompletableFuture::supplyAsync)
                .collect(Collectors.toList())
                .toArray(new CompletableFuture[functors.length]);
        CompletableFuture.allOf(futures).join();
        return stream(futures).map(a-> {
            try {
                return a.get();
            } catch (InterruptedException | ExecutionException e) {
                //logger.error("an error occurred during runtime execution a function",e);
                return null;
            }
        }).collect(Collectors.toList());
    };

Can I force a UITableView to hide the separator between empty cells?

Swift Version

The easiest method is to set the tableFooterView property:

override func viewDidLoad() {
    super.viewDidLoad()
    // This will remove extra separators from tableview
    self.tableView.tableFooterView = UIView(frame: CGRectZero)
}

Creating temporary files in Android

You can use the cache dir using context.getCacheDir().

File temp=File.createTempFile("prefix","suffix",context.getCacheDir());

How to loop and render elements in React-native?

If u want a direct/ quick away, without assing to variables:

{
 urArray.map((prop, key) => {
     console.log(emp);
     return <Picker.Item label={emp.Name} value={emp.id} />;
 })
}

Python: Fetch first 10 results from a list

list[:10]

will give you the first 10 elements of this list using slicing.

However, note, it's best not to use list as a variable identifier as it's already used by Python: list()

To find out more about these type of operations you might find this tutorial on lists helpful and the link @DarenThomas provided Explain Python's slice notation - thanks Daren)

UnicodeEncodeError: 'latin-1' codec can't encode character

SQLAlchemy users can simply specify their field as convert_unicode=True.

Example: sqlalchemy.String(1000, convert_unicode=True)

SQLAlchemy will simply accept unicode objects and return them back, handling the encoding itself.

Docs

Copy a file in a sane, safe and efficient way

Copy a file in a sane way:

#include <fstream>

int main()
{
    std::ifstream  src("from.ogv", std::ios::binary);
    std::ofstream  dst("to.ogv",   std::ios::binary);

    dst << src.rdbuf();
}

This is so simple and intuitive to read it is worth the extra cost. If we were doing it a lot, better to fall back on OS calls to the file system. I am sure boost has a copy file method in its filesystem class.

There is a C method for interacting with the file system:

#include <copyfile.h>

int
copyfile(const char *from, const char *to, copyfile_state_t state, copyfile_flags_t flags);

Interface naming in Java

Is this a broader naming convention in any real sense? I'm more on the C++ side, and not really up on Java and descendants. How many language communities use the I convention?

If you have a language-independent shop standard naming convention here, use it. If not, go with the language naming convention.

Java image resize, maintain aspect ratio

Here we go:

Dimension imgSize = new Dimension(500, 100);
Dimension boundary = new Dimension(200, 200);

Function to return the new size depending on the boundary:

public static Dimension getScaledDimension(Dimension imgSize, Dimension boundary) {

    int original_width = imgSize.width;
    int original_height = imgSize.height;
    int bound_width = boundary.width;
    int bound_height = boundary.height;
    int new_width = original_width;
    int new_height = original_height;

    // first check if we need to scale width
    if (original_width > bound_width) {
        //scale width to fit
        new_width = bound_width;
        //scale height to maintain aspect ratio
        new_height = (new_width * original_height) / original_width;
    }

    // then check if we need to scale even with the new height
    if (new_height > bound_height) {
        //scale height to fit instead
        new_height = bound_height;
        //scale width to maintain aspect ratio
        new_width = (new_height * original_width) / original_height;
    }

    return new Dimension(new_width, new_height);
}

In case anyone also needs the image resizing code, here is a decent solution.

If you're unsure about the above solution, there are different ways to achieve the same result.

SQL WHERE.. IN clause multiple columns

A simple EXISTS clause is cleanest

select *
from table1 t1
WHERE
EXISTS
(
 Select * --or 1. No difference...
 From CRM_VCM_CURRENT_LEAD_STATUS Ex
 Where Lead_Key = :_Lead_Key
-- correlation here...
AND
t1.CM_PLAN_ID = Ex.CM_PLAN_ID AND t1.CM_PLAN_ID =  Ex.Individual_ID
)

If you have multiple rows in the correlation then a JOIN gives multiple rows in the output, so you'd need distinct. Which usually makes the EXISTS more efficient.

Note SELECT * with a JOIN would also include columns from the row limiting tables

Using wire or reg with input or output in Verilog

The Verilog code compiler you use will dictate what you have to do. If you use illegal syntax, you will get a compile error.

An output must also be declared as a reg only if it is assigned using a "procedural assignment". For example:

output reg a;
always @* a = b;

There is no need to declare an output as a wire.

There is no need to declare an input as a wire or reg.

In Gradle, is there a better way to get Environment Variables?

I couldn't get the form suggested by @thoredge to work in Gradle 1.11, but this works for me:

home = System.getenv('HOME')

It helps to keep in mind that anything that works in pure Java will work in Gradle too.

SQL Server: convert ((int)year,(int)month,(int)day) to Datetime

SELECT CAST(CAST(year AS varchar) + '/' + CAST(month AS varchar) + '/' + CAST(day as varchar) AS datetime) AS MyDateTime
FROM table

internet explorer 10 - how to apply grayscale filter?

Use this jQuery plugin https://gianlucaguarini.github.io/jQuery.BlackAndWhite/

That seems to be the only one cross-browser solution. Plus it has a nice fade in and fade out effect.

$('.bwWrapper').BlackAndWhite({
    hoverEffect : true, // default true
    // set the path to BnWWorker.js for a superfast implementation
    webworkerPath : false,
    // to invert the hover effect
    invertHoverEffect: false,
    // this option works only on the modern browsers ( on IE lower than 9 it remains always 1)
    intensity:1,
    speed: { //this property could also be just speed: value for both fadeIn and fadeOut
        fadeIn: 200, // 200ms for fadeIn animations
        fadeOut: 800 // 800ms for fadeOut animations
    },
    onImageReady:function(img) {
        // this callback gets executed anytime an image is converted
    }
});

.htaccess mod_rewrite - how to exclude directory from rewrite rule

We used the following mod_rewrite rule:

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/test/
RewriteCond %{REQUEST_URI} !^/my-folder/
RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]

This redirects (permanently with a 301 redirect) all traffic to the site to http://www.newdomain.com, except requests to resources in the /test and /my-folder directories. We transfer the user to the exact resource they requested by using the (.*) capture group and then including $1 in the new URL. Mind the spaces.

Cursor inside cursor

This smells of something that should be done with a JOIN instead. Can you share the larger problem with us?


Hey, I should be able to get this down to a single statement, but I haven't had time to play with it further yet today and may not get to. In the mean-time, know that you should be able to edit the query for your inner cursor to create the row numbers as part of the query using the ROW_NUMBER() function. From there, you can fold the inner cursor into the outer by doing an INNER JOIN on it (you can join on a sub query). Finally, any SELECT statement can be converted to an UPDATE using this method:

UPDATE [YourTable/Alias]
   SET [Column] = q.Value
FROM
(
   ... complicate select query here ...
) q

Where [YourTable/Alias] is a table or alias used in the select query.

Simple conversion between java.util.Date and XMLGregorianCalendar

Why not use an external binding file to tell XJC to generate java.util.Date fields instead of XMLGregorianCalendar?

Also see How do I map xs:date to java.util.Date? Blog

How to lookup JNDI resources on WebLogic?

You should be able to simply do this:

Context context = new InitialContext();
dataSource = (javax.sql.DataSource) context.lookup("jdbc/myDataSource");

If you are looking it up from a remote destination you need to use the WL initial context factory like this:

Hashtable<String, String> h = new Hashtable<String, String>(7);
h.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
h.put(Context.PROVIDER_URL, pURL); //For example "t3://127.0.0.1:7001"
h.put(Context.SECURITY_PRINCIPAL, pUsername);
h.put(Context.SECURITY_CREDENTIALS, pPassword);

InitialContext context = new InitialContext(h);
dataSource = (javax.sql.DataSource) context.lookup("jdbc/myDataSource");

weblogic.jndi.WLInitialContextFactory

jQuery addClass onClick

It needs to be a jQuery element to use .addClass(), so it needs to be wrapped in $() like this:

function addClassByClick(button){
  $(button).addClass("active")
}

A better overall solution would be unobtrusive script, for example:

<asp:Button ID="Button" runat="server" class="clickable"/>

Then in jquery:

$(function() {                       //run when the DOM is ready
  $(".clickable").click(function() {  //use a class, since your ID gets mangled
    $(this).addClass("active");      //add the class to the clicked element
  });
});

WPF Datagrid Get Selected Cell Value

Ok after doing reverse engineering and a little pixie dust of reflection, one can do this operation on SelectedCells (at any point) to get all (regardless of selected on one row or many rows) the data from one to many selected cells:

MessageBox.Show(

string.Join(", ", myGrid.SelectedCells
                        .Select(cl => cl.Item.GetType()
                                             .GetProperty(cl.Column.SortMemberPath)
                                             .GetValue(cl.Item, null)))

               );

I tried this on text (string) fields only though a DateTime field should return a value the initiate ToString(). Also note that SortMemberPath is not the same as Header so that should always provide the proper property to reflect off of.

<DataGrid ItemsSource="{Binding MyData}"                      
          AutoGenerateColumns="True"
          Name="myGrid"
          IsReadOnly="True"
          SelectionUnit="Cell"
          SelectionMode="Extended">

What is bootstrapping?

For completeness, it is also a rather important (and relatively new) method in statistics that uses resampling / simulation to infer population properties from a sample. It has its own lengthy Wikipedia article on bootstrapping (statistics).

What is the difference between canonical name, simple name and class name in Java Class?

In addition to Nick Holt's observations, I ran a few cases for Array data type:

//primitive Array
int demo[] = new int[5];
Class<? extends int[]> clzz = demo.getClass();
System.out.println(clzz.getName());
System.out.println(clzz.getCanonicalName());
System.out.println(clzz.getSimpleName());       

System.out.println();


//Object Array
Integer demo[] = new Integer[5]; 
Class<? extends Integer[]> clzz = demo.getClass();
System.out.println(clzz.getName());
System.out.println(clzz.getCanonicalName());
System.out.println(clzz.getSimpleName());

Above code snippet prints:

[I
int[]
int[]

[Ljava.lang.Integer;
java.lang.Integer[]
Integer[]

Find the location of a character in string

Here's another straightforward alternative.

> which(strsplit(string, "")[[1]]=="2")
[1]  4 24

How do I call a Django function on button click?

There are 2 possible solutions that I personally use

1.without using form

 <button type="submit" value={{excel_path}} onclick="location.href='{% url 'downloadexcel' %}'" name='mybtn2'>Download Excel file</button>

2.Using Form

<form action="{% url 'downloadexcel' %}" method="post">
{% csrf_token %}


 <button type="submit" name='mybtn2' value={{excel_path}}>Download results in Excel</button>
 </form>

Where urls.py should have this

path('excel/',views1.downloadexcel,name="downloadexcel"),

How do I list all files of a directory?

Getting Full File Paths From a Directory and All Its Subdirectories

import os

def get_filepaths(directory):
    """
    This function will generate the file names in a directory 
    tree by walking the tree either top-down or bottom-up. For each 
    directory in the tree rooted at directory top (including top itself), 
    it yields a 3-tuple (dirpath, dirnames, filenames).
    """
    file_paths = []  # List which will store all of the full filepaths.

    # Walk the tree.
    for root, directories, files in os.walk(directory):
        for filename in files:
            # Join the two strings in order to form the full filepath.
            filepath = os.path.join(root, filename)
            file_paths.append(filepath)  # Add it to the list.

    return file_paths  # Self-explanatory.

# Run the above function and store its results in a variable.   
full_file_paths = get_filepaths("/Users/johnny/Desktop/TEST")

  • The path I provided in the above function contained 3 files— two of them in the root directory, and another in a subfolder called "SUBFOLDER." You can now do things like:
  • print full_file_paths which will print the list:

    • ['/Users/johnny/Desktop/TEST/file1.txt', '/Users/johnny/Desktop/TEST/file2.txt', '/Users/johnny/Desktop/TEST/SUBFOLDER/file3.dat']

If you'd like, you can open and read the contents, or focus only on files with the extension ".dat" like in the code below:

for f in full_file_paths:
  if f.endswith(".dat"):
    print f

/Users/johnny/Desktop/TEST/SUBFOLDER/file3.dat

javax.net.ssl.SSLException: Received fatal alert: protocol_version

I ran into this issue while trying to install a PySpark package. I got around the issue by changing the TLS version with an environment variable:

echo 'export JAVA_TOOL_OPTIONS="-Dhttps.protocols=TLSv1.2"' >> ~/.bashrc
source ~/.bashrc

What is the difference between AF_INET and PF_INET in socket programming?

In fact, AF_ and PF_ are the same thing. There are some words on Wikipedia will clear your confusion

The original design concept of the socket interface distinguished between protocol types (families) and the specific address types that each may use. It was envisioned that a protocol family may have several address types. Address types were defined by additional symbolic constants, using the prefix AF_ instead of PF_. The AF_-identifiers are intended for all data structures that specifically deal with the address type and not the protocol family. However, this concept of separation of protocol and address type has not found implementation support and the AF_-constants were simply defined by the corresponding protocol identifier, rendering the distinction between AF_ versus PF_ constants a technical argument of no significant practical consequence. Indeed, much confusion exists in the proper usage of both forms.

image.onload event and browser cache

I have met the same issue today. After trying various method, I realize that just put the code of sizing inside $(window).load(function() {}) instead of document.ready would solve part of issue (if you are not ajaxing the page).

How can I determine the current CPU utilization from the shell?

You need to sample the load average for several seconds and calculate the CPU utilization from that. If unsure what to you, get the sources of "top" and read it.

pthread_join() and pthread_exit()

The typical use is

void* ret = NULL;
pthread_t tid = something; /// change it suitably
if (pthread_join (tid, &ret)) 
   handle_error();
// do something with the return value ret

Lumen: get URL parameter in a Blade view

Laravel 5.6:

{{ Request::query('parameter') }}

How to write and read a file with a HashMap?

The simplest solution that I can think of is using Properties class.

Saving the map:

Map<String, String> ldapContent = new HashMap<String, String>();
Properties properties = new Properties();

for (Map.Entry<String,String> entry : ldapContent.entrySet()) {
    properties.put(entry.getKey(), entry.getValue());
}

properties.store(new FileOutputStream("data.properties"), null);

Loading the map:

Map<String, String> ldapContent = new HashMap<String, String>();
Properties properties = new Properties();
properties.load(new FileInputStream("data.properties"));

for (String key : properties.stringPropertyNames()) {
   ldapContent.put(key, properties.get(key).toString());
}

EDIT:

if your map contains plaintext values, they will be visible if you open file data via any text editor, which is not the case if you serialize the map:

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.ser"));
out.writeObject(ldapContent);
out.close();

EDIT2:

instead of for loop (as suggested by OldCurmudgeon) in saving example:

properties.putAll(ldapContent);

however, for the loading example this is the best that can be done:

ldapContent = new HashMap<Object, Object>(properties);

MySQL compare now() (only date, not time) with a datetime field

Compare date only instead of date + time (NOW) with:

CURDATE()

LINQ select in C# dictionary

One way would be to first flatten the list with a SelectMany:

subList.SelectMany(m => m).Where(k => k.Key.Equals("valueTitle"));

Can an int be null in Java?

Check for null in your check() method and return an invalid value such as -1 or zero if null. Then the check would be for that value rather than passing the null along. This would be a normal thing to do in old time 'C'.

Why is the time complexity of both DFS and BFS O( V + E )

DFS(analysis):

  • Setting/getting a vertex/edge label takes O(1) time
  • Each vertex is labeled twice
    • once as UNEXPLORED
    • once as VISITED
  • Each edge is labeled twice
    • once as UNEXPLORED
    • once as DISCOVERY or BACK
  • Method incidentEdges is called once for each vertex
  • DFS runs in O(n + m) time provided the graph is represented by the adjacency list structure
  • Recall that Sv deg(v) = 2m

BFS(analysis):

  • Setting/getting a vertex/edge label takes O(1) time
  • Each vertex is labeled twice
    • once as UNEXPLORED
    • once as VISITED
  • Each edge is labeled twice
    • once as UNEXPLORED
    • once as DISCOVERY or CROSS
  • Each vertex is inserted once into a sequence Li
  • Method incidentEdges is called once for each vertex
  • BFS runs in O(n + m) time provided the graph is represented by the adjacency list structure
  • Recall that Sv deg(v) = 2m

Callback when CSS3 transition finishes

For anyone that this might be handy for, here is a jQuery dependent function I had success with for applying a CSS animation via a CSS class, then getting a callback from afterwards. It may not work perfectly since I had it being used in a Backbone.js App, but maybe useful.

var cssAnimate = function(cssClass, callback) {
    var self = this;

    // Checks if correct animation has ended
    var setAnimationListener = function() {
        self.one(
            "webkitAnimationEnd oanimationend msAnimationEnd animationend",
            function(e) {
                if(
                    e.originalEvent.animationName == cssClass &&
                    e.target === e.currentTarget
                ) {
                    callback();
                } else {
                    setAnimationListener();
                }
            }
        );
    }

    self.addClass(cssClass);
    setAnimationListener();
}

I used it kinda like this

cssAnimate.call($("#something"), "fadeIn", function() {
    console.log("Animation is complete");
    // Remove animation class name?
});

Original idea from http://mikefowler.me/2013/11/18/page-transitions-in-backbone/

And this seems handy: http://api.jqueryui.com/addClass/


Update

After struggling with the above code and other options, I would suggest being very cautious with any listening for CSS animation ends. With multiple animations going on, this can get messy very fast for event listening. I would strongly suggest an animation library like GSAP for every animation, even the small ones.

Redirect stderr and stdout in Bash

bash your_script.sh 1>file.log 2>&1

1>file.log instructs the shell to send STDOUT to the file file.log, and 2>&1 tells it to redirect STDERR (file descriptor 2) to STDOUT (file descriptor 1).

Note: The order matters as liw.fi pointed out, 2>&1 1>file.log doesn't work.

UITextView that expands to text using auto layout

You can also do it without subclassing UITextView. Have a look at my answer to How do I size a UITextView to its content on iOS 7?

Use the value of this expression:

[textView sizeThatFits:CGSizeMake(textView.frame.size.width, CGFLOAT_MAX)].height

to update the constant of the textView's height UILayoutConstraint.

Python - 'ascii' codec can't decode byte

"??".encode('utf-8')

encode converts a unicode object to a string object. But here you have invoked it on a string object (because you don't have the u). So python has to convert the string to a unicode object first. So it does the equivalent of

"??".decode().encode('utf-8')

But the decode fails because the string isn't valid ascii. That's why you get a complaint about not being able to decode.

How can I specify the schema to run an sql file against in the Postgresql command line

More universal way is to set search_path (should work in PostgreSQL 7.x and above):

SET search_path TO myschema;

Note that set schema myschema is an alias to above command that is not available in 8.x.

See also: http://www.postgresql.org/docs/9.3/static/ddl-schemas.html

How to SUM and SUBTRACT using SQL?

ah homework...

So wait, you need to deduct the balance of items in stock from the total number of those items that have been ordered? I have to tell you that sounds a bit backwards. Generally I think people do it the other way round. Deduct the total number of items ordered from the balance.

If you really need to do that though... Assuming that ITEM is unique in stock_bal...

SELECT s.ITEM, SUM(m.QTY) - s.QTY AS result
FROM stock_bal s
INNER JOIN master_table m ON m.ITEM = s.ITEM
GROUP BY s.ITEM, s.QTY

struct in class

I'd like to add another use case for an internal struct/class and its usability. An inner struct is often used to declare a data only member of a class that packs together relevant information and as such we can enclose it all in a struct instead of loose data members lying around.

The inner struct/class is but a data only compartment, ie it has no functions (except maybe constructors).

#include <iostream>

class E
{
    // E functions..
public:
    struct X
    {
        int v;
        // X variables..
    } x;
    // E variables..
};

int main()
{
    E e;
    e.x.v = 9;
    std::cout << e.x.v << '\n';
    
    E e2{5};
    std::cout << e2.x.v << '\n';

    // You can instantiate an X outside E like so:
    //E::X xOut{24};
    //std::cout << xOut.v << '\n';
    // But you shouldn't want to in this scenario.
    // X is only a data member (containing other data members)
    // for use only inside the internal operations of E
    // just like the other E's data members
}

This practice is widely used in graphics, where the inner struct will be sent as a Constant Buffer to HLSL. But I find it neat and useful in many cases.

Check if string begins with something?

First, lets extend the string object. Thanks to Ricardo Peres for the prototype, I think using the variable 'string' works better than 'needle' in the context of making it more readable.

String.prototype.beginsWith = function (string) {
    return(this.indexOf(string) === 0);
};

Then you use it like this. Caution! Makes the code extremely readable.

var pathname = window.location.pathname;
if (pathname.beginsWith('/sub/1')) {
    // Do stuff here
}

Plot multiple boxplot in one graph

In base R a formula interface with interactions (:) can be used to achieve this.

df <- read.csv("~/Desktop/TestData.csv")
df <- data.frame(stack(df[,-1]), Label=df$Label) # reshape to long format

boxplot(values ~ Label:ind, data=df, col=c("red", "limegreen"), las=2)

example

Get attribute name value of <input>

Pass class to input tag and access the name value by using class.

<input class="test-class" name='xxxxx' value=1>

<script>
    $('.test-class').attr('name');
</script>

Or you can also access the value using id.

<input id="test-id" name='xxxxx' value=1>

<script>
    $('#test-id').attr('name');
</script>

How to open a page in a new window or tab from code-behind

This code works for me:

Dim script As String = "<script type=""text/javascript"">window.open('" & URL.ToString & "');</script>"
ClientScript.RegisterStartupScript(Me.GetType, "openWindow", script)

xcode-select active developer directory error

Simply run sudo xcode-select -r which should automatically reset the path.

 -r, --reset
              Unsets any user-specified developer directory, so that the developer directory will be found via the default search mechanism. This command must  be
              run with superuser permissions (see sudo(8)), and will affect all users on the system.

Should I use 'has_key()' or 'in' on Python dicts?

in wins hands-down, not just in elegance (and not being deprecated;-) but also in performance, e.g.:

$ python -mtimeit -s'd=dict.fromkeys(range(99))' '12 in d'
10000000 loops, best of 3: 0.0983 usec per loop
$ python -mtimeit -s'd=dict.fromkeys(range(99))' 'd.has_key(12)'
1000000 loops, best of 3: 0.21 usec per loop

While the following observation is not always true, you'll notice that usually, in Python, the faster solution is more elegant and Pythonic; that's why -mtimeit is SO helpful -- it's not just about saving a hundred nanoseconds here and there!-)

How to get "wc -l" to print just the number of lines without file name?

To do this without the leading space, why not:

wc -l < file.txt | bc

Find files and tar them (with spaces)

If you have multiple files or directories and you want to zip them into independent *.gz file you can do this. Optional -type f -atime

find -name "httpd-log*.txt" -type f -mtime +1 -exec tar -vzcf {}.gz {} \;

This will compress

httpd-log01.txt
httpd-log02.txt

to

httpd-log01.txt.gz
httpd-log02.txt.gz

Creating a LINQ select from multiple tables

If you don't want to use anonymous types b/c let's say you're passing the object to another method, you can use the LoadWith load option to load associated data. It requires that your tables are associated either through foreign keys or in your Linq-to-SQL dbml model.

db.DeferredLoadingEnabled = false;
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<ObjectPermissions>(op => op.Pages)
db.LoadOptions = dlo;

var pageObject = from op in db.ObjectPermissions
         select op;

// no join needed

Then you can call

pageObject.Pages.PageID

Depending on what your data looks like, you'd probably want to do this the other way around,

DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<Pages>(p => p.ObjectPermissions)
db.LoadOptions = dlo;

var pageObject = from p in db.Pages
                 select p;

// no join needed

var objectPermissionName = pageObject.ObjectPermissions.ObjectPermissionName;

How to connect with Java into Active Directory

Here is a simple code that authenticate and make an LDAP search usin JNDI on a W2K3 :

class TestAD
{
  static DirContext ldapContext;
  public static void main (String[] args) throws NamingException
  {
    try
    {
      System.out.println("Début du test Active Directory");

      Hashtable<String, String> ldapEnv = new Hashtable<String, String>(11);
      ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
      //ldapEnv.put(Context.PROVIDER_URL,  "ldap://societe.fr:389");
      ldapEnv.put(Context.PROVIDER_URL,  "ldap://dom.fr:389");
      ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
      //ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=administrateur,cn=users,dc=societe,dc=fr");
      ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=jean paul blanc,ou=MonOu,dc=dom,dc=fr");
      ldapEnv.put(Context.SECURITY_CREDENTIALS, "pwd");
      //ldapEnv.put(Context.SECURITY_PROTOCOL, "ssl");
      //ldapEnv.put(Context.SECURITY_PROTOCOL, "simple");
      ldapContext = new InitialDirContext(ldapEnv);

      // Create the search controls         
      SearchControls searchCtls = new SearchControls();

      //Specify the attributes to return
      String returnedAtts[]={"sn","givenName", "samAccountName"};
      searchCtls.setReturningAttributes(returnedAtts);

      //Specify the search scope
      searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

      //specify the LDAP search filter
      String searchFilter = "(&(objectClass=user))";

      //Specify the Base for the search
      String searchBase = "dc=dom,dc=fr";
      //initialize counter to total the results
      int totalResults = 0;

      // Search for objects using the filter
      NamingEnumeration<SearchResult> answer = ldapContext.search(searchBase, searchFilter, searchCtls);

      //Loop through the search results
      while (answer.hasMoreElements())
      {
        SearchResult sr = (SearchResult)answer.next();

        totalResults++;

        System.out.println(">>>" + sr.getName());
        Attributes attrs = sr.getAttributes();
        System.out.println(">>>>>>" + attrs.get("samAccountName"));
      }

      System.out.println("Total results: " + totalResults);
      ldapContext.close();
    }
    catch (Exception e)
    {
      System.out.println(" Search error: " + e);
      e.printStackTrace();
      System.exit(-1);
    }
  }
}

Copy map values to vector in STL

One way is to use functor:

 template <class T1, class T2>
    class CopyMapToVec
    {
    public: 
        CopyMapToVec(std::vector<T2>& aVec): mVec(aVec){}

        bool operator () (const std::pair<T1,T2>& mapVal) const
        {
            mVec.push_back(mapVal.second);
            return true;
        }
    private:
        std::vector<T2>& mVec;
    };


int main()
{
    std::map<std::string, int> myMap;
    myMap["test1"] = 1;
    myMap["test2"] = 2;

    std::vector<int>  myVector;

    //reserve the memory for vector
    myVector.reserve(myMap.size());
    //create the functor
    CopyMapToVec<std::string, int> aConverter(myVector);

    //call the functor
    std::for_each(myMap.begin(), myMap.end(), aConverter);
}

Can I change the fill color of an svg path with CSS?

You can use this syntax but it will require some changes in the SVG file. And remove any fill/stroke from the SVG itself.

icon.svg

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1">
<!-- use symbol instead of defs and g, 
  must add viewBox on symbol just copy yhe viewbox from the svg tag itself
  must add id on symbol
-->
<symbol id="location" viewBox="0 0 430.114 430.114">
  <!-- add all the icon's paths and shapes here -->
  <path d="M356.208,107.051c-1.531-5.738-4.64-11.852-6.94-17.205C321.746,23.704,261.611,0,213.055,0   C148.054,0,76.463,43.586,66.905,133.427v18.355c0,0.766,0.264,7.647,0.639,11.089c5.358,42.816,39.143,88.32,64.375,131.136   c27.146,45.873,55.314,90.999,83.221,136.106c17.208-29.436,34.354-59.259,51.17-87.933c4.583-8.415,9.903-16.825,14.491-24.857   c3.058-5.348,8.9-10.696,11.569-15.672c27.145-49.699,70.838-99.782,70.838-149.104v-20.262   C363.209,126.938,356.581,108.204,356.208,107.051z M214.245,199.193c-19.107,0-40.021-9.554-50.344-35.939   c-1.538-4.2-1.414-12.617-1.414-13.388v-11.852c0-33.636,28.56-48.932,53.406-48.932c30.588,0,54.245,24.472,54.245,55.06   C270.138,174.729,244.833,199.193,214.245,199.193z"/>
</symbol>

icon.html

<svg><use xlink:href="file_path/location.svg#location"></use></svg>

Spark RDD to DataFrame python

I liked Arun's answer better but there is a tiny problem and I could not comment or edit the answer. sparkContext does not have createDeataFrame, sqlContext does (as Thiago mentioned). So:

from pyspark.sql import SQLContext

# assuming the spark environemnt is set and sc is spark.sparkContext 
sqlContext = SQLContext(sc)
schemaPeople = sqlContext.createDataFrame(RDDName)
schemaPeople.createOrReplaceTempView("RDDName")

How to transform numpy.matrix or array to scipy sparse matrix

In Python, the Scipy library can be used to convert the 2-D NumPy matrix into a Sparse matrix. SciPy 2-D sparse matrix package for numeric data is scipy.sparse

The scipy.sparse package provides different Classes to create the following types of Sparse matrices from the 2-dimensional matrix:

  1. Block Sparse Row matrix
  2. A sparse matrix in COOrdinate format.
  3. Compressed Sparse Column matrix
  4. Compressed Sparse Row matrix
  5. Sparse matrix with DIAgonal storage
  6. Dictionary Of Keys based sparse matrix.
  7. Row-based list of lists sparse matrix
  8. This class provides a base class for all sparse matrices.

CSR (Compressed Sparse Row) or CSC (Compressed Sparse Column) formats support efficient access and matrix operations.

Example code to Convert Numpy matrix into Compressed Sparse Column(CSC) matrix & Compressed Sparse Row (CSR) matrix using Scipy classes:

import sys                 # Return the size of an object in bytes
import numpy as np         # To create 2 dimentional matrix
from scipy.sparse import csr_matrix, csc_matrix 
# csr_matrix: used to create compressed sparse row matrix from Matrix
# csc_matrix: used to create compressed sparse column matrix from Matrix

create a 2-D Numpy matrix

A = np.array([[1, 0, 0, 0, 0, 0],\
              [0, 0, 2, 0, 0, 1],\
              [0, 0, 0, 2, 0, 0]])
print("Dense matrix representation: \n", A)
print("Memory utilised (bytes): ", sys.getsizeof(A))
print("Type of the object", type(A))

Print the matrix & other details:

Dense matrix representation: 
 [[1 0 0 0 0 0]
 [0 0 2 0 0 1]
 [0 0 0 2 0 0]]
Memory utilised (bytes):  184
Type of the object <class 'numpy.ndarray'>

Converting Matrix A to the Compressed sparse row matrix representation using csr_matrix Class:

S = csr_matrix(A)
print("Sparse 'row' matrix: \n",S)
print("Memory utilised (bytes): ", sys.getsizeof(S))
print("Type of the object", type(S))

The output of print statements:

Sparse 'row' matrix:
(0, 0) 1
(1, 2) 2
(1, 5) 1
(2, 3) 2
Memory utilised (bytes): 56
Type of the object: <class 'scipy.sparse.csr.csc_matrix'>

Converting Matrix A to Compressed Sparse Column matrix representation using csc_matrix Class:

S = csc_matrix(A)
print("Sparse 'column' matrix: \n",S)
print("Memory utilised (bytes): ", sys.getsizeof(S))
print("Type of the object", type(S))

The output of print statements:

Sparse 'column' matrix:
(0, 0) 1
(1, 2) 2
(2, 3) 2
(1, 5) 1
Memory utilised (bytes): 56
Type of the object: <class 'scipy.sparse.csc.csc_matrix'>

As it can be seen the size of the compressed matrices is 56 bytes and the original matrix size is 184 bytes.

For a more detailed explanation and code examples please refer to this article: https://limitlessdatascience.wordpress.com/2020/11/26/sparse-matrix-in-machine-learning/

What is the difference between gravity and layout_gravity in Android?

Gravity: Allow you move the content inside a container. (How sub-views will be placed).

Important: (MOVE along X-axis or Y-axis within available space).

Example: Let's say if you were to work with LinearLayout (Height: match_parent, Width: match_parent) as root level element, then you will have full frame space available; and the child views says 2 TextViews (Height: wrap_content, Width: wrap_content) inside the LinearLayout can be moved around along x/y axis using corresponding values for gravity on parent.

Layout_Gravity: Allow you to override the parent gravity behavior ONLY along x-axis.

Important: (MOVE[override] along X-axis within available space).

Example: If you keep in mind the previous example, we know gravity enabled us to move along x/y axis, i.e; the place TextViews inside LinearLayout. Let's just say LinearLayout specifies gravity: center; meaning every TextView needs to be center both vertically and horizontally. Now if we want one of the TextView to go left/right, we can override the specified gravity behavior using layout_gravity on the TextView.

Bonus: if you dig deeper, you will find out that text within the TextView act as sub-view; so if you apply the gravity on TextView, the text inside the TextView will move around. (the entire concept apply here too)

Are email addresses case sensitive?

From RFC 5321, section 2.3.11:

The standard mailbox naming convention is defined to be "local-part@domain"; contemporary usage permits a much broader set of applications than simple "user names". Consequently, and due to a long history of problems when intermediate hosts have attempted to optimize transport by modifying them, the local-part MUST be interpreted and assigned semantics only by the host specified in the domain part of the address.

So yes, the part before the "@" could be case-sensitive, since it is entirely under the control of the host system. In practice though, no widely used mail systems distinguish different addresses based on case.

The part after the @ sign however is the domain and according to RFC 1035, section 3.1,

"Name servers and resolvers must compare [domains] in a case-insensitive manner"

In short, you are safe to treat email addresses as case-insensitive.

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

Using ES6 Map (pretty well supported), you can try this:

_x000D_
_x000D_
var arr = [_x000D_
    { key: 'foo', val: 'bar' },_x000D_
    { key: 'hello', val: 'world' }_x000D_
];_x000D_
_x000D_
var result = new Map(arr.map(i => [i.key, i.val]));_x000D_
_x000D_
// When using TypeScript, need to specify type:_x000D_
// var result = arr.map((i): [string, string] => [i.key, i.val])_x000D_
_x000D_
// Unfortunately maps don't stringify well.  This is the contents in array form._x000D_
console.log("Result is: " + JSON.stringify([...result])); _x000D_
// Map {"foo" => "bar", "hello" => "world"}
_x000D_
_x000D_
_x000D_

Fastest JSON reader/writer for C++

https://github.com/quartzjer/js0n

Ugliest interface possible, but does what you ask. Zero allocations.

http://zserge.com/jsmn.html Another zero-allocation approach.

The solutions posted above all do dynamic memory allocation, hence will be inevitably end up slower at some point, depending on the data structure - and will be dangerous to include in a heap constrained environment like an embedded system.

Benchmarks of vjson, rapidjson and sajson here : http://chadaustin.me/2013/01/json-parser-benchmarking/ if you are interested in that sort of thing.

And to answer your "writer" part of the question i doubt that you could beat an efficient

printf("{%s:%s}",name,value)

implementation with any library - assuming your printf/sprintf implementation itself is lightweight of course.

EDIT: actually let me take that back, RapidJson allows on-stack allocation only through its MemoryPoolAllocator and actually makes this a default for its GenericReader. I havent done the comparison but i would expect it to be more robust than anything else listed here. It also doesnt have any dependencies, and it doesnt throw exceptions which probably makes it ultimately suitable for embedded. Fully header based lib so, easy to include anywhere.

Making HTTP Requests using Chrome Developer tools

Expanding on @dhfsk answer

Here's my workflow

  1. From Chrome DevTools, right-click the request you want to manipulate > Copy as cURL Chrome DevTools Copy as cURL

  2. Open Postman

  3. Click Import in the upper-left corner then Paste Raw Text Postman Paste Raw Text cURL from Chrome

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

Many answer above are correct but same time convoluted with other aspects of authN/authZ. What actually resolves the exception in question is this line:

services.AddScheme<YourAuthenticationOptions, YourAuthenticationHandler>(YourAuthenticationSchemeName, options =>
    {
        options.YourProperty = yourValue;
    })

Using app.config in .Net Core

It is possible to use your usual System.Configuration even in .NET Core 2.0 on Linux. Try this test example:

  1. Created a .NET Standard 2.0 Library (say MyLib.dll)
  2. Added the NuGet package System.Configuration.ConfigurationManager v4.4.0. This is needed since this package isn't covered by the meta-package NetStandard.Library v2.0.0 (I hope that changes)
  3. All your C# classes derived from ConfigurationSection or ConfigurationElement go into MyLib.dll. For example MyClass.cs derives from ConfigurationSection and MyAccount.cs derives from ConfigurationElement. Implementation details are out of scope here but Google is your friend.
  4. Create a .NET Core 2.0 app (e.g. a console app, MyApp.dll). .NET Core apps end with .dll rather than .exe in Framework.
  5. Create an app.config in MyApp with your custom configuration sections. This should obviously match your class designs in #3 above. For example:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="myCustomConfig" type="MyNamespace.MyClass, MyLib" />
  </configSections>
  <myCustomConfig>
    <myAccount id="007" />
  </myCustomConfig>
</configuration>

That's it - you'll find that the app.config is parsed properly within MyApp and your existing code within MyLib works just fine. Don't forget to run dotnet restore if you switch platforms from Windows (dev) to Linux (test).

Additional workaround for test projects

If you're finding that your App.config is not working in your test projects, you might need this snippet in your test project's .csproj (e.g. just before the ending </Project>). It basically copies App.config into your output folder as testhost.dll.config so dotnet test picks it up.

  <!-- START: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->
  <Target Name="CopyCustomContent" AfterTargets="AfterBuild">
    <Copy SourceFiles="App.config" DestinationFiles="$(OutDir)\testhost.dll.config" />
  </Target>
  <!-- END: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->

Possible to iterate backwards through a foreach?

As 280Z28 says, for an IList<T> you can just use the index. You could hide this in an extension method:

public static IEnumerable<T> FastReverse<T>(this IList<T> items)
{
    for (int i = items.Count-1; i >= 0; i--)
    {
        yield return items[i];
    }
}

This will be faster than Enumerable.Reverse() which buffers all the data first. (I don't believe Reverse has any optimisations applied in the way that Count() does.) Note that this buffering means that the data is read completely when you first start iterating, whereas FastReverse will "see" any changes made to the list while you iterate. (It will also break if you remove multiple items between iterations.)

For general sequences, there's no way of iterating in reverse - the sequence could be infinite, for example:

public static IEnumerable<T> GetStringsOfIncreasingSize()
{
    string ret = "";
    while (true)
    {
        yield return ret;
        ret = ret + "x";
    }
}

What would you expect to happen if you tried to iterate over that in reverse?

How to check Oracle database for long running queries

v$session_longops

If you look for sofar != totalwork you'll see ones that haven't completed, but the entries aren't removed when the operation completes so you can see a lot of history there too.

Authentication plugin 'caching_sha2_password' is not supported

Use pip install mysql-connector-python

Then connect like this:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",               #hostname
  user="Harish",                   # the user who has privilege to the db
  passwd="Harish96",               #password for user
  database="Factdb",               #database name
    auth_plugin = 'mysql_native_password',

)

Convert nullable bool? to bool

bool? a = null;
bool b = Convert.toBoolean(a); 

How to check if "Radiobutton" is checked?

Check if they're checked with the el.checked attribute.

Docs or this Question

_x000D_
_x000D_
let radio1 = document.querySelector('.radio1');
let radio2 = document.querySelector('.radio2');
let output = document.querySelector('.output');

function update() {
  if (radio1.checked) {
    output.innerHTML = "radio1";
  }
  else {
    output.innerHTML = "radio2";
  }
}

update();
_x000D_
<div class="radios">
  <input class="radio1" type="radio" name="radios" onchange="update()" checked>
  <input class="radio2" type="radio" name="radios" onchange="update()">
</div>
<div class="output"></div>
_x000D_
_x000D_
_x000D_

What's the point of 'meta viewport user-scalable=no' in the Google Maps API

From the v3 documentation (Developer's Guide > Concepts > Developing for Mobile Devices):

Android and iOS devices respect the following <meta> tag:

<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

This setting specifies that the map should be displayed full-screen and should not be resizable by the user. Note that the iPhone's Safari browser requires this <meta> tag be included within the page's <head> element.

Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio

You just rebuilt your project

compile fileTree(dir: 'libs', include: ['*.jar'])

A url resource that is a dot (%2E)

It is not possible. §2.3 says that "." is an unreserved character and that "URIs that differ in the replacement of an unreserved character with its corresponding percent-encoded US-ASCII octet are equivalent". Therefore, /%2E%2E/ is the same as /../, and that will get normalized away.

(This is a combination of an answer by bobince and a comment by slowpoison.)

twitter bootstrap autocomplete dropdown / combobox with Knockoutjs

Does the basic HTML5 datalist work? It's clean and you don't have to play around with the messy third party code. W3SCHOOL tutorial

The MDN Documentation is very eloquent and features examples.

How to change the color of a SwitchCompat from AppCompat library

AppCompat tinting attributs:

First, you should take a look to appCompat lib article there and to different attributs you can set:

colorPrimary: The primary branding color for the app. By default, this is the color applied to the action bar background.

colorPrimaryDark: Dark variant of the primary branding color. By default, this is the color applied to the status bar (via statusBarColor) and navigation bar (via navigationBarColor).

colorAccent: Bright complement to the primary branding color. By default, this is the color applied to framework controls (via colorControlActivated).

colorControlNormal: The color applied to framework controls in their normal state.

colorControlActivated: The color applied to framework controls in their activated (ex. checked, switch on) state.

colorControlHighlight: The color applied to framework control highlights (ex. ripples, list selectors).

colorButtonNormal: The color applied to framework buttons in their normal state.

colorSwitchThumbNormal: The color applied to framework switch thumbs in their normal state. (switch off)


If all custom switches are the same in a single activity:

With previous attributes you can define your own theme for each activity:

<style name="Theme.MyActivityTheme" parent="Theme.AppCompat.Light">
    <!-- colorPrimary is used for the default action bar background -->
    <item name="colorPrimary">@color/my_awesome_color</item>

    <!-- colorPrimaryDark is used for the status bar -->
    <item name="colorPrimaryDark">@color/my_awesome_darker_color</item>

    <!-- colorAccent is used as the default value for colorControlActivated,
         which is used to tint widgets -->
    <item name="colorAccent">@color/accent</item>

    <!-- You can also set colorControlNormal, colorControlActivated
         colorControlHighlight, and colorSwitchThumbNormal. -->

</style>

and :

<manifest>
...
    <activity
        android:name=".MainActivity" 
        android:theme="@style/Theme.MyActivityTheme">
    </activity>
...
</manifest>

If you want to have differents custom switches in a single activity:

As widget tinting in appcompat works by intercepting any layout inflation and inserting a special tint-aware version of the widget in its place (See Chris Banes post about it) you can not apply a custom style to each switch of your layout xml file. You have to set a custom Context that will tint switch with right colors.

--

To do so for pre-5.0 you need to create a Context that overlays global theme with customs attributs and then create your switches programmatically:

ContextThemeWrapper ctw = ContextThemeWrapper(getActivity(), R.style.Color1SwitchStyle); 
SwitchCompat sc = new SwitchCompat(ctw)

As of AppCompat v22.1 you can use the following XML to apply a theme to the switch widget:

<RelativeLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    ...>

    <android.support.v7.widget.SwitchCompat
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:theme="@style/Color1SwitchStyle"/>

Your custom switch theme:

<style name="Color1SwitchStyle">
    <item name="colorControlActivated">@color/my_awesome_color</item>
</style>

--

On Android 5.0 it looks like a new view attribut comes to life : android:theme (same as one use for activity declaration in manifest). Based on another Chris Banes post, with the latter you should be able to define a custom theme directly on a view from your layout xml:

<android.support.v7.widget.SwitchCompat
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:theme="@style/Color1SwitchStyle"/>

To change the track color of a SwitchCompat

Thanks to vine'th I complete my answer with a link to SO answer that explains how to specify the Foreground of the Track when Switch is Off, it's there.

Python Error: unsupported operand type(s) for +: 'int' and 'NoneType'

When none of the if test in number_translator() evaluate to true, the function returns None. The error message is the consequence of that.

Whenever you see an error that include 'NoneType' that means that you have an operand or an object that is None when you were expecting something else.

how to determine size of tablespace oracle 11g

The following query can be used to detemine tablespace and other params:

select df.tablespace_name "Tablespace",
       totalusedspace "Used MB",
       (df.totalspace - tu.totalusedspace) "Free MB",
       df.totalspace "Total MB",
       round(100 * ( (df.totalspace - tu.totalusedspace)/ df.totalspace)) "Pct. Free"
  from (select tablespace_name,
               round(sum(bytes) / 1048576) TotalSpace
          from dba_data_files 
         group by tablespace_name) df,
       (select round(sum(bytes)/(1024*1024)) totalusedspace,
               tablespace_name
          from dba_segments 
         group by tablespace_name) tu
 where df.tablespace_name = tu.tablespace_name 
   and df.totalspace <> 0;

Source: https://community.oracle.com/message/1832920

For your case if you want to know the partition name and it's size just run this query:

select owner,
       segment_name,
       partition_name,
       segment_type,
       bytes / 1024/1024 "MB" 
  from dba_segments 
 where owner = <owner_name>;

Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls

Entity Framework – Use a Guid as the primary key

Using a Guid as your tables primary key, when using Entity Framework, requires a little more effort than when using a integer. The setup process is straightforward, after you’ve read/been shown how to do it.

The process is slightly different for the Code First and Database First approaches. This post discusses both techniques.

enter image description here

Code First

Using a Guid as the primary key when taking the code first approach is simple. When creating your entity, add the DatabaseGenerated attribute to your primary key property, as shown below;

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }

Entity framework will create the column as you would expect, with a primary key and uniqueidentifier data type.

codefirst-defaultvalue

Also notice, very important, that the default value on the column has been set to (newsequentialid()). This generates a new sequential (continuous) Guid for each row. If you were so inclined, you could change this to newid()), which would result in a completely random Guid for each new row. This will be cleared each time your database gets dropped and re-created, so this works better when taking the Database First approach.

Database First

The database first approach follows a similar line to the code first approach, but you’ll have to manually edit your model to make it work.

Ensure that you edit the primary key column and add the (newsequentialid()) or (newid()) function as the default value before doing anything.

enter image description here

Next, open you EDMX diagram, select the appropriate property and open the properties window. Ensure that StoreGeneratedPattern is set to identity.

databasefirst-model

No need to give your entity an ID in your code, that will be populated for you automatically after the entity has been commited to the database;

using (ApplicationDbContext context = new ApplicationDbContext())
{
    var person = new Person
                     {
                         FirstName = "Random",
                         LastName = "Person";
                     };

    context.People.Add(person);
    context.SaveChanges();
    Console.WriteLine(person.Id);
}

Important Note: Your Guid field MUST be a primary key, or this does not work. Entity Framework will give you a rather cryptic error message!

Summary

Guid (Globally Unique Identifiers) can easily be used as primary keys in Entity Framework. A little extra effort is required to do this, depending on which approach you are taking. When using the code first approach, add the DatabaseGenerated attribute to your key field. When taking the Database First approach, explicitly set the StoredGeneratedPattern to Identity on your model.

[1]: https://i.stack.imgur.com/IxGdd.png
[2]: https://i.stack.imgur.com/Qssea.png

How to tell git to use the correct identity (name and email) for a given project?

As of Git 2.13 you can use an includeIf in your gitconfig to include a file with a different configuration based on the path of the repository where you are running your git commands.

Since a new enough Git comes with Ubuntu 18.04 I've been using this in my ~/.gitconfig quite happily.

[include]
  path = ~/.gitconfig.alias # I like to keep global aliases separate
  path = ~/.gitconfig.defaultusername # can maybe leave values unset/empty to get warned if a below path didn't match
# If using multiple identities can use per path user/email
# The trailing / is VERY important, git won't apply the config to subdirectories without it
[includeIf "gitdir:~/projects/azure/"]
  path = ~/.gitconfig.azure # user.name and user.email for Azure
[includeIf "gitdir:~/projects/gitlab/"]
  path = ~/.gitconfig.gitlab # user.name and user.email for GitLab
[includeIf "gitdir:~/projects/foss/"]
  path = ~/.gitconfig.github # user.name and user.email for GitHub

https://motowilliams.com/conditional-includes-for-git-config#disqus_thread

To use Git 2.13 you will either need to add a PPA (Ubuntu older than 18.04/Debian) or download the binaries and install (Windows/other Linux).

How can I rename a conda environment?

I'm using Conda on Windows and this answer did not work for me. But I can suggest another solution:

  • rename enviroment folder (old_name to new_name)

  • open shell and activate env with custom folder:

    conda.bat activate "C:\Users\USER_NAME\Miniconda3\envs\new_name"

  • now you can use this enviroment, but it's not on the enviroment list. Update\install\remove any package to fix it. For example, update numpy:

    conda update numpy

  • after applying any action to package, the environment will show in env list. To check this, type:

    conda env list

Selecting Folder Destination in Java?

Oracles Java Tutorial for File Choosers: http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html

Note getSelectedFile() returns the selected folder, despite the name. getCurrentDirectory() returns the directory of the selected folder.

import javax.swing.*;

public class Example
{
    public static void main(String[] args)
    {
        JFileChooser f = new JFileChooser();
        f.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); 
        f.showSaveDialog(null);

        System.out.println(f.getCurrentDirectory());
        System.out.println(f.getSelectedFile());
    }      
}

React JS onClick event handler

If you're using ES6, here's some simple example code:

import React from 'wherever_react_is';

class TestApp extends React.Component {

  getComponent(event) {
      console.log('li item clicked!');
      event.currentTarget.style.backgroundColor = '#ccc';
  }

  render() {
    return(
       <div>
         <ul>
            <li onClick={this.getComponent.bind(this)}>Component 1</li>
         </ul>
       </div>
    );
  }
}

export default TestApp;

In ES6 class bodies, functions no longer require the 'function' keyword and they don't need to be separated by commas. You can also use the => syntax as well if you wish.

Here's an example with dynamically created elements:

import React from 'wherever_react_is';

class TestApp extends React.Component {

constructor(props) {
  super(props);

  this.state = {
    data: [
      {name: 'Name 1', id: 123},
      {name: 'Name 2', id: 456}
    ]
  }
}

  getComponent(event) {
      console.log('li item clicked!');
      event.currentTarget.style.backgroundColor = '#ccc';
  }

  render() {        
       <div>
         <ul>
         {this.state.data.map(d => {
           return(
              <li key={d.id} onClick={this.getComponent.bind(this)}>{d.name}</li>
           )}
         )}
         </ul>
       </div>
    );
  }
}

export default TestApp;

Note that each dynamically created element should have a unique reference 'key'.

Furthermore, if you would like to pass the actual data object (rather than the event) into your onClick function, you will need to pass that into your bind. For example:

New onClick function:

getComponent(object) {
    console.log(object.name);
}

Passing in the data object:

{this.state.data.map(d => {
    return(
      <li key={d.id} onClick={this.getComponent.bind(this, d)}>{d.name}</li>
    )}
)}

Open popup and refresh parent page on close popup

You can access parent window using 'window.opener', so, write something like the following in the child window:

<script>
    window.onunload = refreshParent;
    function refreshParent() {
        window.opener.location.reload();
    }
</script>

Array of an unknown length in C#

Use List<> to build up an 'array' of unknown length.

Use List<>.ToArray() to return a real array, and not a List.

var list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
var array = list.ToArray();

inline conditionals in angular.js

Angular UI library has built-in directive ui-if for condition in template/Views upto angular ui 1.1.4

Example: Support in Angular UI upto ui 1.1.4

<div ui-if="array.length>0"></div>

ng-if available in all the angular version after 1.1.4

<div ng-if="array.length>0"></div>

if you have any data in array variable then only the div will appear

How to fix the "java.security.cert.CertificateException: No subject alternative names present" error?

my problem with getting this error was resolved by using the full URL "qatest.ourCompany.com/webService" instead of just "qatest/webService". Reason was that our security certificate had a wildcard i.e. "*.ourCompany.com". Once I put in the full address the exception went away. Hope this helps.

Solving a "communications link failure" with JDBC and MySQL

I just restarted MySQL (following a tip from here: https://stackoverflow.com/a/14238800) and it solved the issue.

I had the same issue on MacOS (10.10.2) and MySql (5.6.21) installed via homebrew.

The confusing thing was that one of my apps connected to the database fine and the other did not.

After trying many things on the app that threw the exception com.mysql.jdbc.CommunicationsException as suggested by the accepted answer of this question to no avail, I was surprised that restarting MySQL worked.

The cause of my issue might have been the following as suggested in the answer in the aforementioned link:

Are you using connection pool ? If yes, then try to restart the server. Probably few of the connections in your connection pool are in closed state.

Undefined symbols for architecture armv7

In my case, I'd added a framework that must be using Objective C++. I found this post:

XCode .m vs. .mm

that explained how the main.m needed to be renamed to main.mm so that the Objective-C++ classes could be compiled, too.

That fixed it for me.

How can I format the output of a bash command in neat columns

If your output is delimited by tabs a quick solution would be to use the tabs command to adjust the size of your tabs.

tabs 20
keys | awk '{ print $1"\t\t" $2 }'

How to make an installer for my C# application?

  1. Add a new install project to your solution.
  2. Add targets from all projects you want to be installed.
  3. Configure pre-requirements and choose "Check for .NET 3.5 and SQL Express" option. Choose the location from where missing components must be installed.
  4. Configure your installer settings - company name, version, copyright, etc.
  5. Build and go!

http://localhost/ not working on Windows 7. What's the problem?

I had the exact same issue, and the solution is what someone has already said:

In the taskbar, click on the WAMP icon.

Go to Apache-->Service-->Install Service

Then go back by clicking and selecting Apache-->Service-->Start/Resume Service

This will allow the localhost function to work (keep in mind I had already changed the host file located under c:\windows\system32\drivers\etc to remove the # from the 127.0.0.1 line)

If you need to edit that file still, you need to right click on it and select Properties. Then go to the Security tab, and click the Advanced button. You then need to select the Users, click Edit and select "Full Control". This will enable you to edit it.

That being said, you need to ALSO install the MySQL service following the same procedure.

MySQL-->Service-->Install Service

Then go back by right clicking yet again and selecting MySQL-->Service-->Start/Resume Service.

And that should fix it all up in Windows 7!

Razor-based view doesn't see referenced assemblies

Your Project FOLDER name needs to be the same. If your Project or Solution name is different, then MVC will hurt you.

Example : If you create a new Application and it gets the default name Webapplicaiton1, then this namespace will be created. So, let us say that you dont want to have this namespace, so from the VS you change everywhere you can see to "MyNamespace". You also search and replace all code from "Webapplication1" and replace it with "MyNamespace". This also changes web.config file, so that it inculdes

Now everything will work, except Razor views.

RazorViews cannot find it, because there is some kind of strange dependency on the FOLDERNAME of the project. It is terrible design.

I have tested this semi-thoroughly by copying my files into a new solution, and the only difference being the foldername.

Adding a new line/break tag in XML

The solution to this question is:

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="dummy.xsl"?>
  <item>
     <summary>
        <![CDATA[Tootsie roll tiramisu macaroon wafer carrot cake. <br />      
                 Danish topping sugar plum tart bonbon caramels cake.]]>
     </summary>
  </item>

by adding the <br /> inside the the <![CDATA]]> this allows the line to break, thus creating a new line!

MySQL - Operand should contain 1 column(s)

Your subquery is selecting two columns, while you are using it to project one column (as part of the outer SELECT clause). You can only select one column from such a query in this context.

Consider joining to the users table instead; this will give you more flexibility when selecting what columns you want from users.

SELECT
topics.id,
topics.name,
topics.post_count,
topics.view_count,
COUNT( posts.solved_post ) AS solved_post,
users.username AS posted_by,
users.id AS posted_by_id

FROM topics

LEFT OUTER JOIN posts ON posts.topic_id = topics.id
LEFT OUTER JOIN users ON users.id = posts.posted_by

WHERE topics.cat_id = :cat
GROUP BY topics.id

How to make Twitter Bootstrap menu dropdown on hover rather than click

Here's my technique that adds a slight delay before the menu is closed after you stop hovering on the menu or the toggle button. The <button> that you would normally click to display the nav menu is #nav_dropdown.

$(function() {
  var delay_close_it, nav_menu_timeout, open_it;
  nav_menu_timeout = void 0;
  open_it = function() {
    if (nav_menu_timeout) {
      clearTimeout(nav_menu_timeout);
      nav_menu_timeout = null;
    }
    return $('.navbar .dropdown').addClass('open');
  };
  delay_close_it = function() {
    var close_it;
    close_it = function() {
      return $('.navbar .dropdown').removeClass('open');
    };
    return nav_menu_timeout = setTimeout(close_it, 500);
  };
  $('body').on('mouseover', '#nav_dropdown, #nav_dropdown *', open_it).on('mouseout', '#nav_dropdown', delay_close_it);
  return $('body').on('mouseover', '.navbar .dropdown .dropdown-menu', open_it).on('mouseout', '.navbar .dropdown .dropdown-menu', delay_close_it);
});

Find index of last occurrence of a sub-string using T-SQL

Reverse both your string and your substring, then search for the first occurrence.

What is causing ImportError: No module named pkg_resources after upgrade of Python on os X?

[UPDATE] TL;DR pkg_resources is provided by either Distribute or setuptools.

[UPDATE 2] As announced at PyCon 2013, the Distribute and setuptools projects have re-merged. Distribute is now deprecated and you should just use the new current setuptools. Try this:

curl -O https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py
python ez_setup.py

Or, better, use a current pip as the high level interface and which will use setuptools under the covers.

[Longer answer for OP's specific problem]:

You don't say in your question but I'm assuming you upgraded from the Apple-supplied Python (2.5 on 10.5 or 2.6.1 on 10.6) or that you upgraded from a python.org Python 2.5. In any of those cases, the important point is that each Python instance has its own library, including its own site-packages library, which is where additional packages are installed. (And none of them use /usr/local/lib by default, by the way.) That means you'll need to install those additional packages you need for your new python 2.6. The easiest way to do this is to first ensure that the new python2.6 appears first on your search $PATH (that is, typing python2.6 invokes it as expected); the python2.6 installer should have modified your .bash_profile to put its framework bin directory at the front of $PATH. Then install easy_install using setuptools following the instructions there. The pkg_resources module is also automatically installed by this step.

Then use the newly-installed version of easy_install (or pip) to install ipython.

easy_install ipython

or

pip install ipython

It should automatically get installed to the correct site-packages location for that python instance and you should be good to go.

Doing a cleanup action just before Node.js exits

async-exit-hook seems to be the most up-to-date solution for handling this problem. It's a forked/re-written version of exit-hook that supports async code before exiting.

CSS Selector that applies to elements with two classes

Chain both class selectors (without a space in between):

.foo.bar {
    /* Styles for element(s) with foo AND bar classes */
}

If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar in this case) instead, regardless of what other classes you list.

To illustrate how other browsers and IE6 interpret this, consider this CSS:

* {
    color: black;
}

.foo.bar {
    color: red;
}

Output on supported browsers is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Not selected, black text [3] -->

Output on IE6 is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Selected, red text [2] -->

Footnotes:

  • Supported browsers:
    1. Not selected as this element only has class foo.
    2. Selected as this element has both classes foo and bar.
    3. Not selected as this element only has class bar.

  • IE6:
    1. Not selected as this element doesn't have class bar.
    2. Selected as this element has class bar, regardless of any other classes listed.

How to fix "containing working copy admin area is missing" in SVN?

I came across this problem when replacing a third party API library with a newer version, and none of the solutions here really worked for me because I wanted to replace the SVN version with the local version. My solution was as follows:

1) Move the offending folder to my home dir, delete it from SVN and commit:

mv foldercausingproblem ~/
svn --force delete foldercausingproblem
svn commit --message "Temporary removing folder with old API"

2) Put the folder back, add it to SVN and commit again:

mv ~/foldercausingproblem ./
svn --force add .
svn commit --message "Finally all working!"

Slightly irritating to have to commit twice, but it seems to have worked fine.

How to display the function, procedure, triggers source code in postgresql?

There are many possibilities. Simplest way is to just use pgAdmin and get this from SQL window. However if you want to get this programmatically then examinate pg_proc and pg_trigger system catalogs or routines and triggers views from information schema (that's SQL standard way, but it might not cover all features especially PostgreSQL-specific). For example:

SELECT
    routine_definition 
FROM
    information_schema.routines 
WHERE
    specific_schema LIKE 'public'
    AND routine_name LIKE 'functionName';

Git add all files modified, deleted, and untracked?

The following answer only applies to Git version 1.x, but to Git version 2.x.

You want git add -A:

git add -A stages All;

git add . stages new and modified, without deleted;

git add -u stages modified and deleted, without new.

align images side by side in html

Here is how I would do it, (however I would use an external style sheet for this project and all others. just makes things easier to work with. Also this example is with html5.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
  .container {
      display:inline-block;
  }
</style>
</head>
<body>

  <div class="container">
    <figure>
    <img src="http://placehold.it/350x150" height="200" width="200">
    <figcaption>This is image 1</figcaption>
    </figure>

    <figure>
    <img class="middle-img" src="http://placehold.it/350x150"/ height="200" width="200">
    <figcaption>This is image 2</figcaption>
    </figure>

    <figure>
    <img src="http://placehold.it/350x150" height="200" width="200">
    <figcaption>This is image 3</figcaption>
    </figure>

  </div>
</body>
</html>

jQuery hyperlinks - href value?

Why use a <a href>? I solve it like this:

<span class='a'>fake link</span>

And style it with:

.a {text-decoration:underline; cursor:pointer;}

You can easily access it with jQuery:

$(".a").click();

Javascript: How to generate formatted easy-to-read JSON straight from an object?

JSON.stringify takes more optional arguments.

Try:

 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab

From:

How can I beautify JSON programmatically?

Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre> tag to get newlines to show.

Current timestamp as filename in Java

Date, SimpleDateFormat and whatever classes are required on the I/O side of things (there are many possibilities).

Accessing dict keys like an attribute?

Caveat emptor: For some reasons classes like this seem to break the multiprocessing package. I just struggled with this bug for awhile before finding this SO: Finding exception in python multiprocessing

Adding options to a <select> using jQuery?

$('#select_id').append($('<option>',{ value: v, text: t }));

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

My silly mistake was this: change != to ==

if(convertView != null) { // <---- HERE 
                LayoutInflater layoutInflater = LayoutInflater.from(z_selBoardElectricity.this);
                convertView = layoutInflater.inflate(R.layout.listview_board_alert, null);

                TextView textView = convertView.findViewById(R.id.board_name_tv);
                ImageView imageView = convertView.findViewById(R.id.board_imageview);

                textView.setText(text_list.get(position));
                imageView.setImageDrawable(imageAddressList.get(position));

                convertView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.putExtra("MESSAGE", text_list.get(pos));
                        setResult(98, intent);
                        finish();
                    }
                });
            }
return convertView;

How to get the cell value by column name not by index in GridView in asp.net

It is possible to use the data field name, if not the title so easily, which solved the problem for me. For ASP.NET & VB:

e.g. For a string:

Dim Encoding = e.Row.DataItem("Encoding").ToString().Trim()

e.g. For an integer:

Dim MsgParts = Convert.ToInt32(e.Row.DataItem("CalculatedMessageParts").ToString())

Where is NuGet.Config file located in Visual Studio project?

There are multiple nuget packages read in the following order:

  1. First the NuGetDefaults.Config file. You will find this in %ProgramFiles(x86)%\NuGet\Config.
  2. The computer-level file.
  3. The user-level file. You will find this in %APPDATA%\NuGet\nuget.config.
  4. Any file named nuget.config beginning from the root of your drive up to the directory where nuget.exe is called.
  5. The config file you specify in the -configfile option when calling nuget.exe

You can find more information here.

How to clear APC cache entries?

This is not stated in the documentation, but to clear the opcode cache you must do:

apc_clear_cache('opcode');

EDIT: This seems to only apply to some older versions of APC..

No matter what version you are using you can't clear mod_php or fastcgi APC cache from a php cli script since the cli script will run from a different process as mod_php or fastcgi. You must call apc_clear_cache() from within the process (or child process) which you want to clear the cache for. Using curl to run a simple php script is one such approach.

Running powershell script within python script, how to make python print the powershell output while it is running

  1. Make sure you can run powershell scripts (it is disabled by default). Likely you have already done this. http://technet.microsoft.com/en-us/library/ee176949.aspx

    Set-ExecutionPolicy RemoteSigned
    
  2. Run this python script on your powershell script helloworld.py:

    # -*- coding: iso-8859-1 -*-
    import subprocess, sys
    
    p = subprocess.Popen(["powershell.exe", 
                  "C:\\Users\\USER\\Desktop\\helloworld.ps1"], 
                  stdout=sys.stdout)
    p.communicate()
    

This code is based on python3.4 (or any 3.x series interpreter), though it should work on python2.x series as well.

C:\Users\MacEwin\Desktop>python helloworld.py
Hello World

how to get login option for phpmyadmin in xampp

Step 1:

Locate phpMyAdmin installation path.

Step 2:

Open phpMyAdmin/config.inc.php in your favourite text editor. Copy config.sample.inc.php to config.inc.php if it's missing.

Step 3:

Search for $cfg['Servers'][$i]['auth_type'] = 'config';

Replace it with $cfg['Servers'][$i]['auth_type'] = 'cookie';

Validation to check if password and confirm password are same is not working

function validate()
{
  var a=documents.forms["yourformname"]["yourpasswordfieldname"].value;
  var b=documents.forms["yourformname"]["yourconfirmpasswordfieldname"].value;
  if(!(a==b))
  {
    alert("both passwords are not matching");
    return false;
  }
  return true;
}

HTML5 Canvas: Zooming

Just try this out:

<!DOCTYPE HTML>
<html>
    <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
        <style>
            body {
                margin: 0px;
                padding: 0px;
            }

            #wrapper {
                position: relative;
                border: 1px solid #9C9898;
                width: 578px;
                height: 200px;
            }

            #buttonWrapper {
                position: absolute;
                width: 30px;
                top: 2px;
                right: 2px;
            }

            input[type =
            "button"] {
                padding: 5px;
                width: 30px;
                margin: 0px 0px 2px 0px;
            }
        </style>
        <script>
            function draw(scale, translatePos){
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d");

                // clear canvas
                context.clearRect(0, 0, canvas.width, canvas.height);

                context.save();
                context.translate(translatePos.x, translatePos.y);
                context.scale(scale, scale);
                context.beginPath(); // begin custom shape
                context.moveTo(-119, -20);
                context.bezierCurveTo(-159, 0, -159, 50, -59, 50);
                context.bezierCurveTo(-39, 80, 31, 80, 51, 50);
                context.bezierCurveTo(131, 50, 131, 20, 101, 0);
                context.bezierCurveTo(141, -60, 81, -70, 51, -50);
                context.bezierCurveTo(31, -95, -39, -80, -39, -50);
                context.bezierCurveTo(-89, -95, -139, -80, -119, -20);
                context.closePath(); // complete custom shape
                var grd = context.createLinearGradient(-59, -100, 81, 100);
                grd.addColorStop(0, "#8ED6FF"); // light blue
                grd.addColorStop(1, "#004CB3"); // dark blue
                context.fillStyle = grd;
                context.fill();

                context.lineWidth = 5;
                context.strokeStyle = "#0000ff";
                context.stroke();
                context.restore();
            }

            window.onload = function(){
                var canvas = document.getElementById("myCanvas");

                var translatePos = {
                    x: canvas.width / 2,
                    y: canvas.height / 2
                };

                var scale = 1.0;
                var scaleMultiplier = 0.8;
                var startDragOffset = {};
                var mouseDown = false;

                // add button event listeners
                document.getElementById("plus").addEventListener("click", function(){
                    scale /= scaleMultiplier;
                    draw(scale, translatePos);
                }, false);

                document.getElementById("minus").addEventListener("click", function(){
                    scale *= scaleMultiplier;
                    draw(scale, translatePos);
                }, false);

                // add event listeners to handle screen drag
                canvas.addEventListener("mousedown", function(evt){
                    mouseDown = true;
                    startDragOffset.x = evt.clientX - translatePos.x;
                    startDragOffset.y = evt.clientY - translatePos.y;
                });

                canvas.addEventListener("mouseup", function(evt){
                    mouseDown = false;
                });

                canvas.addEventListener("mouseover", function(evt){
                    mouseDown = false;
                });

                canvas.addEventListener("mouseout", function(evt){
                    mouseDown = false;
                });

                canvas.addEventListener("mousemove", function(evt){
                    if (mouseDown) {
                        translatePos.x = evt.clientX - startDragOffset.x;
                        translatePos.y = evt.clientY - startDragOffset.y;
                        draw(scale, translatePos);
                    }
                });

                draw(scale, translatePos);
            };



            jQuery(document).ready(function(){
               $("#wrapper").mouseover(function(e){
                  $('#status').html(e.pageX +', '+ e.pageY);
               }); 
            })  
        </script>
    </head>
    <body onmousedown="return false;">
        <div id="wrapper">
            <canvas id="myCanvas" width="578" height="200">
            </canvas>
            <div id="buttonWrapper">
                <input type="button" id="plus" value="+"><input type="button" id="minus" value="-">
            </div>
        </div>
        <h2 id="status">
        0, 0
        </h2>
    </body>
</html>

Works perfect for me with zooming and mouse movement.. you can customize it to mouse wheel up & down Njoy!!!

Here is fiddle for this Fiddle

How many bytes in a JavaScript string?

Note that if you're targeting node.js you can use Buffer.from(string).length:

var str = "\u2620"; // => "?"
str.length; // => 1 (character)
Buffer.from(str).length // => 3 (bytes)

Fastest way to tell if two files have the same contents in Unix/Linux?

Because I suck and don't have enough reputation points I can't add this tidbit in as a comment.

But, if you are going to use the cmp command (and don't need/want to be verbose) you can just grab the exit status. Per the cmp man page:

If a FILE is '-' or missing, read standard input. Exit status is 0 if inputs are the same, 1 if different, 2 if trouble.

So, you could do something like:

STATUS="$(cmp --silent $FILE1 $FILE2; echo $?)"  # "$?" gives exit status for each comparison

if [[ $STATUS -ne 0 ]]; then  # if status isn't equal to 0, then execute code
    DO A COMMAND ON $FILE1
else
    DO SOMETHING ELSE
fi

EDIT: Thanks for the comments everyone! I updated the test syntax here. However, I would suggest you use Vasili's answer if you are looking for something similar to this answer in readability, style, and syntax.

Selecting an element in iFrame jQuery

var iframe = $('iframe'); // or some other selector to get the iframe
$('[tokenid=' + token + ']', iframe.contents()).addClass('border');

Also note that if the src of this iframe is pointing to a different domain, due to security reasons, you will not be able to access the contents of this iframe in javascript.

How to run regasm.exe from command line other than Visual Studio command prompt?

Like Cheeso said:

You don't need the directory on your path. You could put it on your path, but you don't NEED to do that. If you are calling regasm rarely, or calling it from a batch file, you may find it is simpler to just invoke regasm via the fully-qualified pathname on the exe, eg:

%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\regasm.exe MyAssembly.dll

How to discard uncommitted changes in SourceTree?

Ok I just noticed that my question was already answered in the question title.

To unstage files use

git reset HEAD /file/name

And to undo the changes to a file

git checkout -- /file/name

If you have a batch of files inside a folder you can undo the whole folder

git checkout -- /folder/name

Note that all these commands are already displayed when you git status

Here I created a dummy repo and listed all 3 possibilities

# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       modified:   test
#
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       modified:   test2
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       test3

What is the "-->" operator in C/C++?

One book I read (I don't remember correctly which book) stated: Compilers try to parse expressions to the biggest token by using the left right rule.

In this case, the expression:

x-->0

Parses to biggest tokens:

token 1: x
token 2: --
token 3: >
token 4: 0
conclude: x-- > 0

The same rule applies to this expression:

a-----b

After parse:

token 1: a
token 2: --
token 3: --
token 4: -
token 5: b
conclude: (a--)-- - b

I hope this helps to understand the complicated expression ^^

How to escape JSON string?

I nice one-liner, used JsonConvert as others have but added substring to remove the added quotes and backslash.

 var escapedJsonString = JsonConvert.ToString(JsonString).Substring(1, JsonString.Length - 2);

Best way to do multiple constructors in PHP

Let me add my grain of sand here

I personally like adding a constructors as static functions that return an instance of the class (the object). The following code is an example:

 class Person
 {
     private $name;
     private $email;

     public static function withName($name)
     {
         $person = new Person();
         $person->name = $name;

         return $person;
     }

     public static function withEmail($email)
     {
         $person = new Person();
         $person->email = $email;

         return $person;
     }
 }

Note that now you can create instance of the Person class like this:

$person1 = Person::withName('Example');
$person2 = Person::withEmail('yo@mi_email.com');

I took that code from:

http://alfonsojimenez.com/post/30377422731/multiple-constructors-in-php

SVG Positioning

There are two ways to group multiple SVG shapes and position the group:

The first to use <g> with transform attribute as Aaron wrote. But you can't just use a x attribute on the <g> element.

The other way is to use nested <svg> element.

<svg id="parent">
   <svg id="group1" x="10">
      <!-- some shapes -->
   </svg>
</svg>

In this way, the #group1 svg is nested in #parent, and the x=10 is relative to the parent svg. However, you can't use transform attribute on <svg> element, which is quite the contrary of <g> element.

Regular expression for address field validation

Just to add to Serzas' answer(since don't have enough reps. to comment). alphabets and numbers can effectively be replaced by \w for words. Additionally apostrophe,comma,period and hyphen doesn't necessarily need a backslash. My requirement also involved front and back slashes so \/ and finally whitespaces with \s. The working regex for me ,as such was :

pattern: "[\w',-\\/.\s]"

What does '?' do in C++?

You can just rewrite it as:

int qempty(){ return(f==r);}

Which does the same thing as said in the other answers.

Can I fade in a background image (CSS: background-image) with jQuery?

With modern browser i prefer a much lightweight approach with a bit of Js and CSS3...

transition: background 300ms ease-in 200ms;

Look at this demo:

http://codepen.io/nicolasbonnici/pen/gPVNbr

Compile throws a "User-defined type not defined" error but does not go to the offending line of code

I had exactly the same problem (always seems to occur when I try to implement a Interface onto a userform. Download and install Code Cleaner from here. This is a freeware utility that has saved me on numerous occasions. With your VBA project open, run the "Clean Code..." option. Make sure you check the "backup project" and/or "export all code modules" to safe locations before running the clean. As far as I understand it, this utility exports and then re-imports all modules and classes, which eliminates compiler errors that have crept into the code. Worked like a charm for me! Good luck.

How to receive JSON as an MVC 5 action method parameter

There are a couple issues here. First, you need to make sure to bind your JSON object back to the model in the controller. This is done by changing

data: JSON.stringify(usersRoles),

to

data: { model: JSON.stringify(usersRoles) },

Secondly, you aren't binding types correctly with your jquery call. If you remove

contentType: "application/json; charset=utf-8",

it will inherently bind back to a string.

All together, use the first ActionResult method and the following jquery ajax call:

    jQuery.ajax({
        type: "POST",
        url: "@Url.Action("AddUser")",
        dataType: "json",
        data: { model: JSON.stringify(usersRoles) },
        success: function (data) { alert(data); },
        failure: function (errMsg) {
        alert(errMsg);
        }
   });

How do I run PHP code when a user clicks on a link?

If you haven't yet installed jquery (because you're just a beginner or something), use this bit of code:

<a href="#" onclick="thisfunction()">link</a>

<script type="text/javascript">
function thisfunction(){
    var x = new XMLHttpRequest();
    x.open("GET","function.php",true);
    x.send();
    return false;
}
</script>

How do I convert NSMutableArray to NSArray?

i was search for the answer in swift 3 and this question was showed as first result in search and i get inspired the answer from it so here is the swift 3 code

let array: [String] = nsMutableArrayObject.copy() as! [String]

What is the difference between an annotated and unannotated tag?

TL;DR

The difference between the commands is that one provides you with a tag message while the other doesn't. An annotated tag has a message that can be displayed with git-show(1), while a tag without annotations is just a named pointer to a commit.

More About Lightweight Tags

According to the documentation: "To create a lightweight tag, don’t supply any of the -a, -s, or -m options, just provide a tag name". There are also some different options to write a message on annotated tags:

  • When you use git tag <tagname>, Git will create a tag at the current revision but will not prompt you for an annotation. It will be tagged without a message (this is a lightweight tag).
  • When you use git tag -a <tagname>, Git will prompt you for an annotation unless you have also used the -m flag to provide a message.
  • When you use git tag -a -m <msg> <tagname>, Git will tag the commit and annotate it with the provided message.
  • When you use git tag -m <msg> <tagname>, Git will behave as if you passed the -a flag for annotation and use the provided message.

Basically, it just amounts to whether you want the tag to have an annotation and some other information associated with it or not.

Catching "Maximum request length exceeded"

You can solve this by increasing the maximum request length and execution time out in your web.config:

-Please Clarify the maximum execution time out grater then 1200

<?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <httpRuntime maxRequestLength="102400" executionTimeout="1200" /> </system.web> </configuration>

How to implement a ConfigurationSection with a ConfigurationElementCollection

Try inheriting from ConfigurationSection. This blog post by Phil Haack has an example.

Confirmed, per the documentation for IConfigurationSectionHandler:

In .NET Framework version 2.0 and above, you must instead derive from the ConfigurationSection class to implement the related configuration section handler.

Why is a primary-foreign key relation required when we can join without it?

The main reason for primary and foreign keys is to enforce data consistency.

A primary key enforces the consistency of uniqueness of values over one or more columns. If an ID column has a primary key then it is impossible to have two rows with the same ID value. Without that primary key, many rows could have the same ID value and you wouldn't be able to distinguish between them based on the ID value alone.

A foreign key enforces the consistency of data that points elsewhere. It ensures that the data which is pointed to actually exists. In a typical parent-child relationship, a foreign key ensures that every child always points at a parent and that the parent actually exists. Without the foreign key you could have "orphaned" children that point at a parent that doesn't exist.

Set mouse focus and move cursor to end of input using jQuery

2 artlung's answer: It works with second line only in my code (IE7, IE8; Jquery v1.6):

var input = $('#some_elem');
input.focus().val(input.val());

Addition: if input element was added to DOM using JQuery, a focus is not set in IE. I used a little trick:

input.blur().focus().val(input.val());

How to efficiently check if variable is Array or Object (in NodeJS & V8)?

I know it's been a while, but I thought i would update the answer since there are new (faster and simpler) ways to solve this problem. Since ECMAscript 5.1 yo can use the isArray() method avaiable in the Array class.

Yo can see it's documentation in MDN here.

I think you shouldn't have a compatibility problem nowadays, but just in case, if you add this to your code you should be always safe that Array.isArray() is polyfilled:

if (!Array.isArray) {
  Array.isArray = function(arg) {
    return Object.prototype.toString.call(arg) === '[object Array]';
  };
}

cmake error 'the source does not appear to contain CMakeLists.txt'

This reply may be late but it may help users having similar problem. The opencv-contrib (available at https://github.com/opencv/opencv_contrib/releases) contains extra modules but the build procedure has to be done from core opencv (available at from https://github.com/opencv/opencv/releases) modules.

Follow below steps (assuming you are building it using CMake GUI)

  1. Download openCV (from https://github.com/opencv/opencv/releases) and unzip it somewhere on your computer. Create build folder inside it

  2. Download exra modules from OpenCV. (from https://github.com/opencv/opencv_contrib/releases). Ensure you download the same version.

  3. Unzip the folder.

  4. Open CMake

  5. Click Browse Source and navigate to your openCV folder.

  6. Click Browse Build and navigate to your build Folder.

  7. Click the configure button. You will be asked how you would like to generate the files. Choose Unix-Makefile from the drop down menu and Click OK. CMake will perform some tests and return a set of red boxes appear in the CMake Window.

  8. Search for "OPENCV_EXTRA_MODULES_PATH" and provide the path to modules folder (e.g. /Users/purushottam_d/Programs/OpenCV3_4_5_contrib/modules)

  9. Click Configure again, then Click Generate.

  10. Go to build folder

# cd build
# make
# sudo make install
  1. This will install the opencv libraries on your computer.

How to run a makefile in Windows?

You can install GNU make with chocolatey, a well-maintained package manager, which will add make to the global path and runs on all CLIs (powershell, git bash, cmd, etc…) saving you a ton of time in both maintenance and initial setup to get make running.

  1. Install the chocolatey package manager for Windows
    compatible to Windows 7+ / Windows Server 2003+

  2. Run choco install make

I am not affiliated with choco, but I highly recommend it, so far it has never let me down and I do have a talent for breaking software unintentionally.

Correct way to integrate jQuery plugins in AngularJS

i have alreay 2 situations where directives and services/factories didnt play well.

the scenario is that i have (had) a directive that has dependency injection of a service, and from the directive i ask the service to make an ajax call (with $http).

in the end, in both cases the ng-Repeat did not file at all, even when i gave the array an initial value.

i even tried to make a directive with a controller and an isolated-scope

only when i moved everything to a controller and it worked like magic.

example about this here Initialising jQuery plugin (RoyalSlider) in Angular JS

Convert Enumeration to a Set/List

You can use Collections.list() to convert an Enumeration to a List in one line:

List<T> list = Collections.list(enumeration);

There's no similar method to get a Set, however you can still do it one line:

Set<T> set = new HashSet<T>(Collections.list(enumeration));

how to calculate percentage in python

marks = raw_input('Enter your Obtain marks:')
outof = raw_input('Enter Out of marks:')
marks = int(marks)
outof = int(outof)
per = marks*100/outof
print 'Your Percentage is:'+str(per)

Note : raw_input() function is used to take input from console and its return string formatted value. So we need to convert into integer otherwise it give error of conversion.

How to print jquery object/array

var arrofobject = [{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}];

$.each(arrofobject, function(index, val) {
    console.log(val.category);
});

Mailto: Body formatting

Use %0D%0A for a line break in your body

Example (Demo):

<a href="mailto:[email protected]?subject=Suggestions&body=name:%0D%0Aemail:">test</a>?
                                                                  ^^^^^^

Implementing a Custom Error page on an ASP.Net website

Is it a spelling error in your closing tag ie:

</CustomErrors> instead of </CustomError>?

open link of google play store in mobile version android

You can use Android Intents library for opening your application page at Google Play like that:

Intent intent = IntentUtils.openPlayStore(getApplicationContext());
startActivity(intent);

Deserialize JSON with C#

Newtonsoft.JSON is a good solution for these kind of situations. Also Newtonsof.JSON is faster than others, such as JavaScriptSerializer, DataContractJsonSerializer.

In this sample, you can the following:

var jsonData = JObject.Parse("your JSON data here");

Then you can cast jsonData to JArray, and you can use a for loop to get data at each iteration.

Also, I want to add something:

for (int i = 0; (JArray)jsonData["data"].Count; i++)
{
    var data = jsonData[i - 1];
}

Working with dynamic object and using Newtonsoft serialize is a good choice.

How do I draw a circle in iOS Swift?

A simple function drawing a circle on the middle of your window frame, using a multiplicator percentage

/// CGFloat is a multiplicator from self.view.frame.width
func drawCircle(withMultiplicator coefficient: CGFloat) {

    let radius = self.view.frame.width / 2 * coefficient

    let circlePath = UIBezierPath(arcCenter: self.view.center, radius: radius, startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2), clockwise: true)
    let shapeLayer = CAShapeLayer()
    shapeLayer.path = circlePath.cgPath

    //change the fill color
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.strokeColor = UIColor.darkGray.cgColor
    shapeLayer.lineWidth = 2.0

    view.layer.addSublayer(shapeLayer)
}

Get ID of element that called a function

You can use 'this' in event handler:

document.getElementById("preview").onmouseover = function() {
    alert(this.id);
}

Or pass event object to handler as follows:

document.getElementById("preview").onmouseover = function(evt) {
    alert(evt.target.id);
}

It's recommended to use attachEvent(for IE < 9)/addEventListener(IE9 and other browsers) to attach events. Example above is for brevity.

function myHandler(evt) {
    alert(evt.target.id);
}

var el = document.getElementById("preview");
if (el.addEventListener){
    el.addEventListener('click', myHandler, false); 
} else if (el.attachEvent){
    el.attachEvent('onclick', myHandler);
}

What is this spring.jpa.open-in-view=true property in Spring Boot?

The OSIV Anti-Pattern

Instead of letting the business layer decide how it’s best to fetch all the associations that are needed by the View layer, OSIV (Open Session in View) forces the Persistence Context to stay open so that the View layer can trigger the Proxy initialization, as illustrated by the following diagram.

enter image description here

  • The OpenSessionInViewFilter calls the openSession method of the underlying SessionFactory and obtains a new Session.
  • The Session is bound to the TransactionSynchronizationManager.
  • The OpenSessionInViewFilter calls the doFilter of the javax.servlet.FilterChain object reference and the request is further processed
  • The DispatcherServlet is called, and it routes the HTTP request to the underlying PostController.
  • The PostController calls the PostService to get a list of Post entities.
  • The PostService opens a new transaction, and the HibernateTransactionManager reuses the same Session that was opened by the OpenSessionInViewFilter.
  • The PostDAO fetches the list of Post entities without initializing any lazy association.
  • The PostService commits the underlying transaction, but the Session is not closed because it was opened externally.
  • The DispatcherServlet starts rendering the UI, which, in turn, navigates the lazy associations and triggers their initialization.
  • The OpenSessionInViewFilter can close the Session, and the underlying database connection is released as well.

At first glance, this might not look like a terrible thing to do, but, once you view it from a database perspective, a series of flaws start to become more obvious.

The service layer opens and closes a database transaction, but afterward, there is no explicit transaction going on. For this reason, every additional statement issued from the UI rendering phase is executed in auto-commit mode. Auto-commit puts pressure on the database server because each transaction issues a commit at end, which can trigger a transaction log flush to disk. One optimization would be to mark the Connection as read-only which would allow the database server to avoid writing to the transaction log.

There is no separation of concerns anymore because statements are generated both by the service layer and by the UI rendering process. Writing integration tests that assert the number of statements being generated requires going through all layers (web, service, DAO) while having the application deployed on a web container. Even when using an in-memory database (e.g. HSQLDB) and a lightweight webserver (e.g. Jetty), these integration tests are going to be slower to execute than if layers were separated and the back-end integration tests used the database, while the front-end integration tests were mocking the service layer altogether.

The UI layer is limited to navigating associations which can, in turn, trigger N+1 query problems. Although Hibernate offers @BatchSize for fetching associations in batches, and FetchMode.SUBSELECT to cope with this scenario, the annotations are affecting the default fetch plan, so they get applied to every business use case. For this reason, a data access layer query is much more suitable because it can be tailored to the current use case data fetch requirements.

Last but not least, the database connection is held throughout the UI rendering phase which increases connection lease time and limits the overall transaction throughput due to congestion on the database connection pool. The more the connection is held, the more other concurrent requests are going to wait to get a connection from the pool.

Spring Boot and OSIV

Unfortunately, OSIV (Open Session in View) is enabled by default in Spring Boot, and OSIV is really a bad idea from a performance and scalability perspective.

So, make sure that in the application.properties configuration file, you have the following entry:

spring.jpa.open-in-view=false

This will disable OSIV so that you can handle the LazyInitializationException the right way.

Starting with version 2.0, Spring Boot issues a warning when OSIV is enabled by default, so you can discover this problem long before it affects a production system.

Null & empty string comparison in Bash

First of all, note you are not using the variable correctly:

if [ "pass_tc11" != "" ]; then
#     ^
#     missing $

Anyway, to check if a variable is empty or not you can use -z --> the string is empty:

if [ ! -z "$pass_tc11" ]; then
   echo "hi, I am not empty"
fi

or -n --> the length is non-zero:

if [ -n "$pass_tc11" ]; then
   echo "hi, I am not empty"
fi

From man test:

-z STRING

the length of STRING is zero

-n STRING

the length of STRING is nonzero

Samples:

$ [ ! -z "$var" ] && echo "yes"
$

$ var=""
$ [ ! -z "$var" ] && echo "yes"
$

$ var="a"
$ [ ! -z "$var" ] && echo "yes"
yes

$ var="a"
$ [ -n "$var" ] && echo "yes"
yes

General error: 1364 Field 'user_id' doesn't have a default value

So, after After reviewing the code again, I found the error. I am wondering how no one notice that! In the above code I wrote

Post::create(request([  // <= the error is Here!!!
    'body' => request('body'),
    'title' => request('title'),
    'user_id' => auth()->id()
]));

actually, there is no need for the request function warping the body of the create function.

// this is right
Post::create([
    'body' => request('body'),
    'title' => request('title'),
    'user_id' => auth()->id()
]);

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

Simply comparing the textfield object to the empty string "" is not the right way to go about this. You have to compare the textfield's text property, as it is a compatible type and holds the information you are looking for.

@IBAction func Button(sender: AnyObject) {
    if textField1.text == "" || textField2.text == "" {
        // either textfield 1 or 2's text is empty
    }
}

Swift 2.0:

Guard:

guard let text = descriptionLabel.text where !text.isEmpty else {
    return
}
text.characters.count  //do something if it's not empty

if:

if let text = descriptionLabel.text where !text.isEmpty
{
    //do something if it's not empty  
    text.characters.count  
}

Swift 3.0:

Guard:

guard let text = descriptionLabel.text, !text.isEmpty else {
    return
}
text.characters.count  //do something if it's not empty

if:

if let text = descriptionLabel.text, !text.isEmpty
{
    //do something if it's not empty  
    text.characters.count  
}

Excel: replace part of cell's string value

What you need to do is as follows:

  1. List item
  2. Select the entire column by clicking once on the corresponding letter or by simply selecting the cells with your mouse.
  3. Press Ctrl+H.
  4. You are now in the "Find and Replace" dialog. Write "Author" in the "Find what" text box.
  5. Write "Authoring" in the "Replace with" text box.
  6. Click the "Replace All" button.

That's it!

how to get a list of dates between two dates in java

With java 8

public Stream<LocalDate> getDaysBetween(LocalDate startDate, LocalDate endDate) {
    return IntStream.range(0, (int) DAYS.between(startDate, endDate)).mapToObj(startDate::plusDays);
}

Angular - How to apply [ngStyle] conditions

<ion-col size="12">
  <ion-card class="box-shadow ion-text-center background-size"
  *ngIf="data != null"
  [ngStyle]="{'background-image': 'url(' + data.headerImage + ')'}">

  </ion-card>

How do I use hexadecimal color strings in Flutter?

No need functions

For example to give color to a container using colorcode

Container (

color:Color(0xff000000)

)

Here the 0xff is the format followed by color code

set the width of select2 input (through Angular-ui directive)

You can try like this. It works for me

$("#MISSION_ID").select2();

On hide/show or ajax request, we have to reinitialize the select2 plugin

For example:

$("#offialNumberArea").show();
$("#eventNameArea").hide();

$('.selectCriteria').change(function(){
    var thisVal = $(this).val();
    if(thisVal == 'sailor'){
        $("#offialNumberArea").show();
        $("#eventNameArea").hide();
    }
    else
    {
        $("#offialNumberArea").hide();
        $("#eventNameArea").show();
        $("#MISSION_ID").select2();
    }
});

React Native: Possible unhandled promise rejection

catch function in your api should either return some data which could be handled by Api call in React class or throw new error which should be caught using a catch function in your React class code. Latter approach should be something like:

return fetch(url)
.then(function(response){
  return response.json();
})
.then(function(json){
  return {
    city: json.name,
    temperature: kelvinToF(json.main.temp),
    description: _.capitalize(json.weather[0].description)
  }
})
.catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
 // ADD THIS THROW error
  throw error;
});

Then in your React Class:

Api(region.latitude, region.longitude)
  .then((data) => {
    console.log(data);
    this.setState(data);
  }).catch((error)=>{
     console.log("Api call error");
     alert(error.message);
  });

Pushing to Git returning Error Code 403 fatal: HTTP request failed

I just got the same problem and just figured out what's cause.

Github seems only supports ssh way to read&write the repo, although https way also displayed 'Read&Write'.

So you need to change your repo config on your PC to ssh way:

  1. edit .git/config file under your repo directory
  2. find url=entry under section [remote "origin"]
  3. change it from url=https://[email protected]/derekerdmann/lunch_call.git to [email protected]/derekerdmann/lunch_call.git. that is, change all the texts before @ symbol to ssh://git
  4. Save config file and quit. now you could use git push origin master to sync your repo on GitHub

How to use JavaScript regex over multiple lines?

You do not specify your environment and version of Javascript (ECMAscript), and I realise this post was from 2009, but just for completeness, with the release of ECMA2018 we can now use the s flag to cause . to match '\n', see https://stackoverflow.com/a/36006948/141801

Thus:

let s = 'I am a string\nover several\nlines.';
console.log('String: "' + s + '".');

let r = /string.*several.*lines/s; // Note 's' modifier
console.log('Match? ' + r.test(s); // 'test' returns true

This is a recent addition and will not work in many current environments, for example Node v8.7.0 does not seem to recognise it, but it works in Chromium, and I'm using it in a Typescript test I'm writing and presumably it will become more mainstream as time goes by.

height: calc(100%) not working correctly in CSS

First off - check with Firebug(or what ever your preference is) whether the css property is being interpreted by the browser. Sometimes the tool used will give you the problem right there, so no more hunting.

Second off - check compatibility: http://caniuse.com/#feat=calc

And third - I ran into some problems a few hours ago and just resolved it. It's the smallest thing but it kept me busy for 30 minutes.

Here's how my CSS looked

#someElement {
    height:calc(100%-100px);
    height:-moz-calc(100%-100px);
    height:-webkit-calc(100%-100px);
}

Looks right doesn't it? WRONG Here's how it should look:

#someElement {
    height:calc(100% - 100px);
    height:-moz-calc(100% - 100px);
    height:-webkit-calc(100% - 100px);
}

Looks the same right?

Notice the spaces!!! Checked android browser, Firefox for android, Chrome for android, Chrome and Firefox for Windows and Internet Explorer 11. All of them ignored the CSS if there were no spaces.

Hope this helps someone.

Change image size via parent div

Yours:

  <div style="height:42px;width:42px">
  <img src="http://someimage.jpg">

Is it okay to use this code?

  <div class= "box">
  <img src= "http://someimage.jpg" class= "img">
  </div>

  <style type="text/css">
  .box{width: 42; height: 42;}
  .img{width: 20; height:20;}
  </style>

Just trying, though late. :3 For someone else reading this, letme know if the way i wrote the code were not good. im new in this kind of language. and i still want to learn more.