Programs & Examples On #Rest client

REST Client is an open-source HTTP and REST client for Ruby.

How to download excel (.xls) file from API in postman?

Try selecting send and download instead of send when you make the request. (the blue button)

https://www.getpostman.com/docs/responses

"For binary response types, you should select Send and download which will let you save the response to your hard disk. You can then view it using the appropriate viewer."

Inserting HTML elements with JavaScript

Instead of directly messing with innerHTML it might be better to create a fragment and then insert that:

function create(htmlStr) {
    var frag = document.createDocumentFragment(),
        temp = document.createElement('div');
    temp.innerHTML = htmlStr;
    while (temp.firstChild) {
        frag.appendChild(temp.firstChild);
    }
    return frag;
}

var fragment = create('<div>Hello!</div><p>...</p>');
// You can use native DOM methods to insert the fragment:
document.body.insertBefore(fragment, document.body.childNodes[0]);

Benefits:

  1. You can use native DOM methods for insertion such as insertBefore, appendChild etc.
  2. You have access to the actual DOM nodes before they're inserted; you can access the fragment's childNodes object.
  3. Using document fragments is very quick; faster than creating elements outside of the DOM and in certain situations faster than innerHTML.

Even though innerHTML is used within the function, it's all happening outside of the DOM so it's much faster than you'd think...

How to compare each item in a list with the rest, only once?

I think using enumerate on the outer loop and using the index to slice the list on the inner loop is pretty Pythonic:

for index, this in enumerate(mylist):
    for that in mylist[index+1:]:
        compare(this, that)

Why do people hate SQL cursors so much?

Cursors make people overly apply a procedural mindset to a set-based environment.

And they are SLOW!!!

From SQLTeam:

Please note that cursors are the SLOWEST way to access data inside SQL Server. The should only be used when you truly need to access one row at a time. The only reason I can think of for that is to call a stored procedure on each row. In the Cursor Performance article I discovered that cursors are over thirty times slower than set based alternatives.

How to get selenium to wait for ajax response?

For those who is using primefaces, just do:

selenium.waitForCondition("selenium.browserbot.getCurrentWindow().$.active==0", defaultWaitingPeriod);

What is use of c_str function In c++

c_str() converts a C++ string into a C-style string which is essentially a null terminated array of bytes. You use it when you want to pass a C++ string into a function that expects a C-style string (e.g. a lot of the Win32 API, POSIX style functions, etc).

Cross origin requests are only supported for HTTP but it's not cross-domain

For all python users:

Simply go to your destination folder in the terminal.

cd projectFoder

then start HTTP server For Python3+:

python -m http.server 8000

Serving HTTP on :: port 8000 (http://[::]:8000/) ...

go to your link: http://0.0.0.0:8000/

Enjoy :)

How to validate a file upload field using Javascript/jquery

Building on Ravinders solution, this code stops the form being submitted. It might be wise to check the extension at the server-side too. So you don't get hackers uploading anything they want.

<script>
var valid = false;

function validate_fileupload(input_element)
{
    var el = document.getElementById("feedback");
    var fileName = input_element.value;
    var allowed_extensions = new Array("jpg","png","gif");
    var file_extension = fileName.split('.').pop(); 
    for(var i = 0; i < allowed_extensions.length; i++)
    {
        if(allowed_extensions[i]==file_extension)
        {
            valid = true; // valid file extension
            el.innerHTML = "";
            return;
        }
    }
    el.innerHTML="Invalid file";
    valid = false;
}

function valid_form()
{
    return valid;
}
</script>

<div id="feedback" style="color: red;"></div>
<form method="post" action="/image" enctype="multipart/form-data">
  <input type="file" name="fileName" accept=".jpg,.png,.bmp" onchange="validate_fileupload(this);"/>
  <input id="uploadsubmit" type="submit" value="UPLOAD IMAGE" onclick="return valid_form();"/>
</form>

How can I get the current network interface throughput statistics on Linux/UNIX?

  • dstat - Combines vmstat, iostat, ifstat, netstat information and more
  • iftop - Amazing network bandwidth utility to analyse what is really happening on your eth
  • netio - Measures the net throughput of a network via TCP/IP
  • inq - CLI troubleshooting utility that displays info on storage, typically Symmetrix. By default, INQ returns the device name, Symmetrix ID, Symmetrix LUN, and capacity.
  • send_arp - Sends out an arp broadcast on the specified network device (defaults to eth0), reporting an old and new IP address mapping to a MAC address.
  • EtherApe - is a graphical network monitor for Unix modeled after etherman. Featuring link layer, IP and TCP modes, it displays network activity graphically.
  • iptraf - An IP traffic monitor that shows information on the IP traffic passing over your network.

More details: http://felipeferreira.net/?p=1194

How can I escape a double quote inside double quotes?

Make use of $"string".

In this example, it would be,

dbload=$"load data local infile \"'gfpoint.csv'\" into table $dbtable FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY \"'\n'\" IGNORE 1 LINES"

Note(from the man page):

A double-quoted string preceded by a dollar sign ($"string") will cause the string to be translated according to the current locale. If the current locale is C or POSIX, the dollar sign is ignored. If the string is translated and replaced, the replacement is double-quoted.

How to create an empty array in Swift?

Here are some common tasks in Swift 4 you can use as a reference until you get used to things.

    let emptyArray = [String]()
    let emptyDouble: [Double] = []

    let preLoadArray = Array(repeating: 0, count: 10) // initializes array with 10 default values of the number 0

    let arrayMix = [1, "two", 3] as [Any]
    var arrayNum = [1, 2, 3]
    var array = ["1", "two", "3"]
    array[1] = "2"
    array.append("4")
    array += ["5", "6"]
    array.insert("0", at: 0)
    array[0] = "Zero"
    array.insert(contentsOf: ["-3", "-2", "-1"], at: 0)
    array.remove(at: 0)
    array.removeLast()
    array = ["Replaces all indexes with this"]
    array.removeAll()

    for item in arrayMix {
        print(item)
    }

    for (index, element) in array.enumerated() {
        print(index)
        print(element)
    }

    for (index, _) in arrayNum.enumerated().reversed() {
        arrayNum.remove(at: index)
    }

    let words = "these words will be objects in an array".components(separatedBy: " ")
    print(words[1])

    var names = ["Jemima", "Peter", "David", "Kelly", "Isabella", "Adam"]
    names.sort() // sorts names in alphabetical order

    let nums = [1, 1234, 12, 123, 0, 999]
    print(nums.sorted()) // sorts numbers from lowest to highest

How do I get a file's last modified time in Perl?

I think you're looking for the stat function (perldoc -f stat)

In particular, the 9th field (10th, index #9) of the returned list is the last modify time of the file in seconds since the epoch.

So:

my $last_modified = (stat($fh))[9];

Best way to "negate" an instanceof

You can achieve by doing below way.. just add a condition by adding bracket if(!(condition with instanceOf)) with the whole condition by adding ! operator at the start just the way mentioned in below code snippets.

if(!(str instanceof String)) { /* do Something */ } // COMPILATION WORK

instead of

if(str !instanceof String) { /* do Something */ } // COMPILATION FAIL

How to make an app's background image repeat

Here is a pure-java implementation of background image repeating:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.bg_image);
    BitmapDrawable bitmapDrawable = new BitmapDrawable(bmp);
    bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
    LinearLayout layout = new LinearLayout(this);
    layout.setBackgroundDrawable(bitmapDrawable);
}

In this case, our background image would have to be stored in res/drawable/bg_image.png.

dbms_lob.getlength() vs. length() to find blob size in oracle

length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

how to get program files x86 env variable?

On a Windows 64 bit machine, echo %programfiles(x86)% does print C:\Program Files (x86)

How to generate a GUID in Oracle?

You can run the following query

 select sys_guid() from dual
 union all
 select sys_guid() from dual
 union all 
 select sys_guid() from dual

Android Studio - Emulator - eglSurfaceAttrib not implemented

Fix: Unlock your device before running it.

Hi Guys: Think I may have a fix for this:

Sounds ridiculous but try unlocking your Virtual Device; i.e. use your mouse to swipe and open. Your app should then work!!

How can I make git accept a self signed certificate?

To disable SSL verification for a specific repository If the repository is completely under your control, you can try:

 git config --global http.sslVerify false

Adding 30 minutes to time formatted as H:i in PHP

$time = strtotime('10:00');
$startTime = date("H:i", strtotime('-30 minutes', $time));
$endTime = date("H:i", strtotime('+30 minutes', $time));

Using FileUtils in eclipse

I have come accross the above issue. I have solved it as below. Its working fine for me.

  1. Download the 'org.apache.commons.io.jar' file on navigating to [org.apache.commons.io.FileUtils] [ http://www.java2s.com/Code/Jar/o/Downloadorgapachecommonsiojar.htm ]

  2. Extract the downloaded zip file to a specified folder.

  3. Update the project properties by using below navigation Right click on project>Select Properties>Select Java Build Path> Click Libraries tab>Click Add External Class Folder button>Select the folder where zip file is extracted for org.apache.commons.io.FileUtils.zip file.

  4. Now access the File Utils.

Check if a string is a valid date using DateTime.TryParse

[TestCase("11/08/1995", Result= true)]
[TestCase("1-1", Result = false)]
[TestCase("1/1", Result = false)]
public bool IsValidDateTimeTest(string dateTime)
{
    string[] formats = { "MM/dd/yyyy" };
    DateTime parsedDateTime;
    return DateTime.TryParseExact(dateTime, formats, new CultureInfo("en-US"),
                                   DateTimeStyles.None, out parsedDateTime);
}

Simply specify the date time formats that you wish to accept in the array named formats.

Find text string using jQuery?

Take a look at highlight (jQuery plugin).

Split a python list into other "sublists" i.e smaller lists

I'd say

chunks = [data[x:x+100] for x in range(0, len(data), 100)]

If you are using python 2.x instead of 3.x, you can be more memory-efficient by using xrange(), changing the above code to:

chunks = [data[x:x+100] for x in xrange(0, len(data), 100)]

How can I use Ruby to colorize the text output to a terminal?

I wrote a little method to test out the basic color modes, based on answers by Erik Skoglund and others.

#outputs color table to console, regular and bold modes
def colortable
  names = %w(black red green yellow blue pink cyan white default)
  fgcodes = (30..39).to_a - [38]

  s = ''
  reg  = "\e[%d;%dm%s\e[0m"
  bold = "\e[1;%d;%dm%s\e[0m"
  puts '                       color table with these background codes:'
  puts '          40       41       42       43       44       45       46       47       49'
  names.zip(fgcodes).each {|name,fg|
    s = "#{fg}"
    puts "%7s "%name + "#{reg}  #{bold}   "*9 % [fg,40,s,fg,40,s,  fg,41,s,fg,41,s,  fg,42,s,fg,42,s,  fg,43,s,fg,43,s,  
      fg,44,s,fg,44,s,  fg,45,s,fg,45,s,  fg,46,s,fg,46,s,  fg,47,s,fg,47,s,  fg,49,s,fg,49,s ]
  }
end

example output: ruby colortest

Delete all nodes and relationships in neo4j 1.8

Neo4j cannot delete nodes that have a relation. You have to delete the relations before you can delete the nodes.

But, it is simple way to delete "ALL" nodes and "ALL" relationships with a simple chyper. This is the code:

MATCH (n) DETACH DELETE n

--> DETACH DELETE will remove all of the nodes and relations by Match

How to exit from ForEach-Object in PowerShell

Since ForEach-Object is a cmdlet, break and continue will behave differently here than with the foreach keyword. Both will stop the loop but will also terminate the entire script:

break:

0..3 | foreach {
    if ($_ -eq 2) { break }
    $_
}
echo "Never printed"

# OUTPUT:
# 0
# 1

continue:

0..3 | foreach {
    if ($_ -eq 2) { continue }
    $_
}
echo "Never printed"

# OUTPUT:
# 0
# 1

So far, I have not found a "good" way to break a foreach script block without breaking the script, except "abusing" exceptions:

throw:

try {
    0..3 | foreach {
        if ($_ -eq 2) { throw }
        $_
    }
} catch { }
echo "End"

# OUTPUT:
# 0
# 1
# End

The alternative (which is not always possible) would be to use the foreach keyword:

foreach:

foreach ($_ in (0..3)) {
    if ($_ -eq 2) { break }
    $_
}
echo "End"

# OUTPUT:
# 0
# 1
# End

Can multiple different HTML elements have the same ID if they're different elements?

How about a pragmatic answer.

Let's go to youtube and run this code

Object.fromEntries(Object.entries([...document.querySelectorAll('[id]')].reduce((s, e) => { s[e.id] = (s[e.id] || 0) + 1; return s; }, {})).filter(([k,v]) => v > 1))

and see all the repeated ids.

enter image description here

Changing the code above to show ids repeated more than 10 times here's the list it produced

additional-metadata-line: 43
avatar: 46
avatar-link: 43
button: 120
buttons: 45
byline-container: 45
channel-name: 44
container: 51
content: 49
details: 43
dismissable: 46
dismissed: 46
dismissed-content: 43
hover-overlays: 45
img: 90
menu: 50
meta: 44
metadata: 44
metadata-line: 43
mouseover-overlay: 45
overlays: 45
repeat: 36
separator: 43
text: 49
text-container: 44
thumbnail: 46
tooltip: 80
top-level-buttons: 45
video-title: 43
video-title-link: 43

Other sites that use the same id more than once include Amazon.com, ebay.com, expedia.com, cnn.com

clearly ids are just another piece of metadata on an element.

getElementById is pretty much obsolete. You can use querySelectorAll for all elements or querySelector for the first, regardless of selector so if you want all elements with id foo then

document.querySelectorAll('#foo')  // returns all elements with id="foo"

where as if you want only the first element use querySelector

document.querySelector('#foo')  // returns the first element with id="foo"
document.querySelector('.foo')  // returns the first element with class "foo"
document.querySelector('foo')   // returns the first <foo> element
document.querySelector('foo .foo #foo') // returns the first element with
                                        // id="foo" that has an ancestor
                                        // with class "foo" who has an
                                        // ancestor <foo> element.

And we can see that using selectors we can find different elements with the same id.

_x000D_
_x000D_
function addClick(selector, add) {
  document.querySelector(selector).addEventListener('click', function() {
    const e = this.parentElement.querySelector('span');
    e.textContent = parseInt(e.textContent) + add;
  });
}
addClick('.e #foo', 1);
addClick('.f #foo', 10);
_x000D_
body { font-size: x-large; font-weight: bold; }
.a #foo { color: red; }
.b #foo { color: green; }
div:nth-child(3) #foo { color: blue; }
#foo { color: purple }
_x000D_
<div class="a"><span id="foo">a</span></div>
<div class="b"><span id="foo">b</span></div>
<div><span id="foo">c</span></div>
<span id="foo">d</span>
<div class="e"><button type="button" id="foo">+1</button>: <span>0</span></div>
<div class="f"><button type="button" id="foo">+10</button>: <span>0</span></div>
_x000D_
_x000D_
_x000D_

Where it matters that id is unique

  • <a> tags can reference ids as in <a href="#foo">. Clicking it will jump the document to the first element with id="foo". Similarly the hash tag in the URL which is effectively the same feature.

  • <label> tags have a for attribute that specifies which element they are labeling by id. Clicking the label clicks/activates/give-the-focus-to the corresponding element. The label will only affect the first element with a matching id

_x000D_
_x000D_
label { user-select: none; }
_x000D_
<p>nested for checking</p>
<form>
  <div><input type="checkbox" id="foo"><label for="foo">foo</label></div>
</form>
<form>
  <div><input type="checkbox" id="foo"><label for="foo">foo (clicking here will check first checkbox)</label></div>
</form>
_x000D_
_x000D_
_x000D_

Otherwise, id is just another tool in your toolbox.

set the iframe height automatically

Try this coding

<div>
    <iframe id='iframe2' src="Mypage.aspx" frameborder="0" style="overflow: hidden; height: 100%;
        width: 100%; position: absolute;"></iframe>
</div>

What is the documents directory (NSDocumentDirectory)?

You can access documents directory using this code it is basically used for storing file in plist format:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
return documentsDirectory;

Apply .gitignore on an existing repository already tracking large number of files

As specified here You can update the index:

git update-index --assume-unchanged /path/to/file

By doing this, the files will not show up in git status or git diff.

To begin tracking the files again you can run:

git update-index --no-assume-unchanged /path/to/file

How to import a csv file into MySQL workbench?

At the moment it is not possible to import a CSV (using MySQL Workbench) in all platforms, nor is advised if said file does not reside in the same host as the MySQL server host.

However, you can use mysqlimport.

Example:

mysqlimport --local --compress --user=username --password --host=hostname \
--fields-terminated-by=',' Acme sales.part_*

In this example mysqlimport is instructed to load all of the files named "sales" with an extension starting with "part_". This is a convenient way to load all of the files created in the "split" example. Use the --compress option to minimize network traffic. The --fields-terminated-by=',' option is used for CSV files and the --local option specifies that the incoming data is located on the client. Without the --local option, MySQL will look for the data on the database host, so always specify the --local option.

There is useful information on the subject in AWS RDS documentation.

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

There are two reasons for this error

1) In the array of import if you imported HttpModule twice

