Programs & Examples On #Readonly attribute

How to create a readonly textbox in ASP.NET MVC3 Razor

@Html.TextBoxFor(model => model.IsActive, new { readonly= "readonly" })

This is just fine for text box. However, if you try to do same for the checkbox then try using this if you are using it:

@Html.CheckBoxFor(model => model.IsActive, new { onclick = "return false" })

But don't use disable, because disable always sends the default value false to the server - either it was in the checked or unchecked state. And the readonly does not work for checkbox and radio button. readonly only works for text fields.

How to delete a record in Django models?

If you want to delete one item

wishlist = Wishlist.objects.get(id = 20)
wishlist.delete()

If you want to delete all items in Wishlist for example

Wishlist.objects.all().delete()

How to center icon and text in a android button with width set to "fill parent"

This is my solution I wrote 3 years ago. Button has text and left icon and is in frame that is actual button here and can be stretched by fill_parent. I cannot test it again but it was working back then. Probably Button don't have to be used and can be replaced by TextView but I will not test it right now and it doesn't change functionality too much here.

<FrameLayout
    android:id="@+id/login_button_login"
    android:background="@drawable/apptheme_btn_default_holo_dark"
    android:layout_width="fill_parent"
    android:layout_gravity="center"
    android:layout_height="40dp">
    <Button
        android:clickable="false"
        android:drawablePadding="15dp"
        android:layout_gravity="center"
        style="@style/WhiteText.Small.Bold"
        android:drawableLeft="@drawable/lock"
        android:background="@color/transparent"
        android:text="LOGIN" />
</FrameLayout>

Convert string to JSON array

Using json lib:-

String data="[{"A":"a","B":"b","C":"c","D":"d","E":"e","F":"f","G":"g"}]";
Object object=null;
JSONArray arrayObj=null;
JSONParser jsonParser=new JSONParser();
object=jsonParser.parse(data);
arrayObj=(JSONArray) object;
System.out.println("Json object :: "+arrayObj);

Using GSON lib:-

Gson gson = new Gson();
String data="[{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\",\"D\":\"d\",\"E\":\"e\",\"F\":\"f\",\"G\":\"g\"}]";
JsonParser jsonParser = new JsonParser();
JsonArray jsonArray = (JsonArray) jsonParser.parse(data);

Resize iframe height according to content height in it

Here's my solution to the problem using MooTools which works in Firefox 3.6, Safari 4.0.4 and Internet Explorer 7:

var iframe_container = $('iframe_container_id');
var iframe_style = {
    height: 300,
    width: '100%'
};
if (!Browser.Engine.trident) {
    // IE has hasLayout issues if iframe display is none, so don't use the loading class
    iframe_container.addClass('loading');
    iframe_style.display = 'none';
}
this.iframe = new IFrame({
    frameBorder: 0,
    src: "http://www.youriframeurl.com/",
    styles: iframe_style,
    events: {
        'load': function() {
            var innerDoc = (this.contentDocument) ? this.contentDocument : this.contentWindow.document;
            var h = this.measure(function(){
                return innerDoc.body.scrollHeight;
            });            
            this.setStyles({
                height: h.toInt(),
                display: 'block'
            });
            if (!Browser.Engine.trident) {
                iframe_container.removeClass('loading');
            }
        }
    }
}).inject(iframe_container);

Style the "loading" class to show an Ajax loading graphic in the middle of the iframe container. Then for browsers other than Internet Explorer, it will display the full height IFRAME once the loading of its content is complete and remove the loading graphic.

How to prevent Google Colab from disconnecting?

Try this:

function ClickConnect(){
  console.log("Working"); 
  document
    .querySelector("#top-toolbar > colab-connect-button")
    .shadowRoot
    .querySelector("#connect")
    .click()
}

setInterval(ClickConnect,60000)

What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method?

A static variable shares the value of it among all instances of the class.

Example without declaring it static:

public class Variable
{
    public int i = 5;
    public void test()
    {
        i = i + 5;
        Console.WriteLine(i);
    }
}


public class Exercise
{
    static void Main()
    {
        Variable var = new Variable();
        var.test();
        Variable var1 = new Variable();
        var1.test();
        Console.ReadKey();
    }
}

Explanation: If you look at the above example, I just declare the int variable. When I run this code the output will be 10 and 10. Its simple.

Now let's look at the static variable here; I am declaring the variable as a static.

Example with static variable:

public class Variable
{
    public static int i = 5;
    public void test()
    {
        i = i + 5;
        Console.WriteLine(i);
    }
}


public class Exercise
{
    static void Main()
    {
        Variable var = new Variable();
        var.test();
        Variable var1 = new Variable();
        var1.test();
        Console.ReadKey();
    }
}

Now when I run above code, the output will be 10 and 15. So the static variable value is shared among all instances of that class.

Get just the filename from a path in a Bash script

Most UNIX-like operating systems have a basename executable for a very similar purpose (and dirname for the path):

pax> a=/tmp/file.txt
pax> b=$(basename $a)
pax> echo $b
file.txt

That unfortunately just gives you the file name, including the extension, so you'd need to find a way to strip that off as well.

So, given you have to do that anyway, you may as well find a method that can strip off the path and the extension.

One way to do that (and this is a bash-only solution, needing no other executables):

pax> a=/tmp/xx/file.tar.gz
pax> xpath=${a%/*} 
pax> xbase=${a##*/}
pax> xfext=${xbase##*.}
pax> xpref=${xbase%.*}
pax> echo;echo path=${xpath};echo pref=${xpref};echo ext=${xfext}

path=/tmp/xx
pref=file.tar
ext=gz

That little snippet sets xpath (the file path), xpref (the file prefix, what you were specifically asking for) and xfext (the file extension).

How to get an object's methods?

var funcs = []
for(var name in myObject) {
    if(typeof myObject[name] === 'function') {
        funcs.push(name)
    }
}

I'm on a phone with no semi colons :) but that is the general idea.

How to delete all the rows in a table using Eloquent?

Solution who works with Lumen 5.5 with foreign keys constraints :

$categories = MusicCategory::all();
foreach($categories as $category)
{
$category->delete();

}
return response()->json(['error' => false]);

How to adjust an UIButton's imageSize?

One approach is to resize the UIImage in code like the following. Note: this code only scales by height, but you can easily adjust the function to scale by width as well.

let targetHeight = CGFloat(28)
let newImage = resizeImage(image: UIImage(named: "Image.png")!, targetHeight: targetHeight)
button.setImage(newImage, for: .normal)

fileprivate func resizeImage(image: UIImage, targetHeight: CGFloat) -> UIImage {
    // Get current image size
    let size = image.size

    // Compute scaled, new size
    let heightRatio = targetHeight / size.height
    let newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
    let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)

    // Create new image
    UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
    image.draw(in: rect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    // Return new image
    return newImage!
}

How to perform keystroke inside powershell?

If I understand correctly, you want PowerShell to send the ENTER keystroke to some interactive application?

$wshell = New-Object -ComObject wscript.shell;
$wshell.AppActivate('title of the application window')
Sleep 1
$wshell.SendKeys('~')

If that interactive application is a PowerShell script, just use whatever is in the title bar of the PowerShell window as the argument to AppActivate (by default, the path to powershell.exe). To avoid ambiguity, you can have your script retitle its own window by using the title 'new window title' command.

A few notes:

  • The tilde (~) represents the ENTER keystroke. You can also use {ENTER}, though they're not identical - that's the keypad's ENTER key. A complete list is available here: http://msdn.microsoft.com/en-us/library/office/aa202943%28v=office.10%29.aspx.
  • The reason for the Sleep 1 statement is to wait 1 second because it takes a moment for the window to activate, and if you invoke SendKeys immediately, it'll send the keys to the PowerShell window, or to nowhere.
  • Be aware that this can be tripped up, if you type anything or click the mouse during the second that it's waiting, preventing to window you activate with AppActivate from being active. You can experiment with reducing the amount of time to find the minimum that's reliably sufficient on your system (Sleep accepts decimals, so you could try .5 for half a second). I find that on my 2.6 GHz Core i7 Win7 laptop, anything less than .8 seconds has a significant failure rate. I use 1 second to be safe.
  • IMPORTANT WARNING: Be extra careful if you're using this method to send a password, because activating a different window between invoking AppActivate and invoking SendKeys will cause the password to be sent to that different window in plain text!

Sometimes wscript.shell's SendKeys method can be a little quirky, so if you run into problems, replace the fourth line above with this:

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.SendKeys]::SendWait('~');

Is there a "previous sibling" selector?

I needed a solution to select the previous sibling tr. I came up with this solution using React and Styled-components. This is not my exact solution (This is from memory, hours later). I know there is a flaw in the setHighlighterRow function.

OnMouseOver a row will set the row index to state, and rerender the previous row with a new background color

class ReactClass extends Component {
  constructor() {
    this.state = {
       highlightRowIndex: null
    }
  }

  setHighlightedRow = (index) => {
    const highlightRowIndex = index === null ? null : index - 1;
    this.setState({highlightRowIndex});
  }

  render() {
    return (
       <Table>
        <Tbody>
           {arr.map((row, index) => {
                const isHighlighted = index === this.state.highlightRowIndex
                return {
                    <Trow 
                        isHighlighted={isHighlighted}
                        onMouseOver={() => this.setHighlightedRow(index)}
                        onMouseOut={() => this.setHighlightedRow(null)}
                        >
                        ...
                    </Trow>
                }
           })}  
        </Tbody>   
       </Table>
    )
  }
}

const Trow = styled.tr`
    & td {
        background-color: ${p => p.isHighlighted ? 'red' : 'white'};
    }

    &:hover {
        background-color: red;
    }
`;

How to get the current time as datetime

func getCurrentDate() -> Date {
    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    let dateInString  = dateFormatter.string(from: date)
    let dateinDate = dateFormatter.date(from: dateInString)
    return dateinDate!
}

Get current date in DD-Mon-YYY format in JavaScript/Jquery

var date = new Date();

console.log(date.toJSON().slice(0,10).replace(new RegExp("-", 'g'),"/" ).split("/").reverse().join("/")+" "+date.toJSON().slice(11,19));

// output : 01/09/2016 18:30:00

Cross browser JavaScript (not jQuery...) scroll to top animation

No one mentioned the CSS property scroll-behavior

CSS

html {
  scroll-behavior: smooth;
}

JS

window.scrollTo(0,0)

Java enum - why use toString instead of name

It really depends on what you want to do with the returned value:

  • If you need to get the exact name used to declare the enum constant, you should use name() as toString may have been overriden
  • If you want to print the enum constant in a user friendly way, you should use toString which may have been overriden (or not!).

When I feel that it might be confusing, I provide a more specific getXXX method, for example:

public enum Fields {
    LAST_NAME("Last Name"), FIRST_NAME("First Name");

    private final String fieldDescription;

    private Fields(String value) {
        fieldDescription = value;
    }

    public String getFieldDescription() {
        return fieldDescription;
    }
}

Configure Nginx with proxy_pass

Nginx prefers prefix-based location matches (not involving regular expression), that's why in your code block, /stash redirects are going to /.

The algorithm used by Nginx to select which location to use is described thoroughly here: https://www.digitalocean.com/community/tutorials/understanding-nginx-server-and-location-block-selection-algorithms#matching-location-blocks

Checking if float is an integer

if (f <= LONG_MIN || f >= LONG_MAX || f == (long)f) /* it's an integer */

asp.net: Invalid postback or callback argument

After having this problem on remote servers (production, test, qa, staging, etc), but not on local development workstations, I found that the Application Pool was configured with a RequestLimit other than 0.

This caused the app pool to give up and reply with the exception noted in the question.

Somewhere along the way my installshield project had its App pool definition changed to use "3" (probably just a mis-click or mis-type).

Put icon inside input element in a form

I had situation like this. It didn't work because of background: #ebebeb;. I wanted to put background on the input field and that property was constantly showing up on the top of the background image, and i couldn't see the image! So, I moved the background property to be above the background-image property and it worked.

input[type='text'] {
    border: 0;
    background-image: url('../img/search.png');
    background-position: 9px 20px;
    background-repeat: no-repeat;
    text-align: center;
    padding: 14px;
    background: #ebebeb;
}

Solution for my case was:

input[type='text'] {
    border: 0;
    background: #ebebeb;
    background-image: url('../img/search.png');
    background-position: 9px 20px;
    background-repeat: no-repeat;
    text-align: center;
    padding: 14px;
}

Just to mention, border, padding and text-align properties are not important for the solution. I just replicated my original code.

ASP.NET Temporary files cleanup

Just an update on more current OS's (Vista, Win7, etc.) - the temp file path has changed may be different based on several variables. The items below are not definitive, however, they are a few I have encountered:

"temp" environment variable setting - then it would be:

%temp%\Temporary ASP.NET Files

Permissions and what application/process (VS, IIS, IIS Express) is running the .Net compiler. Accessing the C:\WINDOWS\Microsoft.NET\Framework folders requires elevated permissions and if you are not developing under an account with sufficient permissions then this folder might be used:

c:\Users\[youruserid]\AppData\Local\Temp\Temporary ASP.NET Files

There are also cases where the temp folder can be set via config for a machine or site specific using this:

<compilation tempDirectory="d:\MyTempPlace" />

I even have a funky setup at work where we don't run Admin by default, plus the IT guys have login scripts that set %temp% and I get temp files in 3 different locations depending on what is compiling things! And I'm still not certain about how these paths get picked....sigh.

Still, dthrasher is correct, you can just delete these and VS and IIS will just recompile them as needed.

How do I read from parameters.yml in a controller in symfony2?

In Symfony 4.3.1 I use this:

services.yaml

HTTP_USERNAME: 'admin'
HTTP_PASSWORD: 'password123'

FrontController.php

$username = $this->container->getParameter('HTTP_USERNAME');
$password = $this->container->getParameter('HTTP_PASSWORD');

X-Frame-Options: ALLOW-FROM in firefox and chrome

I posted this question and never saw the feedback (which came in several months after, it seems :).

As Kinlan mentioned, ALLOW-FROM is not supported in all browsers as an X-Frame-Options value.

The solution was to branch based on browser type. For IE, ship X-Frame-Options. For everyone else, ship X-Content-Security-Policy.

Hope this helps, and sorry for taking so long to close the loop!

What is the best way to compare floats for almost-equality in Python?

In terms of absolute error, you can just check

if abs(a - b) <= error:
    print("Almost equal")

Some information of why float act weird in Python https://youtu.be/v4HhvoNLILk?t=1129

You can also use math.isclose for relative errors

Authentication plugin 'caching_sha2_password' cannot be loaded

If you are getting this error on GitLab CI like me: Just change from latest to 5.7 version ;)

# .gitlab-ci.yml

rspec:
  services:
    # - mysql:latest (I'm using latest version and it causes error)
    - mysql:5.7 #(then I've changed to this specific version and fix!)

Values of disabled inputs will not be submitted

disabled input will not submit data.

Use the readonly attribute:

<input type="text" readonly />

Source here

SOAP-ERROR: Parsing WSDL: Couldn't load from - but works on WAMP

Adding ?wsdl at the end and calling the method:

$client->__setLocation('url?wsdl'); 

helped to me.

How to get table cells evenly spaced?

I'm also open to suggestion on how to tidy this up, if there are any? :-)

Well, you could not use the span element, for semantic reasons. And you don't have to define the class PerformanceCell. The cells and rows can be accessed by using PerformanceTable tr {} and PerformanceTable tr {}, respectively.

For the spacing part, I have got the same problem several times. I shamefully admit I avoided the problem, so I am very curious to any answers too.

text box input height

Just use CSS to increase it's height:

<input type="text" style="height:30px;" name="item" align="left" />

Or, often times, you want to increase it's height by using padding instead of specifying an exact height:

<input type="text" style="padding: 5px;" name="item" align="left" />

node.js vs. meteor.js what's the difference?

Meteor's strength is in it's real-time updates feature which works well for some of the social applications you see nowadays where you see everyone's updates for what you're working on. These updates center around replicating subsets of a MongoDB collection underneath the covers as local mini-mongo (their client side MongoDB subset) database updates on your web browser (which causes multiple render events to be fired on your templates). The latter part about multiple render updates is also the weakness. If you want your UI to control when the UI refreshes (e.g., classic jQuery AJAX pages where you load up the HTML and you control all the AJAX calls and UI updates), you'll be fighting this mechanism.

Meteor uses a nice stack of Node.js plugins (Handlebars.js, Spark.js, Bootstrap css, etc. but using it's own packaging mechanism instead of npm) underneath along w/ MongoDB for the storage layer that you don't have to think about. But sometimes you end up fighting it as well...e.g., if you want to customize the Bootstrap theme, it messes up the loading sequence of Bootstrap's responsive.css file so it no longer is responsive (but this will probably fix itself when Bootstrap 3.0 is released soon).

So like all "full stack frameworks", things work great as long as your app fits what's intended. Once you go beyond that scope and push the edge boundaries, you might end up fighting the framework...

How to view file diff in git before commit

Another technique to consider if you want to compare a file to the last commit which is more pedantic:

git diff master myfile.txt

The advantage with this technique is you can also compare to the penultimate commit with:

git diff master^ myfile.txt

and the one before that:

git diff master^^ myfile.txt

Also you can substitute '~' for the caret '^' character and 'you branch name' for 'master' if you are not on the master branch.

How to create an empty file with Ansible?

Another option, using the command module:

- name: Create file
  command: touch /path/to/file
  args:
    creates: /path/to/file

The 'creates' argument ensures that this action is not performed if the file exists.

I want to delete all bin and obj folders to force all projects to rebuild everything

For the solution in batch. I am using the following command:

FOR /D /R %%G in (obj,bin) DO @IF EXIST %%G IF %%~aG geq d RMDIR /S /Q "%%G"


The reason not using DIR /S /AD /B xxx
1. DIR /S /AD /B obj will return empty list (at least on my Windows10) enter image description here
2. DIR /S /AD /B *obj will contain the result which is not expected (tobj folder) enter image description here

Set Memory Limit in htaccess

In your .htaccess you can add:

PHP 5.x

<IfModule mod_php5.c>
    php_value memory_limit 64M
</IfModule>

PHP 7.x

<IfModule mod_php7.c>
    php_value memory_limit 64M
</IfModule>

If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.

If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.

Read more on http://support.tigertech.net/php-value

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

Using a HTTP debugging proxy can cause this - such as Fiddler.

I was loading a PFX certificate from a local file (authentication to Apple.com) and it failed because Fiddler wasn't able to pass this certificate on.

Try disabling Fiddler to check and if that is the solution then you need to probably install the certificate on your machine or in some way that Fiddler can use it.

Combine or merge JSON on node.js without jQuery

I see that this thread is too old, but I put my answer here just in logging purposes.

In one of the comments above you mentioned that you wanted to use 'express' in your project which has 'connect' library in the dependency list. Actually 'connect.utils' library contains a 'merge' method that does the trick. So you can use the 3rd party implementation without adding any new 3rd party libraries.

Is there a way to rollback my last push to Git?

First you need to determine the revision ID of the last known commit. You can use HEAD^ or HEAD~{1} if you know you need to reverse exactly one commit.

git reset --hard <revision_id_of_last_known_good_commit>
git push --force

Center form submit buttons HTML / CSS

I'm assuming that the buttons are supposed to be next to each other on the same line, they should not each be centered using the 'auto' margin, but placed inside a div with a defined width that has a margin '0 auto':

CSS:

#centerbuttons{
   width:250px; 
   margin:0 auto;
}       

