Programs & Examples On #Confirmbuttonextender

HTML5 tag for horizontal line break

I am answering this old question just because it still shows up in google queries and I think one optimal answer is missing. Try this code: use ::before or ::after

See Align <hr> to the left in an HTML5-compliant way

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

Extend the DOM Element, Handle the Error, and Degrade Gracefully

Below I use the prototype function to wrap the native DOM play function, grab its promise, and then degrade to a play button if the browser throws an exception. This extension addresses the shortcoming of the browser and is plug-n-play in any page with knowledge of the target element(s).

// JavaScript
// Wrap the native DOM audio element play function and handle any autoplay errors
Audio.prototype.play = (function(play) {
return function () {
  var audio = this,
      args = arguments,
      promise = play.apply(audio, args);
  if (promise !== undefined) {
    promise.catch(_ => {
      // Autoplay was prevented. This is optional, but add a button to start playing.
      var el = document.createElement("button");
      el.innerHTML = "Play";
      el.addEventListener("click", function(){play.apply(audio, args);});
      this.parentNode.insertBefore(el, this.nextSibling)
    });
  }
};
})(Audio.prototype.play);

// Try automatically playing our audio via script. This would normally trigger and error.
document.getElementById('MyAudioElement').play()

<!-- HTML -->
<audio id="MyAudioElement" autoplay>
  <source src="https://www.w3schools.com/html/horse.ogg" type="audio/ogg">
  <source src="https://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
</audio>

Bootstrap Modal immediately disappearing

In my case, a click on a button causes a (not wanted) reload of the page.

Here is my fix:

<button class="btn btn-success" onclick="javascript: return false;" 
data-target="#modalID" data-toggle="modal">deaktivieren</button>

difference between throw and throw new Exception()

If you want you can throw a new Exception, with the original one set as an inner exception.

How to get status code from webclient?

You should be able to use the "client.ResponseHeaders[..]" call, see this link for examples of getting stuff back from the response

Change a Nullable column to NOT NULL with Default Value

Try this

ALTER TABLE table_name ALTER COLUMN col_name data_type NOT NULL;

npm behind a proxy fails with status 403

For those using Jenkins or other CI server: it matters where you define your proxies, especially when they're different in your local development environment and the CI environment. In this case:

  • don't define proxies in project's .npmrc file. Or if you do, be sure to override the settings on CI server.
  • any other proxy settings might cause 403 Forbidden with little hint to the fact that you're using the wrong proxy. Check your gradle.properties or such and fix/override as necessary.

TLDR: define proxies not in the project but on the machine you're working on.

Get the size of a 2D array

In Java, 2D arrays are really arrays of arrays with possibly different lengths (there are no guarantees that in 2D arrays that the 2nd dimension arrays all be the same length)

You can get the length of any 2nd dimension array as z[n].length where 0 <= n < z.length.

If you're treating your 2D array as a matrix, you can simply get z.length and z[0].length, but note that you might be making an assumption that for each array in the 2nd dimension that the length is the same (for some programs this might be a reasonable assumption).

Removing rounded corners from a <select> element in Chrome/Webkit

Solution with custom right drop-down arrow, uses only css (no images)

