Programs & Examples On #Nsmanagedobject

NSManagedObject is a generic class that implements all the basic behavior required of a Core Data model object. NSManagedObject is available in OS X v10.4 and later and Available in iOS 3.0 and later .

Delete/Reset all entries in Core Data?

You can still delete the file programmatically, using the NSFileManager:removeItemAtPath:: method.

NSPersistentStore *store = ...;
NSError *error;
NSURL *storeURL = store.URL;
NSPersistentStoreCoordinator *storeCoordinator = ...;
[storeCoordinator removePersistentStore:store error:&error];
[[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error];

Then, just add the persistent store back to ensure it is recreated properly.

The programmatic way for iterating through each entity is both slower and prone to error. The use for doing it that way is if you want to delete some entities and not others. However you still need to make sure you retain referential integrity or you won't be able to persist your changes.

Just removing the store and recreating it is both fast and safe, and can certainly be done programatically at runtime.

Update for iOS5+

With the introduction of external binary storage (allowsExternalBinaryDataStorage or Store in External Record File) in iOS 5 and OS X 10.7, simply deleting files pointed by storeURLs is not enough. You'll leave the external record files behind. Since the naming scheme of these external record files is not public, I don't have a universal solution yet. – an0 May 8 '12 at 23:00

How to explain callbacks in plain english? How are they different from calling one function from another function?

How to explain callbacks in plain English?

In plain English, a callback function is like a Worker who "calls back" to his Manager when he has completed a Task.

How are they different from calling one function from another function taking some context from the calling function?

It is true that you are calling a function from another function, but the key is that the callback is treated like an Object, so you can change which Function to call based on the state of the system (like the Strategy Design Pattern).

How can their power be explained to a novice programmer?

The power of callbacks can easily be seen in AJAX-style websites which need to pull data from a server. Downloading the new data may take some time. Without callbacks, your entire User Interface would "freeze up" while downloading the new data, or you would need to refresh the entire page rather than just part of it. With a callback, you can insert a "now loading" image and replace it with the new data once it is loaded.

Some code without a callback:

function grabAndFreeze() {
    showNowLoading(true);
    var jsondata = getData('http://yourserver.com/data/messages.json');
    /* User Interface 'freezes' while getting data */
    processData(jsondata);
    showNowLoading(false);
    do_other_stuff(); // not called until data fully downloaded
}

function processData(jsondata) { // do something with the data
   var count = jsondata.results ? jsondata.results.length : 0;
   $('#counter_messages').text(['Fetched', count, 'new items'].join(' '));
   $('#results_messages').html(jsondata.results || '(no new messages)');
}

With Callback:

Here is an example with a callback, using jQuery's getJSON:

function processDataCB(jsondata) { // callback: update UI with results
   showNowLoading(false);
   var count = jsondata.results ? jsondata.results.length : 0;
   $('#counter_messages').text(['Fetched', count, 'new items'].join(' '));
   $('#results_messages').html(jsondata.results || '(no new messages)');
}

function grabAndGo() { // and don't freeze
    showNowLoading(true);
    $('#results_messages').html(now_loading_image);
    $.getJSON("http://yourserver.com/data/messages.json", processDataCB);
    /* Call processDataCB when data is downloaded, no frozen User Interface! */
    do_other_stuff(); // called immediately
}

With Closure:

Often the callback needs to access state from the calling function using a closure, which is like the Worker needing to get information from the Manager before he can complete his Task. To create the closure, you can inline the function so it sees the data in the calling context:

/* Grab messages, chat users, etc by changing dtable. Run callback cb when done.*/
function grab(dtable, cb) { 
    if (null == dtable) { dtable = "messages"; }
    var uiElem = "_" + dtable;
    showNowLoading(true, dtable);
    $('#results' + uiElem).html(now_loading_image);
    $.getJSON("http://yourserver.com/user/"+dtable+".json", cb || function (jsondata) {
       // Using a closure: can "see" dtable argument and uiElem variables above.
       var count = jsondata.results ? jsondata.results.length : 0, 
           counterMsg = ['Fetched', count, 'new', dtable].join(' '),
           // no new chatters/messages/etc
           defaultResultsMsg = ['(no new ', dtable, ')'].join(''); 
       showNowLoading(false, dtable);
       $('#counter' + uiElem).text(counterMsg);
       $('#results'+ uiElem).html(jsondata.results || defaultResultsMsg);
    });
    /* User Interface calls cb when data is downloaded */

    do_other_stuff(); // called immediately
}

Usage:

// update results_chatters when chatters.json data is downloaded:
grab("chatters"); 
// update results_messages when messages.json data is downloaded
grab("messages"); 
// call myCallback(jsondata) when "history.json" data is loaded:
grab("history", myCallback); 

Closure

Finally, here is a definition of closure from Douglas Crockford:

Functions can be defined inside of other functions. The inner function has access to the vars and parameters of the outer function. If a reference to an inner function survives (for example, as a callback function), the outer function's vars also survive.

See also:

How to increase the gap between text and underlining in CSS

I was able to Do it using the U (Underline Tag)

u {
    text-decoration: none;
    position: relative;
}
u:after {
    content: '';
    width: 100%;
    position: absolute;
    left: 0;
    bottom: 1px;
    border-width: 0 0 1px;
    border-style: solid;
}


<a href="" style="text-decoration:none">
    <div style="text-align: right; color: Red;">
        <u> Shop Now</u>
    </div>
</a>

Where is the visual studio HTML Designer?

The solution of creating a new HTML file with HTML (Web Forms) Designer worked for that file but not for other, individual HTML files that I wanted to edit.

I did find the Open With option in the Open File dialogue and was able to select the HTML (Web Forms) Editor there. Having clicked the "Set as Default" option in that window, VS then remembered to use that editor when I opened other HTML files.

codeigniter, result() vs. result_array()

result_array() is faster, result() is easier

How do I know which version of Javascript I'm using?

Rather than finding which version you are using you can rephrase your question to "which version of ECMA script does my browser's JavaScript/JSscript engine conform to".

For IE :

alert(@_jscript_version);      //IE

Refer Squeegy's answer for non-IE versions :)

How to increase editor font size?

In my case it was because of my 4K screen too thin to read. Then u need to change from monospace In my case it was because of my 4K screen too thin to read. Then u need to change from Monospaced to Consolas.

Settings --> Color Scheme Font --> Font --> Consolas

Python: How do I make a subclass from a superclass?

class BankAccount:

  def __init__(self, balance=0):
    self.balance = int(balance)

  def checkBalance(self): ## Checking opening balance....
    return self.balance

  def deposit(self, deposit_amount=1000): ## takes in cash deposit amount and updates the balance accordingly.
    self.deposit_amount = deposit_amount
    self.balance += deposit_amount
    return self.balance

  def withdraw(self, withdraw_amount=500): ## takes in cash withdrawal amount and updates the balance accordingly
    if self.balance < withdraw_amount: ## if amount is greater than balance return `"invalid transaction"`
        return 'invalid transaction'
    else:
      self.balance -= withdraw_amount
      return self.balance


class MinimumBalanceAccount(BankAccount): #subclass MinimumBalanceAccount of the BankAccount class

    def __init__(self,balance=0, minimum_balance=500):
        BankAccount.__init__(self, balance=0)
        self.minimum_balance = minimum_balance
        self.balance = balance - minimum_balance
        #print "Subclass MinimumBalanceAccount of the BankAccount class created!"

    def MinimumBalance(self):
        return self.minimum_balance

c = BankAccount()
print(c.deposit(50))
print(c.withdraw(10))

b = MinimumBalanceAccount(100, 50)
print(b.deposit(50))
print(b.withdraw(10))
print(b.MinimumBalance())

Launch Pycharm from command line (terminal)

On Mac OSX

Update 2019/05 Now this can be done in the JetBrains Toolbox app. You can set it once with the Toolbox, for all of your JetBrain IDEs.


As of 2019.1 EAP, the Create Commmand Line Launcher option is not available in the Tools menu anymore. My solution is to use the following alias in my bash/zsh profile:

Make sure that you run chmod -x ...../pycharm to make the binary executable.

# in your ~/.profile or other rc file to the effect.

alias pycharm="open -a '$(ls -r /Users/geyang/Library/Application\ Support/JetBrains/Toolbox/apps/PyCharm-P/**/PyCharm*.app/Contents/MacOS/pycharm)'"

Assigning multiple styles on an HTML element

The syntax you used is problematic. In html, an attribute (ex: style) has a value delimited by double quotes. In that case, the value of the style attribute is a css list of selectors. Try this:

<h2 style="text-align:center; font-family:tahoma">TITLE</h2>

Is there an equivalent of CSS max-width that works in HTML emails?

Yes, there is a way to emulate max-width using a table, thus giving you both responsive and Outlook-friendly layout. What's more, this solution doesn't require conditional comments.

Suppose you want the equivalent of a centered div with max-width of 350px. You create a table, set the width to 100%. The table has three cells in a row. Set the width of the center TD to 350 (using the HTML width attribute, not CSS), and there you go.

If you want your content aligned left instead of centered, just leave out the first empty cell.

Example:

<table border="0" cellspacing="0" width="100%">
    <tr>
        <td></td>
        <td width="350">The width of this cell should be a maximum of 
                  350 pixels, but shrink to widths less than 350 pixels.
        </td>
        <td></td>
     </tr>
</table> 

In the jsfiddle I give the table a border so you can see what's going on, but obviously you wouldn't want one in real life:

http://jsfiddle.net/YcwM7/

Issue when importing dataset: `Error in scan(...): line 1 did not have 145 elements`

This simple method solved the problem for me: Copy the content of your dataset, open an empty Excel sheet, choose "Paste Special" -> "Values", and save. Import the new file instead.

(I tried all the existing solutions, and none worked for me. My old dataset appeared to have no missing values, space, special characters, or embedded formulas.)

Correct way to create rounded corners in Twitter Bootstrap

Without less, ans simply for a given div :

In a css :

.footer {
background-color: #ab0000;
padding-top: 40px;
padding-bottom: 10px;
border-radius:5px;
}

In html :

 <div class="footer">
        <p>blablabla</p>
      </div>

File input 'accept' attribute - is it useful?

Yes, it is extremely useful in browsers that support it, but the "limiting" is as a convenience to users (so they are not overwhelmed with irrelevant files) rather than as a way to prevent them from uploading things you don't want them uploading.

It is supported in

  • Chrome 16 +
  • Safari 6 +
  • Firefox 9 +
  • IE 10 +
  • Opera 11 +

Here is a list of content types you can use with it, followed by the corresponding file extensions (though of course you can use any file extension):

application/envoy   evy
application/fractals    fif
application/futuresplash    spl
application/hta hta
application/internet-property-stream    acx
application/mac-binhex40    hqx
application/msword  doc
application/msword  dot
application/octet-stream    *
application/octet-stream    bin
application/octet-stream    class
application/octet-stream    dms
application/octet-stream    exe
application/octet-stream    lha
application/octet-stream    lzh
application/oda oda
application/olescript   axs
application/pdf pdf
application/pics-rules  prf
application/pkcs10  p10
application/pkix-crl    crl
application/postscript  ai
application/postscript  eps
application/postscript  ps
application/rtf rtf
application/set-payment-initiation  setpay
application/set-registration-initiation setreg
application/vnd.ms-excel    xla
application/vnd.ms-excel    xlc
application/vnd.ms-excel    xlm
application/vnd.ms-excel    xls
application/vnd.ms-excel    xlt
application/vnd.ms-excel    xlw
application/vnd.ms-outlook  msg
application/vnd.ms-pkicertstore sst
application/vnd.ms-pkiseccat    cat
application/vnd.ms-pkistl   stl
application/vnd.ms-powerpoint   pot
application/vnd.ms-powerpoint   pps
application/vnd.ms-powerpoint   ppt
application/vnd.ms-project  mpp
application/vnd.ms-works    wcm
application/vnd.ms-works    wdb
application/vnd.ms-works    wks
application/vnd.ms-works    wps
application/winhlp  hlp
application/x-bcpio bcpio
application/x-cdf   cdf
application/x-compress  z
application/x-compressed    tgz
application/x-cpio  cpio
application/x-csh   csh
application/x-director  dcr
application/x-director  dir
application/x-director  dxr
application/x-dvi   dvi
application/x-gtar  gtar
application/x-gzip  gz
application/x-hdf   hdf
application/x-internet-signup   ins
application/x-internet-signup   isp
application/x-iphone    iii
application/x-javascript    js
application/x-latex latex
application/x-msaccess  mdb
application/x-mscardfile    crd
application/x-msclip    clp
application/x-msdownload    dll
application/x-msmediaview   m13
application/x-msmediaview   m14
application/x-msmediaview   mvb
application/x-msmetafile    wmf
application/x-msmoney   mny
application/x-mspublisher   pub
application/x-msschedule    scd
application/x-msterminal    trm
application/x-mswrite   wri
application/x-netcdf    cdf
application/x-netcdf    nc
application/x-perfmon   pma
application/x-perfmon   pmc
application/x-perfmon   pml
application/x-perfmon   pmr
application/x-perfmon   pmw
application/x-pkcs12    p12
application/x-pkcs12    pfx
application/x-pkcs7-certificates    p7b
application/x-pkcs7-certificates    spc
application/x-pkcs7-certreqresp p7r
application/x-pkcs7-mime    p7c
application/x-pkcs7-mime    p7m
application/x-pkcs7-signature   p7s
application/x-sh    sh
application/x-shar  shar
application/x-shockwave-flash   swf
application/x-stuffit   sit
application/x-sv4cpio   sv4cpio
application/x-sv4crc    sv4crc
application/x-tar   tar
application/x-tcl   tcl
application/x-tex   tex
application/x-texinfo   texi
application/x-texinfo   texinfo
application/x-troff roff
application/x-troff t
application/x-troff tr
application/x-troff-man man
application/x-troff-me  me
application/x-troff-ms  ms
application/x-ustar ustar
application/x-wais-source   src
application/x-x509-ca-cert  cer
application/x-x509-ca-cert  crt
application/x-x509-ca-cert  der
application/ynd.ms-pkipko   pko
application/zip zip
audio/basic au
audio/basic snd
audio/mid   mid
audio/mid   rmi
audio/mpeg  mp3
audio/x-aiff    aif
audio/x-aiff    aifc
audio/x-aiff    aiff
audio/x-mpegurl m3u
audio/x-pn-realaudio    ra
audio/x-pn-realaudio    ram
audio/x-wav wav
image/bmp   bmp
image/cis-cod   cod
image/gif   gif
image/ief   ief
image/jpeg  jpe
image/jpeg  jpeg
image/jpeg  jpg
image/pipeg jfif
image/svg+xml   svg
image/tiff  tif
image/tiff  tiff
image/x-cmu-raster  ras
image/x-cmx cmx
image/x-icon    ico
image/x-portable-anymap pnm
image/x-portable-bitmap pbm
image/x-portable-graymap    pgm
image/x-portable-pixmap ppm
image/x-rgb rgb
image/x-xbitmap xbm
image/x-xpixmap xpm
image/x-xwindowdump xwd
message/rfc822  mht
message/rfc822  mhtml
message/rfc822  nws
text/css    css
text/h323   323
text/html   htm
text/html   html
text/html   stm
text/iuls   uls
text/plain  bas
text/plain  c
text/plain  h
text/plain  txt
text/richtext   rtx
text/scriptlet  sct
text/tab-separated-values   tsv
text/webviewhtml    htt
text/x-component    htc
text/x-setext   etx
text/x-vcard    vcf
video/mpeg  mp2
video/mpeg  mpa
video/mpeg  mpe
video/mpeg  mpeg
video/mpeg  mpg
video/mpeg  mpv2
video/quicktime mov
video/quicktime qt
video/x-la-asf  lsf
video/x-la-asf  lsx
video/x-ms-asf  asf
video/x-ms-asf  asr
video/x-ms-asf  asx
video/x-msvideo avi
video/x-sgi-movie   movie
x-world/x-vrml  flr
x-world/x-vrml  vrml
x-world/x-vrml  wrl
x-world/x-vrml  wrz
x-world/x-vrml  xaf
x-world/x-vrml  xof

How to play or open *.mp3 or *.wav sound file in c++ program?

http://sfml-dev.org/documentation/2.0/classsf_1_1Music.php

SFML does not have mp3 support as another has suggested. What I always do is use Audacity and make all my music into ogg, and leave all my sound effects as wav.

Loading and playing a wav is simple (crude example):

http://www.sfml-dev.org/tutorials/2.0/audio-sounds.php

#include <SFML/Audio.hpp>
...
sf::SoundBuffer buffer;
if (!buffer.loadFromFile("sound.wav")){
    return -1;
}
sf::Sound sound;
sound.setBuffer(buffer);
sound.play();

Streaming an ogg music file is also simple:

#include <SFML/Audio.hpp>
...
sf::Music music;
if (!music.openFromFile("music.ogg"))
    return -1; // error
music.play();

How to store image in SQL Server database tables column

Insert Into FEMALE(ID, Image)
Select '1', BulkColumn 
from Openrowset (Bulk 'D:\thepathofimage.jpg', Single_Blob) as Image

You will also need admin rights to run the query.

Using classes with the Arduino

On this page, the Arduino sketch defines a couple of Structs (plus a couple of methods) which are then called in the setup loop and main loop. Simple enough to interpret, even for a barely-literate programmer like me.

How to print object array in JavaScript?

Simple function to alert contents of an object or an array .
Call this function with an array or string or an object it alerts the contents.

Function

function print_r(printthis, returnoutput) {
    var output = '';

    if($.isArray(printthis) || typeof(printthis) == 'object') {
        for(var i in printthis) {
            output += i + ' : ' + print_r(printthis[i], true) + '\n';
        }
    }else {
        output += printthis;
    }
    if(returnoutput && returnoutput == true) {
        return output;
    }else {
        alert(output);
    }
}

Usage

var data = [1, 2, 3, 4];
print_r(data);

How to scroll to the bottom of a RecyclerView? scrollToPosition doesn't work

You must hide AppBarLayout before scrollToPosition if you are using him

How to initialize List<String> object in Java?

Can't instantiate an interface but there are few implementations:

JDK2

List<String> list = Arrays.asList("one", "two", "three");

JDK7

//diamond operator
List<String> list = new ArrayList<>();
list.add("one");
list.add("two");
list.add("three");

JDK8

List<String> list = Stream.of("one", "two", "three").collect(Collectors.toList());

JDK9

// creates immutable lists, so you can't modify such list 
List<String> immutableList = List.of("one", "two", "three");

// if we want mutable list we can copy content of immutable list 
// to mutable one for instance via copy-constructor (which creates shallow copy)
List<String> mutableList = new ArrayList<>(List.of("one", "two", "three"));

Plus there are lots of other ways supplied by other libraries like Guava.

List<String> list = Lists.newArrayList("one", "two", "three");

Vue Js - Loop via v-for X times (in a range)

You can use an index in a range and then access the array via its index:

<ul>
  <li v-for="index in 10" :key="index">
    {{ shoppingItems[index].name }} - {{ shoppingItems[index].price }}
  </li>
</ul>

You can also check the Official Documentation for more information.

How do pointer-to-pointer's work in C? (and when might you use them?)

How it works: It is a variable that can store another pointer.

When would you use them : Many uses one of them is if your function wants to construct an array and return it to the caller.

//returns the array of roll nos {11, 12} through paramater
// return value is total number of  students
int fun( int **i )
{
    int *j;
    *i = (int*)malloc ( 2*sizeof(int) );
    **i = 11;  // e.g., newly allocated memory 0x2000 store 11
    j = *i;
    j++;
    *j = 12; ;  // e.g., newly allocated memory 0x2004 store 12

    return 2;
}

int main()
{
    int *i;
    int n = fun( &i ); // hey I don't know how many students are in your class please send all of their roll numbers.
    for ( int j=0; j<n; j++ )
        printf( "roll no = %d \n", i[j] );

    return 0;
}

Match all elements having class name starting with a specific string

It's not a direct answer to the question, however I would suggest in most cases to simply set multiple classes to each element:

<div class="myclass one"></div>
<div class="myclass two></div>
<div class="myclass three"></div>

In this way you can set rules for all myclass elements and then more specific rules for one, two and three.

.myclass { color: #f00; }

.two { font-weight: bold; }

etc.

How to delete zero components in a vector in Matlab?

I often ended up doing things like this. Therefore I tried to write a simple function that 'snips' out the unwanted elements in an easy way. This turns matlab logic a bit upside down, but looks good:

b = snip(a,'0')

you can find the function file at: http://www.mathworks.co.uk/matlabcentral/fileexchange/41941-snip-m-snip-elements-out-of-vectorsmatrices

It also works with all other 'x', nan or whatever elements.

R color scatter plot points based on values

It's better to create a new factor variable using cut(). I've added a few options using ggplot2 also.

df <- data.frame(
  X1=seq(0, 5, by=0.001),
  X2=rnorm(df$X1, mean = 3.5, sd = 1.5)
)

# Create new variable for plotting
df$Colour <- cut(df$X2, breaks = c(-Inf, 1, 3, +Inf), 
                 labels = c("low", "medium", "high"), 
                 right = FALSE)

### Base Graphics

plot(df$X1, df$X2, 
     col = df$Colour, ylim = c(0, 10), xlab = "POS", 
     ylab = "CS", main = "Plot Title", pch = 21)

plot(df$X1,df$X2, 
     col = df$Colour, ylim = c(0, 10), xlab = "POS", 
     ylab = "CS", main = "Plot Title", pch = 19, cex = 0.5)

# Using `with()` 

with(df, 
     plot(X1, X2, xlab="POS", ylab="CS", col = Colour, pch=21, cex=1.4)
     )

# Using ggplot2
library(ggplot2)

# qplot()
qplot(df$X1, df$X2, colour = df$Colour)

# ggplot()
p <- ggplot(df, aes(X1, X2, colour = Colour)) 
p <- p + geom_point() + xlab("POS") + ylab("CS")
p

p + facet_grid(Colour~., scales = "free")

Checking if a variable is not nil and not zero in ruby

ok, after 5 years have passed....

if discount.try :nonzero?
  ...
end

It's important to note that try is defined in the ActiveSupport gem, so it is not available in plain ruby.

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data

My solution is a bit funny.I never thought that would it be as easy as save as with UTF-8 codec.I'm using notepad++(v5.6.8).I didn't notice that I saved it with ANSI codec initially. I'm using separate file to place all localized dictionary. I found my solution under 'Encoding' tab from my Notepad++.I select 'Encoding in UTF-8 without BOM' and save it. It works brilliantly.

Site does not exist error for a2ensite

Try like this..

NameVirtualHost *:80
<VirtualHost *:80>
    ServerAdmin [email protected]
    ServerName www.cmsplus.dev
    ServerAlias cmsplus.dev

    DocumentRoot /var/www/cmsplus.dev/public

    LogLevel warn
    ErrorLog /var/www/cmsplus.dev/log/error.log
    CustomLog /var/www/cmsplus.dev/log/access.log combined
</VirtualHost>

and add entry in /etc/hosts

127.0.0.1 www.cmsplus.dev

restart apache..

TypeScript enum to object array

Here's the simple function with correct typing I use

/**
 * Helper to produce an array of enum values.
 * @param enumeration Enumeration object.
 */
export function enumToArray<T, G extends keyof T = keyof T>(enumeration: T): T[G][] {
  // tslint:disable: comment-format

  // enum Colors {
  //   WHITE = 0,
  //   BLACK = 1,
  // }
  // Object.values(Colors) will produce ['WHITE', 'BLACK', 0, 1]

  // So, simply slice the second half
  const enumValues = Object.values(enumeration);
  return enumValues.slice(enumValues.length / 2, enumValues.length) as T[G][];
}

Usage example:

enum Colors {
  Red = 1,
  Blue = 2,
}
enumToArray(Colors)

What is the command to exit a Console application in C#?

Console applications will exit when the main function has finished running. A "return" will achieve this.

    static void Main(string[] args)
    {
        while (true)
        {
            Console.WriteLine("I'm running!");
            return; //This will exit the console application's running thread
        }
    }

If you're returning an error code you can do it this way, which is accessible from functions outside of the initial thread:

    System.Environment.Exit(-1);

Font is not available to the JVM with Jasper Reports

sudo apt-get install msttcorefonts works (on our Ubuntu development environment), but is not a very good solution.

Instead, we bundled the fonts with our application based on this tip. Their JAR file bundles the following fonts,

  • Arial
  • Times New Roman
  • Courier New
  • Comic Sans MS
  • Georgia
  • Verdana
  • Monospaced

Direct Link to download jar: Maven ver 1.0. DynamicFonts

Calling a javascript function in another js file

declare function in global scope with window

first.js

window.fn1 = function fn1() {
    alert("external fn clicked");
}

second.js

document.getElementById("btn").onclick = function() {
   fn1();
}

include like this

<script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>

How can I suppress all output from a command using Bash?

In your script you can add the following to the lines that you know are going to give an output:

some_code 2>>/dev/null

Or else you can also try

some_code >>/dev/null

How to show loading spinner in jQuery?

Note that you must use asynchronous calls for spinners to work (at least that is what caused mine to not show until after the ajax call and then swiftly went away as the call had finished and removed the spinner).

$.ajax({
        url: requestUrl,
        data: data,
        dataType: 'JSON',
        processData: false,
        type: requestMethod,
        async: true,                         <<<<<<------ set async to true
        accepts: 'application/json',
        contentType: 'application/json',
        success: function (restResponse) {
            // something here
        },
        error: function (restResponse) {
            // something here                
        }
    });

Using global variables in a function

In case you have a local variable with the same name, you might want to use the globals() function.

globals()['your_global_var'] = 42

How do I subscribe to all topics of a MQTT broker

Concrete example

mosquitto.org is very active (at the time of this posting). This is a nice smoke test for a MQTT subscriber linux device:

mosquitto_sub -h test.mosquitto.org -t "#" -v

The "#" is a wildcard for topics and returns all messages (topics): the server had a lot of traffic, so it returned a 'firehose' of messages.

If your MQTT device publishes a topic of irisys/V4D-19230005/ to the test MQTT broker , then you could filter the messages:

mosquitto_sub -h test.mosquitto.org -t "irisys/V4D-19230005/#" -v

Options:

  • -h the hostname (default MQTT port = 1883)
  • -t precedes the topic

How can I get terminal output in python?

>>> import subprocess
>>> cmd = [ 'echo', 'arg1', 'arg2' ]
>>> output = subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0]
>>> print output
arg1 arg2

>>> 

There is a bug in using of the subprocess.PIPE. For the huge output use this:

import subprocess
import tempfile

with tempfile.TemporaryFile() as tempf:
    proc = subprocess.Popen(['echo', 'a', 'b'], stdout=tempf)
    proc.wait()
    tempf.seek(0)
    print tempf.read()

Rebuild or regenerate 'ic_launcher.png' from images in Android Studio

On Android Studio 0.5.8 I managed to change my icon set by right clicking on the 'res' folder and selecting New > Image Asset. This brings you to the icon screen you are presented when creating the application, here after you change the icon it confirms that it will replace all the icons. Confirm and done.

Recursively look for files with a specific extension

Though using find command can be useful here, the shell itself provides options to achieve this requirement without any third party tools. The bash shell provides an extended glob support option using which you can get the file names under recursive paths that match with the extensions you want.

The extended option is extglob which needs to be set using the shopt option as below. The options are enabled with the -s support and disabled with he -u flag. Additionally you could use couple of options more i.e. nullglob in which an unmatched glob is swept away entirely, replaced with a set of zero words. And globstar that allows to recurse through all the directories

shopt -s extglob nullglob globstar

Now all you need to do is form the glob expression to include the files of a certain extension which you can do as below. We use an array to populate the glob results because when quoted properly and expanded, the filenames with special characters would remain intact and not get broken due to word-splitting by the shell.

For example to list all the *.csv files in the recursive paths

fileList=(**/*.csv)

The option ** is to recurse through the sub-folders and *.csv is glob expansion to include any file of the extensions mentioned. Now for printing the actual files, just do

printf '%s\n' "${fileList[@]}"

Using an array and doing a proper quoted expansion is the right way when used in shell scripts, but for interactive use, you could simply use ls with the glob expression as

ls -1 -- **/*.csv

This could very well be expanded to match multiple files i.e. file ending with multiple extension (i.e. similar to adding multiple flags in find command). For example consider a case of needing to get all recursive image files i.e. of extensions *.gif, *.png and *.jpg, all you need to is

ls -1 -- **/+(*.jpg|*.gif|*.png)

This could very well be expanded to have negate results also. With the same syntax, one could use the results of the glob to exclude files of certain type. Assume you want to exclude file names with the extensions above, you could do

excludeResults=()
excludeResults=(**/!(*.jpg|*.gif|*.png))
printf '%s\n' "${excludeResults[@]}"

The construct !() is a negate operation to not include any of the file extensions listed inside and | is an alternation operator just as used in the Extended Regular Expressions library to do an OR match of the globs.

Note that these extended glob support is not available in the POSIX bourne shell and its purely specific to recent versions of bash. So if your are considering portability of the scripts running across POSIX and bash shells, this option wouldn't be right.

Check if a string is a date value

Use Regular expression to validate it.

isDate('2018-08-01T18:30:00.000Z');

isDate(_date){
        const _regExp  = new RegExp('^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]+)?(Z)?$');
        return _regExp.test(_date);
    }

Android Studio how to run gradle sync manually?

I think ./gradlew tasks is same with Android studio sync. Why? I will explain it.

I meet a problem when I test jacoco coverage report. When I run ./gradlew clean :Test:testDebugUnitTest in command line directly , error appear.

Error opening zip file or JAR manifest missing : build/tmp/expandedArchives/org.jacoco.agent-0.8.2.jar_5bdiis3s7lm1rcnv0gawjjfxc/jacocoagent.jar

However, if I click android studio sync firstly , it runs OK. Because the build/../jacocoagent.jar appear naturally. I dont know why, maybe there is bug in jacoco plugin. Unit I find running .gradlew tasks makes the jar appear as well. So I can get the same result in gralde script.

Besides, gradle --recompile-scripts does not work for the problem.

Using module 'subprocess' with timeout

There's an idea to subclass the Popen class and extend it with some simple method decorators. Let's call it ExpirablePopen.

from logging import error
from subprocess import Popen
from threading import Event
from threading import Thread


class ExpirablePopen(Popen):

    def __init__(self, *args, **kwargs):
        self.timeout = kwargs.pop('timeout', 0)
        self.timer = None
        self.done = Event()

        Popen.__init__(self, *args, **kwargs)

    def __tkill(self):
        timeout = self.timeout
        if not self.done.wait(timeout):
            error('Terminating process {} by timeout of {} secs.'.format(self.pid, timeout))
            self.kill()

    def expirable(func):
        def wrapper(self, *args, **kwargs):
            # zero timeout means call of parent method
            if self.timeout == 0:
                return func(self, *args, **kwargs)

            # if timer is None, need to start it
            if self.timer is None:
                self.timer = thr = Thread(target=self.__tkill)
                thr.daemon = True
                thr.start()

            result = func(self, *args, **kwargs)
            self.done.set()

            return result
        return wrapper

    wait = expirable(Popen.wait)
    communicate = expirable(Popen.communicate)


if __name__ == '__main__':
    from subprocess import PIPE

    print ExpirablePopen('ssh -T [email protected]', stdout=PIPE, timeout=1).communicate()

How to get a barplot with several variables side by side grouped by a factor

Using reshape2 and dplyr. Your data:

df <- read.table(text=
"tea                coke            beer             water           gender
14.55              26.50793651     22.53968254      40              1
24.92997199        24.50980392     26.05042017      24.50980393     2
23.03732304        30.63063063     25.41827542      20.91377091     1   
225.51781276       24.6064623      24.85501243      50.80645161     1
24.53662842        26.03706973     25.24271845      24.18358341     2", header=TRUE)

Getting data into correct form:

library(reshape2)
library(dplyr)
df.melt <- melt(df, id="gender")
bar <- group_by(df.melt, variable, gender)%.%summarise(mean=mean(value))

Plotting:

library(ggplot2)
ggplot(bar, aes(x=variable, y=mean, fill=factor(gender)))+
  geom_bar(position="dodge", stat="identity")

enter image description here

How do I format date value as yyyy-mm-dd using SSIS expression builder?

Looks like you created a separate question. I was answering your other question How to change flat file source using foreach loop container in an SSIS package? with the same answer. Anyway, here it is again.

Create two string data type variables namely DirPath and FilePath. Set the value C:\backup\ to the variable DirPath. Do not set any value to the variable FilePath.

Variables

Select the variable FilePath and select F4 to view the properties. Set the EvaluateAsExpression property to True and set the Expression property as @[User::DirPath] + "Source" + (DT_STR, 4, 1252) DATEPART("yy" , GETDATE()) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)

Expression

How to change column width in DataGridView?

You could set the width of the abbrev column to a fixed pixel width, then set the width of the description column to the width of the DataGridView, minus the sum of the widths of the other columns and some extra margin (if you want to prevent a horizontal scrollbar from appearing on the DataGridView):

dataGridView1.Columns[1].Width = 108;  // or whatever width works well for abbrev
dataGridView1.Columns[2].Width = 
    dataGridView1.Width 
    - dataGridView1.Columns[0].Width 
    - dataGridView1.Columns[1].Width 
    - 72;  // this is an extra "margin" number of pixels

If you wanted the description column to always take up the "remainder" of the width of the DataGridView, you could put something like the above code in a Resize event handler of the DataGridView.

How to add background-image using ngStyle (angular2)?

Looks like your style has been sanitized, to bypass it try using bypassSecurityTrustStyle method from DomSanitizer.

_x000D_
_x000D_
import { Component, OnInit, Input } from '@angular/core';_x000D_
import { DomSanitizer, SafeStyle } from '@angular/platform-browser';_x000D_
_x000D_
@Component({_x000D_
  selector: 'my-component',_x000D_
  templateUrl: './my-component.component.html',_x000D_
  styleUrls: ['./my-component.component.scss']_x000D_
})_x000D_
_x000D_
export class MyComponent implements OnInit {_x000D_
_x000D_
  public backgroundImg: SafeStyle;_x000D_
  @Input() myObject: any;_x000D_
_x000D_
  constructor(private sanitizer: DomSanitizer) {}_x000D_
_x000D_
  ngOnInit() {_x000D_
     this.backgroundImg = this.sanitizer.bypassSecurityTrustStyle('url(' + this.myObject.ImageUrl + ')');_x000D_
  }_x000D_
_x000D_
}
_x000D_
<div *ngIf="backgroundImg.length > 0" [style.background-image]="backgroundImg"></div>
_x000D_
_x000D_
_x000D_

How do you find what version of libstdc++ library is installed on your linux machine?

What exactly do you want to know?

The shared library soname? That's part of the filename, libstdc++.so.6, or shown by readelf -d /usr/lib64/libstdc++.so.6 | grep soname.

The minor revision number? You should be able to get that by simply checking what the symlink points to:

$ ls -l  /usr/lib/libstdc++.so.6
lrwxrwxrwx. 1 root root 19 Mar 23 09:43 /usr/lib/libstdc++.so.6 -> libstdc++.so.6.0.16

That tells you it's 6.0.16, which is the 16th revision of the libstdc++.so.6 version, which corresponds to the GLIBCXX_3.4.16 symbol versions.

Or do you mean the release it comes from? It's part of GCC so it's the same version as GCC, so unless you've screwed up your system by installing unmatched versions of g++ and libstdc++.so you can get that from:

$ g++ -dumpversion
4.6.3

Or, on most distros, you can just ask the package manager. On my Fedora host that's

$ rpm -q libstdc++
libstdc++-4.6.3-2.fc16.x86_64
libstdc++-4.6.3-2.fc16.i686

As other answers have said, you can map releases to library versions by checking the ABI docs

Classes residing in App_Code is not accessible

Go to the page from where you want to access the App_code class, and then add the namespace of the app_code class. You need to provide a using statement, as follows:

using WebApplication3.App_Code;

After that, you will need to go to the app_code class property and set the 'Build Action' to 'Compile'.

How to check "hasRole" in Java Code with Spring Security?

User Roles can be checked using following ways:

  1. Using call static methods in SecurityContextHolder:

    Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null && auth.getAuthorities().stream().anyMatch(role -> role.getAuthority().equals("ROLE_NAME"))) { //do something}

  2. Using HttpServletRequest

_x000D_
_x000D_
@GetMapping("/users")
public String getUsers(HttpServletRequest request) {
    if (request.isUserInRole("ROLE_NAME")) {
      
    }
_x000D_
_x000D_
_x000D_

What's the best way to do a backwards loop in C/C#/C++?

While admittedly a bit obscure, I would say that the most typographically pleasing way of doing this is

for (int i = myArray.Length; i --> 0; )
{
    //do something
}

Parse strings to double with comma and point

You DO NOT NEED to replace the comma and dot..

I have had the very same problem. The reason is simple, the conversion culture plays a big role in which the comma or a dot is interpreted. I use a German culture where the comma distinguish the fractions, where as elsewhere the dot does the job.

Here I made a complete example to make the difference clear.

string[] doubleStrings = {"hello", "0.123", "0,123"};
double localCultreResult;
foreach (var doubleString in doubleStrings)
{
    double.TryParse(doubleString, NumberStyles.Any, CultureInfo.CurrentCulture, out localCultreResult);
    Console.WriteLine(string.Format("Local culture results for the parsing of {0} is {1}", doubleString, localCultreResult));
}

double invariantCultureResult;
foreach (var doubleString in doubleStrings)
{
    double.TryParse(doubleString, NumberStyles.Any, CultureInfo.InvariantCulture, out invariantCultureResult);
    Console.WriteLine(string.Format("Invariant culture results for the parsing of {0} is {1}", doubleString, invariantCultureResult));
}

The results is the following: enter image description here

Play around with the culture and you will get the result you need.

How to use comparison and ' if not' in python?

There are two ways. In case of doubt, you can always just try it. If it does not work, you can add extra braces to make sure, like that:

if not ((u0 <= u) and (u < u0+step)):

How can I turn a List of Lists into a List in Java 8?

An expansion on Eran's answer that was the top answer, if you have a bunch of layers of lists, you can keep flatmapping them.

This also comes with a handy way of filtering as you go down the layers if needed as well.

So for example:

List<List<List<List<List<List<Object>>>>>> multiLayeredList = ...

List<Object> objectList = multiLayeredList
    .stream()
    .flatmap(someList1 -> someList1
        .stream()
        .filter(...Optional...))
    .flatmap(someList2 -> someList2
        .stream()
        .filter(...Optional...))
    .flatmap(someList3 -> someList3
        .stream()
        .filter(...Optional...))
    ...
    .collect(Collectors.toList())

This is would be similar in SQL to having SELECT statements within SELECT statements.

How to deploy a war file in Tomcat 7

1.Generate a war file from your application
2. open tomcat manager, go down the page
3. Click on browse to deploy the war.
4. choose your war file. There you go!

Python Git Module experiences?

For the record, none of the aforementioned Git Python libraries seem to contain a "git status" equivalent, which is really the only thing I would want since dealing with the rest of the git commands via subprocess is so easy.

How to convert a Kotlin source file to a Java source file

Java and Kotlin runs on Java Virtual Machine (JVM).

Converting a Kotlin file to Java file involves two steps i.e. compiling the Kotlin code to the JVM bytecode and then decompile the bytecode to the Java code.

Steps to convert your Kotlin source file to Java source file:

  1. Open your Kotlin project in the Android Studio.
  2. Then navigate to Tools -> Kotlin -> Show Kotlin Bytecode.

enter image description here

  1. You will get the bytecode of your Kotin file.
  2. Now click on the Decompile button to get your Java code from the bytecode

Entity Framework 6 Code first Default value

After @SedatKapanoglu comment, I am adding all my approach that works, because he was right, just using the fluent API does not work.

1- Create custom code generator and override Generate for a ColumnModel.

   public class ExtendedMigrationCodeGenerator : CSharpMigrationCodeGenerator
{

    protected override void Generate(ColumnModel column, IndentedTextWriter writer, bool emitName = false)
    {

        if (column.Annotations.Keys.Contains("Default"))
        {
            var value = Convert.ChangeType(column.Annotations["Default"].NewValue, column.ClrDefaultValue.GetType());
            column.DefaultValue = value;
        }


        base.Generate(column, writer, emitName);
    }

}

2- Assign the new code generator:

public sealed class Configuration : DbMigrationsConfiguration<Data.Context.EfSqlDbContext>
{
    public Configuration()
    {
        CodeGenerator = new ExtendedMigrationCodeGenerator();
        AutomaticMigrationsEnabled = false;
    }
}

3- Use fluent api to created the Annotation:

public static void Configure(DbModelBuilder builder){    
builder.Entity<Company>().Property(c => c.Status).HasColumnAnnotation("Default", 0);            
}

JavaScript + Unicode regexes

As mentioned in other answers, JavaScript regexes have no support for Unicode character classes. However, there is a library that does provide this: Steven Levithan's excellent XRegExp and its Unicode plug-in.

Comprehensive methods of viewing memory usage on Solaris

Here are the basics. I'm not sure that any of these count as "clear and simple" though.

ps(1)

For process-level view:

$ ps -opid,vsz,rss,osz,args
  PID  VSZ  RSS   SZ COMMAND
 1831 1776 1008  222 ps -opid,vsz,rss,osz,args
 1782 3464 2504  433 -bash
$

vsz/VSZ: total virtual process size (kb)

rss/RSS: resident set size (kb, may be inaccurate(!), see man)

osz/SZ: total size in memory (pages)

To compute byte size from pages:

$ sz_pages=$(ps -o osz -p $pid | grep -v SZ )
$ sz_bytes=$(( $sz_pages * $(pagesize) ))
$ sz_mbytes=$(( $sz_bytes / ( 1024 * 1024 ) ))
$ echo "$pid OSZ=$sz_mbytes MB"

vmstat(1M)

$ vmstat 5 5 
 kthr      memory            page            disk          faults      cpu
 r b w   swap  free  re  mf pi po fr de sr rm s3 -- --   in   sy   cs us sy id
 0 0 0 535832 219880  1   2  0  0  0  0  0 -0  0  0  0  402   19   97  0  1 99
 0 0 0 514376 203648  1   4  0  0  0  0  0  0  0  0  0  402   19   96  0  1 99
^C

prstat(1M)

   PID USERNAME  SIZE   RSS STATE  PRI NICE      TIME  CPU PROCESS/NLWP       
  1852 martin   4840K 3600K cpu0    59    0   0:00:00 0.3% prstat/1
  1780 martin   9384K 2920K sleep   59    0   0:00:00 0.0% sshd/1
  ...

swap(1)

"Long listing" and "summary" modes:

$ swap -l
swapfile             dev  swaplo blocks   free
/dev/zvol/dsk/rpool/swap 256,1      16 1048560 1048560
$ swap -s 
total: 42352k bytes allocated + 20192k reserved = 62544k used, 607672k available
$

top(1)

An older version (3.51) is available on the Solaris companion CD from Sun, with the disclaimer that this is "Community (not Sun) supported". More recent binary packages available from sunfreeware.com or blastwave.org.

load averages:  0.02,  0.00,  0.00;                      up 2+12:31:38                                                                                            08:53:58
31 processes: 30 sleeping, 1 on cpu
CPU states: 98.0% idle,  0.0% user,  2.0% kernel,  0.0% iowait,  0.0% swap
Memory: 1024M phys mem, 197M free mem, 512M total swap, 512M free swap

   PID USERNAME LWP PRI NICE  SIZE   RES STATE    TIME    CPU COMMAND
  1898 martin     1  54    0 3336K 1808K cpu      0:00  0.96% top
     7 root      11  59    0   10M 7912K sleep    0:09  0.02% svc.startd

sar(1M)

And just what's wrong with sar? :)

Rolling back bad changes with svn in Eclipse

The svnbook has a section on how Subversion allows you to revert the changes from a particular revision without affecting the changes that occured in subsequent revisions:

http://svnbook.red-bean.com/en/1.4/svn.branchmerge.commonuses.html#svn.branchmerge.commonuses.undo

I don't use Eclipse much, but in TortoiseSVN you can do this from the from the log dialogue; simply right-click on the revision you want to revert and select "Revert changes from this revision".

In the case that the files for which you want to revert "bad changes" had "good changes" in subsequent revisions, then the process is the same. The changes from the "bad" revision will be reverted leaving the changes from "good" revisions untouched, however you might get conflicts.

"No X11 DISPLAY variable" - what does it mean?

Initial Check.

1) When you are exporting the DISPLAY to other machine, ensure you entered the command xhost + on that machine. This command allows to other machine to export their DISPLAY on this machine. There may be security constraints, just know about it. Need to check ssh -X MachineIP will not require xhost + ?

2) Some times JCONSOLE won't show all its process, since those JVM process may run with different user and you are exporting the DISPLAY with another user. so better follow CD_DIR>sudo ./jconsole

3) In WAS (WEBSPHERE); jconsole won't be able to connect its java server process, that time just go till the link, then try connecting it. This worked for me. May be this page is initializing some variables to enable jconsole to connect with that server.

