Programs & Examples On #Lg

LG is a multi national brand that sells electronic goods

How to install Android app on LG smart TV?

LG, VIZIO, SAMSUNG and PANASONIC TVs are not android based, and you cannot run APKs off of them... You should just buy a fire stick and call it a day. The only TVs that are android-based, and you can install APKs are: SONY, PHILIPS and SHARP.
#FACTS.

in iPhone App How to detect the screen resolution of the device

UIScreen class lets you find screen resolution in Points and Pixels.

Screen resolutions is measured in Points or Pixels. It should never be confused with screen size. A smaller screen size can have higher resolution.

UIScreen's 'bounds.width' return rectangular size in Points enter image description here

UIScreen's 'nativeBounds.width' return rectangular size in Pixels.This value is detected as PPI ( Point per inch ). Shows the sharpness & clarity of the Image on a device. enter image description here

You can use UIScreen class to detect all these values.

Swift3

// Normal Screen Bounds - Detect Screen size in Points.
let width = UIScreen.main.bounds.width
let height = UIScreen.main.bounds.height
print("\n width:\(width) \n height:\(height)")

// Native Bounds - Detect Screen size in Pixels.
let nWidth = UIScreen.main.nativeBounds.width
let nHeight = UIScreen.main.nativeBounds.height
print("\n Native Width:\(nWidth) \n Native Height:\(nHeight)")

Console

width:736.0 
height:414.0

Native Width:1080.0 
Native Height:1920.0

Swift 2.x

//Normal Bounds - Detect Screen size in Points.
    let width  = UIScreen.mainScreen.bounds.width
    let height = UIScreen.mainScreen.bounds.height

// Native Bounds - Detect Screen size in Pixels.
    let nWidth  = UIScreen.mainScreen.nativeBounds.width
    let nHeight = UIScreen.mainScreen.nativeBounds.height

ObjectiveC

// Normal Bounds - Detect Screen size in Points.
CGFloat *width  = [UIScreen mainScreen].bounds.size.width;
CGFloat *height = [UIScreen mainScreen].bounds.size.height;

// Native Bounds - Detect Screen size in Pixels.
CGFloat *width  = [UIScreen mainScreen].nativeBounds.size.width
CGFloat *height = [UIScreen mainScreen].nativeBounds.size.width

Failed to execute removeChild on Node

Your myCoolDiv element isn't a child of the player container. It's a child of the div you created as a wrapper for it (markerDiv in the first part of the code). Which is why it fails, removeChild only removes children, not descendants.

You'd want to remove that wrapper div, or not add it at all.

Here's the "not adding it at all" option:

_x000D_
_x000D_
var markerDiv = document.createElement("div");_x000D_
markerDiv.innerHTML = "<div id='MyCoolDiv' style='color: #2b0808'>123</div>";_x000D_
document.getElementById("playerContainer").appendChild(markerDiv.firstChild);_x000D_
// -------------------------------------------------------------^^^^^^^^^^^_x000D_
_x000D_
setTimeout(function(){ _x000D_
    var myCoolDiv = document.getElementById("MyCoolDiv");_x000D_
    document.getElementById("playerContainer").removeChild(myCoolDiv);_x000D_
}, 1500);
_x000D_
<div id="playerContainer"></div>
_x000D_
_x000D_
_x000D_

Or without using the wrapper (although it's quite handy for parsing that HTML):

_x000D_
_x000D_
var myCoolDiv = document.createElement("div");_x000D_
// Don't reall need this: myCoolDiv.id = "MyCoolDiv";_x000D_
myCoolDiv.style.color = "#2b0808";_x000D_
myCoolDiv.appendChild(_x000D_
  document.createTextNode("123")_x000D_
);_x000D_
document.getElementById("playerContainer").appendChild(myCoolDiv);_x000D_
_x000D_
setTimeout(function(){ _x000D_
    // No need for this, we already have it from the above:_x000D_
    // var myCoolDiv = document.getElementById("MyCoolDiv");_x000D_
    document.getElementById("playerContainer").removeChild(myCoolDiv);_x000D_
}, 1500);
_x000D_
<div id="playerContainer"></div>
_x000D_
_x000D_
_x000D_

Clicking a checkbox with ng-click does not update the model

The order in which ng-click and ng-model will be executed is ambiguous (since neither explicitly set their priority). The most stable solution to this would be to avoid using them on the same element.

Also, you probably do not want the behavior that the examples show; you want the checkbox to respond to clicks on the complete label text, not only the checkbox. Hence, the cleanest solution would be to wrap the input (with ng-model) inside a label (with ng-click):

<label ng-click="onCompleteTodo(todo)">
  <input type='checkbox' ng-model="todo.done">
  {{todo.text}}
</label>

Working example: http://jsfiddle.net/b3NLH/1/

ng-mouseover and leave to toggle item using mouse in angularjs

A little late here, but I've found this to be a common problem worth a custom directive to handle. Here's how that might look:

  .directive('toggleOnHover', function(){
    return {
      restrict: 'A',
      link: link
    };

    function link(scope, elem, attrs){
      elem.on('mouseenter', applyToggleExp);
      elem.on('mouseleave', applyToggleExp);

      function applyToggleExp(){
        scope.$apply(attrs.toggleOnHover);
      }
    }

  });

You can use it like this:

<li toggle-on-hover="editableProp = !editableProp">edit</li> 

Change a Rails application to production

rails s -e production

This will run the server with RAILS_ENV = 'production'.

Apart from this you have to set the assets path in production.rb

config.serve_static_assets = true

Without this your assets will not be loaded.

retrieve data from db and display it in table in php .. see this code whats wrong with it?

<html>
    <head>
        <meta charset="UTF-8">
        <title>LoginDB</title>
    </head>
    <body>

        <?php
        $con=  mysqli_connect("localhost", "root", "", "detail");
<!-- detail is the database in MySqli Database -->
        if(!$con)
       {
           die('not connected');
       }
            $con=  mysqli_query($con, "select * from signup");
<!-- signup is the table in the detail_Database -->
       ?>
        <div>
            <td>Login Page Database</td>
         <table border="1">
            <th> First Name</th>
                    <th>Last Name</th>
                    <th>UserName</th>
                     <th>Password</th>
                    <th>Gender</th>
                    <th>D.O.B.</th>
                    <th>Phone Number</th>
                    <th>Address</th>

            </tr>

        <?php

             while($row=  mysqli_fetch_array($con))
<!-- Fetch each row from signup Table  -->
             {
                 ?>
            <tr>
                <td><?php echo $row['FirstName']; ?></td>
                <td><?php echo $row['LastName']; ?></td>
                <td><?php echo $row['Username']; ?></td>
                <td><?php echo $row['Password'] ;?></td>
                <td><?php echo $row['Gender'] ;?></td>
                <td><?php echo $row['DOB'] ;?></td>
                <td><?php echo $row['PhoneNumber'] ;?></td>
                <td><?php echo $row['Address'] ;?></td>
            </tr>
        <?php
             }
             ?>
             </table>
            </div>
    </body>
</html>

Two HTML tables side by side, centered on the page

Off the top of my head, you might try using the "margin: 0 auto" for #outer rather than #inner.

I often add background-color to my DIVs to see how they're laying out on the view. That might be a good way to diagnose what's going onn here.

This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint

Go to the Design, right click on your Widget, Constraint Layout >> Infer Constraints. You can observe that some code has been automatically added to your Text.

What is the difference between dynamic and static polymorphism in Java?

method overloading is an example of compile time/static polymorphism because method binding between method call and method definition happens at compile time and it depends on the reference of the class (reference created at compile time and goes to stack).

method overriding is an example of run time/dynamic polymorphism because method binding between method call and method definition happens at run time and it depends on the object of the class (object created at runtime and goes to the heap).

Cannot connect to local SQL Server with Management Studio

I was having this problem on a Windows 7 (64 bit) after a power outage. The SQLEXPRESS service was not started even though is status was set to 'Automatic' and the mahine had been rebooted several times. Had to start the service manually.

How to show the last queries executed on MySQL?

You can look at the following in linux

cd /root

ls -al

vi .mysql_history It may help

Checking on a thread / remove from list

you need to call thread.isAlive()to find out if the thread is still running

ListBox vs. ListView - how to choose for data binding

A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.

If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).

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

I wonder why people are not highlighting the MOST compelling reason in favor of EFS. EFS can be mounted on more than one EC2 instance at the same time, enabling access to files on EFS at the same time.

(Edit 2020 May, EBS supports mounting to multiple EC2 at same time now as well, see: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volumes-multi.html)

text flowing out of div

use overflow:auto it will give a scroller to your text within the div :).

Is there a Google Chrome-only CSS hack?

Try to use the new '@supports' feature, here is one good hack that you might like:

* UPDATE!!! * Microsoft Edge and Safari 9 both added support for the @supports feature in Fall 2015, Firefox also -- so here is my updated version for you:

/* Chrome 29+ (Only) */

@supports (-webkit-appearance:none) and (not (overflow:-webkit-marquee))
and (not (-ms-ime-align:auto)) and (not (-moz-appearance:none)) { 
   .selector { color:red; } 
}

More info on this here (the reverse... Safari but not Chrome): [ is there a css hack for safari only NOT chrome? ]

The previous CSS Hack [before Edge and Safari 9 or newer Firefox versions]:

/* Chrome 28+ (now also Microsoft Edge, Firefox, and Safari 9+) */

@supports (-webkit-appearance:none) { .selector { color:red; } }

This worked for (only) chrome, version 28 and newer.

(The above chrome 28+ hack was not one of my creations. I found this on the web and since it was so good I sent it to BrowserHacks.com recently, there are others coming.)

August 17th, 2014 update: As I mentioned, I have been working on reaching more versions of chrome (and many other browsers), and here is one I crafted that handles chrome 35 and newer.

/* Chrome 35+ */

_::content, _:future, .selector:not(*:root) { color:red; }

In the comments below it was mentioned by @BoltClock about future, past, not... etc... We can in fact use them to go a little farther back in Chrome history.

So then this is one that also works but not 'Chrome-only' which is why I did not put it here. You still have to separate it by a Safari-only hack to complete the process. I have created css hacks to do this however, not to worry. Here are a few of them, starting with the simplest:

/* Chrome 26+, Safari 6.1+ */

_:past, .selector:not(*:root) { color:red; }

Or instead, this one which goes back to Chrome 22 and newer, but Safari as well...

/* Chrome 22+, Safari 6.1+ */

@media screen and (-webkit-min-device-pixel-ratio:0)
and (min-resolution:.001dpcm),
screen and(-webkit-min-device-pixel-ratio:0)
{
    .selector { color:red; } 
}

The block of Chrome versions 22-28 (more complicated but works nicely) are also possible to target via a combination I worked out:

/* Chrome 22-28 (Only!) */

@media screen and(-webkit-min-device-pixel-ratio:0)
{
    .selector  {-chrome-:only(;

       color:red; 

    );}
}

Now follow up with this next couple I also created that targets Safari 6.1+ (only) in order to still separate Chrome and Safari. Updated to include Safari 8

/* Safari 6.1-7.0 */

@media screen and (-webkit-min-device-pixel-ratio:0) and (min-color-index:0)
{
    .selector {(;  color:blue;  );} 
}


/* Safari 7.1+ */

_::-webkit-full-page-media, _:future, :root .selector { color:blue; } 

So if you put one of the Chrome+Safari hacks above, and then the Safari 6.1-7 and 8 hacks in your styles sequentially, you will have Chrome items in red, and Safari items in blue.

Flask SQLAlchemy query, specify column names

You can use load_only function:

from sqlalchemy.orm import load_only

fields = ['name', 'addr', 'phone', 'url']
companies = session.query(SomeModel).options(load_only(*fields)).all()

Difference between agile and iterative and incremental development

  • Iterative - you don't finish a feature in one go. You are in a code >> get feedback >> code >> ... cycle. You keep iterating till done.
  • Incremental - you build as much as you need right now. You don't over-engineer or add flexibility unless the need is proven. When the need arises, you build on top of whatever already exists. (Note: differs from iterative in that you're adding new things.. vs refining something).
  • Agile - you are agile if you value the same things as listed in the agile manifesto. It also means that there is no standard template or checklist or procedure to "do agile". It doesn't overspecify.. it just states that you can use whatever practices you need to "be agile". Scrum, XP, Kanban are some of the more prescriptive 'agile' methodologies because they share the same set of values. Continuous and early feedback, frequent releases/demos, evolve design, etc.. hence they can be iterative and incremental.

Returning binary file from controller in ASP.NET Web API

You can try the following code snippet

httpResponseMessage.Content.Headers.Add("Content-Type", "application/octet-stream");

Hope it will work for you.

Avoid web.config inheritance in child web application using inheritInChildApplications

As the commenters for the previous answer mentioned, you cannot simply add the line...

<location path="." inheritInChildApplications="false">

...just below <configuration>. Instead, you need to wrap the individual web.config sections for which you want to disable inheritance. For example:

<!-- disable inheritance for the connectionStrings section -->
<location path="." inheritInChildApplications="false">
   <connectionStrings>
   </connectionStrings>
</location>

<!-- leave inheritance enabled for appSettings -->
<appSettings>
</appSettings>

<!-- disable inheritance for the system.web section -->
<location path="." inheritInChildApplications="false">
   <system.web>
        <webParts>
        </webParts>
        <membership>
        </membership>

        <compilation>
        </compilation>
      </system.web>
 </location>

While <clear /> may work for some configuration sections, there are some that instead require a <remove name="..."> directive, and still others don't seem to support either. In these situations, it's probably appropriate to set inheritInChildApplications="false".

How do you reinstall an app's dependencies using npm?

Most of the time I use the following command to achieve a complete reinstall of all the node modules (be sure you are in the project folder).

rm -rf node_modules && npm install

You can also run npm cache clean after removing the node_modules folder to be sure there aren't any cached dependencies.

The endpoint reference (EPR) for the Operation not found is

Action is null means that no Action in given SOAP Message (Request XML). You must set Action before SOAP call:

java.net.URL endpoint = new URL("<URL>"); //sets URL

MimeHeaders headers = message.getMimeHeaders(); // getting MIME Header

headers.addHeader("SOAPAction", "<SOAP Action>"); //add Action To Header