HTML (after removing the margin properties from your buttons' CSS):

<div id="centerbuttons">
     <input value="Search" title="Search" type="submit"> 
     <input value="I'm Feeling Lucky" title="I'm Feeling Lucky" name="lucky" type="submit">
</div>

Detect if a Form Control option button is selected in VBA

You should remove .Value from all option buttons because option buttons don't hold the resultant value, the option group control does. If you omit .Value then the default interface will report the option button status, as you are expecting. You should write all relevant code under commandbutton_click events because whenever the commandbutton is clicked the option button action will run.

If you want to run action code when the optionbutton is clicked then don't write an if loop for that.

EXAMPLE:

Sub CommandButton1_Click
    If OptionButton1 = true then
        (action code...)
    End if
End sub

Sub OptionButton1_Click   
    (action code...)
End sub

Exists Angularjs code/naming conventions?

For structuring an app, this is one of the best guides that I've found:

Note that the structure recommended by Google is different than what you'll find in a lot of seed projects, but for large apps it's a lot saner.

Google also has a style guide that makes sense to use only if you also use Closure.


...this answer is incomplete, but I hope that the limited information above will be helpful to someone.

How to modify STYLE attribute of element with known ID using JQuery

Not sure I completely understand the question but:

$(":button.brown").click(function() {
  $(":button.brown.selected").removeClass("selected");
  $(this).addClass("selected");
});

seems to be along the lines of what you want.

I would certainly recommend using classes instead of directly setting CSS, which is problematic for several reasons (eg removing styles is non-trivial, removing classes is easy) but if you do want to go that way:

$("...").css("background", "brown");

But when you want to reverse that change, what do you set it to?

Is there a default password to connect to vagrant when using `homestead ssh` for the first time?

By default Vagrant uses a generated private key to login, you can try this:

ssh -l ubuntu -p 2222 -i .vagrant/machines/default/virtualbox/private_key 127.0.0.1

npm behind a proxy fails with status 403

I had the same issue and finally it was resolved by disconnecting from all VPN .

How to get the unix timestamp in C#

Updated code from Brad with few things: You don't need Math.truncate, conversion to int or long automatically truncates the value. In my version I am using long instead of int (We will run out of 32 bit signed integers in 2038 year). Also, added timestamp parsing.

public static class DateTimeHelper
{
    /// <summary>
     /// Converts a given DateTime into a Unix timestamp
     /// </summary>
     /// <param name="value">Any DateTime</param>
     /// <returns>The given DateTime in Unix timestamp format</returns>
    public static long ToUnixTimestamp(this DateTime value)
    {
        return (long)(value.ToUniversalTime().Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
    }

    /// <summary>
    /// Gets a Unix timestamp representing the current moment
    /// </summary>
    /// <param name="ignored">Parameter ignored</param>
    /// <returns>Now expressed as a Unix timestamp</returns>
    public static long UnixTimestamp(this DateTime ignored)
    {
        return (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
    }

    /// <summary>
    /// Returns a local DateTime based on provided unix timestamp
    /// </summary>
    /// <param name="timestamp">Unix/posix timestamp</param>
    /// <returns>Local datetime</returns>
    public static DateTime ParseUnixTimestamp(long timestamp)
    {
        return (new DateTime(1970, 1, 1)).AddSeconds(timestamp).ToLocalTime();
    }

}

Convert a CERT/PEM certificate to a PFX certificate

openssl pkcs12 -inkey bob_key.pem -in bob_cert.cert -export -out bob_pfx.pfx

How to add element into ArrayList in HashMap

I know, this is an old question. But just for the sake of completeness, the lambda version.

Map<String, List<Item>> items = new HashMap<>();
items.computeIfAbsent(key, k -> new ArrayList<>()).add(item);

How to solve “Microsoft Visual Studio (VS)” error “Unable to connect to the configured development Web server”

I am using visual studio 2015. Deleting .vs folder in the project folder helped me to fix this. You must close the visual studio first.

How do I efficiently iterate over each entry in a Java Map?

FYI, you can also use map.keySet() and map.values() if you're only interested in keys/values of the map and not the other.

Best way to format multiple 'or' conditions in an if statement (Java)

I use this kind of pattern often. It's very compact:

// Define a constant in your class. Use a HashSet for performance
private static final Set<Integer> values = new HashSet<Integer>(Arrays.asList(12, 16, 19));

// In your method:
if (values.contains(x)) {
    ...
}

A HashSet is used here to give good look-up performance - even very large hash sets are able to execute contains() extremely quickly.

If performance is not important, you can code the gist of it into one line:

if (Arrays.asList(12, 16, 19).contains(x))

but know that it will create a new ArrayList every time it executes.

Bootstrap 4 File Input

Updated 2021

Bootstrap 5

Custom file input no longer exists so to change Choose file... you'd need to use JS or some CSS like this.

Bootstrap 4.4

Displaying the selected filename can also be done with plain JavaScript. Here's an example that assumes the standard custom-file-input with label that is the next sibling element to the input...

document.querySelector('.custom-file-input').addEventListener('change',function(e){
  var fileName = document.getElementById("myInput").files[0].name;
  var nextSibling = e.target.nextElementSibling
  nextSibling.innerText = fileName
})

https://codeply.com/p/LtpNZllird

Bootstrap 4.1+

Now in Bootstrap 4.1 the "Choose file..." placeholder text is set in the custom-file-label:

<div class="custom-file" id="customFile" lang="es">
        <input type="file" class="custom-file-input" id="exampleInputFile" aria-describedby="fileHelp">
        <label class="custom-file-label" for="exampleInputFile">
           Select file...
        </label>
</div>

Changing the "Browse" button text requires a little extra CSS or SASS. Also notice how language translation works using the lang="" attribute.

.custom-file-input ~ .custom-file-label::after {
    content: "Button Text";
}

https://codeply.com/go/gnVCj66Efp (CSS)
https://codeply.com/go/2Mo9OrokBQ (SASS)

Another Bootstrap 4.1 Option

Alternatively you can use this custom file input plugin

https://www.codeply.com/go/uGJOpHUd8L/file-input


Bootstrap 4 Alpha 6 (Original Answer)

I think there are 2 separate issues here..

<label class="custom-file" id="customFile">
        <input type="file" class="custom-file-input">
        <span class="custom-file-control form-control-file"></span>
</label>

1 - How the change the initial placeholder and button text

In Bootstrap 4, the initial placeholder value is set on the custom-file-control with a CSS pseudo ::after element based on the HTML language. The initial file button (which isn't really a button but looks like one) is set with a CSS pseudo ::before element. These values can be overridden with CSS..

#customFile .custom-file-control:lang(en)::after {
  content: "Select file...";
}

#customFile .custom-file-control:lang(en)::before {
  content: "Click me";
}

2 - How to get the selected filename value, and update the input to show the value.

Once a file is selected, the value can be obtained using JavaScript/jQuery.

$('.custom-file-input').on('change',function(){
    var fileName = $(this).val();
})

However, since the placeholder text for the input is a pseudo element, there's no easy way to manipulate this with Js/jQuery. You can however, have a another CSS class that hides the pseudo content once the file is selected...

.custom-file-control.selected:lang(en)::after {
  content: "" !important;
}

Use jQuery to toggle the .selected class on the .custom-file-control once the file is selected. This will hide the initial placeholder value. Then put the filename value in the .form-control-file span...

$('.custom-file-input').on('change',function(){
  var fileName = $(this).val();
  $(this).next('.form-control-file').addClass("selected").html(fileName);
})

You can then handle the file upload or re-selection as needed.

Demo on Codeply (alpha 6)

How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#

I like the WMILinq solution. While not exactly the solution to your problem, find below a taste of it :

using (WmiContext context = new WmiContext(@"\\.")) {

  context.ManagementScope.Options.Impersonation = ImpersonationLevel.Impersonate;
  context.Log = Console.Out;

  var dnss = from nic in context.Source<Win32_NetworkAdapterConfiguration>()
          where nic.IPEnabled
          select nic;

  var ips = from s in dnss.SelectMany(dns => dns.DNSServerSearchOrder)
          select IPAddress.Parse(s);
}  

http://www.codeplex.com/linq2wmi

SVN "Already Locked Error"

I had the same problem, It was solved when I checked the below checkbox

How do I convert a column of text URLs into active hyperlinks in Excel?

  1. Create a temporary new column of hyperlinks using formula =HYPERLINK()
  2. Copy that column into Microsoft Word (copy to clipboard only after Word is running).
  3. Copy everything in the new word document (ctrl+a, then ctrl+c).
  4. Paste into Excel, replacing the original column of text. Delete the temporary column with the formula.

excel vba getting the row,cell value from selection.address

Is this what you are looking for ?

Sub getRowCol()

    Range("A1").Select ' example

    Dim col, row
    col = Split(Selection.Address, "$")(1)
    row = Split(Selection.Address, "$")(2)

    MsgBox "Column is : " & col
    MsgBox "Row is : " & row

End Sub

How to mark a build unstable in Jenkins when running shell scripts

It can be done without printing magic strings and using TextFinder. Here's some info on it.

Basically you need a .jar file from http://yourserver.com/cli available in shell scripts, then you can use the following command to mark a build unstable:

java -jar jenkins-cli.jar set-build-result unstable

To mark build unstable on error, you can use:

failing_cmd cmd_args || java -jar jenkins-cli.jar set-build-result unstable

The problem is that jenkins-cli.jar has to be available from shell script. You can either put it in easy-to-access path, or download in via job's shell script:

wget ${JENKINS_URL}jnlpJars/jenkins-cli.jar

Import and Export Excel - What is the best library?

There's a pretty good article and library on CodeProject by Yogesh Jagota:

Excel XML Import-Export Library

I've used it to export data from SQL queries and other data sources to Excel - works just fine for me.

Cheers

How can I set the form action through JavaScript?

Plain JavaScript:

document.getElementById('form_id').action; //Will retrieve it

document.getElementById('form_id').action = "script.php"; //Will set it

Using jQuery...

$("#form_id").attr("action"); //Will retrieve it

$("#form_id").attr("action", "/script.php"); //Will set it

Java difference between FileWriter and BufferedWriter

BufferedWriter is more efficient. It saves up small writes and writes in one larger chunk if memory serves me correctly. If you are doing lots of small writes then I would use BufferedWriter. Calling write calls to the OS which is slow so having as few writes as possible is usually desirable.

Prevent flex items from stretching

You don't want to stretch the span in height?
You have the possiblity to affect one or more flex-items to don't stretch the full height of the container.

To affect all flex-items of the container, choose this:
You have to set align-items: flex-start; to div and all flex-items of this container get the height of their content.

_x000D_
_x000D_
div {_x000D_
  align-items: flex-start;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}
_x000D_
<div>_x000D_
  <span>This is some text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

To affect only a single flex-item, choose this:
If you want to unstretch a single flex-item on the container, you have to set align-self: flex-start; to this flex-item. All other flex-items of the container aren't affected.

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
  background: tan;_x000D_
}_x000D_
span.only {_x000D_
  background: red;_x000D_
  align-self:flex-start;_x000D_
}_x000D_
span {_x000D_
    background:green;_x000D_
}
_x000D_
<div>_x000D_
  <span class="only">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why is this happening to the span?
The default value of the property align-items is stretch. This is the reason why the span fill the height of the div.

Difference between baseline and flex-start?
If you have some text on the flex-items, with different font-sizes, you can use the baseline of the first line to place the flex-item vertically. A flex-item with a smaller font-size have some space between the container and itself at top. With flex-start the flex-item will be set to the top of the container (without space).

_x000D_
_x000D_
div {_x000D_
  align-items: baseline;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}_x000D_
span.fontsize {_x000D_
  font-size:2em;_x000D_
}
_x000D_
<div>_x000D_
  <span class="fontsize">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can find more information about the difference between baseline and flex-start here:
What's the difference between flex-start and baseline?

Git: See my last commit

If you're talking about finding the latest and greatest commit after you've performed a git checkout of some earlier commit (and forgot to write down HEAD's hash prior to executing the checkout) most of the above won't get you back to where you started. git log -[some #] only shows the log from the CURRENT position of HEAD, which is not necessarily the very last commit (state of the project). Checkout will disconnect the HEAD and point it to whatever you checked out.

You could view the entire git reflog, until reaching the entry referencing the original clone. BTW, this too won't work if any commits were made between the time you cloned the project and when you performed a checkout. Otherwise you can hope all your commits on your local machine are on the server, and then re-clone the entire project.

Hope this helps.

Java Spring Boot: How to map my app root (“/”) to index.html?

if it is a Spring boot App.

Spring Boot automatically detects index.html in public/static/webapp folder. If you have written any controller @Requestmapping("/") it will override the default feature and it will not show the index.html unless you type localhost:8080/index.html

How do I install a Python package with a .whl file?

First, make sure you have updated pip to enable wheel support:

pip install --upgrade pip

Then, to install from wheel, give it the directory where the wheel is downloaded. For example, to install package_name.whl:

pip install --use-wheel --no-index --find-links=/where/its/downloaded package_name

Using ORDER BY and GROUP BY together

Here is the simplest solution

select m_id,v_id,max(timestamp) from table group by m_id;

Group by m_id but get max of timestamp for each m_id.

What does #defining WIN32_LEAN_AND_MEAN exclude exactly?

Directly from the Windows.h header file:

#ifndef WIN32_LEAN_AND_MEAN
    #include <cderr.h>
    #include <dde.h>
    #include <ddeml.h>
    #include <dlgs.h>
    #ifndef _MAC
        #include <lzexpand.h>
        #include <mmsystem.h>
        #include <nb30.h>
        #include <rpc.h>
    #endif
    #include <shellapi.h>
    #ifndef _MAC
        #include <winperf.h>
        #include <winsock.h>
    #endif
    #ifndef NOCRYPT
        #include <wincrypt.h>
        #include <winefs.h>
        #include <winscard.h>
    #endif

    #ifndef NOGDI
        #ifndef _MAC
            #include <winspool.h>
            #ifdef INC_OLE1
                #include <ole.h>
            #else
                #include <ole2.h>
            #endif /* !INC_OLE1 */
        #endif /* !MAC */
        #include <commdlg.h>
    #endif /* !NOGDI */
#endif /* WIN32_LEAN_AND_MEAN */

if you want to know what each of the headers actually do, typeing the header names into the search in the MSDN library will usually produce a list of the functions in that header file.

Also, from Microsoft's support page:

To speed the build process, Visual C++ and the Windows Headers provide the following new defines:

VC_EXTRALEAN
WIN32_LEAN_AND_MEAN

You can use them to reduce the size of the Win32 header files.

Finally, if you choose to use either of these preprocessor defines, and something you need is missing, you can just include that specific header file yourself. Typing the name of the function you're after into MSDN will usually produce an entry which will tell you which header to include if you want to use it, at the bottom of the page.

Is it possible to CONTINUE a loop from an exception?

Notice you can use WHEN exception THEN NULL the same way as you would use WHEN exception THEN continue. Example:

    DECLARE
        extension_already_exists  EXCEPTION;
        PRAGMA EXCEPTION_INIT(extension_already_exists, -20007);
        l_hidden_col_name  varchar2(32);
    BEGIN
        FOR t IN (  SELECT table_name, cast(extension as varchar2(200)) ext
                    FROM all_stat_extensions
                    WHERE owner='{{ prev_schema }}'
                      and droppable='YES'
                    ORDER BY 1
                 )
        LOOP
            BEGIN
                l_hidden_col_name := dbms_stats.create_extended_stats('{{ schema }}', t.table_name, t.ext);
            EXCEPTION
                WHEN extension_already_exists THEN NULL;   -- ignore exception and go to next loop iteration
            END;
        END LOOP;
    END;

Codeigniter $this->db->order_by(' ','desc') result is not complete

Put from before where, and order_by on last:

$this->db->select('*');
$this->db->from('courses');
$this->db->where('tennant_id',$tennant_id);
$this->db->order_by("UPPER(course_name)","desc");

Or try BINARY:

ORDER BY BINARY course_name DESC;

You should add manually on codeigniter for binary sorting.

And set "course_name" character column.

If sorting is used on a character type column, normally the sort is conducted in a case-insensitive fashion.

What type of structure data in courses table?

If you frustrated you can put into array and return using PHP:

Use natcasesort for order in "natural order": (Reference: http://php.net/manual/en/function.natcasesort.php)

Your array from database as example: $array_db = $result_from_db:

$final_result = natcasesort($array_db);

print_r($final_result);

MySQL: Curdate() vs Now()

CURDATE() will give current date while NOW() will give full date time.

Run the queries, and you will find out whats the difference between them.

SELECT NOW();     -- You will get 2010-12-09 17:10:18
SELECT CURDATE(); -- You will get 2010-12-09

How to represent multiple conditions in a shell if statement?

Classic technique (escape metacharacters):

if [ \( "$g" -eq 1 -a "$c" = "123" \) -o \( "$g" -eq 2 -a "$c" = "456" \) ]
then echo abc
else echo efg
fi

I've enclosed the references to $g in double quotes; that's good practice, in general. Strictly, the parentheses aren't needed because the precedence of -a and -o makes it correct even without them.

Note that the -a and -o operators are part of the POSIX specification for test, aka [, mainly for backwards compatibility (since they were a part of test in 7th Edition UNIX, for example), but they are explicitly marked as 'obsolescent' by POSIX. Bash (see conditional expressions) seems to preempt the classic and POSIX meanings for -a and -o with its own alternative operators that take arguments.


With some care, you can use the more modern [[ operator, but be aware that the versions in Bash and Korn Shell (for example) need not be identical.

for g in 1 2 3
do
    for c in 123 456 789
    do
        if [[ ( "$g" -eq 1 && "$c" = "123" ) || ( "$g" -eq 2 && "$c" = "456" ) ]]
        then echo "g = $g; c = $c; true"
        else echo "g = $g; c = $c; false"
        fi
    done
done

Example run, using Bash 3.2.57 on Mac OS X:

g = 1; c = 123; true
g = 1; c = 456; false
g = 1; c = 789; false
g = 2; c = 123; false
g = 2; c = 456; true
g = 2; c = 789; false
g = 3; c = 123; false
g = 3; c = 456; false
g = 3; c = 789; false

You don't need to quote the variables in [[ as you do with [ because it is not a separate command in the same way that [ is.


Isn't it a classic question?

I would have thought so. However, there is another alternative, namely:

if [ "$g" -eq 1 -a "$c" = "123" ] || [ "$g" -eq 2 -a "$c" = "456" ]
then echo abc
else echo efg
fi

Indeed, if you read the 'portable shell' guidelines for the autoconf tool or related packages, this notation — using '||' and '&&' — is what they recommend. I suppose you could even go so far as:

if [ "$g" -eq 1 ] && [ "$c" = "123" ]
then echo abc
elif [ "$g" -eq 2 ] && [ "$c" = "456" ]
then echo abc
else echo efg
fi

Where the actions are as trivial as echoing, this isn't bad. When the action block to be repeated is multiple lines, the repetition is too painful and one of the earlier versions is preferable — or you need to wrap the actions into a function that is invoked in the different then blocks.

Replace "\\" with "\" in a string in C#

string a = @"a\\b";
a = a.Replace(@"\\",@"\");

should work. Remember that in the watch Visual STudio show the "\" escaped so you see "\" in place of a single one.

Alter column in SQL Server

Try this one.

ALTER TABLE tb_TableName
ALTER COLUMN Record_Status VARCHAR(20) NOT NULL

ALTER TABLE tb_TableName
ADD CONSTRAINT DEF_Name DEFAULT '' FOR Record_Status

jQuery Validation plugin: disable validation for specified submit buttons

$("form").validate().settings.ignore = "*";

Or

$("form").validate().cancelSubmit = true;

But without success in a custom required validator. For call a submit dynamically, i have created a fake hidden submit button with this code:

var btn = form.children('input.cancel.fakeSubmitFormButton');
if (btn.length === 0) {
    btn = $('<input name="FakeCancelSubmitButton" class="cancel fakeSubmitFormButton hide" type="submit" formnovalidate value="FakeCancelSubmitButton" />');
    form.append(btn);
}
btn.click();

Now skip the validation correctly :)

Twitter Bootstrap 3.0 how do I "badge badge-important" now

Like the answer above but here is using bootstrap 3 names and colours:

_x000D_
_x000D_
/*css to add back colours for badges and make use of the colours*/_x000D_
.badge-default {_x000D_
  background-color: #999999;_x000D_
}_x000D_
_x000D_
.badge-primary {_x000D_
  background-color: #428bca;_x000D_
}_x000D_
_x000D_
.badge-success {_x000D_
  background-color: #5cb85c;_x000D_
}_x000D_
_x000D_
.badge-info {_x000D_
  background-color: #5bc0de;_x000D_
}_x000D_
_x000D_
.badge-warning {_x000D_
  background-color: #f0ad4e;_x000D_
}_x000D_
_x000D_
.badge-danger {_x000D_
  background-color: #d9534f;_x000D_
}
_x000D_
_x000D_
_x000D_

How to comment lines in rails html.erb files?

This is CLEANEST, SIMPLEST ANSWER for CONTIGUOUS NON-PRINTING Ruby Code:

The below also happens to answer the Original Poster's question without, the "ugly" conditional code that some commenters have mentioned.


  1. CONTIGUOUS NON-PRINTING Ruby Code

    • This will work in any mixed language Rails View file, e.g, *.html.erb, *.js.erb, *.rhtml, etc.

    • This should also work with STD OUT/printing code, e.g. <%#= f.label :title %>

    • DETAILS:

      Rather than use rails brackets on each line and commenting in front of each starting bracket as we usually do like this:

        <%# if flash[:myErrors] %>
          <%# if flash[:myErrors].any? %>
            <%# if @post.id.nil? %>
              <%# if @myPost!=-1 %>
                <%# @post = @myPost %>
              <%# else %>
                <%# @post = Post.new %>
              <%# end %>
            <%# end %>
          <%# end %>
        <%# end %>
      

      YOU CAN INSTEAD add only one comment (hashmark/poundsign) to the first open Rails bracket if you write your code as one large block... LIKE THIS:

        <%# 
          if flash[:myErrors] then
            if flash[:myErrors].any? then
              if @post.id.nil? then
                if @myPost!=-1 then
                  @post = @myPost 
                else 
                  @post = Post.new 
                end 
              end 
            end 
          end 
        %>
      

Python reading from a file and saving to utf-8

You can't do that using open. use codecs.

when you are opening a file in python using the open built-in function you will always read/write the file in ascii. To write it in utf-8 try this:

import codecs
file = codecs.open('data.txt','w','utf-8')

SQL Server 2012 column identity increment jumping from 6 to 1000+ on 7th entry

While trace flag 272 may work for many, it definitely won't work for hosted Sql Server Express installations. So, I created an identity table, and use this through an INSTEAD OF trigger. I'm hoping this helps someone else, and/or gives others an opportunity to improve my solution. The last line allows returning the last identity column added. Since I typically use this to add a single row, this works to return the identity of a single inserted row.

The identity table:

CREATE TABLE [dbo].[tblsysIdentities](
[intTableId] [int] NOT NULL,
[intIdentityLast] [int] NOT NULL,
[strTable] [varchar](100) NOT NULL,
[tsConcurrency] [timestamp] NULL,
CONSTRAINT [PK_tblsysIdentities] PRIMARY KEY CLUSTERED 
(
    [intTableId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,  ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

and the insert trigger:

-- INSERT --
IF OBJECT_ID ('dbo.trgtblsysTrackerMessagesIdentity', 'TR') IS NOT NULL
   DROP TRIGGER dbo.trgtblsysTrackerMessagesIdentity;
GO
CREATE TRIGGER trgtblsysTrackerMessagesIdentity
ON dbo.tblsysTrackerMessages
INSTEAD OF INSERT AS 
BEGIN
    DECLARE @intTrackerMessageId INT
    DECLARE @intRowCount INT

    SET @intRowCount = (SELECT COUNT(*) FROM INSERTED)

    SET @intTrackerMessageId = (SELECT intIdentityLast FROM tblsysIdentities WHERE intTableId=1)
    UPDATE tblsysIdentities SET intIdentityLast = @intTrackerMessageId + @intRowCount WHERE intTableId=1

    INSERT INTO tblsysTrackerMessages( 
    [intTrackerMessageId],
    [intTrackerId],
    [strMessage],
    [intTrackerMessageTypeId],
    [datCreated],
    [strCreatedBy])
    SELECT @intTrackerMessageId + ROW_NUMBER() OVER (ORDER BY [datCreated]) AS [intTrackerMessageId], 
    [intTrackerId],
   [strMessage],
   [intTrackerMessageTypeId],
   [datCreated],
   [strCreatedBy] FROM INSERTED;

   SELECT TOP 1 @intTrackerMessageId + @intRowCount FROM INSERTED;
END

How to search for file names in Visual Studio?

Easily hit CTRL+SHIFT+T . This will look in the files' names.

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0

It worked for me after adding particular version of node-sass package ([email protected])

Slack URL to open a channel from browser

You can use

slack://

in order to open the Slack desktop application. For example, on mac, I've run:

open slack://

from the terminal and it opens the Mac desktop Slack application. Still, I didn't figure out the URL that should be used for opening a certain team, channel or message.

Pandas group-by and sum

Use GroupBy.sum:

df.groupby(['Fruit','Name']).sum()

Out[31]: 
               Number
Fruit   Name         
Apples  Bob        16
        Mike        9
        Steve      10
Grapes  Bob        35
        Tom        87
        Tony       15
Oranges Bob        67
        Mike       57
        Tom        15
        Tony        1

What does the keyword "transient" mean in Java?

Google is your friend - first hit - also you might first have a look at what serialization is.

It marks a member variable not to be serialized when it is persisted to streams of bytes. When an object is transferred through the network, the object needs to be 'serialized'. Serialization converts the object state to serial bytes. Those bytes are sent over the network and the object is recreated from those bytes. Member variables marked by the java transient keyword are not transferred, they are lost intentionally.

Example from there, slightly modified (thanks @pgras):

public class Foo implements Serializable
 {
   private String saveMe;
   private transient String dontSaveMe;
   private transient String password;
   //...
 }

jQuery: how to find first visible input/select/textarea excluding buttons?

This is an improvement over @Mottie's answer because as of jQuery 1.5.2 :text selects input elements that have no specified type attribute (in which case type="text" is implied):

$('form').find(':text,textarea,select').filter(':visible:first')

How to adjust layout when soft keyboard appears

Add this line in your Manifest where your Activity is called

android:windowSoftInputMode="adjustPan|adjustResize"

or

you can add this line in your onCreate

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE|WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

Express.js: how to get remote client address

If you are fine using 3rd-party library. You can check request-ip.

You can use it is by

import requestIp from 'request-ip';

app.use(requestIp.mw())

app.use((req, res) => {
  const ip = req.clientIp;
});

The source code is quite long, so I won't copy here, you can check at https://github.com/pbojinov/request-ip/blob/master/src/index.js

Basically,

It looks for specific headers in the request and falls back to some defaults if they do not exist.

The user ip is determined by the following order:

  1. X-Client-IP
  2. X-Forwarded-For (Header may return multiple IP addresses in the format: "client IP, proxy 1 IP, proxy 2 IP", so we take the the first one.)
  3. CF-Connecting-IP (Cloudflare)
  4. Fastly-Client-Ip (Fastly CDN and Firebase hosting header when forwared to a cloud function)
  5. True-Client-Ip (Akamai and Cloudflare)
  6. X-Real-IP (Nginx proxy/FastCGI)
  7. X-Cluster-Client-IP (Rackspace LB, Riverbed Stingray)
  8. X-Forwarded, Forwarded-For and Forwarded (Variations of #2)
  9. req.connection.remoteAddress
  10. req.socket.remoteAddress
  11. req.connection.socket.remoteAddress
  12. req.info.remoteAddress

If an IP address cannot be found, it will return null.

Disclose: I am not associated with the library.

Jquery select this + class

Use $(this).find(), or pass this in context, using jQuery context with selector.

Using $(this).find()

$(".class").click(function(){
     $(this).find(".subclass").css("visibility","visible");
});

Using this in context, $( selector, context ), it will internally call find function, so better to use find on first place.

$(".class").click(function(){
     $(".subclass", this).css("visibility","visible");
});

Get a Div Value in JQuery

your div looks like this:

<div id="someId">Some Value</div>

With jquery:

   <script type="text/javascript">
     $(function(){
         var text = $('#someId').html(); 
         //or
         var text = $('#someId').text();
       };
  </script> 

How to start automatic download of a file in Internet Explorer?

I hope this will works all the browsers. You can also set the auto download timing.

<html>
<head>
<title>Start Auto Download file</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(function() {
$('a[data-auto-download]').each(function(){
var $this = $(this);
setTimeout(function() {
window.location = $this.attr('href');
}, 2000);
});
});
</script>
</head>
<body>
<div class="wrapper">
<p>The download should start shortly. If it doesn't, click
<a data-auto-download href="auto-download.zip">here</a>.</p>
</div>
</body>
</html>

Demo Here

Separators for Navigation

For those using Sass, I have written a mixin for this purpose:

@mixin addSeparator($element, $separator, $padding) {
    #{$element+'+'+$element}:before {
        content: $separator;
        padding: 0 $padding;
    }
}

Example:

@include addSeparator('li', '|', 1em);

Which will give you this:

li+li:before {
  content: "|";
  padding: 0 1em;
}

append to url and refresh page

location.href = location.href + "&parameter=" + value;

How to create id with AUTO_INCREMENT on Oracle?

Starting with Oracle 12c there is support for Identity columns in one of two ways:

  1. Sequence + Table - In this solution you still create a sequence as you normally would, then you use the following DDL:

    CREATE TABLE MyTable (ID NUMBER DEFAULT MyTable_Seq.NEXTVAL, ...)

  2. Table Only - In this solution no sequence is explicitly specified. You would use the following DDL:

    CREATE TABLE MyTable (ID NUMBER GENERATED AS IDENTITY, ...)

If you use the first way it is backward compatible with the existing way of doing things. The second is a little more straightforward and is more inline with the rest of the RDMS systems out there.

Error: The processing instruction target matching "[xX][mM][lL]" is not allowed

Reason for me is 2 of following code in one xml

<?xml version="1.0" encoding="utf-8"?>

Is it possible to add dynamically named properties to JavaScript object?

in addition to all the previous answers, and in case you're wondering how we're going to write dynamic property names in the Future using Computed Property Names ( ECMAScript 6 ), here's how:

var person = "John Doe";
var personId = "person_" + new Date().getTime();
var personIndex = {
    [ personId ]: person
//  ^ computed property name
};

personIndex[ personId ]; // "John Doe"

reference: Understanding ECMAScript 6 - Nickolas Zakas

const vs constexpr on variables

No difference here, but it matters when you have a type that has a constructor.

struct S {
    constexpr S(int);
};

const S s0(0);
constexpr S s1(1);

s0 is a constant, but it does not promise to be initialized at compile-time. s1 is marked constexpr, so it is a constant and, because S's constructor is also marked constexpr, it will be initialized at compile-time.

Mostly this matters when initialization at runtime would be time-consuming and you want to push that work off onto the compiler, where it's also time-consuming, but doesn't slow down execution time of the compiled program

Compiling Java 7 code via Maven

You might be specifying a wrong version of java. java -version(in your terminal) to check the version of java you are using. Go to maven-compile-plugin for the latest maven compiler version Your plugin may appear like this if you are using java 6 and the latest version of maven compiler plugin is 3.1

<plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
        </plugin>

WPF Button with Image

<Button x:Name="myBtn_DetailsTab_Save" FlowDirection="LeftToRight"  HorizontalAlignment="Left" Margin="835,544,0,0" VerticalAlignment="Top"  Width="143" Height="53" BorderBrush="#FF0F6287" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontFamily="B Titr" FontSize="15" FontWeight="Bold" BorderThickness="2" Click="myBtn_DetailsTab_Save_Click">
    <StackPanel HorizontalAlignment="Stretch" Background="#FF1FB3F5" Cursor="Hand" >
        <Image HorizontalAlignment="Left"  Source="image/bg/Save.png" Height="36" Width="124" />
        <TextBlock HorizontalAlignment="Center" Width="84" Height="22" VerticalAlignment="Top" Margin="0,-31,-58,0" Text="??? ?????" />
    </StackPanel>
</Button>

#1064 -You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version

One obvious thing is that you will have to remove the comma here

receipt int(10),

but the actual problem is because of the line

amount double(10) NOT NULL,

change it to

amount double NOT NULL,

How to execute a file within the python interpreter?

For python3 use either with xxxx = name of yourfile.

exec(open('./xxxx.py').read())

Check date between two other dates spring data jpa

I did use following solution to this:

findAllByStartDateLessThanEqualAndEndDateGreaterThanEqual(OffsetDateTime endDate, OffsetDateTime startDate);

CodeIgniter Select Query

This is your code

$q = $this -> db
       -> select('id')
       -> where('email', $email)
       -> limit(1)
       -> get('users');

Try this

$id = $q->result()[0]->id;

or this one, it's simpler

$id = $q->row()->id;

how to write procedure to insert data in to the table in phpmyadmin?

# Switch delimiter to //, so phpMyAdmin will not execute it line by line.
DELIMITER //
CREATE PROCEDURE usp_rateChapter12

(IN numRating_Chapter INT(11) UNSIGNED, 

 IN txtRating_Chapter VARCHAR(250),

 IN chapterName VARCHAR(250),

 IN addedBy VARCHAR(250)

)

BEGIN
DECLARE numRating_Chapter INT;

DECLARE txtRating_Chapter VARCHAR(250);

DECLARE chapterName1 VARCHAR(250);

DECLARE addedBy1 VARCHAR(250);

DECLARE chapterId INT;

DECLARE studentId INT;

SET chapterName1 = chapterName;
SET addedBy1 = addedBy;

SET chapterId = (SELECT chapterId 
                   FROM chapters 
                   WHERE chaptername = chapterName1);

SET studentId = (SELECT Id 
                   FROM students 
                   WHERE email = addedBy1);

SELECT chapterId;
SELECT studentId;

INSERT INTO ratechapter (rateBy, rateText, rateLevel, chapterRated)
VALUES (studentId, txtRating_Chapter, numRating_Chapter,chapterId);

END //

//DELIMITER;

Converting user input string to regular expression

I use eval to solve this problem.

For example:

    function regex_exec() {

        // Important! Like @Samuel Faure mentioned, Eval on user input is a crazy security risk, so before use this method, please take care of the security risk. 
        var regex = $("#regex").val();

        // eval()
        var patt = eval(userInput);

        $("#result").val(patt.exec($("#textContent").val()));
    }

C# refresh DataGridView when updating or inserted on another form

Create a small function and use it anywhere

public SqlConnection con = "Your connection string"; 
public void gridviewUpdate()
{
    con.Open();
    string select = "SELECT * from table_name";
    SqlDataAdapter da = new SqlDataAdapter(select, con);
    DataSet ds = new DataSet();
    da.Fill(ds, "table_name");
    datagridview.DataSource = ds;
    datagridview.DataMember = "table_name";
    con.Close();
}

What does "javax.naming.NoInitialContextException" mean?

It means that there is no initial context :)

But seriously folks, JNDI (javax.naming) is all about looking up objects or resources from some directory or provider. To look something up, you need somewhere to look (this is the InitialContext). NoInitialContextException means "I want to find the telephone number for John Smith, but I have no phonebook to look in".

An InitialContext can be created in any number of ways. It can be done manually, for instance creating a connection to an LDAP server. It can also be set up by an application server inside which you run your application. In this case, the container (application server) already provides you with a "phonebook", through which you can look up anything the application server makes available. This is often configurable and a common way of moving this type of configuration from the application implementation to the container, where it can be shared across all applications in the server.

UPDATE: from the code snippet you post it looks like you are trying to run code stand-alone that is meant to be run in an application server. In this case, the code attempting to get a connection to a database from the "phonebook". This is one of the resources that is often configured in the application server container. So, rather than having to manage configuration and connections to the database in your code, you can configure it in your application server and simple ask for a connection (using JNDI) in your code.

How do I print out the value of this boolean? (Java)

There are several problems.

One is of style; always capitalize class names. This is a universally observed Java convention. Failing to do so confuses other programmers.

Secondly, the line

System.out.println(boolean isLeapYear);

is a syntax error. Delete it.

Thirdly.

You never call the function from your main routine. That is why you never see any reply to the input.

How to use basic authorization in PHP curl

$headers = array(
    'Authorization: Basic '. base64_encode($username.':'.$password),
);
...
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

How to save a Python interactive session?

IPython is extremely useful if you like using interactive sessions. For example for your use-case there is the %save magic command, you just input %save my_useful_session 10-20 23 to save input lines 10 to 20 and 23 to my_useful_session.py (to help with this, every line is prefixed by its number).

Furthermore, the documentation states:

This function uses the same syntax as %history for input ranges, then saves the lines to the filename you specify.

This allows for example, to reference older sessions, such as

%save current_session ~0/
%save previous_session ~1/

Look at the videos on the presentation page to get a quick overview of the features.

Get operating system info

When you go to a website, your browser sends a request to the web server including a lot of information. This information might look something like this:

GET /questions/18070154/get-operating-system-info-with-php HTTP/1.1  
Host: stackoverflow.com  
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 
            (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36 
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8  
Accept-Language: en-us,en;q=0.5  
Accept-Encoding: gzip,deflate,sdch  
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7  
Keep-Alive: 300  
Connection: keep-alive  
Cookie: <cookie data removed> 
Pragma: no-cache  
Cache-Control: no-cache

These information are all used by the web server to determine how to handle the request; the preferred language and whether compression is allowed.

In PHP, all this information is stored in the $_SERVER array. To see what you're sending to a web server, create a new PHP file and print out everything from the array.

<pre><?php print_r($_SERVER); ?></pre>

This will give you a nice representation of everything that's being sent to the server, from where you can extract the desired information, e.g. $_SERVER['HTTP_USER_AGENT'] to get the operating system and browser.

How to center cell contents of a LaTeX table whose columns have fixed widths?

\usepackage{array} in the preamble

then this:

\begin{tabular}{| >{\centering\arraybackslash}m{1in} | >{\centering\arraybackslash}m{1in} |}

note that the "m" for fixed with column is provided by the array package, and will give you vertical centering (if you don't want this just go back to "p"

Can't create handler inside thread that has not called Looper.prepare()

Coroutine will do it perfectly

CoroutineScope(Job() + Dispatchers.Main).launch {
                        Toast.makeText(context, "yourmessage",Toast.LENGTH_LONG).show()}

What's the best way to add a drop shadow to my UIView

Wasabii's answer in Swift 2.3:

let shadowPath = UIBezierPath(rect: view.bounds)
view.layer.masksToBounds = false
view.layer.shadowColor = UIColor.blackColor().CGColor
view.layer.shadowOffset = CGSize(width: 0, height: 0.5)
view.layer.shadowOpacity = 0.2
view.layer.shadowPath = shadowPath.CGPath

And in Swift 3/4/5:

let shadowPath = UIBezierPath(rect: view.bounds)
view.layer.masksToBounds = false
view.layer.shadowColor = UIColor.black.cgColor
view.layer.shadowOffset = CGSize(width: 0, height: 0.5)
view.layer.shadowOpacity = 0.2
view.layer.shadowPath = shadowPath.cgPath

Put this code in layoutSubviews() if you're using AutoLayout.

In SwiftUI, this is all much easier:

Color.yellow  // or whatever your view
    .shadow(radius: 3)
    .frame(width: 200, height: 100)

Oracle client ORA-12541: TNS:no listener

Check out your TNS Names, this must not have spaces at the left side of the ALIAS

Best regards

SEVERE: Unable to create initial connections of pool - tomcat 7 with context.xml file

You have to add a MySQL jdbc driver to the classpath.

Either put a MySQL binary jar to tomcat lib folder or add it to we application WEB-INF/lib folder.

You can find binary jar (Change version accordingly): https://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.27

R command for setting working directory to source file location in Rstudio

I realize that this is an old thread, but I had a similar problem with needing to set the working directory and couldn't get any of the solutions to work for me. Here's what did work, in case anyone else stumbles across this later on:

# SET WORKING DIRECTORY TO CURRENT DIRECTORY:
system("pwd=`pwd`; $pwd 2> dummyfile.txt")
dir <- fread("dummyfile.txt")
n<- colnames(dir)[2]
n2 <- substr(n, 1, nchar(n)-1)
setwd(n2)

It's a bit convoluted, but basically this uses system commands to get the working directory and save it to dummyfile.txt, then R reads that file using data.table::fread. The rest is just cleaning up what got printed to the file so that I'm left with just the directory path.

I needed to run R on a cluster, so there was no way to know what directory I'd end up in (jobs get assigned a number and a compute node). This did the trick for me.

Show animated GIF

Try this:

// I suppose you have already set your JFrame 
Icon imgIcon = new ImageIcon(this.getClass().getResource("ajax-loader.gif"));
JLabel label = new JLabel(imgIcon);
label.setBounds(668, 43, 46, 14); // for example, you can use your own values
frame.getContentPane().add(label);

Found on this tutorial on how to display animated gif in java

Or live on youtube : https://youtu.be/_NEnhm9mgdE

Conda activate not working?

Try this:

export PATH=/home/your_username/anaconda3/bin:$PATH
in ~/.bashrc

Then source ~/.bashrc This works for me for the same problem.

Why do I get the error "Unsafe code may only appear if compiling with /unsafe"?

To use unsafe code blocks, the project has to be compiled with the /unsafe switch on.

Open the properties for the project, go to the Build tab and check the Allow unsafe code checkbox.

iOS 9 not opening Instagram app with URL SCHEME

Facebook sharing from a share dialog fails even with @Matthieu answer (which is 100% correct for the rest of social URLs). I had to add a set of URL i reversed from Facebook SDK.

<array>
        <string>fbapi</string>
        <string>fbauth2</string>
        <string>fbshareextension</string>
        <string>fb-messenger-api</string>
        <string>twitter</string>
        <string>whatsapp</string>
        <string>wechat</string>
        <string>line</string>
        <string>instagram</string>
        <string>kakaotalk</string>
        <string>mqq</string>
        <string>vk</string>
        <string>comgooglemaps</string>
        <string>fbapi20130214</string>                                                    
        <string>fbapi20130410</string>                                                     
        <string>fbapi20130702</string>                                                    
        <string>fbapi20131010</string>                                                    
        <string>fbapi20131219</string>                                                    
        <string>fbapi20140410</string>                                                     
        <string>fbapi20140116</string>                                                     
        <string>fbapi20150313</string>                                                     
        <string>fbapi20150629</string>
    </array>

How to make a new line or tab in <string> XML (eclipse/android)?

Use \n for a line break and \t if you want to insert a tab.

You can also use some XML tags for basic formatting: <b> for bold text, <i> for italics, and <u> for underlined text

More info:

https://developer.android.com/guide/topics/resources/string-resource.html

Stack array using pop() and push()

Here is an example of implementing stack in java (Array Based implementation):

public class MyStack extends Throwable{

/**
 * 
 */
private static final long serialVersionUID = -4433344892390700337L;

protected static int top = -1;
protected static int capacity;
protected static int size;

public int stackDatas[] = null;

public MyStack(){
    stackDatas = new int[10];
    capacity = stackDatas.length;
}

public static int size(){

    if(top < 0){
        size = top + 1;
        return size;
    }
    size = top+1;
    return size; 
}

public void push(int data){
    if(capacity == size()){
        System.out.println("no memory");
    }else{
        stackDatas[++top] = data;
    }
}

public boolean topData(){
    if(top < 0){
        return true;
    }else{
        System.out.println(stackDatas[top]);
        return false;
    }
}

public void pop(){
    if(top < 0){
        System.out.println("stack is empty");
    }else{
        int temp = stackDatas[top];
        stackDatas = ArrayUtils.remove(stackDatas, top--);
        System.out.println("poped data---> "+temp);
    }
}

public String toString(){
    String result = "[";

    if(top<0){
        return "[]";
    }else{


    for(int i = 0; i< size(); i++){
        result = result + stackDatas[i] +",";
    }
    }

    return result.substring(0, result.lastIndexOf(",")) +"]";
 }
}

calling MyStack:

    public class CallingMyStack {

public static MyStack ms;

public static void main(String[] args) {

    ms = new MyStack();
    ms.push(1);
    ms.push(2);
    ms.push(3);
    ms.push(4);
    ms.push(5);
    ms.push(6);
    ms.push(7);
    ms.push(8);
    ms.push(9);
    ms.push(10);
    System.out.println("size: "+MyStack.size());
    System.out.println("List---> "+ms);
    System.out.println("----------");
    ms.pop();
    ms.pop();
    ms.pop();
    ms.pop();
    System.out.println("List---> "+ms);
    System.out.println("size: "+MyStack.size());

 }
}

output:

size: 10
List---> [1,2,3,4,5,6,7,8,9,10]
----------
poped data---> 10
poped data---> 9
poped data---> 8
poped data---> 7
List---> [1,2,3,4,5,6]
size: 6

Execute PHP scripts within Node.js web server

Take a look here: https://github.com/davidcoallier/node-php

From their read me:

Inline PHP Server Running on Node.js

Be worried, be very worried. The name NodePHP takes its name from the fact that we are effectively turning a nice Node.js server into a FastCGI interface that interacts with PHP-FPM.

This is omega-alpha-super-beta-proof-of-concept but it already runs a few simple scripts. Mostly done for my talks on Node.js for PHP Developers this turns out to be quite an interesting project that we are most likely be going to use with Orchestra when we decide to release our Inline PHP server that allows people to run PHP without Apache, Nginx or any webserver.

Yes this goes against all ideas and concepts of Node.js but the idea is to be able to create a web-server directly from any working directory to allow developers to get going even faster than it was before. No need to create vhosts or server blocks ore modify your /etc/hosts anymore.

IsNothing versus Is Nothing

I'm leaning towards the "Is Nothing" alternative, primarily because it seems more OO.

Surely Visual Basic ain't got the Ain't keyword.

How do you get the Git repository's name in some Git repository?

If you want the whole GitHub repository name ('full name') - user/repository, and you want to do it in with Ruby...

git remote show origin -n | ruby -ne 'puts /^\s*Fetch.*:(.*).git/.match($_)[1] rescue nil'

Taking pictures with camera on Android programmatically

For those who came here looking for a way to take pictures/photos programmatically using both Android's Camera and Camera2 API, take a look at the open source sample provided by Google itself here.

How to enable CORS in AngularJs

Answered by myself.

CORS angular js + restEasy on POST

Well finally I came to this workaround: The reason it worked with IE is because IE sends directly a POST instead of first a preflight request to ask for permission. But I still don't know why the filter wasn't able to manage an OPTIONS request and sends by default headers that aren't described in the filter (seems like an override for that only case ... maybe a restEasy thing ...)

So I created an OPTIONS path in my rest service that rewrites the reponse and includes the headers in the response using response header

I'm still looking for the clean way to do it if anybody faced this before.

Map isn't showing on Google Maps JavaScript API v3 when nested in a div tag

I solved this problem with:

    <div id="map" style="width: 100%; height: 100%; position: absolute;">
                 <div id="map-canvas"></div>
     </div>

How to copy part of an array to another array in C#?

int[] a = {1,2,3,4,5};

int [] b= new int[a.length]; //New Array and the size of a which is 4

Array.Copy(a,b,a.length);

Where Array is class having method Copy, which copies the element of a array to b array.

While copying from one array to another array, you have to provide same data type to another array of which you are copying.

How do I hide anchor text without hiding the anchor?

Mini tip:

I had the following scenario:

<a href="/page/">My link text
:after
</a>

I hided the text with font-size: 0, so I could use a FontAwesome icon for it. This worked on Chrome 36, Firefox 31 and IE9+.

I wouldn't recommend color: transparent because the text stil exists and is selectable. Using line-height: 0px didn't allow me to use :after. Maybe because my element was a inline-block.

Visibility: hidden: Didn't allow me to use :after.

text-indent: -9999px;: Also moved the :after element

Python, compute list difference

Adding an answer to take care of the case where we want a strict difference with repetitions, i.e., there are repetitions in the first list that we want to keep in the result. e.g. to get,

[1, 1, 1, 2] - [1, 1] --> [1, 2]

We could use an additional counter to have an elegant difference function.

from collections import Counter

def diff(first, second):
    secondCntr = Counter(second)
    second = set(second)
    res = []
    for i in first:
        if i not in second:
            res.append(i)
        elif i in secondCntr:
            if secondCntr[i] > 0:
                secondCntr[i] -= 1
            else:
                res.append(i)        
    return res

Use a content script to access the page context variables and functions

in Content script , i add script tag to the head which binds a 'onmessage' handler, inside the handler i use , eval to execute code. In booth content script i use onmessage handler as well , so i get two way communication. Chrome Docs

//Content Script

var pmsgUrl = chrome.extension.getURL('pmListener.js');
$("head").first().append("<script src='"+pmsgUrl+"' type='text/javascript'></script>");


//Listening to messages from DOM
window.addEventListener("message", function(event) {
  console.log('CS :: message in from DOM', event);
  if(event.data.hasOwnProperty('cmdClient')) {
    var obj = JSON.parse(event.data.cmdClient);
    DoSomthingInContentScript(obj);
 }
});

pmListener.js is a post message url listener

//pmListener.js

//Listen to messages from Content Script and Execute Them
window.addEventListener("message", function (msg) {
  console.log("im in REAL DOM");
  if (msg.data.cmnd) {
    eval(msg.data.cmnd);
  }
});

console.log("injected To Real Dom");

This way , I can have 2 way communication between CS to Real Dom. Its very usefull for example if you need to listen webscoket events , or to any in memory variables or events.

How to replace plain URLs with links?

Made some optimizations to Travis' Linkify() code above. I also fixed a bug where email addresses with subdomain type formats would not be matched (i.e. [email protected]).

In addition, I changed the implementation to prototype the String class so that items can be matched like so:

var text = '[email protected]';
text.linkify();

'http://stackoverflow.com/'.linkify();

Anyway, here's the script:

if(!String.linkify) {
    String.prototype.linkify = function() {

        // http://, https://, ftp://
        var urlPattern = /\b(?:https?|ftp):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|]/gim;

        // www. sans http:// or https://
        var pseudoUrlPattern = /(^|[^\/])(www\.[\S]+(\b|$))/gim;

        // Email addresses
        var emailAddressPattern = /[\w.]+@[a-zA-Z_-]+?(?:\.[a-zA-Z]{2,6})+/gim;

        return this
            .replace(urlPattern, '<a href="$&">$&</a>')
            .replace(pseudoUrlPattern, '$1<a href="http://$2">$2</a>')
            .replace(emailAddressPattern, '<a href="mailto:$&">$&</a>');
    };
}

Changing the width of Bootstrap popover

I also needed a wider popover for a search text field. I came up with this Javascript solution (here in Coffee):

$(".product-search-trigger")
  .click(-> false) # cancel click on <a> tag
  .popover
    container: "body"
    html: true
    placement: "left"
    title: "<strong>Product search</strong> enter number or name"
  .on("show.bs.popover", -> $(this).data("bs.popover").tip().css(maxWidth: "600px"))

The workaround is in the last line. Before the popover is being displayed the max-width option is set to a custom value. You could also add a custom class to the tip element.

Coding Conventions - Naming Enums

As already stated, enum instances should be uppercase according to the docs on the Oracle website (http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html).

However, while looking through a JavaEE7 tutorial on the Oracle website (http://www.oracle.com/technetwork/java/javaee/downloads/index.html), I stumbled across the "Duke's bookstore" tutorial and in a class (tutorial\examples\case-studies\dukes-bookstore\src\main\java\javaeetutorial\dukesbookstore\components\AreaComponent.java), I found the following enum definition:

private enum PropertyKeys {
    alt, coords, shape, targetImage;
}

According to the conventions, it should have looked like:

public enum PropertyKeys {
    ALT("alt"), COORDS("coords"), SHAPE("shape"), TARGET_IMAGE("targetImage");

    private final String val;

    private PropertyKeys(String val) {
        this.val = val;
    }

    @Override
    public String toString() {
        return val;
    }
}

So it seems even the guys at Oracle sometimes trade convention with convenience.

Receiving "Attempted import error:" in react app

This is another option:

export default function Counter() {

}

Notepad++ add to every line

Simply in the "Find what:" field, type \r. This means "Ends of the Row". In the "Replace with:" field, you put what you want for instance .xml

if you have several lines, and you are aiming to add that text to the end of the each line, you need to markup the option ". matches newline" in the "Search Mode" group box.

Example:

You have a file name list, but you want to add an extension like .xml. This would be what you need to do and Bang! One shot!:

See the image here

CSS image overlay with color and transparency

something like this? http://codepen.io/Nunotmp/pen/wKjvB

You can add an empty div and use absolute positioning.

How to create friendly URL in php?

ModRewrite is not the only answer. You could also use Options +MultiViews in .htaccess and then check $_SERVER REQUEST_URI to find everything that is in URL.

Get cart item name, quantity all details woocommerce

Note on product price

The price of the product in the cart may be different from that of the product.

This can happen when you use some plugins that change the price of the product when it is added to the cart or if you have added a custom function in the functions.php of your active theme.

If you want to be sure you get the price of the product added to the cart you will have to get it like this:

foreach ( WC()->cart->get_cart() as $cart_item ) {
    // gets the cart item quantity
    $quantity           = $cart_item['quantity'];
    // gets the cart item subtotal
    $line_subtotal      = $cart_item['line_subtotal']; 
    $line_subtotal_tax  = $cart_item['line_subtotal_tax'];
    // gets the cart item total
    $line_total         = $cart_item['line_total'];
    $line_tax           = $cart_item['line_tax'];
    // unit price of the product
    $item_price         = $line_subtotal / $quantity;
    $item_tax           = $line_subtotal_tax / $quantity;

}

Instead of:

foreach ( WC()->cart->get_cart() as $cart_item ) {
    // gets the product object
    $product            = $cart_item['data'];
    // gets the product prices
    $regular_price      = $product->get_regular_price();
    $sale_price         = $product->get_sale_price();
    $price              = $product->get_price();
}

Other data you can get:

foreach ( WC()->cart->get_cart() as $cart_item ) {

    // get the data of the cart item
    $product_id         = $cart_item['product_id'];
    $variation_id       = $cart_item['variation_id'];

    // gets the cart item quantity
    $quantity           = $cart_item['quantity'];
    // gets the cart item subtotal
    $line_subtotal      = $cart_item['line_subtotal']; 
    $line_subtotal_tax  = $cart_item['line_subtotal_tax'];
    // gets the cart item total
    $line_total         = $cart_item['line_total'];
    $line_tax           = $cart_item['line_tax'];
    // unit price of the product
    $item_price         = $line_subtotal / $quantity;
    $item_tax           = $line_subtotal_tax / $quantity;

    // gets the product object
    $product            = $cart_item['data'];
    // get the data of the product
    $sku                = $product->get_sku();
    $name               = $product->get_name();
    $regular_price      = $product->get_regular_price();
    $sale_price         = $product->get_sale_price();
    $price              = $product->get_price();
    $stock_qty          = $product->get_stock_quantity();
    // attributes
    $attributes         = $product->get_attributes();
    $attribute          = $product->get_attribute( 'pa_attribute-name' ); // // specific attribute eg. "pa_color"
    // custom meta
    $custom_meta        = $product->get_meta( '_custom_meta_key', true );
    // product categories
    $categories         = wc_get_product_category_list(  $product->get_id() ); // returns a string with all product categories separated by a comma
}

SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column

@Corey - It just simply strips out all invalid characters. However, your comment made me think of the answer.

The problem was that many of the fields in my database are nullable. When using SqlBulkCopy, an empty string is not inserted as a null value. So in the case of my fields that are not varchar (bit, int, decimal, datetime, etc) it was trying to insert an empty string, which obviously is not valid for that data type.

The solution was to modify my loop where I validate the values to this (repeated for each datatype that is not string)

//--- convert decimal values
foreach (DataColumn DecCol in DecimalColumns)
{
     if(string.IsNullOrEmpty(dr[DecCol].ToString()))
          dr[DecCol] = null; //--- this had to be set to null, not empty
     else
          dr[DecCol] = Helpers.CleanDecimal(dr[DecCol].ToString());
}

After making the adjustments above, everything inserts without issues.

Missing maven .m2 folder

Do you have the file system display config set up to show hidden files and folders? If I remember correctly, by default it's hidden. Should be under c:\users\username\.m2.

Align div with fixed position on the right side

Trying to do the same thing. If you want it to be aligned on the right side then set the value of right to 0. In case you need some padding from the right, set the value to the size of the padding you need.

Example:

.test {
  position: fixed;
  right: 20px; /* Padding from the right side */
}

How to create websockets server in PHP

<?php

// server.php

$server = stream_socket_server("tcp://127.0.0.1:8001", $errno, $errorMessage);

if($server == false) {
    throw new Exception("Could not bind to socket: $errorMessage");

}

for(;;) {
    $client = @stream_socket_accept($server);

    if($client) {
        stream_copy_to_stream($client, $client);
        fclose($client);
    }
}

from one terminal run : php server.php

from another terminal run: echo "hello woerld" | nc 127.0.0.1 8002

How to make primary key as autoincrement for Room Persistence lib

@Entity(tableName = "user")
data class User(

@PrimaryKey(autoGenerate = true)  var id: Int?,
       var name: String,
       var dob: String,
       var address: String,
       var gender: String
)
{
    constructor():this(null,
        "","","","")
}

How to left align a fixed width string?

sys.stdout.write("%-6s %-50s %-25s\n" % (code, name, industry))

on a side note you can make the width variable with *-s

>>> d = "%-*s%-*s"%(25,"apple",30,"something")
>>> d
'apple                    something                     '

How to assign colors to categorical variables in ggplot2 that have stable mapping?

I am in the same situation pointed out by malcook in his comment: unfortunately the answer by Thierry does not work with ggplot2 version 0.9.3.1.

png("figure_%d.png")
set.seed(2014)
library(ggplot2)
dataset <- data.frame(category = rep(LETTERS[1:5], 100),
    x = rnorm(500, mean = rep(1:5, 100)),
    y = rnorm(500, mean = rep(1:5, 100)))
dataset$fCategory <- factor(dataset$category)
subdata <- subset(dataset, category %in% c("A", "D", "E"))

ggplot(dataset, aes(x = x, y = y, colour = fCategory)) + geom_point()
ggplot(subdata, aes(x = x, y = y, colour = fCategory)) + geom_point()

Here it is the first figure:

ggplot A-E, mixed colors

and the second figure:

ggplot ADE, mixed colors

As we can see the colors do not stay fixed, for example E switches from magenta to blu.

As suggested by malcook in his comment and by hadley in his comment the code which uses limits works properly:

ggplot(subdata, aes(x = x, y = y, colour = fCategory)) +       
    geom_point() + 
    scale_colour_discrete(drop=TRUE,
        limits = levels(dataset$fCategory))

gives the following figure, which is correct:

correct ggplot

This is the output from sessionInfo():

R version 3.0.2 (2013-09-25)
Platform: x86_64-pc-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] methods   stats     graphics  grDevices utils     datasets  base     

other attached packages:
[1] ggplot2_0.9.3.1

loaded via a namespace (and not attached):
 [1] colorspace_1.2-4   dichromat_2.0-0    digest_0.6.4       grid_3.0.2        
 [5] gtable_0.1.2       labeling_0.2       MASS_7.3-29        munsell_0.4.2     
 [9] plyr_1.8           proto_0.3-10       RColorBrewer_1.0-5 reshape2_1.2.2    
[13] scales_0.2.3       stringr_0.6.2 

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

To export a single component in ES6, you can use export default as follows:

class MyClass extends Component {
 ...
}

export default MyClass;

And now you use the following syntax to import that module:

import MyClass from './MyClass.react'

If you are looking to export multiple components from a single file the declaration would look something like this:

export class MyClass1 extends Component {
 ...
}

export class MyClass2 extends Component {
 ...
}

And now you can use the following syntax to import those files:

import {MyClass1, MyClass2} from './MyClass.react'

A generic error occurred in GDI+, JPEG Image to MemoryStream

byte[] bts = (byte[])page1.EnhMetaFileBits; 
using (var ms = new MemoryStream(bts)) 
{ 
    var image = System.Drawing.Image.FromStream(ms); 
    System.Drawing.Image img = image.GetThumbnailImage(200, 260, null, IntPtr.Zero);      
    img.Save(NewPath, System.Drawing.Imaging.ImageFormat.Png);
}

Best way to store time (hh:mm) in a database

If you are using SQL Server 2008+, consider the TIME datatype. SQLTeam article with more usage examples.

How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

Elaborating on @Pilcrow's answer the only suitable answer for huge arrays is concat (+) since is fast and does not allocate a new object to be garbage-collected when operating inside a loop.

Here's the benchmark:

require 'benchmark'

huge_ary_1 = Array.new(1_000_000) { rand(5_000_000..30_000_00) }

huge_ary_2 = Array.new(1_000_000) { rand(35_000_000..55_000_00) }

Benchmark.bm do |bm|
  p '-------------------CONCAT ----------------'
  bm.report { huge_ary_1.concat(huge_ary_2) }

  p '------------------- PUSH ----------------'
  bm.report { huge_ary_1.push(*huge_ary_2)  }
end

Results:

       user     system      total        real
"-------------------CONCAT ----------------"
  0.000000   0.000000   0.000000 (  0.009388)
"------------------- PUSH ----------------"
  example/array_concat_vs_push.rb:13:in `block (2 levels) in <main>': stack level too deep (SystemStackError)

As you can see using push throws an ERROR: stack level too deep (SystemStackError) when the arrays are big enough.

How do I correctly detect orientation change using Phonegap on iOS?

This is what I do:

_x000D_
_x000D_
function doOnOrientationChange() {_x000D_
    switch(window.orientation) {  _x000D_
      case -90: case 90:_x000D_
        alert('landscape');_x000D_
        break; _x000D_
      default:_x000D_
        alert('portrait');_x000D_
        break; _x000D_
    }_x000D_
}_x000D_
  _x000D_
window.addEventListener('orientationchange', doOnOrientationChange);_x000D_
  _x000D_
// Initial execution if needed_x000D_
doOnOrientationChange();
_x000D_
_x000D_
_x000D_


Update May 2019: window.orientation is a deprecated feature and not supported by most browsers according to MDN. The orientationchange event is associated with window.orientation and therefore should probably not be used.

Are there any disadvantages to always using nvarchar(MAX)?

1) The SQL server will have to utilize more resources (allocated memory and cpu time) when dealing with nvarchar(max) vs nvarchar(n) where n is a number specific to the field.

2) What does this mean in regards to performance?

On SQL Server 2005, I queried 13,000 rows of data from a table with 15 nvarchar(max) columns. I timed the queries repeatedly and then changed the columns to nvarchar(255) or less.

The queries prior to the optimization averaged at 2.0858 seconds. The queries after the change returned in an average of 1.90 seconds. That was about 184 milliseconds of improvement to the basic select * query. That is an 8.8% improvement.

3) My results are in concurrence with a few other articles that indicated that there was a performance difference. Depending on your database and the query, the percentage of improvement can vary. If you don't have a lot of concurrent users or very many records, then the performance difference won't be an issue for you. However, the performance difference will increase as more records and concurrent users increase.

Input type for HTML form for integer

This might help:

<input type="number" step="1" pattern="\d+" />

step is for convenience (and could be set to another integer), but pattern does some actual enforcing.

Note that since pattern matches the whole expression, it wasn't necessary to express it as ^\d+$.

Even with this outwardly tight regular expression, Chrome and Firefox's implementations, interestingly allow for e here (presumably for scientific notation) as well as - for negative numbers, and Chrome also allows for . whereas Firefox is tighter in rejecting unless the . is followed by 0's only. (Firefox marks the field as red upon the input losing focus whereas Chrome doesn't let you input disallowed values in the first place.)

Since, as observed by others, one should always validate on the server (or on the client too, if using the value locally on the client or wishing to prevent the user from a roundtrip to the server).

Should you use .htm or .html file extension? What is the difference, and which file is correct?

If you plan on putting the files on a machine supporting only 8.3 naming convention, you should limit the extension to 3 characters.

Otherwise, better choose the more descriptive .html version.

How to define an empty object in PHP

Use a generic object and map key value pairs to it.

$oVal = new stdClass();
$oVal->key = $value

Or cast an array into an object

$aVal = array( 'key'=>'value' );
$oVal = (object) $aVal;

Eclipse - "Workspace in use or cannot be created, chose a different one."

Check that you have enough rights to workspace directory. I got this error when I didn't have write permission to workspace.

How to set downloading file name in ASP.NET Web API

Considering the previous answers, it is necessary to be careful with globalized characters.

Suppose the name of the file is: "Esdrújula prenda ñame - güena.jpg"

Raw result to download: "Esdrújula prenda ñame - güena.jpg" [Ugly]

HtmlEncode result to download: "Esdr&_250;jula prenda &_241;ame - g&_252;ena.jpg" [Ugly]

UrlEncode result to download: "Esdrújula+prenda+ñame+-+güena.jpg" [OK]

Then, you need almost always to use the UrlEncode over the file name. Moreover, if you set the content-disposition header as direct string, then you need to ensure surround with quotes to avoid browser compatibility issues.

Response.AddHeader("Content-Disposition", $"attachment; filename=\"{HttpUtility.UrlEncode(YourFilename)}\"");

or with class aid:

var cd = new ContentDisposition("attachment") { FileName = HttpUtility.UrlEncode(resultFileName) };
Response.AddHeader("Content-Disposition", cd.ToString());

The System.Net.Mime.ContentDisposition class takes care of quotes.

How to generate a create table script for an existing table in phpmyadmin?

Use the following query in sql tab:

SHOW CREATE TABLE your_table_name

Press GO button

After show table, above the table ( +options ) Hyperlink.

Press +options Hyperlink then appear some options select (Full texts) press GO button.

Show sql quaery.

Add "Are you sure?" to my excel button, how can I?

On your existing button code, simply insert this line before the procedure:

If MsgBox("This will erase everything! Are you sure?", vbYesNo) = vbNo Then Exit Sub

This will force it to quit if the user presses no.

Remove all html tags from php string

For my this is best solution.

function strip_tags_content($string) { 
    // ----- remove HTML TAGs ----- 
    $string = preg_replace ('/<[^>]*>/', ' ', $string); 
    // ----- remove control characters ----- 
    $string = str_replace("\r", '', $string);
    $string = str_replace("\n", ' ', $string);
    $string = str_replace("\t", ' ', $string);
    // ----- remove multiple spaces ----- 
    $string = trim(preg_replace('/ {2,}/', ' ', $string));
    return $string; 

}

Setting size for icon in CSS

You could override the framework CSS (I guess you're using one) and set the size as you want, like this:

.pnx-msg-icon pnx-icon-msg-warning {
    width: 24px !important;
    height: 24px !important;
}

The "!important" property will make sure your code has priority to the framework's code. Make sure you are overriding the correct property, I don't know how the framework is working, this is just an example of !important usage.

How to check if an appSettings key exists?

MSDN: Configuration Manager.AppSettings

if (ConfigurationManager.AppSettings[name] != null)
{
// Now do your magic..
}

or

string s = ConfigurationManager.AppSettings["myKey"];
if (!String.IsNullOrEmpty(s))
{
    // Key exists
}
else
{
    // Key doesn't exist
}

Memory Allocation "Error: cannot allocate vector of size 75.1 Mb"

does R stop no matter the N value you use? try to use small values and see if it's the mvrnorm function that is the issue or you could simply loop it on subsets. Insert the gc() function in the loop to free some RAM continuously

Restarting cron after changing crontab file?

Try this out: sudo cron reload It works for me on ubuntu 12.10

How to get the data-id attribute?

If you are not concerned about old IE browsers, you can also use HTML5 dataset API

HTML

<div id="my-div" data-info="some info here" data-other-info="more info here">My Awesome Div</div>

JS

var myDiv = document.querySelector('#my-div');

myDiv.dataset.info // "some info here"
myDiv.dataset.otherInfo // "more info here"

Demo: http://html5demos.com/dataset

Full browser support list: http://caniuse.com/#feat=dataset

add created_at and updated_at fields to mongoose schemas

var ItemSchema = new Schema({
    name : { type: String, required: true, trim: true }
});

ItemSchema.set('timestamps', true); // this will add createdAt and updatedAt timestamps

Docs: https://mongoosejs.com/docs/guide.html#timestamps

How does MySQL process ORDER BY and LIMIT in a query?

If there is a suitable index, in this case on the publish_date field, then MySQL need not scan the whole index to get the 20 records requested - the 20 records will be found at the start of the index. But if there is no suitable index, then a full scan of the table will be needed.

There is a MySQL Performance Blog article from 2009 on this.

How to set opacity to the background color of a div?

I think this covers just about all of the browsers. I have used it successfully in the past.

#div {
    filter: alpha(opacity=50); /* internet explorer */
    -khtml-opacity: 0.5;      /* khtml, old safari */
    -moz-opacity: 0.5;       /* mozilla, netscape */
    opacity: 0.5;           /* fx, safari, opera */
}

What to gitignore from the .idea folder?

Github uses the following .gitignore for their programs

https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore

# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839

# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf

# Generated files
.idea/**/contentModel.xml

# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml

# Gradle
.idea/**/gradle.xml
.idea/**/libraries

# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn.  Uncomment if using
# auto-import.
# .idea/modules.xml
# .idea/*.iml
# .idea/modules

# CMake
cmake-build-*/

# Mongo Explorer plugin
.idea/**/mongoSettings.xml

# File-based project format
*.iws

# IntelliJ
out/

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Cursive Clojure plugin
.idea/replstate.xml

# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties

# Editor-based Rest Client
.idea/httpRequests

# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser

Java generating non-repeating random numbers

public class Randoms {

static int z, a = 1111, b = 9999, r;

public static void main(String ... args[])
{
       rand();
}

    public static void rand() {

    Random ran = new Random();
    for (int i = 1; i == 1; i++) {
        z = ran.nextInt(b - a + 1) + a;
        System.out.println(z);
        randcheck();
    }
}

private static void randcheck() {

    for (int i = 3; i >= 0; i--) {
        if (z != 0) {
            r = z % 10;
            arr[i] = r;
            z = z / 10;
        }
    }
    for (int i = 0; i <= 3; i++) {
        for (int j = i + 1; j <= 3; j++) {
            if (arr[i] == arr[j]) {
                rand();
            }
        }

    }
}
}

Not connecting to SQL Server over VPN

This is what fixed my connection problem of accessing the SQL Server 2012 Database via VPN

With the SQL Server 2012 Configuration Manager,

I went to the SQL Server Network configuration

Then clicked on the NEW server instance and double-clicked the TCP/IP protocol [I had also previously enabled this option and rebooted the server but that did still not fix it]

now that the TCP/IP was enabled, I noted that all of the IP port slots in the 'IP Addresses' tab of the TCP/IP Properties advanced dialog were set to Enabled=No.

I was curious to why my new installation set all of these IP slots to NO rather than Yes, so I just changed them to YES.

Now the connection to the sever via VPN works great, I did not change any port numbers.

Note: I also had SQL Server 2008 default from the Visual studio 2010 uninstalled, but I do not think that had a direct effect to the TCP/IP situation. A coworker told me that the 2008 and 2005 installations which come with visual studio may interfere with SQL 2012.

List and kill at jobs on UNIX

To delete a job which has not yet run, you need the atrm command. You can use atq command to get its number in the at list.

To kill a job which has already started to run, you'll need to grep for it using:

ps -eaf | grep <command name>

and then use kill to stop it.

A quicker way to do this on most systems is:

pkill <command name>

php execute a background process

You might try a queuing system like Resque. You then can generate a job, that processes the information and quite fast return with the "processing" image. With this approach you won't know when it is finished though.

This solution is intended for larger scale applications, where you don't want your front machines to do the heavy lifting, so they can process user requests. Therefore it might or might not work with physical data like files and folders, but for processing more complicated logic or other asynchronous tasks (ie new registrations mails) it is nice to have and very scalable.

Highcharts - redraw() vs. new Highcharts.chart

chart.series[0].setData(data,true);

The setData method itself will call the redraw method

How can two strings be concatenated?

For the first non-paste() answer, we can look at stringr::str_c() (and then toString() below). It hasn't been around as long as this question, so I think it's useful to mention that it also exists.

Very simple to use, as you can see.

tmp <- cbind("GAD", "AB")
library(stringr)
str_c(tmp, collapse = ",")
# [1] "GAD,AB"

From its documentation file description, it fits this problem nicely.

To understand how str_c works, you need to imagine that you are building up a matrix of strings. Each input argument forms a column, and is expanded to the length of the longest argument, using the usual recyling rules. The sep string is inserted between each column. If collapse is NULL each row is collapsed into a single string. If non-NULL that string is inserted at the end of each row, and the entire matrix collapsed to a single string.

Added 4/13/2016: It's not exactly the same as your desired output (extra space), but no one has mentioned it either. toString() is basically a version of paste() with collapse = ", " hard-coded, so you can do

toString(tmp)
# [1] "GAD, AB"

Unlocking tables if thread is lost

With Sequel Pro:

Restarting the app unlocked my tables. It resets the session connection.

NOTE: I was doing this for a site on my local machine.

How to add a default "Select" option to this ASP.NET DropDownList control?

Move DropDownList1.Items.Add(new ListItem("Select", "0", true)); After bindStatusDropDownList();

so:

    if (!IsPostBack)
    {
        bindStatusDropDownList(); //first create structure
        DropDownList1.Items.Add(new ListItem("Select", "0", true)); // after add item
    }

How to implement band-pass Butterworth filter with Scipy.signal.butter

The filter design method in accepted answer is correct, but it has a flaw. SciPy bandpass filters designed with b, a are unstable and may result in erroneous filters at higher filter orders.

Instead, use sos (second-order sections) output of filter design.

from scipy.signal import butter, sosfilt, sosfreqz

def butter_bandpass(lowcut, highcut, fs, order=5):
        nyq = 0.5 * fs
        low = lowcut / nyq
        high = highcut / nyq
        sos = butter(order, [low, high], analog=False, btype='band', output='sos')
        return sos

def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
        sos = butter_bandpass(lowcut, highcut, fs, order=order)
        y = sosfilt(sos, data)
        return y

Also, you can plot frequency response by changing

b, a = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = freqz(b, a, worN=2000)

to

sos = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = sosfreqz(sos, worN=2000)

How to get first object out from List<Object> using Linq

Try:

var firstElement = lstComp.First();

You can also use FirstOrDefault() just in case lstComp does not contain any items.

http://msdn.microsoft.com/en-gb/library/bb340482(v=vs.100).aspx

Edit:

To get the Component Value:

var firstElement = lstComp.First().ComponentValue("Dep");

This would assume there is an element in lstComp. An alternative and safer way would be...

var firstOrDefault = lstComp.FirstOrDefault();
if (firstOrDefault != null) 
{
    var firstComponentValue = firstOrDefault.ComponentValue("Dep");
}

Calculating a directory's size using Python?

Python 3.6+ recursive folder/file size using os.scandir. As powerful as in the answer by @blakev, but shorter and in EAFP python style.

import os

def size(path, *, follow_symlinks=False):
    try:
        with os.scandir(path) as it:
            return sum(size(entry, follow_symlinks=follow_symlinks) for entry in it)
    except NotADirectoryError:
        return os.stat(path, follow_symlinks=follow_symlinks).st_size

What exactly is the function of Application.CutCopyMode property in Excel

By referring this(http://www.excelforum.com/excel-programming-vba-macros/867665-application-cutcopymode-false.html) link the answer is as below:

Application.CutCopyMode=False is seen in macro recorder-generated code when you do a copy/cut cells and paste . The macro recorder does the copy/cut and paste in separate statements and uses the clipboard as an intermediate buffer. I think Application.CutCopyMode = False clears the clipboard. Without that line you will get the warning 'There is a large amount of information on the Clipboard....' when you close the workbook with a large amount of data on the clipboard.

With optimised VBA code you can usually do the copy/cut and paste operations in one statement, so the clipboard isn't used and Application.CutCopyMode = False isn't needed and you won't get the warning.

Switch statement with returns -- code correctness

I would take a different tack entirely. Don't RETURN in the middle of the method/function. Instead, just put the return value in a local variable and send it at the end.

Personally, I find the following to be more readable:

String result = "";

switch (something) {
case 0:
  result = "blah";
  break;
case 1:
  result = "foo";
  break;
}

return result;

How to add extension methods to Enums

we have just made an enum extension for c# https://github.com/simonmau/enum_ext

It's just a implementation for the typesafeenum, but it works great so we made a package to share - have fun with it

public sealed class Weekday : TypeSafeNameEnum<Weekday, int>
{
    public static readonly Weekday Monday = new Weekday(1, "--Monday--");
    public static readonly Weekday Tuesday = new Weekday(2, "--Tuesday--");
    public static readonly Weekday Wednesday = new Weekday(3, "--Wednesday--");
    ....

    private Weekday(int id, string name) : base(id, name)
    {
    }

    public string AppendName(string input)
    {
        return $"{Name} {input}";
    }
}

I know the example is kind of useless, but you get the idea ;)

How to get number of entries in a Lua table?

I stumbled upon this thread and want to post another option. I'm using Luad generated from a block controller, but it essentially works by checking values in the table, then incrementing which value is being checked by 1. Eventually, the table will run out, and the value at that index will be Nil.

So subtract 1 from the index that returned a nil, and that's the size of the table.

I have a global Variable for TableSize that is set to the result of this count.

function Check_Table_Size()
  local Count = 1
  local CurrentVal = (CueNames[tonumber(Count)])
  local repeating = true
  print(Count)
  while repeating == true do
    if CurrentVal ~= nil then
      Count = Count + 1
      CurrentVal = CueNames[tonumber(Count)]
     else
      repeating = false
      TableSize = Count - 1
    end
  end
  print(TableSize)
end

Sending HTML email using Python

Here is my answer for AWS using boto3

    subject = "Hello"
    html = "<b>Hello Consumer</b>"

    client = boto3.client('ses', region_name='us-east-1', aws_access_key_id="your_key",
                      aws_secret_access_key="your_secret")

client.send_email(
    Source='ACME <[email protected]>',
    Destination={'ToAddresses': [email]},
    Message={
        'Subject': {'Data': subject},
        'Body': {
            'Html': {'Data': html}
        }
    }

Removing an activity from the history stack

You can use forwarding to remove the previous activity from the activity stack while launching the next one. There's an example of this in the APIDemos, but basically all you're doing is calling finish() immediately after calling startActivity().

ViewDidAppear is not called when opening app from background

Swift 4.2. version

Register with the NotificationCenter in viewDidLoad to be notified when the app returns from background

NotificationCenter.default.addObserver(self, selector: #selector(doSomething), name: UIApplication.willEnterForegroundNotification, object: nil)

Implement the method that should be called.

@objc private func doSomething() {
    // Do whatever you want, for example update your view.
}

You can remove the observer once the ViewController is destroyed. This is only required below iOS9 and macOS 10.11

deinit {
    NotificationCenter.default.removeObserver(self)
}

C++ Remove new line from multiline string

All these answers seem a bit heavy to me.

If you just flat out remove the '\n' and move everything else back a spot, you are liable to have some characters slammed together in a weird-looking way. So why not just do the simple (and most efficient) thing: Replace all '\n's with spaces?

for (int i = 0; i < str.length();i++) {
   if (str[i] == '\n') {
      str[i] = ' ';
   }
}

There may be ways to improve the speed of this at the edges, but it will be way quicker than moving whole chunks of the string around in memory.

Can I use complex HTML with Twitter Bootstrap's Tooltip?

set "html" option to true if you want to have html into tooltip. Actual html is determined by option "title" (link's title attribute shouldn't be set)

$('#example1').tooltip({placement: 'bottom', title: '<p class="testtooltip">par</p>', html: true});

Live sample

How do I retrieve an HTML element's actual width and height?

You should use the .offsetWidth and .offsetHeight properties. Note they belong to the element, not .style.

var width = document.getElementById('foo').offsetWidth;

Function .getBoundingClientRect() returns dimensions and location of element as floating-point numbers after performing CSS transforms.

> console.log(document.getElementById('id').getBoundingClientRect())
DOMRect {
    bottom: 177,
    height: 54.7,
    left: 278.5,?
    right: 909.5,
    top: 122.3,
    width: 631,
    x: 278.5,
    y: 122.3,
}

How to create a .gitignore file

In mac - you can just create a new text file. add content using https://www.gitignore.io/

save the file with file format as - Rich Text document with attachments. change file name to .gitingore and select use"." when a pop up comes as in the attached image.

NOTE : since it is a hidden file so you wont be able to see it in the directory. but it will be created.

see image

Accessing dictionary value by index in python

If you really just want a random value from the available key range, use random.choice on the dictionary's values (converted to list form, if Python 3).

>>> from random import choice
>>> d = {1: 'a', 2: 'b', 3: 'c'}
>>>> choice(list(d.values()))

How to avoid Number Format Exception in java?

Try to convert Prize into decimal format...

import java.math.BigDecimal;
import java.math.RoundingMode;

public class Bigdecimal {
    public static boolean isEmpty (String st) {
        return st == null || st.length() < 1; 
    }
    public static BigDecimal bigDecimalFormat(String Preis){        
        //MathContext   mi = new MathContext(2);
        BigDecimal bd = new BigDecimal(0.00);

                         bd = new BigDecimal(Preis);


            return bd.setScale(2, RoundingMode.HALF_UP);

        }
    public static void main(String[] args) {
        String cost = "12.12";
        if (!isEmpty(cost) ){
            try {
               BigDecimal intCost = bigDecimalFormat(cost);
               System.out.println(intCost);
               List<Book> books = bookService.findBooksCheaperThan(intCost);  
            } catch (NumberFormatException e) {
               System.out.println("This is not a number");
               System.out.println(e.getMessage());
            }
        }

}
}

can't multiply sequence by non-int of type 'float'

for i in growthRates:  
    fund = fund * (1 + 0.01 * growthRates) + depositPerYear

should be:

for i in growthRates:  
    fund = fund * (1 + 0.01 * i) + depositPerYear

You are multiplying 0.01 with the growthRates list object. Multiplying a list by an integer is valid (it's overloaded syntactic sugar that allows you to create an extended a list with copies of its element references).

Example:

>>> 2 * [1,2]
[1, 2, 1, 2]

How to format a float in javascript?

var result = Math.round(original*100)/100;

The specifics, in case the code isn't self-explanatory.

edit: ...or just use toFixed, as proposed by Tim Büthe. Forgot that one, thanks (and an upvote) for reminder :)

plot a circle with pyplot

You need to add it to an axes. A Circle is a subclass of an Patch, and an axes has an add_patch method. (You can also use add_artist but it's not recommended.)

Here's an example of doing this:

import matplotlib.pyplot as plt

circle1 = plt.Circle((0, 0), 0.2, color='r')
circle2 = plt.Circle((0.5, 0.5), 0.2, color='blue')
circle3 = plt.Circle((1, 1), 0.2, color='g', clip_on=False)

fig, ax = plt.subplots() # note we must use plt.subplots, not plt.subplot
# (or if you have an existing figure)
# fig = plt.gcf()
# ax = fig.gca()

ax.add_patch(circle1)
ax.add_patch(circle2)
ax.add_patch(circle3)

fig.savefig('plotcircles.png')

This results in the following figure:

The first circle is at the origin, but by default clip_on is True, so the circle is clipped when ever it extends beyond the axes. The third (green) circle shows what happens when you don't clip the Artist. It extends beyond the axes (but not beyond the figure, ie the figure size is not automatically adjusted to plot all of your artists).

The units for x, y and radius correspond to data units by default. In this case, I didn't plot anything on my axes (fig.gca() returns the current axes), and since the limits have never been set, they defaults to an x and y range from 0 to 1.

Here's a continuation of the example, showing how units matter:

circle1 = plt.Circle((0, 0), 2, color='r')
# now make a circle with no fill, which is good for hi-lighting key results
circle2 = plt.Circle((5, 5), 0.5, color='b', fill=False)
circle3 = plt.Circle((10, 10), 2, color='g', clip_on=False)
    
ax = plt.gca()
ax.cla() # clear things for fresh plot

# change default range so that new circles will work
ax.set_xlim((0, 10))
ax.set_ylim((0, 10))
# some data
ax.plot(range(11), 'o', color='black')
# key data point that we are encircling
ax.plot((5), (5), 'o', color='y')
    
ax.add_patch(circle1)
ax.add_patch(circle2)
ax.add_patch(circle3)
fig.savefig('plotcircles2.png')

which results in:

You can see how I set the fill of the 2nd circle to False, which is useful for encircling key results (like my yellow data point).

HashSet vs LinkedHashSet

HashSet:

The underlined data structure is Hashtable. Duplicate objects are not allowed.insertion order is not preserved and it is based on hash code of objects. Null insertion is possible(only once). It implements Serializable, Clonable but not RandomAccess interface. HashSet is best choose if frequent operation is search operation.

In HashSet duplicates are not allowed.if users are trying to insert duplicates when we won't get any compile or runtime exceptions. add method returns simply false.

Constructors:

HashSet h=new HashSet(); creates an empty HashSet object with default initial capacity 16 and default fill ratio(Load factor) is 0.75 .

HashSet h=new HashSet(int initialCapacity); creates an empty HashSet object with specified initialCapacity and default fill ration is 0.75.

HashSet h=new HashSet(int initialCapacity, float fillRatio);

HashSet h=new HashSet(Collection c); creates an equivalent HashSet object for the given collection. This constructor meant for inter conversion between collection object.

LinkedHashSet:

It is a child class of HashSet. it is exactly same as HashSet including(Constructors and Methods) except the following differences.

Differences HashSet:

  1. The underlined data structure is Hashtable.
  2. Insertion order is not preserved.
  3. introduced 1.2 version.

LinkedHashSet:

  1. The underlined data structure is a combination of LinkedList and Hashtable.
  2. Insertion order is preserved.
  3. Indroduced in 1.4 version.

OpenCV Python rotate image by X degrees around specific point

You can simply use the imutils package to do the rotation. it has two methods

  1. rotate: Rotate the image at specified angle. however the drawback is image might get cropped if it is not a square image.
  2. Rotate_bound: it overcomes the problem happened with rotate. It adjusts the size of the image accordingly while rotating the image.

more info you can get on this blog: https://www.pyimagesearch.com/2017/01/02/rotate-images-correctly-with-opencv-and-python/

Add days to JavaScript Date

the same answer: How to add number of days to today's date?

    function DaysOfMonth(nYear, nMonth) {
        switch (nMonth) {
            case 0:     // January
                return 31; break;
            case 1:     // February
                if ((nYear % 4) == 0) {
                    return 29;
                }
                else {
                    return 28;
                };
                break;
            case 2:     // March
                return 31; break;
            case 3:     // April
                return 30; break;
            case 4:     // May
                return 31; break;
            case 5:     // June
                return 30; break;
            case 6:     // July
                return 31; break;
            case 7:     // August
                return 31; break;
            case 8:     // September
                return 30; break;
            case 9:     // October
                return 31; break;
            case 10:     // November
                return 30; break;
            case 11:     // December
                return 31; break;
        }
    };

    function SkipDate(dDate, skipDays) {
        var nYear = dDate.getFullYear();
        var nMonth = dDate.getMonth();
        var nDate = dDate.getDate();
        var remainDays = skipDays;
        var dRunDate = dDate;

        while (remainDays > 0) {
            remainDays_month = DaysOfMonth(nYear, nMonth) - nDate;
            if (remainDays > remainDays_month) {
                remainDays = remainDays - remainDays_month - 1;
                nDate = 1;
                if (nMonth < 11) { nMonth = nMonth + 1; }
                else {
                    nMonth = 0;
                    nYear = nYear + 1;
                };
            }
            else {
                nDate = nDate + remainDays;
                remainDays = 0;
            };
            dRunDate = Date(nYear, nMonth, nDate);
        }
        return new Date(nYear, nMonth, nDate);
    };

Get list of databases from SQL Server

In SQL Server 7, dbid 1 thru 4 are the system dbs.