WAS console > Application servers > server1 > Process definition > Java Virtual Machine


I have faced the same issue with AIX (where command line interface only available, There is no DISPLAY UI) machine. I resolved by installing

NX Client for Windows

Step 1: Through that Windows machine, I connected with unix box where GUI console is available.
Step 2: SSH to the AIX box from that UNIX box.
Step 3: set DISPLAY like "export DISPLAY=UNIXMACHINE:NXClientPORTConnectedMentionedOnTitle"
Step 4: Now if we launch any programs which requires DISPLAY; it will be launched on this UNIX box.

VNC

If you installed VNC on UNIX box where display is available; then Windows and NX Client is not required. Step 1: Use VNC to connect with Unix box where GUI console is available.
Step 2: SSH to the AIX box from that UNIX box.
Step 3: set DISPLAY like "export DISPLAY=UNIXMACHINE:VNCPORT"
Step 4: Now if we launch any programs which requires DISPLAY; it will be launched on this UNIX box.

ELSE

Step 1: SSH to the AIX box from that UNIX box.
Step 2: set DISPLAY like "export DISPLAY=UNIXMACHINE:VNCPORT"
Step 3: Now if we launch any programs which requires DISPLAY; it will be launched on this UNIX box.

Setting Django up to use MySQL

If you are using python3.x then Run below command