enter image description here

2) If you haven't import:

import { HttpModule, JsonpModule } from '@angular/http'; 

If you want then run:

npm install @angular/http

Generating UML from C++ code?

Seems Umbrello produces best UML from C++ code (suggest to use latest version >= 2.22) comparing to command-line autodia for Dia and other tools.

StarUML have not produced good diagrams for me: strange import, not usable, does not work for many people: https://github.com/staruml/Cpp/issues

T-SQL Substring - Last 3 Characters

if you want to specifically find strings which ends with desired characters then this would help you...

select * from tablename where col_name like '%190'

jQuery multiple conditions within if statement

i == 'InvKey' && i == 'PostDate' will never be true, since i can never equal two different things at once.

You're probably trying to write

if (i !== 'InvKey' && i !== 'PostDate')) 

Auto-indent in Notepad++

Menu TextFX ? TextFX Edit ? Reindent C++ code

enter image description here

But, Notepad++ doesn't come with this "Text FX Character" plugin. You will need to install it via

Plugins ? Plugin Manager ? Show Plugin Manager.

To add shortcut for Indentation.

Click on Settings ? Shortcut Mapper... set the shortcut key you prefer. I prefer Ctrl + =.

Enter image description here

How to fix 'Microsoft Excel cannot open or save any more documents'

Test like this.Sometimes, permission problem.

cmd => dcomcnfg

Click

Component services >Computes >My Computer>Dcom config> and select micro soft Excel Application

Right Click on microsoft Excel Application

Properties>Give Asp.net Permissions

Select Identity table >Select interactive user >select ok

Git commit with no commit message

You don't need git to accomplish this. Creative use of a bash function will do the trick just fine. If you don't care about messages, just set a default one and forget it.

function gitcom() {
  git commit -m "my default commit message"
}

If you were feeling really adventurous you could add, commit and push with one command

function gitzap() {
  git add . && git commit -m "whatevs" && git push $1 $2
}

Which you would then run as

gitzap origin master

You could even get deeper and use parse_git_branch to save yourself some keystrokes there, or set a common default of "origin" and "master".

Converting xml to string using C#

   public string GetXMLAsString(XmlDocument myxml)
    {
        using (var stringWriter = new StringWriter())
        {
            using (var xmlTextWriter = XmlWriter.Create(stringWriter))
            {
               myxml.WriteTo(xmlTextWriter);
               return stringWriter.ToString();
            }

        }    
}

How to upload files to server using JSP/Servlet?

You first have to set the enctype attribute of the form to "multipart/form-data"

This is shown below.

<form action="Controller" method="post" enctype="multipart/form-data">
     <label class="file-upload"> Click here to upload an Image </label>
     <input type="file" name="file" id="file" required> 
</form>

And then, in the Servlet "Controller" add the Annotation for a Multi-part to indicate multipart data is processed in the servlet.

After doing this, retrieve the part sent through the form and then retrieve the file name (with path)of the submitted file. Use this to create a new file in the desired path and write the parts of the file to the newly created file to recreate the file.

As shown below:

@MultipartConfig

public class Controller extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        insertImage(request, response);
    }

    private void addProduct(HttpServletRequest request, HttpServletResponse response) {
        Part filePart = request.getPart("file");
        String imageName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();

        String imageSavePath = "specify image path to save image"; //path to save image
        FileOutputStream outputStream = null;
        InputStream fileContent = null;

        try {
            outputStream = new FileOutputStream(new File(imageSavePath + File.separator + imageName));
            //creating a new file with file path and the file name
            fileContent = filePart.getInputStream();
            //getting the input stream
            int readBytes = 0;
            byte[] readArray = new byte[1024];
            //initializing a byte array with size 1024

            while ((readBytes = fileContent.read(readArray)) != -1) {
                outputStream.write(readArray, 0, readBytes);
            }//this loop will write the contents of the byte array unitl the end to the output stream
        } catch (Exception ex) {
            System.out.println("Error Writing File: " + ex);
        } finally {
            if (outputStream != null) {
                outputStream.close();
                //closing the output stream
            }
            if (fileContent != null) {
                fileContent.close();
                //clocsing the input stream
            }
        }
    }
}

How to copy selected lines to clipboard in vim

First check if your vim installation has clipboard support.

vim --version

If clipboard support is installed you will see:

+clipboard
+X11
+xterm_clipboard

If clipboard support is not installed you will see:

-clipboard
-X11
-xterm_clipboard

To install clipboard support:

apt-get install vim-gnome

Once you have verified that clipboard support is installed do the following:

  1. Position your cursor to the first line you want to copy.
  2. Press Shiftv to enter visual mode.
  3. Press ? to select multiple lines
  4. Press "+y to copy the selected text to system clipboard.
  5. Now you can copy the selected text to browser, text editor etc.
  6. Press "+p if you want to copy system clipboard text to vim.

Above steps might get tedious if you have to repeatedly copy from vim to system clipboard and vice versa. You can create vim shortcuts so that when you press Ctrlc selected text will be copied to system clipboard. And when you press Ctrlp system clipboard text is copied to vim. To create shortcuts :

  1. Open .vimrc file and add following text at the end of file:

     nnoremap <C-c> "+y
     vnoremap <C-c> "+y
     nnoremap <C-p> "+p
     vnoremap <C-p> "+p
    
  2. Save and reload your .vimrc to apply the new changes.

  3. Position your cursor to the first line you want to copy.

  4. Press Shiftv to enter visual mode.

  5. Press ? to select multiple lines

  6. Press Ctrlc to copy the selected text to system clipboard.

  7. Now you can copy the selected text to browser, text editor etc.

  8. Press Ctrlp if you want to copy system clipboard text to vim.

Note: This is for ubuntu systems.

logout and redirecting session in php

Only this is necessary

session_start();
unset($_SESSION["nome"]);  // where $_SESSION["nome"] is your own variable. if you do not have one use only this as follow **session_unset();**
header("Location: home.php");

Does Android keep the .apk files? if so where?

If you're looking for the path of a specific app, a quick and dirty solution is to just grep the bugreport:

$ adb bugreport | grep 'dir=/data/app' 

I don't know that this will provide an exhaustive list, so it may help to run the app first.

HTTP Headers for File Downloads

Acoording to RFC 2046 (Multipurpose Internet Mail Extensions):

The recommended action for an implementation that receives an
"application/octet-stream" entity is to simply offer to put the data in a file

So I'd go for that one.

How to truncate text in Angular2?

Limit length based on words

Try this one, if you want to truncate based on Words instead of characters while also allowing an option to see the complete text.

Came here searching for a Read More solution based on words, sharing the custom Pipe i ended up writing.

Pipe:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'readMore'
})
export class ReadMorePipe implements PipeTransform {

  transform(text: any, length: number = 20, showAll: boolean = false, suffix: string = '...'): any {
    
    if (showAll) {
      return text;
    }

    if ( text.split(" ").length > length ) {
      
      return text.split(" ").splice(0, length).join(" ") + suffix;
    }

    return text;
  }

}

In Template:

<p [innerHTML]="description | readMore:30:showAll"></p>
<button (click)="triggerReadMore()" *ngIf="!showAll">Read More<button>

Component:

export class ExamplePage implements OnInit {

    public showAll: any = false;
    
    triggerReadMore() {
        this.showAll = true;
    }
    
}

In Module:

import { ReadMorePipe } from '../_helpers/read-more.pipe';

@NgModule({
  declarations: [ReadMorePipe]
})
export class ExamplePageModule {}

Fatal error: Maximum execution time of 30 seconds exceeded

if all the above didn't work for you then add an .htaccess file to the directory where your script is located and put this inside

<IfModule mod_php5.c>
php_value post_max_size 200M
php_value upload_max_filesize 200M
php_value memory_limit 300M
php_value max_execution_time 259200
php_value max_input_time 259200
php_value session.gc_maxlifetime 1200
</IfModule>

this was the way I solved my problem , neither ini_set('max_execution_time', 86400); nor set_time_limit(86400) solved my problem , but the .htaccess method did.

How do you query for "is not null" in Mongo?

db.collection_name.find({"filed_name":{$exists:true}});

fetch documents that contain this filed_name even it is null.

Warning

db.collection_name.find({"filed_name":{$ne:null}});

fetch documents that its field_name has a value $ne to null but this value could be an empty string also.

My proposition:

db.collection_name.find({ "field_name":{$ne:null},$where:"this.field_name.length >0"})

How to set dialog to show in full screen?

EDIT Until such time as StackOverflow allows us to version our answers, this is an answer that works for Android 3 and below. Please don't downvote it because it's not working for you now, because it definitely works with older Android versions.


You should only need to add one line to your onCreateDialog() method:

@Override
protected Dialog onCreateDialog(int id) {
    //all other dialog stuff (which dialog to display)

    //this line is what you need:
    dialog.getWindow().setFlags(LayoutParams.FLAG_FULLSCREEN, LayoutParams.FLAG_FULLSCREEN);

    return dialog;
}

Ruby String to Date Conversion

Date.strptime(updated,"%a, %d %m %Y %H:%M:%S %Z")

Should be:

Date.strptime(updated, '%a, %d %b %Y %H:%M:%S %Z')

Android Eclipse - Could not find *.apk

I tried all the above solutions. but it didn't work.

The solution was to restart eclipse !!!!!!!

hope this will help someone :)

JSONDecodeError: Expecting value: line 1 column 1

If you look at the output you receive from print() and also in your Traceback, you'll see the value you get back is not a string, it's a bytes object (prefixed by b):

b'{\n  "note":"This file    .....

If you fetch the URL using a tool such as curl -v, you will see that the content type is

Content-Type: application/json; charset=utf-8

So it's JSON, encoded as UTF-8, and Python is considering it a byte stream, not a simple string. In order to parse this, you need to convert it into a string first.

Change the last line of code to this:

info = json.loads(js.decode("utf-8"))

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

I too got this same error on my image handler that I wrote. I got it like 30 times a day on site with heavy traffic, managed to reproduce it also. You get this when a user cancels the request (closes the page or his internet connection is interrupted for example), in my case in the following row:

myContext.Response.OutputStream.Write(buffer, 0, bytesRead);

I can’t think of any way to prevent it but maybe you can properly handle this. Ex:

        try
        {
            …
            myContext.Response.OutputStream.Write(buffer, 0, bytesRead);
            …
        }catch (HttpException ex)
        {
            if (ex.Message.StartsWith("The remote host closed the connection."))
                ;//do nothing
            else
                //handle other errors
        }            
        catch (Exception e)
        {
            //handle other errors
        }
        finally
        {//close streams etc..
        }

GetType used in PowerShell, difference between variables

First of all, you lack parentheses to call GetType. What you see is the MethodInfo describing the GetType method on [DayOfWeek]. To actually call GetType, you should do:

$a.GetType();
$b.GetType();

You should see that $a is a [DayOfWeek], and $b is a custom object generated by the Select-Object cmdlet to capture only the DayOfWeek property of a data object. Hence, it's an object with a DayOfWeek property only:

C:\> $b.DayOfWeek -eq $a
True

How to combine two vectors into a data frame

Here's a simple function. It generates a data frame and automatically uses the names of the vectors as values for the first column.

myfunc <- function(a, b, names = NULL) {
  setNames(data.frame(c(rep(deparse(substitute(a)), length(a)), 
                        rep(deparse(substitute(b)), length(b))), c(a, b)), names)
}

An example:

x <-c(1,2,3)
y <-c(100,200,300)
x_name <- "cond"
y_name <- "rating"

myfunc(x, y, c(x_name, y_name))

  cond rating
1    x      1
2    x      2
3    x      3
4    y    100
5    y    200
6    y    300

Docker is installed but Docker Compose is not ? why?

You also need to install Docker Compose. See the manual. Here are the commands you need to execute

sudo curl -L "https://github.com/docker/compose/releases/download/1.26.0/docker-compose-$(uname -s)-$(uname -m)"  -o /usr/local/bin/docker-compose
sudo mv /usr/local/bin/docker-compose /usr/bin/docker-compose
sudo chmod +x /usr/bin/docker-compose

Instagram API to fetch pictures with specific hashtags

Take a look here in order to get started: http://instagram.com/developer/

and then in order to retrieve pictures by tag, look here: http://instagram.com/developer/endpoints/tags/

Getting tags from Instagram doesn't require OAuth, so you can make the calls via these URLs:

GET IMAGES https://api.instagram.com/v1/tags/{tag-name}/media/recent?access_token={TOKEN}

SEARCH https://api.instagram.com/v1/tags/search?q={tag-query}&access_token={TOKEN}

TAG INFO https://api.instagram.com/v1/tags/{tag-name}?access_token={TOKEN}

Escape double quote character in XML