_x000D_
_x000D_
select {_x000D_
  -webkit-appearance: none;_x000D_
  -webkit-border-radius: 0px;_x000D_
  background-image: linear-gradient(45deg, transparent 50%, gray 50%), linear-gradient(135deg, gray 50%, transparent 50%);_x000D_
  background-position: calc(100% - 20px) calc(1em + 2px), calc(100% - 15px) calc(1em + 2px), calc(100% - 2.5em) 0.5em;_x000D_
  background-size: 5px 5px, 5px 5px, 1px 1.5em;_x000D_
  background-repeat: no-repeat;_x000D_
_x000D_
  -moz-appearance: none;_x000D_
  display: block;_x000D_
  padding: 0.3rem;_x000D_
  height: 2rem;_x000D_
  width: 100%;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
  <br/>_x000D_
  <h4>Example</h4>_x000D_
  <select>_x000D_
    <option></option>_x000D_
    <option>Hello</option>_x000D_
    <option>World</option>_x000D_
  </select>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Best cross-browser method to capture CTRL+S with JQuery?

You could use a shortcut library to handle the browser specific stuff.

shortcut.add("Ctrl+S",function() {
    alert("Hi there!");
});

Responsive iframe using Bootstrap

Option 3

To update current iframe

$("iframe").wrap('<div class="embed-responsive embed-responsive-16by9"/>');
$("iframe").addClass('embed-responsive-item');

How do you loop through each line in a text file using a windows batch file?

Here's a bat file I wrote to execute all SQL scripts in a folder:

REM ******************************************************************
REM Runs all *.sql scripts sorted by filename in the current folder.
REM To use integrated auth change -U <user> -P <password> to -E
REM ******************************************************************

dir /B /O:n *.sql > RunSqlScripts.tmp
for /F %%A in (RunSqlScripts.tmp) do osql -S (local) -d DEFAULT_DATABASE_NAME -U USERNAME_GOES_HERE -P PASSWORD_GOES_HERE -i %%A
del RunSqlScripts.tmp

How to Set Selected value in Multi-Value Select in Jquery-Select2.?

To Select all

 $('select[name=eventsFilter]').find('option').attr('selected', true);
$('select[name=eventsFilter]').select2();

To UnSellect all

$('select[name=eventsFilter]').find('option').attr('selected', false);
  $('select[name=eventsFilter]').select2("");

Get properties of a class

Use these

export class TableColumns<T> {
   constructor(private t: new () => T) {
        var fields: string[] = Object.keys(new t())

        console.log('fields', fields)
        console.log('t', t)

    }
}

Usage

columns_logs = new TableColumns<LogItem>(LogItem);

Output

fields (12) ["id", "code", "source", "title", "deleted", "checked", "body", "json", "dt_insert", "dt_checked", "screenshot", "uid"]

js class

t class LogItem {
constructor() {
    this.id = 0;
    this.code = 0;
    this.source = '';
    this.title = '';
    this.deleted = false;
    this.checked = false;
  …

How to remove files that are listed in the .gitignore but still on the repository?

If you really want to prune your history of .gitignored files, first save .gitignore outside the repo, e.g. as /tmp/.gitignore, then run

git filter-branch --force --index-filter \
    "git ls-files -i -X /tmp/.gitignore | xargs -r git rm --cached --ignore-unmatch -rf" \
    --prune-empty --tag-name-filter cat -- --all

Notes:

  • git filter-branch --index-filter runs in the .git directory I think, i.e. if you want to use a relative path you have to prepend one more ../ first. And apparently you cannot use ../.gitignore, the actual .gitignore file, that yields a "fatal: cannot use ../.gitignore as an exclude file" for some reason (maybe during a git filter-branch --index-filter the working directory is (considered) empty?)
  • I was hoping to use something like git ls-files -iX <(git show $(git hash-object -w .gitignore)) instead to avoid copying .gitignore somewhere else, but that alone already returns an empty string (whereas cat <(git show $(git hash-object -w .gitignore)) indeed prints .gitignore's contents as expected), so I cannot use <(git show $GITIGNORE_HASH) in git filter-branch...
  • If you actually only want to .gitignore-clean a specific branch, replace --all in the last line with its name. The --tag-name-filter cat might not work properly then, i.e. you'll probably not be able to directly transfer a single branch's tags properly

SaveFileDialog setting default path and file type?

Here's an example that actually filters for BIN files. Also Windows now want you to save files to user locations, not system locations, so here's an example (you can use intellisense to browse the other options):

            var saveFileDialog = new Microsoft.Win32.SaveFileDialog()
            {
                DefaultExt = "*.xml",
                Filter = "BIN Files (*.bin)|*.bin",
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
            };

            var result = saveFileDialog.ShowDialog();
            if (result != null && result == true)
            {
                // Save the file here
            }

docker unauthorized: authentication required - upon push with successful login

Here the solution for my case ( private repos, free account plan)

https://success.docker.com/Datacenter/Solve/Getting_%22unauthorized%3A_authentication_required%22_when_trying_to_push_image_to_DTR

The image build name to push has to have the same name of the repos.

Example: repos on docker hub is: accountName/resposName image build name "accountName/resposName" -> docker build -t accountName/resposName

then type docker push accountName/resposName:latest

That's all.

Read a XML (from a string) and get some fields - Problems reading XML

I used the System.Xml.Linq.XElement for the purpose. Just check code below for reading the value of first child node of the xml(not the root node).

        string textXml = "<xmlroot><firstchild>value of first child</firstchild>........</xmlroot>";
        XElement xmlroot = XElement.Parse(textXml);
        string firstNodeContent = ((System.Xml.Linq.XElement)(xmlroot.FirstNode)).Value;

Git refusing to merge unrelated histories on rebase

Two possibilities when this can happen -

  1. You have cloned a project and, somehow, the .git directory got deleted or corrupted. This leads Git to be unaware of your local history and will, therefore, cause it to throw this error when you try to push to or pull from the remote repository.

  2. You have created a new repository, added a few commits to it, and now you are trying to pull from a remote repository that already has some commits of its own. Git will also throw the error in this case, since it has no idea how the two projects are related.

SOLUTION

git pull origin master --allow-unrelated-histories

Ref - https://www.educative.io/edpresso/the-fatal-refusing-to-merge-unrelated-histories-git-error

Difference between FetchType LAZY and EAGER in Java Persistence API?

I may consider performance and memory utilization. One big difference is that EAGER fetch strategy allows to use fetched data object without session. Why?
All data is fetched when eager marked data in the object when session is connected. However, in case of lazy loading strategy, lazy loading marked object does not retrieve data if session is disconnected (after session.close() statement). All that can be made by hibernate proxy. Eager strategy lets data to be still available after closing session.

How to sort an ArrayList?

  yearList = arrayListOf()
    for (year in 1950 until 2021) {
        yearList.add(year)
    }

   yearList.reverse()
    val list: ArrayList<String> = arrayListOf()

    for (year in yearList) {
        list.add(year.toString())
    }

Foreach value from POST from form

Use array-like fields:

<input name="name_for_the_items[]"/>

You can loop through the fields:

foreach($_POST['name_for_the_items'] as $item)
{
  //do something with $item
}

How can I hide the Adobe Reader toolbar when displaying a PDF in the .NET WebBrowser control?

It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.

The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:

   Adobe Reader Preferences dialog

You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:

   Adobe Reader Read Mode toolbar button

Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:

#toolbar=0&navpanes=0

So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.

string url = @"http://www.domain.com/file.pdf#toolbar=0&navpanes=0";
this._WebBrowser.Navigate(url);

You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.

Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3

For any one having this issue with Flurry framework. This is what fixed my issue. For me the issue was that i had imported the following files but never used them. "libFlurryTVOS_9.2.3" "libFlurryWatch_9.2.3"

So all I had to do was go to project target settings and remove these 2 files from the "Linked framework and libraries" section and the problem was solved.

Display TIFF image in all web browser

You can try converting your image from tiff to PNG, here is how to do it:

import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.ImageEncoder;
import com.sun.media.jai.codec.PNGEncodeParam;
import com.sun.media.jai.codec.TIFFDecodeParam;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import javaxt.io.Image;

public class ImgConvTiffToPng {

    public static byte[] convert(byte[] tiff) throws Exception {

        byte[] out = new byte[0];
        InputStream inputStream = new ByteArrayInputStream(tiff);

        TIFFDecodeParam param = null;

        ImageDecoder dec = ImageCodec.createImageDecoder("tiff", inputStream, param);
        RenderedImage op = dec.decodeAsRenderedImage(0);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        PNGEncodeParam jpgparam = null;
        ImageEncoder en = ImageCodec.createImageEncoder("png", outputStream, jpgparam);
        en.encode(op);
        outputStream = (ByteArrayOutputStream) en.getOutputStream();
        out = outputStream.toByteArray();
        outputStream.flush();
        outputStream.close();

        return out;

    }

How to change column width in DataGridView?

In my Visual Studio 2019 it worked only after I set the AutoSizeColumnsMode property to None.

How do you uninstall the package manager "pip", if installed from source?

If you installed pip like this:

 - sudo apt install python-pip
 - sudo apt install python3-pip

Uninstall them like this:

 - sudo apt remove python-pip
 - sudo apt remove python3-pip

how to convert image to byte array in java?

I think the best way to do that is to first read the file into a byte array, then convert the array to an image with ImageIO.read()

Two Divs on the same row and center align both of them

I would vote against display: inline-block since its not supported across browsers, IE < 8 specifically.

.wrapper {
    width:500px; /* Adjust to a total width of both .left and .right */
    margin: 0 auto;
}
.left {
    float: left;
    width: 49%; /* Not 50% because of 1px border. */
    border: 1px solid #000;
}
.right {
    float: right;
    width: 49%; /* Not 50% because of 1px border. */
    border: 1px solid #F00;
}

<div class="wrapper">
    <div class="left">Div 1</div>
    <div class="right">Div 2</div>
</div>

EDIT: If no spacing between the cells is desired just change both .left and .right to use float: left;

What is the difference between null and undefined in JavaScript?

The difference between undefined and null is minimal, but there is a difference. A variable whose value is undefined has never been initialized. A variable whose value is null was explicitly given a value of null, which means that the variable was explicitly set to have no value. If you compare undefined and null by using the null==undefined expression, they will be equal.

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

I have another even simpler solution, to be used without autolayout and with everything done through the XIB :

1/ Put your header in the tableview by drag and dropping it directly on the tableview.

2/ In the Size Inspector of the newly made header, just change its autosizing : you should only leave the top, left and right anchors, plus the fill horizontally.

That's how it should be set for the header

That should do the trick !

Remove all whitespace in a string

If you want to remove leading and ending spaces, use str.strip():

sentence = ' hello  apple'
sentence.strip()
>>> 'hello  apple'

If you want to remove all space characters, use str.replace():

(NB this only removes the “normal” ASCII space character ' ' U+0020 but not any other whitespace)

sentence = ' hello  apple'
sentence.replace(" ", "")
>>> 'helloapple'

If you want to remove duplicated spaces, use str.split():

sentence = ' hello  apple'
" ".join(sentence.split())
>>> 'hello apple'

Throw away local commits in Git

Before answering let's add some background, explaining what is this HEAD. since some of the options below will result in detached head

First of all what is HEAD?

HEAD is simply a reference to the current commit (latest) on the current branch.
There can only be a single HEAD at any given time. (excluding git worktree)

The content of HEAD is stored inside .git/HEAD and it contains the 40 bytes SHA-1 of the current commit.


detached HEAD

If you are not on the latest commit - meaning that HEAD is pointing to a prior commit in history its called detached HEAD.

enter image description here

On the command line, it will look like this- SHA-1 instead of the branch name since the HEAD is not pointing to the tip of the current branch

enter image description here

enter image description here

A few options on how to recover from a detached HEAD:


git checkout

git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits t go back

This will checkout new branch pointing to the desired commit.
This command will checkout to a given commit.
At this point, you can create a branch and start to work from this point on.

# Checkout a given commit. 
# Doing so will result in a `detached HEAD` which mean that the `HEAD`
# is not pointing to the latest so you will need to checkout branch
# in order to be able to update the code.
git checkout <commit-id>

# create a new branch forked to the given commit
git checkout -b <branch name>

git reflog

You can always use the reflog as well.
git reflog will display any change which updated the HEAD and checking out the desired reflog entry will set the HEAD back to this commit.

Every time the HEAD is modified there will be a new entry in the reflog

git reflog
git checkout HEAD@{...}

This will get you back to your desired commit

enter image description here


git reset --hard <commit_id>

"Move" your HEAD back to the desired commit.

# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32

# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts if you've modified things which were
# changed since the commit you reset to.
  • Note: (Since Git 2.7)
    you can also use the git rebase --no-autostash as well.

git revert <sha-1>

"Undo" the given commit or commit range.
The reset command will "undo" any changes made in the given commit.
A new commit with the undo patch will be committed while the original commit will remain in the history as well.

# add new commit with the undo of the original one.
# the <sha-1> can be any commit(s) or commit range
git revert <sha-1>

This schema illustrates which command does what.
As you can see there reset && checkout modify the HEAD.

enter image description here

What is INSTALL_PARSE_FAILED_NO_CERTIFICATES error?

Make sure the build variant is set to debug (and not release) in Android Studio (check the build variants panel).

How to redirect siteA to siteB with A or CNAME records

You can only make DNS name pont to a different IP address, so if You you are using virtual hosts redirecting with DNS won't work.

When you enter subdomain.hostone.com in your browser it will use DNS to get it's IP address (if it's a CNAME it will continue trying until it gets IP from A record) then it will connect to that IP and send a http request with

Host: subdomain.hostone.com 

somewhere in the http headers.

How to delete a workspace in Perforce (using p4v)?

From the "View" menu, select "Workspaces". You'll see all of the workspaces you've created. Select the workspaces you want to delete and click "Edit" -> "Delete Workspace", or right-click and select "Delete Workspace". If the workspace is "locked" to prevent changes, you'll get an error message.

To unlock the workspace, click "Edit" (or right-click and click "Edit Workspace") to pull up the workspace editor, uncheck the "locked" checkbox, and save your changes. You can delete the workspace once it's unlocked.

In my experience, the workspace will continue to be shown in the drop-down list until you click on it, at which point p4v will figure out you've deleted it and remove it from the list.

Making an image act like a button

You could implement a JavaScript block which contains a function with your needs.

<div style="position: absolute; left: 10px; top: 40px;"> 
    <img src="logg.png" width="114" height="38" onclick="DoSomething();" />
</div>

Load and execution sequence of a web page?

According to your sample,

<html>
 <head>
  <script src="jquery.js" type="text/javascript"></script>
  <script src="abc.js" type="text/javascript">
  </script>
  <link rel="stylesheets" type="text/css" href="abc.css"></link>
  <style>h2{font-wight:bold;}</style>
  <script>
  $(document).ready(function(){
     $("#img").attr("src", "kkk.png");
  });
 </script>
 </head>
 <body>
    <img id="img" src="abc.jpg" style="width:400px;height:300px;"/>
    <script src="kkk.js" type="text/javascript"></script>
 </body>
</html>

roughly the execution flow is about as follows:

  1. The HTML document gets downloaded
  2. The parsing of the HTML document starts
  3. HTML Parsing reaches <script src="jquery.js" ...
  4. jquery.js is downloaded and parsed
  5. HTML parsing reaches <script src="abc.js" ...
  6. abc.js is downloaded, parsed and run
  7. HTML parsing reaches <link href="abc.css" ...
  8. abc.css is downloaded and parsed
  9. HTML parsing reaches <style>...</style>
  10. Internal CSS rules are parsed and defined
  11. HTML parsing reaches <script>...</script>
  12. Internal Javascript is parsed and run
  13. HTML Parsing reaches <img src="abc.jpg" ...
  14. abc.jpg is downloaded and displayed
  15. HTML Parsing reaches <script src="kkk.js" ...
  16. kkk.js is downloaded, parsed and run
  17. Parsing of HTML document ends

Note that the download may be asynchronous and non-blocking due to behaviours of the browser. For example, in Firefox there is this setting which limits the number of simultaneous requests per domain.

Also depending on whether the component has already been cached or not, the component may not be requested again in a near-future request. If the component has been cached, the component will be loaded from the cache instead of the actual URL.

When the parsing is ended and document is ready and loaded, the events onload is fired. Thus when onload is fired, the $("#img").attr("src","kkk.png"); is run. So:

  1. Document is ready, onload is fired.
  2. Javascript execution hits $("#img").attr("src", "kkk.png");
  3. kkk.png is downloaded and loads into #img

The $(document).ready() event is actually the event fired when all page components are loaded and ready. Read more about it: http://docs.jquery.com/Tutorials:Introducing_$(document).ready()

Edit - This portion elaborates more on the parallel or not part:

By default, and from my current understanding, browser usually runs each page on 3 ways: HTML parser, Javascript/DOM, and CSS.

The HTML parser is responsible for parsing and interpreting the markup language and thus must be able to make calls to the other 2 components.

For example when the parser comes across this line:

<a href="#" onclick="alert('test');return false;" style="font-weight:bold">a hypertext link</a>

The parser will make 3 calls, two to Javascript and one to CSS. Firstly, the parser will create this element and register it in the DOM namespace, together with all the attributes related to this element. Secondly, the parser will call to bind the onclick event to this particular element. Lastly, it will make another call to the CSS thread to apply the CSS style to this particular element.

The execution is top down and single threaded. Javascript may look multi-threaded, but the fact is that Javascript is single threaded. This is why when loading external javascript file, the parsing of the main HTML page is suspended.

However, the CSS files can be download simultaneously because CSS rules are always being applied - meaning to say elements are always repainted with the freshest CSS rules defined - thus making it unblocking.

An element will only be available in the DOM after it has been parsed. Thus when working with a specific element, the script is always placed after, or within the window onload event.

Script like this will cause error (on jQuery):

<script type="text/javascript">/* <![CDATA[ */
  alert($("#mydiv").html());
/* ]]> */</script>
<div id="mydiv">Hello World</div>

Because when the script is parsed, #mydiv element is still not defined. Instead this would work:

<div id="mydiv">Hello World</div>
<script type="text/javascript">/* <![CDATA[ */
  alert($("#mydiv").html());
/* ]]> */</script>

OR

<script type="text/javascript">/* <![CDATA[ */
  $(window).ready(function(){
                    alert($("#mydiv").html());
                  });
/* ]]> */</script>
<div id="mydiv">Hello World</div>

How to create a byte array in C++?

Try

class MissileLauncher
{
public:
    MissileLauncher(void);

private:
    unsigned char abc[3];
};

or

using byte = unsigned char;

class MissileLauncher
{
public:
    MissileLauncher(void);

private:
    byte abc[3];
};

**Note: In older compilers (non-C++11) replace the using line with typedef unsigned char byte;

How to trigger Jenkins builds remotely and to pass parameters

See Jenkins documentation: Parameterized Build

Below is the line you are interested in:

http://server/job/myjob/buildWithParameters?token=TOKEN&PARAMETER=Value

What is difference between Lightsail and EC2?

Check official website https://aws.amazon.com/free/compute/lightsail-vs-ec2/

enter image description here

Amazon Lightsail – The Power of AWS, the Simplicity of a VPS https://aws.amazon.com/blogs/aws/amazon-lightsail-the-power-of-aws-the-simplicity-of-a-vps/

Amazon EC2 vs Amazon Lightsail (comparison on point )

  • Web Performances
  • Plans
  • Features and Usability enter image description here

Source : https://www.vpsbenchmarks.com/compare/features/ec2_vs_lightsail

How do I find and replace all occurrences (in all files) in Visual Studio Code?

Visual Studio Code: Version: 1.53.2


If you are looking for the answer in 2021 (like I was), the answer is here on the Microsoft website but honestly hard to follow.

Go to Edit > Replace in Files

enter image description here

From there it is similar to the search funtionality for a single file.

I changed the name of a class I was using across files and this worked perfectly.

Note: If you cannot find the Replace in Files option, first click on the Search icon (magnifying glass) and then it will appear.

Remove title in Toolbar in appcompat-v7

The correct way to hide/change the Toolbar Title is this:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);

This because when you call setSupportActionBar(toolbar);, then the getSupportActionBar() will be responsible of handling everything to the Action Bar, not the toolbar object.

See here

How to upper case every first letter of word in a string?

public String UpperCaseWords(String line)
{
    line = line.trim().toLowerCase();
    String data[] = line.split("\\s");
    line = "";
    for(int i =0;i< data.length;i++)
    {
        if(data[i].length()>1)
            line = line + data[i].substring(0,1).toUpperCase()+data[i].substring(1)+" ";
        else
            line = line + data[i].toUpperCase();
    }
    return line.trim();
}

How do I prevent the error "Index signature of object type implicitly has an 'any' type" when compiling typescript with noImplicitAny flag enabled?

Similar to @Piotr Lewandowski's answer, but within a forEach:

const config: MyConfig = { ... };

Object.keys(config)
  .forEach((key: keyof MyConfig) => {
    if (config[key]) {
      // ...
    }
  });

android studio 0.4.2: Gradle project sync failed error

I had same problem but finally I could solve it forever
Steps:

  1. Delete gradle and .gradle folders from your project folder.
  2. In Android Studio: Open your project then: File -> settings -> compiler -> gradle: enable offline mode
    Note: In relatively newer Android Studios, Offline mode has been moved to gradle setting. enter image description here
  3. Close your project: File -> close project
  4. Connect to the Internet and open your project again then let Android Studio downloads what it wants

If success then :)
else

  1. If you encounter gradle project sync failed again please follow these steps:
  2. Download the latest gradle package from this directory
  3. Extract it and put it somewhere (for example f:\gradle-1.10)
  4. Go to your Android Studio and load your project then open File->Settings->gradle, in this page click on Use local gradle distribution
  5. Type your gradle folder address there
    enter image description here

Congratulation you are done!

Generating a PNG with matplotlib when DISPLAY is undefined

To make sure your code is portable across Windows, Linux and OSX and for systems with and without displays, I would suggest following snippet:

import matplotlib
import os
# must be before importing matplotlib.pyplot or pylab!
if os.name == 'posix' and "DISPLAY" not in os.environ:
    matplotlib.use('Agg')

# now import other things from matplotlib
import matplotlib.pyplot as plt

Credit: https://stackoverflow.com/a/45756291/207661

SQL - How to select a row having a column with max value

SQL> create table t (mydate,value)
  2  as
  3  select to_date('18/5/2010, 1 pm','dd/mm/yyyy, hh am'), 40 from dual union all
  4  select to_date('18/5/2010, 2 pm','dd/mm/yyyy, hh am'), 20 from dual union all
  5  select to_date('18/5/2010, 3 pm','dd/mm/yyyy, hh am'), 60 from dual union all
  6  select to_date('18/5/2010, 4 pm','dd/mm/yyyy, hh am'), 30 from dual union all
  7  select to_date('18/5/2010, 5 pm','dd/mm/yyyy, hh am'), 60 from dual union all
  8  select to_date('18/5/2010, 6 pm','dd/mm/yyyy, hh am'), 25 from dual
  9  /

Table created.

SQL> select min(mydate) keep (dense_rank last order by value) mydate
  2       , max(value) value
  3    from t
  4  /

MYDATE                   VALUE
------------------- ----------
18-05-2010 15:00:00         60

1 row selected.

Regards, Rob.

Algorithm to return all combinations of k elements from n

Here is a simple JS solution:

_x000D_
_x000D_
function getAllCombinations(n, k, f1) {_x000D_
 indexes = Array(k);_x000D_
  for (let i =0; i< k; i++) {_x000D_
   indexes[i] = i;_x000D_
  }_x000D_
  var total = 1;_x000D_
  f1(indexes);_x000D_
  while (indexes[0] !== n-k) {_x000D_
   total++;_x000D_
  getNext(n, indexes);_x000D_
    f1(indexes);_x000D_
  }_x000D_
  return {total};_x000D_
}_x000D_
_x000D_
function getNext(n, vec) {_x000D_
 const k = vec.length;_x000D_
  vec[k-1]++;_x000D_
 for (var i=0; i<k; i++) {_x000D_
   var currentIndex = k-i-1;_x000D_
    if (vec[currentIndex] === n - i) {_x000D_
    var nextIndex = k-i-2;_x000D_
      vec[nextIndex]++;_x000D_
      vec[currentIndex] = vec[nextIndex] + 1;_x000D_
    }_x000D_
  }_x000D_
_x000D_
 for (var i=1; i<k; i++) {_x000D_
    if (vec[i] === n - (k-i - 1)) {_x000D_
      vec[i] = vec[i-1] + 1;_x000D_
    }_x000D_
  }_x000D_
 return vec;_x000D_
} _x000D_
_x000D_
_x000D_
_x000D_
let start = new Date();_x000D_
let result = getAllCombinations(10, 3, indexes => console.log(indexes)); _x000D_
let runTime = new Date() - start; _x000D_
_x000D_
console.log({_x000D_
result, runTime_x000D_
});
_x000D_
_x000D_
_x000D_

Add list to set?

list objects are unhashable. you might want to turn them in to tuples though.

How do multiple clients connect simultaneously to one port, say 80, on a server?

Multiple clients can connect to the same port (say 80) on the server because on the server side, after creating a socket and binding (setting local IP and port) listen is called on the socket which tells the OS to accept incoming connections.

When a client tries to connect to server on port 80, the accept call is invoked on the server socket. This creates a new socket for the client trying to connect and similarly new sockets will be created for subsequent clients using same port 80.

Words in italics are system calls.

Ref

http://www.scs.stanford.edu/07wi-cs244b/refs/net2.pdf

download csv file from web api in angular js

I used the below solution and it worked for me.

_x000D_
_x000D_
 if (window.navigator.msSaveOrOpenBlob) {_x000D_
   var blob = new Blob([decodeURIComponent(encodeURI(result.data))], {_x000D_
     type: "text/csv;charset=utf-8;"_x000D_
   });_x000D_
   navigator.msSaveBlob(blob, 'filename.csv');_x000D_
 } else {_x000D_
   var a = document.createElement('a');_x000D_
   a.href = 'data:attachment/csv;charset=utf-8,' + encodeURI(result.data);_x000D_
   a.target = '_blank';_x000D_
   a.download = 'filename.csv';_x000D_
   document.body.appendChild(a);_x000D_
   a.click();_x000D_
 }
_x000D_
_x000D_
_x000D_

Arrays in unix shell?

You can try of the following type :

#!/bin/bash
 declare -a arr

 i=0
 j=0

  for dir in $(find /home/rmajeti/programs -type d)
   do
        arr[i]=$dir
        i=$((i+1))
   done


  while [ $j -lt $i ]
  do
        echo ${arr[$j]}
        j=$((j+1))
  done

Do checkbox inputs only post data if they're checked?

I resolved the problem with this code:

HTML Form

<input type="checkbox" id="is-business" name="is-business" value="off" onclick="changeValueCheckbox(this)" >
<label for="is-business">Soy empresa</label>

and the javascript function by change the checkbox value form:

//change value of checkbox element
function changeValueCheckbox(element){
   if(element.checked){
    element.value='on';
  }else{
    element.value='off';
  }
}

and the server checked if the data post is "on" or "off". I used playframework java

        final Map<String, String[]> data = request().body().asFormUrlEncoded();

        if (data.get("is-business")[0].equals('on')) {
            login.setType(new MasterValue(Login.BUSINESS_TYPE));
        } else {
            login.setType(new MasterValue(Login.USER_TYPE));
        }

GitHub - List commits by author

Just add ?author=<emailaddress> or ?author=<githubUserName> to the url when viewing the "commits" section of a repo.

PHP foreach loop through multidimensional array

If you mean the first and last entry of the array when talking about a.first and a.last, it goes like this:

foreach ($arr_nav as $inner_array) {
    echo reset($inner_array); //apple, orange, pear
    echo end($inner_array); //My Apple, View All Oranges, A Pear
}

arrays in PHP have an internal pointer which you can manipulate with reset, next, end. Retrieving keys/values works with key and current, but using each might be better in many cases..

How to open .dll files to see what is written inside?

I think you have downloaded the .NET Reflector & this FileGenerator plugin http://filegenreflector.codeplex.com/ , If you do,

  1. Open up the Reflector.exe,

  2. Go to View and click Add-Ins,

  3. In the Add-Ins window click Add...,

  4. Then find the dll you have downloaded

  5. FileGenerator.dll (witch came wth the FileGenerator plugin),

  6. Then close the Add-Ins window.

  7. Go to File and click Open and choose the dll that you want to decompile,

  8. After you have opend it, it will appear in the tree view,

  9. Go to Tools and click Generate Files(Crtl+Shift+G),

  10. select the output directory and select appropriate settings as your wish, Click generate files.

OR

use http://ilspy.net/

Use "ENTER" key on softkeyboard instead of clicking button

may be you could add a attribute to your EditText like this:

android:imeOptions="actionSearch"

How do I write JSON data to a file?

All previous answers are correct here is a very simple example:

#! /usr/bin/env python
import json

def write_json():
    # create a dictionary  
    student_data = {"students":[]}
    #create a list
    data_holder = student_data["students"]
    # just a counter
    counter = 0
    #loop through if you have multiple items..         
    while counter < 3:
        data_holder.append({'id':counter})
        data_holder.append({'room':counter})
        counter += 1    
    #write the file        
    file_path='/tmp/student_data.json'
    with open(file_path, 'w') as outfile:
        print("writing file to: ",file_path)
        # HERE IS WHERE THE MAGIC HAPPENS 
        json.dump(student_data, outfile)
    outfile.close()     
    print("done")

write_json()

enter image description here

Using setDate in PreparedStatement

tl;dr

With JDBC 4.2 or later and java 8 or later:

myPreparedStatement.setObject( … , myLocalDate  )

…and…

myResultSet.getObject( … , LocalDate.class )

Details

The Answer by Vargas is good about mentioning java.time types but refers only to converting to java.sql.Date. No need to convert if your driver is updated.

java.time

The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat. The Joda-Time team also advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

LocalDate

In java.time, the java.time.LocalDate class represents a date-only value without time-of-day and without time zone.

If using a JDBC driver compliant with JDBC 4.2 or later spec, no need to use the old java.sql.Date class. You can pass/fetch LocalDate objects directly to/from your database via PreparedStatement::setObject and ResultSet::getObject.

LocalDate localDate = LocalDate.now( ZoneId.of( "America/Montreal" ) );
myPreparedStatement.setObject( 1 , localDate  );

…and…

LocalDate localDate = myResultSet.getObject( 1 , LocalDate.class );

Before JDBC 4.2, convert

If your driver cannot handle the java.time types directly, fall back to converting to java.sql types. But minimize their use, with your business logic using only java.time types.

New methods have been added to the old classes for conversion to/from java.time types. For java.sql.Date see the valueOf and toLocalDate methods.

java.sql.Date sqlDate = java.sql.Date.valueOf( localDate );

…and…

LocalDate localDate = sqlDate.toLocalDate();

Placeholder value

Be wary of using 0000-00-00 as a placeholder value as shown in your Question’s code. Not all databases and other software can handle going back that far in time. I suggest using something like the commonly-used Unix/Posix epoch reference date of 1970, 1970-01-01.

LocalDate EPOCH_DATE = LocalDate.ofEpochDay( 0 ); // 1970-01-01 is day 0 in Epoch counting.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

What is .Net Framework 4 extended?

It's the part of the .NET Framework that isn't contained within the Client Profile. See MSDN for more info; specifically:

The .NET Framework is made up of the .NET Framework 4 Client Profile and .NET Framework 4 Extended components that exist separately in Programs and Features.

Using HTML and Local Images Within UIWebView

In Swift 3:

webView.loadHTMLString("<img src=\"myImg.jpg\">", baseURL: Bundle.main.bundleURL)

This worked for me even when the image was inside of a folder without any modifications.

Change the borderColor of the TextBox

Isn't it Simple as this,

txtbox1.BorderColor = System.Drawing.Color.Red;

how to replace characters in hive?

select translate(description,'\\t','') from myTable;

Translates the input string by replacing the characters present in the from string with the corresponding characters in the to string. This is similar to the translate function in PostgreSQL. If any of the parameters to this UDF are NULL, the result is NULL as well. (Available as of Hive 0.10.0, for string types)

Char/varchar support added as of Hive 0.14.0

How to upload a file from Windows machine to Linux machine using command lines via PuTTy?

Try using SCP on Windows to transfer files, you can download SCP from Putty's website. Then try running:

pscp.exe filename.extension [email protected]:directory/subdirectory

There is a full length guide here.

How to restart ADB manually from Android Studio

open command prompt -> cd to your sdk\platform-tools type below command:

adb kill-server && adb start-server

How to use border with Bootstrap

Depending what size you want your div to be, you could utilize Bootstrap's built-in component thumbnail class, along with (or without) the grid system to create borders around each of your div items.

These examples on Bootstrap's website demonstrates the ease-of-use and lack of need for any special additional CSS:

<div class="row">
    <div class="col-xs-6 col-md-3">
        <a href="#" class="thumbnail">
            <img src="..." alt="...">
        </a>
    </div>
    ...
</div>

which produces the following div grid items:

Simple grid objects

or add some additional content:

<div class="row">
  <div class="col-sm-6 col-md-4">
    <div class="thumbnail">
      <img src="..." alt="...">
      <div class="caption">
        <h3>Thumbnail label</h3>
        <p>...</p>
        <p>
            <a href="#" class="btn btn-primary" role="button">Button</a>
            <a href="#" class="btn btn-default" role="button">Button</a>
       </p>
      </div>
    </div>
  </div>
</div>

which produces the following div grid items:

Custom grid objects

Implement a loading indicator for a jQuery AJAX call

I solved the same problem following this example:

This example uses the jQuery JavaScript library.

First, create an Ajax icon using the AjaxLoad site.
Then add the following to your HTML :

<img src="/images/loading.gif" id="loading-indicator" style="display:none" />

And the following to your CSS file:

#loading-indicator {
  position: absolute;
  left: 10px;
  top: 10px;
}

Lastly, you need to hook into the Ajax events that jQuery provides; one event handler for when the Ajax request begins, and one for when it ends:

$(document).ajaxSend(function(event, request, settings) {
    $('#loading-indicator').show();
});

$(document).ajaxComplete(function(event, request, settings) {
    $('#loading-indicator').hide();
});

This solution is from the following link. How to display an animated icon during Ajax request processing

Undefined symbols for architecture i386: _OBJC_CLASS_$_SKPSMTPMessage", referenced from: error

Change in active architecture worked for me, One of my lib was using i386.

In build settings >> change Build Active Architecture Only to Yes from NO

It worked for me. Hope it helps to others as well.

enter image description here

Remove sensitive files and their commits from Git history

Changing your passwords is a good idea, but for the process of removing password's from your repo's history, I recommend the BFG Repo-Cleaner, a faster, simpler alternative to git-filter-branch explicitly designed for removing private data from Git repos.

Create a private.txt file listing the passwords, etc, that you want to remove (one entry per line) and then run this command:

$ java -jar bfg.jar  --replace-text private.txt  my-repo.git

All files under a threshold size (1MB by default) in your repo's history will be scanned, and any matching string (that isn't in your latest commit) will be replaced with the string "***REMOVED***". You can then use git gc to clean away the dead data:

$ git gc --prune=now --aggressive

The BFG is typically 10-50x faster than running git-filter-branch and the options are simplified and tailored around these two common use-cases:

  • Removing Crazy Big Files
  • Removing Passwords, Credentials & other Private data

Full disclosure: I'm the author of the BFG Repo-Cleaner.

xls to csv converter

First read your excel spreadsheet into pandas, below code will import your excel spreadsheet into pandas as a OrderedDict type which contain all of your worksheet as dataframes. Then simply use worksheet_name as a key to access specific worksheet as a dataframe and save only required worksheet as csv file by using df.to_csv(). Hope this will workout in your case.

import pandas as pd
df = pd.read_excel('YourExcel.xlsx', sheet_name=None)
df['worksheet_name'].to_csv('YourCsv.csv')  

If your Excel file contain only one worksheet then simply use below code:

import pandas as pd
df = pd.read_excel('YourExcel.xlsx')
df.to_csv('YourCsv.csv') 

If someone want to convert all the excel worksheets from single excel workbook to the different csv files, try below code:

import pandas as pd
def excelTOcsv(filename):
    df = pd.read_excel(filename, sheet_name=None)  
    for key, value in df.items(): 
        return df[key].to_csv('%s.csv' %key)

This function is working as a multiple Excel sheet of same excel workbook to multiple csv file converter. Where key is the sheet name and value is the content inside sheet.

Angular 2 TypeScript how to find element in Array

You need to use method Array.filter:

this.persons =  this.personService.getPersons().filter(x => x.id == this.personId)[0];

or Array.find

this.persons =  this.personService.getPersons().find(x => x.id == this.personId);

Check if DataRow exists by column name in c#?

You can use the DataColumnCollection of Your datatable to check if the column is in the collection.

Something like:

DataColumnCollection Columns = dtItems.Columns;

if (Columns.Contains(ColNameToCheck))
{
  row["ColNameToCheck"] = "Checked";
}

How do I print bytes as hexadecimal?

Well you can convert one byte (unsigned char) at a time into a array like so

char buffer [17];
buffer[16] = 0;
for(j = 0; j < 8; j++)
    sprintf(&buffer[2*j], "%02X", data[j]);

Check for special characters in string

Wouldn't it be easier to negative-match alphanumerics instead?

return string.match(/^[^a-zA-Z0-9]+$/) ? true : false;

Access Form - Syntax error (missing operator) in query expression

I had this on a form where the Recordsource is dynamic.

The Sql was fine, answer is to trap the error!

Private Sub Form_Error(DataErr As Integer, Response As Integer)
'    Debug.Print DataErr

    If DataErr = 3075 Then
        Response = acDataErrContinue
    End If

End Sub

show/hide html table columns using css

if you're looking for a simple column hide you can use the :nth-child selector as well.

#tableid tr td:nth-child(3),
#tableid tr th:nth-child(3) {
    display: none;
}

I use this with the @media tag sometimes to condense wider tables when the screen is too narrow.

Move existing, uncommitted work to a new branch in Git

3 Steps to Commit your changes

Suppose you have created a new branch on GitHub with the name feature-branch.

enter image description here

FETCH

    git pull --all         Pull all remote branches
    git branch -a          List all branches now

Checkout and switch to the feature-branch directory. You can simply copy the branch name from the output of branch -a command above

git checkout -b feature-branch

