Programs & Examples On #System.web.caching

Find records from one table which don't exist in another

SELECT name, phone_number FROM Call a
WHERE a.phone_number NOT IN (SELECT b.phone_number FROM Phone_book b)

Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."

I got this error sporadically when using an async method. Has not happened since I switched to a synchronous method.

Errors sporadically:

[Authorize(Roles = "Admin")]
[HttpDelete]
[Route("file/{id}/{customerId}/")]
public async Task<IHttpActionResult> Delete(int id, int customerId)
{
    var file = new Models.File() { Id = id, CustomerId = customerId };
    db.Files.Attach(file);
    db.Files.Remove(file);

    await db.SaveChangesAsync();

    return Ok();
}

Works all the time:

[Authorize(Roles = "Admin")]
[HttpDelete]
[Route("file/{id}/{customerId}/")]
public IHttpActionResult Delete(int id, int customerId)
{
    var file = new Models.File() { Id = id, CustomerId = customerId };
    db.Files.Attach(file);
    db.Files.Remove(file);

    db.SaveChanges();

    return Ok();
}

Download a div in a HTML page as pdf using javascript

Content inside a <div class='html-content'>....</div> can be downloaded as pdf with styles using jspdf & html2canvas.

You need to refer both js libraries,

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>

Then call below function,

//Create PDf from HTML...
function CreatePDFfromHTML() {
    var HTML_Width = $(".html-content").width();
    var HTML_Height = $(".html-content").height();
    var top_left_margin = 15;
    var PDF_Width = HTML_Width + (top_left_margin * 2);
    var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
    var canvas_image_width = HTML_Width;
    var canvas_image_height = HTML_Height;

    var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;

    html2canvas($(".html-content")[0]).then(function (canvas) {
        var imgData = canvas.toDataURL("image/jpeg", 1.0);
        var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
        pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height);
        for (var i = 1; i <= totalPDFPages; i++) { 
            pdf.addPage(PDF_Width, PDF_Height);
            pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height*i)+(top_left_margin*4),canvas_image_width,canvas_image_height);
        }
        pdf.save("Your_PDF_Name.pdf");
        $(".html-content").hide();
    });
}

Ref: pdf genration from html canvas and jspdf.

May be this will help someone.

How do I run a file on localhost?

Think of it this way.

Anything that you type after localhost/ is the path inside the root directory of your server(www or htdocs).

You don't need to specify the complete path of the file you want to run but just the path after the root folder because putting localhost/ takes you inside the root folder itself.

Key Listeners in python?

Although I like using the keyboard module to capture keyboard events, I don't like its record() function because it returns an array like [KeyboardEvent("A"), KeyboardEvent("~")], which I find kind of hard to read. So, to record keyboard events, I like to use the keyboard module and the threading module simultaneously, like this:

import keyboard
import string
from threading import *


# I can't find a complete list of keyboard keys, so this will have to do:
keys = list(string.ascii_lowercase)
"""
Optional code(extra keys):

keys.append("space_bar")
keys.append("backspace")
keys.append("shift")
keys.append("esc")
"""
def listen(key):
    while True:
        keyboard.wait(key)
        print("[+] Pressed",key)
threads = [Thread(target=listen, kwargs={"key":key}) for key in keys]
for thread in threads:
    thread.start()

JavaFX Application Icon

Toggle icons in runtime:

In addition to the responses here, I found that once you have assigned an Icon to your application by the first time you cannot toggle it by just adding a new icon to your stage (this would be helpful if you need to toggle the icon of your app from on/off enabled/disabled).

To set a new icon during run time use the getIcons().remove(0) before trying to add a new icon, where 0 is the index of the icon you want to override like is shown here:

//Setting icon by first time (You can do this on your start method).
stage.getIcons().add(new Image(getClass().getResourceAsStream("enabled.png")));

//Overriding app icon with a new status (This can be in another method)
stage.getIcons().remove(0);
stage.getIcons().add(new Image(getClass().getResourceAsStream("disabled.png")));

To access the stage from other methods or classes you can create a new static field for stage in you main class so can access it from out of the start() method by encapsulating in on a static method that you can access from anywhere in your app.

public class MainApp extends Application {
    private static Stage stage;
    public static Stage getStage() { return stage; }

    @Override public void start(Stage primaryStage) {
        stage = primaryStage
        stage.getIcons().add(new Image(getClass().getResourceAsStream("enabled.png")));
    }
}

public class AnotherClass {
    public void setStageTitle(String newTitle) {
        MainApp.getStage().setTitle(newTitle);
        MainApp.getStage().getIcons().remove(0);
        MainApp.getStage().getIcons().add(new Image(getClass().getResourceAsStream("disabled.png")));
    }
}

How to set the image from drawable dynamically in android?

imageview= (ImageView)findViewById(R.id.imageView);
imageview.setImageResource(R.drawable.mydrawable);

python-pandas and databases like mysql

import the module

import pandas as pd
import oursql

connect

conn=oursql.connect(host="localhost",user="me",passwd="mypassword",db="classicmodels")
sql="Select customerName, city,country from customers order by customerName,country,city"
df_mysql = pd.read_sql(sql,conn)
print df_mysql

That works just fine and using pandas.io.sql frame_works (with the deprecation warning). Database used is the sample database from mysql tutorial.

How to import a CSS file in a React Component

CSS Modules let you use the same CSS class name in different files without worrying about naming clashes.

Button.module.css

.error {
  background-color: red;
}

another-stylesheet.css

.error {
  color: red;
}

Button.js

import React, { Component } from 'react';
import styles from './Button.module.css'; // Import css modules stylesheet as styles
import './another-stylesheet.css'; // Import regular stylesheet
class Button extends Component {
  render() {
    // reference as a js object
    return <button className={styles.error}>Error Button</button>;
  }
}

What is the difference between a static and const variable?

static keyword defines the scope of variables whereas const keyword defines the value of variable that can't be changed during program execution

What is href="#" and why is it used?

Unfortunately, the most common use of <a href="#"> is by lazy programmers who want clickable non-hyperlink javascript-coded elements that behave like anchors, but they can't be arsed to add cursor: pointer; or :hover styles to a class for their non-hyperlink elements, and are additionally too lazy to set href to javascript:void(0);.

The problem with this is that one <a href="#" onclick="some_function();"> or another inevitably ends up with a javascript error, and an anchor with an onclick javascript error always ends up following its href. Normally this ends up being an annoying jump to the top of the page, but in the case of sites using <base>, <a href="#"> is handled as <a href="[base href]/#">, resulting in an unexpected navigation. If any logable errors are being generated, you won't see them in the latter case unless you enable persistent logs.

If an anchor element is used as a non-anchor it should have its href set to javascript:void(0); for the sake of graceful degradation.

I just wasted two days debugging a random unexpected page redirect that should have simply refreshed the page, and finally tracked it down to a function raising the click event of an <a href="#">. Replacing the # with javascript:void(0); fixed it.

The first thing I'm doing Monday is purging the project of all instances of <a href="#">.

I don't have "Dynamic Web Project" option in Eclipse new Project wizard

Make sure to check dynamic web app in "other section" i.e File>New>Other>Web or type in "dynamic web app" in your wizard filter. If dynamic web app is not there then follow following steps:

  1. On Eclipse Menu Select HELP > INSTALL NEW SOFTWARE
  2. In work with test box simply type in your eclipse version, which is oxygen in my case
  3. Once you type in yur version something like this "Oxygen - http://download.eclipse.org/releases/oxygen"will be recommended to you in drop down
  4. If you do not get any recommendation then simply copy " http://download.eclipse.org/releases/your-version" and paste it. Make sure to edit your-version.
  5. After you Enter the address and press enter bunch of new softwares will be listed just ubderneath work with text box.
  6. Scroll, find and Expand WEB, XML, Java EE .... tab
  7. Select only these three options: Eclipse Java EE Developer Tools, Eclipse Java Web Developer Tools,Eclipse Web Developer Tools
  8. Next, next and finish!

what is the difference between uint16_t and unsigned short int incase of 64 bit processor?

uint16_t is unsigned 16-bit integer.

unsigned short int is unsigned short integer, but the size is implementation dependent. The standard only says it's at least 16-bit (i.e, minimum value of UINT_MAX is 65535). In practice, it usually is 16-bit, but you can't take that as guaranteed.

Note:

  1. If you want a portable unsigned 16-bit integer, use uint16_t.
  2. inttypes.h and stdint.h are both introduced in C99. If you are using C89, define your own type.
  3. uint16_t may not be provided in certain implementation(See reference below), but unsigned short int is always available.

Reference: C11(ISO/IEC 9899:201x) §7.20 Integer types

For each type described herein that the implementation provides) shall declare that typedef name and define the associated macros. Conversely, for each type described herein that the implementation does not provide, shall not declare that typedef name nor shall it define the associated macros. An implementation shall provide those types described as ‘‘required’’, but need not provide any of the others (described as ‘optional’’).

Error : No resource found that matches the given name (at 'icon' with value '@drawable/icon')

In my case, I use Xamarin with Visual Studio 2013. I create Blank App (Android) then deploy without any code update.

You can try:

  • Make sure that icon.png (or whatever files mentioned in the application android:icon tag) is present in the drawable-hdpi folder inside res folder of Android project.

  • If it shows the error even if the icon.png is present,then remove the statement application android:icon from the AndroidManifest.xml and add it again.

  • Check your project folder's path. If it is too long, or contains space, or contains any unicode character, try to relocated.

Better way to find control in ASP.NET

https://blog.codinghorror.com/recursive-pagefindcontrol/

Page.FindControl("DataList1:_ctl0:TextBox3");

OR

private Control FindControlRecursive(Control root, string id)
{
    if (root.ID == id)
    {
        return root;
    }
    foreach (Control c in root.Controls)
    {
        Control t = FindControlRecursive(c, id);
        if (t != null)
        {
            return t;
        }
    }
    return null;
}

How do you create a remote Git branch?

Now with git, you can just type, when you are in the correct branch

git push --set-upstream origin <remote-branch-name>

and git create for you the origin branch.

$(document).ready shorthand

The shorthand for $(document).ready(handler) is $(handler) (where handler is a function). See here.

The code in your question has nothing to do with .ready(). Rather, it is an immediately-invoked function expression (IIFE) with the jQuery object as its argument. Its purpose is to restrict the scope of at least the $ variable to its own block so it doesn't cause conflicts. You typically see the pattern used by jQuery plugins to ensure that $ == jQuery.

How to test if list element exists?

This is actually a bit trickier than you'd think. Since a list can actually (with some effort) contain NULL elements, it might not be enough to check is.null(foo$a). A more stringent test might be to check that the name is actually defined in the list:

foo <- list(a=42, b=NULL)
foo

is.null(foo[["a"]]) # FALSE
is.null(foo[["b"]]) # TRUE, but the element "exists"...
is.null(foo[["c"]]) # TRUE

"a" %in% names(foo) # TRUE
"b" %in% names(foo) # TRUE
"c" %in% names(foo) # FALSE

...and foo[["a"]] is safer than foo$a, since the latter uses partial matching and thus might also match a longer name:

x <- list(abc=4)
x$a  # 4, since it partially matches abc
x[["a"]] # NULL, no match

[UPDATE] So, back to the question why exists('foo$a') doesn't work. The exists function only checks if a variable exists in an environment, not if parts of a object exist. The string "foo$a" is interpreted literary: Is there a variable called "foo$a"? ...and the answer is FALSE...

foo <- list(a=42, b=NULL) # variable "foo" with element "a"
"bar$a" <- 42   # A variable actually called "bar$a"...
ls() # will include "foo" and "bar$a" 
exists("foo$a") # FALSE 
exists("bar$a") # TRUE

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

Here is a working example.

Keypoints are:

  • Declaration of Accounts
  • Use of JsonProperty attribute

.

using (WebClient wc = new WebClient())
{
    var json = wc.DownloadString("http://coderwall.com/mdeiters.json");
    var user = JsonConvert.DeserializeObject<User>(json);
}

-

public class User
{
    /// <summary>
    /// A User's username. eg: "sergiotapia, mrkibbles, matumbo"
    /// </summary>
    [JsonProperty("username")]
    public string Username { get; set; }

    /// <summary>
    /// A User's name. eg: "Sergio Tapia, John Cosack, Lucy McMillan"
    /// </summary>
    [JsonProperty("name")]
    public string Name { get; set; }

    /// <summary>
    /// A User's location. eh: "Bolivia, USA, France, Italy"
    /// </summary>
    [JsonProperty("location")]
    public string Location { get; set; }

    [JsonProperty("endorsements")]
    public int Endorsements { get; set; } //Todo.

    [JsonProperty("team")]
    public string Team { get; set; } //Todo.

    /// <summary>
    /// A collection of the User's linked accounts.
    /// </summary>
    [JsonProperty("accounts")]
    public Account Accounts { get; set; }

    /// <summary>
    /// A collection of the User's awarded badges.
    /// </summary>
    [JsonProperty("badges")]
    public List<Badge> Badges { get; set; }
}

public class Account
{
    public string github;
}

public class Badge
{
    [JsonProperty("name")]
    public string Name;
    [JsonProperty("description")]
    public string Description;
    [JsonProperty("created")]
    public string Created;
    [JsonProperty("badge")]
    public string BadgeUrl;
}

How to square all the values in a vector in R?

How about sapply (not really necessary for this simple case):

newData<- sapply(data, function(x) x^2)

How to install SQL Server 2005 Express in Windows 8

I found that on Windows 8.1 with an instance of SQL 2014 already installed, if I ran the SQLEXPR.EXE and then dismissed the Windows 'warning this may be incompatible' dialogs, that the installer completed successfully.

I suspect having 2014 bits already in place probably helped.

Get a DataTable Columns DataType

What you want to use is this property:

dt.Columns[0].DataType

The DataType property will set to one of the following:

Boolean
Byte
Char
DateTime
Decimal
Double
Int16
Int32
Int64
SByte
Single
String
TimeSpan
UInt16
UInt32
UInt64

DataColumn.DataType Property MSDN Reference

Form Submit jQuery does not work

Since every control element gets referenced with its name on the form element (see forms specs), controls with name "submit" will override the build-in submit function.

Which leads to the error mentioned in comments above:

Uncaught TypeError: Property 'submit' of object #<HTMLFormElement> is not a function

As in the accepted answer above the simplest solution would be to change the name of that control element.