pip install mysqlclient

Then change setting.py like

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'DB',
     'USER': 'username',
    'PASSWORD': 'passwd',
  }
  }

The remote host closed the connection. The error code is 0x800704CD

As m.edmondson mentioned, "The remote host closed the connection." occurs when a user or browser cancels something, or the network connection drops etc. It doesn't necessarily have to be a file download however, just any request for any resource that results in a response to the client. Basically the error means that the response could not be sent because the server can no longer talk to the client(browser).

There are a number of steps that you can take in order to stop it happening. If you are manually sending something in the response with a Response.Write, Response.Flush, returning data from a web servivce/page method or something similar, then you should consider checking Response.IsClientConnected before sending the response. Also, if the response is likely to take a long time or a lot of server-side processing is required, you should check this periodically until the response.end if called. See the following for details on this property:

http://msdn.microsoft.com/en-us/library/system.web.httpresponse.isclientconnected.aspx

Alternatively, which I believe is most likely in your case, the error is being caused by something inside the framework. The following link may by of use:

http://blog.whitesites.com/fixing-The-remote-host-closed-the-connection-The-error-code-is-0x80070057__633882307305519259_blog.htm

The following stack-overflow post might also be of interest:

"The remote host closed the connection" in Response.OutputStream.Write

Anaconda version with Python 3.5