VALIDATE

Next use the git branch command to see the current branch. It will show feature-branch with * In front of it

git branch         

COMMIT

git add .   add all files
git commit -m "Rafactore code or use your message"

Take update and the push changes on the origin server

 git pull origin feature-branch
 git push origin feature-branch

ActiveMQ connection refused

Your application is not able to connect to activemq. Check that your activemq is running and listening on localhost 61616.

You can try using: netstat -a to check if the activemq process has started. Or try check if you can access your actvemq using admin page: localhost:8161/admin/queues.jsp

On mac you will start your activemq using:

$ACTMQ_HOME/bin/activemq start 

Or if your config file (activemq.xml ) if located in another location you can use:

$ACTMQ_HOME/bin/activemq start xbean:file:${location_of_your_config_file}

In your case the executable is under: bin/macosx/activemq so you need to use: $ACTMQ_HOME/bin/macosx/activemq start

What does "javascript:void(0)" mean?

There is a huge difference in the behaviour of # vs javascript:void(0);.

# scrolls you to the top of the page but javascript:void(0); does not.

This is very important if you are coding dynamic pages because the user does not want to go back to the top when they click a link on the page.

C++ Singleton design pattern

I did not find a CRTP implementation among the answers, so here it is:

template<typename HeirT>
class Singleton
{
public:
    Singleton() = delete;

    Singleton(const Singleton &) = delete;

    Singleton &operator=(const Singleton &) = delete;

    static HeirT &instance()
    {
        static HeirT instance;
        return instance;
    }
};

To use just inherit your class from this, like: class Test : public Singleton<Test>

How to remove line breaks from a file in Java?

str = str.replaceAll("\\r\\n|\\r|\\n", " ");

Worked perfectly for me after searching a lot, having failed with every other line.

Docker-Compose can't connect to Docker Daemon

In my case a have the same error when I try to docker-compose build and my solution was just add sudo

sudo docker-compose build

Python: finding an element in a list

If you just want to find out if an element is contained in the list or not:

>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> 'example' in li
True
>>> 'damn' in li
False

Error in eval(expr, envir, enclos) : object not found

Don't know why @Janos deleted his answer, but it's correct: your data frame Train doesn't have a column named pre. When you pass a formula and a data frame to a model-fitting function, the names in the formula have to refer to columns in the data frame. Your Train has columns called residual.sugar, total.sulfur, alcohol and quality. You need to change either your formula or your data frame so they're consistent with each other.

And just to clarify: Pre is an object containing a formula. That formula contains a reference to the variable pre. It's the latter that has to be consistent with the data frame.

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

Somehow, the Build checkbox in the Configuration Manager had been unchecked for my executable, so it was still running with the old Any CPU build. After I fixed that, Visual Studio complained that it couldn't debug the assembly, but that was fixed with a restart.

Filtering Sharepoint Lists on a "Now" or "Today"

Pass Today as value as mentioned below in $viewQuery property :

$web = Get-SPWeb "http://sitename"
$list = $web.Lists.TryGetList($listtitle)
write-host "Exporting '$($list.Title)' data from '$($web.Title)' site.."
$viewTitle = "Program Events" #Title property
#Add the column names from the ViewField property to a string collection
$viewFields = New-Object System.Collections.Specialized.StringCollection
$viewFields.Add("Event Date") > $null
$viewFields.Add("Title") > $null
#Query property
$viewQuery = "<Where><Geq><FieldRef Name='EventDate' /><Value IncludeTimeValue='TRUE' Type='DateTime'><Today/></Value></Geq></Where><OrderBy><FieldRef Name='EventDate' Ascending='True' /></OrderBy>"
#RowLimit property
$viewRowLimit = 30
#Paged property
$viewPaged = $true
#DefaultView property
$viewDefaultView = $false
#Create the view in the destination list
$newview = $list.Views.Add($viewTitle, $viewFields, $viewQuery, $viewRowLimit, $viewPaged, $viewDefaultView)
Write-Host ("View '" + $newview.Title + "' created in list '" + $list.Title + "' on site " + $web.Url)
$web.Dispose()

Limit to 2 decimal places with a simple pipe

It's Works

.ts -> pi = 3.1415

.html -> {{ pi | number : '1.0-2' }}

Ouput -> 3.14
  1. if it has a decimal it only shows one
  2. if it has two decimals it shows both

https://stackblitz.com/edit/angular-e8g2pt?file=src/app/app.component.html

this works for me!!! thanks!!

Automapper missing type map configuration or unsupported mapping - Error

I was trying to map an IEnumerable to an object. This is way I got this error. Maybe it helps.

Doctrine and LIKE query

You can use the createQuery method (direct in the controller) :

$query = $em->createQuery("SELECT o FROM AcmeCodeBundle:Orders o WHERE o.OrderMail =  :ordermail and o.Product like :searchterm")
->setParameter('searchterm', '%'.$searchterm.'%')
->setParameter('ordermail', '[email protected]');

You need to change AcmeCodeBundle to match your bundle name

Or even better - create a repository class for the entity and create a method in there - this will make it reusable

Randomize numbers with jQuery?

Javascript has a random() available. Take a look at Math.random().

Integrity constraint violation: 1452 Cannot add or update a child row:

Maybe you have some rows in the table that you want to create de FK.

Run the migration with foreign_key_checks OFF Insert only those records that have corresponding id field in contents table.

How to install Visual Studio 2015 on a different drive

I use Xamarin with Visual Studio, and I prefer to move only some large android to another directory with(copy these folders to destination before create hardlinks):

mklink \J "C:\Users\yourUser\.android" "E:\yourFolder\.android"

mklink \J "C:\Program Files (x86)\Android" "E:\yourFolder\Android"

How to convert a String into an ArrayList?

 String s1="[a,b,c,d]";
 String replace = s1.replace("[","");
 System.out.println(replace);
 String replace1 = replace.replace("]","");
 System.out.println(replace1);
 List<String> myList = new ArrayList<String>(Arrays.asList(replace1.split(",")));
 System.out.println(myList.toString());

How to run Spring Boot web application in Eclipse itself?

If you are doing code in STS you just need to add the devtools dependency in your maven file. After that it will run itself whenever you will do some change.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
</dependency>

Delete all local git branches

From Windows Command Line, delete all except the current checked out branch using:

for /f "tokens=*" %f in ('git branch ^| find /v "*"') do git branch -D %f

CSS: borders between table columns only

I used this in a style sheet for three columns separated by vertical borders and it worked fine:

#column-left {
     border-left: 1px solid #dddddd;
}
#column-center {
     /*no border needed/*
}
#column-right {
     border-right: 1px solid #dddddd;
}

The column on the left gets a border on the right, the column on the right gets a border on the left and the the middle column is already taken care of by the left and right.

If your columns are inside a div/wrapper/table/etc... don't forget to add extra space to accomodate the width of the borders.

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

To add to the valuable content, I would like to create this reminder on why sometimes RegEx within VBA is not ideal. Not all expressions are supported, but instead may throw an Error 5017 and may leave the author guessing (which I am a victim of myself).

Whilst we can find some sources on what is supported, it would be helpfull to know which metacharacters etc. are not supported. A more in-depth explaination can be found here. Mentioned in this source:

"Although "VBScript’s regular expression ... version 5.5 implements quite a few essential regex features that were missing in previous versions of VBScript. ... JavaScript and VBScript implement Perl-style regular expressions. However, they lack quite a number of advanced features available in Perl and other modern regular expression flavors:"


So, not supported are:

  • Start of String ancor \A, alternatively use the ^ caret to match postion before 1st char in string
  • End of String ancor \Z, alternatively use the $ dollar sign to match postion after last char in string
  • Positive LookBehind, e.g.: (?<=a)b (whilst postive LookAhead is supported)
  • Negative LookBehind, e.g.: (?<!a)b (whilst negative LookAhead is supported)
  • Atomic Grouping
  • Possessive Quantifiers
  • Unicode e.g.: \{uFFFF}
  • Named Capturing Groups. Alternatively use Numbered Capturing Groups
  • Inline modifiers, e.g.: /i (case sensitivity) or /g (global) etc. Set these through the RegExp object properties > RegExp.Global = True and RegExp.IgnoreCase = True if available.
  • Conditionals
  • Regular Expression Comments. Add these with regular ' comments in script

I already hit a wall more than once using regular expressions within VBA. Usually with LookBehind but sometimes I even forget the modifiers. I have not experienced all these above mentioned backdrops myself but thought I would try to be extensive referring to some more in-depth information. Feel free to comment/correct/add. Big shout out to regular-expressions.info for a wealth of information.

P.S. You have mentioned regular VBA methods and functions, and I can confirm they (at least to myself) have been helpful in their own ways where RegEx would fail.

Check if item is in an array / list

You can also use the same syntax for an array. For example, searching within a Pandas series:

ser = pd.Series(['some', 'strings', 'to', 'query'])

if item in ser.values:
    # do stuff

Multiple Indexes vs Multi-Column Indexes

If you have queries that will be frequently using a relatively static set of columns, creating a single covering index that includes them all will improve performance dramatically.

By putting multiple columns in your index, the optimizer will only have to access the table directly if a column is not in the index. I use these a lot in data warehousing. The downside is that doing this can cost a lot of overhead, especially if the data is very volatile.

Creating indexes on single columns is useful for lookup operations frequently found in OLTP systems.

You should ask yourself why you're indexing the columns and how they'll be used. Run some query plans and see when they are being accessed. Index tuning is as much instinct as science.

PostgreSQL "DESCRIBE TABLE"

Try this (in the psql command-line tool):

\d+ tablename

See the manual for more info.

How to inspect Javascript Objects

This is blatant rip-off of Christian's excellent answer. I've just made it a bit more readable:

/**
 * objectInspector digs through a Javascript object
 * to display all its properties
 *
 * @param object - a Javascript object to inspect
 * @param result - a string of properties with datatypes
 *
 * @return result - the concatenated description of all object properties
 */
function objectInspector(object, result) {
    if (typeof object != "object")
        return "Invalid object";
    if (typeof result == "undefined")
        result = '';

    if (result.length > 50)
        return "[RECURSION TOO DEEP. ABORTING.]";

    var rows = [];
    for (var property in object) {
        var datatype = typeof object[property];

        var tempDescription = result+'"'+property+'"';
        tempDescription += ' ('+datatype+') => ';
        if (datatype == "object")
            tempDescription += 'object: '+objectInspector(object[property],result+'  ');
        else
            tempDescription += object[property];

        rows.push(tempDescription);
    }//Close for

    return rows.join(result+"\n");
}//End objectInspector

TypeScript hashmap/dictionary interface

Just as a normal js object:

let myhash: IHash = {};   

myhash["somestring"] = "value"; //set

let value = myhash["somestring"]; //get

There are two things you're doing with [indexer: string] : string

  • tell TypeScript that the object can have any string-based key
  • that for all key entries the value MUST be a string type.

enter image description here

You can make a general dictionary with explicitly typed fields by using [key: string]: any;

enter image description here

e.g. age must be number, while name must be a string - both are required. Any implicit field can be any type of value.

As an alternative, there is a Map class:

let map = new Map<object, string>(); 

let key = new Object();

map.set(key, "value");
map.get(key); // return "value"

This allows you have any Object instance (not just number/string) as the key.

Although its relatively new so you may have to polyfill it if you target old systems.

Creating a segue programmatically

Here is the code sample for Creating a segue programmatically:

class ViewController: UIViewController {
    ...
    // 1. Define the Segue
    private var commonSegue: UIStoryboardSegue!
    ...
    override func viewDidLoad() {
        ...
        // 2. Initialize the Segue
        self.commonSegue = UIStoryboardSegue(identifier: "CommonSegue", source: ..., destination: ...) {
            self.commonSegue.source.showDetailViewController(self.commonSegue.destination, sender: self)
        }
        ...
    }
    ...
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // 4. Prepare to perform the Segue
        if self.commonSegue == segue {
            ...
        }
        ...
    }
    ...
    func actionFunction() {
        // 3. Perform the Segue
        self.prepare(for: self.commonSegue, sender: self)
        self.commonSegue.perform()
    }
    ...
}

UTF-8 encoded html pages show ? (questions marks) instead of characters

When [dropping] the encoding settings mentioned above all characters [are rendered] correctly but the encoding that is detected shows either windows-1252 or ISO-8859-1 depending on the browser.

Then that's what you're really sending. None of the encoding settings in your bullet list will actually modify your output in any way; all they do is tell the browser what encoding to assume when interpreting what you send. That's why you're getting those ?s - you're telling the browser that what you're sending is UTF-8, but it's really ISO-8859-1.

Finding what branch a Git commit came from

git branch --contains <ref> is the most obvious "porcelain" command to do this. If you want to do something similar with only "plumbing" commands:

COMMIT=$(git rev-parse <ref>) # expands hash if needed
for BRANCH in $(git for-each-ref --format "%(refname)" refs/heads); do
  if $(git rev-list $BRANCH | fgrep -q $COMMIT); then
    echo $BRANCH
  fi
done

(crosspost from this SO answer)

vi/vim editor, copy a block (not usual action)

You can do it as you do in vi, for example to yank lines from 3020 to the end, execute this command (write the block to a file):

:3020,$ w /tmp/yank

And to write this block in another line/file, go to the desired position and execute next command (insert file written before):

:r /tmp/yank

(Reminder: don't forget to remove file: /tmp/yank)

Spring MVC: How to perform validation?

I would like to extend nice answer of Jerome Dalbert. I found very easy to write your own annotation validators in JSR-303 way. You are not limited to have "one field" validation. You can create your own annotation on type level and have complex validation (see examples below). I prefer this way because I don't need mix different types of validation (Spring and JSR-303) like Jerome do. Also this validators are "Spring aware" so you can use @Inject/@Autowire out of box.

Example of custom object validation:

@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = { YourCustomObjectValidator.class })
public @interface YourCustomObjectValid {

    String message() default "{YourCustomObjectValid.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

public class YourCustomObjectValidator implements ConstraintValidator<YourCustomObjectValid, YourCustomObject> {