However another solution could be to use dispatchEvent method on form element:

$("#form_id")[0].dispatchEvent(new Event('submit')); 

Trying to Validate URL Using JavaScript

You can use the URL API that is recently standard. Browser support is sketchy at best, see the link. new URL(str) is guaranteed to throw TypeError for invalid URLs.

As stated above, http://wwww is a valid URL.

How best to determine if an argument is not sent to the JavaScript function

In ES6 (ES2015) you can use Default parameters

_x000D_
_x000D_
function Test(arg1 = 'Hello', arg2 = 'World!'){_x000D_
  alert(arg1 + ' ' +arg2);_x000D_
}_x000D_
_x000D_
Test('Hello', 'World!'); // Hello World!_x000D_
Test('Hello'); // Hello World!_x000D_
Test(); // Hello World!
_x000D_
_x000D_
_x000D_

Connection Strings for Entity Framework

What I understand is you want same connection string with different Metadata in it. So you can use a connectionstring as given below and replace "" part. I have used your given connectionString in same sequence.

connectionString="<METADATA>provider=System.Data.SqlClient;provider connection string=&quot;Data Source=SomeServer;Initial Catalog=SomeCatalog;Persist Security Info=True;User ID=Entity;Password=SomePassword;MultipleActiveResultSets=True&quot;"

For first connectionString replace <METADATA> with "metadata=res://*/ModEntity.csdl|res://*/ModEntity.ssdl|res://*/ModEntity.msl;"

For second connectionString replace <METADATA> with "metadata=res://*/Entity.csdl|res://*/Entity.ssdl|res://*/Entity.msl;"

For third connectionString replace <METADATA> with "metadata=res://*/Entity.csdl|res://*/Entity.ssdl|res://*/Entity.msl|res://*/ModEntity.csdl|res://*/ModEntity.ssdl|res://*/ModEntity.msl;"

Happy coding!

error running apache after xampp install

After changing main port from 80 to 8080 you have to change the config in XAMPP control panel as I show in the images:

1) enter image description here

2) enter image description here

3) enter image description here

Then restart the service and that's it !

Inner Joining three tables

try this:

SELECT * FROM TableA
JOIN TableB ON TableA.primary_key = TableB.foreign_key 
JOIN TableB ON TableB.foreign_key = TableC.foreign_key

How to set maximum fullscreen in vmware?

Go to view and press "Switch to scale mode" which will adjust the virtual screen when you adjust the application.

Where should my npm modules be installed on Mac OS X?

npm root -g

to check the npm_modules global location

How do I perform an insert and return inserted identity with Dapper?

The InvalidCastException you are getting is due to SCOPE_IDENTITY being a Decimal(38,0).

You can return it as an int by casting it as follows:

string sql = @"
INSERT INTO [MyTable] ([Stuff]) VALUES (@Stuff);
SELECT CAST(SCOPE_IDENTITY() AS INT)";

int id = connection.Query<int>(sql, new { Stuff = mystuff}).Single();

How do I uniquely identify computers visiting my web site?

I think cookies might be what you are looking for; this is how most websites uniquely identify visitors.

How to read PDF files using Java?

PDFBox contains tools for text extraction.

iText has more low-level support for text manipulation, but you'd have to write a considerable amount of code to get text extraction.

iText in Action contains a good overview of the limitations of text extraction from PDF, regardless of the library used (Section 18.2: Extracting and editing text), and a convincing explanation why the library does not have text extraction support. In short, it's relatively easy to write a code that will handle simple cases, but it's basically impossible to extract text from PDF in general.

Getting only Month and Year from SQL DATE

Get Month & Year From Date

DECLARE @lcMonth nvarchar(10)
DECLARE @lcYear nvarchar(10)

SET @lcYear=(SELECT  DATEPART(YEAR,@Date))
SET @lcMonth=(SELECT  DATEPART(MONTH,@Date))

Initialising a multidimensional array in Java

You can also use the following construct:

String[][] myStringArray = new String [][] { { "X0", "Y0"},
                                             { "X1", "Y1"},
                                             { "X2", "Y2"},
                                             { "X3", "Y3"},
                                             { "X4", "Y4"} };

Converting String to "Character" array in Java

if you are working with JTextField then it can be helpfull..

public JTextField display;
String number=e.getActionCommand();

display.setText(display.getText()+number);

ch=number.toCharArray();
for( int i=0; i<ch.length; i++)
    System.out.println("in array a1= "+ch[i]);

How to fetch the row count for all tables in a SQL SERVER database

Don't use SELECT COUNT(*) FROM TABLENAME, since that is a resource intensive operation. One should use SQL Server Dynamic Management Views or System Catalogs to get the row count information for all tables in a database.

How to get a list of programs running with nohup

Instead of nohup, you should use screen. It achieves the same result - your commands are running "detached". However, you can resume screen sessions and get back into their "hidden" terminal and see recent progress inside that terminal.

screen has a lot of options. Most often I use these:

To start first screen session or to take over of most recent detached one:

screen -Rd 

To detach from current session: Ctrl+ACtrl+D

You can also start multiple screens - read the docs.

Application not picking up .css file (flask/python)

The flask project structure is different. As you mentioned in question the project structure is the same but the only problem is wit the styles folder. Styles folder must come within the static folder.

static/styles/style.css

Eclipse Build Path Nesting Errors

The accepted solution didn't work for me but I did some digging on the project settings.

The following solution fixed it for me at least IF you are using a Dynamic Web Project:

  1. Right click on the project then properties. (or alt-enter on the project)
  2. Under Deployment Assembly remove "src".

You should be able to add the src/main/java. It also automatically adds it to Deployment Assembly.

Caveat: If you added a src/test/java note that it also adds it to Deployment Assembly. Generally, you don't need this. You may remove it.

How to import and export components using React + ES6 + webpack?

I Hope this is Helpfull

Step 1: App.js is (main module) import the Login Module

import React, { Component } from 'react';
import './App.css';
import Login from './login/login';

class App extends Component {
  render() {
    return (
      <Login />
    );
  }
}

export default App;

Step 2: Create Login Folder and create login.js file and customize your needs it automatically render to App.js Example Login.js

import React, { Component } from 'react';
import '../login/login.css';

class Login extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

export default Login;

Java: unparseable date exception

What you're basically doing here is relying on Date#toString() which already has a fixed pattern. To convert a Java Date object into another human readable String pattern, you need SimpleDateFormat#format().

private String modifyDateLayout(String inputDate) throws ParseException{
    Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").parse(inputDate);
    return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date);
}

By the way, the "unparseable date" exception can here only be thrown by SimpleDateFormat#parse(). This means that the inputDate isn't in the expected pattern "yyyy-MM-dd HH:mm:ss z". You'll probably need to modify the pattern to match the inputDate's actual pattern.

Update: Okay, I did a test:

public static void main(String[] args) throws Exception {
    String inputDate = "2010-01-04 01:32:27 UTC";
    String newDate = new Test().modifyDateLayout(inputDate);
    System.out.println(newDate);
}

This correctly prints:

03.01.2010 21:32:27

(I'm on GMT-4)

Update 2: as per your edit, you really got a ParseException on that. The most suspicious part would then be the timezone of UTC. Is this actually known at your Java environment? What Java version and what OS version are you using? Check TimeZone.getAvailableIDs(). There must be a UTC in between.

How to close a Tkinter window by pressing a Button?

from tkinter import *

window = tk()
window.geometry("300x300")

def close_window (): 

    window.destroy()

button = Button ( text = "Good-bye", command = close_window)
button.pack()

window.mainloop()

Example of waitpid() in use?

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int main (){
    int pid;
    int status;

    printf("Parent: %d\n", getpid());

    pid = fork();
    if (pid == 0){
        printf("Child %d\n", getpid());
        sleep(2);
        exit(EXIT_SUCCESS);
    }

//Comment from here to...
    //Parent waits process pid (child)
    waitpid(pid, &status, 0);
    //Option is 0 since I check it later

    if (WIFSIGNALED(status)){
        printf("Error\n");
    }
    else if (WEXITSTATUS(status)){
        printf("Exited Normally\n");
    }
//To Here and see the difference
    printf("Parent: %d\n", getpid());

    return 0;
}

Unused arguments in R

The R.utils package has a function called doCall which is like do.call, but it does not return an error if unused arguments are passed.

multiply <- function(a, b) a * b

# these will fail
multiply(a = 20, b = 30, c = 10)
# Error in multiply(a = 20, b = 30, c = 10) : unused argument (c = 10)
do.call(multiply, list(a = 20, b = 30, c = 10))
# Error in (function (a, b)  : unused argument (c = 10)

# R.utils::doCall will work
R.utils::doCall(multiply, args = list(a = 20, b = 30, c = 10))
# [1] 600
# it also does not require the arguments to be passed as a list
R.utils::doCall(multiply, a = 20, b = 30, c = 10)
# [1] 600

VBA module that runs other modules

Is "Module1" part of the same workbook that contains "moduleController"?
If not, you could call public method of "Module1" using Application.Run someWorkbook.xlsm!methodOfModule.

SQL Server SELECT LAST N Rows

Try using the EXCEPT syntax.
Something like this:

   SELECT * 
    FROM   clientDetails 
    EXCEPT 
    (SELECT TOP (numbers of rows - how many rows you want) * 
     FROM   clientDetails) 

a page can have only one server-side form tag

please remove " runat="server" " from "form" tag then it will definetly works.

how to align all my li on one line?

I think the NOBR tag might be overkill, and as you said, unreliable.

There are 2 options available depending on how you are displaying the text.

If you are displaying text in a table cell you would do Long Text Here. If you are using a div or a span, you can use the style="white-space: nowrap;"

How to use if, else condition in jsf to display image

For those like I who just followed the code by skuntsel and received a cryptic stack trace, allow me to save you some time.

It seems c:if cannot by itself be followed by c:otherwise.

The correct solution is as follows:

<c:choose>
    <c:when test="#{some.test}">
        <p>some.test is true</p>
    </c:when>
    <c:otherwise>
        <p>some.test is not true</p>
    </c:otherwise>
</c:choose>

You can add additional c:when tests in as necessary.

Python: Binding Socket: "Address already in use"

You need to set the allow_reuse_address before binding. Instead of the SimpleHTTPServer run this snippet:

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler, bind_and_activate=False)
httpd.allow_reuse_address = True
httpd.server_bind()
httpd.server_activate()
httpd.serve_forever()

This prevents the server from binding before we got a chance to set the flags.

Update multiple rows with different values in a single SQL query

Use a comma ","

eg: 
UPDATE my_table SET rowOneValue = rowOneValue + 1, rowTwoValue  = rowTwoValue + ( (rowTwoValue / (rowTwoValue) ) + ?) * (v + 1) WHERE value = ?

Spring Boot @Value Properties

To read the values from application.properties we need to just annotate our main class with @SpringBootApplication and the class where you are reading with @Component or variety of it. Below is the sample where I have read the values from application.properties and it is working fine when web service is invoked. If you deploy the same code as is and try to access from http://localhost:8080/hello you will get the value you have stored in application.properties for the key message.

package com.example;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class DemoApplication {

    @Value("${message}")
    private String message;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @RequestMapping("/hello")
    String home() {
        return message;
    }

}

Try and let me know

Meaning of .Cells(.Rows.Count,"A").End(xlUp).row

It is used to find the how many rows contain data in a worksheet that contains data in the column "A". The full usage is

 lastRowIndex = ws.Cells(ws.Rows.Count, "A").End(xlUp).row

Where ws is a Worksheet object. In the questions example it was implied that the statement was inside a With block

With ws
    lastRowIndex = .Cells(.Rows.Count, "A").End(xlUp).row
End With
  1. ws.Rows.Count returns the total count of rows in the worksheet (1048576 in Excel 2010).
  2. .Cells(.Rows.Count, "A") returns the bottom most cell in column "A" in the worksheet

Then there is the End method. The documentation is ambiguous as to what it does.

Returns a Range object that represents the cell at the end of the region that contains the source range

Particularly it doesn't define what a "region" is. My understanding is a region is a contiguous range of non-empty cells. So the expected usage is to start from a cell in a region and find the last cell in that region in that direction from the original cell. However there are multiple exceptions for when you don't use it like that:

  • If the range is multiple cells, it will use the region of rng.cells(1,1).
  • If the range isn't in a region, or the range is already at the end of the region, then it will travel along the direction until it enters a region and return the first encountered cell in that region.
  • If it encounters the edge of the worksheet it will return the cell on the edge of that worksheet.

So Range.End is not a trivial function.

  1. .row returns the row index of that cell.

Passing Objects By Reference or Value in C#

I guess its clearer when you do it like this. I recommend downloading LinqPad to test things like this.

void Main()
{
    var Person = new Person(){FirstName = "Egli", LastName = "Becerra"};

    //Will update egli
    WontUpdate(Person);
    Console.WriteLine("WontUpdate");
    Console.WriteLine($"First name: {Person.FirstName}, Last name: {Person.LastName}\n");

    UpdateImplicitly(Person);
    Console.WriteLine("UpdateImplicitly");
    Console.WriteLine($"First name: {Person.FirstName}, Last name: {Person.LastName}\n");

    UpdateExplicitly(ref Person);
    Console.WriteLine("UpdateExplicitly");
    Console.WriteLine($"First name: {Person.FirstName}, Last name: {Person.LastName}\n");
}

//Class to test
public class Person{
    public string FirstName {get; set;}
    public string LastName {get; set;}

    public string printName(){
        return $"First name: {FirstName} Last name:{LastName}";
    }
}

public static void WontUpdate(Person p)
{
    //New instance does jack...
    var newP = new Person(){FirstName = p.FirstName, LastName = p.LastName};
    newP.FirstName = "Favio";
    newP.LastName = "Becerra";
}

public static void UpdateImplicitly(Person p)
{
    //Passing by reference implicitly
    p.FirstName = "Favio";
    p.LastName = "Becerra";
}

public static void UpdateExplicitly(ref Person p)
{
    //Again passing by reference explicitly (reduntant)
    p.FirstName = "Favio";
    p.LastName = "Becerra";
}

And that should output

WontUpdate

First name: Egli, Last name: Becerra

UpdateImplicitly

First name: Favio, Last name: Becerra

UpdateExplicitly

First name: Favio, Last name: Becerra

Get final URL after curl is redirected