Here are the common characters which need to be escaped in XML, starting with double quotes:

  1. double quotes (") are escaped to &quot;
  2. ampersand (&) is escaped to &amp;
  3. single quotes (') are escaped to &apos;
  4. less than (<) is escaped to &lt;
  5. greater than (>) is escaped to &gt;

Basic example for sharing text or image with UIActivityViewController in Swift

Share : Text

@IBAction func shareOnlyText(_ sender: UIButton) {
    let text = "This is the text....."
    let textShare = [ text ]
    let activityViewController = UIActivityViewController(activityItems: textShare , applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.view 
    self.present(activityViewController, animated: true, completion: nil)
}
}

Share : Image

@IBAction func shareOnlyImage(_ sender: UIButton) {
    let image = UIImage(named: "Product")
    let imageShare = [ image! ]
    let activityViewController = UIActivityViewController(activityItems: imageShare , applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.view 
    self.present(activityViewController, animated: true, completion: nil)
 }

Share : Text - Image - URL

   @IBAction func shareAll(_ sender: UIButton) {
    let text = "This is the text...."
    let image = UIImage(named: "Product")
    let myWebsite = NSURL(string:"https://stackoverflow.com/users/4600136/mr-javed-multani?tab=profile")
    let shareAll= [text , image! , myWebsite]
    let activityViewController = UIActivityViewController(activityItems: shareAll, applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.view 
    self.present(activityViewController, animated: true, completion: nil)
   }

enter image description here

AngularJs: How to set radio button checked based on model

One way that I see more powerful and avoid having a isDefault in all the models is by using the ng-attributes ng-model, ng-value and ng-checked.

ng-model: binds the value to your model.

ng-value: the value to pass to the ng-model binding.

ng-checked: value or expression that is evaluated. Useful for radio-button and check-boxes.

Example of use: In the following example, I have my model and a list of languages that my site supports. To display the different languages supported and updating the model with the selecting language we can do it in this way.

<!-- Radio -->
<div ng-repeat="language in languages">

  <div>
    <label>

      <input ng-model="site.lang"
             ng-value="language"
             ng-checked="(site.lang == language)"
             name="localizationOptions"
             type="radio">

      <span> {{language}} </span>

    </label>
  </div>

</div>
<!-- end of Radio -->

Our model site.lang will get a language value whenever the expression under evaluation (site.lang == language) is true. This will allow you to sync it with server easily since your model already has the change.

How to sync with a remote Git repository?

Generally git pull is enough, but I'm not sure what layout you have chosen (or has github chosen for you).

getContext is not a function

I got the same error because I had accidentally used <div> instead of <canvas> as the element on which I attempt to call getContext.

How do I create an array of strings in C?

In ANSI C:

char* strings[3];
strings[0] = "foo";
strings[1] = "bar";
strings[2] = "baz";

IOError: [Errno 2] No such file or directory trying to open a file

Um...

with open(os.path.join(src_dir, f)) as fin:
    for line in fin:

Also, you never output to a new file.

Oracle query to fetch column names

The query to use with Oracle is:

String sqlStr="select COLUMN_NAME from ALL_TAB_COLUMNS where TABLE_NAME='"+_db+".users' and COLUMN_NAME not in ('password','version','id')"

Never heard of HQL for such queries. I assume it doesn't make sense for ORM implementations to deal with it. ORM is an Object Relational Mapping, and what you're looking for is metadata mapping... You wouldn't use HQL, rather use API methods for this purpose, or direct SQL. For instance, you can use JDBC DatabaseMetaData.

I think tablespace has nothing to do with schema. AFAIK tablespaces are mainly used for logical internal technical purposes which should bother DBAs. For more information regarding tablespaces, see Oracle doc.

What is the &#xA; character?

It's a linefeed character. How you use it would be up to you.

Check if enum exists in Java

One of my favorite lib: Apache Commons.

The EnumUtils can do that easily.

Following an example to validate an Enum with that library:

public enum MyEnum {
    DIV("div"), DEPT("dept"), CLASS("class");

    private final String val;

    MyEnum(String val) {
    this.val = val;
    }

    public String getVal() {
    return val;
    }
}


MyEnum strTypeEnum = null;

// test if String str is compatible with the enum 
// e.g. if you pass str = "div", it will return false. If you pass "DIV", it will return true.
if( EnumUtils.isValidEnum(MyEnum.class, str) ){
    strTypeEnum = MyEnum.valueOf(str);
}

Copy Data from a table in one Database to another separate database

INSERT INTO DB1.dbo.TempTable
SELECT * FROM DB2.dbo.TempTable

If we use this query it will return Primary key error.... So better to choose which columns need to be moved, like

INSERT INTO db1.dbo.TempTable // (List of columns here)
SELECT (Same list of columns here)
FROM db2.dbo.TempTable

Is Google Play Store supported in avd emulators?

It's not officially supported yet.

Edit: It's now supported in modern versions of Android Studio, at least on some platforms.

Old workarounds

If you're using an old version of Android Studio which doesn't support the Google Play Store, and you refuse to upgrade, here are two possible workarounds:

  1. Ask your favorite app's maintainers to upload a copy of their app into the Amazon Appstore. Next, install the Appstore onto your Android device. Finally, use the Appstore to install your favorite app.

  2. Or: Do a Web search to find a .apk file for the software you want. For example, if you want to install SleepBot in your Android emulator, you can do a Google Web search for [ SleepBot apk ]. Then use adb install to install the .apk file.

jQuery returning "parsererror" for ajax request

Make sure that you remove any debug code or anything else that might be outputting unintended information. Somewhat obvious, but easy to forgot in the moment.

Why use double indirection? or Why use pointers to pointers?

I have used double pointers today while I was programming something for work, so I can answer why we had to use them (it's the first time I actually had to use double pointers). We had to deal with real time encoding of frames contained in buffers which are members of some structures. In the encoder we had to use a pointer to one of those structures. The problem was that our pointer was being changed to point to other structures from another thread. In order to use the current structure in the encoder, I had to use a double pointer, in order to point to the pointer that was being modified in another thread. It wasn't obvious at first, at least for us, that we had to take this approach. A lot of address were printed in the process :)).

You SHOULD use double pointers when you work on pointers that are changed in other places of your application. You might also find double pointers to be a must when you deal with hardware that returns and address to you.

Install IPA with iTunes 12

Edit: See Jayprakash Dubey's answer for iTunes 12.7


From the menu shown in the following screenshot, choose Apps. You can drag and drop you IPA file in the next view.

enter image description here

After that, go to your device's page, you'll see the list of apps, install your app and press Apply from the bottom bar.

SQL Server 2008 Connection Error "No process is on the other end of the pipe"

This Might help as reference

I had the same issue, after multiple trial of suggested solution on this site and others, I found a solution for my scenario. The account was locked out How to Check if the account is Locked out... Login to the server using higher privileged account (like SA or admin rights) Expand security ==> select the login name ==>open the property window of the login ==> select the status page on the property window

Make sure This 3 Things 1, permission to connect database is GRANTED 2, Login is ENABLED 3, Status SQL server authentication Login is not locked out (Uncheck the box)

Thanks Tsige

How to use variables in a command in sed?

Say:

sed "s|\$ROOT|${HOME}|" abc.sh

Note:

  • Use double quotes so that the shell would expand variables.
  • Use a separator different than / since the replacement contains /
  • Escape the $ in the pattern since you don't want to expand it.

EDIT: In order to replace all occurrences of $ROOT, say

sed "s|\$ROOT|${HOME}|g" abc.sh

AngularJS: How do I manually set input to $valid in controller?

I came across this post w/a similar issue. My fix was to add a hidden field to hold my invalid state for me.

<input type="hidden" ng-model="vm.application.isValid" required="" />

In my case I had a nullable bool which a person had to select one of two different buttons. if they answer yes, an entity is added to the collection and the state of the button changes. Until all of the questions get answered, (one of the buttons in each of the pairs has a click) the form is not valid.

vm.hasHighSchool = function (attended) { 
  vm.application.hasHighSchool = attended;
  applicationSvc.addSchool(attended, 1, vm.application);
}
<input type="hidden" ng-model="vm.application.hasHighSchool" required="" />
<div class="row">
  <div class="col-lg-3"><label>Did You Attend High School?</label><label class="required" ng-hide="vm.application.hasHighSchool != undefined">*</label></div>
  <div class="col-lg-2">
    <button value="Yes" title="Yes" ng-click="vm.hasHighSchool(true)" class="btn btn-default" ng-class="{'btn-success': vm.application.hasHighSchool == true}">Yes</button>
    <button value="No" title="No" ng-click="vm.hasHighSchool(false)" class="btn btn-default" ng-class="{'btn-success':  vm.application.hasHighSchool == false}">No</button>
  </div>
</div>

Populating VBA dynamic arrays

As Cody and Brett mentioned, you could reduce VBA slowdown with sensible use of Redim Preserve. Brett suggested Mod to do this.

You can also use a user defined Type and Sub to do this. Consider my code below:

Public Type dsIntArrayType
   eElems() As Integer
   eSize As Integer
End Type

Public Sub PushBackIntArray( _
    ByRef dsIntArray As dsIntArrayType, _
    ByVal intValue As Integer)

    With dsIntArray
    If UBound(.eElems) < (.eSize + 1) Then
        ReDim Preserve .eElems(.eSize * 2 + 1)
    End If
    .eSize = .eSize + 1
    .eElems(.eSize) = intValue
    End With

End Sub

This calls ReDim Preserve only when the size has doubled. The member variable eSize keeps track of the actual data size of eElems. This approach has helped me improve performance when final array length is not known until run time.

Hope this helps others too.

Build tree array from flat array in javascript

This is a modified version of the above that works with multiple root items, I use GUIDs for my ids and parentIds so in the UI that creates them I hard code root items to something like 0000000-00000-00000-TREE-ROOT-ITEM

var tree = unflatten(records, "TREE-ROOT-ITEM");

function unflatten(records, rootCategoryId, parent, tree){
    if(!_.isArray(tree)){
        tree = [];
        _.each(records, function(rec){
            if(rec.parentId.indexOf(rootCategoryId)>=0){        // change this line to compare a root id
            //if(rec.parentId == 0 || rec.parentId == null){    // example for 0 or null
                var tmp = angular.copy(rec);
                tmp.children = _.filter(records, function(r){
                    return r.parentId == tmp.id;
                });
                tree.push(tmp);
                //console.log(tree);
                _.each(tmp.children, function(child){
                    return unflatten(records, rootCategoryId, child, tree);
                });
            }
        });
    }
    else{
        if(parent){
            parent.children = _.filter(records, function(r){
                return r.parentId == parent.id;
            });
            _.each(parent.children, function(child){
                return unflatten(records, rootCategoryId, child, tree);
            });
        }
    }
    return tree;
}

Find a value in an array of objects in Javascript

function getValue(){
    for(var i = 0 ; i< array.length; i++){
        var obj = array[i];
        var arr = array["types"];
        for(var j = 0; j<arr.length;j++ ){
            if(arr[j] == "value"){
                return obj;
            }
        }

    }
}

Common HTTPclient and proxy

Although this question is very old, but I see still there are no exact answer. I will try to answer the question here.

I believe the question in short here is how to set the proxy settings for the Apache commons HttpClient (org.apache.commons.httpclient.HttpClient).

Code snippet below should work :

HttpClient client = new HttpClient();
HostConfiguration hostConfiguration = client.getHostConfiguration();
hostConfiguration.setProxy("localhost", 8080);
client.setHostConfiguration(hostConfiguration);

How to pass parameters in $ajax POST?

function funcion(y) {
$.ajax({
   type: 'POST',
   url: '/ruta',
   data: {"x": y},
   contentType: "application/x-www-form-urlencoded;charset=utf8",
});
}

How to use in jQuery :not and hasClass() to get a specific element without a class

It's much easier to do like this:

if(!$('#foo').hasClass('bar')) { 
  ...
}

The ! in front of the criteria means false, works in most programming languages.

Why is using a wild card with a Java import statement bad?

Here are the few things that I found regarding this topic.

  • During compilation, the compiler tries to find classes that are used in the code from the .* import and the corresponding byte code will be generated by selecting the used classes from .* import. So the byte code of using .* import or .class names import will be same and the runtime performance will also be the same because of the same byte code.

  • In each compilation, the compiler has to scan all the classes of .* package to match the classes that are actually used in the code. So, code with .* import takes more time during the compilation process as compared to using .class name imports.

  • Using .* import helps to make code more cleaner

  • Using .* import can create ambiguity when we use two classes of the same name from two different packages. Eg, Date is available in both packages.

      import java.util.*;
      import java.sql.*;
    
      public class DateDemo {
          private Date utilDate;
          private Date sqlDate;
      }
    

Converting Java objects to JSON with Jackson

Just follow any of these:

  • For jackson it should work:

          ObjectMapper mapper = new ObjectMapper();  
          return mapper.writeValueAsString(object);
          //will return json in string
    
  • For gson it should work:

        Gson gson = new Gson();
        return Response.ok(gson.toJson(yourClass)).build();
    

How to set initial value and auto increment in MySQL?

For this you have to set AUTO_INCREMENT value

ALTER TABLE tablename AUTO_INCREMENT = <INITIAL_VALUE>

Example

ALTER TABLE tablename AUTO_INCREMENT = 101

How to open generated pdf using jspdf in new window

Javascript code: Add in end line

$("#pdf_preview").attr("src", pdf.output('datauristring'));

HTML Code: Insert in body

<head>
</head>
<body>
<H1>Testing</h1>
<iframe id="pdf_preview" type="application/pdf" src="" width="800" height="400"></iframe>
</body>
</html>

preview within same window inside iframe along with with other contents.

Output Django queryset as JSON

It didn't work, because QuerySets are not JSON serializable.

1) In case of json.dumps you have to explicitely convert your QuerySet to JSON serializable objects:

class Model(model.Model):
    def as_dict(self):
        return {
            "id": self.id,
            # other stuff
        }

And the serialization:

dictionaries = [ obj.as_dict() for obj in self.get_queryset() ]
return HttpResponse(json.dumps({"data": dictionaries}), content_type='application/json')

2) In case of serializers. Serializers accept either JSON serializable object or QuerySet, but a dictionary containing a QuerySet is neither. Try this:

serializers.serialize("json", self.get_queryset())

Read more about it here:

https://docs.djangoproject.com/en/dev/topics/serialization/

Why is setState in reactjs Async instead of Sync?

You can use the following wrap to make sync call

_x000D_
_x000D_
this.setState((state =>{_x000D_
  return{_x000D_
    something_x000D_
  }_x000D_
})
_x000D_
_x000D_
_x000D_

Why doesn't document.addEventListener('load', function) work in a greasemonkey script?

The problem is WHEN the event is added and EXECUTED via triggering (the document onload property modification can be verified by examining the properties list).

When does this execute and modify onload relative to the onload event trigger:

document.addEventListener('load', ... );

before, during or after the load and/or render of the page's HTML?
This simple scURIple (cut & paste to URL) "works" w/o alerting as naively expected:

data:text/html;charset=utf-8,
    <html content editable><head>
          <script>
                document.addEventListener('load', function(){ alert(42) } );
          </script>
          </head><body>goodbye universe - hello muiltiverse</body>
    </html>

Does loading imply script contents have been executed?

A little out of this world expansion ...
Consider a slight modification:

data:text/html;charset=utf-8,
    <html content editable><head>
          <script>
              if(confirm("expand mind?"))document.addEventListener('load', function(){ alert(42) } );
          </script>
        </head><body>goodbye universe - hello muiltiverse</body>
    </html>

and whether the HTML has been loaded or not.

Rendering is certainly pending since goodbye universe - hello muiltiverse is not seen on screen but, does not the confirm( ... ) have to be already loaded to be executed? ... and so document.addEventListener('load', ... ) ... ?

In other words, can you execute code to check for self-loading when the code itself is not yet loaded?

Or, another way of looking at the situation, if the code is executable and executed then it has ALREADY been loaded as a done deal and to retroactively check when the transition occurred between not yet loaded and loaded is a priori fait accompli.

So which comes first: loading and executing the code or using the code's functionality though not loaded?

onload as a window property works because it is subordinate to the object and not self-referential as in the document case, ie. it's the window's contents, via document, that determine the loaded question err situation.

PS.: When do the following fail to alert(...)? (personally experienced gotcha's):

caveat: unless loading to the same window is really fast ... clobbering is the order of the day
so what is really needed below when using the same named window:

window.open(URIstr1,"w") .
   addEventListener('load', 
      function(){ alert(42); 
         window.open(URIstr2,"w") .
            addEventListener('load', 
               function(){ alert(43); 
                  window.open(URIstr3,"w") .
                     addEventListener('load', 
                        function(){ alert(44); 
                 /*  ...  */
                        } )
               } )
      } ) 

alternatively, proceed each successive window.open with:
alert("press Ok either after # alert shows pending load is done or inspired via divine intervention" );

data:text/html;charset=utf-8,
    <html content editable><head><!-- tagging fluff --><script>

        window.open(
            "data:text/plain, has no DOM or" ,"Window"
         ) . addEventListener('load', function(){ alert(42) } )

        window.open(
            "data:text/plain, has no DOM but" ,"Window"
         ) . addEventListener('load', function(){ alert(4) } )

        window.open(
            "data:text/html,<html><body>has DOM and", "Window"
         ) . addEventListener('load', function(){ alert(2) } )

        window.open(
            "data:text/html,<html><body>has DOM and", "noWindow"
         ) . addEventListener('load', function(){ alert(1) } )

        /* etc. including where body has onload=... in each appropriate open */

    </script><!-- terminating fluff --></head></html>

which emphasize onload differences as a document or window property.

Another caveat concerns preserving XSS, Cross Site Scripting, and SOP, Same Origin Policy rules which may allow loading an HTML URI but not modifying it's content to check for same. If a scURIple is run as a bookmarklet/scriplet from the same origin/site then there maybe success.

ie. From an arbitrary page, this link will do the load but not likely do alert('done'):

    <a href="javascript:window.open('view-source:http://google.ca') . 
                   addEventListener( 'load',  function(){ alert('done') }  )"> src. vu </a>

but if the link is bookmarked and then clicked when viewing a google.ca page, it does both.

test environment:

 window.navigator.userAgent = 
   Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4 (Splashtop-v1.2.17.0)

Java, How to get number of messages in a topic in apache kafka

Using the Java client of Kafka 2.11-1.0.0, you can do the following thing :

    KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
    consumer.subscribe(Collections.singletonList("test"));
    while(true) {
        ConsumerRecords<String, String> records = consumer.poll(100);
        for (ConsumerRecord<String, String> record : records) {
            System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());

            // after each message, query the number of messages of the topic
            Set<TopicPartition> partitions = consumer.assignment();
            Map<TopicPartition, Long> offsets = consumer.endOffsets(partitions);
            for(TopicPartition partition : offsets.keySet()) {
                System.out.printf("partition %s is at %d\n", partition.topic(), offsets.get(partition));
            }
        }
    }

Output is something like this :

offset = 10, key = null, value = un
partition test is at 13
offset = 11, key = null, value = deux
partition test is at 13
offset = 12, key = null, value = trois
partition test is at 13

Apache shutdown unexpectedly

on your XAMPP control panel, next to apache, select the "Config" option and select the first file (httpd.conf):

there, look for the "listen" line (you may use the find tool in the notepad) and there must be a line stating "Listen 80". Note: there are other lines with "listen" on them but they should be commented (start with a #), the one you need to change is the one saying exactly "listen 80". Now change it to "Listen 1337".

Start apache now.

If the error subsists, it's because there's another port that's already in use. So, select the config option again (next to apache in your xampp control panel) and select the second option this time (httpd-ssl.conf):

there, look for the line "Listen 443" and change it to "Listen 7331".

Start apache, it should be working now.

Insert a string at a specific index

You could prototype your own splice() into String.

Polyfill

if (!String.prototype.splice) {
    /**
     * {JSDoc}
     *
     * The splice() method changes the content of a string by removing a range of
     * characters and/or adding new characters.
     *
     * @this {String}
     * @param {number} start Index at which to start changing the string.
     * @param {number} delCount An integer indicating the number of old chars to remove.
     * @param {string} newSubStr The String that is spliced in.
     * @return {string} A new string with the spliced substring.
     */
    String.prototype.splice = function(start, delCount, newSubStr) {
        return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
    };
}

Example

_x000D_
_x000D_
String.prototype.splice = function(idx, rem, str) {_x000D_
    return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));_x000D_
};_x000D_
_x000D_
var result = "foo baz".splice(4, 0, "bar ");_x000D_
_x000D_
document.body.innerHTML = result; // "foo bar baz"
_x000D_
_x000D_
_x000D_


EDIT: Modified it to ensure that rem is an absolute value.

Moment.js - how do I get the number of years since a date, not rounded up?

I prefer this small method.

function getAgeFromBirthday(birthday) {
    if(birthday){
      var totalMonths = moment().diff(birthday, 'months');
      var years = parseInt(totalMonths / 12);
      var months = totalMonths % 12;
        if(months !== 0){
           return parseFloat(years + '.' + months);
         }
    return years;
      }
    return null;
}

MySQL "ERROR 1005 (HY000): Can't create table 'foo.#sql-12c_4' (errno: 150)"

Check that BOTH tables have the same ENGINE. For example if you have:

CREATE Table FOO ();

and:

CREATE Table BAR () ENGINE=INNODB;

If you try to create a constraint from table BAR to table FOO, it will not work on certain MySQL versions.

Fix the issue by following:

CREATE Table FOO () ENGINE=INNODB;

How to use SQL LIKE condition with multiple values in PostgreSQL?

Following query helped me. Instead of using LIKE, you can use ~*.

select id, name from hosts where name ~* 'julia|lena|jack';

Is there a wikipedia API just for retrieve content summary?

There is actually a very nice prop called extracts that can be used with queries designed specifically for this purpose. Extracts allow you to get article extracts (truncated article text). There is a parameter called exintro that can be used to retrieve the text in the zeroth section (no additional assets like images or infoboxes). You can also retrieve extracts with finer granularity such as by a certain number of characters (exchars) or by a certain number of sentences(exsentences)

Here is a sample query http://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&titles=Stack%20Overflow and the API sandbox http://en.wikipedia.org/wiki/Special:ApiSandbox#action=query&prop=extracts&format=json&exintro=&titles=Stack%20Overflow to experiment more with this query.

Please note that if you want the first paragraph specifically you still need to do some additionally parsing as suggested in the chosen answer. The difference here is that the response returned by this query is shorter than some of the other api queries suggested because you don't have additional assets such as images in the api response to parse.

How to read line by line or a whole text file at once?

I think you could use istream .read() function. You can just loop with reasonable chunk size and read directly to memory buffer, then append it to some sort of arbitrary memory container (such as std::vector). I could write an example, but I doubt you want a complete solution; please let me know if you shall need any additional information.

How to run bootRun with spring profile via gradle task

Spring Boot v2 Gradle plugin docs provide an answer:

6.1. Passing arguments to your application

Like all JavaExec tasks, arguments can be passed into bootRun from the command line using --args='<arguments>' when using Gradle 4.9 or later.

To run server with active profile set to dev:

$ ./gradlew bootRun --args='--spring.profiles.active=dev'

The action or event has been blocked by Disabled Mode

I solved this with Access options.

Go to the Office Button --> Access Options --> Trust Center --> Trust Center Settings Button --> Message Bar

In the right hand pane I selected the radio button "Show the message bar in all applications when content has been blocked."

Closed Access, reopened the database and got the warning for blocked content again.

Recommended date format for REST GET API

Always use UTC:

For example I have a schedule component that takes in one parameter DATETIME. When I call this using a GET verb I use the following format where my incoming parameter name is scheduleDate.

Example:
https://localhost/api/getScheduleForDate?scheduleDate=2003-11-21T01:11:11Z

Pod install is staying on "Setting up CocoaPods Master repo"

Just setup the master repo, was excited to see that we have a download progress, see screenshot ;)