    @Override
    public void initialize(YourCustomObjectValid constraintAnnotation) { }

    @Override
    public boolean isValid(YourCustomObject value, ConstraintValidatorContext context) {

        // Validate your complex logic 

        // Mark field with error
        ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
        cvb.addNode(someField).addConstraintViolation();

        return true;
    }
}

@YourCustomObjectValid
public YourCustomObject {
}

Example of generic fields equality:

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = { FieldsEqualityValidator.class })
public @interface FieldsEquality {

    String message() default "{FieldsEquality.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * Name of the first field that will be compared.
     * 
     * @return name
     */
    String firstFieldName();

    /**
     * Name of the second field that will be compared.
     * 
     * @return name
     */
    String secondFieldName();

    @Target({ TYPE, ANNOTATION_TYPE })
    @Retention(RUNTIME)
    public @interface List {
        FieldsEquality[] value();
    }
}




import java.lang.reflect.Field;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;

public class FieldsEqualityValidator implements ConstraintValidator<FieldsEquality, Object> {

    private static final Logger log = LoggerFactory.getLogger(FieldsEqualityValidator.class);

    private String firstFieldName;
    private String secondFieldName;

    @Override
    public void initialize(FieldsEquality constraintAnnotation) {
        firstFieldName = constraintAnnotation.firstFieldName();
        secondFieldName = constraintAnnotation.secondFieldName();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null)
            return true;

        try {
            Class<?> clazz = value.getClass();

            Field firstField = ReflectionUtils.findField(clazz, firstFieldName);
            firstField.setAccessible(true);
            Object first = firstField.get(value);

            Field secondField = ReflectionUtils.findField(clazz, secondFieldName);
            secondField.setAccessible(true);
            Object second = secondField.get(value);

            if (first != null && second != null && !first.equals(second)) {
                    ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
          cvb.addNode(firstFieldName).addConstraintViolation();

          ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
          cvb.addNode(someField).addConstraintViolation(secondFieldName);

                return false;
            }
        } catch (Exception e) {
            log.error("Cannot validate fileds equality in '" + value + "'!", e);
            return false;
        }

        return true;
    }
}

@FieldsEquality(firstFieldName = "password", secondFieldName = "confirmPassword")
public class NewUserForm {

    private String password;

    private String confirmPassword;

}

Android Studio Could not initialize class org.codehaus.groovy.runtime.InvokerHelper

I'm using Pop OS 20.04 and I have Java versions 8, 11 and 14 installed on my notebook.

This error was happening to me when version 14 was standard.

When I switched to using version 11 as the default, the error no longer occurred.

sudo update-alternatives --config java

JQuery .hasClass for multiple values in an if statement

The hasClass method will accept an array of class names as an argument, you can do something like this:

$(document).ready(function() {
function filterFilesList() {
    var rows = $('.file-row');
    var checked = $("#filterControls :checkbox:checked");

    if (checked.length) {
        var criteriaCollection = [];

        checked.each(function() {
            criteriaCollection.push($(this).val());
        });

        rows.each(function() {
            var row = $(this);
            var rowMatch = row.hasClass(criteriaCollection);

            if (rowMatch) {
                row.show();
            } else {
                row.hide(200);
            }
        });
    } else {
        rows.each(function() {
            $(this).show();
        });
    }
}

    $("#filterControls :checkbox").click(filterFilesList);
    filterFilesList();
});

Change the value in app.config file dynamically

You have to update your app.config file manually

// Load the app.config file
XmlDocument xml = new XmlDocument();
xml.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

// Do whatever you need, like modifying the appSettings section

// Save the new setting
xml.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

And then tell your application to reload any section you modified

ConfigurationManager.RefreshSection("appSettings");

How to copy to clipboard using Access/VBA?

I couldn't figure out how to use the API using the first Google results. Fortunately a thread somewhere pointed me to this link: http://access.mvps.org/access/api/api0049.htm

Which works nicely. :)

How do I detect unsigned integer multiply overflow?

To expand on Head Geek's answer, there is a faster way to do the addition_is_safe;

bool addition_is_safe(unsigned int a, unsigned int b)
{
    unsigned int L_Mask = std::numeric_limits<unsigned int>::max();
    L_Mask >>= 1;
    L_Mask = ~L_Mask;

    a &= L_Mask;
    b &= L_Mask;

    return ( a == 0 || b == 0 );
}

This uses machine-architecture safe, in that 64-bit and 32-bit unsigned integers will still work fine. Basically, I create a mask that will mask out all but the most significant bit. Then, I mask both integers, and if either of them do not have that bit set, then addition is safe.

This would be even faster if you pre-initialize the mask in some constructor, since it never changes.

What is the significance of #pragma marks? Why do we need #pragma marks?

#pragma mark directives show up in Xcode in the menus for direct access to methods. They have no impact on the program at all.

For example, using it with Xcode 4 will make those items appear directly in the Jump Bar.

There is a special pragma mark - which creates a line.

enter image description here

In WPF, what are the differences between the x:Name and Name attributes?

They are not the same thing.

x:Name is a xaml concept, used mainly to reference elements. When you give an element the x:Name xaml attribute, "the specified x:Name becomes the name of a field that is created in the underlying code when xaml is processed, and that field holds a reference to the object." (MSDN) So, it's a designer-generated field, which has internal access by default.

Name is the existing string property of a FrameworkElement, listed as any other wpf element property in the form of a xaml attribute.

As a consequence, this also means x:Name can be used on a wider range of objects. This is a technique to enable anything in xaml to be referenced by a given name.

jquery json to string?

The best way I have found is to use jQuery JSON

INSERT INTO @TABLE EXEC @query with SQL Server 2000

N.B. - this question and answer relate to the 2000 version of SQL Server. In later versions, the restriction on INSERT INTO @table_variable ... EXEC ... were lifted and so it doesn't apply for those later versions.


You'll have to switch to a temp table:

CREATE TABLE #tmp (code varchar(50), mount money)
DECLARE @q nvarchar(4000)
SET @q = 'SELECT coa_code, amount FROM T_Ledger_detail'

INSERT INTO  #tmp (code, mount)
EXEC sp_executesql (@q)

SELECT * from #tmp

From the documentation:

A table variable behaves like a local variable. It has a well-defined scope, which is the function, stored procedure, or batch in which it is declared.

Within its scope, a table variable may be used like a regular table. It may be applied anywhere a table or table expression is used in SELECT, INSERT, UPDATE, and DELETE statements. However, table may not be used in the following statements:

INSERT INTO table_variable EXEC stored_procedure

SELECT select_list INTO table_variable statements.

C++ unordered_map using a custom class type as the key

To be able to use std::unordered_map (or one of the other unordered associative containers) with a user-defined key-type, you need to define two things:

  1. A hash function; this must be a class that overrides operator() and calculates the hash value given an object of the key-type. One particularly straight-forward way of doing this is to specialize the std::hash template for your key-type.

  2. A comparison function for equality; this is required because the hash cannot rely on the fact that the hash function will always provide a unique hash value for every distinct key (i.e., it needs to be able to deal with collisions), so it needs a way to compare two given keys for an exact match. You can implement this either as a class that overrides operator(), or as a specialization of std::equal, or – easiest of all – by overloading operator==() for your key type (as you did already).

The difficulty with the hash function is that if your key type consists of several members, you will usually have the hash function calculate hash values for the individual members, and then somehow combine them into one hash value for the entire object. For good performance (i.e., few collisions) you should think carefully about how to combine the individual hash values to ensure you avoid getting the same output for different objects too often.

A fairly good starting point for a hash function is one that uses bit shifting and bitwise XOR to combine the individual hash values. For example, assuming a key-type like this:

struct Key
{
  std::string first;
  std::string second;
  int         third;

  bool operator==(const Key &other) const
  { return (first == other.first
            && second == other.second
            && third == other.third);
  }
};

Here is a simple hash function (adapted from the one used in the cppreference example for user-defined hash functions):

namespace std {

  template <>
  struct hash<Key>
  {
    std::size_t operator()(const Key& k) const
    {
      using std::size_t;
      using std::hash;
      using std::string;

      // Compute individual hash values for first,
      // second and third and combine them using XOR
      // and bit shifting:

      return ((hash<string>()(k.first)
               ^ (hash<string>()(k.second) << 1)) >> 1)
               ^ (hash<int>()(k.third) << 1);
    }
  };

}

With this in place, you can instantiate a std::unordered_map for the key-type:

int main()
{
  std::unordered_map<Key,std::string> m6 = {
    { {"John", "Doe", 12}, "example"},
    { {"Mary", "Sue", 21}, "another"}
  };
}

It will automatically use std::hash<Key> as defined above for the hash value calculations, and the operator== defined as member function of Key for equality checks.

If you don't want to specialize template inside the std namespace (although it's perfectly legal in this case), you can define the hash function as a separate class and add it to the template argument list for the map:

struct KeyHasher
{
  std::size_t operator()(const Key& k) const
  {
    using std::size_t;
    using std::hash;
    using std::string;

    return ((hash<string>()(k.first)
             ^ (hash<string>()(k.second) << 1)) >> 1)
             ^ (hash<int>()(k.third) << 1);
  }
};

int main()
{
  std::unordered_map<Key,std::string,KeyHasher> m6 = {
    { {"John", "Doe", 12}, "example"},
    { {"Mary", "Sue", 21}, "another"}
  };
}

How to define a better hash function? As said above, defining a good hash function is important to avoid collisions and get good performance. For a real good one you need to take into account the distribution of possible values of all fields and define a hash function that projects that distribution to a space of possible results as wide and evenly distributed as possible.

This can be difficult; the XOR/bit-shifting method above is probably not a bad start. For a slightly better start, you may use the hash_value and hash_combine function template from the Boost library. The former acts in a similar way as std::hash for standard types (recently also including tuples and other useful standard types); the latter helps you combine individual hash values into one. Here is a rewrite of the hash function that uses the Boost helper functions:

#include <boost/functional/hash.hpp>

struct KeyHasher
{
  std::size_t operator()(const Key& k) const
  {
      using boost::hash_value;
      using boost::hash_combine;

      // Start with a hash value of 0    .
      std::size_t seed = 0;

      // Modify 'seed' by XORing and bit-shifting in
      // one member of 'Key' after the other:
      hash_combine(seed,hash_value(k.first));
      hash_combine(seed,hash_value(k.second));
      hash_combine(seed,hash_value(k.third));

      // Return the result.
      return seed;
  }
};

And here’s a rewrite that doesn’t use boost, yet uses good method of combining the hashes:

namespace std
{
    template <>
    struct hash<Key>
    {
        size_t operator()( const Key& k ) const
        {
            // Compute individual hash values for first, second and third
            // http://stackoverflow.com/a/1646913/126995
            size_t res = 17;
            res = res * 31 + hash<string>()( k.first );
            res = res * 31 + hash<string>()( k.second );
            res = res * 31 + hash<int>()( k.third );
            return res;
        }
    };
}

ASP.NET MVC Html.ValidationSummary(true) does not display model errors

If nearly everything seems right, another thing to look out for is to ensure that the validation summary is not being explicitly hidden via some CSS override like this:

.validation-summary-valid {
    display: none;
}

This may also cause the @Html.ValidationSummary to appear hidden, as the summary is dynamically rendered with the validation-summary-valid class.

Replace specific text with a redacted version using Python

You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.

NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.

Example:

Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.

Returns:

NER with spacy

Just be aware that this is not 100%!

Here are a little snippet for you to try out:

import spacy

phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
   doc = nlp(phrase)
   replaced = ""
   for token in doc:
      if token in doc.ents:
         replaced+="XXXX "
      else:
         replaced+=token.text+" "

Read more here: https://spacy.io/usage/linguistic-features#named-entities

You could, instead of replacing with XXXX, replace based on the entity type, like:

if ent.label_ == "PERSON":
   replaced += "<PERSON> "

Then:

import re, random

personames = ["Jack", "Mike", "Bob", "Dylan"]

phrase = re.replace("<PERSON>", random.choice(personames), phrase)

onchange equivalent in angular2

We can use Angular event bindings to respond to any DOM event. The syntax is simple. We surround the DOM event name in parentheses and assign a quoted template statement to it. -- reference

Since change is on the list of standard DOM events, we can use it:

(change)="saverange()"

In your particular case, since you're using NgModel, you could break up the two-way binding like this instead:

[ngModel]="range" (ngModelChange)="saverange($event)"

Then

saverange(newValue) {
  this.range = newValue;
  this.Platform.ready().then(() => {
     this.rootRef.child("users").child(this.UserID).child('range').set(this.range)
  })
} 

However, with this approach saverange() is called with every keystroke, so you're probably better off using (change).

Display only date and no time

You could simply convert the datetime. Something like:

@Convert.ToString(string.Format("{0:dd/MM/yyyy}", Model.Returndate))

After updating Entity Framework model, Visual Studio does not see changes

First Build your Project and if it was successful, right click on the "model.tt" file and choose run custom tool. It will fix it.

Again Build your project and point to "model.context.tt" run custom tool. it will update DbSet lists.

How to: Create trigger for auto update modified date with SQL Server 2008

My approach:

  • define a default constraint on the ModDate column with a value of GETDATE() - this handles the INSERT case

  • have a AFTER UPDATE trigger to update the ModDate column

Something like:

CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
    UPDATE dbo.TimeEntry
    SET ModDate = GETDATE()
    WHERE ID IN (SELECT DISTINCT ID FROM Inserted)

Why is this printing 'None' in the output?

Because of double print function. I suggest you to use return instead of print inside the function definition.

def lyrics():
    return "The very first line"
print(lyrics())

OR

def lyrics():
    print("The very first line")
lyrics()

How to retrieve Jenkins build parameters using the Groovy API?

Update: Jenkins 2.x solution:

With Jenkins 2 pipeline dsl, you can directly access any parameter with the trivial syntax based on the params (Map) built-in:

echo " FOOBAR value: ${params.'FOOBAR'}"