curl can only follow http redirects. To also follow meta refresh directives and javascript redirects, you need a full-blown browser like headless chrome:

#!/bin/bash
real_url () {
    printf 'location.href\nquit\n' | \
    chromium-browser --headless --disable-gpu --disable-software-rasterizer \
    --disable-dev-shm-usage --no-sandbox --repl "$@" 2> /dev/null \
    | tr -d '>>> ' | jq -r '.result.value'
}

If you don't have chrome installed, you can use it from a docker container:

#!/bin/bash
real_url () {
    printf 'location.href\nquit\n' | \
    docker run -i --rm --user "$(id -u "$USER")" --volume "$(pwd)":/usr/src/app \
    zenika/alpine-chrome --no-sandbox --repl "$@" 2> /dev/null \
    | tr -d '>>> ' | jq -r '.result.value'
}

Like so:

$ real_url http://dx.doi.org/10.1016/j.pgeola.2020.06.005 
https://www.sciencedirect.com/science/article/abs/pii/S0016787820300638?via%3Dihub

Detecting user leaving page with react-router

Using history.listen

For example like below:

In your component,

componentWillMount() {
    this.props.history.listen(() => {
      // Detecting, user has changed URL
      console.info(this.props.history.location.pathname);
    });
}

Java - Reading XML file

Avoid hardcoding try making the code that is dynamic below is the code it will work for any xml I have used SAX Parser you can use dom,xpath it's upto you I am storing all the tags name and values in the map after that it becomes easy to retrieve any values you want I hope this helps
SAMPLE XML:

<parent>
<child >
    <child1> value 1 </child1>
    <child2> value 2 </child2>
    <child3> value 3 </child3>
    </child>
    <child >
     <child4> value 4 </child4>
    <child5> value 5</child5>
    <child6> value 6 </child6>
    </child>
  </parent>

JAVA CODE:

 import java.io.File;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.LinkedHashMap;
    import java.util.Map;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;


    public class saxParser {
           static Map<String,String> tmpAtrb=null;
           static Map<String,String> xmlVal= new LinkedHashMap<String, String>();
        public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, VerifyError {

            /**
             * We can pass the class name of the XML parser
             * to the SAXParserFactory.newInstance().
             */

            //SAXParserFactory saxDoc = SAXParserFactory.newInstance("com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl", null);

            SAXParserFactory saxDoc = SAXParserFactory.newInstance();
            SAXParser saxParser = saxDoc.newSAXParser();

            DefaultHandler handler = new DefaultHandler() {
                String tmpElementName = null;
                String tmpElementValue = null;


                @Override
                public void startElement(String uri, String localName, String qName, 
                                                                    Attributes attributes) throws SAXException {
                    tmpElementValue = "";
                    tmpElementName = qName;
                    tmpAtrb=new HashMap();
                    //System.out.println("Start Element :" + qName);
                    /**
                     * Store attributes in HashMap
                     */
                    for (int i=0; i<attributes.getLength(); i++) {
                        String aname = attributes.getLocalName(i);
                        String value = attributes.getValue(i);
                        tmpAtrb.put(aname, value);
                    }

                }

                @Override
                public void endElement(String uri, String localName, String qName) 
                                                            throws SAXException { 

                    if(tmpElementName.equals(qName)){
                        System.out.println("Element Name :"+tmpElementName);
                    /**
                     * Retrive attributes from HashMap
                     */                    for (Map.Entry<String, String> entrySet : tmpAtrb.entrySet()) {
                            System.out.println("Attribute Name :"+ entrySet.getKey() + "Attribute Value :"+ entrySet.getValue());
                        }
                        System.out.println("Element Value :"+tmpElementValue);
                        xmlVal.put(tmpElementName, tmpElementValue);
                        System.out.println(xmlVal);
                      //Fetching The Values From The Map
                        String getKeyValues=xmlVal.get(tmpElementName);
                        System.out.println("XmlTag:"+tmpElementName+":::::"+"ValueFetchedFromTheMap:"+getKeyValues);   
                    }   
                }
                @Override
                public void characters(char ch[], int start, int length) throws SAXException {
                    tmpElementValue = new String(ch, start, length) ;  
                } 
            };
            /**
             * Below two line used if we use SAX 2.0
             * Then last line not needed.
             */

            //saxParser.setContentHandler(handler);
            //saxParser.parse(new InputSource("c:/file.xml"));
            saxParser.parse(new File("D:/Test _ XML/file.xml"), handler);
        }  
    }

OUTPUT:

Element Name :child1
Element Value : value 1 
XmlTag:<child1>:::::ValueFetchedFromTheMap: value 1 
Element Name :child2
Element Value : value 2 
XmlTag:<child2>:::::ValueFetchedFromTheMap: value 2 
Element Name :child3
Element Value : value 3 
XmlTag:<child3>:::::ValueFetchedFromTheMap: value 3 
Element Name :child4
Element Value : value 4 
XmlTag:<child4>:::::ValueFetchedFromTheMap: value 4 
Element Name :child5
Element Value : value 5
XmlTag:<child5>:::::ValueFetchedFromTheMap: value 5
Element Name :child6
Element Value : value 6 
XmlTag:<child6>:::::ValueFetchedFromTheMap: value 6 
Values Inside The Map:{child1= value 1 , child2= value 2 , child3= value 3 , child4= value 4 , child5= value 5, child6= value 6 }

Generic htaccess redirect www to non-www

RewriteEngine on
# if host value starts with "www."
RewriteCond %{HTTP_HOST} ^www\.
# redirect the request to "non-www"
RewriteRule ^ http://example.com%{REQUEST_URI} [NE,L,R]

If you want to remove www on both http and https , use the following :

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTPS}s ^on(s)|offs
RewriteRule ^ http%1://example.com%{REQUEST_URI} [NE,L,R]

This redirects Non ssl

to

And SSL

to

on apache 2.4.* you can accomplish this using a Redirect with if directive,

<if "%{HTTP_HOST} =='www.example.com'">
Redirect / http://example.com/
</if>

HTML input arrays

Follow it...

<form action="index.php" method="POST">
<input type="number" name="array[]" value="1">
<input type="number" name="array[]" value="2">
<input type="number" name="array[]" value="3"> <!--taking array input by input name array[]-->
<input type="number" name="array[]" value="4">
<input type="submit" name="submit">
</form>
<?php
$a=$_POST['array'];
echo "Input :" .$a[3];  // Displaying Selected array Value
foreach ($a as $v) {
    print_r($v); //print all array element.
}
?>

How to display all elements in an arraylist?

Hi sorry the code for the second one should be:

private static void getAll(CarList c1) {

ArrayList <Car> cars = c1.getAll(); // error incompatible type
for(Car item : cars)
{   
      System.out.println(item.getMake()
                       + " "
                       + item.getReg()
                       );
}

}

I have a class called CarList which contains the arraylist and its method, so in the tester class, i have basically this code to use that CarList class:

CarList c1; c1 = new CarList();

everything else works, such as adding and removing cars and displaying an inidividual car, i just need a code to display all cars in the arraylist.

Store text file content line by line into array

You need to do something like this for your case:-

int i = 0;
while((str = in.readLine()) != null){
    arr[i] = str;
    i++;
}

But note that the arr should be declared properly, according to the number of entries in your file.

Suggestion:- Use a List instead(Look at @Kevin Bowersox post for that)

std::wstring VS std::string

I frequently use std::string to hold utf-8 characters without any problems at all. I heartily recommend doing this when interfacing with API's which use utf-8 as the native string type as well.

For example, I use utf-8 when interfacing my code with the Tcl interpreter.

The major caveat is the length of the std::string, is no longer the number of characters in the string.

WebSockets vs. Server-Sent events/EventSource

Opera, Chrome, Safari supports SSE, Chrome, Safari supports SSE inside of SharedWorker Firefox supports XMLHttpRequest readyState interactive, so we can make EventSource polyfil for Firefox

Where to get "UTF-8" string literal in Java?