CocoaPods release 1.2.0 (Jan 28) fixes this issue, thanks to all contributors and Danielle Tomlinson for this release.


enter image description here

How to use mysql JOIN without ON condition?

There are several ways to do a cross join or cartesian product:

SELECT column_names FROM table1 CROSS JOIN table2;

SELECT column_names FROM table1, table2;

SELECT column_names FROM table1 JOIN table2;

Neglecting the on condition in the third case is what results in a cross join.

How to create a timer using tkinter?

I just created a simple timer using the MVP pattern (however it may be overkill for that simple project). It has quit, start/pause and a stop button. Time is displayed in HH:MM:SS format. Time counting is implemented using a thread that is running several times a second and the difference between the time the timer has started and the current time.

Source code on github

Don't reload application when orientation changes

In manifiest file add to each activity this. This will help

android:configChanges = "orientation|keyboard|keyboardHidden|screenLayout|screenSize"

What should a Multipart HTTP request with multiple files look like?

Well, note that the request contains binary data, so I'm not posting the request as such - instead, I've converted every non-printable-ascii character into a dot (".").

POST /cgi-bin/qtest HTTP/1.1
Host: aram
User-Agent: Mozilla/5.0 Gecko/2009042316 Firefox/3.0.10
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://aram/~martind/banner.htm
Content-Type: multipart/form-data; boundary=2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Length: 514

--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile1"; filename="r.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile2"; filename="g.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile3"; filename="b.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f--

Note that every line (including the last one) is terminated by a \r\n sequence.

Drop shadow on a div container?

You can try using the PNG drop shadows. IE6 doesn't support it, however it will degrade nicely.

http://www.positioniseverything.net/articles/dropshadows.html

static constructors in C++? I need to initialize private static objects

A static constructor can be emulated by using a friend class or nested class as below.

class ClassStatic{
private:
    static char *str;
public:
    char* get_str() { return str; }
    void set_str(char *s) { str = s; }
    // A nested class, which used as static constructor
    static class ClassInit{
    public:
        ClassInit(int size){ 
            // Static constructor definition
            str = new char[size];
            str = "How are you?";
        }
    } initializer;
};

// Static variable creation
char* ClassStatic::str; 
// Static constructor call
ClassStatic::ClassInit ClassStatic::initializer(20);

int main() {
    ClassStatic a;
    ClassStatic b;
    std::cout << "String in a: " << a.get_str() << std::endl;
    std::cout << "String in b: " << b.get_str() << std::endl;
    a.set_str("I am fine");
    std::cout << "String in a: " << a.get_str() << std::endl;
    std::cout << "String in b: " << b.get_str() << std::endl;
    std::cin.ignore();
}

Output:

String in a: How are you?
String in b: How are you?
String in a: I am fine
String in b: I am fine

How to remove leading and trailing zeros in a string? Python

You can simply do this with a bool:

if int(number) == float(number):

   number = int(number)

else:

   number = float(number)

How get permission for camera in android.(Specifically Marshmallow)

You can try the following code to request camera permission in marshmallow. First check if the user grant the permission. If user has not granted the permission, then request the camera permission:

private static final int MY_CAMERA_REQUEST_CODE = 100;

if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
    requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_REQUEST_CODE);
}

After requesting the permission, dialog will display to ask permission containing allow and deny options. After clicking action we can get result of the request with the following method:

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == MY_CAMERA_REQUEST_CODE) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
        }
    }
}

How to do joins in LINQ on multiple fields in single join

Just to complete this with an equivalent method chain syntax:

entity.Join(entity2, x => new {x.Field1, x.Field2},
                     y => new {y.Field1, y.Field2}, (x, y) => x);

While the last argument (x, y) => x is what you select (in the above case we select x).

Get top most UIViewController

The best solution for me is an extension with a function. Create a swift file with this extension

First is the UIWindow extension:

public extension UIWindow {
    var visibleViewController: UIViewController? {
        return UIWindow.visibleVC(vc: self.rootViewController)
    }

    static func visibleVC(vc: UIViewController?) -> UIViewController? {
        if let navigationViewController = vc as? UINavigationController {
            return UIWindow.visibleVC(vc: navigationViewController.visibleViewController)
        } else if let tabBarVC = vc as? UITabBarController {
            return UIWindow.visibleVC(vc: tabBarVC.selectedViewController)
        } else {
            if let presentedVC = vc?.presentedViewController {
                return UIWindow.visibleVC(vc: presentedVC)
            } else {
                return vc
            }
        }
    }
}

inside that file add function

func visibleViewController() -> UIViewController? {
    let appDelegate = UIApplication.shared.delegate
    if let window = appDelegate!.window {
        return window?.visibleViewController
    }
    return nil
}

And if you want to use it, you can call it anywhere. Example:

  override func viewDidLoad() {
    super.viewDidLoad()
      if let topVC = visibleViewController() {
             //show some label or text field 
    }
}

File code is like this:

import UIKit

public extension UIWindow {
    var visibleViewController: UIViewController? {
        return UIWindow.visibleVC(vc: self.rootViewController)
    }

    static func visibleVC(vc: UIViewController?) -> UIViewController? {
        if let navigationViewController = vc as? UINavigationController {
            return UIWindow.visibleVC(vc: navigationViewController.visibleViewController)
        } else if let tabBarVC = vc as? UITabBarController {
            return UIWindow.visibleVC(vc: tabBarVC.selectedViewController)
        } else {
            if let presentedVC = vc?.presentedViewController {
                return UIWindow.visibleVC(vc: presentedVC)
            } else {
                return vc
            }
        }
    }
}

func visibleViewController() -> UIViewController? {
    let appDelegate = UIApplication.shared.delegate
    if let window = appDelegate!.window {
        return window?.visibleViewController
    }
    return nil
}

how to set the default value to the drop down list control?

After your DataBind():

lstDepartment.SelectedIndex = 0;  //first item

or

lstDepartment.SelectedValue = "Yourvalue"

or 
//add error checking, just an example, FindByValue may return null
lstDepartment.Items.FindByValue("Yourvalue").Selected = true;

or
//add error checking, just an example, FindByText may return null
lstDepartment.Items.FindByText("Yourvalue").Selected = true;

Efficiently convert rows to columns in sql server

This is rather a method than just a single script but gives you much more flexibility.

First of all There are 3 objects:

  1. User defined TABLE type [ColumnActionList] -> holds data as parameter
  2. SP [proc_PivotPrepare] -> prepares our data
  3. SP [proc_PivotExecute] -> execute the script