It is very simple, first, you need to be inside the virtualenv you created, then to install a specific version of python say 3.5, use Anaconda, conda install python=3.5

In general you can do this for any python package you want

conda install package_name=package_version

How to show Page Loading div until the page has finished loading?

This script will add a div that covers the entire window as the page loads. It will show a CSS-only loading spinner automatically. It will wait until the window (not the document) finishes loading, then it will wait an optional extra few seconds.

  • Works with jQuery 3 (it has a new window load event)
  • No image needed but it's easy to add one
  • Change the delay for more branding or instructions
  • Only dependency is jQuery.

CSS loader code from https://projects.lukehaas.me/css-loaders

_x000D_
_x000D_
    _x000D_
$('body').append('<div style="" id="loadingDiv"><div class="loader">Loading...</div></div>');_x000D_
$(window).on('load', function(){_x000D_
  setTimeout(removeLoader, 2000); //wait for page load PLUS two seconds._x000D_
});_x000D_
function removeLoader(){_x000D_
    $( "#loadingDiv" ).fadeOut(500, function() {_x000D_
      // fadeOut complete. Remove the loading div_x000D_
      $( "#loadingDiv" ).remove(); //makes page more lightweight _x000D_
  });  _x000D_
}
_x000D_
        .loader,_x000D_
        .loader:after {_x000D_
            border-radius: 50%;_x000D_
            width: 10em;_x000D_
            height: 10em;_x000D_
        }_x000D_
        .loader {            _x000D_
            margin: 60px auto;_x000D_
            font-size: 10px;_x000D_
            position: relative;_x000D_
            text-indent: -9999em;_x000D_
            border-top: 1.1em solid rgba(255, 255, 255, 0.2);_x000D_
            border-right: 1.1em solid rgba(255, 255, 255, 0.2);_x000D_
            border-bottom: 1.1em solid rgba(255, 255, 255, 0.2);_x000D_
            border-left: 1.1em solid #ffffff;_x000D_
            -webkit-transform: translateZ(0);_x000D_
            -ms-transform: translateZ(0);_x000D_
            transform: translateZ(0);_x000D_
            -webkit-animation: load8 1.1s infinite linear;_x000D_
            animation: load8 1.1s infinite linear;_x000D_
        }_x000D_
        @-webkit-keyframes load8 {_x000D_
            0% {_x000D_
                -webkit-transform: rotate(0deg);_x000D_
                transform: rotate(0deg);_x000D_
            }_x000D_
            100% {_x000D_
                -webkit-transform: rotate(360deg);_x000D_
                transform: rotate(360deg);_x000D_
            }_x000D_
        }_x000D_
        @keyframes load8 {_x000D_
            0% {_x000D_
                -webkit-transform: rotate(0deg);_x000D_
                transform: rotate(0deg);_x000D_
            }_x000D_
            100% {_x000D_
                -webkit-transform: rotate(360deg);_x000D_
                transform: rotate(360deg);_x000D_
            }_x000D_
        }_x000D_
        #loadingDiv {_x000D_
            position:absolute;;_x000D_
            top:0;_x000D_
            left:0;_x000D_
            width:100%;_x000D_
            height:100%;_x000D_
            background-color:#000;_x000D_
        }
_x000D_
This script will add a div that covers the entire window as the page loads. It will show a CSS-only loading spinner automatically. It will wait until the window (not the document) finishes loading._x000D_
_x000D_
  <ul>_x000D_
    <li>Works with jQuery 3, which has a new window load event</li>_x000D_
    <li>No image needed but it's easy to add one</li>_x000D_
    <li>Change the delay for branding or instructions</li>_x000D_
    <li>Only dependency is jQuery.</li>_x000D_
  </ul>_x000D_
_x000D_
Place the script below at the bottom of the body._x000D_
_x000D_
CSS loader code from https://projects.lukehaas.me/css-loaders_x000D_
_x000D_
<!-- Place the script below at the bottom of the body -->_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

How to submit a form with JavaScript by clicking a link?

this works well without any special function needed. Much easier to write with php as well. <input onclick="this.form.submit()"/>

How to step through Python code to help debug issues?

If you come from Java/C# background I guess your best bet would be to use Eclipse with Pydev. This gives you a fully functional IDE with debugger built in. I use it with django as well.

How do I force git to checkout the master branch and remove carriage returns after I've normalized files using the "text" attribute?

Ahah! Checkout the previous commit, then checkout the master.

git checkout HEAD^
git checkout -f master

Android Studio doesn't start, fails saying components not installed

Android Studio was not able to connect to internet in my work PC due to Intranet Proxy/Firewall settings, changing the proxy settings didnt help me either.

Android studio was failing to run as it requires to install the above mentioned packages. As a work around I installed the packages from Android SDK Manager and it solved it.

You can find the SDK Manager under C:\Users\< UserName> \AppData\Local\Android\sdk\SDK Manager.exe In the GUI choose the following options whichever is relavant.

  • Tools->All Android SDK Build-tools and SDK Platform-tools under version 21.*
  • Everything under Android 5.0.1(API 21)
  • Everything under Extras

After installation is complete try launching the Android Studio

What is the correct way to represent null XML elements?

It depends on how you validate your XML. If you use XML Schema validation, the correct way of representing null values is with the xsi:nil attribute.

[Source]

Hash function that produces short hashes?

If you don't need an algorithm that's strong against intentional modification, I've found an algorithm called adler32 that produces pretty short (~8 character) results. Choose it from the dropdown here to try it out:

http://www.sha1-online.com/

JQuery to load Javascript file dynamically

I realize I am a little late here, (5 years or so), but I think there is a better answer than the accepted one as follows:

$("#addComment").click(function() {
    if(typeof TinyMCE === "undefined") {
        $.ajax({
            url: "tinymce.js",
            dataType: "script",
            cache: true,
            success: function() {
                TinyMCE.init();
            }
        });
    }
});

The getScript() function actually prevents browser caching. If you run a trace you will see the script is loaded with a URL that includes a timestamp parameter:

http://www.yoursite.com/js/tinymce.js?_=1399055841840

If a user clicks the #addComment link multiple times, tinymce.js will be re-loaded from a differently timestampped URL. This defeats the purpose of browser caching.

===

Alternatively, in the getScript() documentation there is a some sample code that demonstrates how to enable caching by creating a custom cachedScript() function as follows:

jQuery.cachedScript = function( url, options ) {

    // Allow user to set any option except for dataType, cache, and url
    options = $.extend( options || {}, {
        dataType: "script",
        cache: true,
        url: url
    });

    // Use $.ajax() since it is more flexible than $.getScript
    // Return the jqXHR object so we can chain callbacks
    return jQuery.ajax( options );
};

// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
    console.log( textStatus );
});

===

Or, if you want to disable caching globally, you can do so using ajaxSetup() as follows:

$.ajaxSetup({
    cache: true
});

How to post data to specific URL using WebClient in C#

Using WebClient.UploadString or WebClient.UploadData you can POST data to the server easily. I’ll show an example using UploadData, since UploadString is used in the same manner as DownloadString.

byte[] bret = client.UploadData("http://www.website.com/post.php", "POST",
                System.Text.Encoding.ASCII.GetBytes("field1=value1&amp;field2=value2") );
 
string sret = System.Text.Encoding.ASCII.GetString(bret);

More: http://www.daveamenta.com/2008-05/c-webclient-usage/

C# find highest array value and index

int[] Data= { 1, 212, 333,2,12,3311,122,23 };
int large = Data.Max();
Console.WriteLine(large);

How can I test a change made to Jenkinsfile locally?

i am using replay future , to do some update and run quickly .

Copy from one workbook and paste into another

This should do it, let me know if you have trouble with it:

Sub foo()
Dim x As Workbook
Dim y As Workbook

'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")

'Now, copy what you want from x:
x.Sheets("name of copying sheet").Range("A1").Copy

'Now, paste to y worksheet:
y.Sheets("sheetname").Range("A1").PasteSpecial

'Close x:
x.Close

End Sub

Alternatively, you could just:

Sub foo2()
Dim x As Workbook
Dim y As Workbook

'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")

'Now, transfer values from x to y:
y.Sheets("sheetname").Range("A1").Value = x.Sheets("name of copying sheet").Range("A1") 

'Close x:
x.Close

End Sub

To extend this to the entire sheet:

With x.Sheets("name of copying sheet").UsedRange
    'Now, paste to y worksheet:
    y.Sheets("sheet name").Range("A1").Resize( _
        .Rows.Count, .Columns.Count) = .Value
End With

And yet another way, store the value as a variable and write the variable to the destination:

Sub foo3()
Dim x As Workbook
Dim y As Workbook
Dim vals as Variant

'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")

'Store the value in a variable:
vals = x.Sheets("name of sheet").Range("A1").Value

'Use the variable to assign a value to the other file/sheet:
y.Sheets("sheetname").Range("A1").Value = vals 

'Close x:
x.Close

End Sub

The last method above is usually the fastest for most applications, but do note that for very large datasets (100k rows) it's observed that the Clipboard actually outperforms the array dump:

Copy/PasteSpecial vs Range.Value = Range.Value

That said, there are other considerations than just speed, and it may be the case that the performance hit on a large dataset is worth the tradeoff, to avoid interacting with the Clipboard.

How to destroy an object?

I would go with unset because it might give the garbage collector a better hint so that the memory can be available again sooner. Be careful that any things the object points to either have other references or get unset first or you really will have to wait on the garbage collector since there would then be no handles to them.

Remove all html tags from php string

Use PHP's strip_tags() function.

For example:

$businessDesc = strip_tags($row_get_Business['business_description']);
$businessDesc = substr($businessDesc, 0, 110);


print($businessDesc);

how to draw directed graphs using networkx in python?

You need to use a directed graph instead of a graph, i.e.

G = nx.DiGraph()

Then, create a list of the edge colors you want to use and pass those to nx.draw (as shown by @Marius).

Putting this all together, I get the image below. Still not quite the other picture you show (I don't know where your edge weights are coming from), but much closer! If you want more control of how your output graph looks (e.g. get arrowheads that look like arrows), I'd check out NetworkX with Graphviz.

enter image description here

Host 'xxx.xx.xxx.xxx' is not allowed to connect to this MySQL server

Problem: root@localhost is unable to connect to a fresh installation of mysql-community-server on openSUSE 42.2-1.150.x86_64. Mysql refuses connections - period.

Solution:

$ ls -l /var/lib/mysql/mysql/user.*
-rw-rw---- 1 mysql mysql     0 Apr 29 19:44 /var/lib/mysql/mysql/user.MYD
-rw-rw---- 1 mysql mysql  1024 Apr 29 19:44 /var/lib/mysql/mysql/user.MYI
-rw-rw---- 1 mysql mysql 10684 Apr 29 19:44 /var/lib/mysql/mysql/user.frm

File user.MYD has 0 size (really ?!). I copied all 3 files from another working system.

$ /usr/sbin/rcmysql stop
$ cd /var/lib/mysql/mysql/
$ scp root@othersytem:/var/lib/mysql/mysql/user.* ./
$ /usr/sbin/rcmysql start
$ cd -
$ mysql -u root -p

I was able to log in. Then, it was just a matter of re-applying all schema privileges. Also, if you disabled IPv6, re-enable it temporary so that root@::1 account can also work.

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Right click on your website go to property pages and check both the check-boxes under Accessibility validation click on ok. run the website.

Where does this come from: -*- coding: utf-8 -*-

This way of specifying the encoding of a Python file comes from PEP 0263 - Defining Python Source Code Encodings.

It is also recognized by GNU Emacs (see Python Language Reference, 2.1.4 Encoding declarations), though I don't know if it was the first program to use that syntax.

Delete the 'first' record from a table in SQL Server, without a WHERE condition

Does this really make sense?
There is no "first" record in a relational database, you can only delete one random record.

How to dynamically add rows to a table in ASP.NET?

You need to use JavaScript in your HTML and make sure you are using forms so that. You may finally serialize the data using Ajax method to push the data from HTML into database

C#: Printing all properties of an object

You can use the TypeDescriptor class to do this:

foreach(PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj))
{
    string name=descriptor.Name;
    object value=descriptor.GetValue(obj);
    Console.WriteLine("{0}={1}",name,value);
}