SOAPMessage response = soapConnection.call(<SOAPMessage>, endpoint); //then Call

soapConnection.close(); // then Close the connection

Using Python, how can I access a shared folder on windows network?

Use forward slashes to specify the UNC Path:

open('//HOST/share/path/to/file')

(if your Python client code is also running under Windows)

How to detect Ctrl+V, Ctrl+C using JavaScript?

I just did this out of interest. I agree it's not the right thing to do, but I think it should be the op's decision... Also the code could easily be extended to add functionality, rather than take it away (like a more advanced clipboard, or Ctrl+s triggering a server-side save).

_x000D_
_x000D_
$(document).ready(function() {_x000D_
    var ctrlDown = false,_x000D_
        ctrlKey = 17,_x000D_
        cmdKey = 91,_x000D_
        vKey = 86,_x000D_
        cKey = 67;_x000D_
_x000D_
    $(document).keydown(function(e) {_x000D_
        if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = true;_x000D_
    }).keyup(function(e) {_x000D_
        if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = false;_x000D_
    });_x000D_
_x000D_
    $(".no-copy-paste").keydown(function(e) {_x000D_
        if (ctrlDown && (e.keyCode == vKey || e.keyCode == cKey)) return false;_x000D_
    });_x000D_
    _x000D_
    // Document Ctrl + C/V _x000D_
    $(document).keydown(function(e) {_x000D_
        if (ctrlDown && (e.keyCode == cKey)) console.log("Document catch Ctrl+C");_x000D_
        if (ctrlDown && (e.keyCode == vKey)) console.log("Document catch Ctrl+V");_x000D_
    });_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<h3>Ctrl+c Ctrl+v disabled</h3>_x000D_
<textarea class="no-copy-paste"></textarea>_x000D_
<br><br>_x000D_
<h3>Ctrl+c Ctrl+v allowed</h3>_x000D_
<textarea></textarea>
_x000D_
_x000D_
_x000D_

Also just to clarify, this script requires the jQuery library.

Codepen demo

EDIT: removed 3 redundant lines (involving e.which) thanks to Tim Down's suggestion (see comments)

EDIT: added support for Macs (cmd key instead of ctrl)

Finding height in Binary Search Tree

Height of Binary Tree

public static int height(Node root)
    {
        // Base case: empty tree has height 0
        if (root == null) {
            return 0;
        }

        // recursively for left and right subtree and consider maximum depth
        return 1 + Math.max(height(root.left), height(root.right));
    }

Show "Open File" Dialog

I have a similar solution to the above and it works for opening, saving, file selecting. I paste it into its own module and use in all the Access DB's I create. As the code states it requires Microsoft Office 14.0 Object Library. Just another option I suppose:

Public Function Select_File(InitPath, ActionType, FileType)
    ' Requires reference to Microsoft Office 14.0 Object Library.

    Dim fDialog As Office.FileDialog
    Dim varFile As Variant


    If ActionType = "FilePicker" Then
        Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
        ' Set up the File Dialog.
    End If
    If ActionType = "SaveAs" Then
        Set fDialog = Application.FileDialog(msoFileDialogSaveAs)
    End If
    If ActionType = "Open" Then
        Set fDialog = Application.FileDialog(msoFileDialogOpen)
    End If
    With fDialog
        .AllowMultiSelect = False
        ' Disallow user to make multiple selections in dialog box
        .Title = "Please specify the file to save/open..."
        ' Set the title of the dialog box.
        If ActionType <> "SaveAs" Then
            .Filters.Clear
            ' Clear out the current filters, and add our own.
            .Filters.Add FileType, "*." & FileType
        End If
        .InitialFileName = InitPath
        ' Show the dialog box. If the .Show method returns True, the
        ' user picked a file. If the .Show method returns
        ' False, the user clicked Cancel.
        If .Show = True Then
        'Loop through each file selected and add it to our list box.
            For Each varFile In .SelectedItems
                'return the subroutine value as the file path & name selected
                Select_File = varFile
            Next
        End If
    End With
End Function

Refresh Fragment at reload

I think you want to refresh the fragment contents upon db update

If so, detach the fragment and reattach it

// Reload current fragment
Fragment frg = null;
frg = getSupportFragmentManager().findFragmentByTag("Your_Fragment_TAG");
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();

Your_Fragment_TAG is the name you gave your fragment when you created it

This code is for support library.

If you're not supporting older devices, just use getFragmentManager instead of getSupportFragmentManager

[EDIT]

This method requires the Fragment to have a tag.
In case you don't have it, then @Hammer's method is what you need.

Can vue-router open a link in a new tab?

This works for me:

In HTML template: <a target="_blank" :href="url" @click.stop>your_name</a>

In mounted(): this.url = `${window.location.origin}/your_page_name`;

how to use Spring Boot profiles

If you are using maven, define your profiles as shown below within your pom.xml

<profiles>
<profile>
    <id>local</id>
    <activation>
        <activeByDefault>true</activeByDefault>
    </activation>
    <properties>
        <jdbc.url>dbUrl</jdbc.url>
        <jdbc.username>dbuser</jdbc.username>
        <jdbc.password>dbPassword</jdbc.password>
        <jdbc.driver>dbDriver</jdbc.driver>
    </properties>
</profile>
<profile>
    <id>dev</id>
    <properties>
        <jdbc.url>dbUrl</jdbc.url>
        <jdbc.username>dbuser</jdbc.username>
        <jdbc.password>dbPassword</jdbc.password>
        <jdbc.driver>dbDriver</jdbc.driver>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
        </dependency>
    </dependencies>
</profile>
<profile>
    <id>prod</id>
    <properties>
        <jdbc.url>dbUrl</jdbc.url>
        <jdbc.username>dbuser</jdbc.username>
        <jdbc.password>dbPassword</jdbc.password>
        <jdbc.driver>dbDriver</jdbc.driver>
    </properties>
</profile>

By default, i.e if No profile is selected, the local profile will always be use.

To select a specific profile in Spring Boot 2.x.x, use the below command.

mvn spring-boot:run -Dspring-boot.run.profiles=dev

If you want want to build/compile using properties of a specific profile, use the below command.

mvn clean install -Pdev -DprofileIdEnabled=true

How to make html table vertically scrollable

The best way to do this is strictly separate your table into two different tables - header and body:

<div class="header">
  <table><tr><!-- th here --></tr></table>
</div>

<div class="body">
  <table><tr><!-- td here --></tr></table>
</div>

.body {
  height: 100px;
  overflow: auto
}

If your table has a big width (more than screen width), then you have to add scroll events for horizontal scrolling header and body synchroniously.

You should never touch table tags (table, tbody, thead, tfoot, tr) with CSS properties display and overflow. Dealing with DIV wrappers is much more preferable.

How do I apply a CSS class to Html.ActionLink in ASP.NET MVC?

This works for MVC 5

@Html.ActionLink("LinkText", "ActionName", new { id = item.id }, new { @class = "btn btn-success" })

kubectl apply vs kubectl create?

When running in a CI script, you will have trouble with imperative commands as create raises an error if the resource already exists.

What you can do is applying (declarative pattern) the output of your imperative command, by using --dry-run=true and -o yaml options:

kubectl create whatever --dry-run=true -o yaml | kubectl apply -f -

The command above will not raise an error if the resource already exists (and will update the resource if needed).

This is very useful in some cases where you cannot use the declarative pattern (for instance when creating a docker-registry secret).

Android - How to download a file from a webserver

Download File Usind Download Manager

    DownloadManager downloadmanager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    Uri uri = Uri.parse("https://www.globalgreyebooks.com/content/books/ebooks/game-of-life.pdf");

    DownloadManager.Request request = new DownloadManager.Request(uri);
    request.setTitle("My File");
    request.setDescription("Downloading");//request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,"game-of-life");
    downloadmanager.enqueue(request);

How to include the reference of DocumentFormat.OpenXml.dll on Mono2.10?

You need to have DocumentFormat.OpenXML.dll in the same folder as your application - or in the 'bin' path if you are developing an ASP.NET application. However, I'm not certain that the OpenXML SDK is supported on non-Windows operating systems - you may need to look into a third-party solution.

Yes, this answer is right, the only difference is that you copy your .dll into bin folder of the project.

jQuery scroll() detect when user stops scrolling

I agreed with some of the comments above that listening for a timeout wasn't accurate enough as that will trigger when you stop moving the scroll bar for long enough instead of when you stop scrolling. I think a better solution is to listen for the user letting go of the mouse (mouseup) as soon as they start scrolling:

$(window).scroll(function(){
    $('#scrollMsg').html('SCROLLING!');
    var stopListener = $(window).mouseup(function(){ // listen to mouse up
        $('#scrollMsg').html('STOPPED SCROLLING!');
        stopListner(); // Stop listening to mouse up after heard for the first time 
    });
});

and an example of it working can be seen in this JSFiddle

How to center buttons in Twitter Bootstrap 3?

I tried the following code and it worked for me.

<button class="btn btn-default center-block" type="submit">Button</button>

The button control is in a div and using center-block class of bootstrap helped me to align the button to the center of div

Check the link where you will find the center-block class

http://getbootstrap.com/css/#helper-classes-center

How to hide image broken Icon using only CSS/HTML?

There is no way for CSS/HTML to know if the image is broken link, so you are going to have to use JavaScript no matter what

But here is a minimal method for either hiding the image, or replacing the source with a backup.

<img src="Error.src" onerror="this.style.display='none'"/>

or

<img src="Error.src" onerror="this.src='fallback-img.jpg'"/>

Update

You can apply this logic to multiple images at once by doing something like this:

_x000D_
_x000D_
document.addEventListener("DOMContentLoaded", function(event) {_x000D_
   document.querySelectorAll('img').forEach(function(img){_x000D_
   img.onerror = function(){this.style.display='none';};_x000D_
   })_x000D_
});
_x000D_
<img src="error.src">_x000D_
<img src="error.src">_x000D_
<img src="error.src">_x000D_
<img src="error.src">
_x000D_
_x000D_
_x000D_

Update 2

For a CSS option see michalzuber's answer below. You can't hide the entire image, but you change how the broken icon looks.

How to change the color of an image on hover

If the icon is from Font Awesome (https://fontawesome.com/icons/) then you could tap into the color css property to change it's background.

fb-icon{
color:none;
}

fb-icon:hover{
color:#0000ff;
}

This is irrespective of the color it had. So you could use an entirely different color in its usual state and define another in its active state.

Regarding 'main(int argc, char *argv[])'

The comp.lang.c FAQ deals with the question

"What's the correct declaration of main()?"
in Question 11.12a.

Time complexity of Euclid's Algorithm

There's a great look at this on the wikipedia article.

It even has a nice plot of complexity for value pairs.

It is not O(a%b).

It is known (see article) that it will never take more steps than five times the number of digits in the smaller number. So the max number of steps grows as the number of digits (ln b). The cost of each step also grows as the number of digits, so the complexity is bound by O(ln^2 b) where b is the smaller number. That's an upper limit, and the actual time is usually less.

Best way to get all selected checkboxes VALUES in jQuery

You want the :checkbox:checked selector and map to create an array of the values:

var checkedValues = $('input:checkbox:checked').map(function() {
    return this.value;
}).get();

If your checkboxes have a shared class it would be faster to use that instead, eg. $('.mycheckboxes:checked'), or for a common name $('input[name="Foo"]:checked')

- Update -

If you don't need IE support then you can now make the map() call more succinct by using an arrow function:

var checkedValues = $('input:checkbox:checked').map((i, el) => el.value).get();

Converting an int to a binary string representation in Java?

The simplest approach is to check whether or not the number is odd. If it is, by definition, its right-most binary number will be "1" (2^0). After we've determined this, we bit shift the number to the right and check the same value using recursion.

@Test
public void shouldPrintBinary() {
    StringBuilder sb = new StringBuilder();
    convert(1234, sb);
}

private void convert(int n, StringBuilder sb) {

    if (n > 0) {
        sb.append(n % 2);
        convert(n >> 1, sb);
    } else {
        System.out.println(sb.reverse().toString());
    }
}

Creating a new directory in C

You can use mkdir:

$ man 2 mkdir

#include <sys/stat.h>
#include <sys/types.h>

int result = mkdir("/home/me/test.txt", 0777);

Bootstrap trying to load map file. How to disable it? Do I need to do it?

This only happens when you use the dev-tools, and won't happen for normal users accessing the production server.

In any case, I found it useful to simply disable this behavior in the dev-tools: open the settings and uncheck the "Enable source maps" option.

There will no longer be an attempt to access map files.

How to convert an address to a latitude/longitude?

Nothing much new to add, but I have had a lot of real-world experience in GIS and geocoding from a previous job. Here is what I remember:

If it is a "every once in a while" need in your application, I would definitely recommend the Google or Yahoo Geocoding APIs, but be careful to read their licensing terms.

I know that the Google Maps API in general is easy to license for even commercial web pages, but can't be used in a pay-to-access situation. In other words you can use it to advertise or provide a service that drives ad revenue, but you can't charge people to acess your site or even put it behind a password system.

Despite these restrictions, they are both excellent choices because they frequently update their street databases. Most of the free backend tools and libraries use Census and TIGER road data that is updated infrequently, so you are less likely to successfully geocode addresses in rapidly growing areas or new subdivisions.

Most of the services also restrict the number of geocoding queries you can make per day, so it's OK to look up addresses of, say, new customers who get added to your database, but if you run a batch job that feeds thousands of addresses from your database into the geocoder, you're going to get shutoff.

I don't think this one has been mentioned yet, but ESRI has ArcWeb web services that include geocoding, although they aren't very cheap. Last time I used them it cost around 1.5cents per lookup, but you had to prepay a certain amount to get started. Again the major advantage is that the road data they use is kept up to date in a timely manner and you can use the data in commercial situations that Google doesn't allow. The ArcWeb service will also serve up high-resolution satellite and aerial photos a la Google Maps, again priced per request.

If you want to roll your own or have access to much more accurate data, you can purchase subscriptions to GIS data from companies like TeleAtlas, but that ain't cheap. You can buy only a state or county worth of data if your needs are extremely local. There are several tiers of data - GIS features only, GIS plus detailed streets, all that plus geocode data, all of that plus traffic flow/direction/speed limits for routing. Of course, the price goes up as you go up the tiers.

Finally, the Wikipedia article on Geocoding has some good information on the algorithms and techniques. Even if you aren't doing it in your own code, it's useful to know what kind of errors and accuracy you can expect from various kinds of data sources.

How to set the color of an icon in Angular Material?

Or simply

add to your element

[ngStyle]="{'color': myVariableColor}"

eg

<mat-icon [ngStyle]="{'color': myVariableColor}">{{ getActivityIcon() }}</mat-icon>

Where color can be defined at another component etc

typeof operator in C

It's not exactly an operator, rather a keyword. And no, it doesn't do any runtime-magic.

jQuery UI dialog positioning

You ca set top position in style for display on center, saw that the code:

.ui-dialog{top: 100px !important;}

This style should show dialog box 100px bellow from top.

Difference between $(window).load() and $(document).ready() functions

I think the $(window).load event is not supported by JQuery 3.x

How to access session variables from any class in ASP.NET?

I had the same error, because I was trying to manipulate session variables inside a custom Session class.

I had to pass the current context (system.web.httpcontext.current) into the class, and then everything worked out fine.

MA

How to use multiple LEFT JOINs in SQL?

Yes it is possible. You need one ON for each join table.

LEFT JOIN ab
  ON ab.sht = cd.sht
LEFT JOIN aa
  ON aa.sht = cd.sht

Incidentally my personal formatting preference for complex SQL is described in http://bentilly.blogspot.com/2011/02/sql-formatting-style.html. If you're going to be writing a lot of this, it likely will help.

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

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

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

int main(void)

and

int main(int argc, char **argv)

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

Finding the position of bottom of a div with jquery

Add the outerheight to the top and you have the bottom, relative to the parent element:

var $el = $('#bottom');  //record the elem so you don't crawl the DOM everytime  
var bottom = $el.position().top + $el.outerHeight(true); // passing "true" will also include the top and bottom margin

With absolutely positioned elements or when positioning relative to the document, you will need to instead evaluate using offset:

var bottom = $el.offset().top + $el.outerHeight(true);

As pointed out by trnelson this does not work 100% of the time. To use this method for positioned elements, you also must account for offset. For an example see the following code.

var bottom = $el.position().top + $el.offset().top + $el.outerHeight(true);

String vs. StringBuilder

Yes, StringBuilder gives better performance while performing repeated operation over a string. It is because all the changes are made to a single instance so it can save a lot of time instead of creating a new instance like String.

String Vs Stringbuilder

  • String

    1. under System namespace
    2. immutable (read-only) instance
    3. performance degrades when continuous change of value occures
    4. thread safe
  • StringBuilder (mutable string)

    1. under System.Text namespace
    2. mutable instance
    3. shows better performance since new changes are made to existing instance

Strongly recommend dotnet mob article : String Vs StringBuilder in C#.

Related Stack Overflow question: Mutability of string when string doesn't change in C#?.

python pip - install from local dir

You were looking for help on installations with pip. You can find it with the following command:

pip install --help

Running pip install -e /path/to/package installs the package in a way, that you can edit the package, and when a new import call looks for it, it will import the edited package code. This can be very useful for package development.

How to get Toolbar from fragment?

if you are using custom toolbar or ActionBar and you want to get reference of your toolbar/action bar from Fragments then you need to first get instance of your Main Activity from Fragment's onCreateView Method like below.

MainActivity activity = (MainActivity) getActivity();

then use activity for further implementation like below

ImageView vRightBtn = activity.toolbar.findViewById(R.id.toolbar_right_btn);

Before calling this, you need to initialize your custom toolbar in your MainActivity as below.

First set define your toolbar public like

public Toolbar toolbar;
public ActionBar actionBar;

and in onCreate() Method assign the custom toolbar id

toolbar = findViewById(R.id.custom_toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();

That's It. It will work in Fragment.

Is there a shortcut to make a block comment in Xcode?

There is a symbol before help menu on xcode which has Edit user script. On Un/Comment Selection under comments section change my $cCmt = "//"; to my $cCmt = "#"; or whatever your IDE works with. Then by selecting lines and command + / (It's my xcode default) you can comment and uncomment the selected lines.

How to convert a string to an integer in JavaScript?

Try parseInt.

var number = parseInt("10", 10); //number will have value of 10.

Regex - how to match everything except a particular pattern

My answer here might solve your problem as well:

https://stackoverflow.com/a/27967674/543814

  • Instead of Replace, you would use Match.
  • Instead of group $1, you would read group $2.
  • Group $2 was made non-capturing there, which you would avoid.

Example:

Regex.Match("50% of 50% is 25%", "(\d+\%)|(.+?)");

The first capturing group specifies the pattern that you wish to avoid. The last capturing group captures everything else. Simply read out that group, $2.

Load a HTML page within another HTML page

Why don't you use

_x000D_
_x000D_
function jsredir() {_x000D_
  window.location.href = "https://stackoverflow.com";_x000D_
}
_x000D_
<button onclick="jsredir()">Click Me!</button>
_x000D_
_x000D_
_x000D_

iOS 7 status bar overlapping UI

Place this code snippet in your MainViewController.m file in the phonegap project.

- (void)viewDidLayoutSubviews{

    if ([self respondsToSelector:@selector(topLayoutGuide)]) // iOS 7 or above
    {
        CGFloat top = self.topLayoutGuide.length;
        if(self.webView.frame.origin.y == 0){
            // We only want to do this once, or 
            // if the view has somehow been "restored" by other    code.
            self.webView.frame = CGRectMake(self.webView.frame.origin.x,
                                           self.webView.frame.origin.y + top,
                                           self.webView.frame.size.width,
                                           self.webView.frame.size.height-top);
        } 
    } 
}

JSONObject - How to get a value?

If it's a deeper key/value you're after and you're not dealing with arrays of keys/values at each level, you could recursively search the tree:

public static String recurseKeys(JSONObject jObj, String findKey) throws JSONException {
    String finalValue = "";
    if (jObj == null) {
        return "";
    }

    Iterator<String> keyItr = jObj.keys();
    Map<String, String> map = new HashMap<>();

    while(keyItr.hasNext()) {
        String key = keyItr.next();
        map.put(key, jObj.getString(key));
    }

    for (Map.Entry<String, String> e : (map).entrySet()) {
        String key = e.getKey();
        if (key.equalsIgnoreCase(findKey)) {
            return jObj.getString(key);
        }

        // read value
        Object value = jObj.get(key);

        if (value instanceof JSONObject) {
            finalValue = recurseKeys((JSONObject)value, findKey);
        }
    }

    // key is not found
    return finalValue;
}

Usage:

JSONObject jObj = new JSONObject(jsonString);
String extract = recurseKeys(jObj, "extract");

Using Map code from https://stackoverflow.com/a/4149555/2301224

Server.Mappath in C# classlibrary

Use this System.Web.Hosting.HostingEnvironment.MapPath().

HostingEnvironment.MapPath("~/file")

Wonder why nobody mentioned it here.

Is there a C# String.Format() equivalent in JavaScript?

Based on @Vlad Bezden answer I use this slightly modified code because I prefer named placeholders:

String.prototype.format = function(placeholders) {
    var s = this;
    for(var propertyName in placeholders) {
        var re = new RegExp('{' + propertyName + '}', 'gm');
        s = s.replace(re, placeholders[propertyName]);
    }    
    return s;
};

usage:

"{greeting} {who}!".format({greeting: "Hello", who: "world"})

_x000D_
_x000D_
String.prototype.format = function(placeholders) {_x000D_
    var s = this;_x000D_
    for(var propertyName in placeholders) {_x000D_
        var re = new RegExp('{' + propertyName + '}', 'gm');_x000D_
        s = s.replace(re, placeholders[propertyName]);_x000D_
    }    _x000D_
    return s;_x000D_
};_x000D_
_x000D_
$("#result").text("{greeting} {who}!".format({greeting: "Hello", who: "world"}));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

How to completely uninstall kubernetes

The guide you linked now has a Tear Down section:

Talking to the master with the appropriate credentials, run:

kubectl drain <node name> --delete-local-data --force --ignore-daemonsets
kubectl delete node <node name>

Then, on the node being removed, reset all kubeadm installed state:

kubeadm reset

Creating CSS Global Variables : Stylesheet theme management

I do it this way:

The html:

<head>
    <style type="text/css"> <? require_once('xCss.php'); ?> </style>
</head>

The xCss.php:

<? // place here your vars
$fntBtn = 'bold 14px  Arial'
$colBorder  = '#556677' ;
$colBG0     = '#dddddd' ;
$colBG1     = '#44dddd' ;
$colBtn     = '#aadddd' ;

// here goes your css after the php-close tag: 
?>
button { border: solid 1px <?= $colBorder; ?>; border-radius:4px; font: <?= $fntBtn; ?>; background-color:<?= $colBtn; ?>; } 

How do you add a scroll bar to a div?

to add scroll u need to define max-height of your div and then add overflow-y

so do something like this

.my_scroll_div{
    overflow-y: auto;
    max-height: 100px;
}

How to Validate on Max File Size in Laravel?

Edit: Warning! This answer worked on my XAMPP OsX environment, but when I deployed it to AWS EC2 it did NOT prevent the upload attempt.

I was tempted to delete this answer as it is WRONG But instead I will explain what tripped me up

My file upload field is named 'upload' so I was getting "The upload failed to upload.". This message comes from this line in validation.php:

in resources/lang/en/validaton.php:

'uploaded' => 'The :attribute failed to upload.',

And this is the message displayed when the file is larger than the limit set by PHP.

I want to over-ride this message, which you normally can do by passing a third parameter $messages array to Validator::make() method.

However I can't do that as I am calling the POST from a React Component, which renders the form containing the csrf field and the upload field.

So instead, as a super-dodgy-hack, I chose to get into my view that displays the messages and replace that specific message with my friendly 'file too large' message.

Here is what works if the file to smaller than the PHP file size limit:

In case anyone else is using Laravel FormRequest class, here is what worked for me on Laravel 5.7:

This is how I set a custom error message and maximum file size:

I have an input field <input type="file" name="upload">. Note the CSRF token is required also in the form (google laravel csrf_field for what this means).

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class Upload extends FormRequest
{
  ...
  ...
  public function rules() {
    return [
      'upload' => 'required|file|max:8192',
    ];
  }
  public function messages()
  {
    return [            
      'upload.required' => "You must use the 'Choose file' button to select which file you wish to upload",
      'upload.max' => "Maximum file size to upload is 8MB (8192 KB). If you are uploading a photo, try to reduce its resolution to make it under 8MB"
    ];
  }
}

Change Select List Option background colour on hover

Select / Option elements are rendered by the OS, not HTML. You cannot change the style for these elements.

iOS 8 UITableView separator inset 0 not working

Use below code snippet avoid unwanted padding issue for UITableView in IOS 8 & 7.

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{

    if ([tableView respondsToSelector:@selector(setSeparatorInset:)])
    {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }

    if ([tableView respondsToSelector:@selector(setLayoutMargins:)])
    {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }

    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

Run javascript script (.js file) in mongodb including another file inside js

To call external file you can use :

load ("path\file")

Exemple: if your file.js file is on your "Documents" file (on windows OS), you can type:

load ("C:\users\user_name\Documents\file.js")

Vue.js dynamic images not working

Here is a shorthand that webpack will use so you don't have to use require.context.

HTML:

<div class="col-lg-2" v-for="pic in pics">
    <img :src="getImgUrl(pic)" v-bind:alt="pic">
</div>

Vue Method:

getImgUrl(pic) {
    return require('../assets/'+pic)
}

And I find that the first 2 paragraphs in here explain why this works? well.

Please note that it's a good idea to put your pet pictures inside a subdirectory, instead of lobbing it in with all your other image assets. Like so: ./assets/pets/

MYSQL Truncated incorrect DOUBLE value

It seems mysql handles the type casting gracefully with SELECT statements. The shop_id field is of type varchar but the select statements works

select * from shops where shop_id = 26244317283;

But when you try updating the fields

update stores set store_url = 'https://test-url.com' where shop_id = 26244317283;

It fails with error Truncated incorrect DOUBLE value: '1t5hxq9'

You need to put the shop_id 26244317283 in quotes '26244317283' for the query to work since the field is of type varchar not int

update stores set store_url = 'https://test-url.com' where shop_id = '26244317283';

Reload content in modal (twitter bootstrap)

It will works for all version of twitterbootstrap

Javascript code :

<script type="text/javascript">
/* <![CDATA[ */
(function(){
   var bsModal = null;
   $("[data-toggle=modal]").click(function(e) {
      e.preventDefault();
      var trgId = $(this).attr('data-target'); 
      if ( bsModal == null ) 
       bsModal = $(trgId).modal;
      $.fn.bsModal = bsModal;
      $(trgId + " .modal-body").load($(this).attr("href"));
      $(trgId).bsModal('show');
    });
 })();
/* <![CDATA[ */
</script>

links to modal are

<a data-toggle="modal" data-target="#myModal" href="edit1.aspx">Open modal 1</a>
<a data-toggle="modal" data-target="#myModal" href="edit2.aspx">Open modal 2</a>
<a data-toggle="modal" data-target="#myModal" href="edit3.aspx">Open modal 3</a>

pop up modal

<div id="myModal" class="modal hide fade in">
<div class="modal-header">
    <a class="close" data-dismiss="modal">×</a>
    <h3>Header</h3>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
    <input type="submit" class="btn btn-success" value="Save"/>
</div>

How can I loop through a List<T> and grab each item?

Just like any other collection. With the addition of the List<T>.ForEach method.

foreach (var item in myMoney)
    Console.WriteLine("amount is {0}, and type is {1}", item.amount, item.type);

for (int i = 0; i < myMoney.Count; i++)
    Console.WriteLine("amount is {0}, and type is {1}", myMoney[i].amount, myMoney[i].type);

myMoney.ForEach(item => Console.WriteLine("amount is {0}, and type is {1}", item.amount, item.type));

What does !important mean in CSS?

It changes the rules for override priority of css cascades. See the CSS2 spec.

Enable binary mode while restoring a Database from an SQL dump

I meet the same problem in windows restoring a dump file. My dump file was created with windows powershell and mysqldump like:

mysqldump db > dump.sql

The problem comes from the default encoding of powershell is UTF16. To look deeper into this, we can use "file" utility of GNU, and there exists a windows version here.
The output of my dump file is:

Little-endian UTF-16 Unicode text, with very long lines, with CRLF line terminators.

Then a conversion of coding system is needed, and there are various software can do this. For example in emacs,

M-x set-buffer-file-coding-system

then input required coding system such as utf-8.

And in the future, for a better mysqldump result, use:

mysqldump <dbname> -r <filename>

and then the output is handled by mysqldump itself but not redirection of powershell.

reference: https://dba.stackexchange.com/questions/44721/error-while-restoring-a-database-from-an-sql-dump

Text in Border CSS HTML

You can use a fieldset tag.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<form>_x000D_
 <fieldset>_x000D_
  <legend>Personalia:</legend>_x000D_
  Name: <input type="text"><br>_x000D_
  Email: <input type="text"><br>_x000D_
  Date of birth: <input type="text">_x000D_
 </fieldset>_x000D_
</form>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Check this link: HTML Tag

How to grep a string in a directory and all its subdirectories?

If your grep supports -R, do:

grep -R 'string' dir/

If not, then use find:

find dir/ -type f -exec grep -H 'string' {} +

How can I make a CSS glass/blur effect work for an overlay?

For a more simple and up to date answer:

backdrop-filter: blur(6px);

Note browser support is not perfect but in most cases a blur would be non essential.

How can I load storyboard programmatically from class?

You can always jump right to the root controller:

UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UIViewController *vc = [storyboard instantiateInitialViewController];
vc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:vc animated:YES completion:NULL];

How to make a back-to-top button using CSS and HTML only?

This is the HTML only way:

<body>
<a name="top"></a>
foo content
foo bottom of page
<a href="#top">Back to Top</a>
</body>

There are quite a few other alternatives using jquery and jscript though which offer additional effects. It really just depends on what you are looking for.

How to update a record using sequelize for node?

If Model.update statement does not work for you, you can try like this:

try{ 
    await sequelize.query('update posts set param=:param where conditionparam=:conditionparam', {replacements: {param: 'parameter', conditionparam:'condition'}, type: QueryTypes.UPDATE})
}
catch(err){
    console.log(err)
}

Simple regular expression for a decimal with a precision of 2

To include an optional minus sign and to disallow numbers like 015 (which can be mistaken for octal numbers) write:

-?(0|([1-9]\d*))(\.\d+)?

How to convert a full date to a short date in javascript?

Here you go:

(new Date()).toLocaleDateString('en-US');

That's it !!

you can use it on any date object

let's say.. you have an object called "currentDate"

var currentDate = new Date(); //use your date here
currentDate.toLocaleDateString('en-US'); // "en-US" gives date in US Format - mm/dd/yy

(or)

If you want it in local format then

currentDate.toLocaleDateString(); // gives date in local Format

vertical-align image in div

If you have a fixed height in your container, you can set line-height to be the same as height, and it will center vertically. Then just add text-align to center horizontally.

Here's an example: http://jsfiddle.net/Cthulhu/QHEnL/1/

EDIT

Your code should look like this:

.img_thumb {
    float: left;
    height: 120px;
    margin-bottom: 5px;
    margin-left: 9px;
    position: relative;
    width: 147px;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 3px;
    line-height:120px;
    text-align:center;
}

.img_thumb img {
    vertical-align: middle;
}

The images will always be centered horizontally and vertically, no matter what their size is. Here's 2 more examples with images with different dimensions:

http://jsfiddle.net/Cthulhu/QHEnL/6/

http://jsfiddle.net/Cthulhu/QHEnL/7/

UPDATE

It's now 2016 (the future!) and looks like a few things are changing (finally!!).

Back in 2014, Microsoft announced that it will stop supporting IE8 in all versions of Windows and will encourage all users to update to IE11 or Edge. Well, this is supposed to happen next Tuesday (12th January).

Why does this matter? With the announced death of IE8, we can finally start using CSS3 magic.

With that being said, here's an updated way of aligning elements, both horizontally and vertically:

.container {
    position: relative;
}

.container .element {
   position: absolute;
   left: 50%;
   top: 50%;
   transform: translate(-50%, -50%);
}

Using this transform: translate(); method, you don't even need to have a fixed height in your container, it's fully dynamic. Your element has fixed height or width? Your container as well? No? It doesn't matter, it will always be centered because all centering properties are fixed on the child, it's independent from the parent. Thank you CSS3.

If you only need to center in one dimension, you can use translateY or translateX. Just try it for a while and you'll see how it works. Also, try to change the values of the translate, you will find it useful for a bunch of different situations.

Here, have a new fiddle: https://jsfiddle.net/Cthulhu/1xjbhsr4/

For more information on transform, here's a good resource.

Happy coding.

How to invoke function from external .c file in C?

use #include "ClasseAusiliaria.c" [Dont use angle brackets (< >) ]

and I prefer save file with .h extension in the same Directory/folder.

#include "ClasseAusiliaria.h"

Authentication plugin 'caching_sha2_password' is not supported

pip install -U mysql-connector-python this worked for me, if you already have installed mysql-connector-python and then follow https://stackoverflow.com/a/50557297/6202853 this answer

scrollIntoView Scrolls just too far

I add this css tips for those who not resolved this issue with solutions above :

#myDiv::before {
  display: block;
  content: " ";
  margin-top: -90px; // adjust this with your header height
  height: 90px; // adjust this with your header height
  visibility: hidden;
}

How to create EditText with rounded corners?

Here is the same solution (with some extra bonus code) in just one XML file:

<?xml version="1.0" encoding="utf-8"?>
<!--  res/drawable/edittext_rounded_corners.xml -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true" android:state_focused="true">
    <shape>
        <solid android:color="#FF8000"/>
        <stroke
            android:width="2.3dp"
            android:color="#FF8000" />
         <corners
            android:radius="15dp" />
    </shape>
</item>

<item android:state_pressed="true" android:state_focused="false">
    <shape>
        <solid android:color="#FF8000"/>
        <stroke
            android:width="2.3dp"
            android:color="#FF8000" />      
        <corners
            android:radius="15dp" />       
    </shape>
</item>

<item android:state_pressed="false" android:state_focused="true">
    <shape>
        <solid android:color="#FFFFFF"/>
        <stroke
            android:width="2.3dp"
            android:color="#FF8000" />  
        <corners
            android:radius="15dp" />                          
    </shape>
</item>

<item android:state_pressed="false" android:state_focused="false">
    <shape>
        <gradient 
            android:startColor="#F2F2F2"
            android:centerColor="#FFFFFF"
            android:endColor="#FFFFFF"
            android:angle="270"
        />
        <stroke
            android:width="0.7dp"                
            android:color="#BDBDBD" /> 
        <corners
            android:radius="15dp" />            
    </shape>
</item>

<item android:state_enabled="true">
    <shape>
        <padding 
                android:left="4dp"
                android:top="4dp"
                android:right="4dp"
                android:bottom="4dp"
            />
    </shape>
</item>

</selector>

You then just set the background attribute to edittext_rounded_corners.xml file:

<EditText  android:id="@+id/editText_name"
      android:background="@drawable/edittext_rounded_corners"/>

m2e error in MavenArchiver.getManifest()

I solved this error in pom.xml by adding the below code

spring-rest-demo org.apache.maven.plugins maven-war-plugin 2.6

error C2039: 'string' : is not a member of 'std', header file problem

You need to have

#include <string>

in the header file too.The forward declaration on it's own doesn't do enough.

Also strongly consider header guards for your header files to avoid possible future problems as your project grows. So at the top do something like:

#ifndef THE_FILE_NAME_H
#define THE_FILE_NAME_H

/* header goes in here */

#endif

This will prevent the header file from being #included multiple times, if you don't have such a guard then you can have issues with multiple declarations.

How to add property to a class dynamically?

For those coming from search engines, here are the two things I was looking for when talking about dynamic properties:

class Foo:
    def __init__(self):
        # we can dynamically have access to the properties dict using __dict__
        self.__dict__['foo'] = 'bar'

assert Foo().foo == 'bar'


# or we can use __getattr__ and __setattr__ to execute code on set/get
class Bar:
    def __init__(self):
        self._data = {}
    def __getattr__(self, key):
        return self._data[key]
    def __setattr__(self, key, value):
        self._data[key] = value

bar = Bar()
bar.foo = 'bar'
assert bar.foo == 'bar'

__dict__ is good if you want to put dynamically created properties. __getattr__ is good to only do something when the value is needed, like query a database. The set/get combo is good to simplify the access to data stored in the class (like in the example above).

If you only want one dynamic property, have a look at the property() built-in function.

Disable Pinch Zoom on Mobile Web

Not sure is this could help, but I solved the pinch / zoom problem (I wanted to avoid users to do zooming on my webapp) using angular hammer module:

In my app.component.html I added:

<div id="app" (pinchin)="pinchin();">

and in my app.component.ts:

  pinchin() {
      //console.log('pinch in');
  }

How do I parse JSON from a Java HTTPResponse?

There is no need to do the reader loop yourself. The JsonTokener has this built in. E.g.

ttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new    
JSONTokener tokener = new JSONTokener(reader);
JSONArray finalResult = new JSONArray(tokener);

How is a non-breaking space represented in a JavaScript string?

That entity is converted to the char it represents when the browser renders the page. JS (jQuery) reads the rendered page, thus it will not encounter such a text sequence. The only way it could encounter such a thing is if you're double encoding entities.

How to use concerns in Rails 4

This post helped me understand concerns.

# app/models/trader.rb
class Trader
  include Shared::Schedule
end

# app/models/concerns/shared/schedule.rb
module Shared::Schedule
  extend ActiveSupport::Concern
  ...
end

Adding an external directory to Tomcat classpath

I might be a bit late for the party but I follow below steps to make it fully configurable using IntelliJ's way of in-IDE app test. I believe the best way to go with is to Combine below with @BelusC's answer.

1. run the application using IDE's tomcat run config. 
2. ps -ef | grep -i tomcat //this will give you a good idea about what the ide doing actually.
3. Copy the -Dcatalina.base parameter value from the command. this is your application specific catalina base. In this folder you can play with catalina.properties, application root path etc.. basically everything you have been doing is doable here too. 

Best JavaScript compressor

bananascript.com used to give me best results.

How to get list of dates between two dates in mysql select query

Try:

select * from 
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'

-for date ranges up to nearly 300 years in the future.

[Corrected following a suggested edit by UrvishAtSynapse.]

Save classifier to disk in scikit-learn

In many cases, particularly with text classification it is not enough just to store the classifier but you'll need to store the vectorizer as well so that you can vectorize your input in future.

import pickle
with open('model.pkl', 'wb') as fout:
  pickle.dump((vectorizer, clf), fout)

future use case:

with open('model.pkl', 'rb') as fin:
  vectorizer, clf = pickle.load(fin)

X_new = vectorizer.transform(new_samples)
X_new_preds = clf.predict(X_new)

Before dumping the vectorizer, one can delete the stop_words_ property of vectorizer by:

vectorizer.stop_words_ = None

to make dumping more efficient. Also if your classifier parameters is sparse (as in most text classification examples) you can convert the parameters from dense to sparse which will make a huge difference in terms of memory consumption, loading and dumping. Sparsify the model by:

clf.sparsify()

Which will automatically work for SGDClassifier but in case you know your model is sparse (lots of zeros in clf.coef_) then you can manually convert clf.coef_ into a csr scipy sparse matrix by:

clf.coef_ = scipy.sparse.csr_matrix(clf.coef_)

and then you can store it more efficiently.

Adding values to specific DataTable cells

You mean you want to add a new row and only put data in a certain column? Try the following:

var row = dataTable.NewRow();
row[myColumn].Value = "my new value";
dataTable.Add(row);

As it is a data table, though, there will always be data of some kind in every column. It just might be DBNull.Value instead of whatever data type you imagine it would be.

How can I write output from a unit test?

Solved with the following example:

public void CheckConsoleOutput()
{
    Console.WriteLine("Hello, World!");
    Trace.WriteLine("Trace Trace the World");
    Debug.WriteLine("Debug Debug World");
    Assert.IsTrue(true);
}

After running this test, under 'Test Passed', there is the option to view the output, which will bring up the output window.

How can I alias a default import in JavaScript?

defaultMember already is an alias - it doesn't need to be the name of the exported function/thing. Just do

import alias from 'my-module';

Alternatively you can do

import {default as alias} from 'my-module';

but that's rather esoteric.

Programmatically get height of navigation bar

Did you try this?

let barHeight = self.navigationController?.navigationBar.frame.height ?? 0

Mysql Compare two datetime fields

You can use the following SQL to compare both date and time -

Select * From temp where mydate > STR_TO_DATE('2009-06-29 04:00:44', '%Y-%m-%d %H:%i:%s');

Attached mysql output when I used same SQL on same kind of table and field that you mentioned in the problem-

enter image description here

It should work perfect.

phpMyAdmin - Error > Incorrect format parameter?

Without any problems, I imported directly from the command line.

mysql -uroot -hURLServer -p DBName< filename.sql

Escape invalid XML characters in C#

Here is an optimized version of the above method RemoveInvalidXmlChars which doesn't create a new array on every call, thus stressing the GC unnecessarily:

public static string RemoveInvalidXmlChars(string text)
{
    if (text == null)
        return text;
    if (text.Length == 0)
        return text;

    // a bit complicated, but avoids memory usage if not necessary
    StringBuilder result = null;
    for (int i = 0; i < text.Length; i++)
    {
        var ch = text[i];
        if (XmlConvert.IsXmlChar(ch))
        {
            result?.Append(ch);
        }
        else if (result == null)
        {
            result = new StringBuilder();
            result.Append(text.Substring(0, i));
        }
    }

    if (result == null)
        return text; // no invalid xml chars detected - return original text
    else
        return result.ToString();

}

Remove a CLASS for all child elements

You can also do like this :

  $("#table-filters li").parent().find('li').removeClass("active");

Print a variable in hexadecimal in Python

A way that will fail if your input string isn't valid pairs of hex characters...:

>>> import binascii
>>> ' '.join(hex(ord(i)) for i in binascii.unhexlify('deadbeef'))
'0xde 0xad 0xbe 0xef'

Android Studio update -Error:Could not run build action using Gradle distribution

I forced to use a proxy and also forced to add proxy setting on gradle.properties as these:

systemProp.http.proxyHost=127.0.0.1
systemProp.http.proxyPort=1080
systemProp.https.proxyHost=127.0.0.1
systemProp.https.proxyPort=1080

And also forced to close and open studio64.exe as administrator . Now its all seems greate

Event log says

8:21:39 AM Platform and Plugin Updates: The following components are ready to update: Android Support Repository, Google Repository, Intel x86 Emulator Accelerator (HAXM installer), Android SDK Platform-Tools 24, Google APIs Intel x86 Atom System Image, Android SDK Tools 25.1.7
8:21:40 AM Gradle sync started
8:22:03 AM Gradle sync completed
8:22:04 AM Executing tasks: [:app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:prepareDebugUnitTestDependencies, :app:mockableAndroidJar]
8:22:25 AM Gradle build finished in 21s 607ms

I'm using android studio 2.1.2 downloaded as exe setup file. it has its Gradle ( I also forced to use custom install to address the Gradle )

How to refresh activity after changing language (Locale) inside application

You can use recreate(); to restart your activity when Language change.

I am using following code to restart activity when language change:

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
Configuration config = getBaseContext().getResources().getConfiguration();

String lang = settings.getString("lang_list", "");

if (! "".equals(lang) && ! config.locale.getLanguage().equals(lang)) {
      recreate();  //this is used for recreate activity
      Locale locale = new Locale(lang);
      Locale.setDefault(locale);
      config.locale = locale;
      getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
}

Return 0 if field is null in MySQL

Use IFNULL:

IFNULL(expr1, 0)

From the documentation:

If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns expr2. IFNULL() returns a numeric or string value, depending on the context in which it is used.

jQuery: how to scroll to certain anchor/div on page load?

There's no need to use jQuery because this is native JavaScript functionality

element.scrollIntoView()

In Python, how do you convert a `datetime` object to seconds?

The standard way to find the processing time in ms of a block of code in python 3.x is the following:

import datetime

t_start = datetime.datetime.now()

# Here is the python3 code, you want 
# to check the processing time of

t_end = datetime.datetime.now()
print("Time taken : ", (t_end - t_start).total_seconds()*1000, " ms")

Accessing post variables using Java Servlets

POST variables should be accessible via the request object: HttpRequest.getParameterMap(). The exception is if the form is sending multipart MIME data (the FORM has enctype="multipart/form-data"). In that case, you need to parse the byte stream with a MIME parser. You can write your own or use an existing one like the Apache Commons File Upload API.

how to modify an existing check constraint?

NO, you can't do it other way than so.

How do I create a user with the same privileges as root in MySQL/MariaDB?

% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;

Handling Enter Key in Vue.js

You forget a '}' before the last line (to close the "methods {...").

This code works :

_x000D_
_x000D_
Vue.config.keyCodes.atsign = 50;_x000D_
_x000D_
new Vue({_x000D_
  el: '#myApp',_x000D_
  data: {_x000D_
    emailAddress: '',_x000D_
    log: ''_x000D_
  },_x000D_
  methods: {_x000D_
  _x000D_
    onEnterClick: function() {_x000D_
     alert('Enter was pressed');_x000D_
    },_x000D_
    _x000D_
    onAtSignClick: function() {_x000D_
     alert('@ was pressed');_x000D_
    },_x000D_
    _x000D_
    postEmailAddress: function() {_x000D_
   this.log += '\n\nPosting';_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
html, body, #editor {_x000D_
  margin: 0;_x000D_
  height: 100%;_x000D_
  color: #333;_x000D_
}
_x000D_
<script src="https://vuejs.org/js/vue.min.js"></script>_x000D_
_x000D_
<div id="myApp" style="padding:2rem; background-color:#fff;">_x000D_
_x000D_
  <input type="text" v-model="emailAddress" v-on:keyup.enter="onEnterClick" v-on:keyup.atsign="onAtSignClick" />_x000D_
  _x000D_
  <button type="button" v-on:click="postEmailAddress" >Subscribe</button> _x000D_
  <br /><br />_x000D_
  _x000D_
  <textarea v-model="log" rows="4"></textarea>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get the selected index of a RadioGroup in Android

You should be able to do something like this:

int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
View radioButton = radioButtonGroup.findViewById(radioButtonID);
int idx = radioButtonGroup.indexOfChild(radioButton);

If the RadioGroup contains other Views (like a TextView) then the indexOfChild() method will return wrong index.

To get the selected RadioButton text on the RadioGroup:

 RadioButton r = (RadioButton) radioButtonGroup.getChildAt(idx);
 String selectedtext = r.getText().toString();

Windows task scheduler error 101 launch failure code 2147943785

Had the same issue today. I added the user to:

Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment -> Log on as a batch job

But was still getting the error. I found this post, and it turns out there's also this setting that I had to remove the user from (not sure how it got in there):

Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment -> Deny log on as a batch job

So just be aware that you may need to check both policies for the user.

How to Install pip for python 3.7 on Ubuntu 18?

Combining the answers from @mpenkon and @dangel, this is what worked for me:

  1. sudo apt install python3-pip

  2. python3.7 -m pip install pip

Step #1 is required (assuming you don't already have pip for python3) for step #2 to work. It uses pip for Python3.6 to install pip for Python 3.7 apparently.

Best way to save a trained model in PyTorch?

If you want to save the model and wants to resume the training later:

Single GPU: Save:

state = {
        'epoch': epoch,
        'state_dict': model.state_dict(),
        'optimizer': optimizer.state_dict(),
}
savepath='checkpoint.t7'
torch.save(state,savepath)

Load:

checkpoint = torch.load('checkpoint.t7')
model.load_state_dict(checkpoint['state_dict'])
optimizer.load_state_dict(checkpoint['optimizer'])
epoch = checkpoint['epoch']

Multiple GPU: Save

state = {
        'epoch': epoch,
        'state_dict': model.module.state_dict(),
        'optimizer': optimizer.state_dict(),
}
savepath='checkpoint.t7'
torch.save(state,savepath)

Load:

checkpoint = torch.load('checkpoint.t7')
model.load_state_dict(checkpoint['state_dict'])
optimizer.load_state_dict(checkpoint['optimizer'])
epoch = checkpoint['epoch']

#Don't call DataParallel before loading the model otherwise you will get an error

model = nn.DataParallel(model) #ignore the line if you want to load on Single GPU

How does OkHttp get Json string?

I am also faced the same issue

use this code:

// notice string() call
String resStr = response.body().string();    
JSONObject json = new JSONObject(resStr);

it definitely works

Spring Boot Multiple Datasource

MySqlBDConfig.java

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "PACKAGE OF YOUR CRUDS USING MYSQL DATABASE",entityManagerFactoryRef = "mysqlEmFactory" ,transactionManagerRef = "mysqlTransactionManager")
public class MySqlBDConfig{

@Autowired
private Environment env;

@Bean(name="mysqlProperities")
@ConfigurationProperties(prefix="spring.mysql")
public DataSourceProperties mysqlProperities(){
    return new  DataSourceProperties();
}


@Bean(name="mysqlDataSource")
public DataSource interfaceDS(@Qualifier("mysqlProperities")DataSourceProperties dataSourceProperties){
    return dataSourceProperties.initializeDataSourceBuilder().build();

}

@Primary
@Bean(name="mysqlEmFactory")
public LocalContainerEntityManagerFactoryBean mysqlEmFactory(@Qualifier("mysqlDataSource")DataSource mysqlDataSource,EntityManagerFactoryBuilder builder){
    return builder.dataSource(mysqlDataSource).packages("PACKAGE OF YOUR MODELS").build();
}


@Bean(name="mysqlTransactionManager")
public PlatformTransactionManager mysqlTransactionManager(@Qualifier("mysqlEmFactory")EntityManagerFactory factory){
    return new JpaTransactionManager(factory);
}
}

H2DBConfig.java

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "PACKAGE OF YOUR CRUDS USING MYSQL DATABASE",entityManagerFactoryRef = "dsEmFactory" ,transactionManagerRef = "dsTransactionManager")
public class H2DBConfig{

        @Autowired
        private Environment env;

        @Bean(name="dsProperities")
        @ConfigurationProperties(prefix="spring.h2")
        public DataSourceProperties dsProperities(){
            return new  DataSourceProperties();
        }


    @Bean(name="dsDataSource")
    public DataSource dsDataSource(@Qualifier("dsProperities")DataSourceProperties dataSourceProperties){
        return dataSourceProperties.initializeDataSourceBuilder().build();

    }

    @Bean(name="dsEmFactory")
    public LocalContainerEntityManagerFactoryBean dsEmFactory(@Qualifier("dsDataSource")DataSource dsDataSource,EntityManagerFactoryBuilder builder){
        LocalContainerEntityManagerFactoryBean em =  builder.dataSource(dsDataSource).packages("PACKAGE OF YOUR MODELS").build();
        HibernateJpaVendorAdapter ven = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(ven);
        HashMap<String, Object> prop = new HashMap<>();
        prop.put("hibernate.dialect", env.getProperty("spring.jpa.properties.hibernate.dialect"));
        prop.put("hibernate.show_sql", env.getProperty("spring.jpa.show-sql"));

        em.setJpaPropertyMap(prop);
        em.afterPropertiesSet();
        return em;
    }


    @Bean(name="dsTransactionManager")
    public PlatformTransactionManager dsTransactionManager(@Qualifier("dsEmFactory")EntityManagerFactory factory){
        return new JpaTransactionManager(factory);
    }
}

application.properties

#---mysql DATASOURCE---
spring.mysql.driverClassName = com.mysql.jdbc.Driver
spring.mysql.url = jdbc:mysql://127.0.0.1:3306/test
spring.mysql.username = root
spring.mysql.password = root
#----------------------

#---H2 DATASOURCE----
spring.h2.driverClassName = org.h2.Driver
spring.h2.url = jdbc:h2:file:~/test
spring.h2.username = root
spring.h2.password = root
#---------------------------

#------JPA----- 
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true

Application.java

@SpringBootApplication
public class Application {


    public static void main(String[] args)   {
        ApplicationContext ac=SpringApplication.run(KeopsSageInvoiceApplication.class, args);
        UserMysqlDao userRepository = ac.getBean(UserMysqlDao.class)
        //for exemple save a new user using your repository 
        userRepository.save(new UserMysql());

    }
}

Cannot import keras after installation

Firstly checked the list of installed Python packages by:

pip list | grep -i keras

If there is keras shown then install it by:

pip install keras --upgrade --log ./pip-keras.log

now check the log, if there is any pending dependencies are present, it will affect your installation. So remove dependencies and then again install it.

What to put in a python module docstring?

To quote the specifications:

The docstring of a script (a stand-alone program) should be usable as its "usage" message, printed when the script is invoked with incorrect or missing arguments (or perhaps with a "-h" option, for "help"). Such a docstring should document the script's function and command line syntax, environment variables, and files. Usage messages can be fairly elaborate (several screens full) and should be sufficient for a new user to use the command properly, as well as a complete quick reference to all options and arguments for the sophisticated user.

The docstring for a module should generally list the classes, exceptions and functions (and any other objects) that are exported by the module, with a one-line summary of each. (These summaries generally give less detail than the summary line in the object's docstring.) The docstring for a package (i.e., the docstring of the package's __init__.py module) should also list the modules and subpackages exported by the package.

The docstring for a class should summarize its behavior and list the public methods and instance variables. If the class is intended to be subclassed, and has an additional interface for subclasses, this interface should be listed separately (in the docstring). The class constructor should be documented in the docstring for its __init__ method. Individual methods should be documented by their own docstring.

The docstring of a function or method is a phrase ending in a period. It prescribes the function or method's effect as a command ("Do this", "Return that"), not as a description; e.g. don't write "Returns the pathname ...". A multiline-docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable). Optional arguments should be indicated. It should be documented whether keyword arguments are part of the interface.

__FILE__ macro shows full path

A short, working answer for both Windows and *nix:

#define __FILENAME__ std::max<const char*>(__FILE__,\
    std::max(strrchr(__FILE__, '\\')+1, strrchr(__FILE__, '/')+1))

Redirecting to another page in ASP.NET MVC using JavaScript/jQuery

// in the HTML code I used some razor
@Html.Hidden("RedirectTo", Url.Action("Action", "Controller"));

// now down in the script I do this
<script type="text/javascript">

var url = $("#RedirectTo").val();

$(document).ready(function () {
    $.ajax({
        dataType: 'json',
        type: 'POST',
        url: '/Controller/Action',
        success: function (result) {
            if (result.UserFriendlyErrMsg === 'Some Message') {
                // display a prompt
                alert("Message: " + result.UserFriendlyErrMsg);
                // redirect us to the new page
                location.href = url;
            }
            $('#friendlyMsg').html(result.UserFriendlyErrMsg);
        }
    });
</script>

How to Convert a Text File into a List in Python

Going with what you've started:

row = [[]] 
crimefile = open(fileName, 'r') 
for line in crimefile.readlines(): 
    tmp = []
    for element in line[0:-1].split(','):
        tmp.append(element)
row.append(tmp)

ReDim Preserve to a Multi-Dimensional Array in Visual Basic 6

Since VB6 is very similar to VBA, I think I might have a solution which does not require this much code to ReDim a 2-dimensional array - using Transpose, if you are working in Excel.

The solution (Excel VBA):

Dim n, m As Integer
n = 2
m = 1
Dim arrCity() As Variant
ReDim arrCity(1 To n, 1 To m)

m = m + 1
ReDim Preserve arrCity(1 To n, 1 To m)
arrCity = Application.Transpose(arrCity)
n = n + 1
ReDim Preserve arrCity(1 To m, 1 To n)
arrCity = Application.Transpose(arrCity)

What is different from OP's question: the lower bound of arrCity array is not 0, but 1. This is in order to let Application.Transpose do it's job.

Note that Transpose is a method of the Excel Application object (which in actuality is a shortcut to Application.WorksheetFunction.Transpose). And in VBA, one must take care when using Transpose as it has two significant limitations: If the array has more than 65536 elements, it will fail. If ANY element's length exceed 256 characters, it will fail. If neither of these is an issue, then Transpose will nicely convert the rank of an array form 1D to 2D or vice-versa.

Unfortunately there is nothing like 'Transpose' build into VB6.

How do I fetch only one branch of a remote Git repository?

I know there are a lot of answers already, but these are the steps that worked for me:

  1. git fetch <remote_name> <branch_name>
  2. git branch <branch_name> FETCH_HEAD
  3. git checkout <branch_name>

These are based on the answer by @Abdulsattar Mohammed, the comment by @Christoph on that answer, and these other stack overflow questions and their answers:

How to get all options in a drop-down list by Selenium WebDriver using C#?

To get all the dropdown values you can use List.

List<string> lstDropDownValues = new List<string>();
int iValuescount = driver.FindElement(By.Xpath("\html\....\select\option"))

for(int ivalue = 1;ivalue<=iValuescount;ivalue++)
 {
  string strValue = driver.FindElement(By.Xpath("\html\....\select\option["+ ivalue +"]"));
  lstDropDownValues.Add(strValue); 
 }

How to get a particular date format ('dd-MMM-yyyy') in SELECT query SQL Server 2008 R2

select convert(varchar(11), transfer_date, 106)

got me my desired result of date formatted as 07 Mar 2018

My column transfer_date is a datetime type column and I am using SQL Server 2017 on azure

Add custom headers to WebView resource requests - android

Here is an implementation using HttpUrlConnection:

class CustomWebviewClient : WebViewClient() {
    private val charsetPattern = Pattern.compile(".*?charset=(.*?)(;.*)?$")

    override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {
        try {
            val connection: HttpURLConnection = URL(request.url.toString()).openConnection() as HttpURLConnection
            connection.requestMethod = request.method
            for ((key, value) in request.requestHeaders) {
                connection.addRequestProperty(key, value)
            }

            connection.addRequestProperty("custom header key", "custom header value")

            var contentType: String? = connection.contentType
            var charset: String? = null
            if (contentType != null) {
                // some content types may include charset => strip; e. g. "application/json; charset=utf-8"
                val contentTypeTokenizer = StringTokenizer(contentType, ";")
                val tokenizedContentType = contentTypeTokenizer.nextToken()

                var capturedCharset: String? = connection.contentEncoding
                if (capturedCharset == null) {
                    val charsetMatcher = charsetPattern.matcher(contentType)
                    if (charsetMatcher.find() && charsetMatcher.groupCount() > 0) {
                        capturedCharset = charsetMatcher.group(1)
                    }
                }
                if (capturedCharset != null && !capturedCharset.isEmpty()) {
                    charset = capturedCharset
                }

                contentType = tokenizedContentType
            }

            val status = connection.responseCode
            var inputStream = if (status == HttpURLConnection.HTTP_OK) {
                connection.inputStream
            } else {
                // error stream can sometimes be null even if status is different from HTTP_OK
                // (e. g. in case of 404)
                connection.errorStream ?: connection.inputStream
            }
            val headers = connection.headerFields
            val contentEncodings = headers.get("Content-Encoding")
            if (contentEncodings != null) {
                for (header in contentEncodings) {
                    if (header.equals("gzip", true)) {
                        inputStream = GZIPInputStream(inputStream)
                        break
                    }
                }
            }
            return WebResourceResponse(contentType, charset, status, connection.responseMessage, convertConnectionResponseToSingleValueMap(connection.headerFields), inputStream)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return super.shouldInterceptRequest(view, request)
    }

    private fun convertConnectionResponseToSingleValueMap(headerFields: Map<String, List<String>>): Map<String, String> {
        val headers = HashMap<String, String>()
        for ((key, value) in headerFields) {
            when {
                value.size == 1 -> headers[key] = value[0]
                value.isEmpty() -> headers[key] = ""
                else -> {
                    val builder = StringBuilder(value[0])
                    val separator = "; "
                    for (i in 1 until value.size) {
                        builder.append(separator)
                        builder.append(value[i])
                    }
                    headers[key] = builder.toString()
                }
            }
        }
        return headers
    }
}

Note that this does not work for POST requests because WebResourceRequest doesn't provide POST data. There is a Request Data - WebViewClient library which uses a JavaScript injection workaround for intercepting POST data.

How to read a large file line by line?

if ($file = fopen("file.txt", "r")) {
    while(!feof($file)) {
        $line = fgets($file);
        # do same stuff with the $line
    }
    fclose($file);
}

Pass data to layout that are common to all pages

You don't have to mess with actions or change the model, just use a base controller and cast the existing controller from the layout viewcontext.

Create a base controller with the desired common data (title/page/location etc) and action initialization...

public abstract class _BaseController:Controller {
    public Int32 MyCommonValue { get; private set; }

    protected override void OnActionExecuting(ActionExecutingContext filterContext) {

        MyCommonValue = 12345;

        base.OnActionExecuting(filterContext);
    }
}

Make sure every controller uses the base controller...

public class UserController:_BaseController {...

Cast the existing base controller from the view context in your _Layout.cshml page...

@{
    var myController = (_BaseController)ViewContext.Controller;
}

Now you can refer to values in your base controller from your layout page.

@myController.MyCommonValue

UPDATE

You could also create a page extension that would allow you to use this.

//Allows typed "this.Controller()." in cshtml files
public static class MyPageExtensions {
    public static _BaseController Controller(this WebViewPage page) => Controller<_BaseController>(page);
    public static T Controller<T>(this WebViewPage page) where T : _BaseController => (T)page.ViewContext.Controller;
}

Then you only have to remember to use this.Controller() when you want the controller.

@{
    var myController = this.Controller(); //_BaseController
}

or specific controller that inherits from _BaseController...

@{
    var myController = this.Controller<MyControllerType>();
}

How to resize image (Bitmap) to a given size?

In MonoDroid here's how (c#)

/// <summary>
/// Graphics support for resizing images
/// </summary>
public static class Graphics
{
    public static Bitmap ScaleDownBitmap(Bitmap originalImage, float maxImageSize, bool filter)
    {
        float ratio = Math.Min((float)maxImageSize / originalImage.Width, (float)maxImageSize / originalImage.Height);
        int width = (int)Math.Round(ratio * (float)originalImage.Width);
        int height =(int) Math.Round(ratio * (float)originalImage.Height);

        Bitmap newBitmap = Bitmap.CreateScaledBitmap(originalImage, width, height, filter);
        return newBitmap;
    }

    public static Bitmap ScaleBitmap(Bitmap originalImage, int wantedWidth, int wantedHeight)
    {
        Bitmap output = Bitmap.CreateBitmap(wantedWidth, wantedHeight, Bitmap.Config.Argb8888);
        Canvas canvas = new Canvas(output);
        Matrix m = new Matrix();
        m.SetScale((float)wantedWidth / originalImage.Width, (float)wantedHeight / originalImage.Height);
        canvas.DrawBitmap(originalImage, m, new Paint());
        return output;
    }

}

Run all SQL files in a directory

You can create a single script that calls all the others.

Put the following into a batch file:

@echo off
echo.>"%~dp0all.sql"
for %%i in ("%~dp0"*.sql) do echo @"%%~fi" >> "%~dp0all.sql"

When you run that batch file it will create a new script named all.sql in the same directory where the batch file is located. It will look for all files with the extension .sql in the same directory where the batch file is located.

You can then run all scripts by using sqlplus user/pwd @all.sql (or extend the batch file to call sqlplus after creating the all.sql script)

AngularJS : automatically detect change in model

In views with {{}} and/or ng-model, Angular is setting up $watch()es for you behind the scenes.

By default $watch compares by reference. If you set the third parameter to $watch to true, Angular will instead "shallow" watch the object for changes. For arrays this means comparing the array items, for object maps this means watching the properties. So this should do what you want:

$scope.$watch('myModel', function() { ... }, true);

Update: Angular v1.2 added a new method for this, `$watchCollection():

$scope.$watchCollection('myModel', function() { ... });

Note that the word "shallow" is used to describe the comparison rather than "deep" because references are not followed -- e.g., if the watched object contains a property value that is a reference to another object, that reference is not followed to compare the other object.

Generate a UUID on iOS from Swift

Try this one:

let uuid = NSUUID().uuidString
print(uuid)

Swift 3/4/5

let uuid = UUID().uuidString
print(uuid)

Where is Java's Array indexOf?

Jeffrey Hantin's answer is good but it has some constraints, if its this do this or else to that...

You can write your own extension method and it always works the way you want.

Lists.indexOf(array, x -> item == x); // compare in the way you want

And here is your extension

public final class Lists {
    private Lists() {
    }

    public static <T> int indexOf(T[] array, Predicate<T> predicate) {
        for (int i = 0; i < array.length; i++) {
            if (predicate.test(array[i])) return i;
        }
        return -1;
    }

    public static <T> int indexOf(List<T> list, Predicate<T> predicate) {
        for (int i = 0; i < list.size(); i++) {
            if (predicate.test(list.get(i))) return i;
        }
        return -1;
    }

    public interface Predicate<T> {
        boolean test(T t);
    }
}

Jquery UI Datepicker not displaying

If you are using the scripts of metro UI css (excellent free metro UI set from http://metroui.org.ua/) , that can clash too. In my case, this was the problem recently.

So, removed the scripts reference of metro UI (as I was not using its components), datepicker is showing.

But you cant get metro look for datepicker of jQuery-ui

But in most cases, as others mentioned, its clash with duplicate versions of jQuery-UI javascripts.

NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver

Solved the problem by re-installing CUDA:

wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/cuda-ubuntu1804.pin
mv cuda-ubuntu1804.pin /etc/apt/preferences.d/cuda-repository-pin-600
wget https://developer.download.nvidia.com/compute/cuda/11.1.0/local_installers/cuda-repo-ubuntu1804-11-1-local_11.1.0-455.23.05-1_amd64.deb
echo "md5sum: $(md5sum cuda-repo-ubuntu1804-11-1-local_11.1.0-455.23.05-1_amd64.deb)"
echo "correct: 056de5e03444cce506202f50967b0016"
dpkg -i cuda-repo-ubuntu1804-11-1-local_11.1.0-455.23.05-1_amd64.deb
apt-key add /var/cuda-repo-ubuntu1804-11-1-local/7fa2af80.pub
apt-get -qq update
apt-get -qq -y install cuda
rm cuda-repo-ubuntu1804-11-1-local_11.1.0-455.23.05-1_amd64.deb

Android: disabling highlight on listView click

RoflcoptrException's answer should do the trick,but for some reason it did not work for me, So I am posting the solution which worked for me, hope it helps someone

<ListView 
android:listSelector="@android:color/transparent" 
android:cacheColorHint="@android:color/transparent"
/>

How to efficiently build a tree from a flat structure?

Store IDs of the objects in a hash table mapping to the specific object. Enumerate through all the objects and find their parent if it exists and update its parent pointer accordingly.

class MyObject
{ // The actual object
    public int ParentID { get; set; }
    public int ID { get; set; }
}

class Node
{
    public List<Node> Children = new List<Node>();
    public Node Parent { get; set; }
    public MyObject AssociatedObject { get; set; }
}

IEnumerable<Node> BuildTreeAndGetRoots(List<MyObject> actualObjects)
{
    Dictionary<int, Node> lookup = new Dictionary<int, Node>();
    actualObjects.ForEach(x => lookup.Add(x.ID, new Node { AssociatedObject = x }));
    foreach (var item in lookup.Values) {
        Node proposedParent;
        if (lookup.TryGetValue(item.AssociatedObject.ParentID, out proposedParent)) {
            item.Parent = proposedParent;
            proposedParent.Children.Add(item);
        }
    }
    return lookup.Values.Where(x => x.Parent == null);
}

Excel 2013 horizontal secondary axis

You should follow the guidelines on Add a secondary horizontal axis:

Add a secondary horizontal axis

To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.

  1. Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.

  2. On the Layout tab, in the Axes group, click Axes.

    enter image description here

  3. Click Secondary Horizontal Axis, and then click the display option that you want.

enter image description here


Add a secondary vertical axis

You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.

  1. In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:

    • Click the chart.

      This displays the Chart Tools, adding the Design, Layout, and Format tabs.

    • On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.

      enter image description here

  2. On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.

    Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.

  3. On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.

    A secondary vertical axis is displayed in the chart.

  4. To change the display of the secondary vertical axis, do the following:

    • On the Layout tab, in the Axes group, click Axes.

    • Click Secondary Vertical Axis, and then click the display option that you want.

  5. To change the axis options of the secondary vertical axis, do the following:

    • Right-click the secondary vertical axis, and then click Format Axis.

    • Under Axis Options, select the options that you want to use.

What is the main purpose of setTag() getTag() methods of View?

For web developers, this seems to be the equivalent to data-..

Bootstrap fixed header and footer with scrolling body-content area in fluid-container

Until I get a better option, this is the most "bootstrappy" answer I can work out:

JSFiddle: http://jsfiddle.net/TrueBlueAussie/6cbrjrt5/

I have switched to using LESS and including the Bootstrap Source NuGet package to ensure compatibility (by giving me access to the bootstrap variables.less file:

in _layout.cshtml master page

  • Move footer outside the body-content container
  • Use boostrap's navbar-fixed-bottom on the footer
  • Drop the <hr/> before the footer (as now redundant)

Relevant page HTML:

<div class="container-fluid body-content">
    @RenderBody()
</div>
<footer class="navbar-fixed-bottom">
    <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
</footer>

In Site.less

  • Set HTML and BODY heights to 100%
  • Set BODY overflow to hidden
  • Set body-content div position to absolute
  • Set body-content div top to @navbar-height instead of hard-wiring value
  • Set body-content div bottom to 30px.
  • Set body-content div left and right to 0
  • Set body-content div overflow-y to auto

Site.less

html {
    height: 100%;

    body {
        height: 100%;
        overflow: hidden;

        .container-fluid.body-content {
            position: absolute;
            top: @navbar-height;
            bottom: 30px;
            right: 0;
            left: 0;
            overflow-y: auto;
        }
    }
}

The remaining problem is there seems to be no defining variable for the footer height in bootstrap. If someone call tell me if there is a magic 30px variable defined in Bootstrap I would appreciate it.

Run automatically program on startup under linux ubuntu

sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename 
sudo update-rc.d filename defaults 

Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln).

Edit

At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*. Updated above code to reflect this.

Another Edit

Also as pointed out in the comments (by Charles Brandt), /filename must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.

Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts

yetAnother Edit

As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.

According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering", in which case you have to pass sequence and runlevel configuration through command line arguments.

The equivalent argument set for the above example is

sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .

convert pfx format to p12

Run this command to change .cert file to .p12:

openssl pkcs12 -export -out server.p12 -inkey server.key -in server.crt 

Where server.key is the server key and server.cert is a CA issue cert or a self sign cert file.

Cross-Origin Read Blocking (CORB)

There is an edge case worth mentioning in this context: Chrome (some versions, at least) checks CORS preflights using the algorithm set up for CORB. IMO, this is a bit silly because preflights don't seem to affect the CORB threat model, and CORB seems designed to be orthogonal to CORS. Also, the body of a CORS preflight is not accessible, so there is no negative consequence just an irritating warning.

Anyway, check that your CORS preflight responses (OPTIONS method responses) don't have a body (204). An empty 200 with content type application/octet-stream and length zero worked well here too.

You can confirm if this is the case you are hitting by counting CORB warnings vs. OPTIONS responses with a message body.

Error renaming a column in MySQL

With MySQL 5.x you can use:

ALTER TABLE table_name
CHANGE COLUMN old_column_name new_column_name DATATYPE NULL DEFAULT NULL;

How do I use Safe Area Layout programmatically?

I'm using this instead of add leading and trailing margin constraints to the layoutMarginsGuide:

UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
yourView.translatesAutoresizingMaskIntoConstraints = NO;
[NSLayoutConstraint activateConstraints:@[
                                           [safe.trailingAnchor constraintEqualToAnchor:yourView.trailingAnchor],
                                           [yourView.leadingAnchor constraintEqualToAnchor:safe.leadingAnchor],
                                           [yourView.topAnchor constraintEqualToAnchor:safe.topAnchor],
                                           [safe.bottomAnchor constraintEqualToAnchor:yourView.bottomAnchor]
                                          ]];

Please also check the option for lower version of ios 11 from Krunal's answer.

How to initialize an array of objects in Java

It is almost fine. Just have:

Player[] thePlayers = new Player[playerCount + 1];

And let the loop be:

for(int i = 0; i < thePlayers.length; i++)

And note that java convention dictates that names of methods and variables should start with lower-case.

Update: put your method within the class body.

How to center a window on the screen in Tkinter?

You can try to use the methods winfo_screenwidth and winfo_screenheight, which return respectively the width and height (in pixels) of your Tk instance (window), and with some basic math you can center your window:

import tkinter as tk
from PyQt4 import QtGui    # or PySide

def center(toplevel):
    toplevel.update_idletasks()

    # Tkinter way to find the screen resolution
    # screen_width = toplevel.winfo_screenwidth()
    # screen_height = toplevel.winfo_screenheight()

    # PyQt way to find the screen resolution
    app = QtGui.QApplication([])
    screen_width = app.desktop().screenGeometry().width()
    screen_height = app.desktop().screenGeometry().height()

    size = tuple(int(_) for _ in toplevel.geometry().split('+')[0].split('x'))
    x = screen_width/2 - size[0]/2
    y = screen_height/2 - size[1]/2

    toplevel.geometry("+%d+%d" % (x, y))
    toplevel.title("Centered!")    

if __name__ == '__main__':
    root = tk.Tk()
    root.title("Not centered")

    win = tk.Toplevel(root)
    center(win)

    root.mainloop()

I am calling update_idletasks method before retrieving the width and the height of the window in order to ensure that the values returned are accurate.

Tkinter doesn't see if there are 2 or more monitors extended horizontal or vertical. So, you 'll get the total resolution of all screens together and your window will end-up somewhere in the middle of the screens.

PyQt from the other hand, doesn't see multi-monitors environment either, but it will get only the resolution of the Top-Left monitor (Imagine 4 monitors, 2 up and 2 down making a square). So, it does the work by putting the window on center of that screen. If you don't want to use both, PyQt and Tkinter, maybe it would be better to go with PyQt from start.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

You should verify the owner of the group for /var/run/mysqld. If it isn't mysql.mysql, then do:

su root
chown mysql.mysql /var/run/mysqld

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

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

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

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

Android on-screen keyboard auto popping up

This code will work on all android versions:

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

 //Automatic popping up keyboard on start Activity

     getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

 or

 //avoid automatically appear android keyboard when activity start
     getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
 }

What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?

pickling is recursive, not sequential. Thus, to pickle a list, pickle will start to pickle the containing list, then pickle the first element… diving into the first element and pickling dependencies and sub-elements until the first element is serialized. Then moves on to the next element of the list, and so on, until it finally finishes the list and finishes serializing the enclosing list. In short, it's hard to treat a recursive pickle as sequential, except for some special cases. It's better to use a smarter pattern on your dump, if you want to load in a special way.

The most common pickle, it to pickle everything with a single dump to a file -- but then you have to load everything at once with a single load. However, if you open a file handle and do multiple dump calls (e.g. one for each element of the list, or a tuple of selected elements), then your load will mirror that… you open the file handle and do multiple load calls until you have all the list elements and can reconstruct the list. It's still not easy to selectively load only certain list elements, however. To do that, you'd probably have to store your list elements as a dict (with the index of the element or chunk as the key) using a package like klepto, which can break up a pickled dict into several files transparently, and enables easy loading of specific elements.

Saving and loading multiple objects in pickle file?

jQuery: selecting each td in a tr

Your $(magicSelector) could be $('td', this). This will grab all td that are children of this, which in your case is each tr. This is the same as doing $(this).find('td').

$('td', this).each(function() {
// Logic
});

hadoop copy a local file system folder to HDFS

Navigate to your "/install/hadoop/datanode/bin" folder or path where you could execute your hadoop commands:

To place the files in HDFS: Format: hadoop fs -put "Local system path"/filename.csv "HDFS destination path"

eg)./hadoop fs -put /opt/csv/load.csv /user/load

Here the /opt/csv/load.csv is source file path from my local linux system.

/user/load means HDFS cluster destination path in "hdfs://hacluster/user/load"

To get the files from HDFS to local system: Format : hadoop fs -get "/HDFSsourcefilepath" "/localpath"

eg)hadoop fs -get /user/load/a.csv /opt/csv/

After executing the above command, a.csv from HDFS would be downloaded to /opt/csv folder in local linux system.

This uploaded files could also be seen through HDFS NameNode web UI.

Service Reference Error: Failed to generate code for the service reference

I have encountered this problem when upgrading a VS2010 WCF+Silverlight solution in VS2015 Professional. Besides automatically upgrading from Silverlight 4 to Silverlight 5, the service reference reuse checkbox value was changed and generation failed.

missing FROM-clause entry for table

Because that gtab82 table isn't in your FROM or JOIN clause. You refer gtab82 table in these cases: gtab82.memno and gtab82.memacid

Simple DateTime sql query

Open up the Access File you are trying to export SQL data to. Delete any Queries that are there. Everytime you run SQL Server Import wizard, even if it fails, it creates a Query in the Access DB that has to be deleted before you can run the SQL export Wizard again.

jquery smooth scroll to an anchor?

I used the plugin Smooth Scroll, at http://plugins.jquery.com/smooth-scroll/. With this plugin all you need to include is a link to jQuery and to the plugin code:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="javascript/smoothscroll.js"></script>

(the links need to have the class smoothScroll to work).

Another feature of Smooth Scroll is that the ancor name is not displayed in the URL!

UnsatisfiedDependencyException: Error creating bean with name

If you describe a field as criteria in method definition ("findBy"), You must pass that parameter to the method, otherwise you will get "Unsatisfied dependency expressed through method parameter" exception.

public interface ClientRepository extends JpaRepository<Client, Integer> {
       Client findByClientId();                ////WRONG !!!!
       Client findByClientId(int clientId);    /// CORRECT 
}

*I assume that your Client entity has clientId attribute.

"This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded"

Its .net Version mismatch of the dll so try changing to from in app.config or web.config. Generally have a higher Framework than lower because when we add system's dll to the lower version built .net application so it won't work therefore just change to the higher version

$.ajax - dataType

  • contentType is the HTTP header sent to the server, specifying a particular format.
    Example: I'm sending JSON or XML
  • dataType is you telling jQuery what kind of response to expect.
    Expecting JSON, or XML, or HTML, etc. The default is for jQuery to try and figure it out.

The $.ajax() documentation has full descriptions of these as well.


In your particular case, the first is asking for the response to be in UTF-8, the second doesn't care. Also the first is treating the response as a JavaScript object, the second is going to treat it as a string.

So the first would be:

success: function(data) {
  // get data, e.g. data.title;
}

The second:

success: function(data) {
  alert("Here's lots of data, just a string: " + data);
}

Can you call ko.applyBindings to bind a partial view?

I've managed to bind a custom model to an element at runtime. The code is here: http://jsfiddle.net/ZiglioNZ/tzD4T/457/

The interesting bit is that I apply the data-bind attribute to an element I didn't define:

    var handle = slider.slider().find(".ui-slider-handle").first();
    $(handle).attr("data-bind", "tooltip: viewModel.value");
    ko.applyBindings(viewModel.value, $(handle)[0]);

how to get the first and last days of a given month

Print only current month week:

function my_week_range($date) {
    $ts = strtotime($date);
    $start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
    echo $currentWeek = ceil((date("d",strtotime($date)) - date("w",strtotime($date)) - 1) / 7) + 1;
    $start_date = date('Y-m-d', $start);$end_date=date('Y-m-d', strtotime('next saturday', $start));
    if($currentWeek==1)
        {$start_date = date('Y-m-01', strtotime($date));}
    else if($currentWeek==5)
       {$end_date = date('Y-m-t', strtotime($date));}
    else
       {}
    return array($start_date, $end_date );
}

$date_range=list($start_date, $end_date) = my_week_range($new_fdate);

Plot different DataFrames in the same figure

If you a running Jupyter/Ipython notebook and having problems using;

ax = df1.plot()

df2.plot(ax=ax)

Run the command inside of the same cell!! It wont, for some reason, work when they are separated into sequential cells. For me at least.

What exactly is nullptr?

How is it a keyword and an instance of a type?

This isn't surprising. Both true and false are keywords and as literals they have a type ( bool ). nullptr is a pointer literal of type std::nullptr_t, and it's a prvalue (you cannot take the address of it using &).

  • 4.10 about pointer conversion says that a prvalue of type std::nullptr_t is a null pointer constant, and that an integral null pointer constant can be converted to std::nullptr_t. The opposite direction is not allowed. This allows overloading a function for both pointers and integers, and passing nullptr to select the pointer version. Passing NULL or 0 would confusingly select the int version.

  • A cast of nullptr_t to an integral type needs a reinterpret_cast, and has the same semantics as a cast of (void*)0 to an integral type (mapping implementation defined). A reinterpret_cast cannot convert nullptr_t to any pointer type. Rely on the implicit conversion if possible or use static_cast.

  • The Standard requires that sizeof(nullptr_t) be sizeof(void*).

Java constructor/method with optional parameters?

Java doesn't support default parameters. You will need to have two constructors to do what you want.

An alternative if there are lots of possible values with defaults is to use the Builder pattern, whereby you use a helper object with setters.

e.g.

   public class Foo {
     private final String param1;
     private final String param2;

     private Foo(Builder builder) {
       this.param1 = builder.param1;
       this.param2 = builder.param2;
     }
     public static class Builder {
       private String param1 = "defaultForParam1";
       private String param2 = "defaultForParam2";

       public Builder param1(String param1) {
         this.param1 = param1;
         return this;
       }
       public Builder param2(String param1) {
         this.param2 = param2;
         return this;
       }
       public Foo build() {
         return new Foo(this);
       }
     }
   }

which allows you to say:

Foo myFoo = new Foo.Builder().param1("myvalue").build();

which will have a default value for param2.

Confirm Password with jQuery Validate

I'm implementing it in Play Framework and for me it worked like this:

1) Notice that I used data-rule-equalTo in input tag for the id inputPassword1. The code section of userform in my Modal:

<div class="form-group">
    <label for="pass1">@Messages("authentication.password")</label>
    <input class="form-control required" id="inputPassword1" placeholder="@Messages("authentication.password")" type="password" name="password" maxlength=10 minlength=5>
</div>
<div class="form-group">
    <label for="pass2">@Messages("authentication.password2")</label>
    <input class="form-control required" data-rule-equalTo="#inputPassword1" id="inputPassword2" placeholder="@Messages("authentication.password")" type="password" name="password2">
</div>

2)Since I used validator within a Modal

$(document).on("click", ".createUserModal", function () {
       $(this).find('#userform').validate({
           rules: {
               firstName: "required",
               lastName: "required",
               nationalId: {
                   required: true,
                   digits:true
               },
               email: {
                   required: true,
                   email: true
               },
               optradio: "required",
               password :{
                   required: true,
                   minlength: 5
               },
               password2: {
                   required: true
               }
           },
           highlight: function (element) {
               $(element).parent().addClass('error')
           },
           unhighlight: function (element) {
               $(element).parent().removeClass('error')
           },
           onsubmit: true
       });

   });

Hope it helps someone :).

Maven: How to change path to target directory from command line?

Colin is correct that a profile should be used. However, his answer hard-codes the target directory in the profile. An alternate solution would be to add a profile like this:

    <profile>
        <id>alternateBuildDir</id>
        <activation>
            <property>
                <name>alt.build.dir</name>
            </property>
        </activation>
        <build>
            <directory>${alt.build.dir}</directory>
        </build>
    </profile>

Doing so would have the effect of changing the build directory to whatever is given by the alt.build.dir property, which can be given in a POM, in the user's settings, or on the command line. If the property is not present, the compilation will happen in the normal target directory.

Highest Salary in each department

select T1.* from (select empname as e1,department_name,salary from employee ) as T1, (select max(salary) maxsal,department_name dept1 from employee group by department_name) as T2 where T1.department_name=T2.dept1 and T1.salary=maxsal;

Setting Timeout Value For .NET Web Service

After creating your client specifying the binding and endpoint address, you can assign an OperationTimeout,

client.InnerChannel.OperationTimeout = new TimeSpan(0, 5, 0);

Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet

I have Windows 10 and PowerShell 5.1 was already installed. For whatever reason the x86 version works and can find "Install-Module", but the other version cannot.

Search your Start Menu for "powershell", and find the entry that ends in "(x86)":

Windows 10 Start Menu searching for PowerShell

Here is what I experience between the two different versions:

PowerShell x86 vs x64 running Install-Module cmdlet comparison

Comparing two byte arrays in .NET

If you are looking for a very fast byte array equality comparer, I suggest you take a look at this STSdb Labs article: Byte array equality comparer. It features some of the fastest implementations for byte[] array equality comparing, which are presented, performance tested and summarized.

You can also focus on these implementations:

BigEndianByteArrayComparer - fast byte[] array comparer from left to right (BigEndian) BigEndianByteArrayEqualityComparer - - fast byte[] equality comparer from left to right (BigEndian) LittleEndianByteArrayComparer - fast byte[] array comparer from right to left (LittleEndian) LittleEndianByteArrayEqualityComparer - fast byte[] equality comparer from right to left (LittleEndian)

angular.service vs angular.factory

  angular.service('myService', myServiceFunction);
  angular.factory('myFactory', myFactoryFunction);

I had trouble wrapping my head around this concept until I put it to myself this way:

Service: the function that you write will be new-ed:

  myInjectedService  <----  new myServiceFunction()

Factory: the function (constructor) that you write will be invoked:

  myInjectedFactory  <---  myFactoryFunction()

What you do with that is up to you, but there are some useful patterns...

Such as writing a service function to expose a public API:

function myServiceFunction() {
  this.awesomeApi = function(optional) {
    // calculate some stuff
    return awesomeListOfValues;
  }
}
---------------------------------------------------------------------------------
// Injected in your controller
$scope.awesome = myInjectedService.awesomeApi();

Or using a factory function to expose a public API:

function myFactoryFunction() {
  var aPrivateVariable = "yay";

  function hello() {
    return "hello mars " + aPrivateVariable;
  }
  
  // expose a public API
  return {
    hello: hello
  };
}
---------------------------------------------------------------------------------
// Injected in your controller
$scope.hello = myInjectedFactory.hello();

Or using a factory function to return a constructor:

function myFactoryFunction() {
    return function() {
        var a = 2;
        this.a2 = function() {
            return a*2;
        };
    };
}
---------------------------------------------------------------------------------
// Injected in your controller
var myShinyNewObject = new myInjectedFactory();
$scope.four = myShinyNewObject.a2();

Which one to use?...

You can accomplish the same thing with both. However, in some cases the factory gives you a little bit more flexibility to create an injectable with a simpler syntax. That's because while myInjectedService must always be an object, myInjectedFactory can be an object, a function reference, or any value at all. For example, if you wrote a service to create a constructor (as in the last example above), it would have to be instantiated like so:

var myShinyNewObject = new myInjectedService.myFunction()

which is arguably less desirable than this:

var myShinyNewObject = new myInjectedFactory();

(But you should be wary about using this type of pattern in the first place because new-ing objects in your controllers creates hard-to-track dependencies that are difficult to mock for testing. Better to have a service manage a collection of objects for you than use new() wily-nilly.)


One more thing, they are all Singletons...

Also keep in mind that in both cases, angular is helping you manage a singleton. Regardless of where or how many times you inject your service or function, you will get the same reference to the same object or function. (With the exception of when a factory simply returns a value like a number or string. In that case, you will always get the same value, but not a reference.)

Bootstrap 3: How to get two form inputs on one line and other inputs on individual lines?

You can code like two input box inside one div

<div class="input-group">
            <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
            <input style="width:50% " class="form-control " placeholder="first name"  name="firstname" type="text" />
            <input style="width:50% " class="form-control " placeholder="lastname"  name="lastname" type="text" />
        </div>

How to show DatePickerDialog on Button click?

Following code works..

datePickerButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showDialog(0);
        }
    });

@Override
@Deprecated
protected Dialog onCreateDialog(int id) {
    return new DatePickerDialog(this, datePickerListener, year, month, day);
}

private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
    public void onDateSet(DatePicker view, int selectedYear,
                          int selectedMonth, int selectedDay) {
        day = selectedDay;
        month = selectedMonth;
        year = selectedYear;
        datePickerButton.setText(selectedDay + " / " + (selectedMonth + 1) + " / "
                + selectedYear);
    }
};

Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

I am using xUnit 2.2.0.

My issue was my solution was not able to find certain dlls and app.config was trying to resolve them. The error was not showing up in the test output window in Visual Studio.

I was able to identify the error when I installed xunit.runner.console and tried to run the tests through command line.

How to run xunit tests in CLI.

Explain the "setUp" and "tearDown" Python methods used in test cases

Suppose you have a suite with 10 tests. 8 of the tests share the same setup/teardown code. The other 2 don't.

setup and teardown give you a nice way to refactor those 8 tests. Now what do you do with the other 2 tests? You'd move them to another testcase/suite. So using setup and teardown also helps give a natural way to break the tests into cases/suites

Can HTML be embedded inside PHP "if" statement?

<?php if ($my_name == 'aboutme') { ?>
    HTML_GOES_HERE
<?php } ?>

How to join two JavaScript Objects, without using JQUERY

There are couple of different solutions to achieve this:

1 - Native javascript for-in loop:

const result = {};
let key;

for (key in obj1) {
  if(obj1.hasOwnProperty(key)){
    result[key] = obj1[key];
  }
}

for (key in obj2) {
  if(obj2.hasOwnProperty(key)){
    result[key] = obj2[key];
  }
}

2 - Object.keys():

const result = {};

Object.keys(obj1)
  .forEach(key => result[key] = obj1[key]);

Object.keys(obj2)
  .forEach(key => result[key] = obj2[key]);

3 - Object.assign():
(Browser compatibility: Chrome: 45, Firefox (Gecko): 34, Internet Explorer: No support, Edge: (Yes), Opera: 32, Safari: 9)

const result = Object.assign({}, obj1, obj2);

4 - Spread Operator:
Standardised from ECMAScript 2015 (6th Edition, ECMA-262):

Defined in several sections of the specification: Array Initializer, Argument Lists

Using this new syntax you could join/merge different objects into one object like this:

const result = {
  ...obj1,
  ...obj2,
};

5 - jQuery.extend(target, obj1, obj2):

Merge the contents of two or more objects together into the first object.

const target = {};

$.extend(target, obj1, obj2);

6 - jQuery.extend(true, target, obj1, obj2):

Run a deep merge of the contents of two or more objects together into the target. Passing false for the first argument is not supported.

const target = {};

$.extend(true, target, obj1, obj2);

7 - Lodash _.assignIn(object, [sources]): also named as _.extend:

const result = {};

_.assignIn(result, obj1, obj2);

8 - Lodash _.merge(object, [sources]):

const result = _.merge(obj1, obj2);

There are a couple of important differences between lodash's merge function and Object.assign:

1- Although they both receive any number of objects but lodash's merge apply a deep merge of those objects but Object.assign only merges the first level. For instance:

_.isEqual(_.merge({
  x: {
    y: { key1: 'value1' },
  },
}, {
  x: {
    y: { key2: 'value2' },
  },
}), {
  x: {
    y: {
      key1: 'value1',
      key2: 'value2',
    },
  },
}); // true

BUT:

const result = Object.assign({
  x: {
    y: { key1: 'value1' },
  },
}, {
  x: {
    y: { key2: 'value2' },
  },
});
_.isEqual(result, {
  x: {
    y: {
      key1: 'value1',
      key2: 'value2',
    },
  },
}); // false
// AND
_.isEqual(result, {
  x: {
    y: {
      key2: 'value2',
    },
  },
}); // true

2- Another difference has to do with how Object.assign and _.merge interpret the undefined value:

_.isEqual(_.merge({x: 1}, {x: undefined}), { x: 1 }) // false

BUT:

_.isEqual(Object.assign({x: 1}, {x: undefined}), { x: undefined })// true

Update 1:

When using for in loop in JavaScript, we should be aware of our environment specially the possible prototype changes in the JavaScript types. For instance some of the older JavaScript libraries add new stuff to Array.prototype or even Object.prototype. To safeguard your iterations over from the added stuff we could use object.hasOwnProperty(key) to mke sure the key is actually part of the object you are iterating over.


Update 2:

I updated my answer and added the solution number 4, which is a new JavaScript feature but not completely standardized yet. I am using it with Babeljs which is a compiler for writing next generation JavaScript.


Update 3:
I added the difference between Object.assign and _.merge.

MongoDB: Server has startup warnings ''Access control is not enabled for the database''

Mongodb v3.4

You need to do the following to create a secure database:

Make sure the user starting the process has permissions and that the directories exist (/data/db in this case).

1) Start MongoDB without access control.

mongod --port 27017 --dbpath /data/db

2) Connect to the instance.

mongo --port 27017

3) Create the user administrator (in the admin authentication database).

use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: "abc123",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)

4) Re-start the MongoDB instance with access control.

mongod --auth --port 27017 --dbpath /data/db

5) Connect and authenticate as the user administrator.

mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"

6) Create additional users as needed for your deployment (e.g. in the test authentication database).

use test
db.createUser(
  {
    user: "myTester",
    pwd: "xyz123",
    roles: [ { role: "readWrite", db: "test" },
             { role: "read", db: "reporting" } ]
  }
)

7) Connect and authenticate as myTester.

mongo --port 27017 -u "myTester" -p "xyz123" --authenticationDatabase "test"

I basically just explained the short version of the official docs here: https://docs.mongodb.com/master/tutorial/enable-authentication/

pass **kwargs argument to another function with **kwargs

For #2 args will be only a formal parameter with dict value, but not a keyword type parameter.

If you want to pass a keyword type parameter into a keyword argument You need to specific ** before your dictionary, which means **args

check this out for more detail on using **kw

http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/

Convert array of JSON object strings to array of JS objects

If you have a JS array of JSON objects:

var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];

and you want an array of objects:

// JavaScript array of JavaScript objects
var objs = s.map(JSON.parse);

// ...or for older browsers
var objs=[];
for (var i=s.length;i--;) objs[i]=JSON.parse(s[i]);

// ...or for maximum speed:
var objs = JSON.parse('['+s.join(',')+']');

See the speed tests for browser comparisons.


If you have a single JSON string representing an array of objects:

var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';

and you want an array of objects:

// JavaScript array of JavaScript objects
var objs = JSON.parse(s);

If you have an array of objects:

// A JavaScript array of JavaScript objects
var s = [{"Select":"11", "PhotoCount":"12"},{"Select":"21", "PhotoCount":"22"}];

…and you want JSON representation for it, then:

// JSON string representing an array of objects
var json = JSON.stringify(s);

…or if you want a JavaScript array of JSON strings, then:

// JavaScript array of strings (that are each a JSON object)
var jsons = s.map(JSON.stringify);

// ...or for older browsers
var jsons=[];
for (var i=s.length;i--;) jsons[i]=JSON.stringify(s[i]);

Compare two Timestamp in java

Use the before and after methods: Javadoc

if (mytime.after(fromtime) && mytime.before(totime))

downloading all the files in a directory with cURL

Oh, I have just the thing you need!

$host = "ftp://example.com/dir/";
$savePath = "downloadedFiles";
if($check = isFtpUp($host)){

    echo $ip." -is alive<br />";

    $check = trim($check);
    $files = explode("\n",$check);

    foreach($files as $n=>$file){
        $file = trim($file);
        if($file !== "." || $file !== ".."){
            if(!saveFtpFile($file, $host.$file, $savePath)){
                // downloading failed. possible reason: $file is a folder name.
                // echo "Error downloading file.<br />";
            }else{
                echo "File: ".$file." - saved!<br />";
            }
        }else{
            // do nothing
        }
    }
}else{
    echo $ip." - is down.<br />";
}

and functions isFtpUp and saveFtpFile are as follows:

function isFtpUp($host){
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $host);
curl_setopt($ch, CURLOPT_USERPWD, "anonymous:[email protected]");
curl_setopt($ch, CURLOPT_FTPLISTONLY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);

$result = curl_exec($ch);

return $result;

}

function saveFtpFile( $targetFile = null, $sourceFile = null, $savePath){

// function settings
set_time_limit(60);
$timeout = 60;
$ftpuser = "anonymous";
$ftppassword = "[email protected]";
$savePath = "downloadedFiles"; // should exist!
$curl = curl_init();
$file = @fopen ($savePath.'/'.$targetFile, 'w');

if(!$file){
    return false;
}

curl_setopt($curl, CURLOPT_URL, $sourceFile);
curl_setopt($curl, CURLOPT_USERPWD, $ftpuser.':'.$ftppassword);

// curl settings

// curl_setopt($curl, CURLOPT_FAILONERROR, 1);
// curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_FILE, $file);

$result = curl_exec($curl);


if(!$result){
    return false;
}

curl_close($curl);
fclose($file);

return $result;
}

EDIT:

it's a php script. save it as a .php file, put it on your webserver, change $ip to address(need not be ip) of ftp server you want to download files from, create a directory named downloadedFiles on the same directory as this file.

Exporting result of select statement to CSV format in DB2

This is how you can do it from DB2 client.

  1. Open the Command Editor and Run the select Query in the Commands Tab.

  2. Open the corresponding Query Results Tab

  3. Then from Menu --> Selected --> Export

Node.js - use of module.exports as a constructor

The example code is:

in main

square(width,function (data)
{
   console.log(data.squareVal);
});

using the following may works

exports.square = function(width,callback)
{
     var aa = new Object();
     callback(aa.squareVal = width * width);    
}

How to make Python speak

If you are using python 3 and windows 10, the best solution that I found to be working is from Giovanni Gianni. This played for me in the male voice:

import win32com.client as wincl
speak = wincl.Dispatch("SAPI.SpVoice")
speak.Speak("This is the pc voice speaking")

I also found this video on youtube so if you really want to, you can get someone you know and make your own DIY tts voice.