Class org.apache.commons.lang3.CharEncoding.UTF_8 is deprecated after Java 7 introduced java.nio.charset.StandardCharsets

  • @see JRE character encoding names
  • @since 2.1
  • @deprecated Java 7 introduced {@link java.nio.charset.StandardCharsets}, which defines these constants as
  • {@link Charset} objects. Use {@link Charset#name()} to get the string values provided in this class.
  • This class will be removed in a future release.

jQuery UI autocomplete with JSON

I use this script for autocomplete...

$('#custmoers_name').autocomplete({
    source: function (request, response) {

        // $.getJSON("<?php echo base_url('index.php/Json_cr_operation/autosearch_custmoers');?>", function (data) {
          $.getJSON("Json_cr_operation/autosearch_custmoers?term=" + request.term, function (data) {
          console.log(data);
            response($.map(data, function (value, key) {
                console.log(value);
                return {
                    label: value.label,
                    value: value.value
                };
            }));
        });
    },
    minLength: 1,
    delay: 100
});

My json return :- [{"label":"Mahesh Arun Wani","value":"1"}] after search m

but it display in dropdown [object object]...

When to use in vs ref vs out

Extra notes regarding C# 7:
In C# 7 there's no need to predeclare variables using out. So a code like this:

public void PrintCoordinates(Point p)
{
  int x, y; // have to "predeclare"
  p.GetCoordinates(out x, out y);
  WriteLine($"({x}, {y})");
}

Can be written like this:

public void PrintCoordinates(Point p)
{
  p.GetCoordinates(out int x, out int y);
  WriteLine($"({x}, {y})");
}

Source: What's new in C# 7.

Can I stop 100% Width Text Boxes from extending beyond their containers?

This works:

<div>
    <input type="text" 
        style="margin: 5px; padding: 4px; border: 1px solid; 
        width: 200px; width: calc(100% - 20px);">
</div>

The first 'width' is a fallback rule for older browsers.

How to build & install GLFW 3 and use it in a Linux project

Step 1: Installing GLFW 3 on your system with CMAKE

For this install, I was using KUbuntu 13.04, 64bit.

The first step is to download the latest version (assuming versions in the future work in a similar way) from www.glfw.org, probably using this link.

The next step is to extract the archive, and open a terminal. cd into the glfw-3.X.X directory and run cmake -G "Unix Makefiles" you may need elevated privileges, and you may also need to install build dependencies first. To do this, try sudo apt-get build-dep glfw or sudo apt-get build-dep glfw3 or do it manually, as I did using sudo apt-get install cmake xorg-dev libglu1-mesa-dev... There may be other libs you require such as the pthread libraries... Apparently I had them already. (See the -l options given to the g++ linker stage, below.)

Now you can type make and then make install, which will probably require you to sudo first.

Okay, you should get some verbose output on the last three CMake stages, telling you what has been built or where it has been placed. (In /usr/include, for example.)

Step 2: Create a test program and compile

The next step is to fire up vim ("what?! vim?!" you say) or your preferred IDE / text editor... I didn't use vim, I used Kate, because I am on KUbuntu 13.04... Anyway, download or copy the test program from here (at the bottom of the page) and save, exit.

Now compile using g++ -std=c++11 -c main.cpp - not sure if c++11 is required but I used nullptr so, I needed it... You may need to upgrade your gcc to version 4.7, or the upcoming version 4.8... Info on that here.

Then fix your errors if you typed the program by hand or tried to be "too clever" and something didn't work... Then link it using this monster! g++ main.o -o main.exec -lGL -lGLU -lglfw3 -lX11 -lXxf86vm -lXrandr -lpthread -lXi So you see, in the "install build dependencies" part, you may also want to check you have the GL, GLU, X11 Xxf86vm (whatever that is) Xrandr posix-thread and Xi (whatever that is) development libraries installed also. Maybe update your graphics drivers too, I think GLFW 3 may require OpenGL version 3 or higher? Perhaps someone can confirm that? You may also need to add the linker options -ldl -lXinerama -lXcursor to get it to work correctly if you are getting undefined references to dlclose (credit to @user2255242).

And, yes, I really did need that many -ls!

Step 3: You are finished, have a nice day!

Hopefully this information was correct and everything worked for you, and you enjoyed writing the GLFW test program. Also hopefully this guide has helped, or will help, a few people in the future who were struggling as I was today yesterday!

By the way, all the tags are the things I searched for on stackoverflow looking for an answer that didn't exist. (Until now.) Hopefully they are what you searched for if you were in a similar position to myself.

Author Note:

This might not be a good idea. This method (using sudo make install) might be harzardous to your system. (See Don't Break Debian)

Ideally I, or someone else, should propose a solution which does not just install lib files etc into the system default directories as these should be managed by package managers such as apt, and doing so may cause a conflict and break your package management system.

See the new "2020 answer" for an alternative solution.

"call to undefined function" error when calling class method

Mates,

I stumbled upon this error today while testing a simple script. I am not using "class" function though so it take it with grain of salt. I was calling function before its definition & declaration ...something like this

      try{
             foo();
         }
       catch (exception $e)
           {
            echo "$e->getMessage()";
           }

       function foo(){
                       echo "blah blah blah";
                     }

so php was throwing me error "call to undefined function ".

This kinda seem classic programming error but may help someone in need of clue.

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

I may be quite late to the party, but we can create custom foldr using simple lambda calculus and curried function. Here is my implementation of foldr in python.

def foldr(func):
    def accumulator(acc):
        def listFunc(l):
            if l:
                x = l[0]
                xs = l[1:]
                return func(x)(foldr(func)(acc)(xs))
            else:
                return acc
        return listFunc
    return accumulator  


def curried_add(x):
    def inner(y):
        return x + y
    return inner

def curried_mult(x):
    def inner(y):
        return x * y
    return inner

print foldr(curried_add)(0)(range(1, 6))
print foldr(curried_mult)(1)(range(1, 6))

Even though the implementation is recursive (might be slow), it will print the values 15 and 120 respectively

Angular 5 Button Submit On Enter Key Press

In addition to other answers which helped me, you can also add to surrounding div. In my case this was for sign on with user Name/Password fields.

<div (keyup.enter)="login()" class="container-fluid">

Why does using an Underscore character in a LIKE filter give me all the results?

Modify your WHERE condition like this:

WHERE mycolumn LIKE '%\_%' ESCAPE '\'

This is one of the ways in which Oracle supports escape characters. Here you define the escape character with the escape keyword. For details see this link on Oracle Docs.

The '_' and '%' are wildcards in a LIKE operated statement in SQL.

The _ character looks for a presence of (any) one single character. If you search by columnName LIKE '_abc', it will give you result with rows having 'aabc', 'xabc', '1abc', '#abc' but NOT 'abc', 'abcc', 'xabcd' and so on.

The '%' character is used for matching 0 or more number of characters. That means, if you search by columnName LIKE '%abc', it will give you result with having 'abc', 'aabc', 'xyzabc' and so on, but no 'xyzabcd', 'xabcdd' and any other string that does not end with 'abc'.

In your case you have searched by '%_%'. This will give all the rows with that column having one or more characters, that means any characters, as its value. This is why you are getting all the rows even though there is no _ in your column values.

How To fix white screen on app Start up?

This is my AppTheme on an example app:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:windowIsTranslucent">true</item>
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

As you can see, I have the default colors and then I added the android:windowIsTranslucent and set it to true.

As far as I know as an Android Developer, this is the only thing you need to set in order to hide the white screen on the start of the application.

How to iterate through an ArrayList of Objects of ArrayList of Objects?

Edit:

Well, he edited his post.

If an Object inherits Iterable, you are given the ability to use the for-each loop as such:

for(Object object : objectListVar) {
     //code here
}

So in your case, if you wanted to update your Guns and their Bullets:

for(Gun g : guns) {
     //invoke any methods of each gun
     ArrayList<Bullet> bullets = g.getBullets()
     for(Bullet b : bullets) {
          System.out.println("X: " + b.getX() + ", Y: " + b.getY());
          //update, check for collisions, etc
     }
}

First get your third Gun object:

Gun g = gunList.get(2);

Then iterate over the third gun's bullets:

ArrayList<Bullet> bullets = g.getBullets();

for(Bullet b : bullets) {
     //necessary code here
}

How can I get a user's media from Instagram without authenticating as a user?

11.11.2017
Since Instagram changed the way they provide this data, none of above methods work nowadays. Here is the new way to get user's media:
GET https://instagram.com/graphql/query/?query_id=17888483320059182&variables={"id":"1951415043","first":20,"after":null}
Where:
query_id - permanent value: 17888483320059182 (note it might be changed in future).
id - id of the user. It may come with list of users. To get the list of users you can use following request: GET https://www.instagram.com/web/search/topsearch/?context=blended&query=YOUR_QUERY
first - amount of items to get.
after - id of the last item if you want to get items from that id.

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

If you want your dates to conform a particular format or formats then use DateTime.TryParseExact otherwise that is the default behaviour of DateTime.TryParse

DateTime.TryParse

This method tries to ignore unrecognized data, if possible, and fills in missing month, day, and year information with the current date. If s contains only a date and no time, this method assumes the time is 12:00 midnight. If s includes a date component with a two-digit year, it is converted to a year in the current culture's current calendar based on the value of the Calendar.TwoDigitYearMax property. Any leading, inner, or trailing white space character in s is ignored.

If you want to confirm against multiple formats then look at DateTime.TryParseExact Method (String, String[], IFormatProvider, DateTimeStyles, DateTime) overload. Example from the same link:

string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
                   "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", 
                   "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", 
                   "M/d/yyyy h:mm", "M/d/yyyy h:mm", 
                   "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM", 
                        "5/1/2009 6:32:00", "05/01/2009 06:32", 
                        "05/01/2009 06:32:00 PM", "05/01/2009 06:32:00"}; 
DateTime dateValue;

foreach (string dateString in dateStrings)
{
   if (DateTime.TryParseExact(dateString, formats, 
                              new CultureInfo("en-US"), 
                              DateTimeStyles.None, 
                              out dateValue))
      Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
   else
      Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
}
// The example displays the following output: 
//       Converted '5/1/2009 6:32 PM' to 5/1/2009 6:32:00 PM. 
//       Converted '05/01/2009 6:32:05 PM' to 5/1/2009 6:32:05 PM. 
//       Converted '5/1/2009 6:32:00' to 5/1/2009 6:32:00 AM. 
//       Converted '05/01/2009 06:32' to 5/1/2009 6:32:00 AM. 
//       Converted '05/01/2009 06:32:00 PM' to 5/1/2009 6:32:00 PM. 
//       Converted '05/01/2009 06:32:00' to 5/1/2009 6:32:00 AM.

How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?

I don't think the jar tool supports this natively, but you can just unzip a JAR file with "unzip" and specify the output directory with that with the "-d" option, so something like:

$ unzip -d /home/foo/bar/baz /home/foo/bar/Portal.ear Binaries.war

Call removeView() on the child's parent first

What I was doing wrong so I got this error is I wasn't instantiating dynamic layout and adding childs to it so got this error

How can I get the number of days between 2 dates in Oracle 11g?

Or you could have done this:

select trunc(sysdate) - to_date('2009-10-01', 'yyyy-mm-dd') from dual

This returns a NUMBER of whole days:

SQL> create view v as 
  2  select trunc(sysdate) - to_date('2009-10-01', 'yyyy-mm-dd') diff 
  3  from dual;

View created.

SQL> select * from v;

      DIFF
----------
        29

SQL> desc v
 Name                   Null?    Type
 ---------------------- -------- ------------------------
 DIFF                            NUMBER(38)

How do I improve ASP.NET MVC application performance?

I did all the answers above and it just didn't solve my problem.

Finally, I solved my slow site loading problem with setting PrecompileBeforePublish in Publish Profile to true. If you want to use msbuild you can use this argument:

 /p:PrecompileBeforePublish=true

It really help a lot. Now my MVC ASP.NET loads 10 times faster.

How to watch for array changes?

I found the following which seems to accomplish this: https://github.com/mennovanslooten/Observable-Arrays

Observable-Arrays extends underscore and can be used as follow: (from that page)

// For example, take any array:
var a = ['zero', 'one', 'two', 'trhee'];

// Add a generic observer function to that array:
_.observe(a, function() {
    alert('something happened');
});

gcc-arm-linux-gnueabi command not found

got the same error when trying to cross compile the raspberry pi kernel on ubunto 14.04.03 64bit under VM. the solution was found here:

-Install packages used for cross compiling on the Ubuntu box.

sudo apt-get install gcc-arm-linux-gnueabi make git-core ncurses-dev

-Download the toolchain

cd ~
git clone https://github.com/raspberrypi/tools

-Add the toolchain to your path

PATH=$PATH:~/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian:~/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin

notice the x64 version in the path command

How to install ADB driver for any android device?

You don't really need to install or use any third party tools.

The drivers located in ...\Android\Sdk\extras\google\usb_driver work just fine.

Step 1: In Device Manager, Right click on the malfunctioning Android ADB Interface driver

Step 2: Select Update Driver Software

Step 3: Select Browse my computer for driver software

Step 4: Select Let me pick from a list of device drivers on my computer

Step 5: Select Have Disk

This window pops up:

enter image description here

Step 6: Copy the location of the Google USB Driver (...\Android\Sdk\extras\google\usb_driver) or browse to it.

Step 7: Click Ok

This window pops up:

enter image description here

Step 8: Select Android ADB Interface and click Next

The window below pops up with a warning:

enter image description here

That's it. You driver installation will start and in a few seconds, you should be able to see your device

Understanding Chrome network log "Stalled" state

https://developers.google.com/web/tools/chrome-devtools/network-performance/understanding-resource-timing

This comes from the official site of Chome-devtools and it helps. Here i quote:

  • Queuing If a request is queued it indicated that:
    • The request was postponed by the rendering engine because it's considered lower priority than critical resources (such as scripts/styles). This often happens with images.
    • The request was put on hold to wait for an unavailable TCP socket that's about to free up.
    • The request was put on hold because the browser only allows six TCP connections per origin on HTTP 1. Time spent making disk cache entries (typically very quick.)
  • Stalled/Blocking Time the request spent waiting before it could be sent. It can be waiting for any of the reasons described for Queueing. Additionally, this time is inclusive of any time spent in proxy negotiation.

How to combine two vectors into a data frame

df = data.frame(cond=c(rep("x",3),rep("y",3)),rating=c(x,y))

coercing to Unicode: need string or buffer, NoneType found when rendering in django admin

The return value def __unicode __ should be similar to the return value of the related models (tables) for correct viewing of "some_field" in django admin panel. You can also use:

def __str__(self):
    return self.some_field

Use jquery to set value of div tag

You have referenced the jQuery JS file haven't you? There's no reason why farzad's answer shouldn't work.

How to select a node of treeview programmatically in c#?

Apologies for my previously mixed up answer.

Here is how to do:

myTreeView.SelectedNode = myTreeNode;

(Update)

I have tested the code below and it works:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        treeView1.Nodes.Add("1", "1");
        treeView1.Nodes.Add("2", "2");
        treeView1.Nodes[0].Nodes.Add("1-1", "1-1");
        TreeNode treeNode = treeView1.Nodes[0].Nodes.Add("1-2", "1-3");
        treeView1.SelectedNode = treeNode;
        MessageBox.Show(treeNode.IsSelected.ToString());
    }


}

Nested select statement in SQL Server

You need to alias the subquery.

SELECT name FROM (SELECT name FROM agentinformation) a  

or to be more explicit

SELECT a.name FROM (SELECT name FROM agentinformation) a  

Installing Node.js (and npm) on Windows 10

In addition to the answer from @StephanBijzitter I would use the following PATH variables instead:

%appdata%\npm
%ProgramFiles%\nodejs

So your new PATH would look like:

[existing stuff];%appdata%\npm;%ProgramFiles%\nodejs

This has the advantage of neiter being user dependent nor 32/64bit dependent.

Getting pids from ps -ef |grep keyword

I use

ps -C "keyword" -o pid=

This command should give you a PID number.

How to change TextField's height and width?

I think you want to change the inner padding/margin of the TextField.

You can do that by adding isDense: true and contentPadding: EdgeInsets.all(8) properties as follow:

Container(
  padding: EdgeInsets.all(12),
  child: Column(
    children: <Widget>[
      TextField(
        decoration: InputDecoration(
          border: OutlineInputBorder(),
          labelText: 'Default TextField',
        ),
      ),
      SizedBox(height: 16,),
      TextField(
        decoration: InputDecoration(
          border: OutlineInputBorder(),
          labelText: 'Densed TextField',
          isDense: true,                      // Added this
        ),
      ),
      SizedBox(height: 16,),
      TextField(
        decoration: InputDecoration(
          border: OutlineInputBorder(),
          labelText: 'Even Densed TextFiled',
          isDense: true,                      // Added this
          contentPadding: EdgeInsets.all(8),  // Added this
        ),
      )
    ],
  ),
)

It will be displayed as:

How to update flutter TextField's height and width / Inner Padding?

Choosing the correct upper and lower HSV boundaries for color detection with`cv::inRange` (OpenCV)

I Created this simple program to get HSV Codes in realtime

import cv2
import numpy as np


cap = cv2.VideoCapture(0)

def nothing(x):
    pass
# Creating a window for later use
cv2.namedWindow('result')

# Starting with 100's to prevent error while masking
h,s,v = 100,100,100

# Creating track bar
cv2.createTrackbar('h', 'result',0,179,nothing)
cv2.createTrackbar('s', 'result',0,255,nothing)
cv2.createTrackbar('v', 'result',0,255,nothing)

while(1):

    _, frame = cap.read()

    #converting to HSV
    hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)

    # get info from track bar and appy to result
    h = cv2.getTrackbarPos('h','result')
    s = cv2.getTrackbarPos('s','result')
    v = cv2.getTrackbarPos('v','result')

    # Normal masking algorithm
    lower_blue = np.array([h,s,v])
    upper_blue = np.array([180,255,255])

    mask = cv2.inRange(hsv,lower_blue, upper_blue)

    result = cv2.bitwise_and(frame,frame,mask = mask)

    cv2.imshow('result',result)

    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break

cap.release()

cv2.destroyAllWindows()

Permission denied at hdfs

I've solved this problem by using following steps

su hdfs
hadoop fs -put /usr/local/input-data/ /input
exit

Best way to disable button in Twitter's Bootstrap

You just need the $('button').prop('disabled', true); part, the button will automatically take the disabled class.

TypeScript and field initializers

Update

Since writing this answer, better ways have come up. Please see the other answers below that have more votes and a better answer. I cannot remove this answer since it's marked as accepted.


Old answer

There is an issue on the TypeScript codeplex that describes this: Support for object initializers.

As stated, you can already do this by using interfaces in TypeScript instead of classes:

interface Name {
    first: string;
    last: string;
}
class Person {
    name: Name;
    age: number;
}

var bob: Person = {
    name: {
        first: "Bob",
        last: "Smith",
    },
    age: 35,
};

Android: Flush DNS

You have a few options:

  • Release an update for your app that uses a different hostname that isn't in anyone's cache.
  • Same thing, but using the IP address of your server
  • Have your users go into settings -> applications -> Network Location -> Clear data.

You may want to check that last step because i don't know for a fact that this is the appropriate service. I can't really test that right now. Good luck!

What are carriage return, linefeed, and form feed?

In Short :

Carriage_return(\r or 0xD): To take control at starting of same line.

Line_Feed(\n or 0xA): To Take control at starting of next line.

form_feed(\f or 0xC): To take control at starting of next page.

installing python packages without internet and using source code as .tar.gz and .whl

This is how I handle this case:

On the machine where I have access to Internet:

mkdir keystone-deps
pip download python-keystoneclient -d "/home/aviuser/keystone-deps"
tar cvfz keystone-deps.tgz keystone-deps

Then move the tar file to the destination machine that does not have Internet access and perform the following:

tar xvfz keystone-deps.tgz
cd keystone-deps
pip install python_keystoneclient-2.3.1-py2.py3-none-any.whl -f ./ --no-index

You may need to add --no-deps to the command as follows:

pip install python_keystoneclient-2.3.1-py2.py3-none-any.whl -f ./ --no-index --no-deps

Using the rJava package on Win7 64 bit with R

I think this is an update. I was unable to install rJava (on Windows) until I installed the JDK, as per Javac is not found and javac not working in windows command prompt. The message I was getting was

'javac' is not recognized as an internal or external command, operable program or batch file.

The JDK includes the JRE, and according to https://cran.r-project.org/web/packages/rJava/index.html the current version (0.9-7 published 2015-Jul-29) of rJava

SystemRequirements:     Java JDK 1.2 or higher (for JRI/REngine JDK 1.4 or higher), GNU make