The returned value will be a String or a boolean depending on the Parameter type itself. The syntax is the same for scripted or declarative syntax. More info at: https://jenkins.io/doc/book/pipeline/jenkinsfile/#handling-parameters

Original Answer for Jenkins 1.x:

For Jenkins 1.x, the syntax is based on the build.buildVariableResolver built-ins:

// ... or if you want the parameter by name ...
def hardcoded_param = "FOOBAR"
def resolver = build.buildVariableResolver
def hardcoded_param_value = resolver.resolve(hardcoded_param)

Please note the official Jenkins Wiki page covers this in more details as well, especially how to iterate upon the build parameters: https://wiki.jenkins-ci.org/display/JENKINS/Parameterized+System+Groovy+script

The salient part is reproduced below:

// get parameters
def parameters = build?.actions.find{ it instanceof ParametersAction }?.parameters
parameters.each {
   println "parameter ${it.name}:"
   println it.dump()
}

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

Simple steps: 1.Go to Android Studio. 2.Close all open projects if any. 3.There will be an option which says import non Android Studio Projects(Eclipse ect). 4.Click on it and choose ur project Thats't it enjoy!!!

svn list of files that are modified in local copy

As said you have to use SVN Check for modification in GUI and tortoiseproc.exe /command:repostatus /path:"<path-to-version-control-file-or-directory>" in CLI to see changes related to the root of the <path-to-version-control-file-or-directory>.

Sadly, but this command won't show ALL local changes, it does show only those changes which are related to the requested directory root. The changes taken separately, like standalone checkouts or orphan external directories in the root subdirectory will be shown as Unversioned or Nested and you might miss to commit/lookup them.

To avoid such condition you have to either call to tortoiseproc.exe /command:repostatus /pathfile:"<path-to-file-with-list-of-items-to-lookup-from>" (see detailed documentation on the command line: https://tortoisesvn.net/docs/nightly/TortoiseSVN_en/tsvn-automation.html), or use some 3dparty applications/utilities/scripts to wrap the call.

I has been wrote my own set of scripts for Windows to automate the call from the Total Commander: https://sf.net/p/contools/contools/HEAD/tree/trunk/Scripts/Tools/ToolAdaptors/totalcmd/README_EN.txt (search for TortoiseSVN)

- Opens TortoiseSVN status dialog for a set of WC directories (always opens to show unversioned changes).

Command:   call_nowindow.vbs
Arguments: tortoisesvn\TortoiseProcByNestedWC.bat /command:repostatus "%P" %S

- Opens TortoiseSVN commit dialogs for a set of WC directories (opens only if has not empty versioned changes).

Command:   call_nowindow.vbs
Arguments: tortoisesvn\TortoiseProcByNestedWC.bat /command:commit "%P" %S

See the README_EN.txt for the latest details (you have to execute the configure.bat before the usage and copy rest of scripts on yourself like call_nowindow.vbs).

Create empty data frame with column names by assigning a string vector?

How about:

df <- data.frame(matrix(ncol = 3, nrow = 0))
x <- c("name", "age", "gender")
colnames(df) <- x

To do all these operations in one-liner:

setNames(data.frame(matrix(ncol = 3, nrow = 0)), c("name", "age", "gender"))

#[1] name   age    gender
#<0 rows> (or 0-length row.names)

Or

data.frame(matrix(ncol=3,nrow=0, dimnames=list(NULL, c("name", "age", "gender"))))

Access parent DataContext from DataTemplate

I was searching how to do something similar in WPF and I got this solution:

<ItemsControl ItemsSource="{Binding MyItems,Mode=OneWay}">
<ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
        <StackPanel Orientation="Vertical" />
    </ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
    <DataTemplate>
        <RadioButton 
            Content="{Binding}" 
            Command="{Binding Path=DataContext.CustomCommand, 
                        RelativeSource={RelativeSource Mode=FindAncestor,      
                        AncestorType={x:Type ItemsControl}} }"
            CommandParameter="{Binding}" />
    </DataTemplate>
</ItemsControl.ItemTemplate>

I hope this works for somebody else. I have a data context which is set automatically to the ItemsControls, and this data context has two properties: MyItems -which is a collection-, and one command 'CustomCommand'. Because of the ItemTemplate is using a DataTemplate, the DataContext of upper levels is not directly accessible. Then the workaround to get the DC of the parent is use a relative path and filter by ItemsControl type.

.mp4 file not playing in chrome

I was actually running into some strange errors with mp4's a while ago. What fixed it for me was re-encoding the video using known supported codecs (H.264 & MP3).

I actually used the VLC player to do so and it worked fine afterward. I converted using the mentioned codecs H.264/MP3. That solved it for me.

Maybe the problem is not in the format but in the JavaScript implementation of the play/ pause methods. May I suggest visiting the following link where Google developer explains it in a good way?

Additionally, you could choose to use the newer webp format, which Chrome supports out of the box, but be careful with other browsers. Check the support for it before implementation. Here's a link that describes the mentioned format.

On that note: I've created a small script that easily converts all standard formats to webp. You can easily configure it to fit your needs. Here's the Github repo of the same projects.

How to create exe of a console application

Normally, the exe can be found in the debug folder, as suggested previously, but not in the release folder, that is disabled by default in my configuration. If you want to activate the release folder, you can do this: BUILD->Batch Build And activate the "build" checkbox in the release configuration. When you click the build button, the exe with some dependencies will be generated. Now you can copy and use it.

Group by multiple field names in java 8

You have a few options here. The simplest is to chain your collectors:

Map<String, Map<Integer, List<Person>>> map = people
    .collect(Collectors.groupingBy(Person::getName,
        Collectors.groupingBy(Person::getAge));

Then to get a list of 18 year old people called Fred you would use:

map.get("Fred").get(18);

A second option is to define a class that represents the grouping. This can be inside Person. This code uses a record but it could just as easily be a class (with equals and hashCode defined) in versions of Java before JEP 359 was added:

class Person {
    record NameAge(String name, int age) { }

    public NameAge getNameAge() {
        return new NameAge(name, age);
    }
}

Then you can use:

Map<NameAge, List<Person>> map = people.collect(Collectors.groupingBy(Person::getNameAge));

and search with

map.get(new NameAge("Fred", 18));

Finally if you don't want to implement your own group record then many of the Java frameworks around have a pair class designed for this type of thing. For example: apache commons pair If you use one of these libraries then you can make the key to the map a pair of the name and age:

Map<Pair<String, Integer>, List<Person>> map =
    people.collect(Collectors.groupingBy(p -> Pair.of(p.getName(), p.getAge())));

and retrieve with:

map.get(Pair.of("Fred", 18));

Personally I don't really see much value in generic tuples now that records are available in the language as records display intent better and require very little code.

Check if string begins with something?

You can use string.match() and a regular expression for this too:

if(pathname.match(/^\/sub\/1/)) { // you need to escape the slashes

string.match() will return an array of matching substrings if found, otherwise null.

.Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned

I know this has already been answered a long time ago, but I made an extension method to hopefully help other people that come to this question.

Code:

public static class WebRequestExtensions
{
    public static WebResponse GetResponseWithoutException(this WebRequest request)
    {
        if (request == null)
        {
            throw new ArgumentNullException("request");
        }

        try
        {
            return request.GetResponse();
        }
        catch (WebException e)
        {
            if (e.Response == null)
            {
                throw;
            }

            return e.Response;
        }
    }
}

Usage:

var request = (HttpWebRequest)WebRequest.CreateHttp("http://invalidurl.com");

//... (initialize more fields)

using (var response = (HttpWebResponse)request.GetResponseWithoutException())
{
    Console.WriteLine("I got Http Status Code: {0}", response.StatusCode);
}

Select from multiple tables without a join?

select 'test', (select name from employee where id=1) as name, (select name from address where id=2) as address ;

Calculate percentage Javascript

To get the percentage of a number, we need to multiply the desired percentage percent by that number. In practice we will have:

function percentage(percent, total) {
    return ((percent/ 100) * total).toFixed(2)
}

Example of usage:

const percentResult = percentage(10, 100);
// print 10.00

.toFixed() is optional for monetary formats.

A CORS POST request works from plain JavaScript, but why not with jQuery?

Modify your Jquery in following way:

$.ajax({
            url: someurl,
            contentType: 'application/json',
            data: JSONObject,
            headers: { 'Access-Control-Allow-Origin': '*' }, //add this line
            dataType: 'json',
            type: 'POST',                
            success: function (Data) {....}
});

MongoDB: How To Delete All Records Of A Collection in MongoDB Shell?

db.users.count()
db.users.remove({})
db.users.count()

Pentaho Data Integration SQL connection

Above answers were helpful, but for unknown reasons they did not seem to work. So if you have already installed MySql workbench on your system, instead of downloading the jar files and struggling with the correct version just go to

C:\Program Files (x86)\MySQL\Connector J 8.0

and copy mysql-connector-java-8.0.12 (does not matter what version it is) the jar file in that location and paste it to C:\Program Files\pentaho\design-tools\data-integration\lib

How to use paths in tsconfig.json?

You can use combination of baseUrl and paths docs.

Assuming root is on the topmost src dir(and I read your image properly) use

// tsconfig.json
{
  "compilerOptions": {
    ...
    "baseUrl": ".",
    "paths": {
      "lib/*": [
        "src/org/global/lib/*"
      ]
    }
  }
}

For webpack you might also need to add module resolution. For webpack2 this could look like

// webpack.config.js
module.exports = {
    resolve: {
        ...
        modules: [
            ...
            './src/org/global'
        ]
    }
}

Sending a JSON HTTP POST request from Android

try some thing like blow:

SString otherParametersUrServiceNeed =  "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";

URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();   
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);

   JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

wr.writeBytes(jsonParam.toString());

wr.flush();
wr.close();

References :

  1. http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
  2. Java - sending HTTP parameters via POST method easily

Undefined symbols for architecture armv7

In Xcode Version 6.3.2 , I solved the exactly same problem by adding Library libxml2.dylib and libz.dylib In Link Binary With Libraries !

How to convert int[] to Integer[] in Java?

This worked like a charm!

int[] mInt = new int[10];
Integer[] mInteger = new Integer[mInt.length];

List<Integer> wrapper = new AbstractList<Integer>() {
    @Override
    public int size() {
        return mInt.length;
    }

    @Override
    public Integer get(int i) {
        return mInt[i];
    }
};

wrapper.toArray(mInteger);

How to view Plugin Manager in Notepad++

Latest version of Notepad++ got a new built-in plugin manager which works nicely.

How do I fix the "You don't have write permissions into the /usr/bin directory" error when installing Rails?

To fix your specific error you need to run that command as sudo, ie:

sudo gem install rails --pre

How to properly reference local resources in HTML?

  • A leading slash tells the browser to start at the root directory.
  • If you don't have the leading slash, you're referencing from the current directory.
  • If you add two dots before the leading slash, it means you're referencing the parent of the current directory.

Take the following folder structure

demo folder structure

notice:

  • the ROOT checkmark is green,
  • the second checkmark is orange,
  • the third checkmark is purple,
  • the forth checkmark is yellow

Now in the index.html.en file you'll want to put the following markup

<p>
    <span>src="check_mark.png"</span>
    <img src="check_mark.png" />
    <span>I'm purple because I'm referenced from this current directory</span>
</p>

<p>
    <span>src="/check_mark.png"</span>
    <img src="/check_mark.png" />
    <span>I'm green because I'm referenced from the ROOT directory</span>
</p>

<p>
    <span>src="subfolder/check_mark.png"</span>
    <img src="subfolder/check_mark.png" />
    <span>I'm yellow because I'm referenced from the child of this current directory</span>
</p>

<p>
    <span>src="/subfolder/check_mark.png"</span>
    <img src="/subfolder/check_mark.png" />
    <span>I'm orange because I'm referenced from the child of the ROOT directory</span>
</p>

<p>
    <span>src="../subfolder/check_mark.png"</span>
    <img src="../subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced from the parent of this current directory</span>
</p>

<p>
    <span>src="subfolder/subfolder/check_mark.png"</span>
    <img src="subfolder/subfolder/check_mark.png" />
    <span>I'm [broken] because there is no subfolder two children down from this current directory</span>
</p>

<p>
    <span>src="/subfolder/subfolder/check_mark.png"</span>
    <img src="/subfolder/subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced two children down from the ROOT directory</span>
</p>

Now if you load up the index.html.en file located in the second subfolder
http://example.com/subfolder/subfolder/

This will be your output

enter image description here

How to get the <html> tag HTML with JavaScript / jQuery?

In jQuery:

var html_string = $('html').outerHTML()

In plain Javascript:

var html_string = document.documentElement.outerHTML

Laravel Eloquent groupBy() AND also return count of each group

Try with this

->groupBy('state_id','locality')
  ->havingRaw('count > 1 ')
  ->having('items.name','LIKE',"%$keyword%")
  ->orHavingRaw('brand LIKE ?',array("%$keyword%"))

Run Android studio emulator on AMD processor

I am using microsoft's Android emulator with Android Studio. I have an AMD FX8350. The ARM one in android studio is terribly slow.

The only issue is that it requires Hyper-V which is not available on windows 10 Home.

Its a really quick emulator and it is free. The best emulator I have used.

Top 1 with a left join

Because the TOP 1 from the ordered sub-query does not have profile_id = 'u162231993' Remove where u.id = 'u162231993' and see results then.

Run the sub-query separately to understand what's going on.

ORA-01830: date format picture ends before converting entire input string / Select sum where date query

You can try this:

Select To_date ('15/2/2007 00:00:00', 'DD/MM/YYYY HH24:MI:SS'),
       To_date ('28/2/2007 10:12', 'DD/MM/YYYY HH24:MI:SS')
  From DUAL;

Source: http://notsyncing.org/2008/02/manipulando-fechas-con-horas-en-plsql-y-sql/

PHP Fatal error: Cannot access empty property

To access a variable in a class, you must use $this->myVar instead of $this->$myvar.

And, you should use access identifier to declare a variable instead of var.

Please read the doc here.

Spring RestTemplate timeout

I finally got this working.

I think the fact that our project had two different versions of the commons-httpclient jar wasn't helping. Once I sorted that out I found you can do two things...

In code you can put the following:

HttpComponentsClientHttpRequestFactory rf =
    (HttpComponentsClientHttpRequestFactory) restTemplate.getRequestFactory();
rf.setReadTimeout(1 * 1000);
rf.setConnectTimeout(1 * 1000);

The first time this code is called it will set the timeout for the HttpComponentsClientHttpRequestFactory class used by the RestTemplate. Therefore, all subsequent calls made by RestTemplate will use the timeout settings defined above.

Or the better option is to do this:

<bean id="RestOperations" class="org.springframework.web.client.RestTemplate">
    <constructor-arg>
        <bean class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
            <property name="readTimeout" value="${application.urlReadTimeout}" />
            <property name="connectTimeout" value="${application.urlConnectionTimeout}" />
        </bean>
    </constructor-arg>
</bean>

Where I use the RestOperations interface in my code and get the timeout values from a properties file.

Command copy exited with code 4 when building - Visual Studio restart solves it

I had the same issue. It was caused by having the same flag twice, for example:

if $(ConfigurationName) == Release (xcopy "$(TargetDir)." "$(SolutionDir)Deployment\$(ProjectName)\" /e /d /i /y /e)

Observe that the "/e" flag appears twice. Removing the duplicate solved the issue.

How to call python script on excel vba?

Try this:

retVal = Shell("python.exe <full path to your python script>", vbNormalFocus)

replace <full path to your python script> with the full path

How to center text vertically with a large font-awesome icon?

I use icons next to text 99% of the time so I made the change globally:

.fa-2x {
  vertical-align: middle;
}

Add 3x, 4x, etc to the same definition as needed.

How do I mock a REST template exchange?

This work on my side.

ResourceBean resourceBean = initResourceBean();
ResponseEntity<ResourceBean> responseEntity  
    = new ResponseEntity<ResourceBean>(resourceBean, HttpStatus.ACCEPTED);
when(restTemplate.exchange(
    Matchers.anyObject(), 
    Matchers.any(HttpMethod.class),
    Matchers.<HttpEntity> any(), 
    Matchers.<Class<ResourceBean>> any())
 ).thenReturn(responseEntity);

Building and running app via Gradle and Android Studio is slower than via Eclipse

Searched everywhere for this and finally found a solution that works for us. Enabling parallel builds (On OSX: preferences -> compiler -> gradle -> "Compile independent modules in parallel") and enabling 'make project automatically' brought it down from ~1 min to ~20 sec. Thanks to /u/Covalence.

http://www.reddit.com/r/androiddev/comments/1k3nb3/gradle_and_android_studio_way_slower_to_build/

case-insensitive matching in xpath?

XPath 2 has a lower-case (and upper-case) string function. That's not quite the same as case-insensitive, but hopefully it will be close enough:

//CD[lower-case(@title)='empire burlesque']

If you are using XPath 1, there is a hack using translate.

Variable is accessed within inner class. Needs to be declared final

Here's a funny answer.

You can declare a final one-element array and change the elements of the array all you want apparently. I'm sure it breaks the very reason why this compiler rule was implemented in the first place but it's handy when you're in a time-bind as I was today.

I actually can't claim credit for this one. It was IntelliJ's recommendation! Feels a bit hacky. But doesn't seem as bad as a global variable so I thought it worth mentioning here. It's just one solution to the problem. Not necessarily the best one.

final int[] tapCount = {0};

addSiteButton.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
       tapCount[0]++;
    }

});