TypeDescriptor lives in the System.ComponentModel namespace and is the API that Visual Studio uses to display your object in its property browser. It's ultimately based on reflection (as any solution would be), but it provides a pretty good level of abstraction from the reflection API.

Create space at the beginning of a UITextField

Here is Haagenti's answer updated to Swift 4.2:

class PaddedTextField: UITextField {

    func getPadding(plusExtraFor clearButtonMode: ViewMode) -> UIEdgeInsets {
        var padding = UIEdgeInsets(top: 11, left: 16, bottom: 11, right: 16)

        // Add additional padding on the right side when showing the clear button
        if self.clearButtonMode == .always || self.clearButtonMode == clearButtonMode {
            padding.right = 28
        }

        return padding
    }

    override open func textRect(forBounds bounds: CGRect) -> CGRect {
        let padding = getPadding(plusExtraFor: .unlessEditing)
        return bounds.inset(by: padding)
    }

    override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
        let padding = getPadding(plusExtraFor: .unlessEditing)
        return bounds.inset(by: padding)
    }

    override open func editingRect(forBounds bounds: CGRect) -> CGRect {
        let padding = getPadding(plusExtraFor: .whileEditing)
        return bounds.inset(by: padding)
    }

}

Reference: Upgrading To Swift 4.2.

Edit: Account for clear button.

Swift Alamofire: How to get the HTTP response status code

For Swift 2.0 users with Alamofire > 2.0

Alamofire.request(.GET, url)
  .responseString { _, response, result in
    if response?.statusCode == 200{
      //Do something with result
    }
}

Git error on git pull (unable to update local ref)

I discoverd the same Error message trying to pull from a Bitbuck Repo into my lokal copy. There is also only one Branche Master and the command git pull origin master lead to this Error Message

From https://bitbucket.org/xxx
 * branch            master     -> FETCH_HEAD
error: Couldn't set ORIG_HEAD
fatal: Cannot update the ref 'ORIG_HEAD'.

Solution as follows

  1. git reflog find the number of the last commit
  2. git reset --hard <numnber> reset to the last commit
  3. git pull origin master pull again without error

How to get mouse position in jQuery without mouse-events?

I used this method:

$(document).mousemove(function(e) {
    window.x = e.pageX;
    window.y = e.pageY;
});

function show_popup(str) {
    $("#popup_content").html(str);
    $("#popup").fadeIn("fast");
    $("#popup").css("top", y);
    $("#popup").css("left", x);
}

In this way I'll always have the distance from the top saved in y and the distance from the left saved in x.

How to detect the end of loading of UITableView

@folex answer is right.

But it will fail if the tableView has more than one section displayed at a time.

-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
   if([indexPath isEqual:((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject])]){
    //end of loading

 }
}

multiple conditions for JavaScript .includes() method

How about ['hello', 'hi', 'howdy'].includes(str)?

Basic http file downloading and saving to disk in python?

Another clean way to save the file is this:

import csv
import urllib

urllib.retrieve("your url goes here" , "output.csv")

Remove rows with all or some NAs (missing values) in data.frame

If you want control over how many NAs are valid for each row, try this function. For many survey data sets, too many blank question responses can ruin the results. So they are deleted after a certain threshold. This function will allow you to choose how many NAs the row can have before it's deleted:

delete.na <- function(DF, n=0) {
  DF[rowSums(is.na(DF)) <= n,]
}

By default, it will eliminate all NAs:

delete.na(final)
             gene hsap mmul mmus rnor cfam
2 ENSG00000199674    0    2    2    2    2
6 ENSG00000221312    0    1    2    3    2

Or specify the maximum number of NAs allowed:

delete.na(final, 2)
             gene hsap mmul mmus rnor cfam
2 ENSG00000199674    0    2    2    2    2
4 ENSG00000207604    0   NA   NA    1    2
6 ENSG00000221312    0    1    2    3    2

Load a WPF BitmapImage from a System.Drawing.Bitmap

Thanks to Hallgrim, here is the code I ended up with:

ScreenCapture = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
   bmp.GetHbitmap(), 
   IntPtr.Zero, 
   System.Windows.Int32Rect.Empty, 
   BitmapSizeOptions.FromWidthAndHeight(width, height));

I also ended up binding to a BitmapSource instead of a BitmapImage as in my original question

TCPDF not render all CSS properties

At the moment I write this, TCPDF only supports padding for tables.

Link to their forum page with that information

How to read a single char from the console in Java (as the user types it)?

I have written a Java class RawConsoleInput that uses JNA to call operating system functions of Windows and Unix/Linux.

  • On Windows it uses _kbhit() and _getwch() from msvcrt.dll.
  • On Unix it uses tcsetattr() to switch the console to non-canonical mode, System.in.available() to check whether data is available and System.in.read() to read bytes from the console. A CharsetDecoder is used to convert bytes to characters.

It supports non-blocking input and mixing raw mode and normal line mode input.

How can I move a tag on a git branch to a different commit?

To sum up if your remote is called origin and you're working on master branch:

git tag -d <tagname>
git push origin :refs/tags/<tagname>
git tag <tagname> <commitId>
git push origin <tagname>
  • Line 1 removes the tag in local env.
  • Line 2 removes the tag in remote env.
  • Line 3 adds the tag to different commit
  • Line 4 pushes the change to the remote

You can also exchange line 4 to git push origin --tags to push all the changes with tags from your local changes.

Basing on @stuart-golodetz, @greg-hewgill, @eedeep, @ben-hocking answers, comments below their answers and NateS comments below my answer.

Install specific version using laravel installer

From Laravel 6, Now It's working with the following command:

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

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

This can be changed to 0/1 through using CASE WHEN like this example:

SELECT 
 CASE WHEN SchemaName.TableName.BitFieldName = 'true' THEN 1 ELSE 0 END AS 'bit Value' 
 FROM SchemaName.TableName

How to replace a character with a newline in Emacs?

There are four ways I've found to put a newline into the minibuffer.

  1. C-o

  2. C-q C-j

  3. C-q 12 (12 is the octal value of newline)

  4. C-x o to the main window, kill a newline with C-k, then C-x o back to the minibuffer, yank it with C-y

How to merge two files line by line in Bash

Try following.

pr -tmJ a.txt b.txt > c.txt

Display current time in 12 hour format with AM/PM

    //To get Filename + date and time


    SimpleDateFormat f = new SimpleDateFormat("MMM");
    SimpleDateFormat f1 = new SimpleDateFormat("dd");
    SimpleDateFormat f2 = new SimpleDateFormat("a");

    int h;
         if(Calendar.getInstance().get(Calendar.HOUR)==0)
            h=12;
         else
            h=Calendar.getInstance().get(Calendar.HOUR)

    String filename="TestReport"+f1.format(new Date())+f.format(new Date())+h+f2.format(new Date())+".txt";


The Output Like:TestReport27Apr3PM.txt

Read file from line 2 or skip header row

If you want to read multiple CSV files starting from line 2, this works like a charm

for files in csv_file_list:
        with open(files, 'r') as r: 
            next(r)                  #skip headers             
            rr = csv.reader(r)
            for row in rr:
                #do something

(this is part of Parfait's answer to a different question)

Creating a Pandas DataFrame from a Numpy array: How do I specify the index column and column headers?

Here simple example to create pandas dataframe by using numpy array.

import numpy as np
import pandas as pd

# create an array 
var1  = np.arange(start=1, stop=21, step=1).reshape(-1)
var2 = np.random.rand(20,1).reshape(-1)
print(var1.shape)
print(var2.shape)

dataset = pd.DataFrame()
dataset['col1'] = var1
dataset['col2'] = var2
dataset.head()

jQuery AJAX Character Encoding

You need to set up your server to use ISO-8859-15 as the character encoding (adding the appropriate HTTP header). Doing it in the body of the html won't help.

I can see this line

<?php header('Content-Type: text/html; charset=ISO-8859-15'); ?>

at the source of your html. This shouldn't happen. Using Live HTTP Headers I can't see the appropriate charset HTTP header. Use that for both your first page and the ajax service.

How to move or copy files listed by 'find' command in unix?

Adding to Eric Jablow's answer, here is a possible solution (it worked for me - linux mint 14 /nadia)

find /path/to/search/ -type f -name "glob-to-find-files" | xargs cp -t /target/path/

You can refer to "How can I use xargs to copy files that have spaces and quotes in their names?" as well.

how to get the host url using javascript from the current page

// will return the host name and port
var host = window.location.host; 

or possibly

var host = window.location.protocol + "//" + window.location.host;

or if you like concatenation

var protocol = location.protocol;
var slashes = protocol.concat("//");
var host = slashes.concat(window.location.host);

// or as you probably should do
var host = location.protocol.concat("//").concat(window.location.host);

// the above is the same as origin, e.g. "https://stackoverflow.com"
var host = window.location.origin;

If you have or expect custom ports use window.location.host instead of window.location.hostname

Dealing with "Xerces hell" in Java/Maven?

You should debug first, to help identify your level of XML hell. In my opinion, the first step is to add

-Djavax.xml.parsers.SAXParserFactory=com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl
-Djavax.xml.transform.TransformerFactory=com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl
-Djavax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl

to the command line. If that works, then start excluding libraries. If not, then add

-Djaxp.debug=1

to the command-line.

Error:java: invalid source release: 8 in Intellij. What does it mean?

Check your pom.xml first (if you have one)
Check your module's JDK dependancy. Make sure that it is 1.8
To do this,go to Project Structure -> SDK's
Add the path to where you have stored 1.8 (jdk1.8.0_45.jdk in my case)
Apply the changes
Now, go to Project Structure ->Modules
Change the Module SDK to 1.8
Apply the changes

Voila! You're done

Android studio- "SDK tools directory is missing"

for me, i did this and it worked. just go to C:\Users\$your username$\AppData(which is hidden most likely)\Local\ then at this location try to find this Folder : "Android" if you don't have it already make one with the exact name and try to open the android studio again.

Can't connect Nexus 4 to adb: unauthorized

I reinstalled the usb drivers and ensured that I was not using USB 3.0 port.

I then closed out eclipse and killed and restarted adb.

Was immediately prompted on phone to allow computer access. After accepting I restarted eclipse and now my Galaxy S3 shows up in device Device Manager.

handling DATETIME values 0000-00-00 00:00:00 in JDBC

I stumbled across this attempting to solve the same issue. The installation I am working with uses JBOSS and Hibernate, so I had to do this a different way. For the basic case, you should be able to add zeroDateTimeBehavior=convertToNull to your connection URI as per this configuration properties page.

I found other suggestions across the land referring to putting that parameter in your hibernate config:

In hibernate.cfg.xml:

<property name="hibernate.connection.zeroDateTimeBehavior">convertToNull</property>

In hibernate.properties:

hibernate.connection.zeroDateTimeBehavior=convertToNull

But I had to put it in my mysql-ds.xml file for JBOSS as:

<connection-property name="zeroDateTimeBehavior">convertToNull</connection-property>

Hope this helps someone. :)

What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

import java.util.Timer;
import java.util.TimerTask;

class Clock {
    private Timer mTimer = new Timer();

    private int mSecondsPassed = 0;
    private TimerTask mTask = new TimerTask() {
        @Override
        public void run() {
            mSecondsPassed++;
            System.out.println("Seconds passed: " + mSecondsPassed);
        }
    };

    private void start() {
        mTimer.scheduleAtFixedRate(mTask, 1000, 1000);
    }

    public static void main(String[] args) {
        Clock c = new Clock();
        c.start();
    }
}

Uncaught TypeError: Cannot assign to read only property

If sometimes a link! will not work. so create a temporary object and take all values from the writable object then change the value and assign it to the writable object. it should perfectly.

var globalObject = {
    name:"a",
    age:20
}
function() {
    let localObject = {
    name:'a',
    age:21
    }
    this.globalObject = localObject;
}

How to create hyperlink to call phone number on mobile devices?

You can also use callto:########### replacing the email code mail with call, at least according to W3Cschool site but I haven't had an opportunity to test it out.

Restrict SQL Server Login access to only one database

For anyone else out there wondering how to do this, I have the following solution for SQL Server 2008 R2 and later:

USE master
go
DENY VIEW ANY DATABASE TO [user]
go

This will address exactly the requirement outlined above..

Get all LI elements in array

After some years have passed, you can do that now with ES6 Array.from (or spread syntax):

_x000D_
_x000D_
const navbar = Array.from(document.querySelectorAll('#navbar>ul>li'));_x000D_
console.log('Get first: ', navbar[0].textContent);_x000D_
_x000D_
// If you need to iterate once over all these nodes, you can use the callback function:_x000D_
console.log('Iterate with Array.from callback argument:');_x000D_
Array.from(document.querySelectorAll('#navbar>ul>li'),li => console.log(li.textContent))_x000D_
_x000D_
// ... or a for...of loop:_x000D_
console.log('Iterate with for...of:');_x000D_
for (const li of document.querySelectorAll('#navbar>ul>li')) {_x000D_
    console.log(li.textContent);_x000D_
}
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
<div id="navbar">_x000D_
  <ul>_x000D_
    <li id="navbar-One">One</li>_x000D_
    <li id="navbar-Two">Two</li>_x000D_
    <li id="navbar-Three">Three</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

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

The solution angular.element(document.getElementById('ID')).scope().get() stopped working for me in angular 1.5.2. Sombody mention in a comment that this doesn't work in 1.4.9 also. I fixed it by storing the scope in a global variable:

var scopeHolder;
angular.module('fooApp').controller('appCtrl', function ($scope) {
    $scope = function bar(){
        console.log("foo");        
    };
    scopeHolder = $scope;
})

call from custom code:

scopeHolder.bar()

if you wants to restrict the scope to only this method. To minimize the exposure of whole scope. use following technique.

var scopeHolder;
angular.module('fooApp').controller('appCtrl', function ($scope) {
    $scope.bar = function(){
        console.log("foo");        
    };
    scopeHolder = $scope.bar;
})

call from custom code:

scopeHolder()

Making Maven run all tests, even when some fail