So there you are: if rJava won't install because it can't find javac, and you have the JRE installed, then try the JDK. Also, make sure that JAVA_HOME points to the JDK and not the JRE.

Create local maven repository

If maven is not creating Local Repository i.e .m2/repository folder then try below step.

In your Eclipse\Spring Tool Suite, Go to Window->preferences-> maven->user settings-> click on Restore Defaults-> Apply->Apply and close

How do you comment an MS-access Query?

if you are trying to add a general note to the overall object (query or table etc..)

Access 2016 go to navigation pane, highlight object, right click, select object / table properties, add a note in the description window i.e. inventory "table last last updated 05/31/17"

convert string to specific datetime format?

Use DATE_FORMAT from Date Conversions:

In your initializer:

DateTime::DATE_FORMATS[:my_date_format] = "%a %b %d %H:%M:%S %Z %Y"

In your view:

date = DateTime.parse("2011-05-19 10:30:14")
date.to_formatted_s(:my_date_format)
date.to_s(:my_date_format) 

How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

_x000D_
_x000D_
function timeSince(date) {

  var seconds = Math.floor((new Date() - date) / 1000);

  var interval = seconds / 31536000;

  if (interval > 1) {
    return Math.floor(interval) + " years";
  }
  interval = seconds / 2592000;
  if (interval > 1) {
    return Math.floor(interval) + " months";
  }
  interval = seconds / 86400;
  if (interval > 1) {
    return Math.floor(interval) + " days";
  }
  interval = seconds / 3600;
  if (interval > 1) {
    return Math.floor(interval) + " hours";
  }
  interval = seconds / 60;
  if (interval > 1) {
    return Math.floor(interval) + " minutes";
  }
  return Math.floor(seconds) + " seconds";
}
var aDay = 24*60*60*1000;
console.log(timeSince(new Date(Date.now()-aDay)));
console.log(timeSince(new Date(Date.now()-aDay*2)));
_x000D_
_x000D_
_x000D_

What's the best practice to "git clone" into an existing folder?

Don't clone, fetch instead. In the repo:

git init
git remote add origin $url_of_clone_source
git fetch origin
git checkout -b master --track origin/master # origin/master is clone's default

Then you can reset the tree to get the commit you want:

git reset origin/master # or whatever commit you think is proper...

and you are like you cloned.

The interesting question here (and the one without answer): How to find out which commit your naked tree was based on, hence to which position to reset to.

What is the difference between linear regression and logistic regression?

In linear regression, the outcome (dependent variable) is continuous. It can have any one of an infinite number of possible values. In logistic regression, the outcome (dependent variable) has only a limited number of possible values.

For instance, if X contains the area in square feet of houses, and Y contains the corresponding sale price of those houses, you could use linear regression to predict selling price as a function of house size. While the possible selling price may not actually be any, there are so many possible values that a linear regression model would be chosen.

If, instead, you wanted to predict, based on size, whether a house would sell for more than $200K, you would use logistic regression. The possible outputs are either Yes, the house will sell for more than $200K, or No, the house will not.

`React/RCTBridgeModule.h` file not found

For me, this error occurred when I added a new scheme/target (app.staging) in the app and installed pods using pod install.

This issue is occurring due to pods are not shared for all targets. So I need to add newly added target (app.staging) inside the Podfile.

Here is my Podfile.

platform :ios, '9.0'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

target 'app' do
  # Pods for app
  pod 'FBLazyVector', :path => "../node_modules/react-native/Libraries/FBLazyVector"
  pod 'FBReactNativeSpec', :path => "../node_modules/react-native/Libraries/FBReactNativeSpec"

  target 'appTests' do
    inherit! :search_paths
    # Pods for testing
  end

  # Pods for staging app // important line below
  target 'app.staging'

  use_native_modules!
end

Getting the text from a drop-down box

Please try the below this is the easiest way and it works perfectly

var newSkill_Text = document.getElementById("newSkill")[document.getElementById("newSkill").selectedIndex];

How does DateTime.Now.Ticks exactly work?

You can get the milliseconds since 1/1/1970 using such code:

private static DateTime JanFirst1970 = new DateTime(1970, 1, 1);
public static long getTime()
{
    return (long)((DateTime.Now.ToUniversalTime() - JanFirst1970).TotalMilliseconds + 0.5);
}

Rollback to an old Git commit in a public repo

Here is an example to do that

    cd /yourprojects/project-acme 


    git checkout efc11170c78 .

How to get input text value on click in ReactJS

First of all, you can't pass to alert second argument, use concatenation instead

alert("Input is " + inputValue);

Example

However in order to get values from input better to use states like this

_x000D_
_x000D_
var MyComponent = React.createClass({_x000D_
  getInitialState: function () {_x000D_
    return { input: '' };_x000D_
  },_x000D_
_x000D_
  handleChange: function(e) {_x000D_
    this.setState({ input: e.target.value });_x000D_
  },_x000D_
_x000D_
  handleClick: function() {_x000D_
    console.log(this.state.input);_x000D_
  },_x000D_
_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <input type="text" onChange={ this.handleChange } />_x000D_
        <input_x000D_
          type="button"_x000D_
          value="Alert the text input"_x000D_
          onClick={this.handleClick}_x000D_
        />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
ReactDOM.render(_x000D_
  <MyComponent />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

Calculate the center point of multiple latitude/longitude coordinate pairs

Java Version if anyone needs it. Constants defined static to not calculate them twice.

/**************************************************************************************************************
 *   Center of geometry defined by coordinates
 **************************************************************************************************************/
private static double pi = Math.PI / 180;
private static double xpi = 180 / Math.PI;

public static Coordinate center(Coordinate... arr) {
    if (arr.length == 1) {
        return arr[0];
    }
    double x = 0, y = 0, z = 0;

    for (Coordinate c : arr) {
        double latitude = c.lat() * pi, longitude = c.lon() * pi;
        double cl = Math.cos(latitude);//save it as we need it twice
        x += cl * Math.cos(longitude);
        y += cl * Math.sin(longitude);
        z += Math.sin(latitude);
    }

    int total = arr.length;

    x = x / total;
    y = y / total;
    z = z / total;

    double centralLongitude = Math.atan2(y, x);
    double centralSquareRoot = Math.sqrt(x * x + y * y);
    double centralLatitude = Math.atan2(z, centralSquareRoot);

    return new Coordinate(centralLatitude * xpi, centralLongitude * xpi);
}

RGB to hex and hex to RGB

I'm working with XAML data that has a hex format of #AARRGGBB (Alpha, Red, Green, Blue). Using the answers above, here's my solution:

function hexToRgba(hex) {
    var bigint, r, g, b, a;
    //Remove # character
    var re = /^#?/;
    var aRgb = hex.replace(re, '');
    bigint = parseInt(aRgb, 16);

    //If in #FFF format
    if (aRgb.length == 3) {
        r = (bigint >> 4) & 255;
        g = (bigint >> 2) & 255;
        b = bigint & 255;
        return "rgba(" + r + "," + g + "," + b + ",1)";
    }

    //If in #RRGGBB format
    if (aRgb.length >= 6) {
        r = (bigint >> 16) & 255;
        g = (bigint >> 8) & 255;
        b = bigint & 255;
        var rgb = r + "," + g + "," + b;

        //If in #AARRBBGG format
        if (aRgb.length == 8) {
            a = ((bigint >> 24) & 255) / 255;
            return "rgba(" + rgb + "," + a.toFixed(1) + ")";
        }
    }
    return "rgba(" + rgb + ",1)";
}

http://jsfiddle.net/kvLyscs3/

How to check whether a string is a valid HTTP URL?

This would return bool:

Uri.IsWellFormedUriString(a.GetAttribute("href"), UriKind.Absolute)

Creating Threads in python

There are a few problems with your code:

def MyThread ( threading.thread ):
  • You can't subclass with a function; only with a class
  • If you were going to use a subclass you'd want threading.Thread, not threading.thread

If you really want to do this with only functions, you have two options:

With threading:

import threading
def MyThread1():
    pass
def MyThread2():
    pass

t1 = threading.Thread(target=MyThread1, args=[])
t2 = threading.Thread(target=MyThread2, args=[])
t1.start()
t2.start()

With thread:

import thread
def MyThread1():
    pass
def MyThread2():
    pass

thread.start_new_thread(MyThread1, ())
thread.start_new_thread(MyThread2, ())

Doc for thread.start_new_thread

What is the difference between Multiple R-squared and Adjusted R-squared in a single-variate least squares regression?

The R-squared is not dependent on the number of variables in the model. The adjusted R-squared is.

The adjusted R-squared adds a penalty for adding variables to the model that are uncorrelated with the variable your trying to explain. You can use it to test if a variable is relevant to the thing your trying to explain.

Adjusted R-squared is R-squared with some divisions added to make it dependent on the number of variables in the model.

Rails: select unique values from a column

Model.pluck("DISTINCT column_name")

How can I get the values of data attributes in JavaScript code?

if you are targeting data attribute in Html element,

document.dataset will not work

you should use

document.querySelector("html").dataset.pbUserId

or

document.getElementsByTagName("html")[0].dataset.pbUserId

Find index of a value in an array

Try this...

var key = words.Where(x => x.IsKey == true);

Android Pop-up message

Suppose you want to set a pop-up text box for clicking a button lets say bt whose id is button, then code using Toast will somewhat look like this:

Button bt;
bt = (Button) findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {            
Toast.makeText(getApplicationContext(),"The text you want to display",Toast.LENGTH_LONG)
}

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

It looks like the CSRF (Cross Site Request Forgery) protection in your Spring application is enabled. Actually it is enabled by default.

According to spring.io:

When should you use CSRF protection? Our recommendation is to use CSRF protection for any request that could be processed by a browser by normal users. If you are only creating a service that is used by non-browser clients, you will likely want to disable CSRF protection.

So to disable it:

@Configuration
public class RestSecurityConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
  }
}

If you want though to keep CSRF protection enabled then you have to include in your form the csrftoken. You can do it like this:

<form .... >
  ....other fields here....
  <input type="hidden"  name="${_csrf.parameterName}"   value="${_csrf.token}"/>
</form>

You can even include the CSRF token in the form's action:

<form action="./upload?${_csrf.parameterName}=${_csrf.token}" method="post" enctype="multipart/form-data">

Angular ngClass and click event for toggling class

If you want to toggle text with a toggle button.

HTMLfile which is using bootstrap:

<input class="btn" (click)="muteStream()"  type="button"
          [ngClass]="status ? 'btn-success' : 'btn-danger'" 
          [value]="status ? 'unmute' : 'mute'"/>

TS file:

muteStream() {
   this.status = !this.status;
}

INNER JOIN vs LEFT JOIN performance in SQL Server

Try both queries (the one with inner and left join) with OPTION (FORCE ORDER) at the end and post the results. OPTION (FORCE ORDER) is a query hint that forces the optimizer to build the execution plan with the join order you provided in the query.

If INNER JOIN starts performing as fast as LEFT JOIN, it's because:

  • In a query composed entirely by INNER JOINs, the join order doesn't matter. This gives freedom for the query optimizer to order the joins as it sees fit, so the problem might rely on the optimizer.
  • With LEFT JOIN, that's not the case because changing the join order will alter the results of the query. This means the engine must follow the join order you provided on the query, which might be better than the optimized one.

Don't know if this answers your question but I was once in a project that featured highly complex queries making calculations, which completely messed up the optimizer. We had cases where a FORCE ORDER would reduce the execution time of a query from 5 minutes to 10 seconds.

How to create a sticky footer that plays well with Bootstrap 3

   <style type="text/css">

     /* Sticky footer styles
     -------------------------------------------------- */

     html,
     body {
       height: 100%;
       /* The html and body elements cannot have any padding or margin. */
     }

     /* Wrapper for page content to push down footer */
     #wrap {
       min-height: 100%;
       height: auto !important;
       height: 100%;
       /* Negative indent footer by it's height */
       margin: 0 auto -60px;
     }

     /* Set the fixed height of the footer here */
     #push,
     #footer {
       height: 60px;
     }
     #footer {
       background-color: #f5f5f5;
     }

     /* Lastly, apply responsive CSS fixes as necessary */
     @media (max-width: 767px) {
       #footer {
         margin-left: -20px;
         margin-right: -20px;
         padding-left: 20px;
         padding-right: 20px;
       }
     }



     /* Custom page CSS
     -------------------------------------------------- */
     /* Not required for template or sticky footer method. */

     .container {
       width: auto;
       max-width: 680px;
     }
     .container .credit {
       margin: 20px 0;
     }

   </style>


<div id="wrap">

  <!-- Begin page content -->
  <div class="container">
    <div class="page-header">
      <h1>Sticky footer</h1>
    </div>
    <p class="lead">Pin a fixed-height footer to the bottom of the viewport in desktop browsers with this custom HTML and CSS.</p>
    <p>Use <a href="./sticky-footer-navbar.html">the sticky footer</a> with a fixed navbar if need be, too.</p>
  </div>

  <div id="push"></div>
</div>

<div id="footer">
  <div class="container">
    <p class="muted credit">Example courtesy <a href="http://martinbean.co.uk">Martin Bean</a> and <a href="http://ryanfait.com/sticky-footer/">Ryan Fait</a>.</p>
  </div>
</div>

Shadow Effect for a Text in Android?

Perhaps you'd consider using android:shadowColor, android:shadowDx, android:shadowDy, android:shadowRadius; alternatively setShadowLayer() ?

How do I change the default library path for R packages

Facing the very same problem (avoiding the default path in a network) I came up to this solution with the hints given in other answers.

The solution is editing the Rprofile file to overwrite the variable R_LIBS_USER which by default points to the home directory.