How to get a cookie from an AJAX response?

Similar to yebmouxing I could not the

 xhr.getResponseHeader('Set-Cookie');

method to work. It would only return null even if I had set HTTPOnly to false on my server.

I too wrote a simple js helper function to grab the cookies from the document. This function is very basic and only works if you know the additional info (lifespan, domain, path, etc. etc.) to add yourself:

function getCookie(cookieName){
  var cookieArray = document.cookie.split(';');
  for(var i=0; i<cookieArray.length; i++){
    var cookie = cookieArray[i];
    while (cookie.charAt(0)==' '){
      cookie = cookie.substring(1);
    }
    cookieHalves = cookie.split('=');
    if(cookieHalves[0]== cookieName){
      return cookieHalves[1];
    }
  }
  return "";
}

Editing hosts file to redirect url?

You could use the RedirectMatch directive in Apache to do something similar you want.

It's pretty simple.

RedirectMatch / http://222.222.222.222/

Anyway, I can't see any reason to do that thing. Aren't you trying to intercept traffic? There are better ways. For Linux boxes as a router: iptables -j REDIRECT + Squid or Apache. For Cisco routers, you can use WCCP to a Cache or Web Server...

Notepad++ Setting for Disabling Auto-open Previous Files

My problem was that Notepad++ was crashing on a file I had previously opened; I was unable to open the application at all. This blog post discusses how to delete the data from the "Sessions" file so that Notepad++ will open without having any prior files open:

From the blog post:

Method 1 - edit session.xml

  1. Open file session.xml in C:\Users\Username\AppData\Roaming\Notepad++ or %APPDATA%\Notepad++
  2. Delete its contents and save it
  3. Run Notepad++ , session.xml will get new content automatically

Method 2 - add the -nosession parameter to Notepad++ shortcut

  1. Create a desktop shortcut referring to your Notepad++ program, e.g. C:\Program Files\Notepad++\notepad++.exe
  2. Right click on this shortcut
  3. In the "Target" field add the -nosession parameter so the target field looks exaxtly like (apostrophes included too): "C:\Program Files\Notepad++\notepad++.exe" -nosession
  4. Save and run Notepad++ from this shortcut icon with no recent files

Note: This is not a permanent setting, this simply deletes the prior session's information / opened files and starts over.

Alternatively, if you know the file which is causing notepad++ to hang, you can simply rename the file and open notepad++. This will solve the problem.

I hadn't seen this solution listed when I was googling my problem so I wanted to add it here!

CSS transition effect makes image blurry / moves image 1px, in Chrome?

None of this worked, what worked for me is scaling image down.

So depending on what size you want the image or what resoultion your image is, you can do something like this:

_x000D_
_x000D_
.ok {
      transform: perspective(100px) rotateY(0deg) scale(0.5);
      transition: transform 1s;
      object-fit:contain;
}
.ok:hover{
      transform: perspective(100px) rotateY(-10deg) scale(0.5);
}

/* Demo Preview Stuff */
.bad {
   max-width: 320px;
   object-fit:contain;
   transform: perspective(100px) rotateY(0deg);
   transition: transform 1s;
}
.bad:hover{
      transform: perspective(100px) rotateY(-10deg);
}

div {
     text-align: center;
     position: relative;
     display: flex;
}
h3{
    position: absolute;
    bottom: 30px;
    left: 0;
    right: 0;
}
     
.b {
    display: flex;
}
_x000D_
<center>
<h2>Hover on images</h2>
<div class="b">
<div>
  <img class="ok" src='https://www.howtogeek.com/wp-content/uploads/2018/10/preview-11.png'>
  <h3>Sharp</h3>
</div>

<div>
  <img class="bad" src='https://www.howtogeek.com/wp-content/uploads/2018/10/preview-11.png'>
  <h3>Blurry</h3>
</div>

</div>

</center>
_x000D_
_x000D_
_x000D_

The image should be scaled down, make sure you have a big image resoultion

How to set cursor to input box in Javascript?

This way sets the focus and cursor to the end of your input:

div.getElementsByTagName("input")[0].focus();
div.getElementsByTagName("input")[0].setSelectionRange(div.getElementsByTagName("input")[0].value.length,div.getElementsByTagName("input")[0].value.length,"forward");

How can I inspect element in an Android browser?

You can inspect elements of a website in your Android device using Chrome browser.

Open your Chrome browser and go to the website you want to inspect.

Go to the address bar and type "view-source:" before the "HTTP" and reload the page.

The whole elements of the page will be shown.

Mongoose, Select a specific field with find

DB Data

[
  {
    "_id": "70001",
    "name": "peter"
  },
  {
    "_id": "70002",
    "name": "john"
  },
  {
    "_id": "70003",
    "name": "joseph"
  }
]

Query

db.collection.find({},
{
  "_id": 0,
  "name": 1
}).exec((Result)=>{
    console.log(Result);
})

Output:

[
  {
    "name": "peter"
  },
  {
    "name": "john"
  },
  {
    "name": "joseph"
  }
]

Working sample playground

link

LINQ with groupby and count

Assuming userInfoList is a List<UserInfo>:

        var groups = userInfoList
            .GroupBy(n => n.metric)
            .Select(n => new
            {
                MetricName = n.Key,
                MetricCount = n.Count()
            }
            )
            .OrderBy(n => n.MetricName);

The lambda function for GroupBy(), n => n.metric means that it will get field metric from every UserInfo object encountered. The type of n is depending on the context, in the first occurrence it's of type UserInfo, because the list contains UserInfo objects. In the second occurrence n is of type Grouping, because now it's a list of Grouping objects.

Groupings have extension methods like .Count(), .Key() and pretty much anything else you would expect. Just as you would check .Lenght on a string, you can check .Count() on a group.

How do I update/upsert a document in Mongoose?

//Here is my code to it... work like ninj

router.param('contractor', function(req, res, next, id) {
  var query = Contractors.findById(id);

  query.exec(function (err, contractor){
    if (err) { return next(err); }
    if (!contractor) { return next(new Error("can't find contractor")); }

    req.contractor = contractor;
    return next();
  });
});

router.get('/contractors/:contractor/save', function(req, res, next) {

    contractor = req.contractor ;
    contractor.update({'_id':contractor._id},{upsert: true},function(err,contractor){
       if(err){ 
            res.json(err);
            return next(); 
            }
    return res.json(contractor); 
  });
});


--

How to compare different branches in Visual Studio Code

Use the Git History Diff plugin for easy side-by-side branch diffing:

https://marketplace.visualstudio.com/items?itemName=huizhou.githd

Visit the link above and scroll down to the animated GIF image titled Diff Branch. You'll see you can easily pick any branch and do side-by-side comparison with the branch you are on! It is like getting a preview of what you will see in the GitHub Pull Request. For other Git stuff I prefer Visual Studio Code's built-in functionality or Git Lens as others have mentioned.

However, the above plugin is outstanding for doing branch diffing (i.e., for those doing a rebase Git flow and need to preview before a force push up to a GitHub PR).

D3 transform scale and translate

I realize this question is fairly old, but wanted to share a quick demo of group transforms, paths/shapes, and relative positioning, for anyone else who found their way here looking for more info:

http://bl.ocks.org/dustinlarimer/6050773

Best way to display data via JSON using jQuery

Something like this:

$.getJSON("http://mywebsite.com/json/get.php?cid=15",
        function(data){
          $.each(data.products, function(i,product){
            content = '<p>' + product.product_title + '</p>';
            content += '<p>' + product.product_short_description + '</p>';
            content += '<img src="' + product.product_thumbnail_src + '"/>';
            content += '<br/>';
            $(content).appendTo("#product_list");
          });
        });

Would take a json object made from a PHP array returned with the key of products. e.g:

Array('products' => Array(0 => Array('product_title' => 'Product 1',
                                     'product_short_description' => 'Product 1 is a useful product',
                                     'product_thumbnail_src' => '/images/15/1.jpg'
                                    )
                          1 => Array('product_title' => 'Product 2',
                                     'product_short_description' => 'Product 2 is a not so useful product',
                                     'product_thumbnail_src' => '/images/15/2.jpg'
                                    )
                         )
     )

To reload the list you would simply do:

$("#product_list").empty();

And then call getJSON again with new parameters.

How to add percent sign to NSString

seems if %% followed with a %@, the NSString will go to some strange codes try this and this worked for me

NSString *str = [NSString stringWithFormat:@"%@%@%@", @"%%", 
                 [textfield text], @"%%"]; 

How to get html to print return value of javascript function?

Most likely you're looking for something like

var targetElement = document.getElementById('idOfTargetElement');
targetElement.innerHTML = produceMessage();

provided that this is not something which happens on page load, in which case it should already be there from the start.

update package.json version automatically

I am using husky and git-branch-is:

As of husky v1+:

// package.json
{
  "husky": {
    "hooks": {
      "post-merge": "(git-branch-is master && npm version minor || 
  (git-branch-is dev && npm --no-git-tag-version version patch)",
    }
  }
}

Prior to husky V1:

"scripts": {
  ...
  "postmerge": "(git-branch-is master && npm version minor || 
  (git-branch-is dev && npm --no-git-tag-version version patch)",
  ...
},

Read more about npm version

Webpack or Vue.js

If you are using webpack or Vue.js, you can display this in the UI using Auto inject version - Webpack plugin

NUXT

In nuxt.config.js:

var WebpackAutoInject = require('webpack-auto-inject-version');

module.exports = {
  build: {
    plugins: [
      new WebpackAutoInject({
        // options
        // example:
        components: {
          InjectAsComment: false
        },
      }),
    ]
  },
}

Inside your template for example in the footer:

<p> All rights reserved © 2018 [v[AIV]{version}[/AIV]]</p>

In Angular, how to add Validator to FormControl after control is created?

I think the selected answer is not correct, as the original question is "how to add a new validator after create the formControl".

As far as I know, that's not possible. The only thing you can do, is create the array of validators dynamicaly.

But what we miss is to have a function addValidator() to not override the validators already added to the formControl. If anybody has an answer for that requirement, would be nice to be posted here.

Best Practice: Software Versioning

We follow a.b.c approach like:

increament 'a' if there is some major changes happened in application. Like we upgrade .NET 1.1 application to .NET 3.5

increament 'b' if there is some minor changes like any new CR or Enhancement is implemented.

increament 'c' if there is some defects fixes in the code.

how to overlap two div in css?

I edited you fiddle you just need to add z-index to the front element and position it accordingly.