CREATE TYPE [dbo].[ColumnActionList] AS TABLE ( [ID] [smallint] NOT NULL, [ColumnName] nvarchar NOT NULL, [Action] nchar NOT NULL ); GO

    CREATE PROCEDURE [dbo].[proc_PivotPrepare] 
    (
    @DB_Name        nvarchar(128),
    @TableName      nvarchar(128)
    )
    AS
            SELECT @DB_Name = ISNULL(@DB_Name,db_name())
    DECLARE @SQL_Code nvarchar(max)

    DECLARE @MyTab TABLE (ID smallint identity(1,1), [Column_Name] nvarchar(128), [Type] nchar(1), [Set Action SQL] nvarchar(max));

    SELECT @SQL_Code        =   'SELECT [<| SQL_Code |>] = '' '' '
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''-----| Declare user defined type [ID] / [ColumnName] / [PivotAction] '' '
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''DECLARE @ColumnListWithActions ColumnActionList;'''
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''-----| Set [PivotAction] (''''S'''' as default) to select dimentions and values '' '
                                        + 'UNION ALL '
                                        + 'SELECT ''-----|'''
                                        + 'UNION ALL '
                                        + 'SELECT ''-----| ''''S'''' = Stable column || ''''D'''' = Dimention column || ''''V'''' = Value column '' '
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''INSERT INTO  @ColumnListWithActions VALUES ('' + CAST( ROW_NUMBER() OVER (ORDER BY [NAME]) as nvarchar(10)) + '', '' + '''''''' + [NAME] + ''''''''+ '', ''''S'''');'''
                                        + 'FROM [' + @DB_Name + '].sys.columns  '
                                        + 'WHERE object_id = object_id(''[' + @DB_Name + ']..[' + @TableName + ']'') '
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''-----| Execute sp_PivotExecute with parameters: columns and dimentions and main table name'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''EXEC [dbo].[sp_PivotExecute] @ColumnListWithActions, ' + '''''' + @TableName + '''''' + ';'''
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '                            
EXECUTE SP_EXECUTESQL @SQL_Code;

GO

CREATE PROCEDURE [dbo].[sp_PivotExecute]
(
@ColumnListWithActions  ColumnActionList ReadOnly
,@TableName                     nvarchar(128)
)
AS


--#######################################################################################################################
--###| Step 1 - Select our user-defined-table-variable into temp table
--#######################################################################################################################

IF OBJECT_ID('tempdb.dbo.#ColumnListWithActions', 'U') IS NOT NULL DROP TABLE #ColumnListWithActions; 
SELECT * INTO #ColumnListWithActions FROM @ColumnListWithActions;

--#######################################################################################################################
--###| Step 2 - Preparing lists of column groups as strings:
--#######################################################################################################################

DECLARE @ColumnName                     nvarchar(128)
DECLARE @Destiny                        nchar(1)

DECLARE @ListOfColumns_Stable           nvarchar(max)
DECLARE @ListOfColumns_Dimension    nvarchar(max)
DECLARE @ListOfColumns_Variable     nvarchar(max)
--############################
--###| Cursor for List of Stable Columns
--############################

DECLARE ColumnListStringCreator_S CURSOR FOR
SELECT      [ColumnName]
FROM        #ColumnListWithActions
WHERE       [Action] = 'S'
OPEN ColumnListStringCreator_S;
FETCH NEXT FROM ColumnListStringCreator_S
INTO @ColumnName
  WHILE @@FETCH_STATUS = 0

   BEGIN
        SELECT @ListOfColumns_Stable = ISNULL(@ListOfColumns_Stable, '') + ' [' + @ColumnName + '] ,';
        FETCH NEXT FROM ColumnListStringCreator_S INTO @ColumnName
   END

CLOSE ColumnListStringCreator_S;
DEALLOCATE ColumnListStringCreator_S;

--############################
--###| Cursor for List of Dimension Columns
--############################

DECLARE ColumnListStringCreator_D CURSOR FOR
SELECT      [ColumnName]
FROM        #ColumnListWithActions
WHERE       [Action] = 'D'
OPEN ColumnListStringCreator_D;
FETCH NEXT FROM ColumnListStringCreator_D
INTO @ColumnName
  WHILE @@FETCH_STATUS = 0

   BEGIN
        SELECT @ListOfColumns_Dimension = ISNULL(@ListOfColumns_Dimension, '') + ' [' + @ColumnName + '] ,';
        FETCH NEXT FROM ColumnListStringCreator_D INTO @ColumnName
   END

CLOSE ColumnListStringCreator_D;
DEALLOCATE ColumnListStringCreator_D;

--############################
--###| Cursor for List of Variable Columns
--############################

DECLARE ColumnListStringCreator_V CURSOR FOR
SELECT      [ColumnName]
FROM        #ColumnListWithActions
WHERE       [Action] = 'V'
OPEN ColumnListStringCreator_V;
FETCH NEXT FROM ColumnListStringCreator_V
INTO @ColumnName
  WHILE @@FETCH_STATUS = 0

   BEGIN
        SELECT @ListOfColumns_Variable = ISNULL(@ListOfColumns_Variable, '') + ' [' + @ColumnName + '] ,';
        FETCH NEXT FROM ColumnListStringCreator_V INTO @ColumnName
   END

CLOSE ColumnListStringCreator_V;
DEALLOCATE ColumnListStringCreator_V;

SELECT @ListOfColumns_Variable      = LEFT(@ListOfColumns_Variable, LEN(@ListOfColumns_Variable) - 1);
SELECT @ListOfColumns_Dimension = LEFT(@ListOfColumns_Dimension, LEN(@ListOfColumns_Dimension) - 1);
SELECT @ListOfColumns_Stable            = LEFT(@ListOfColumns_Stable, LEN(@ListOfColumns_Stable) - 1);

--#######################################################################################################################
--###| Step 3 - Preparing table with all possible connections between Dimension columns excluding NULLs
--#######################################################################################################################
DECLARE @DIM_TAB TABLE ([DIM_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @DIM_TAB 
SELECT [DIM_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName] FROM #ColumnListWithActions WHERE [Action] = 'D';

DECLARE @DIM_ID smallint;
SELECT      @DIM_ID = 1;


DECLARE @SQL_Dimentions nvarchar(max);

IF OBJECT_ID('tempdb.dbo.##ALL_Dimentions', 'U') IS NOT NULL DROP TABLE ##ALL_Dimentions; 

SELECT @SQL_Dimentions      = 'SELECT [xxx_ID_xxx] = ROW_NUMBER() OVER (ORDER BY ' + @ListOfColumns_Dimension + '), ' + @ListOfColumns_Dimension
                                            + ' INTO ##ALL_Dimentions '
                                            + ' FROM (SELECT DISTINCT' + @ListOfColumns_Dimension + ' FROM  ' + @TableName
                                            + ' WHERE ' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @DIM_ID) + ' IS NOT NULL ';
                                            SELECT @DIM_ID = @DIM_ID + 1;
            WHILE @DIM_ID <= (SELECT MAX([DIM_ID]) FROM @DIM_TAB)
            BEGIN
            SELECT @SQL_Dimentions = @SQL_Dimentions + 'AND ' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @DIM_ID) +  ' IS NOT NULL ';
            SELECT @DIM_ID = @DIM_ID + 1;
            END

SELECT @SQL_Dimentions   = @SQL_Dimentions + ' )x';

EXECUTE SP_EXECUTESQL  @SQL_Dimentions;

--#######################################################################################################################
--###| Step 4 - Preparing table with all possible connections between Stable columns excluding NULLs
--#######################################################################################################################
DECLARE @StabPos_TAB TABLE ([StabPos_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @StabPos_TAB 
SELECT [StabPos_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName] FROM #ColumnListWithActions WHERE [Action] = 'S';

DECLARE @StabPos_ID smallint;
SELECT      @StabPos_ID = 1;


DECLARE @SQL_MainStableColumnTable nvarchar(max);

IF OBJECT_ID('tempdb.dbo.##ALL_StableColumns', 'U') IS NOT NULL DROP TABLE ##ALL_StableColumns; 

SELECT @SQL_MainStableColumnTable       = 'SELECT xxx_ID_xxx = ROW_NUMBER() OVER (ORDER BY ' + @ListOfColumns_Stable + '), ' + @ListOfColumns_Stable
                                            + ' INTO ##ALL_StableColumns '
                                            + ' FROM (SELECT DISTINCT' + @ListOfColumns_Stable + ' FROM  ' + @TableName
                                            + ' WHERE ' + (SELECT [ColumnName] FROM @StabPos_TAB WHERE [StabPos_ID] = @StabPos_ID) + ' IS NOT NULL ';
                                            SELECT @StabPos_ID = @StabPos_ID + 1;
            WHILE @StabPos_ID <= (SELECT MAX([StabPos_ID]) FROM @StabPos_TAB)
            BEGIN
            SELECT @SQL_MainStableColumnTable = @SQL_MainStableColumnTable + 'AND ' + (SELECT [ColumnName] FROM @StabPos_TAB WHERE [StabPos_ID] = @StabPos_ID) +  ' IS NOT NULL ';
            SELECT @StabPos_ID = @StabPos_ID + 1;
            END

SELECT @SQL_MainStableColumnTable    = @SQL_MainStableColumnTable + ' )x';

EXECUTE SP_EXECUTESQL  @SQL_MainStableColumnTable;

--#######################################################################################################################
--###| Step 5 - Preparing table with all options ID
--#######################################################################################################################

DECLARE @FULL_SQL_1 NVARCHAR(MAX)
SELECT @FULL_SQL_1 = ''

DECLARE @i smallint

IF OBJECT_ID('tempdb.dbo.##FinalTab', 'U') IS NOT NULL DROP TABLE ##FinalTab; 

SELECT @FULL_SQL_1 = 'SELECT t.*, dim.[xxx_ID_xxx] '
                                    + ' INTO ##FinalTab '
                                    +   'FROM ' + @TableName + ' t '
                                    +   'JOIN ##ALL_Dimentions dim '
                                    +   'ON t.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = 1) + ' = dim.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = 1);
                                SELECT @i = 2                               
                                WHILE @i <= (SELECT MAX([DIM_ID]) FROM @DIM_TAB)
                                    BEGIN
                                    SELECT @FULL_SQL_1 = @FULL_SQL_1 + ' AND t.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @i) + ' = dim.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @i)
                                    SELECT @i = @i +1
                                END
EXECUTE SP_EXECUTESQL @FULL_SQL_1

--#######################################################################################################################
--###| Step 6 - Selecting final data
--#######################################################################################################################
DECLARE @STAB_TAB TABLE ([STAB_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @STAB_TAB 
SELECT [STAB_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName]
FROM #ColumnListWithActions WHERE [Action] = 'S';

DECLARE @VAR_TAB TABLE ([VAR_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @VAR_TAB 
SELECT [VAR_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName]
FROM #ColumnListWithActions WHERE [Action] = 'V';

DECLARE @y smallint;
DECLARE @x smallint;
DECLARE @z smallint;


DECLARE @FinalCode nvarchar(max)

SELECT @FinalCode = ' SELECT ID1.*'
                                        SELECT @y = 1
                                        WHILE @y <= (SELECT MAX([xxx_ID_xxx]) FROM ##FinalTab)
                                            BEGIN
                                                SELECT @z = 1
                                                WHILE @z <= (SELECT MAX([VAR_ID]) FROM @VAR_TAB)
                                                    BEGIN
                                                        SELECT @FinalCode = @FinalCode +    ', [ID' + CAST((@y) as varchar(10)) + '.' + (SELECT [ColumnName] FROM @VAR_TAB WHERE [VAR_ID] = @z) + '] =  ID' + CAST((@y + 1) as varchar(10)) + '.' + (SELECT [ColumnName] FROM @VAR_TAB WHERE [VAR_ID] = @z)
                                                        SELECT @z = @z + 1
                                                    END
                                                    SELECT @y = @y + 1
                                                END
        SELECT @FinalCode = @FinalCode + 
                                        ' FROM ( SELECT * FROM ##ALL_StableColumns)ID1';
                                        SELECT @y = 1
                                        WHILE @y <= (SELECT MAX([xxx_ID_xxx]) FROM ##FinalTab)
                                        BEGIN
                                            SELECT @x = 1
                                            SELECT @FinalCode = @FinalCode 
                                                                                + ' LEFT JOIN (SELECT ' +  @ListOfColumns_Stable + ' , ' + @ListOfColumns_Variable 
                                                                                + ' FROM ##FinalTab WHERE [xxx_ID_xxx] = ' 
                                                                                + CAST(@y as varchar(10)) + ' )ID' + CAST((@y + 1) as varchar(10))  
                                                                                + ' ON 1 = 1' 
                                                                                WHILE @x <= (SELECT MAX([STAB_ID]) FROM @STAB_TAB)
                                                                                BEGIN
                                                                                    SELECT @FinalCode = @FinalCode + ' AND ID1.' + (SELECT [ColumnName] FROM @STAB_TAB WHERE [STAB_ID] = @x) + ' = ID' + CAST((@y+1) as varchar(10)) + '.' + (SELECT [ColumnName] FROM @STAB_TAB WHERE [STAB_ID] = @x)
                                                                                    SELECT @x = @x +1
                                                                                END
                                            SELECT @y = @y + 1
                                        END

SELECT * FROM ##ALL_Dimentions;
EXECUTE SP_EXECUTESQL @FinalCode;

From executing the first query (by passing source DB and table name) you will get a pre-created execution query for the second SP, all you have to do is define is the column from your source: + Stable + Value (will be used to concentrate values based on that) + Dim (column you want to use to pivot by)

Names and datatypes will be defined automatically!

I cant recommend it for any production environments but does the job for adhoc BI requests.

Add new column with foreign key constraint in one command

In MS SQL SERVER:

With user defined foreign key name

ALTER TABLE tableName
ADD columnName dataType,
CONSTRAINT fkName FOREIGN KEY(fkColumnName) 
   REFERENCES pkTableName(pkTableColumnName);

Without user defined foreign key name

ALTER TABLE tableName
ADD columnName dataType,
FOREIGN KEY(fkColumnName) REFERENCES pkTableName(pkTableColumnName);

Regex replace uppercase with lowercase letters

Before searching with regex like [A-Z], you should press the case sensitive button (or Alt+C) (as leemour nicely suggested to be edited in the accepted answer). Just to be clear, I'm leaving a few other examples:

  1. Capitalize words
    • Find: (\s)([a-z]) (\s also matches new lines, i.e. "venuS" => "VenuS")
    • Replace: $1\u$2
  2. Uncapitalize words
    • Find: (\s)([A-Z])
    • Replace: $1\l$2
  3. Remove camel case (e.g. cAmelCAse => camelcAse => camelcase)
    • Find: ([a-z])([A-Z])
    • Replace: $1\l$2
  4. Lowercase letters within words (e.g. LowerCASe => Lowercase)
    • Find: (\w)([A-Z]+)
    • Replace: $1\L$2
    • Alternate Replace: \L$0
  5. Uppercase letters within words (e.g. upperCASe => uPPERCASE)
    • Find: (\w)([A-Z]+)
    • Replace: $1\U$2
  6. Uppercase previous (e.g. upperCase => UPPERCase)
    • Find: (\w+)([A-Z])
    • Replace: \U$1$2
  7. Lowercase previous (e.g. LOWERCase => lowerCase)
    • Find: (\w+)([A-Z])
    • Replace: \L$1$2
  8. Uppercase the rest (e.g. upperCase => upperCASE)
    • Find: ([A-Z])(\w+)
    • Replace: $1\U$2
  9. Lowercase the rest (e.g. lOWERCASE => lOwercase)
    • Find: ([A-Z])(\w+)
    • Replace: $1\L$2
  10. Shift-right-uppercase (e.g. Case => cAse => caSe => casE)
    • Find: ([a-z\s])([A-Z])(\w)
    • Replace: $1\l$2\u$3
  11. Shift-left-uppercase (e.g. CasE => CaSe => CAse => Case)
    • Find: (\w)([A-Z])([a-z\s])
    • Replace: \u$1\l$2$3

Regarding the question (match words with at least one uppercase and one lowercase letter and make them lowercase), leemour's comment-answer is the right answer. Just to clarify, if there is only one group to replace, you can just use ?: in the inner groups (i.e. non capture groups) or avoid creating them at all:

  • Find: ((?:[a-z][A-Z]+)|(?:[A-Z]+[a-z])) OR ([a-z][A-Z]+|[A-Z]+[a-z])
  • Replace: \L$1

2016-06-23 Edit

Tyler suggested by editing this answer an alternate find expression for #4:

  • (\B)([A-Z]+)

According to the documentation, \B will look for a character that is not at the word's boundary (i.e. not at the beginning and not at the end). You can use the Replace All button and it does the exact same thing as if you had (\w)([A-Z]+) as the find expression.

However, the downside of \B is that it does not allow single replacements, perhaps due to the find's "not boundary" restriction (please do edit this if you know the exact reason).

What in layman's terms is a Recursive Function using PHP

Recursion occurs when something contains, or uses, a similar version of itself.When talking specifically about computer programming, recursion occurs when a function calls itself.

The following link helps me to understand recursion better, even I consider this is the best so far what I've learned.

It comes with an example to understand how the inner(recursive) functions called while executing.

Please go through the article and I have pasted the test program in case if the article got trashed. You may please run the program in local server to see it in action.

https://www.elated.com/php-recursive-functions/

<?php

function factorial( $n ) {

  // Base case
  if ( $n == 0 ) {
    echo "Base case: $n = 0. Returning 1...<br>";
    return 1;
  }

  // Recursion
  echo "$n = $n: Computing $n * factorial( " . ($n-1) . " )...<br>";
  $result = ( $n * factorial( $n-1 ) );
  echo "Result of $n * factorial( " . ($n-1) . " ) = $result. Returning $result...<br>";
  return $result;
}

echo "The factorial of 5 is: " . factorial( 5 );

?>

How to git clone a specific tag

git clone --depth 1 --branch <tag_name> <repo_url>

Example

git clone --depth 1 --branch 0.37.2 https://github.com/apache/incubator-superset.git

<tag_name> : 0.37.2

<repo_url> : https://github.com/apache/incubator-superset.git

What's the Linq to SQL equivalent to TOP or LIMIT/OFFSET?

Use the Take(int n) method:

var q = query.Take(10);

SQL Server SELECT into existing table

There are two different ways to implement inserting data from one table to another table.

For Existing Table - INSERT INTO SELECT

This method is used when the table is already created in the database earlier and the data is to be inserted into this table from another table. If columns listed in insert clause and select clause are same, they are not required to list them. It is good practice to always list them for readability and scalability purpose.

----Create testable
CREATE TABLE TestTable (FirstName VARCHAR(100), LastName VARCHAR(100))
----INSERT INTO TestTable using SELECT
INSERT INTO TestTable (FirstName, LastName)
SELECT FirstName, LastName
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
----Clean Up Database
DROP TABLE TestTable

For Non-Existing Table - SELECT INTO

This method is used when the table is not created earlier and needs to be created when data from one table is to be inserted into the newly created table from another table. The new table is created with the same data types as selected columns.

----Create a new table and insert into table using SELECT INSERT
SELECT FirstName, LastName
INTO TestTable
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
----Clean Up Database
DROP TABLE TestTable

Ref 1 2

Equivalent of LIMIT for DB2

There are 2 solutions to paginate efficiently on a DB2 table :

1 - the technique using the function row_number() and the clause OVER which has been presented on another post ("SELECT row_number() OVER ( ORDER BY ... )"). On some big tables, I noticed sometimes a degradation of performances.

2 - the technique using a scrollable cursor. The implementation depends of the language used. That technique seems more robust on big tables.

I presented the 2 techniques implemented in PHP during a seminar next year. The slide is available on this link : http://gregphplab.com/serendipity/uploads/slides/DB2_PHP_Best_practices.pdf

Sorry but this document is only in french.

Cannot uninstall angular-cli

The following approach worked for me:

npm uninstall -g @angular/cli

and

npm cache verify

Python DNS module import error

On Debian 7 Wheezy, I had to do:

pip install --upgrade dnspython

even if python-dns package was installed.

How to configure Git post commit hook

As the previous answer did show an example of how the full hook might look like here is the code of my working post-receive hook:

#!/usr/bin/python

import sys
from subprocess import call

if __name__ == '__main__':
    for line in sys.stdin.xreadlines():
        old, new, ref = line.strip().split(' ')
        if ref == 'refs/heads/master':
            print "=============================================="
            print "Pushing to master. Triggering jenkins.        "
            print "=============================================="
            sys.stdout.flush()
            call(["curl", "-sS", "http://jenkinsserver/git/notifyCommit?url=ssh://user@gitserver/var/git/repo.git"])

In this case I trigger jenkins jobs only when pushing to master and not other branches.

Change Toolbar color in Appcompat 21

Try this in your styles.xml:

colorPrimary will be the toolbar color.

<resources>

<style name="AppTheme" parent="Theme.AppCompat">
    <item name="colorPrimary">@color/primary</item>
    <item name="colorPrimaryDark">@color/primary_pressed</item>
    <item name="colorAccent">@color/accent</item>
</style>

Did you build this in Eclipse by the way?

From milliseconds to hour, minutes, seconds and milliseconds

Here is how I would do it in Java:

int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours   = (int) ((milliseconds / (1000*60*60)) % 24);

Android AlertDialog Single Button

Another approach

Builder alert = new AlertDialog.Builder(ActivityName.this);
alert.setTitle("Doctor");
alert.setMessage("message");
alert.setPositiveButton("OK",null);
alert.show(); 

Bonus

AlertDialog.Builder builder = new AlertDialog.Builder(YourActivityName.this);
builder.setMessage("Message dialog with three buttons");

       builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                //do things
           }
       });

      builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                //do things
           }
       });

       builder.setNeutralButton("CANCEL", new DialogInterface.OnClickListener()     {
           public void onClick(DialogInterface dialog, int id) {
                //do things
           }
       });
AlertDialog alert = builder.create();
alert.show();

Now it is up to you to use one,two or three buttons..

Select values from XML field in SQL Server 2008

If you are able to wrap your XML in a root element - say then the following is your solution:

DECLARE @PersonsXml XML = '<persons><person><firstName>Jon</firstName><lastName>Johnson</lastName></person>
<person><firstName>Kathy</firstName><lastName>Carter</lastName></person>
<person><firstName>Bob</firstName><lastName>Burns</lastName></person></persons>'

SELECT  b.value('(./firstName/text())[1]','nvarchar(max)') as FirstName, b.value('(./lastName/text())[1]','nvarchar(max)') as LastName
FROM @PersonsXml.nodes('/persons/person') AS a(b)

enter image description here

Magento - Retrieve products with a specific attribute value

To Get TEXT attributes added from admin to front end on product listing page.

Thanks Anita Mourya

I have found there is two methods. Let say product attribute called "na_author" is added from backend as text field.

METHOD 1

on list.phtml

<?php $i=0; foreach ($_productCollection as $_product): ?>

FOR EACH PRODUCT LOAD BY SKU AND GET ATTRIBUTE INSIDE FOREACH

<?php
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$_product->getSku());
$author = $product['na_author'];
?>