Here the steps:

  1. Create the target destination folder for the libraries, e.g., ~\target.
  2. Find the Rprofile file. In my case it was at C:\Program Files\R\R-3.3.3\library\base\R\Rprofile.
  3. Edit the file and change the definition the variable R_LIBS_USER. In my case, I replaced the this line file.path(Sys.getenv("R_USER"), "R", with file.path("~\target", "R",.

The documentation that support this solution is here

Original file with:

 if(!nzchar(Sys.getenv("R_LIBS_USER")))
     Sys.setenv(R_LIBS_USER=
                file.path(Sys.getenv("R_USER"), "R",
                          "win-library",
                          paste(R.version$major,
                                sub("\\..*$", "", R.version$minor),
                                sep=".")
                          )) 

Modified file:

if(!nzchar(Sys.getenv("R_LIBS_USER")))
     Sys.setenv(R_LIBS_USER=
                file.path("~\target", "R",
                          "win-library",
                          paste(R.version$major,
                                sub("\\..*$", "", R.version$minor),
                                sep=".")
                          ))

How do I activate a virtualenv inside PyCharm's terminal?

I wanted a separate virtual environment for each project, and didn't care much for having additional files to facilitate this. A solution which you only need to do once and works for all projects is then adding the following to your .bashrc or .bash_profile:

if [ -d "./venv" ]; then
    source ./venv/bin/activate
fi

This checks if there is a virtual environment where the terminal is being opened, and if so activates it (and of course other relative paths could be used). PyCharm's terminal settings can be left as their default.

How to hide output of subprocess in Python 2.7

As of Python3 you no longer need to open devnull and can call subprocess.DEVNULL.

Your code would be updated as such:

import subprocess
text = 'Hello World.'
print(text)
subprocess.call(['espeak', text], stderr=subprocess.DEVNULL)

How do I compile with -Xlint:unchecked?

If you work with an IDE like NetBeans, you can specify the Xlint:unchecked compiler option in the propertys of your project.

Just go to projects window, right click in the project and then click in Properties.

In the window that appears search the Compiling category, and in the textbox labeled Additional Compiler Options set the Xlint:unchecked option.

Thus, the setting will remain set for every time you compile the project.

MySQL "NOT IN" query

Be carefull NOT IN is not an alias for <> ANY, but for <> ALL!

http://dev.mysql.com/doc/refman/5.0/en/any-in-some-subqueries.html

SELECT c FROM t1 LEFT JOIN t2 USING (c) WHERE t2.c IS NULL

cant' be replaced by

SELECT c FROM t1 WHERE c NOT IN (SELECT c FROM t2)

You must use

SELECT c FROM t1 WHERE c <> ANY (SELECT c FROM t2)

How do I pass along variables with XMLHTTPRequest

If you're allergic to string concatenation and don't need IE compatibility, you can use URL and URLSearchParams:

_x000D_
_x000D_
const target = new URL('https://example.com/endpoint');_x000D_
const params = new URLSearchParams();_x000D_
params.set('var1', 'foo');_x000D_
params.set('var2', 'bar');_x000D_
target.search = params.toString();_x000D_
_x000D_
console.log(target);
_x000D_
_x000D_
_x000D_

Or to convert an entire object's worth of parameters:

_x000D_
_x000D_
const paramsObject = {_x000D_
  var1: 'foo',_x000D_
  var2: 'bar'_x000D_
};_x000D_
_x000D_
const target = new URL('https://example.com/endpoint');_x000D_
target.search = new URLSearchParams(paramsObject).toString();_x000D_
_x000D_
console.log(target);
_x000D_
_x000D_
_x000D_

jQuery call function after load

In regards to the question in your comment:

Assuming that you've previously bound your function to the click event of the radio button, add this to your $(document).ready function:

$('#[radioButtonOptionID]').click()

Without a parameter, that simulates the click event.

Error:Cause: unable to find valid certification path to requested target

I got the same issue and I fixed it by changing my firewall setting or you can switch to another network

reasons behind it

when we are running our project run command its configure and check for exiting packages and make proceed to download the new or required package and the packages are stored on non-secure IP/hosting so your firewall will try to protect you and you will get these errors

Printing object properties in Powershell

To print out object's properties and values in Powershell. Below examples work well for me.

$pool = Get-Item "IIS:\AppPools.NET v4.5"

$pool | Get-Member

   TypeName: Microsoft.IIs.PowerShell.Framework.ConfigurationElement#system.applicationHost/applicationPools#add

Name                        MemberType            Definition
----                        ----------            ----------
Recycle                     CodeMethod            void Recycle()
Start                       CodeMethod            void Start()
Stop                        CodeMethod            void Stop()
applicationPoolSid          CodeProperty          Microsoft.IIs.PowerShell.Framework.CodeProperty
state                       CodeProperty          Microsoft.IIs.PowerShell.Framework.CodeProperty
ClearLocalData              Method                void ClearLocalData()
Copy                        Method                void Copy(Microsoft.IIs.PowerShell.Framework.ConfigurationElement ...
Delete                      Method                void Delete()
...

$pool | Select-Object -Property * # You can omit -Property

name                        : .NET v4.5
queueLength                 : 1000
autoStart                   : True
enable32BitAppOnWin64       : False
managedRuntimeVersion       : v4.0
managedRuntimeLoader        : webengine4.dll
enableConfigurationOverride : True
managedPipelineMode         : Integrated
CLRConfigFile               :
passAnonymousToken          : True
startMode                   : OnDemand
state                       : Started
applicationPoolSid          : S-1-5-82-271721585-897601226-2024613209-625570482-296978595
processModel                : Microsoft.IIs.PowerShell.Framework.ConfigurationElement
...

What's the best way to detect a 'touch screen' device using JavaScript?

I like this one:

function isTouchDevice(){
    return typeof window.ontouchstart !== 'undefined';
}

alert(isTouchDevice());

Adding a caption to an equation in LaTeX

You may want to look at http://tug.ctan.org/tex-archive/macros/latex/contrib/float/ which allows you to define new floats using \newfloat

I say this because captions are usually applied to floats.

Straight ahead equations (those written with $ ... $, $$ ... $$, begin{equation}...) are in-line objects that do not support \caption.

This can be done using the following snippet just before \begin{document}

\usepackage{float}
\usepackage{aliascnt}
\newaliascnt{eqfloat}{equation}
\newfloat{eqfloat}{h}{eqflts}
\floatname{eqfloat}{Equation}

\newcommand*{\ORGeqfloat}{}
\let\ORGeqfloat\eqfloat
\def\eqfloat{%
  \let\ORIGINALcaption\caption
  \def\caption{%
    \addtocounter{equation}{-1}%
    \ORIGINALcaption
  }%
  \ORGeqfloat
}

and when adding an equation use something like

\begin{eqfloat}
\begin{equation}
f( x ) = ax + b
\label{eq:linear}
\end{equation}
\caption{Caption goes here}
\end{eqfloat}

Github: Can I see the number of downloads for a repo?

For those who need the solution in Python, I wrote a simple script.


Python Script:


Usage:

ghstats.py [user] [repo] [tag] [options]


Support:

  • Supports both Python 2 and Python 3 out of the box.
  • Can be used as both a standalone and a Python module.

How to style components using makeStyles and still have lifecycle methods in Material UI?

Another one solution can be used for class components - just override default MUI Theme properties with MuiThemeProvider. This will give more flexibility in comparison with other methods - you can use more than one MuiThemeProvider inside your parent component.

simple steps:

  1. import MuiThemeProvider to your class component
  2. import createMuiTheme to your class component
  3. create new theme
  4. wrap target MUI component you want to style with MuiThemeProvider and your custom theme

please, check this doc for more details: https://material-ui.com/customization/theming/

_x000D_
_x000D_
import React from 'react';
import PropTypes from 'prop-types';
import Button from '@material-ui/core/Button';

import { MuiThemeProvider } from '@material-ui/core/styles';
import { createMuiTheme } from '@material-ui/core/styles';

const InputTheme = createMuiTheme({
    overrides: {
        root: {
            background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
            border: 0,
            borderRadius: 3,
            boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
            color: 'white',
            height: 48,
            padding: '0 30px',
        },
    }
});

class HigherOrderComponent extends React.Component {

    render(){
        const { classes } = this.props;
        return (
            <MuiThemeProvider theme={InputTheme}>
                <Button className={classes.root}>Higher-order component</Button>
            </MuiThemeProvider>
        );
    }
}

HigherOrderComponent.propTypes = {
    classes: PropTypes.object.isRequired,
};

export default HigherOrderComponent;
_x000D_
_x000D_
_x000D_

Python - Extracting and Saving Video Frames

Following script will extract frames every half a second of all videos in folder. (Works on python 3.7)

import cv2
import os
listing = os.listdir(r'D:/Images/AllVideos')
count=1
for vid in listing:
    vid = r"D:/Images/AllVideos/"+vid
    vidcap = cv2.VideoCapture(vid)
    def getFrame(sec):
        vidcap.set(cv2.CAP_PROP_POS_MSEC,sec*1000)
        hasFrames,image = vidcap.read()
        if hasFrames:
            cv2.imwrite("D:/Images/Frames/image"+str(count)+".jpg", image) # Save frame as JPG file
        return hasFrames
    sec = 0
    frameRate = 0.5 # Change this number to 1 for each 1 second
    
    success = getFrame(sec)
    while success:
        count = count + 1
        sec = sec + frameRate
        sec = round(sec, 2)
        success = getFrame(sec)

How do I concatenate const/literal strings in C?

If you have experience in C you will notice that strings are only char arrays where the last character is a null character.

Now that is quite inconvenient as you have to find the last character in order to append something. strcat will do that for you.

So strcat searches through the first argument for a null character. Then it will replace this with the second argument's content (until that ends in a null).

Now let's go through your code:

message = strcat("TEXT " + var);

Here you are adding something to the pointer to the text "TEXT" (the type of "TEXT" is const char*. A pointer.).

That will usually not work. Also modifying the "TEXT" array will not work as it is usually placed in a constant segment.

message2 = strcat(strcat("TEXT ", foo), strcat(" TEXT ", bar));

That might work better, except that you are again trying to modify static texts. strcat is not allocating new memory for the result.

I would propose to do something like this instead:

sprintf(message2, "TEXT %s TEXT %s", foo, bar);

Read the documentation of sprintf to check for it's options.

And now an important point:

Ensure that the buffer has enough space to hold the text AND the null character. There are a couple of functions that can help you, e.g., strncat and special versions of printf that allocate the buffer for you. Not ensuring the buffer size will lead to memory corruption and remotely exploitable bugs.

How do I create HTML table using jQuery dynamically?

I understand you want to create stuff dynamically. That does not mean you have to actually construct DOM elements to do it. You can just make use of html to achieve what you want .

Look at the code below :

HTML:

<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'></table>

JS :

createFormElement("Nickname","nickname")

function createFormElement(labelText, id) {

$("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='"+id+"' name='nickname'></td><lable id='"+labelText+"'></lable></td></tr>");
$('#providersFormElementsTable').append('<br />');
}

This one does what you want dynamically, it just needs the id and labelText to make it work, which actually must be the only dynamic variables as only they will be changing. Your DOM structure will always remain the same .

WORKING DEMO:

Moreover, when you use the process you mentioned in your post you get only [object Object]. That is because when you call createProviderFormFields , it is a function call and hence it's returning an object for you. You will not be seeing the text box as it needs to be added . For that you need to strip individual content form the object, then construct the html from it.

It's much easier to construct just the html and change the id s of the label and input according to your needs.

Using switch statement with a range of value in each case?

Or you could use your solo cases as intended and use your default case to specify range instructions as :

switch(n) {
    case 1 : System.out.println("case 1"); break;
    case 4 : System.out.println("case 4"); break;
    case 99 : System.out.println("case 99"); break;
    default :
        if (n >= 10 && n <= 15)
            System.out.println("10-15 range"); 
        else if (n >= 100 && n <= 200)
            System.out.println("100-200 range");
        else
            System.out.println("Your default case");
        break;   
}

Using if-else in JSP

You may try this example:

_x000D_
_x000D_
<form>_x000D_
  <h1>Hello! I'm duke! What's you name?</h1>_x000D_
  <input type="text" name="user">_x000D_
  <br>_x000D_
  <br>_x000D_
  <input type="submit" value="submit">&nbsp;&nbsp;&nbsp;&nbsp;_x000D_
  <input type="reset">_x000D_
</form>_x000D_
<h1>Hello ${param.user}</h1> _x000D_
<!-- its Expression Language -->
_x000D_
_x000D_
_x000D_

CSS :not(:last-child):after selector

You can try this, I know is not the answers you are looking for but the concept is the same.

Where you are setting the styles for all the children and then removing it from the last child.

Code Snippet

li
  margin-right: 10px

  &:last-child
    margin-right: 0

Image

enter image description here

Starting of Tomcat failed from Netbeans

None of the answers here solved my issue (as at February 2020), so I raised an issue at https://issues.apache.org/jira/browse/NETBEANS-3903 and Netbeans fixed the issue!

They're working on a pull request so the fix will be in a future .dmg installer soon, but in the meantime you can copy a file referenced in the bug and replace one in your netbeans modules folder.

Tip - if you right click on Applications > Netbeans and choose Show Package Contents Show Package Contents then you can find and replace the file org-netbeans-modules-tomcat5.jar that they refer to in your Netbeans folder, e.g. within /Applications/NetBeans/Apache NetBeans 11.2.app/Contents/Resources/NetBeans/netbeans/enterprise/modules

CSS Custom Dropdown Select that works across all browsers IE7+ FF Webkit

As per Link: http://bavotasan.com/2011/style-select-box-using-only-css/ there are lot of extra rework that needs to be done(Put extra div and position the image there. Also the design will break as the option drilldown will be mis alligned to the the select.

Here is an easy and simple way which will allow you to put your own dropdown image and remove the browser default dropdown.(Without using any extra div). Its cross browser as well.

HTML

<select class="dropdown" name="drop-down">
  <option value="select-option">Please select...</option>
  <option value="Local-Community-Enquiry">Option 1</option>
  <option value="Bag-Packing-in-Store">Option 2</option>
</select>

CSS

select.dropdown {
  margin: 0px;
  margin-top: 12px;
  height: 48px;
  width: 100%;
  border-width: 1px;
  border-style: solid;
  border-color: #666666;
  padding: 9px;
  font-family: tescoregular;
  font-size: 16px;
  color: #666666;
  -webkit-appearance: none;
  -webkit-border-radius: 0px;
  -moz-appearance: none;
  appearance: none;
  background: url('yoururl/dropdown.png') no-repeat 97% 50% #ffffff;
  background-size: 11px 7px;
}

Creating a .p12 file

I'm debugging an issue I'm having with SSL connecting to a database (MySQL RDS) using an ORM called, Prisma. The database connection string requires a PKCS12 (.p12) file (if interested, described here), which brought me here.

I know the question has been answered, but I found the following steps (in Github Issue#2676) to be helpful for creating a .p12 file and wanted to share. Good luck!

  1. Generate 2048-bit RSA private key:

    openssl genrsa -out key.pem 2048

  2. Generate a Certificate Signing Request:

    openssl req -new -sha256 -key key.pem -out csr.csr

  3. Generate a self-signed x509 certificate suitable for use on web servers.

    openssl req -x509 -sha256 -days 365 -key key.pem -in csr.csr -out certificate.pem

  4. Create SSL identity file in PKCS12 as mentioned here

    openssl pkcs12 -export -out client-identity.p12 -inkey key.pem -in certificate.pem

IIS - 401.3 - Unauthorized

Just in case anyone else runs into this. I troubleshooted all of these steps and it turns out because I unzipped some files from a MAC, Microsoft automatically without any notification Encrypted the files. After hours of trying to set folder permissions I went in and saw the file names were green which means the files were encrypted and IIS will throw the same error even if folder permissions are correct.

Are duplicate keys allowed in the definition of binary search trees?

Any definition is valid. As long as you are consistent in your implementation (always put equal nodes to the right, always put them to the left, or never allow them) then you're fine. I think it is most common to not allow them, but it is still a BST if they are allowed and place either left or right.

Convert double to Int, rounded down

If the double is a Double with capital D (a boxed primitive value):

Double d = 4.97542;
int i = (int) d.doubleValue();

// or directly:
int i2 = d.intValue();

If the double is already a primitive double, then you simply cast it:

double d = 4.97542;
int i = (int) d;

How can I convert a VBScript to an executable (EXE) file?

Here are a couple possible solutions...

I have not tried all of these myself yet, but I will be trying them all soon.

Note: I do not have any personal or financial connection to any of these tools.

1) VB Script to EXE Converter (NOT Compiler): (Free)
vbs2exe.com.

The exe produced appears to be a true EXE.

From their website:

VBS to EXE is a free online converter that doesn't only convert your vbs files into exe but it also:

1- Encrypt your vbs file source code using 128 bit key.
2- Allows you to call win32 API
3- If you have troubles with windows vista especially when UAC is enabled then you may give VBS to EXE a try.
4- No need for wscript.exe to run your vbs anymore.
5- Your script is never saved to the hard disk like some others converters. it is a TRUE exe not an extractor.

This solution should work even if wscript/cscript is not installed on the computer.

Basically, this creates a true .EXE file. Inside the created .EXE is an "engine" that replaces wscript/cscript, and an encrypted copy of your VB Script code. This replacement engine executes your code IN MEMORY without calling wscript/cscript to do it.


2) Compile and Convert VBS to EXE...:
ExeScript

The current version is 3.5.

This is NOT a Free solution. They have a 15 day trial. After that, you need to buy a license for a hefty $44.96 (Home License/noncommercial), or $89.95 (Business License/commercial usage).

It seems to work in a similar way to the previous solution.

According to a forum post there:
Post: "A Exe file still need Windows Scripting Host (WSH) ??"

WSH is not required if "Compile" option was used, since ExeScript
implements it's own scripting host. ...


3) Encrypt the script with Microsoft's ".vbs to .vbe" encryption tool.

Apparently, this does not work for Windows 7/8, and it is possible there are ways to "decrypt" the .vbe file. At the time of writing this, I could not find a working link to download this. If I find one, I will add it to this answer.

PostgreSQL psql terminal command

These are not command line args. Run psql. Manage to log into database (so pass the hostname, port, user and database if needed). And then write it in the psql program.

Example (below are two commands, write the first one, press enter, wait for psql to login, write the second):

psql -h host -p 5900 -U username database
\pset format aligned

How to convert date in to yyyy-MM-dd Format?

A date-time object is supposed to store the information about the date, time, timezone etc., not about the formatting. You can format a date-time object into a String with the pattern of your choice using date-time formatting API.

  • The date-time formatting API for the modern date-time types is in the package, java.time.format e.g. java.time.format.DateTimeFormatter, java.time.format.DateTimeFormatterBuilder etc.
  • The date-time formatting API for the legacy date-time types is in the package, java.text e.g. java.text.SimpleDateFormat, java.text.DateFormat etc.

Demo using modern API:

import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        ZonedDateTime zdt = ZonedDateTime.of(LocalDate.of(2012, Month.DECEMBER, 1).atStartOfDay(),
                ZoneId.of("Europe/London"));

        // Default format returned by Date#toString
        System.out.println(zdt);

        // Custom format
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
        String formattedDate = dtf.format(zdt);
        System.out.println(formattedDate);
    }
}