From the Maven Embedder documentation:

-fae,--fail-at-end Only fail the build afterwards; allow all non-impacted builds to continue

-fn,--fail-never NEVER fail the build, regardless of project result

So if you are testing one module than you are safe using -fae.

Otherwise, if you have multiple modules, and if you want all of them tested (even the ones that depend on the failing tests module), you should run mvn clean install -fn.
-fae will continue with the module that has a failing test (will run all other tests), but all modules that depend on it will be skipped.

SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable

If you are trying to run Google android sample code, try to import the entire repository instead of an individual sample.

Here is instructions.html, included with the Google Calendar API sample code.

  • Import calendar-android-sample project
  • Select "Import Project..." or File > Import Project...
  • Select [someDirectory]/google-api-java-client-samples/build.gradle and click OK.
    • Note: it will not work if you try to import [someDirectory]/google-api-java-client-samples/calendar-android-sample/build.gradle
  • Select "Use local gradle distribution" with "Gradle home" of [someDirectory]/gradle-2.2.1 and click OK.

How to gettext() of an element in Selenium Webdriver

You need to store it in a String variable first before displaying it like so:

String Txt = TxtBoxContent.getText();
System.out.println(Txt);

The shortest possible output from git log containing author and date

I use these two .gitconfig settings:

[log]
  date = relative
[format]
  pretty = format:%h %Cblue%ad%Creset %ae %Cgreen%s%Creset

%ad is the author date, which can be overidden by --date or the option specified in the [log] stanza in .gitconfig. I like the relative date because it gives an immediate feeling of when stuff was comitted. Output looks like this:

6c3e1a2 2 hours ago [email protected] lsof is a dependency now.
0754f18 11 hours ago [email protected] Properly unmount, so detaching works.
336a3ac 13 hours ago [email protected] Show ami registration command if auto register fails
be2ad45 17 hours ago [email protected] Fixes #6. Sao Paolo region is included as well.
5aed68e 17 hours ago [email protected] Shorten while loops

This is all of course in color, so it is easy to distinguish the various parts of a log line. Also it is the default when typing git log because of the [format] section.

2014 UPDATE: Since git now supports padding I have a nice amendment to the version above:

pretty = format:%C(yellow)%h %Cblue%>(12)%ad %Cgreen%<(7)%aN%Cred%d %Creset%s

This right aligns the relative dates and left aligns committer names, meaning you get a column-like look that is easy on the eyes.

Screenshot

  ss#1

2016 UPDATE: Since GPG commit signing is becoming a thing, I thought I'd update this post with a version that includes signature verification (in the screenshot it's the magenta letter right after the commit). A short explanation of the flag:

%G?: show "G" for a good (valid) signature, "B" for a bad signature, "U" for a good signature with unknown validity and "N" for no signature

Other changes include:

  • colors are now removed if the output is to something other than the tty (which is useful for grepping etc.)
  • git log -g now contains the reflog selector.
  • Save 2 parens on refnames and put them at the end (to preserve column alignment)
  • Truncate relative dates if they are too long (e.g. 3 years, 4..)
  • Truncate commiter names (might be a little short for some ppl, just change the %<(7,trunc) or check out the git .mailmap feature to shorten commiter names)

Here's the config:

pretty = format:%C(auto,yellow)%h%C(auto,magenta)% G? %C(auto,blue)%>(12,trunc)%ad %C(auto,green)%<(7,trunc)%aN%C(auto,reset)%s%C(auto,red)% gD% D

All in all column alignment is now preserved a lot better at the expense of some (hopefully) useless characters. Feel free to edit if you have any improvements, I'd love to make the message color depend on whether a commit is signed, but it doesn't seem like that is possible atm.

Screenshot

Screenshot of git log

Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?

This was a problem for me for a long time. I had to come up with a solution that can be easily migrated once we get Elvis operator or something.

This is what I use; works for both arrays and objects

put this in tools.js file or something

// this will create the object/array if null
Object.prototype.__ = function (prop) {
    if (this[prop] === undefined)
        this[prop] = typeof prop == 'number' ? [] : {}
    return this[prop]
};

// this will just check if object/array is null
Object.prototype._ = function (prop) {
    return this[prop] === undefined ? {} : this[prop]
};

usage example:

let student = {
    classes: [
        'math',
        'whatev'
    ],
    scores: {
        math: 9,
        whatev: 20
    },
    loans: [
        200,
        { 'hey': 'sup' },
        500,
        300,
        8000,
        3000000
    ]
}

// use one underscore to test

console.log(student._('classes')._(0)) // math
console.log(student._('classes')._(3)) // {}
console.log(student._('sports')._(3)._('injuries')) // {}
console.log(student._('scores')._('whatev')) // 20
console.log(student._('blabla')._('whatev')) // {}
console.log(student._('loans')._(2)) // 500 
console.log(student._('loans')._(1)._('hey')) // sup
console.log(student._('loans')._(6)._('hey')) // {} 

// use two underscores to create if null

student.__('loans').__(6)['test'] = 'whatev'

console.log(student.__('loans').__(6).__('test')) // whatev

well I know it makes the code a bit unreadable but it's a simple one liner solution and works great. I hope it helps someone :)

How can I declare and define multiple variables in one line using C++?

As @Josh said, the correct answer is:

int column = 0,
    row = 0,
    index = 0;

You'll need to watch out for the same thing with pointers. This:

int* a, b, c;

Is equivalent to:

int *a;
int b;
int c;

Spring data JPA query with parameter properties

Define the query method with signatures as follows.

@Query(select p from Person p where p.forename = :forename and p.surname = :surname)
User findByForenameAndSurname(@Param("surname") String lastname,
                             @Param("forename") String firstname);
}

For further details, check the Spring Data JPA reference

Why doesn't list have safe "get" method like dictionary?

Instead of using .get, using like this should be ok for lists. Just a usage difference.

>>> l = [1]
>>> l[10] if 10 < len(l) else 'fail'
'fail'

AngularJS passing data to $http.get request

You can pass params directly to $http.get() The following works fine

$http.get(user.details_path, {
    params: { user_id: user.id }
});

Remove background drawable programmatically in Android

Try this code:

imgView.setImageResource(android.R.color.transparent); 

also this one works:

imgView.setImageResource(0); 

but be careful this one doesn't work:

imgView.setImageResource(null); 

Calling a function within a Class method?

I think you are searching for something like this one.

class test {

    private $str = NULL;

    public function newTest(){

        $this->str .= 'function "newTest" called, ';
        return $this;
    }
    public function bigTest(){

        return $this->str . ' function "bigTest" called,';
    }
    public function smallTest(){

        return $this->str . ' function "smallTest" called,';
    }
    public function scoreTest(){

        return $this->str . ' function "scoreTest" called,';
    }
}

$test = new test;

echo $test->newTest()->bigTest();

Calculate difference between two dates (number of days)?

I think this will do what you want:

DateTime d1 = DateTime.Now;
DateTime d2 = DateTime.Now.AddDays(-1);

TimeSpan t = d1 - d2;
double NrOfDays = t.TotalDays;

Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view

I found 3 ways to implement this:

C# class:

public class AddressInfo {
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }
    public string Country { get; set; }
}

Action:

[HttpPost]
public ActionResult Check(AddressInfo addressInfo)
{
    return Json(new { success = true });
}

JavaScript you can do it three ways:

1) Query String:

$.ajax({
    url: '/en/Home/Check',
    data: $('#form').serialize(),
    type: 'POST',
});

Data here is a string.

"Address1=blah&Address2=blah&City=blah&State=blah&ZipCode=blah&Country=blah"

2) Object Array:

$.ajax({
    url: '/en/Home/Check',
    data: $('#form').serializeArray(),
    type: 'POST',
});

Data here is an array of key/value pairs :

=[{name: 'Address1', value: 'blah'}, {name: 'Address2', value: 'blah'}, {name: 'City', value: 'blah'}, {name: 'State', value: 'blah'}, {name: 'ZipCode', value: 'blah'}, {name: 'Country', value: 'blah'}]

3) JSON:

$.ajax({
      url: '/en/Home/Check',
      data: JSON.stringify({ addressInfo:{//missing brackets
          Address1: $('#address1').val(),
          Address2: $('#address2').val(),
          City: $('#City').val(),
          State: $('#State').val(),
          ZipCode: $('#ZipCode').val()}}),
      type: 'POST',
      contentType: 'application/json; charset=utf-8'
});

Data here is a serialized JSON string. Note that the name has to match the parameter name in the server!!

='{"addressInfo":{"Address1":"blah","Address2":"blah","City":"blah","State":"blah", "ZipCode", "blah", "Country", "blah"}}'

jQuery: get the file name selected from <input type="file" />

The simplest way is to simply use the following line of jquery, using this you don't get the /fakepath nonsense, you straight up get the file that was uploaded:

$('input[type=file]')[0].files[0]; // This gets the file
$('#idOfFileUpload')[0].files[0]; // This gets the file with the specified id

Some other useful commands are:

To get the name of the file:

$('input[type=file]')[0].files[0].name; // This gets the file name

To get the type of the file:

If I were to upload a PNG, it would return image/png

$("#imgUpload")[0].files[0].type

To get the size (in bytes) of the file:

$("#imgUpload")[0].files[0].size

Also you don't have to use these commands on('change', you can get the values at any time, for instance you may have a file upload and when the user clicks upload, you simply use the commands I listed.

How can I show three columns per row?

Even though the above answer appears to be correct, I wanted to add a (hopefully) more readable example that also stays in 3 columns form at different widths:

_x000D_
_x000D_
.flex-row-container {_x000D_
    background: #aaa;_x000D_
    display: flex;_x000D_
    flex-wrap: wrap;_x000D_
    align-items: center;_x000D_
    justify-content: center;_x000D_
}_x000D_
.flex-row-container > .flex-row-item {_x000D_
    flex: 1 1 30%; /*grow | shrink | basis */_x000D_
    height: 100px;_x000D_
}_x000D_
_x000D_
.flex-row-item {_x000D_
  background-color: #fff4e6;_x000D_
  border: 1px solid #f76707;_x000D_
}
_x000D_
<div class="flex-row-container">_x000D_
  <div class="flex-row-item">1</div>_x000D_
  <div class="flex-row-item">2</div>_x000D_
  <div class="flex-row-item">3</div>_x000D_
  <div class="flex-row-item">4</div>_x000D_
  <div class="flex-row-item">5</div>_x000D_
  <div class="flex-row-item">6</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Hope this helps someone else.

Checking if a file is a directory or just a file

Use the S_ISDIRmacro:

int isDirectory(const char *path) {
   struct stat statbuf;
   if (stat(path, &statbuf) != 0)
       return 0;
   return S_ISDIR(statbuf.st_mode);
}

Sql Server : How to use an aggregate function like MAX in a WHERE clause

But its still giving an error message in Query Builder. I am using SqlServerCe 2008.

SELECT         Products_Master.ProductName, Order_Products.Quantity, Order_Details.TotalTax, Order_Products.Cost, Order_Details.Discount, 
                     Order_Details.TotalPrice
FROM           Order_Products INNER JOIN
                     Order_Details ON Order_Details.OrderID = Order_Products.OrderID INNER JOIN
                     Products_Master ON Products_Master.ProductCode = Order_Products.ProductCode
HAVING        (Order_Details.OrderID = (SELECT MAX(OrderID) AS Expr1 FROM Order_Details AS mx1))

I replaced WHERE with HAVING as said by @powerlord. But still showing an error.

Error parsing the query. [Token line number = 1, Token line offset = 371, Token in error = SELECT]

Is there a way to get the git root directory in one command?

Yes:

git rev-parse --show-toplevel

If you want to replicate the Git command more directly, you can create an alias:

git config --global alias.root 'rev-parse --show-toplevel'

and now git root will function just as hg root.


Note: In a submodule this will display the root directory of the submodule and not the parent repository. If you are using Git >=2.13 or above, there is a way that submodules can show the superproject's root directory. If your git is older than that, see this other answer.

Passing array in GET for a REST call

Instead of using http GET, use http POST. And JSON. Or XML

This is how your request stream to the server would look like.

POST /appointments HTTP/1.0
Content-Type: application/json
Content-Length: (calculated by your utility)

{users: [user:{id:id1}, user:{id:id2}]}

Or in XML,

POST /appointments HTTP/1.0
Content-Type: application/json
Content-Length: (calculated by your utility)

<users><user id='id1'/><user id='id2'/></users>

You could certainly continue using GET as you have proposed, as it is certainly simpler.

/appointments?users=1d1,1d2

Which means you would have to keep your data structures very simple.

However, if/when your data structure gets more complex, http GET and without JSON, your programming and ability to recognise the data gets very difficult.

Therefore,unless you could keep your data structure simple, I urge you adopt a data transfer framework. If your requests are browser based, the industry usual practice is JSON. If your requests are server-server, than XML is the most convenient framework.

JQuery

If your client is a browser and you are not using GWT, you should consider using jquery REST. Google on RESTful services with jQuery.

How to read barcodes with the camera on Android?

Here is a sample code: my app uses ZXing Barcode Scanner.

  1. You need these 2 classes: IntentIntegrator and IntentResult

  2. Call scanner (e.g. OnClickListener, OnMenuItemSelected...), "PRODUCT_MODE" - it scans standard 1D barcodes (you can add more).:

    IntentIntegrator.initiateScan(this, 
               "Warning", 
               "ZXing Barcode Scanner is not installed, download?",
               "Yes", "No",
               "PRODUCT_MODE");
    
  3. Get barcode as a result:

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {  
      switch (requestCode) {
      case IntentIntegrator.REQUEST_CODE:
         if (resultCode == Activity.RESULT_OK) {
    
            IntentResult intentResult = 
               IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
    
            if (intentResult != null) {
    
               String contents = intentResult.getContents();
               String format = intentResult.getFormatName();
    
               this.elemQuery.setText(contents);
               this.resume = false;
               Log.d("SEARCH_EAN", "OK, EAN: " + contents + ", FORMAT: " + format);
            } else {
               Log.e("SEARCH_EAN", "IntentResult je NULL!");
            }
         } else if (resultCode == Activity.RESULT_CANCELED) {
            Log.e("SEARCH_EAN", "CANCEL");
         }
      }
    }
    

contents holds barcode number

link_to method and click event in Rails

another solution is catching onClick event and for aggregate data to js function you can

.hmtl.erb

<%= link_to "Action", 'javascript:;', class: 'my-class', data: { 'array' => %w(foo bar) } %>

.js

// handle my-class click
$('a.my-class').on('click', function () {
  var link = $(this);
  var array = link.data('array');
});

convert datetime to date format dd/mm/yyyy

DateTime.ToString("dd/MM/yyyy") may give the date in dd-MM-yyyy format. This depends on your short date format. If short date format is not as per format, we have to replace character '-' with '/' as below:

 date = DateTime.Now.ToString("dd/MM/yyyy").Replace('-','/');