<?php
if($author!=""){echo "<br /><span class='home_book_author'>By ".$author ."</span>";} else{echo "";}
?>

METHOD 2

Mage/Catalog/Block/Product/List.phtml OVER RIDE and set in 'local folder'

i.e. Copy From

Mage/Catalog/Block/Product/List.phtml

and PASTE TO

app/code/local/Mage/Catalog/Block/Product/List.phtml

change the function by adding 2 lines shown in bold below.

protected function _getProductCollection()
{
       if (is_null($this->_productCollection)) {
           $layer = Mage::getSingleton('catalog/layer');
           /* @var $layer Mage_Catalog_Model_Layer */
           if ($this->getShowRootCategory()) {
               $this->setCategoryId(Mage::app()->getStore()->getRootCategoryId());
           }

           // if this is a product view page
           if (Mage::registry('product')) {
               // get collection of categories this product is associated with
               $categories = Mage::registry('product')->getCategoryCollection()
                   ->setPage(1, 1)
                   ->load();
               // if the product is associated with any category
               if ($categories->count()) {
                   // show products from this category
                   $this->setCategoryId(current($categories->getIterator()));
               }
           }

           $origCategory = null;
           if ($this->getCategoryId()) {
               $category = Mage::getModel('catalog/category')->load($this->getCategoryId());

               if ($category->getId()) {
                   $origCategory = $layer->getCurrentCategory();
                   $layer->setCurrentCategory($category);
               }
           }
           $this->_productCollection = $layer->getProductCollection();

           $this->prepareSortableFieldsByCategory($layer->getCurrentCategory());

           if ($origCategory) {
               $layer->setCurrentCategory($origCategory);
           }
       }
       **//CMI-PK added na_author to filter on product listing page//
       $this->_productCollection->addAttributeToSelect('na_author');**
       return $this->_productCollection;

}

and you will be happy to see it....!!

Set HTML element's style property in javascript

The DOM element style "property" is a readonly collection of all the style attributes defined on the element. (The collection property is readonly, not necessarily the items within the collection.)

You would be better off using the className "property" on the elements.

How to change line width in ggplot?

Line width in ggplot2 can be changed with argument lwd= in geom_line().

geom_line(aes(x=..., y=..., color=...), lwd=1.5)

Format numbers in django templates

In case someone stumbles upon this, in Django 2.0.2 you can use this

Thousand separator. Be sure to read format localization as well.

Convert string to buffer Node

This is working for me, you might change your code like this

var responseData=x.toString();

to

var responseData=x.toString("binary");

and finally

response.write(new Buffer(toTransmit, "binary"));

How to while loop until the end of a file in Python without checking for empty line?

for line in f

reads all file to a memory, and that can be a problem.

My offer is to change the original source by replacing stripping and checking for empty line. Because if it is not last line - You will receive at least newline character in it ('\n'). And '.strip()' removes it. But in last line of a file You will receive truely empty line, without any characters. So the following loop will not give You false EOF, and You do not waste a memory:

with open("blablabla.txt", "r") as fl_in:
   while True:
      line = fl_in.readline()

        if not line:
            break

      line = line.strip()
      # do what You want

How do I toggle an element's class in pure JavaScript?

This one works in earlier versions of IE also.

_x000D_
_x000D_
function toogleClass(ele, class1) {_x000D_
  var classes = ele.className;_x000D_
  var regex = new RegExp('\\b' + class1 + '\\b');_x000D_
  var hasOne = classes.match(regex);_x000D_
  class1 = class1.replace(/\s+/g, '');_x000D_
  if (hasOne)_x000D_
    ele.className = classes.replace(regex, '');_x000D_
  else_x000D_
    ele.className = classes + class1;_x000D_
}
_x000D_
.red {_x000D_
  background-color: red_x000D_
}_x000D_
div {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  margin-bottom: 10px;_x000D_
  border: 1px solid black;_x000D_
}
_x000D_
<div class="does red redAnother " onclick="toogleClass(this, 'red')"></div>_x000D_
_x000D_
<div class="does collapse navbar-collapse " onclick="toogleClass(this, 'red')"></div>
_x000D_
_x000D_
_x000D_

Why did Servlet.service() for servlet jsp throw this exception?

If your project is Maven-based, remember to set scope to provided for such dependencies as servlet-api, jsp-api. Otherwise, these jars will be exported to WEB-INF/lib and hence contaminate with those in Tomcat server. That causes painful problems.

<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>servlet-api</artifactId>
  <version>2.5</version>
  <scope>provided</scope>
</dependency>
<dependency>
  <groupId>javax.servlet.jsp</groupId>
  <artifactId>jsp-api</artifactId>
  <version>2.1</version>
  <scope>provided</scope>
</dependency>

iframe to Only Show a Certain Part of the Page

Assuming you are using an iframe to import content available to the public but not owned by you into your website, you can always use the page anchor to direct you iframe to load where you want it to.

First you create an iframe with the width and height needed to display the data.

<iframe src="http://www.mygreatsite.com/page2.html" width="200px" height="100px"></iframe>

Second install addon such as Show Anchors 2 for Firefox and use it to display all the page anchors on the page you would like display in your iframe. Find the anchor point you want your frame to use and copy the anchor location by right clicking on it.