Output:

2012-12-01T00:00Z[Europe/London]
2012-12-01

Learn about the modern date-time API from Trail: Date Time.

Demo using legacy API:

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public class Main {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        calendar.setTimeInMillis(0);
        calendar.set(Calendar.YEAR, 2012);
        calendar.set(Calendar.MONTH, 11);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        Date date = calendar.getTime();

        // Default format returned by Date#toString
        System.out.println(date);

        // Custom format
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
        String formattedDate = sdf.format(date);
        System.out.println(formattedDate);
    }
}

Output:

Sat Dec 01 00:00:00 GMT 2012
2012-12-01

Some more important points:

  1. The java.util.Date object is not a real date-time object like the modern date-time types; rather, it represents the milliseconds from the Epoch of January 1, 1970. When you print an object of java.util.Date, its toString method returns the date-time calculated from this milliseconds value. Since java.util.Date does not have timezone information, it applies the timezone of your JVM and displays the same. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFomrat and obtain the formatted string from it.
  2. The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.

HTTP POST using JSON in Java

I recomend http-request built on apache http api.

HttpRequest<String> httpRequest = HttpRequestBuilder.createPost(yourUri, String.class)
    .responseDeserializer(ResponseDeserializer.ignorableDeserializer()).build();

public void send(){
   ResponseHandler<String> responseHandler = httpRequest.execute("details", yourJsonData);

   int statusCode = responseHandler.getStatusCode();
   String responseContent = responseHandler.orElse(null); // returns Content from response. If content isn't present returns null. 
}

If you want send JSON as request body you can:

  ResponseHandler<String> responseHandler = httpRequest.executeWithBody(yourJsonData);

I higly recomend read documentation before use.

Heroku deployment error H10 (App crashed)

I was having the same issue. Logs weren't giving me any clues either. So I scaled down and scaled back up the dynos. This solved the problem for me:

heroku ps:scale web=0

Waited a few seconds...

heroku ps:scale web=1

Find all table names with column name?

Please try the below query. Use sys.columns to get the details :-

SELECT c.name AS ColName, t.name AS TableName
FROM sys.columns c
    JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%MyCol%';

Get size of all tables in database

From a command prompt using OSQL:

OSQL -E -d <*databasename*> -Q "exec sp_msforeachtable 'sp_spaceused [?]'" > result.txt

rebase in progress. Cannot commit. How to proceed or stop (abort)?

Another option to ABORT / SKIP / CONTINUE from IDE

VCS > Git > Abort Rebasing

enter image description here

What is the behavior of integer division?

Yes, the result is always truncated towards zero. It will round towards the smallest absolute value.

-5 / 2 = -2
 5 / 2 =  2

For unsigned and non-negative signed values, this is the same as floor (rounding towards -Infinity).

How to set viewport meta for iPhone that handles rotation properly?

You're setting it to not be able to scale (maximum-scale = initial-scale), so it can't scale up when you rotate to landscape mode. Set maximum-scale=1.6 and it will scale properly to fit landscape mode.

How to assign the output of a Bash command to a variable?

Here's your script...

DIR=$(pwd)
echo $DIR
while [ "$DIR" != "/" ]; do
    cd ..
    DIR=$(pwd)
    echo $DIR
done

Note the spaces, use of quotes, and $ signs.

Display the current date and time using HTML and Javascript with scrollable effects in hta application

Try this one:

HTML:

<div id="para1"></div>

JavaScript:

document.getElementById("para1").innerHTML = formatAMPM();

function formatAMPM() {
var d = new Date(),
    minutes = d.getMinutes().toString().length == 1 ? '0'+d.getMinutes() : d.getMinutes(),
    hours = d.getHours().toString().length == 1 ? '0'+d.getHours() : d.getHours(),
    ampm = d.getHours() >= 12 ? 'pm' : 'am',
    months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
    days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
return days[d.getDay()]+' '+months[d.getMonth()]+' '+d.getDate()+' '+d.getFullYear()+' '+hours+':'+minutes+ampm;
}

Result:

Mon Sep 18 2017 12:40pm

How to create image slideshow in html?

Instead of writing the code from the scratch you can use jquery plug in. Such plug in can provide many configuration option as well.

Here is the one I most liked.

http://www.zurb.com/playground/orbit-jquery-image-slider

n-grams in python, four, five, six grams?

People have already answered pretty nicely for the scenario where you need bigrams or trigrams but if you need everygram for the sentence in that case you can use nltk.util.everygrams

>>> from nltk.util import everygrams

>>> message = "who let the dogs out"

>>> msg_split = message.split()

>>> list(everygrams(msg_split))
[('who',), ('let',), ('the',), ('dogs',), ('out',), ('who', 'let'), ('let', 'the'), ('the', 'dogs'), ('dogs', 'out'), ('who', 'let', 'the'), ('let', 'the', 'dogs'), ('the', 'dogs', 'out'), ('who', 'let', 'the', 'dogs'), ('let', 'the', 'dogs', 'out'), ('who', 'let', 'the', 'dogs', 'out')]

Incase you have a limit like in case of trigrams where the max length should be 3 then you can use max_len param to specify it.

>>> list(everygrams(msg_split, max_len=2))
[('who',), ('let',), ('the',), ('dogs',), ('out',), ('who', 'let'), ('let', 'the'), ('the', 'dogs'), ('dogs', 'out')]

You can just modify the max_len param to achieve whatever gram i.e four gram, five gram, six or even hundred gram.

The previous mentioned solutions can be modified to implement the above mentioned solution but this solution is much straight forward than that.

For further reading click here

And when you just need a specific gram like bigram or trigram etc you can use the nltk.util.ngrams as mentioned in M.A.Hassan's answer.

How do I enable logging for Spring Security?

Basic debugging using Spring's DebugFilter can be configured like this:

@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.debug(true);
    }
}

How can I style even and odd elements?

but it's not working in IE. recommend using :nth-child(2n+1) :nth-child(2n+2)

_x000D_
_x000D_
li {_x000D_
    color: black;_x000D_
}_x000D_
li:nth-child(odd) {_x000D_
    color: #777;_x000D_
}_x000D_
li:nth-child(even) {_x000D_
    color: blue;_x000D_
}
_x000D_
<ul>_x000D_
    <li>ho</li>_x000D_
    <li>ho</li>_x000D_
    <li>ho</li>_x000D_
    <li>ho</li>_x000D_
    <li>ho</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

JavaScript open in a new window, not tab

OK, after making a lot of test, here my concluson:

When you perform:

     window.open('www.yourdomain.tld','_blank');
     window.open('www.yourdomain.tld','myWindow');

or whatever you put in the destination field, this will change nothing: the new page will be opened in a new tab (so depend on user preference)

If you want the page to be opened in a new "real" window, you must put extra parameter. Like:

window.open('www.yourdomain.tld', 'mywindow','location=1,status=1,scrollbars=1, resizable=1, directories=1, toolbar=1, titlebar=1');

After testing, it seems the extra parameter you use, dont' really matter: this is not the fact you put "this parameter" or "this other one" which create the new "real window" but the fact there is new parameter(s).

But something is confused and may explain a lot of wrong answers:

This:

 win1 = window.open('myurl1', 'ID_WIN');
 win2 = window.open('myurl2', 'ID_WIN', 'location=1,status=1,scrollbars=1');

And this:

 win2 = window.open('myurl2', 'ID_WIN', 'location=1,status=1,scrollbars=1');
 win1 = window.open('myurl1', 'ID_WIN');

will NOT give the same result.

In the first case, as you first open a page without extra parameter, it will open in a new tab. And in this case, the second call will be also opened in this tab because of the name you give.

In second case, as your first call is made with extra parameter, the page will be opened in a new "real window". And in that case, even if the second call is made without the extra parameter, it will also be opened in this new "real window"... but same tab!

This mean the first call is important as it decided where to put the page.

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

If you use proxy, you will have to edit the Nuget.config file.

In Windows 7 and 10, this file is in the path:
C:\Users\YouUser\AppData\Roaming\NuGet.

Include the setting:

<config>
  <add key = "http_proxy" value = "http://Youproxy:8080" />
  <add key = "http_proxy.user" value = "YouProxyUser" />
</config>

How to return a custom object from a Spring Data JPA GROUP BY query

Solution for JPQL queries

This is supported for JPQL queries within the JPA specification.

Step 1: Declare a simple bean class

package com.path.to;

public class SurveyAnswerStatistics {
  private String answer;
  private Long   cnt;

  public SurveyAnswerStatistics(String answer, Long cnt) {
    this.answer = answer;
    this.count  = cnt;
  }
}

Step 2: Return bean instances from the repository method

public interface SurveyRepository extends CrudRepository<Survey, Long> {
    @Query("SELECT " +
           "    new com.path.to.SurveyAnswerStatistics(v.answer, COUNT(v)) " +
           "FROM " +
           "    Survey v " +
           "GROUP BY " +
           "    v.answer")
    List<SurveyAnswerStatistics> findSurveyCount();
}

Important notes

  1. Make sure to provide the fully-qualified path to the bean class, including the package name. For example, if the bean class is called MyBean and it is in package com.path.to, the fully-qualified path to the bean will be com.path.to.MyBean. Simply providing MyBean will not work (unless the bean class is in the default package).
  2. Make sure to call the bean class constructor using the new keyword. SELECT new com.path.to.MyBean(...) will work, whereas SELECT com.path.to.MyBean(...) will not.
  3. Make sure to pass attributes in exactly the same order as that expected in the bean constructor. Attempting to pass attributes in a different order will lead to an exception.
  4. Make sure the query is a valid JPA query, that is, it is not a native query. @Query("SELECT ..."), or @Query(value = "SELECT ..."), or @Query(value = "SELECT ...", nativeQuery = false) will work, whereas @Query(value = "SELECT ...", nativeQuery = true) will not work. This is because native queries are passed without modifications to the JPA provider, and are executed against the underlying RDBMS as such. Since new and com.path.to.MyBean are not valid SQL keywords, the RDBMS then throws an exception.

Solution for native queries