Run a controller function whenever a view is opened/shown

If you have assigned a certain controller to your view, then your controller will be invoked every time your view loads. In that case, you can execute some code in your controller as soon as it is invoked, for example this way:

<ion-nav-view ng-controller="indexController" name="other" ng-init="doSomething()"></ion-nav-view>

And in your controller:

app.controller('indexController', function($scope) {
    /*
        Write some code directly over here without any function,
        and it will be executed every time your view loads.
        Something like this:
    */
    $scope.xyz = 1;
});

Edit: You might try to track state changes and then execute some code when the route is changed and a certain route is visited, for example:

$rootScope.$on('$stateChangeSuccess', 
function(event, toState, toParams, fromState, fromParams){ ... })

You can find more details here: State Change Events.

Provide password to ssh command inside bash script, Without the usage of public keys and Expect

For security reasons you must avoid providing password on a command line otherwise anyone running ps command can see your password. Better to use sshpass utility like this:

#!/bin/bash

export SSHPASS="your-password"
sshpass -e ssh -oBatchMode=no sshUser@remoteHost

You might be interested in How to run the sftp command with a password from Bash script?

Adjusting HttpWebRequest Connection Timeout in C#

No matter what we tried we couldn't manage to get the timeout below 21 seconds when the server we were checking was down.

To work around this we combined a TcpClient check to see if the domain was alive followed by a separate check to see if the URL was active

public static bool IsUrlAlive(string aUrl, int aTimeoutSeconds)
{
    try
    {
        //check the domain first
        if (IsDomainAlive(new Uri(aUrl).Host, aTimeoutSeconds))
        {
            //only now check the url itself
            var request = System.Net.WebRequest.Create(aUrl);
            request.Method = "HEAD";
            request.Timeout = aTimeoutSeconds * 1000;
            var response = (HttpWebResponse)request.GetResponse();
            return response.StatusCode == HttpStatusCode.OK;
        }
    }
    catch
    {
    }
    return false;

}

private static bool IsDomainAlive(string aDomain, int aTimeoutSeconds)
{
    try
    {
        using (TcpClient client = new TcpClient())
        {
            var result = client.BeginConnect(aDomain, 80, null, null);

            var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(aTimeoutSeconds));

            if (!success)
            {
                return false;
            }

            // we have connected
            client.EndConnect(result);
            return true;
        }
    }
    catch
    {
    }
    return false;
}

jQuery: load txt file and insert into div

The .load("file.txt") is much easier. Which works but even if testing, you won't get results from a localdrive, you'll need an actual http server. The invisible error is an XMLHttpRequest error.

What Are Some Good .NET Profilers?

Haven't tried it myself, but maybe dotTrace? Their ReSharper application is certainly a good one. Maybe dotTrace is too :)

Apache: client denied by server configuration

if you are having the

Allow from All

in httpd.conf then make sure us have

index.php

like in the below line in httpd.conf

DirectoryIndex index.html index.php

How can I create an object and add attributes to it?

The built-in object can be instantiated but can't have any attributes set on it. (I wish it could, for this exact purpose.) It doesn't have a __dict__ to hold the attributes.

I generally just do this:

class Object(object):
    pass

a = Object()
a.somefield = somevalue

When I can, I give the Object class a more meaningful name, depending on what kind of data I'm putting in it.

Some people do a different thing, where they use a sub-class of dict that allows attribute access to get at the keys. (d.key instead of d['key'])

Edit: For the addition to your question, using setattr is fine. You just can't use setattr on object() instances.

params = ['attr1', 'attr2', 'attr3']
for p in params:
    setattr(obj.a, p, value)

Get the cartesian product of a series of lists?

with itertools.product:

import itertools
result = list(itertools.product(*somelists))

How to write a:hover in inline CSS?

using Javascript:

a) Adding inline style

document.head.insertAdjacentHTML('beforeend', '<style>#mydiv:hover{color:red;}</style>');

b) or a bit harder method - adding "mouseover"

document.getElementById("mydiv").onmouseover= function(e){this.className += ' my-special-class'; };
document.getElementById("mydiv").onmouseleave= function(e){this.className = this.className.replace('my-special-class',''); };

Note: multi-word styles (i.e.font-size) in Javascript are written together:

element.style.fontSize="12px"

How to access data/data folder in Android device?

One of the simple way is to create your database on SD-Card. Because you cannot get access to your phone's data folder in internal memory, unless you root your phone. So why not simply create your database on SD-Card.

Moreover, if you want, you may write some file copying-code to copy your existing database file (from internal memory) to external memory without requiring any root.

What is the difference between re.search and re.match?

The difference is, re.match() misleads anyone accustomed to Perl, grep, or sed regular expression matching, and re.search() does not. :-)

More soberly, As John D. Cook remarks, re.match() "behaves as if every pattern has ^ prepended." In other words, re.match('pattern') equals re.search('^pattern'). So it anchors a pattern's left side. But it also doesn't anchor a pattern's right side: that still requires a terminating $.

Frankly given the above, I think re.match() should be deprecated. I would be interested to know reasons it should be retained.

ssh server connect to host xxx port 22: Connection timed out on linux-ubuntu

I got this error and found that I don't have my SSH port (non standard number) whitelisted in config server firewall.

How do I specify "not equals to" when comparing strings in an XSLT <xsl:if>?

As Filburt says; but also note that it's usually better to write

test="not(Count = 'N/A')"

If there's exactly one Count element they mean the same thing, but if there's no Count, or if there are several, then the meanings are different.

6 YEARS LATER

Since this answer seems to have become popular, but may be a little cryptic to some readers, let me expand it.

The "=" and "!=" operator in XPath can compare two sets of values. In general, if A and B are sets of values, then "=" returns true if there is any pair of values from A and B that are equal, while "!=" returns true if there is any pair that are unequal.

In the common case where A selects zero-or-one nodes, and B is a constant (say "NA"), this means that not(A = "NA") returns true if A is either absent, or has a value not equal to "NA". By contrast, A != "NA" returns true if A is present and not equal to "NA". Usually you want the "absent" case to be treated as "not equal", which means that not(A = "NA") is the appropriate formulation.

SVN "Already Locked Error"

Sometimes cleaning the repository with the "break locks"-option still doesn't work if the lock was created by another process. Possible Solution: 1) Acquire a new lock on the folder/file and choose the option "Steal the locks" 2) Release your new lock.

yii2 hidden input value

Hello World!
You see, the main question while using hidden input is what kind of data you want to pass? I will assume that you are trying to pass the user ID.
Which is not a really good idea to pass it here because field() method will generate input and the value will be shown to user as we can't hide html from the users browser. This if you really care about security of your website.

please check this link, and you will see that it's impossible to hide value attribute from users to see.

so what to do then?

See, this is the core of OOP in PHP. and I quote from Matt Zandstr in his great book PHP Objects, Patterns, and Practice fifth edition

I am still stuck with a great deal of unwanted flexibility, though. I rely on the client coder to change a ShopProduct object’s properties from their default values. This is problematic in two ways. First, it takes five lines to properly initialize a ShopProduct object, and no coder will thank you for that. Second, I have no way of ensuring that any of the properties are set when a ShopProduct object is initialized. What I need is a method that is called automatically when an object is instantiated from a class.


Please check this example of using __construct() method which is mentioned in his book too.

     class ShopProduct { 
       public $title;   
       public $producerMainName;  
       public $producerFirstName;  
       public $price = 0;
    
       public function __construct($title,$firstName,$mainName,$price) {
            $this->title = $title;
            $this->producerFirstName = $firstName;  
            $this->producerMainName = $mainName; 
            $this->price = $price;
    }
 }
     

And you can simply do this magic.

$product1 = new ShopProduct("My Antonia","Willa","Cather",5.99 );
print "author: {$product1->getProducer()}\n";

This produces the following:

author: Willa Cather

In your case it will be something semilar to this, every time you create an object just pass the user ID to the user_id property, and save yourself a lot of coding.

Class Car {
  private $user_id;
//.. your properties

  public function __construct($title,$firstName,$mainName,$price){
     $this->user_id = \Yii::$app->user->id;
    //..Your magic

   }
}

Good luck! And Happy Coding!

how does int main() and void main() work

Neither main() or void main() are standard C. The former is allowed as it has an implicit int return value, making it the same as int main(). The purpose of main's return value is to return an exit status to the operating system.

In standard C, the only valid signatures for main are:

int main(void)

and

int main(int argc, char **argv)

The form you're using: int main() is an old style declaration that indicates main takes an unspecified number of arguments. Don't use it - choose one of those above.

Generating statistics from Git repository

A quick google search lead me to: http://gitstats.sourceforge.net/

Have you tried this project? I'm sure there are similar projects.

lvalue required as left operand of assignment

You need to compare, not assign:

if (strcmp("hello", "hello") == 0)
                             ^

Because you want to check if the result of strcmp("hello", "hello") equals to 0.

About the error:

lvalue required as left operand of assignment

lvalue means an assignable value (variable), and in assignment the left value to the = has to be lvalue (pretty clear).

Both function results and constants are not assignable (rvalues), so they are rvalues. so the order doesn't matter and if you forget to use == you will get this error. (edit:)I consider it a good practice in comparison to put the constant in the left side, so if you write = instead of ==, you will get a compilation error. for example:

int a = 5;
if (a = 0) // Always evaluated as false, no error.
{
    //...
}

vs.

int a = 5;
if (0 = a) // Generates compilation error, you cannot assign a to 0 (rvalue)
{
    //...
}