(You can download and install the plugin here => https://addons.mozilla.org/en-us/firefox/addon/show-anchors-2/)

Third use the copied web address with anchor point as your iframe source. When the frame loads, it will show the page starting at the anchor point you specified.

<iframe src="http://www.mygreatsite.com/page2.html#anchorname_1" width="200px" height="100px"></iframe>

That is the condensed instruction list. Hope it helps!

How to split a string between letters and digits (or between digits and letters)?

How about:

private List<String> Parse(String str) {
    List<String> output = new ArrayList<String>();
    Matcher match = Pattern.compile("[0-9]+|[a-z]+|[A-Z]+").matcher(str);
    while (match.find()) {
        output.add(match.group());
    }
    return output;
}

How to efficiently concatenate strings in go

You could create a big slice of bytes and copy the bytes of the short strings into it using string slices. There is a function given in "Effective Go":

func Append(slice, data[]byte) []byte {
    l := len(slice);
    if l + len(data) > cap(slice) { // reallocate
        // Allocate double what's needed, for future growth.
        newSlice := make([]byte, (l+len(data))*2);
        // Copy data (could use bytes.Copy()).
        for i, c := range slice {
            newSlice[i] = c
        }
        slice = newSlice;
    }
    slice = slice[0:l+len(data)];
    for i, c := range data {
        slice[l+i] = c
    }
    return slice;
}

Then when the operations are finished, use string ( ) on the big slice of bytes to convert it into a string again.

Index of element in NumPy array

I'm torn between these two ways of implementing an index of a NumPy array:

idx = list(classes).index(var)
idx = np.where(classes == var)

Both take the same number of characters, but the first method returns an int instead of a numpy.ndarray.

How to read fetch(PDO::FETCH_ASSOC);

PDO:FETCH_ASSOC puts the results in an array where values are mapped to their field names.

You can access the name field like this: $user['name'].

I recommend using PDO::FETCH_OBJ. It fetches fields in an object and you can access like this: $user->name

How do I change the default schema in sql developer?

Just right clic on the created connection and select "Schema browser", then use the filter to display the desired one.

Cheers.

MySQL Error: : 'Access denied for user 'root'@'localhost'

All solutions I found were much more complex than necessary and none worked for me. Here is the solution that solved my problem. No need to restart mysqld or start it with special privileges.

sudo mysql

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root';

With a single query we are changing the auth_plugin to mysql_native_password and setting the root password to root (feel free to change it in the query)

Now you should be able to login with root. More information can be found in mysql documentation

(exit mysql console with Ctrl + D or by typing exit)

Uploading files to file server using webclient class

Just use

File.Copy(filepath, "\\\\192.168.1.28\\Files");

A windows fileshare exposed via a UNC path is treated as part of the file system, and has nothing to do with the web.

The credentials used will be that of the ASP.NET worker process, or any impersonation you've enabled. If you can tweak those to get it right, this can be done.

You may run into problems because you are using the IP address instead of the server name (windows trust settings prevent leaving the domain - by using IP you are hiding any domain details). If at all possible, use the server name!

If this is not on the same windows domain, and you are trying to use a different domain account, you will need to specify the username as "[domain_or_machine]\[username]"

If you need to specify explicit credentials, you'll need to look into coding an impersonation solution.

django - get() returned more than one topic

get() returns a single object. If there is no existing object to return, you will receive <class>.DoesNotExist. If your query returns more than one object, then you will get MultipleObjectsReturned. You can check here for more details about get() queries.

Similarly, Django will complain if more than one item matches the get() query. In this case, it will raise MultipleObjectsReturned, which again is an attribute of the model class itself.

M2M will return any number of query that it is related to. In this case you can receive zero, one or more items with your query.

In your models you can us following:

for _topic in topic.objects.all():
    _topic.learningobjective_set.all()

you can use _set to execute a select query on M2M. In above case, you will filter all learningObjectives related to each topic

How to upload file using Selenium WebDriver in Java

I have tried to use the above robot there is a need to add a delay :( also you cannot debug or do something else because you lose the focus :(

//open upload window upload.click();

//put path to your image in a clipboard
StringSelection ss = new StringSelection(file.getAbsoluteFile());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);

//imitate mouse events like ENTER, CTRL+C, CTRL+V
Robot robot = new Robot();
robot.delay(250);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.delay(50);
robot.keyRelease(KeyEvent.VK_ENTER);

Using sed, how do you print the first 'N' characters of a line?

How about head ?

echo alonglineoftext | head -c 9

jQuery add text to span within a div

Careful - append() will append HTML, and you may run into cross-site-scripting problems if you use it all the time and a user makes you append('<script>alert("Hello")</script>').

Use text() to replace element content with text, or append(document.createTextNode(x)) to append a text node.

How to remove unused imports from Eclipse

If you want to do this on whole project then inside project -->select src folder-->press Ctrl+Shift+O

How to include Authorization header in cURL POST HTTP Request in PHP?

You have most of the code…

CURLOPT_HTTPHEADER for curl_setopt() takes an array with each header as an element. You have one element with multiple headers.

You also need to add the Authorization header to your $header array.

$header = array();
$header[] = 'Content-length: 0';
$header[] = 'Content-type: application/json';
$header[] = 'Authorization: OAuth SomeHugeOAuthaccess_tokenThatIReceivedAsAString';

Multiple separate IF conditions in SQL Server

IF you are checking one variable against multiple condition then you would use something like this Here the block of code where the condition is true will be executed and other blocks will be ignored.

IF(@Var1 Condition1)
     BEGIN
      /*Your Code Goes here*/
     END

ELSE IF(@Var1 Condition2)
      BEGIN
        /*Your Code Goes here*/ 
      END 

    ELSE      --<--- Default Task if none of the above is true
     BEGIN
       /*Your Code Goes here*/
     END

If you are checking conditions against multiple variables then you would have to go for multiple IF Statements, Each block of code will be executed independently from other blocks.

IF(@Var1 Condition1)
 BEGIN
   /*Your Code Goes here*/
 END


IF(@Var2 Condition1)
 BEGIN
   /*Your Code Goes here*/
 END


IF(@Var3 Condition1)
 BEGIN
   /*Your Code Goes here*/
 END

After every IF statement if there are more than one statement being executed you MUST put them in BEGIN..END Block. Anyway it is always best practice to use BEGIN..END blocks

Update

Found something in your code some BEGIN END you are missing

ELSE IF(@ID IS NOT NULL AND @ID in (SELECT ID FROM Places))   -- Outer Most Block ELSE IF
BEGIN   
     SELECT @MyName = Name ...  
    ...Some stuff....                       
    IF(SOMETHNG_1)         -- IF
                 --BEGIN
        BEGIN TRY               
            UPDATE ....                                                                 
        END TRY

        BEGIN CATCH
            SELECT ERROR_MESSAGE() AS 'Message' 
            RETURN -1
        END CATCH
                -- END
    ELSE IF(SOMETHNG_2)    -- ELSE IF
                 -- BEGIN
        BEGIN TRY
            UPDATE ...                                                      
        END TRY
        BEGIN CATCH
            SELECT ERROR_MESSAGE() AS 'Message' 
            RETURN -1
        END CATCH   
               -- END
    ELSE                  -- ELSE
        BEGIN
            BEGIN TRY
                UPDATE ...                                                              
            END TRY
            BEGIN CATCH
                SELECT ERROR_MESSAGE() AS 'Message' 
                RETURN -1
            END CATCH   
         END             
      --The above works I then insert this below and these if statement become nested----
          IF(@A!= @SA)
            BEGIN
             exec Store procedure 
                    @FIELD = 15,
                    ... more params...
            END                 
        IF(@S!= @SS)
          BEGIN
             exec Store procedure 
                    @FIELD = 10,
                    ... more params...

Mean Squared Error in Numpy?

The standard numpy methods for calculation mean squared error (variance) and its square root (standard deviation) are numpy.var() and numpy.std(), see here and here. They apply to matrices and have the same syntax as numpy.mean().

I suppose that the question and the preceding answers might have been posted before these functions became available.

In MVC, how do I return a string result?

public ActionResult GetAjaxValue()
{
   return Content("string value");
}

Find nearest latitude/longitude with an SQL query

Mysql query for search coordinates with distance limit and where condition

SELECT , ( 3959 acos( cos( radians('28.5850154') ) cos( radians(lat) ) cos( radians( lng ) - radians('77.07207489999999') ) + sin( radians('28.5850154') ) * sin( radians( lat ) ) ) ) AS distance FROM `Wo_Products` WHERE `active` = '1' HAVING distance < 5

LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria

For LINQ -> SQL:

SingleOrDefault

  • will generate query like "select * from users where userid = 1"
  • Select matching record, Throws exception if more than one records found
  • Use if you are fetching data based on primary/unique key column

FirstOrDefault

  • will generate query like "select top 1 * from users where userid = 1"
  • Select first matching rows
  • Use if you are fetching data based on non primary/unique key column

Java - Convert int to Byte Array of 4 Bytes?

int integer = 60;
byte[] bytes = new byte[4];
for (int i = 0; i < 4; i++) {
    bytes[i] = (byte)(integer >>> (i * 8));
}

Oracle SQL Where clause to find date records older than 30 days

Use:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= TRUNC(SYSDATE) - 30

SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date that is 30 days previous including the current time.

Depending on your needs, you could also look at using ADD_MONTHS:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)

Cut Corners using CSS

I recently cut off the top right corner and overlaid the tabs like folders. Complete code noob, so ignore the shitty code, but I did this by combining a square, a triangle, and a rectangle... This may or may not be a new approach, but hopefully, someone finds it helpful.

https://i.stack.imgur.com/qFMRz.png

Here is the HTML:

<!DOCTYPE html>
<html lang ="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" type="text/css" href="style.css"> 
    </head>
    <body>
        <div class="folders">
            <div class="container">
                <div class="triangleOne">
                    <p class="folderNames">Home</p>
                </div>
                <div class="triangleOneCut">
                </div>
                <div class="triangleOneFill">
                </div>
            </div>

            <div class="container2">
                <div class="triangleOne blue">
                    <p class="folderNames">About</p>
                </div>
                <div class="triangleOneCut blueCut">
                </div>
                <div class="triangleOneFill blue">
                </div>
            </div>

            <div class="container3">
                <div class="triangleOne green">
                    <p class="folderNames">Contact</p>
                </div>
                <div class="triangleOneCut greenCut">
                </div>
                <div class="triangleOneFill green">
                </div>
            </div>
        </div>
    </body>
</html>

Here is the CSS:

.triangleOne {
    height: 50px;
    width: 40px;
    background: red;
    border-radius: 5px 0px 0px 5px;
    position: absolute;
}

.triangleOneCut {
    content: '';
    position: absolute;
    top: 0; left: 40px;
    border-top: 10px solid transparent;
    border-left: 10px solid red;
    width: 0;
}

.triangleOneFill {
    content: '';
    position: absolute;
    top: 10px; left: 40px;
    width: 10px;
    height: 40px;
    background-color: red;
    border-radius: 0px 0px 5px 0px;
}

.container {
    position: relative;
    height: 50px;
    width: 50px;
    display: inline-block;
    z-index: 3;
}

.container2 {
    position: relative;
    height: 50px;
    width: 50px;
    display: inline-block;
    left: -10px;
    z-index: 2;
}

.container3 {
    position: relative;
    height: 50px;
    width: 50px;
    display: inline-block;
    left: -20px;
    z-index: 1;
}

.blue {
    background-color: blue;
}

.green {
    background-color: green;
}

.blueCut {
    border-left: 10px solid blue;
}

.greenCut {
    border-left: 10px solid green;
}

.folders {
    width: 160px;
    height: 50px;
    /* border: 10px solid white; */
    margin: auto;
    padding-left: 25px;
    margin-top: 100px;
}

.folderNames {
    text-align: right;
    padding-left: 2px;
    color: white;
    margin-top: 1.5px;
    font-family: monospace;
    font-size: 6.5px;
    border-bottom: double 1.5px white;
}

How can I store HashMap<String, ArrayList<String>> inside a list?

First you need to define the List as :

List<Map<String, ArrayList<String>>> list = new ArrayList<>();

To add the Map to the List , use add(E e) method :

list.add(map);

Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted

Another solution from the manual:

Composer also respects a memory limit defined by the COMPOSER_MEMORY_LIMIT environment variable:

COMPOSER_MEMORY_LIMIT=-1 composer.phar <...>

Or in my case

export COMPOSER_MEMORY_LIMIT=-1
composer <...>

git clone error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054

Uninstalling(version: 2.19.2) and installing(version: 2.21.0) git client fixed the issue for me.

How can I check if my python object is a number?

That's not really how python works. Just use it like you would a number, and if someone passes you something that's not a number, fail. It's the programmer's responsibility to pass in the correct types.

Onclick CSS button effect

You should apply the following styles:

#button:active {
    vertical-align: top;
    padding: 8px 13px 6px;
}

This will give you the necessary effect, demo here.

Printing prime numbers from 1 through 100

To find whether no. is prime or not C++:

#include<iostream>
#include<cmath>

using namespace std;
int main(){

int n, counter=0;

cout <<"Enter a number to check whether it is prime or not \n";
cin>>n;

  for(int i=2; i<=n-1;i++) {
    if (n%i==0) {
      cout<<n<<" is NOT a prime number \n";
      break;
    }
    counter++;
                }
    //cout<<"Value n is "<<n<<endl;
    //cout << "number of times counter run is "<<counter << endl;
    if (counter == n-2)
      cout << n<< " is prime \n";
   return 0;
}

how to programmatically fake a touch event to a UIButton?

Swift 3:

self.btn.sendActions(for: .touchUpInside)

How can I call the 'base implementation' of an overridden virtual method?

You can't, and you shouldn't. That's what polymorphism is for, so that each object has its own way of doing some "base" things.

How to get text and a variable in a messagebox

As has been suggested, using the string.format method is nice and simple and very readable.

In vb.net the " + " is used for addition and the " & " is used for string concatenation.

In your example:

MsgBox("Variable = " + variable)

becomes:

MsgBox("Variable = " & variable)

I may have been a bit quick answering this as it appears these operators can both be used for concatenation, but recommended use is the "&", source http://msdn.microsoft.com/en-us/library/te2585xw(v=VS.100).aspx

maybe call

variable.ToString()

update:

Use string interpolation (vs2015 onwards I believe):

MsgBox($"Variable = {variable}")

jQuery AJAX Call to PHP Script with JSON Return

Your datatype is wrong, change datatype for dataType.

new Runnable() but no new thread?

If you want to create a new Thread...you can do something like this...

Thread t = new Thread(new Runnable() { public void run() { 
  // your code goes here... 
}});

Mongoose limit/offset and count query

I suggest you to use 2 queries:

  1. db.collection.count() will return total number of items. This value is stored somewhere in Mongo and it is not calculated.

  2. db.collection.find().skip(20).limit(10) here I assume you could use a sort by some field, so do not forget to add an index on this field. This query will be fast too.

I think that you shouldn't query all items and than perform skip and take, cause later when you have big data you will have problems with data transferring and processing.

C convert floating point to int

Good guestion! -- where I have not yet found a satisfying answer for my case, the answer I provide here works for me, but may not be future proof...

If one uses gcc (clang?) and have -Werror and -Wbad-function-cast defined,

int val = (int)pow(10,9);

will result:

error: cast from function call of type 'double' to non-matching type 'int' [-Werror=bad-function-cast]

(for a good reason, overflow and where values are rounded needs to be thought out)

EDIT: 2020-08-30: So, my use case casting the value from function returning double to int, and chose pow() to represent that in place of a private function somewhere. Then I sidestepped thinking pow() more. (See comments more why pow() used below could be problematic...).

After properly thought out (that parameters to pow() are good), int val = pow(10,9); seems to work with gcc 9.2 x86-64 ...

but note:

printf("%d\n", pow(10,4));

may output e.g.

-1121380856

(did for me) where

int i = pow(10,4); printf("%d\n", i);

printed

10000

in one particular case I tried.

Django Rest Framework -- no module named rest_framework

To install it, do the following:

pip install djangorestframework
pip install markdown     
pip install django-filter

We have to check for a few common mistakes:

  1. check comma at installed list elements

  2. typo errors

Attach Authorization header for all axios requests

The best solution to me is to create a client service that you'll instantiate with your token an use it to wrap axios.

import axios from 'axios';

const client = (token = null) => {
    const defaultOptions = {
        headers: {
            Authorization: token ? `Token ${token}` : '',
        },
    };

    return {
        get: (url, options = {}) => axios.get(url, { ...defaultOptions, ...options }),
        post: (url, data, options = {}) => axios.post(url, data, { ...defaultOptions, ...options }),
        put: (url, data, options = {}) => axios.put(url, data, { ...defaultOptions, ...options }),
        delete: (url, options = {}) => axios.delete(url, { ...defaultOptions, ...options }),
    };
};

const request = client('MY SECRET TOKEN');

request.get(PAGES_URL);

In this client, you can also retrieve the token from the localStorage / cookie, as you want.

How do I change select2 box height

If anyone here trying to match input styles and the form group height of bootstrap4 with select2 here's what i did ,

.select2-container{
    .select2-selection{
        height: 37px!important;
    }
    .select2-selection__rendered{
        margin-top: 4px!important;
    }
    .select2-selection__arrow{
        margin-top: 4px;
    }
    .select2-selection--single{
        border: 1px solid #ced4da!important;
    }
    *:focus{
        outline: none;
    } 
}

This will also remove the outlines.

Why can't Python find shared objects that are in directories in sys.path?

Ensure your libcurl.so module is in the system library path, which is distinct and separate from the python library path.

A "quick fix" is to add this path to a LD_LIBRARY_PATH variable. However, setting that system wide (or even account wide) is a BAD IDEA, as it is possible to set it in such a way that some programs will find a library it shouldn't, or even worse, open up security holes.