As noted above, the new ... syntax is a JPA-supported mechanism and works with all JPA providers. However, if the query itself is not a JPA query, that is, it is a native query, the new ... syntax will not work as the query is passed on directly to the underlying RDBMS, which does not understand the new keyword since it is not part of the SQL standard.

In situations like these, bean classes need to be replaced with Spring Data Projection interfaces.

Step 1: Declare a projection interface

package com.path.to;

public interface SurveyAnswerStatistics {
  String getAnswer();

  int getCnt();
}

Step 2: Return projected properties from the query

public interface SurveyRepository extends CrudRepository<Survey, Long> {
    @Query(nativeQuery = true, value =
           "SELECT " +
           "    v.answer AS answer, COUNT(v) AS cnt " +
           "FROM " +
           "    Survey v " +
           "GROUP BY " +
           "    v.answer")
    List<SurveyAnswerStatistics> findSurveyCount();
}

Use the SQL AS keyword to map result fields to projection properties for unambiguous mapping.

XPath to get all child nodes (elements, comments, and text) without parent

Use this XPath expression:

/*/*/X/node()

This selects any node (element, text node, comment or processing instruction) that is a child of any X element that is a grand-child of the top element of the XML document.

To verify what is selected, here is this XSLT transformation that outputs exactly the selected nodes:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes"/>
 <xsl:template match="/">
  <xsl:copy-of select="/*/*/X/node()"/>
 </xsl:template>
</xsl:stylesheet>

and it produces exactly the wanted, correct result:

   First Text Node #1            
    <y> Y can Have Child Nodes #                
        <child> deep to it </child>
    </y>            Second Text Node #2 
    <z />

Explanation:

  1. As defined in the W3 XPath 1.0 Spec, "child::node() selects all the children of the context node, whatever their node type." This means that any element, text-node, comment-node and processing-instruction node children are selected by this node-test.

  2. node() is an abbreviation of child::node() (because child:: is the primary axis and is used when no axis is explicitly specified).

Java, looping through result set

Result Set are actually contains multiple rows of data, and use a cursor to point out current position. So in your case, rs4.getString(1) only get you the data in first column of first row. In order to change to next row, you need to call next()

a quick example

while (rs.next()) {
    String sid = rs.getString(1);
    String lid = rs.getString(2);
    // Do whatever you want to do with these 2 values
}

there are many useful method in ResultSet, you should take a look :)

Try-Catch-End Try in VBScript doesn't seem to work

VBScript doesn't have Try/Catch. (VBScript language reference. If it had Try, it would be listed in the Statements section.)

On Error Resume Next is the only error handling in VBScript. Sorry. If you want try/catch, JScript is an option. It's supported everywhere that VBScript is and has the same capabilities.

How can I remove the top and right axis in matplotlib?

If you need to remove it from all your plots, you can remove spines in style settings (style sheet or rcParams). E.g:

import matplotlib as mpl

mpl.rcParams['axes.spines.right'] = False
mpl.rcParams['axes.spines.top'] = False

If you want to remove all spines:

mpl.rcParams['axes.spines.left'] = False
mpl.rcParams['axes.spines.right'] = False
mpl.rcParams['axes.spines.top'] = False
mpl.rcParams['axes.spines.bottom'] = False

How to coerce a list object to type 'double'

If you want to convert all elements of a to a single numeric vector and length(a) is greater than 1 (OK, even if it is of length 1), you could unlist the object first and then convert.

as.numeric(unlist(a))
# [1]  10  38  66 101 129 185 283 374

Bear in mind that there aren't any quality controls here. Also, X$Days a mighty odd name.

Should I use window.navigate or document.location in JavaScript?

Late joining this conversation to shed light on a mildly interesting factoid for web-facing, analytics-aware websites. Passing the mic over to Michael Papworth:

https://github.com/michaelpapworth/jQuery.navigate

"When using website analytics, window.location is not sufficient due to the referer not being passed on the request. The plugin resolves this and allows for both aliased and parametrised URLs."

If one examines the code what it does is this:

   var methods = {
            'goTo': function (url) {
                // instead of using window.location to navigate away
                // we use an ephimeral link to click on and thus ensure
                // the referer (current url) is always passed on to the request
                $('<a></a>').attr("href", url)[0].click();
            },
            ...
   };

Neato!

How can I order a List<string>?

Other answers are correct to suggest Sort, but they seem to have missed the fact that the storage location is typed as IList<string. Sort is not part of the interface.

If you know that ListaServizi will always contain a List<string>, you can either change its declared type, or use a cast. If you're not sure, you can test the type:

if (typeof(List<string>).IsAssignableFrom(ListaServizi.GetType()))
    ((List<string>)ListaServizi).Sort();
else
{
    //... some other solution; there are a few to choose from.
}

Perhaps more idiomatic:

List<string> typeCheck = ListaServizi as List<string>;
if (typeCheck != null)
    typeCheck.Sort();
else
{
    //... some other solution; there are a few to choose from.
}

If you know that ListaServizi will sometimes hold a different implementation of IList<string>, leave a comment, and I'll add a suggestion or two for sorting it.

How to enable external request in IIS Express?

[project properties dialog]

For development using VisualStudio 2017 and a NetCore API-project:

1) In Cmd-Box: ipconfig /all to determine IP-address

2a) Enter the retrieved IP-address in Project properties-> Debug Tab

2b) Select a Port and attach that to the IP-address from step 2a.

3) Add an allow rule in the firewall to allow incoming TCP-traffic on the selected Port (my firewall triggered with a dialog: "Block or add rule to firewall"). Add will in that case do the trick.

Disadvantage of the solution above:

1) If you use a dynamic IP-address you need to redo the steps above in case another IP-address has been assigned.

2) You server has now an open Port which you might forget, but this open port remains an invitation for unwanted guests.

convert string to char*

First of all, you would have to allocate memory:

char * S = new char[R.length() + 1];

then you can use strcpy with S and R.c_str():

std::strcpy(S,R.c_str());

You can also use R.c_str() if the string doesn't get changed or the c string is only used once. However, if S is going to be modified, you should copy the string, as writing to R.c_str() results in undefined behavior.

Note: Instead of strcpy you can also use str::copy.

Excel is not updating cells, options > formula > workbook calculation set to automatic

In short

creating or moving some/all reference containing worksheets (out and) into your workbook may solve it.

More details

I had this issue after copying some sheets from "template" sheets/workbooks to some new "destination" workbook (the templates were provided by other users!):

I got:

  • workbook WbTempl1
    • with sheet WsTempl1RefDef (defining the references used e.g. in WsTempl2RefUsr below, e.g. project on A1)
  • workbook WbTempl2 (above references do not exist, because WsTempl1RefDef is not contained nor externally referenced, e.g. like WbTempl2.Names("project").refersTo="C:\WbTempl1.xls]'WsTempl1RefDef!A1")
    • contains sheet WsTempl2RefUsr (uses inexisting global references, e.g. =project)

and wanted to create a WbDst to copy WsTempl1RefDef and WsTempl2RefUsr into it.


The following did not work:

  1. create workbook WbDst
  2. copy sheet WsTempl1RefDef into it (references were locally created)
  3. copy sheet WsTempl2RefUsr into it

Here as well the Ctrl(SHIFT)ALTF9 nor Application.CalculateFullRebuild worked on WbDst.


The following worked:

  1. create workbook WbDst
  2. move (not copy) sheet WsTempl1RefDef into WbTempl2
    • (we do not have to save them)
  3. copy sheet WsTempl1RefDef into WbDst
  4. copy sheet WsTempl2RefUsr into WbDst

Using getResources() in non-activity class

This always works for me:

import android.app.Activity;
import android.content.Context;

public class yourClass {

 Context ctx;

 public yourClass (Handler handler, Context context) {
 super(handler);
    ctx = context;
 }

 //Use context (ctx) in your code like this:
 XmlPullParser xpp = ctx.getResources().getXml(R.xml.samplexml);
 //OR
 final Intent intent = new Intent(ctx, MainActivity.class);
 //OR
 NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
 //ETC...

}

Not related to this question but example using a Fragment to access system resources/activity like this:

public boolean onQueryTextChange(String newText) {
 Activity activity = getActivity();
 Context context = activity.getApplicationContext();
 returnSomething(newText);
 return false;
}

View customerInfo = getActivity().getLayoutInflater().inflate(R.layout.main_layout_items, itemsLayout, false);
 itemsLayout.addView(customerInfo);

Find directory name with wildcard or similar to "like"

find supports wildcard matches, just add a *:

find / -type d -name "ora10*"

How can I render a list select box (dropdown) with bootstrap?

The Bootstrap3 .form-control is cool but for those who love or need the drop-down with button and ul option, here is the updated code. I have edited the code by Steve to fix jumping to the hash link and closing the drop-down after selection.

Thanks to Steve, Ben and Skelly!

$(".dropdown-menu li a").click(function () {
    var selText = $(this).text();
    $(this).closest('div').find('button[data-toggle="dropdown"]').html(selText + ' <span class="caret"></span>');
    $(this).closest('.dropdown').removeClass("open");
    return false;
});

Is it possible to get only the first character of a String?

The string has a substring method that returns the string at the specified position.

String name="123456789";
System.out.println(name.substring(0,1));

HTML SELECT - Change selected option by VALUE using JavaScript

If you are using jQuery:

$('#sel').val('bike');

Python write line by line to a text file

Well, the problem you have is wrong line ending/encoding for notepad. Notepad uses Windows' line endings - \r\n and you use \n.

Pandas split column of lists into multiple columns

Based on the previous answers, here is another solution which returns the same result as df2.teams.apply(pd.Series) with a much faster run time:

pd.DataFrame([{x: y for x, y in enumerate(item)} for item in df2['teams'].values.tolist()], index=df2.index)

Timings:

In [1]:
import pandas as pd
d1 = {'teams': [['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],
                ['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG']]}
df2 = pd.DataFrame(d1)
df2 = pd.concat([df2]*1000).reset_index(drop=True)

In [2]: %timeit df2['teams'].apply(pd.Series)

8.27 s ± 2.73 s per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [3]: %timeit pd.DataFrame([{x: y for x, y in enumerate(item)} for item in df2['teams'].values.tolist()], index=df2.index)

35.4 ms ± 5.22 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Increase max execution time for php

Try to set a longer max_execution_time:

<IfModule mod_php5.c>
    php_value max_execution_time 300
</IfModule>

<IfModule mod_php7.c>
    php_value max_execution_time 300
</IfModule>

How does one get started with procedural generation?

Procedural generation is used heavily in the demoscene to create complex graphics in a small executable. Will Wright even said that he was inspired by the demoscene while making Spore. That may be your best place to start.

http://en.wikipedia.org/wiki/Demoscene

Nesting await in Parallel.ForEach

I am a little late to party but you may want to consider using GetAwaiter.GetResult() to run your async code in sync context but as paralled as below;

 Parallel.ForEach(ids, i =>
{
    ICustomerRepo repo = new CustomerRepo();
    // Run this in thread which Parallel library occupied.
    var cust = repo.GetCustomer(i).GetAwaiter().GetResult();
    customers.Add(cust);
});

MySQL - How to select rows where value is in array?

Use the FIND_IN_SET function:

SELECT t.*
  FROM YOUR_TABLE t
 WHERE FIND_IN_SET(3, t.ids) > 0

Retrieve filename from file descriptor in C

As Tyler points out, there's no way to do what you require "directly and reliably", since a given FD may correspond to 0 filenames (in various cases) or > 1 (multiple "hard links" is how the latter situation is generally described). If you do still need the functionality with all the limitations (on speed AND on the possibility of getting 0, 2, ... results rather than 1), here's how you can do it: first, fstat the FD -- this tells you, in the resulting struct stat, what device the file lives on, how many hard links it has, whether it's a special file, etc. This may already answer your question -- e.g. if 0 hard links you will KNOW there is in fact no corresponding filename on disk.

If the stats give you hope, then you have to "walk the tree" of directories on the relevant device until you find all the hard links (or just the first one, if you don't need more than one and any one will do). For that purpose, you use readdir (and opendir &c of course) recursively opening subdirectories until you find in a struct dirent thus received the same inode number you had in the original struct stat (at which time if you want the whole path, rather than just the name, you'll need to walk the chain of directories backwards to reconstruct it).

If this general approach is acceptable, but you need more detailed C code, let us know, it won't be hard to write (though I'd rather not write it if it's useless, i.e. you cannot withstand the inevitably slow performance or the possibility of getting != 1 result for the purposes of your application;-).

How to get label text value form a html page?

Try this:

document.getElementById('*spaM4').textContent

If you need to target < IE9 then you need to use .innerText

SQLite Query in Android to count rows

See rawQuery(String, String[]) and the documentation for Cursor

Your DADABASE_COMPARE SQL statement is currently invalid, loginname and loginpass won't be escaped, there is no space between loginname and the and, and you end the statement with ); instead of ; -- If you were logging in as bob with the password of password, that statement would end up as

select count(*) from users where uname=boband pwd=password);

Also, you should probably use the selectionArgs feature, instead of concatenating loginname and loginpass.

To use selectionArgs you would do something like

final String SQL_STATEMENT = "SELECT COUNT(*) FROM users WHERE uname=? AND pwd=?";

private void someMethod() {
    Cursor c = db.rawQuery(SQL_STATEMENT, new String[] { loginname, loginpass });
    ...
}

pycharm convert tabs to spaces automatically

For selections, you can also convert the selection using the "To spaces" function. I usually just use it via the ctrl-shift-A then find "To Spaces" from there.

Is it possible to get multiple values from a subquery?

you can use cross apply:

select
    a.x,
    bb.y,
    bb.z
from
    a
    cross apply
    (   select b.y, b.z
        from b
        where b.v = a.v
    ) bb

If there will be no row from b to mach row from a then cross apply wont return row. If you need such a rows then use outer apply

If you need to find only one specific row for each of row from a, try:

    cross apply
    (   select top 1 b.y, b.z
        from b
        where b.v = a.v
        order by b.order
    ) bb

Invoke-WebRequest, POST with parameters

For some picky web services, the request needs to have the content type set to JSON and the body to be a JSON string. For example:

Invoke-WebRequest -UseBasicParsing http://example.com/service -ContentType "application/json" -Method POST -Body "{ 'ItemID':3661515, 'Name':'test'}"

or the equivalent for XML, etc.