(see first answer to this question: https://stackoverflow.com/questions/2349378/new-programming-jargon-you-coined)

Why call super() in a constructor?

It simply calls the default constructor of the superclass.

Error 1022 - Can't write; duplicate key in table

As others have mentioned, it's possible that the name for your constraint is already in use by another table in your DB. They must be unique across the database.

A good convention for naming foreign key constraints is:

fk_TableName_ColumnName

To investigate whether there's a possible clash, you can list all constraints used by your database with this query:

SELECT * FROM information_schema.table_constraints WHERE constraint_schema = 'YOUR_DB';

When I ran this query, I discovered I had previously made a temporary copy of a table and this copy was already using the constraint name I was attempting to use.

How do I overload the [] operator in C#

public int this[int key]
{
    get => GetValue(key);
    set => SetValue(key, value);
}

NSString property: copy or retain?

Copy should be used for NSString. If it's Mutable, then it gets copied. If it's not, then it just gets retained. Exactly the semantics that you want in an app (let the type do what's best).

Java reading a file into an ArrayList?

A one-liner with commons-io:

List<String> lines = FileUtils.readLines(new File("/path/to/file.txt"), "utf-8");

The same with guava:

List<String> lines = 
     Files.readLines(new File("/path/to/file.txt"), Charset.forName("utf-8"));

How to append strings using sprintf?

Why do you want to use sprintf for string concatenation when there are methods intended specifically for what you need such as strcat and strncat?

How to use paginator from material angular?

based on Wesley Coetzee's answer i wrote this. Hope it can help anyone googling this issue. I had bugs with swapping the paginator size in the middle of the list that's why i submit my answer:

Paginator html and list

<mat-paginator [length]="localNewspapers.length" pageSize=20
               (page)="getPaginatorData($event)" [pageSizeOptions]="[10, 20, 30]"
               showFirstLastButtons="false">
</mat-paginator>
<mat-list>
   <app-newspaper-pagi-item *ngFor="let paper of (localNewspapers | 
                         slice: lowValue : highValue)"
                         [newspaper]="paper"> 
  </app-newspaper-pagi-item>

Component logic

import {Component, Input, OnInit} from "@angular/core";
import {PageEvent} from "@angular/material";

@Component({
  selector: 'app-uniques-newspaper-list',
  templateUrl: './newspaper-uniques-list.component.html',
})
export class NewspaperUniquesListComponent implements OnInit {
  lowValue: number = 0;
  highValue: number = 20;

  // used to build an array of papers relevant at any given time
  public getPaginatorData(event: PageEvent): PageEvent {
    this.lowValue = event.pageIndex * event.pageSize;
    this.highValue = this.lowValue + event.pageSize;
    return event;
  }

}

Set Font Color, Font Face and Font Size in PHPExcel

I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray() According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.

This will work for you:

$phpExcel = new PHPExcel();

$styleArray = array(
    'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));

$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);

To apply font style to complete excel document:

 $styleArray = array(
   'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));      
 $phpExcel->getDefaultStyle()
    ->applyFromArray($styleArray);

How can I let a table's body scroll but keep its head fixed in place?

If you have low enough standards ;) you could place a table that contains only a header directly above a table that has only a body. It won't scroll horizontally, but if you don't need that...

How do I convert a IPython Notebook into a Python file via commandline?

Jupytext is nice to have in your toolchain for such conversions. It allows not only conversion from a notebook to a script, but you can go back again from the script to notebook as well. And even have that notebook produced in executed form.

jupytext --to py notebook.ipynb                 # convert notebook.ipynb to a .py file
jupytext --to notebook notebook.py              # convert notebook.py to an .ipynb file with no outputs
jupytext --to notebook --execute notebook.py    # convert notebook.py to an .ipynb file and run it 

NuGet behind a proxy

Another flavor for same "proxy for nuget": alternatively you can set your nuget proxing settings to connect through fiddler. Below cmd will save proxy settings in in default nuget config file for user at %APPDATA%\NuGet\NuGet.Config

nuget config -Set HTTP_PROXY=http://127.0.0.1:8888

Whenever you need nuget to reach out the internet, just open Fiddler, asumming you have fiddler listening on default port 8888.

This configuration is not sensitive to passwork changes because fiddler will resolve any authentication with up stream proxy for you.

How to get multiple counts with one SQL query?

Building on other posted answers.

Both of these will produce the right values:

select distributor_id,
    count(*) total,
    sum(case when level = 'exec' then 1 else 0 end) ExecCount,
    sum(case when level = 'personal' then 1 else 0 end) PersonalCount
from yourtable
group by distributor_id

SELECT a.distributor_id,
          (SELECT COUNT(*) FROM myTable WHERE level='personal' and distributor_id = a.distributor_id) as PersonalCount,
          (SELECT COUNT(*) FROM myTable WHERE level='exec' and distributor_id = a.distributor_id) as ExecCount,
          (SELECT COUNT(*) FROM myTable WHERE distributor_id = a.distributor_id) as TotalCount
       FROM myTable a ; 

However, the performance is quite different, which will obviously be more relevant as the quantity of data grows.

I found that, assuming no indexes were defined on the table, the query using the SUMs would do a single table scan, while the query with the COUNTs would do multiple table scans.

As an example, run the following script:

IF OBJECT_ID (N't1', N'U') IS NOT NULL 
drop table t1

create table t1 (f1 int)


    insert into t1 values (1) 
    insert into t1 values (1) 
    insert into t1 values (2)
    insert into t1 values (2)
    insert into t1 values (2)
    insert into t1 values (3)
    insert into t1 values (3)
    insert into t1 values (3)
    insert into t1 values (3)
    insert into t1 values (4)
    insert into t1 values (4)
    insert into t1 values (4)
    insert into t1 values (4)
    insert into t1 values (4)


SELECT SUM(CASE WHEN f1 = 1 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 2 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 3 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 4 THEN 1 else 0 end)
from t1

SELECT 
(select COUNT(*) from t1 where f1 = 1),
(select COUNT(*) from t1 where f1 = 2),
(select COUNT(*) from t1 where f1 = 3),
(select COUNT(*) from t1 where f1 = 4)

Highlight the 2 SELECT statements and click on the Display Estimated Execution Plan icon. You will see that the first statement will do one table scan and the second will do 4. Obviously one table scan is better than 4.

Adding a clustered index is also interesting. E.g.

Create clustered index t1f1 on t1(f1);
Update Statistics t1;

The first SELECT above will do a single Clustered Index Scan. The second SELECT will do 4 Clustered Index Seeks, but they are still more expensive than a single Clustered Index Scan. I tried the same thing on a table with 8 million rows and the second SELECT was still a lot more expensive.

Setting default permissions for newly created files and sub-directories under a directory in Linux?

Here's how to do it using default ACLs, at least under Linux.

First, you might need to enable ACL support on your filesystem. If you are using ext4 then it is already enabled. Other filesystems (e.g., ext3) need to be mounted with the acl option. In that case, add the option to your /etc/fstab. For example, if the directory is located on your root filesystem:

/dev/mapper/qz-root   /    ext3    errors=remount-ro,acl   0  1

Then remount it:

mount -oremount /

Now, use the following command to set the default ACL:

setfacl -dm u::rwx,g::rwx,o::r /shared/directory

All new files in /shared/directory should now get the desired permissions. Of course, it also depends on the application creating the file. For example, most files won't be executable by anyone from the start (depending on the mode argument to the open(2) or creat(2) call), just like when using umask. Some utilities like cp, tar, and rsync will try to preserve the permissions of the source file(s) which will mask out your default ACL if the source file was not group-writable.

Hope this helps!

Setting unique Constraint with fluent API?

Unfortunately this is not supported in Entity Framework. It was on the roadmap for EF 6, but it got pushed back: Workitem 299: Unique Constraints (Unique Indexes)

Creating folders inside a GitHub repository without using Git

When creating a file, use slashes to specify the directory. For example:

Name the file:

repositoryname/newfoldername/filename

GitHub will automatically create a folder with the name newfoldername.

C# get and set properties for a List Collection

Your setters are strange, which is why you may be seeing a problem.

First, consider whether you even need these setters - if so, they should take a List<string>, not just a string:

set
{
    _subHead = value;
}

These lines:

newSec.subHead.Add("test string");

Are calling the getter and then call Add on the returned List<string> - the setter is not invoked.

how to change class name of an element by jquery

$('.IsBestAnswer').removeClass('IsBestAnswer').addClass('bestanswer');

Your code has two problems:

  1. The selector .IsBestAnswe does not match what you thought
  2. It's addClass(), not addclass().

Also, I'm not sure whether you want to replace the class or add it. The above will replace, but remove the .removeClass('IsBestAnswer') part to add only:

$('.IsBestAnswer').addClass('bestanswer');

You should decide whether to use camelCase or all-lowercase in your CSS classes too (e.g. bestAnswer vs. bestanswer).

Upgrade python in a virtualenv

Updated again: The following method might not work in newer versions of virtualenv. Before you try to make modifications to the old virtualenv, you should save the dependencies in a requirement file (pip freeze > requirements.txt) and make a backup of it somewhere else. If anything goes wrong, you can still create a new virtualenv and install the old dependencies in it (pip install -r requirements.txt).

Updated: I changed the answer 5 months after I originally answered. The following method is more convenient and robust.

Side effect: it also fixes the Symbol not found: _SSLv2_method exception when you do import ssl in a virtual environment after upgrading Python to v2.7.8.

Notice: Currently, this is for Python 2.7.x only.


If you're using Homebrew Python on OS X, first deactivate all virtualenv, then upgrade Python:

brew update && brew upgrade python

Run the following commands (<EXISTING_ENV_PATH> is path of your virtual environment):

cd <EXISTING_ENV_PATH>
rm .Python
rm bin/pip{,2,2.7}
rm bin/python{,2,2.7}
rm -r include/python2.7
rm lib/python2.7/*
rm -r lib/python2.7/distutils
rm lib/python2.7/site-packages/easy_install.*
rm -r lib/python2.7/site-packages/pip
rm -r lib/python2.7/site-packages/pip-*.dist-info
rm -r lib/python2.7/site-packages/setuptools
rm -r lib/python2.7/site-packages/setuptools-*.dist-info

Finally, re-create your virtual environment:

virtualenv <EXISTING_ENV_PATH>

By doing so, old Python core files and standard libraries (plus setuptools and pip) are removed, while the custom libraries installed in site-packages are preserved and working, as soon as they are in pure Python. Binary libraries may or may not need to be reinstalled to function properly.

This worked for me on 5 virtual environments with Django installed.

BTW, if ./manage.py compilemessages is not working afterwards, try this:

brew install gettext && brew link gettext --force

How to move child element from one parent to another using jQuery

As Jage's answer removes the element completely, including event handlers and data, I'm adding a simple solution that doesn't do that, thanks to the detach function.

var element = $('#childNode').detach();
$('#parentNode').append(element);

Edit:

Igor Mukhin suggested an even shorter version in the comments below:

$("#childNode").detach().appendTo("#parentNode");

How to check certificate name and alias in keystore files?

In order to get all the details I had to add the -v option to romaintaz answer:

keytool -v -list -keystore <FileName>.keystore

Split a string by another string in C#

As of .NET Core 2.0, there is an override that takes a string.

So now you can do "THExxQUICKxxBROWNxxFOX".Split("xx").

See https://docs.microsoft.com/en-us/dotnet/api/system.string.split?view=netcore-2.0#System_String_Split_System_String_System_StringSplitOptions_

mysql error 1364 Field doesn't have a default values

Before every insert action I added below line and solved my issue,

SET SQL_MODE = '';

I'm not sure if this is the best solution,

SET SQL_MODE = ''; INSERT INTO  `mytable` (  `field1` ,  `field2`) VALUES ('value1',  'value2');

jquery how to catch enter key and change event to tab

These solutions didn't work with my datagrid. I was hoping they would. I don't really need Tab or Enter to move to the next input, column, row or whatever. I just need Enter to trigger .focusout or .change and my datagrid updates the database. So I added the "enter" class to the relevant text inputs and this did the trick for me:

$(function() {
   if ($.browser.mozilla) {
        $(".enter").keypress(checkForEnter);
    } else {
        $(".enter").keydown(checkForEnter);
    }
});

function checkForEnter(event) {
    if (event.keyCode == 13) {
        $(".enter").blur();
    }
}

How to replicate background-attachment fixed on iOS

It looks to me like the background images aren't actually background images...the site has the background images and the quotes in sibling divs with the children of the div containing the images having been assigned position: fixed; The quotes div is also given a transparent background.

wrapper div{
   image wrapper div{
       div for individual image{ <--- Fixed position
          image <--- relative position
       }
   }
   quote wrapper div{
       div for individual quote{
          quote
       }
   }
 }

Detecting user leaving page with react-router

You can use this prompt.

import React, { Component } from "react";
import { BrowserRouter as Router, Route, Link, Prompt } from "react-router-dom";

function PreventingTransitionsExample() {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <Link to="/">Form</Link>
          </li>
          <li>
            <Link to="/one">One</Link>
          </li>
          <li>
            <Link to="/two">Two</Link>
          </li>
        </ul>
        <Route path="/" exact component={Form} />
        <Route path="/one" render={() => <h3>One</h3>} />
        <Route path="/two" render={() => <h3>Two</h3>} />
      </div>
    </Router>
  );
}

class Form extends Component {
  state = { isBlocking: false };

  render() {
    let { isBlocking } = this.state;

    return (
      <form
        onSubmit={event => {
          event.preventDefault();
          event.target.reset();
          this.setState({
            isBlocking: false
          });
        }}
      >
        <Prompt
          when={isBlocking}
          message={location =>
            `Are you sure you want to go to ${location.pathname}`
          }
        />

        <p>
          Blocking?{" "}
          {isBlocking ? "Yes, click a link or the back button" : "Nope"}
        </p>

        <p>
          <input
            size="50"
            placeholder="type something to block transitions"
            onChange={event => {
              this.setState({
                isBlocking: event.target.value.length > 0
              });
            }}
          />
        </p>

        <p>
          <button>Submit to stop blocking</button>
        </p>
      </form>
    );
  }
}

export default PreventingTransitionsExample;

A long bigger than Long.MAX_VALUE

If triangle.lborderA is indeed a long then the test in the original code is trivially true, and there is no way to test it. It is also useless.

However, if triangle.lborderA is a double, the comparison is useful and can be tested. isBiggerThanMaxLong(1e300) does return true.

  public static boolean isBiggerThanMaxLong(double in){
    return in > Long.MAX_VALUE;
  }

Cleanest way to reset forms

Angular Reactive Forms:

onCancel(): void {
  this.registrationForm.reset();
  this.registrationForm.controls['name'].setErrors(null);
  this.registrationForm.controls['email'].setErrors(null);
}

How to check type of object in Python?

use isinstance(v, type_name) or type(v) is type_name or type(v) == type_name,

where type_name can be one of the following:

  • None
  • bool
  • int
  • float
  • complex
  • str
  • list
  • tuple
  • set
  • dict

and, of course,

  • custom types (classes)

How can I pipe stderr, and not stdout?

I just came up with a solution for sending stdout to one command and stderr to another, using named pipes.

Here goes.

mkfifo stdout-target
mkfifo stderr-target
cat < stdout-target | command-for-stdout &
cat < stderr-target | command-for-stderr &
main-command 1>stdout-target 2>stderr-target

It's probably a good idea to remove the named pipes afterward.

Reading rows from a CSV file in Python

#  This program reads columns in a csv file
import csv
ifile = open('years.csv', "r")
reader = csv.reader(ifile)

# initialization and declaration of variables
rownum = 0
year = 0
dec = 0
jan = 0
total_years = 0`

for row in reader:
    if rownum == 0:
        header = row  #work with header row if you like
    else:
    colnum = 0
    for col in row:
        if colnum == 0:
            year = float(col)
        if colnum == 1:
            dec = float(col)
        if colnum == 2:
            jan = float(col)
        colnum += 1
    # end of if structure

# now we can process results
if rownum != 0:
    print(year, dec, jan)
    total_years = total_years + year
    print(total_years)

# time to go after the next row/bar
rownum += 1

ifile.close()

A bit late but nonetheless... You need to create and identify the csv file named "years.csv":

Year Dec Jan 1 50 60 2 25 50 3 30 30 4 40 20 5 10 10

Simplest way to serve static data from outside the application server in a Java web application

Add to server.xml :

 <Context docBase="c:/dirtoshare" path="/dir" />

Enable dir file listing parameter in web.xml :

    <init-param>
        <param-name>listings</param-name>
        <param-value>true</param-value>
    </init-param>

Remove Primary Key in MySQL

First modify the column to remove the auto_increment field like this: alter table user_customer_permission modify column id int;

Next, drop the primary key. alter table user_customer_permission drop primary key;

Git - How to close commit editor?

Better yet, configure the editor to something you are comfortable with (gedit as an example):

git config --global core.editor "gedit"

You can read the current configuration like this:

git config core.editor

You can also add the commit message from the command line.

git commit -m "blablabla"

and the editor will not be opened in the first place.

How to check if a URL exists or returns 404 with Java?

There is nothing wrong with your code. It's the NBC.com doing tricks on you. When NBC.com decides that your browser is not capable of displaying PDF, it simply sends back a webpage regardless what you are requesting, even if it doesn't exist.

You need to trick it back by telling it your browser is capable, something like,

conn.setRequestProperty("User-Agent",
    "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13");

Inserting data into a MySQL table using VB.NET

  • First, You missed this one: sqlCommand.CommandType = CommandType.Text
  • Second, Your MySQL Parameter Declaration is wrong. It should be @ and not ?

try this:

Public Function InsertCar() As Boolean

    Dim iReturn as boolean
    Using SQLConnection As New MySqlConnection(connectionString)
        Using sqlCommand As New MySqlCommand()
            With sqlCommand
                .CommandText = "INSERT INTO members_car (`car_id`, `member_id`, `model`, `color`, `chassis_id`, `plate_number`, `code`) values (@xid,@m_id,@imodel,@icolor,@ch_id,@pt_num,@icode)"
                .Connection = SQLConnection
                .CommandType = CommandType.Text // You missed this line
                .Parameters.AddWithValue("@xid", TextBox20.Text)
                .Parameters.AddWithValue("@m_id", TextBox20.Text)
                .Parameters.AddWithValue("@imodel", TextBox23.Text)
                .Parameters.AddWithValue("@icolor", TextBox24.Text)
                .Parameters.AddWithValue("@ch_id", TextBox22.Text)
                .Parameters.AddWithValue("@pt_num", TextBox21.Text)
                .Parameters.AddWithValue("@icode", ComboBox1.SelectedItem)
            End With
            Try
                SQLConnection.Open()
                sqlCommand.ExecuteNonQuery()
                iReturn = TRUE
            Catch ex As MySqlException
                MsgBox ex.Message.ToString
                iReturn = False
            Finally
                SQLConnection.Close()
            End Try
        End Using
    End Using

   Return iReturn

End Function

How to access command line arguments of the caller inside a function?

You can use the shift keyword (operator?) to iterate through them. Example:

#!/bin/bash
function print()
{
    while [ $# -gt 0 ]
    do
        echo $1;
        shift 1;
    done
}
print $*;

CSS align images and text on same line

You can either use (on the h4 elements, as they are block by default)

display: inline-block;

Or you can float the elements to the left/rght

float: left;

Just don't forget to clear the floats after

clear: left;

More visual example for the float left/right option as shared below by @VSB:

_x000D_
_x000D_
<h4> _x000D_
    <div style="float:left;">Left Text</div>_x000D_
    <div style="float:right;">Right Text</div>_x000D_
    <div style="clear: left;"/>_x000D_
</h4>
_x000D_
_x000D_
_x000D_

How to set a transparent background of JPanel?

(Feature Panel).setOpaque(false);

Hope this helps.

:before and background-image... should it work?

you can set an image URL for the content prop instead of the background-image.

content: url(/img/border-left3.png);

Can you append strings to variables in PHP?

This is because PHP uses the period character . for string concatenation, not the plus character +. Therefore to append to a string you want to use the .= operator:

for ($i=1;$i<=100;$i++)
{
    $selectBox .= '<option value="' . $i . '">' . $i . '</option>';
}
$selectBox .= '</select>';