If your "locally installed libraries" are installed in, for example, /usr/local/lib, add this directory to /etc/ld.so.conf (it's a text file) and run "ldconfig"

The command will run a caching utility, but will also create all the necessary "symbolic links" required for the loader system to function. It is surprising that the "make install" for libcurl did not do this already, but it's possible it could not if /usr/local/lib is not in /etc/ld.so.conf already.

PS: it's possible that your /etc/ld.so.conf contains nothing but "include ld.so.conf.d/*.conf". You can still add a directory path after it, or just create a new file inside the directory it's being included from. Dont forget to run "ldconfig" after it.

Be careful. Getting this wrong can screw up your system.

Additionally: make sure your python module is compiled against THAT version of libcurl. If you just copied some files over from another system, this wont always work. If in doubt, compile your modules on the system you intend to run them on.

INSTALL_FAILED_NO_MATCHING_ABIS when install apk

Somehow, this fix the issue out of no reason.

./gradlew clean assemble and then install the app.

How to force addition instead of concatenation in javascript

Your code concatenates three strings, then converts the result to a number.

You need to convert each variable to a number by calling parseFloat() around each one.

total = parseFloat(myInt1) + parseFloat(myInt2) + parseFloat(myInt3);

How to Consume WCF Service with Android

Another option might be to avoid WCF all-together and just use a .NET HttpHandler. The HttpHandler can grab the query-string variables from your GET and just write back a response to the Java code.

What is the difference between i++ and ++i?

The way the operator works is that it gets incremented at the same time, but if it is before a variable, the expression will evaluate with the incremented/decremented variable:

int x = 0;   //x is 0
int y = ++x; //x is 1 and y is 1

If it is after the variable the current statement will get executed with the original variable, as if it had not yet been incremented/decremented:

int x = 0;   //x is 0
int y = x++; //'y = x' is evaluated with x=0, but x is still incremented. So, x is 1, but y is 0

I agree with dcp in using pre-increment/decrement (++x) unless necessary. Really the only time I use the post-increment/decrement is in while loops or loops of that sort. These loops are the same:

while (x < 5)  //evaluates conditional statement
{
    //some code
    ++x;       //increments x
}

or

while (x++ < 5) //evaluates conditional statement with x value before increment, and x is incremented
{
    //some code
}

You can also do this while indexing arrays and such:

int i = 0;
int[] MyArray = new int[2];
MyArray[i++] = 1234; //sets array at index 0 to '1234' and i is incremented
MyArray[i] = 5678;   //sets array at index 1 to '5678'
int temp = MyArray[--i]; //temp is 1234 (becasue of pre-decrement);

Etc, etc...

Hide separator line on one UITableViewCell

The best way to achieve this is to turn off default line separators, subclass UITableViewCell and add a custom line separator as a subview of the contentView - see below a custom cell that is used to present an object of type SNStock that has two string properties, ticker and name:

import UIKit

private let kSNStockCellCellHeight: CGFloat = 65.0
private let kSNStockCellCellLineSeparatorHorizontalPaddingRatio: CGFloat = 0.03
private let kSNStockCellCellLineSeparatorBackgroundColorAlpha: CGFloat = 0.3
private let kSNStockCellCellLineSeparatorHeight: CGFloat = 1

class SNStockCell: UITableViewCell {

  private let primaryTextColor: UIColor
  private let secondaryTextColor: UIColor

  private let customLineSeparatorView: UIView

  var showsCustomLineSeparator: Bool {
    get {
      return !customLineSeparatorView.hidden
    }
    set(showsCustomLineSeparator) {
      customLineSeparatorView.hidden = !showsCustomLineSeparator
    }
  }

  var customLineSeparatorColor: UIColor? {
   get {
     return customLineSeparatorView.backgroundColor
   }
   set(customLineSeparatorColor) {
     customLineSeparatorView.backgroundColor = customLineSeparatorColor?.colorWithAlphaComponent(kSNStockCellCellLineSeparatorBackgroundColorAlpha)
    }
  }

  required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  init(reuseIdentifier: String, primaryTextColor: UIColor, secondaryTextColor: UIColor) {
    self.primaryTextColor = primaryTextColor
    self.secondaryTextColor = secondaryTextColor
    self.customLineSeparatorView = UIView(frame:CGRectZero)
    super.init(style: UITableViewCellStyle.Subtitle, reuseIdentifier:reuseIdentifier)
    selectionStyle = UITableViewCellSelectionStyle.None
    backgroundColor = UIColor.clearColor()

    contentView.addSubview(customLineSeparatorView)
    customLineSeparatorView.hidden = true
  }

  override func prepareForReuse() {
    super.prepareForReuse()
    self.showsCustomLineSeparator = false
  }

  // MARK: Layout

  override func layoutSubviews() {
    super.layoutSubviews()
    layoutCustomLineSeparator()
  }

  private func layoutCustomLineSeparator() {
    let horizontalPadding: CGFloat = bounds.width * kSNStockCellCellLineSeparatorHorizontalPaddingRatio
    let lineSeparatorWidth: CGFloat = bounds.width - horizontalPadding * 2;
    customLineSeparatorView.frame = CGRectMake(horizontalPadding,
      kSNStockCellCellHeight - kSNStockCellCellLineSeparatorHeight,
      lineSeparatorWidth,
      kSNStockCellCellLineSeparatorHeight)
  }

  // MARK: Public Class API

  class func cellHeight() -> CGFloat {
    return kSNStockCellCellHeight
  }

  // MARK: Public API

  func configureWithStock(stock: SNStock) {
    textLabel!.text = stock.ticker as String
    textLabel!.textColor = primaryTextColor
    detailTextLabel!.text = stock.name as String
    detailTextLabel!.textColor = secondaryTextColor
    setNeedsLayout()
  } 
}

To disable the default line separator use, tableView.separatorStyle = UITableViewCellSeparatorStyle.None;. The consumer side is relatively simple, see example below:

private func stockCell(tableView: UITableView, indexPath:NSIndexPath) -> UITableViewCell {
  var cell : SNStockCell? = tableView.dequeueReusableCellWithIdentifier(stockCellReuseIdentifier) as? SNStockCell
  if (cell == nil) {
    cell = SNStockCell(reuseIdentifier:stockCellReuseIdentifier, primaryTextColor:primaryTextColor, secondaryTextColor:secondaryTextColor)
  }
  cell!.configureWithStock(stockAtIndexPath(indexPath))
  cell!.showsCustomLineSeparator = true
  cell!.customLineSeparatorColor = tintColor
  return cell!
}

Windows Explorer "Command Prompt Here"

Right-click the title-bar icon of the Explorer window. You'll get the current folder's context menu, where you'll find the "command window here" item.

(Note that to see that menu item, you need to have the corresponding "power toy" installed, or you can create the right registry keys yourself to add that item to folders' context menus.)

WMI "installed" query different from add/remove programs list?

Hope this helps somebody: I've been using the registry-based enumeration in my scripts (as suggested by some of the answers above), but have found that it does not properly enumerate 64-bit software when run on Windows 10 x64 via SCCM (which uses a 32-bit client). Found something like this to be the most straightforward solution in my particular case:

Function Get-Programs($Bits) {
  $Result = @()
  $Output = (reg query HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall /reg:$Bits /s)

  Foreach ($Line in $Output) {
    If ($Line -match '^\s+DisplayName\s+REG_SZ\s+(.+?)$') {
      $Result += New-Object PSObject -Property @{
        DisplayName = $matches[1];
        Bits = "$($Bits)-bit";
      }
    }
  }

  $Result
}

$Software  = Get-Programs 32
$Software += Get-Programs 64

Realize this is a little too Perl-ish in a bad way, but all other alternatives I've seen involved insanity with wrapper scripts and similar clever-clever solutions, and this seems a little more human.

P.S. Trying really hard to refrain from dumping a ton of salt on Microsoft here for making an absolutely trivial thing next to impossible. I.e., enumerating all MS Office versions in use on a network is a task to make a grown man weep.

AWS EFS vs EBS vs S3 (differences & when to use?)

EBS is simple - block level storage which can be attached to an instance from same AZ, and can survive irrespective of instance life.

However, interesting difference is between EFS and S3, and to identify proper use cases for it.

Cost: EFS is approximately 10 times costly than S3.

Usecases:

  • Whenever we have thousands of instances who needs to process file simultaneously EFS is recommended over S3.
  • Also note that S3 is object based storage while EFS is file based it implies that whenever we have requirement that files are updated continuously (refreshed) we should use EFS.
  • S3 is eventually consistent while EFS is strong consistent. In case you can't afford eventual consistency, you should use EFS

Using Camera in the Android emulator

Update: ICS emulator supports camera.

Simplest way to display current month and year like "Aug 2016" in PHP?

Here is a simple and more update format of getting the data:

   $now = new \DateTime('now');
   $month = $now->format('m');
   $year = $now->format('Y');

Import data into Google Colaboratory

On the left bar of any colaboratory there is a section called "Files". Upload your files there and use this path

"/content/YourFileName.extension"

ex: pd.read_csv('/content/Forbes2015.csv');

Comparison of DES, Triple DES, AES, blowfish encryption for data

The encryption methods described are symmetric key block ciphers.

Data Encryption Standard (DES) is the predecessor, encrypting data in 64-bit blocks using a 56 bit key. Each block is encrypted in isolation, which is a security vulnerability.

Triple DES extends the key length of DES by applying three DES operations on each block: an encryption with key 0, a decryption with key 1 and an encryption with key 2. These keys may be related.

DES and 3DES are usually encountered when interfacing with legacy commercial products and services.

AES is considered the successor and modern standard. http://en.wikipedia.org/wiki/Advanced_Encryption_Standard

I believe the use of Blowfish is discouraged.

It is highly recommended that you do not attempt to implement your own cryptography and instead use a high-level implementation such as GPG for data at rest or SSL/TLS for data in transit. Here is an excellent and sobering video on encryption vulnerabilities http://rdist.root.org/2009/08/06/google-tech-talk-on-common-crypto-flaws/

vuetify center items into v-flex

wrap button inside <div class="text-xs-center">

<div class="text-xs-center">
  <v-btn primary>
    Signup
  </v-btn>
</div>

Dev uses it in his examples.


For centering buttons in v-card-actions we can add class="justify-center" (note in v2 class is text-center (so without xs):

<v-card-actions class="justify-center">
  <v-btn>
    Signup
  </v-btn>
</v-card-actions>

Codepen


For more examples with regards to centering see here

How to install maven on redhat linux

I made the following script:

#!/bin/bash

# Target installation location
MAVEN_HOME="/your/path/here"

# Link to binary tar.gz archive
# See https://maven.apache.org/download.cgi?html_a_name#Files
MAVEN_BINARY_TAR_GZ_ARCHIVE="http://www.trieuvan.com/apache/maven/maven-3/3.3.9/binaries/apache-maven-3.3.9-bin.tar.gz"

# Configuration parameters used to start up the JVM running Maven, i.e. "-Xms256m -Xmx512m"
# See https://maven.apache.org/configure.html
MAVEN_OPTS="" # Optional (not needed)

if [[ ! -d $MAVEN_HOME ]]; then
  # Create nonexistent subdirectories recursively
  mkdir -p $MAVEN_HOME

  # Curl location of tar.gz archive & extract without first directory
  curl -L $MAVEN_BINARY_TAR_GZ_ARCHIVE | tar -xzf - -C $MAVEN_HOME --strip 1

  # Creating a symbolic/soft link to Maven in the primary directory of executable commands on the system
  ln -s $MAVEN_HOME/bin/mvn /usr/bin/mvn

  # Permanently set environmental variable (if not null)
  if [[ -n $MAVEN_OPTS ]]; then
    echo "export MAVEN_OPTS=$MAVEN_OPTS" >> ~/.bashrc
  fi

  # Using MAVEN_HOME, MVN_HOME, or M2 as your env var is irrelevant, what counts
  # is your $PATH environment.
  # See http://stackoverflow.com/questions/26609922/maven-home-mvn-home-or-m2-home
  echo "export PATH=$MAVEN_HOME/bin:$PATH" >> ~/.bashrc
else
  # Do nothing if target installation directory already exists
  echo "'$MAVEN_HOME' already exists, please uninstall existing maven first."
fi

jquery, domain, get URL

Similar to the answer before there there is

location.host

The location global has more fun facts about the current url as well. ( protocol, host, port, pathname, search, hash )

How to highlight cell if value duplicate in same column for google spreadsheet?

From the "Text Contains" dropdown menu select "Custom formula is:", and write: "=countif(A:A, A1) > 1" (without the quotes)

I did exactly as zolley proposed, but there should be done small correction: use "Custom formula is" instead of "Text Contains". And then conditional rendering will work.

Screenshot from menu

Leap year calculation

You really should try to google first.

Wikipedia has a explanation of leap years. The algorithm your describing is for the Proleptic Gregorian calendar.

More about the math around it can be found in the article Calendar Algorithms.

How do I change db schema to dbo

Move table from dbo schema to MySchema:

 ALTER SCHEMA MySchema TRANSFER dbo.MyTable


Move table from MySchema to dbo schema:

 ALTER SCHEMA dbo TRANSFER MySchema.MyTable

How to suppress Update Links warning?

I wanted to suppress the prompt that asks if you wish to update links to another workbook when my workbook is manually opened in Excel (as opposed to opening it programmatically via VBA). I tried including: Application.AskToUpdateLinks = False as the first line in my Auto_Open() macro but that didn't work. I discovered however that if you put it instead in the Workbook_Open() function in the ThisWorkbook module, it works brilliantly - the dialog is suppressed but the update still occurs silently in the background.

 Private Sub Workbook_Open()
    ' Suppress dialog & update automatically without asking
    Application.AskToUpdateLinks = False
End Sub

How can I get a uitableViewCell by indexPath?

Here is a code to get custom cell from index path

 NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
 YourCell *cell = (YourCell *)[tblRegister cellForRowAtIndexPath:indexPath];

For Swift

let indexpath = NSIndexPath(forRow: 2, inSection: 0)
let currentCell = tblTest.cellForRowAtIndexPath(indexpath) as! CellTest

For Swift 4 (for collectionview)

let indexpath = NSIndexPath(row: 2, section: 0)
let cell = self.colVw!.cellForItem(at: indexpath as IndexPath) as? ColViewCell

Java: How to insert CLOB into oracle database

I had similar issue. Changed one of my table column from varchar2 to CLOB. I didn't needed to change any java code. I kept it as setString(..) only so no need to change set method as setClob() etch if you are using following versions ATLEAST of Oracle and jdbc driver.

I tried in In Oracle 11g and driver ojdbc6-11.2.0.4.jar

Transaction isolation levels relation with locks on table

As brb tea says, depends on the database implementation and the algorithm they use: MVCC or Two Phase Locking.

CUBRID (open source RDBMS) explains the idea of this two algorithms:

  • Two-phase locking (2PL)

The first one is when the T2 transaction tries to change the A record, it knows that the T1 transaction has already changed the A record and waits until the T1 transaction is completed because the T2 transaction cannot know whether the T1 transaction will be committed or rolled back. This method is called Two-phase locking (2PL).

  • Multi-version concurrency control (MVCC)

The other one is to allow each of them, T1 and T2 transactions, to have their own changed versions. Even when the T1 transaction has changed the A record from 1 to 2, the T1 transaction leaves the original value 1 as it is and writes that the T1 transaction version of the A record is 2. Then, the following T2 transaction changes the A record from 1 to 3, not from 2 to 4, and writes that the T2 transaction version of the A record is 3.

When the T1 transaction is rolled back, it does not matter if the 2, the T1 transaction version, is not applied to the A record. After that, if the T2 transaction is committed, the 3, the T2 transaction version, will be applied to the A record. If the T1 transaction is committed prior to the T2 transaction, the A record is changed to 2, and then to 3 at the time of committing the T2 transaction. The final database status is identical to the status of executing each transaction independently, without any impact on other transactions. Therefore, it satisfies the ACID property. This method is called Multi-version concurrency control (MVCC).

The MVCC allows concurrent modifications at the cost of increased overhead in memory (because it has to maintain different versions of the same data) and computation (in REPETEABLE_READ level you can't loose updates so it must check the versions of the data, like Hiberate does with Optimistick Locking).

In 2PL Transaction isolation levels control the following:

  • Whether locks are taken when data is read, and what type of locks are requested.

  • How long the read locks are held.

  • Whether a read operation referencing rows modified by another transaction:

    • Block until the exclusive lock on the row is freed.

    • Retrieve the committed version of the row that existed at the time the statement or transaction started.

    • Read the uncommitted data modification.

Choosing a transaction isolation level does not affect the locks that are acquired to protect data modifications. A transaction always gets an exclusive lock on any data it modifies and holds that lock until the transaction completes, regardless of the isolation level set for that transaction. For read operations, transaction isolation levels primarily define the level of protection from the effects of modifications made by other transactions.

A lower isolation level increases the ability of many users to access data at the same time, but increases the number of concurrency effects, such as dirty reads or lost updates, that users might encounter.

Concrete examples of the relation between locks and isolation levels in SQL Server (use 2PL except on READ_COMMITED with READ_COMMITTED_SNAPSHOT=ON)

  • READ_UNCOMMITED: do not issue shared locks to prevent other transactions from modifying data read by the current transaction. READ UNCOMMITTED transactions are also not blocked by exclusive locks that would prevent the current transaction from reading rows that have been modified but not committed by other transactions. [...]

  • READ_COMMITED:

    • If READ_COMMITTED_SNAPSHOT is set to OFF (the default): uses shared locks to prevent other transactions from modifying rows while the current transaction is running a read operation. The shared locks also block the statement from reading rows modified by other transactions until the other transaction is completed. [...] Row locks are released before the next row is processed. [...]
    • If READ_COMMITTED_SNAPSHOT is set to ON, the Database Engine uses row versioning to present each statement with a transactionally consistent snapshot of the data as it existed at the start of the statement. Locks are not used to protect the data from updates by other transactions.
  • REPETEABLE_READ: Shared locks are placed on all data read by each statement in the transaction and are held until the transaction completes.

  • SERIALIZABLE: Range locks are placed in the range of key values that match the search conditions of each statement executed in a transaction. [...] The range locks are held until the transaction completes.