Tuples( or arrays ) as Dictionary keys in C#

The good, clean, fast, easy and readable ways is:

  • generate equality members (Equals() and GetHashCode()) method for the current type. Tools like ReSharper not only creates the methods, but also generates the necessary code for an equality check and/or for calculating hash code. The generated code will be more optimal than Tuple realization.
  • just make a simple key class derived from a tuple.

add something similar like this:

public sealed class myKey : Tuple<TypeA, TypeB, TypeC>
{
    public myKey(TypeA dataA, TypeB dataB, TypeC dataC) : base (dataA, dataB, dataC) { }

    public TypeA DataA => Item1; 

    public TypeB DataB => Item2;

    public TypeC DataC => Item3;
}

So you can use it with dictionary:

var myDictinaryData = new Dictionary<myKey, string>()
{
    {new myKey(1, 2, 3), "data123"},
    {new myKey(4, 5, 6), "data456"},
    {new myKey(7, 8, 9), "data789"}
};
  • You also can use it in contracts
  • as a key for join or groupings in linq
  • going this way you never ever mistype order of Item1, Item2, Item3 ...
  • you no need to remember or look into to code to understand where to go to get something
  • no need to override IStructuralEquatable, IStructuralComparable, IComparable, ITuple they all alredy here

Initializing array of structures

This is quite simple: my_data is a before defined structure type. So you want to declare an my_data-array of some elements, as you would do with

char a[] = { 'a', 'b', 'c', 'd' };

So the array would have 4 elements and you initialise them as

a[0] = 'a', a[1] = 'b', a[1] = 'c', a[1] ='d';

This is called a designated initializer (as i remember right).

and it just indicates that data has to be of type my_dat and has to be an array that needs to store so many my_data structures that there is a structure with each type member name Peter, James, John and Mike.

How do I select an element with its name attribute in jQuery?

$('[name="ElementNameHere"]').doStuff();

jQuery supports CSS3 style selectors, plus some more.

See more

How can I reverse a list in Python?

Can be done using __reverse__ , which returns a generator.

>>> l = [1,2,3,4,5]
>>> for i in l.__reversed__():
...   print i
... 
5
4
3
2
1
>>>

What is the best way to implement "remember me" for a website?

Store their UserId and a RememberMeToken. When they login with remember me checked generate a new RememberMeToken (which invalidate any other machines which are marked are remember me).

When they return look them up by the remember me token and make sure the UserId matches.

Java : Comparable vs Comparator

When your class implements Comparable, the compareTo method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals() comparisons return true.

A Comparator is its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.

For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b") would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.

In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.

Convert a object into JSON in REST service by Spring MVC

You can always add the @Produces("application/json") above your web method or specify produces="application/json" to return json. Then on top of the Student class you can add @XmlRootElement from javax.xml.bind.annotation package.

Please note, it might not be a good idea to directly return model classes. Just a suggestion.

HTH.

Run as java application option disabled in eclipse

Had the same problem. I apparently wrote the Main wrong:

public static void main(String[] args){

I missed the [] and that was the whole problem.

Check and recheck the Main function!

Is there a way to make a PowerShell script work by double clicking a .ps1 file?

A solution in the same spirit as UNIX shar (shell archive).

You can put your powershell script in a file with the .cmd extension (instead of .ps1), and put this at the start:

@echo off
Rem Make powershell read this file, skip a number of lines, and execute it.
Rem This works around .ps1 bad file association as non executables.
PowerShell -Command "Get-Content '%~dpnx0' | Select-Object -Skip 5 | Out-String | Invoke-Expression"
goto :eof
# Start of PowerShell script here

Create HTTP post request and receive response using C# console application

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace WebserverInteractionClassLibrary
{
    public class RequestManager
    {
        public string LastResponse { protected set; get; }

        CookieContainer cookies = new CookieContainer();

        internal string GetCookieValue(Uri SiteUri,string name)
        {
            Cookie cookie = cookies.GetCookies(SiteUri)[name];
            return (cookie == null) ? null : cookie.Value;
        }

        public string GetResponseContent(HttpWebResponse response)
        {
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }
            Stream dataStream = null;
            StreamReader reader = null;
            string responseFromServer = null;

            try
            {
                // Get the stream containing content returned by the server.
                dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                reader = new StreamReader(dataStream);
                // Read the content.
                responseFromServer = reader.ReadToEnd();
                // Cleanup the streams and the response.
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {                
                if (reader != null)
                {
                    reader.Close();
                }
                if (dataStream != null)
                {
                    dataStream.Close();
                }
                response.Close();
            }
            LastResponse = responseFromServer;
            return responseFromServer;
        }

        public HttpWebResponse SendPOSTRequest(string uri, string content, string login, string password, bool allowAutoRedirect)
        {
            HttpWebRequest request = GeneratePOSTRequest(uri, content, login, password, allowAutoRedirect);
            return GetResponse(request);
        }

        public HttpWebResponse SendGETRequest(string uri, string login, string password, bool allowAutoRedirect)
        {
            HttpWebRequest request = GenerateGETRequest(uri, login, password, allowAutoRedirect);
            return GetResponse(request);
        }

        public HttpWebResponse SendRequest(string uri, string content, string method, string login, string password, bool allowAutoRedirect)
        {
            HttpWebRequest request = GenerateRequest(uri, content, method, login, password, allowAutoRedirect);
            return GetResponse(request);
        }

        public HttpWebRequest GenerateGETRequest(string uri, string login, string password, bool allowAutoRedirect)
        {
            return GenerateRequest(uri, null, "GET", null, null, allowAutoRedirect);
        }

        public HttpWebRequest GeneratePOSTRequest(string uri, string content, string login, string password, bool allowAutoRedirect)
        {
            return GenerateRequest(uri, content, "POST", null, null, allowAutoRedirect);
        }

        internal HttpWebRequest GenerateRequest(string uri, string content, string method, string login, string password, bool allowAutoRedirect)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }
            // Create a request using a URL that can receive a post. 
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
            // Set the Method property of the request to POST.
            request.Method = method;
            // Set cookie container to maintain cookies
            request.CookieContainer = cookies;
            request.AllowAutoRedirect = allowAutoRedirect;
            // If login is empty use defaul credentials
            if (string.IsNullOrEmpty(login))
            {
                request.Credentials = CredentialCache.DefaultNetworkCredentials;
            }
            else
            {
                request.Credentials = new NetworkCredential(login, password);
            }
            if (method == "POST")
            {
                // Convert POST data to a byte array.
                byte[] byteArray = Encoding.UTF8.GetBytes(content);
                // Set the ContentType property of the WebRequest.
                request.ContentType = "application/x-www-form-urlencoded";
                // Set the ContentLength property of the WebRequest.
                request.ContentLength = byteArray.Length;
                // Get the request stream.
                Stream dataStream = request.GetRequestStream();
                // Write the data to the request stream.
                dataStream.Write(byteArray, 0, byteArray.Length);
                // Close the Stream object.
                dataStream.Close();
            }
            return request;
        }

        internal HttpWebResponse GetResponse(HttpWebRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();                
                cookies.Add(response.Cookies);                
                // Print the properties of each cookie.
                Console.WriteLine("\nCookies: ");
                foreach (Cookie cook in cookies.GetCookies(request.RequestUri))
                {
                    Console.WriteLine("Domain: {0}, String: {1}", cook.Domain, cook.ToString());
                }
            }
            catch (WebException ex)
            {
                Console.WriteLine("Web exception occurred. Status code: {0}", ex.Status);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return response;
        }

    }
}

Spring @Transactional - isolation, propagation

We can add for this:

@Transactional(readOnly = true)
public class Banking_CustomerService implements CustomerService {

    public Customer getDetail(String customername) {
        // do something
    }

    // these settings have precedence for this method
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public void updateCustomer(Customer customer) {
        // do something
    }
}

What's a simple way to get a text input popup dialog box on an iPhone

Just wanted to add an important piece of information that I believe was left out perhaps with the assumption that the ones seeking answers might already know. This problem happens a lot and I too found myself stuck when I tried to implement the viewAlert method for the buttons of the UIAlertView message. To do this you need to 1st add the delegate class which may look something like this:

@interface YourViewController : UIViewController <UIAlertViewDelegate>

Also you can find a very helpful tutorial here!

Hope this helps.

Center the content inside a column in Bootstrap 4

Add class text-center to your column:

<div class="col text-center">
I am centered
</div>

In Visual Studio C++, what are the memory allocation representations?

There's actually quite a bit of useful information added to debug allocations. This table is more complete:

http://www.nobugs.org/developer/win32/debug_crt_heap.html#table

Address  Offset After HeapAlloc() After malloc() During free() After HeapFree() Comments
0x00320FD8  -40    0x01090009    0x01090009     0x01090009    0x0109005A     Win32 heap info
0x00320FDC  -36    0x01090009    0x00180700     0x01090009    0x00180400     Win32 heap info
0x00320FE0  -32    0xBAADF00D    0x00320798     0xDDDDDDDD    0x00320448     Ptr to next CRT heap block (allocated earlier in time)
0x00320FE4  -28    0xBAADF00D    0x00000000     0xDDDDDDDD    0x00320448     Ptr to prev CRT heap block (allocated later in time)
0x00320FE8  -24    0xBAADF00D    0x00000000     0xDDDDDDDD    0xFEEEFEEE     Filename of malloc() call
0x00320FEC  -20    0xBAADF00D    0x00000000     0xDDDDDDDD    0xFEEEFEEE     Line number of malloc() call
0x00320FF0  -16    0xBAADF00D    0x00000008     0xDDDDDDDD    0xFEEEFEEE     Number of bytes to malloc()
0x00320FF4  -12    0xBAADF00D    0x00000001     0xDDDDDDDD    0xFEEEFEEE     Type (0=Freed, 1=Normal, 2=CRT use, etc)
0x00320FF8  -8     0xBAADF00D    0x00000031     0xDDDDDDDD    0xFEEEFEEE     Request #, increases from 0
0x00320FFC  -4     0xBAADF00D    0xFDFDFDFD     0xDDDDDDDD    0xFEEEFEEE     No mans land
0x00321000  +0     0xBAADF00D    0xCDCDCDCD     0xDDDDDDDD    0xFEEEFEEE     The 8 bytes you wanted
0x00321004  +4     0xBAADF00D    0xCDCDCDCD     0xDDDDDDDD    0xFEEEFEEE     The 8 bytes you wanted
0x00321008  +8     0xBAADF00D    0xFDFDFDFD     0xDDDDDDDD    0xFEEEFEEE     No mans land
0x0032100C  +12    0xBAADF00D    0xBAADF00D     0xDDDDDDDD    0xFEEEFEEE     Win32 heap allocations are rounded up to 16 bytes
0x00321010  +16    0xABABABAB    0xABABABAB     0xABABABAB    0xFEEEFEEE     Win32 heap bookkeeping
0x00321014  +20    0xABABABAB    0xABABABAB     0xABABABAB    0xFEEEFEEE     Win32 heap bookkeeping
0x00321018  +24    0x00000010    0x00000010     0x00000010    0xFEEEFEEE     Win32 heap bookkeeping
0x0032101C  +28    0x00000000    0x00000000     0x00000000    0xFEEEFEEE     Win32 heap bookkeeping
0x00321020  +32    0x00090051    0x00090051     0x00090051    0xFEEEFEEE     Win32 heap bookkeeping
0x00321024  +36    0xFEEE0400    0xFEEE0400     0xFEEE0400    0xFEEEFEEE     Win32 heap bookkeeping
0x00321028  +40    0x00320400    0x00320400     0x00320400    0xFEEEFEEE     Win32 heap bookkeeping
0x0032102C  +44    0x00320400    0x00320400     0x00320400    0xFEEEFEEE     Win32 heap bookkeeping

What is the recommended way to delete a large number of items from DynamoDB?

If you want to delete items after some time, e.g. after a month, just use Time To Live option. It will not count write units.

In your case, I would add ttl when logs expire and leave those after a user is deleted. TTL would make sure logs are removed eventually.

When Time To Live is enabled on a table, a background job checks the TTL attribute of items to see if they are expired.

DynamoDB typically deletes expired items within 48 hours of expiration. The exact duration within which an item truly gets deleted after expiration is specific to the nature of the workload and the size of the table. Items that have expired and not been deleted will still show up in reads, queries, and scans. These items can still be updated and successful updates to change or remove the expiration attribute will be honored.

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/TTL.html https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/howitworks-ttl.html

In Angular, how to pass JSON object/array into directive?

What you need is properly a service:

.factory('DataLayer', ['$http',

    function($http) {

        var factory = {};
        var locations;

        factory.getLocations = function(success) {
            if(locations){
                success(locations);
                return;
            }
            $http.get('locations/locations.json').success(function(data) {
                locations = data;
                success(locations);
            });
        };

        return factory;
    }
]);

The locations would be cached in the service which worked as singleton model. This is the right way to fetch data.

Use this service DataLayer in your controller and directive is ok as following:

appControllers.controller('dummyCtrl', function ($scope, DataLayer) {
    DataLayer.getLocations(function(data){
        $scope.locations = data;
    });
});

.directive('map', function(DataLayer) {
    return {
        restrict: 'E',
        replace: true,
        template: '<div></div>',
        link: function(scope, element, attrs) {

            DataLayer.getLocations(function(data) {
                angular.forEach(data, function(location, key){
                    //do something
                });
            });
        }
    };
});

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''')' at line 2

I was getting the same error when I used this code to update the record:

@mysqli_query($dbc,$query or die()))

After removing or die, it started working properly.

Errno 10061 : No connection could be made because the target machine actively refused it ( client - server )

if you have remote server installed on you machine. give server.py host as "localhost" and the port number. then client side , you have to give local ip- 127.0.0.1 and port number. then its works

Why isn't ProjectName-Prefix.pch created automatically in Xcode 6?

You need to create own PCH file
Add New file -> Other-> PCH file

Then add the path of this PCH file to your build setting->prefix header->path

($(SRCROOT)/filename.pch)

enter image description here