Programs & Examples On #Ferret

How to create Gmail filter searching for text only at start of subject line?

The only option I have found to do this is find some exact wording and put that under the "Has the words" option. Its not the best option, but it works.

string in namespace std does not name a type

You need to

#include <string>

<iostream> declares cout, cin, not string.

Correct way to initialize HashMap and can HashMap hold different value types?

Map.of literals

As of Java 9, there is yet another way to instantiate a Map. You can create an unmodifiable map from zero, one, or several pairs of objects in a single-line of code. This is quite convenient in many situations.

For an empty Map that cannot be modified, call Map.of(). Why would you want an empty set that cannot be changed? One common case is to avoid returning a NULL where you have no valid content.

For a single key-value pair, call Map.of( myKey , myValue ). For example, Map.of( "favorite_color" , "purple" ).

For multiple key-value pairs, use a series of key-value pairs. ``Map.of( "favorite_foreground_color" , "purple" , "favorite_background_color" , "cream" )`.

If those pairs are difficult to read, you may want to use Map.of and pass Map.Entry objects.

Note that we get back an object of the Map interface. We do not know the underlying concrete class used to make our object. Indeed, the Java team is free to used different concrete classes for different data, or to vary the class in future releases of Java.

The rules discussed in other Answers still apply here, with regard to type-safety. You declare your intended types, and your passed objects must comply. If you want values of various types, use Object.

Map< String , Color > preferences = Map.of( "favorite_color" , Color.BLUE ) ;

Getting a Request.Headers value

The following code should allow you to check for the existance of the header you're after in Request.Headers:

if (Request.Headers.AllKeys.Contains("XYZComponent"))
{
    // Can now check if the value is true:
    var value = Convert.ToBoolean(Request.Headers["XYZComponent"]);
}

How to set the height of table header in UITableView?

With autolayout you could do something like:

tableView.sectionHeaderHeight = UITableViewAutomaticDimension
tableView.estimatedSectionHeaderHeight = <your-header-height>

or if your headers are of different heights, go ahead and implement:

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return <your-header-height>
}

How to generate a random string in Ruby

Another method I like to use:

 rand(2**256).to_s(36)[0..7]

Add ljust if you are really paranoid about the correct string length:

 rand(2**256).to_s(36).ljust(8,'a')[0..7]

Can I run CUDA on Intel's integrated graphics processor?

If you're interested in learning a language which supports massive parallelism better go for OpenCL since you don't have an NVIDIA GPU. You can run OpenCL on Intel CPUs, but at best you can learn to program SIMDs. Optimization on CPU and GPU are different. I really don't think you can use Intel card for GPGPU.

Attaching click event to a JQuery object not yet added to the DOM

I am really surprised that no one has posted this yet

$(document).on('click','#my-butt', function(){
   console.log('document is always there');
}) 

If you are unsure about what elements are going to be on that page at that time just attach it to document.

Note: this is sub-optimal from performance perspective - to get maximum speed one should try to attach to the nearest parent of element that is going to be inserted.

Remove characters from C# string

Here is a nice way to remove the invalid characters in a Filename:

string.Join(string.Empty, filename.Split(System.IO.Path.GetInvalidFileNameChars()));

adding multiple event listeners to one element

Simplest solution for me was passing the code into a separate function and then calling that function in an event listener, works like a charm.

function somefunction() { ..code goes here ..}

variable.addEventListener('keyup', function() {
   somefunction(); // calling function on keyup event
})

variable.addEventListener('keydown', function() {
   somefunction(); //calling function on keydown event
})

How to hide a div from code (c#)

Give the div "runat="server" and an id and you can reference it in your code behind.

<div runat="server" id="theDiv">

In code behind:

{
    theDiv.Visible = false;
}

Excel VBA: function to turn activecell to bold

A UDF will only return a value it won't allow you to change the properties of a cell/sheet/workbook. Move your code to a Worksheet_Change event or similar to change properties.

Eg

Private Sub worksheet_change(ByVal target As Range)
  target.Font.Bold = True
End Sub

Passing functions with arguments to another function in Python?

Here is a way to do it with a closure:

    def generate_add_mult_func(func):
        def function_generator(x):
            return reduce(func,range(1,x))
        return function_generator

    def add(x,y):
        return x+y

    def mult(x,y):
        return x*y

    adding=generate_add_mult_func(add)
    multiplying=generate_add_mult_func(mult)

    print adding(10)
    print multiplying(10)

Getting output of system() calls in Ruby

Be aware that all the solutions where you pass a string containing user provided values to system, %x[] etc. are unsafe! Unsafe actually means: the user may trigger code to run in the context and with all permissions of the program.

As far as I can say only system and Open3.popen3 do provide a secure/escaping variant in Ruby 1.8. In Ruby 1.9 IO::popen also accepts an array.

Simply pass every option and argument as an array to one of these calls.

If you need not just the exit status but also the result you probably want to use Open3.popen3:

require 'open3'
stdin, stdout, stderr, wait_thr = Open3.popen3('usermod', '-p', @options['shadow'], @options['username'])
stdout.gets(nil)
stdout.close
stderr.gets(nil)
stderr.close
exit_code = wait_thr.value

Note that the block form will auto-close stdin, stdout and stderr- otherwise they'd have to be closed explicitly.

More information here: Forming sanitary shell commands or system calls in Ruby

How do I loop through a list by twos?

This might not be as fast as the izip_longest solution (I didn't actually test it), but it will work with python < 2.6 (izip_longest was added in 2.6):

from itertools import imap

def grouper(n, iterable):
    "grouper(3, 'ABCDEFG') --> ('A,'B','C'), ('D','E','F'), ('G',None,None)"
    args = [iter(iterable)] * n

    return imap(None, *args)

If you need to go earlier than 2.3, you can substitute the built-in map for imap. The disadvantage is that it provides no ability to customize the fill value.

What is the difference between GitHub and gist?

My personal understanding or to say my personal usage of Gist and Github is:

  • Github

A big project work. If you wanna build website, develop mobile or web application or do your assignment with your teammates of course use github.

  • Gist

more like a memo. for example you can write the implementation of a small feature and share it to your blog or write down what you think about the project and share it with your teammates. Just like what the above answers said, gist is used for more like code snippet thing. So normally if you work on a project you use github.

Get index of selected option with jQuery

I have a slightly different solution based on the answer by user167517. In my function I'm using a variable for the id of the select box I'm targeting.

var vOptionSelect = "#productcodeSelect1";

The index is returned with:

$(vOptionSelect).find(":selected").index();

How to get a shell environment variable in a makefile?

If you've exported the environment variable:

export demoPath=/usr/local/demo

you can simply refer to it by name in the makefile (make imports all the environment variables you have set):

DEMOPATH = ${demoPath}    # Or $(demoPath) if you prefer.

If you've not exported the environment variable, it is not accessible until you do export it, or unless you pass it explicitly on the command line:

make DEMOPATH="${demoPath}" …

If you are using a C shell derivative, substitute setenv demoPath /usr/local/demo for the export command.

How to delete a folder and all contents using a bat file in windows?

  1. del /s /q c:\where ever the file is\*
  2. rmdir /s /q c:\where ever the file is\
  3. mkdir c:\where ever the file is\

How to remove "rows" with a NA value?

dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))

na.omit(dat)
  x1  x2
1  1 100
3  3 300
5  5 500

Play audio from a stream using C#

I wrapped the MP3 decoder library and made it available for .NET developers as mpg123.net.

Included are the samples to convert MP3 files to PCM, and read ID3 tags.

Compile c++14-code with g++

G++ does support C++14 both via -std=c++14 and -std=c++1y. The latter was the common name for the standard before it was known in which year it would be released. In older versions (including yours) only the latter is accepted as the release year wasn't known yet when those versions were released.

I used "sudo apt-get install g++" which should automatically retrieve the latest version, is that correct?

It installs the latest version available in the Ubuntu repositories, not the latest version that exists.

The latest GCC version is 5.2.

Get human readable version of file size?

Riffing on the snippet provided as an alternative to hurry.filesize(), here is a snippet that gives varying precision numbers based on the prefix used. It isn't as terse as some snippets, but I like the results.

def human_size(size_bytes):
    """
    format a size in bytes into a 'human' file size, e.g. bytes, KB, MB, GB, TB, PB
    Note that bytes/KB will be reported in whole numbers but MB and above will have greater precision
    e.g. 1 byte, 43 bytes, 443 KB, 4.3 MB, 4.43 GB, etc
    """
    if size_bytes == 1:
        # because I really hate unnecessary plurals
        return "1 byte"

    suffixes_table = [('bytes',0),('KB',0),('MB',1),('GB',2),('TB',2), ('PB',2)]

    num = float(size_bytes)
    for suffix, precision in suffixes_table:
        if num < 1024.0:
            break
        num /= 1024.0

    if precision == 0:
        formatted_size = "%d" % num
    else:
        formatted_size = str(round(num, ndigits=precision))

    return "%s %s" % (formatted_size, suffix)

How can I get the file name from request.FILES?

file = request.FILES['filename']
file.name           # Gives name
file.content_type   # Gives Content type text/html etc
file.size           # Gives file's size in byte
file.read()         # Reads file

How to get the difference (only additions) between two files in linux

A similar approach to https://stackoverflow.com/a/15385080/337172 but hopefully more understandable and easy to tweak:

diff \
  --new-line-format="%L" \
  --old-line-format="" \
  --unchanged-line-format="" \
  A1 A2

C# Validating input for textbox on winforms

With WinForms you can use the ErrorProvider in conjunction with the Validating event to handle the validation of user input. The Validating event provides the hook to perform the validation and ErrorProvider gives a nice consistent approach to providing the user with feedback on any error conditions.

http://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.aspx

Can't perform a React state update on an unmounted component

Edit: I just realized the warning is referencing a component called TextLayerInternal. That's likely where your bug is. The rest of this is still relevant, but it might not fix your problem.

1) Getting the instance of a component for this warning is tough. It looks like there is some discussion to improve this in React but there currently is no easy way to do it. The reason it hasn't been built yet, I suspect, is likely because components are expected to be written in such a way that setState after unmount isn't possible no matter what the state of the component is. The problem, as far as the React team is concerned, is always in the Component code and not the Component instance, which is why you get the Component Type name.

That answer might be unsatisfactory, but I think I can fix your problem.

2) Lodashes throttled function has a cancel method. Call cancel in componentWillUnmount and ditch the isComponentMounted. Canceling is more "idiomatically" React than introducing a new property.

Error in file(file, "rt") : cannot open the connection

close your R studio and run it again as an administrator. That did the magic for me. Hope it works for you and anyone going through this too.

How to Uninstall RVM?

It’s easy; just do the following:

rvm implode

or

rm -rf ~/.rvm

And don’t forget to remove the script calls in the following files:

  • ~/.bashrc
  • ~/.bash_profile
  • ~/.profile

And maybe others depending on whatever shell you’re using.

How to use not contains() in xpath?

I need to select every production with a category that doesn't contain "Business"

Although I upvoted @Arran's answer as correct, I would also add this... Strictly interpreted, the OP's specification would be implemented as

//production[category[not(contains(., 'Business'))]]

rather than

//production[not(contains(category, 'Business'))]

The latter selects every production whose first category child doesn't contain "Business". The two XPath expressions will behave differently when a production has no category children, or more than one.

It doesn't make any difference in practice as long as every <production> has exactly one <category> child, as in your short example XML. Whether you can always count on that being true or not, depends on various factors, such as whether you have a schema that enforces that constraint. Personally, I would go for the more robust option, since it doesn't "cost" much... assuming your requirement as stated in the question is really correct (as opposed to e.g. 'select every production that doesn't have a category that contains "Business"').

How to scroll HTML page to given anchor?

You can use jQuerys .animate(), .offset() and scrollTop. Like

$(document.body).animate({
    'scrollTop':   $('#anchorName2').offset().top
}, 2000);

example link: http://jsbin.com/unasi3/edit

If you don't want to animate use .scrollTop() like

$(document.body).scrollTop($('#anchorName2').offset().top);

or javascripts native location.hash like

location.hash = '#' + anchorid;

Why does one use dependency injection?

Quite frankly, I believe people use these Dependency Injection libraries/frameworks because they just know how to do things in runtime, as opposed to load time. All this crazy machinery can be substituted by setting your CLASSPATH environment variable (or other language equivalent, like PYTHONPATH, LD_LIBRARY_PATH) to point to your alternative implementations (all with the same name) of a particular class. So in the accepted answer you'd just leave your code like

var logger = new Logger() //sane, simple code

And the appropriate logger will be instantiated because the JVM (or whatever other runtime or .so loader you have) would fetch it from the class configured via the environment variable mentioned above.

No need to make everything an interface, no need to have the insanity of spawning broken objects to have stuff injected into them, no need to have insane constructors with every piece of internal machinery exposed to the world. Just use the native functionality of whatever language you're using instead of coming up with dialects that won't work in any other project.

P.S.: This is also true for testing/mocking. You can very well just set your environment to load the appropriate mock class, in load time, and skip the mocking framework madness.

Should I use JSLint or JSHint JavaScript validation?

I had the same question a couple of weeks ago and was evaluating both JSLint and JSHint.

Contrary to the answers in this question, my conclusion was not:

By all means use JSLint.

Or:

If you're looking for a very high standard for yourself or team, JSLint.

As you can configure almost the same rules in JSHint as in JSLint. So I would argue that there's not much difference in the rules you could achieve.

So the reasons to choose one over another are more political than technical.

We've finally decided to go with JSHint because of the following reasons:

  • Seems to be more configurable that JSLint.
  • Looks definitely more community-driven rather than one-man-show (no matter how cool The Man is).
  • JSHint matched our code style OOTB better that JSLint.

Python script to convert from UTF-8 to ASCII

import codecs

 ...

fichier = codecs.open(filePath, "r", encoding="utf-8")

 ...

fichierTemp = codecs.open("tempASCII", "w", encoding="ascii", errors="ignore")
fichierTemp.write(contentOfFile)

 ...

run a python script in terminal without the python command

There are three parts:

  1. Add a 'shebang' at the top of your script which tells how to execute your script
  2. Give the script 'run' permissions.
  3. Make the script in your PATH so you can run it from anywhere.

Adding a shebang

You need to add a shebang at the top of your script so the shell knows which interpreter to use when parsing your script. It is generally:

#!path/to/interpretter

To find the path to your python interpretter on your machine you can run the command:

which python

This will search your PATH to find the location of your python executable. It should come back with a absolute path which you can then use to form your shebang. Make sure your shebang is at the top of your python script:

#!/usr/bin/python

Run Permissions

You have to mark your script with run permissions so that your shell knows you want to actually execute it when you try to use it as a command. To do this you can run this command:

chmod +x myscript.py

Add the script to your path

The PATH environment variable is an ordered list of directories that your shell will search when looking for a command you are trying to run. So if you want your python script to be a command you can run from anywhere then it needs to be in your PATH. You can see the contents of your path running the command:

echo $PATH

This will print out a long line of text, where each directory is seperated by a semicolon. Whenever you are wondering where the actual location of an executable that you are running from your PATH, you can find it by running the command:

which <commandname>

Now you have two options: Add your script to a directory already in your PATH, or add a new directory to your PATH. I usually create a directory in my user home directory and then add it the PATH. To add things to your path you can run the command:

export PATH=/my/directory/with/pythonscript:$PATH

Now you should be able to run your python script as a command anywhere. BUT! if you close the shell window and open a new one, the new one won't remember the change you just made to your PATH. So if you want this change to be saved then you need to add that command at the bottom of your .bashrc or .bash_profile

How do I check that multiple keys are in a dict in a single pass?

>>> if 'foo' in foo and 'bar' in foo:
...     print 'yes'
... 
yes

Jason, () aren't necessary in Python.

Android textview usage as label and value

You can use <LinearLayout> to group elements horizontaly. Also you should use style to set margins, background and other properties. This will allow you not to repeat code for every label you use. Here is an example:

<LinearLayout
                    style="@style/FormItem"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                <TextView
                        style="@style/FormLabel"
                        android:layout_width="wrap_content"
                        android:layout_height="@dimen/default_element_height"
                        android:text="@string/name_label"
                        />

                <EditText
                        style="@style/FormText.Editable"
                        android:id="@+id/cardholderName"
                        android:layout_width="wrap_content"
                        android:layout_height="@dimen/default_element_height"
                        android:layout_weight="1"
                        android:gravity="right|center_vertical"
                        android:hint="@string/card_name_hint"
                        android:imeOptions="actionNext"
                        android:singleLine="true"
                        />
            </LinearLayout>

Also you can create a custom view base on the layout above. Have you looked at Creating custom view ?

Remove all padding and margin table HTML and CSS

Remove padding between cells inside the table. Just use cellpadding=0 and cellspacing=0 attributes in table tag.

Where to change default pdf page width and font size in jspdf.debug.js?

From the documentation page

To set the page type pass the value in constructor

jsPDF(orientation, unit, format) Creates new jsPDF document object

instance Parameters:

orientation One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")

unit Measurement unit to be used when coordinates are specified. One of "pt" (points), "mm" (Default), "cm", "in"

format One of 'a3', 'a4' (Default),'a5' ,'letter' ,'legal'

To set font size

setFontSize(size)

Sets font size for upcoming text elements.

Parameters:

{Number} size Font size in points.

Creating a BLOB from a Base64 string in JavaScript

See this example: https://jsfiddle.net/pqhdce2L/

_x000D_
_x000D_
function b64toBlob(b64Data, contentType, sliceSize) {_x000D_
  contentType = contentType || '';_x000D_
  sliceSize = sliceSize || 512;_x000D_
_x000D_
  var byteCharacters = atob(b64Data);_x000D_
  var byteArrays = [];_x000D_
_x000D_
  for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {_x000D_
    var slice = byteCharacters.slice(offset, offset + sliceSize);_x000D_
_x000D_
    var byteNumbers = new Array(slice.length);_x000D_
    for (var i = 0; i < slice.length; i++) {_x000D_
      byteNumbers[i] = slice.charCodeAt(i);_x000D_
    }_x000D_
_x000D_
    var byteArray = new Uint8Array(byteNumbers);_x000D_
_x000D_
    byteArrays.push(byteArray);_x000D_
  }_x000D_
    _x000D_
  var blob = new Blob(byteArrays, {type: contentType});_x000D_
  return blob;_x000D_
}_x000D_
_x000D_
_x000D_
var contentType = 'image/png';_x000D_
var b64Data = Your Base64 encode;_x000D_
_x000D_
var blob = b64toBlob(b64Data, contentType);_x000D_
var blobUrl = URL.createObjectURL(blob);_x000D_
_x000D_
var img = document.createElement('img');_x000D_
img.src = blobUrl;_x000D_
document.body.appendChild(img);
_x000D_
_x000D_
_x000D_

Default SecurityProtocol in .NET 4.5

The BEST solution to this problem appears to be to upgrade to at least .NET 4.6 or later, which will automatically choose strong protocols as well as strong ciphers.

If you can't upgrade to .NET 4.6, the advice of setting

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

And using the registry settings:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft.NETFramework\v4.0.30319 – SchUseStrongCrypto = DWORD of 1 HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft.NETFramework\v4.0.30319 – SchUseStrongCrypto = DWORD of 1

Results in using something other than TLS 1.0 and a strong cipher.

In my testing, only the setting in the Wow6432Node made any difference, even though my test application was built for Any CPU.

Split large string in n-size chunks in JavaScript

const getChunksFromString = (str, chunkSize) => {
    var regexChunk = new RegExp(`.{1,${chunkSize}}`, 'g')   // '.' represents any character
    return str.match(regexChunk)
}

Call it as needed

console.log(getChunksFromString("Hello world", 3))   // ["Hel", "lo ", "wor", "ld"]

how to clear localstorage,sessionStorage and cookies in javascript? and then retrieve?

There is no way to retrieve localStorage, sessionStorage or cookie values via javascript in the browser after they've been deleted via javascript.

If what you're really asking is if there is some other way (from outside the browser) to recover that data, that's a different question and the answer will entirely depend upon the specific browser and how it implements the storage of each of those types of data.

For example, Firefox stores cookies as individual files. When a cookie is deleted, its file is deleted. That means that the cookie can no longer be accessed via the browser. But, we know that from outside the browser, using system tools, the contents of deleted files can sometimes be retrieved.

If you wanted to look into this further, you'd have to discover how each browser stores each data type on each platform of interest and then explore if that type of storage has any recovery strategy.

Where is nodejs log file?

forever might be of interest to you. It will run your .js-File 24/7 with logging options. Here are two snippets from the help text:

[Long Running Process] The forever process will continue to run outputting log messages to the console. ex. forever -o out.log -e err.log my-script.js

and

[Daemon] The forever process will run as a daemon which will make the target process start in the background. This is extremely useful for remote starting simple node.js scripts without using nohup. It is recommended to run start with -o -l, & -e. ex. forever start -l forever.log -o out.log -e err.log my-daemon.js forever stop my-daemon.js

CSS horizontal scroll

check this link here i change display:inline-block http://cssdesk.com/gUGBH

Changing Underline color

here we can create underline with color in text

_x000D_
_x000D_
<u style="text-decoration-color: red;">The color of the lines should now be red!</u>
_x000D_
_x000D_
_x000D_

or

The color of the lines should now be red!

_x000D_
_x000D_
<h1 style=" text-decoration:underline; text-decoration-color: red;">The color of the lines should now be red!</u>
_x000D_
_x000D_
_x000D_

Could not insert new outlet connection: Could not find any information for the class named

For me it worked when on the right tab > Localization, I checked English check box. Initially only Base was checked. After that I had no more problems. Hope this helps!

You must add a reference to assembly 'netstandard, Version=2.0.0.0

I experienced this when upgrading .NET Core 1.1 to 2.1.

I followed the instructions outlined here.

Try to remove <RuntimeFrameworkVersion>1.1.1</RuntimeFrameworkVersion> or <NetStandardImplicitPackageVersion> section in the .csproj.

Spring MVC: how to create a default controller for index page?

It works for me, but some differences:

  • I have no welcome-file-list in web.xml
  • I have no @RequestMapping at class level.
  • And at method level, just @RequestMapping("/")

I know these are no great differences, but I'm pretty sure (I'm not at work now) this is my configuration and it works with Spring MVC 3.0.5.

One more thing. You don't show your dispatcher configuration in web.xml, but maybe you have some preffix. It has to be something like this:

<servlet-mapping>
    <servlet-name>myServletName</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

If this is not your case, you'll need an url-rewrite filter or try the redirect solution.

EDIT: Answering your question, my view resolver configuration is a little different too:

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/view/" />
    <property name="suffix" value=".jsp" />
</bean>

Plot a bar using matplotlib using a dictionary

Why not just:

import seaborn as sns

sns.barplot(list(D.keys()), list(D.values()))

How can I simulate mobile devices and debug in Firefox Browser?

You can use tools own browser (Firefox, IE, Chrome...) to debug your JavaScript.

As for resizing, Firefox/Chrome has own resources accessible via Ctrl + Shift + I OR F12. Going tab "style editor" and clicking "adaptive/responsive design" icon.

Old Firefox versions

Old Firefox

New Firefox/Firebug

Firefox

Chrome

Chrome

*Another way is to install an addon like "Web Developer"

Best tool for inspecting PDF files?

I use iText RUPS(Reading and Updating PDF Syntax) in Linux. Since it's written in Java, it works on Windows, too. You can browse all the objects in PDF file in a tree structure. It can also decode Flate encoded streams on-the-fly to make inspecting easier.

Here is a screenshot:

iText RUPS screenshot

ShowAllData method of Worksheet class failed

AutoFilterMode will be True if engaged, regardless of whether there is actually a filter applied to a specific column or not. When this happens, ActiveSheet.ShowAllData will still run, throwing an error (because there is no actual filtering).

I had the same issue and got it working with

If (ActiveSheet.AutoFilterMode And ActiveSheet.FilterMode) Or ActiveSheet.FilterMode Then
  ActiveSheet.ShowAllData
End If

This seems to prevent ShowAllData from running when there is no actual filter applied but with AutoFilterMode turned on.

The second catch Or ActiveSheet.FilterMode should catch advanced filters

Where to download visual studio express 2005?

For somebody like me who lands onto this page from Google ages after this question had been posted, you can find VS2005 here: http://apdubey.blogspot.com/2009/04/microsoft-visual-studio-2005-express.html

EDIT: In case that blog dies, here are the links from the blog.

All the bellow files are more them 400MB.

Visual Web Developer 2005 Express Edition
449,848 KB
.IMG File | .ISO File

Visual Basic 2005 Express Edition
445,282 KB
.IMG File | .ISO File

Visual C# 2005 Express Edition
445,282 KB
.IMG File | .ISO File

Visual C++ 2005 Express Edition
474,686 KB
.IMG File | .ISO File

Visual J# 2005 Express Edition
448,702 KB
.IMG File | .ISO File

Install NuGet via PowerShell script

Here's a short PowerShell script to do what you probably expect:

$sourceNugetExe = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe"
$targetNugetExe = "$rootPath\nuget.exe"
Invoke-WebRequest $sourceNugetExe -OutFile $targetNugetExe
Set-Alias nuget $targetNugetExe -Scope Global -Verbose

Note that Invoke-WebRequest cmdlet arrived with PowerShell v3.0. This article gives the idea.

HTML5 Audio Looping

Simplest way is:

bgSound = new Audio("sounds/background.mp3");
bgSound.loop = true;
bgSound.play();

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

After having all the proposed solutions fail my tests one way or the other, (edit: some were updated to pass the tests after I wrote this) I found the mozilla implementation for Array.indexOf and Array.lastIndexOf

I used those to implement my version of String.prototype.regexIndexOf and String.prototype.regexLastIndexOf as follows:

String.prototype.regexIndexOf = function(elt /*, from*/)
  {
    var arr = this.split('');
    var len = arr.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0) ? Math.ceil(from) : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++) {
      if (from in arr && elt.exec(arr[from]) ) 
        return from;
    }
    return -1;
};

String.prototype.regexLastIndexOf = function(elt /*, from*/)
  {
    var arr = this.split('');
    var len = arr.length;

    var from = Number(arguments[1]);
    if (isNaN(from)) {
      from = len - 1;
    } else {
      from = (from < 0) ? Math.ceil(from) : Math.floor(from);
      if (from < 0)
        from += len;
      else if (from >= len)
        from = len - 1;
    }

    for (; from > -1; from--) {
      if (from in arr && elt.exec(arr[from]) )
        return from;
    }
    return -1;
  };

They seem to pass the test functions I provided in the question.

Obviously they only work if the regular expression matches one character but that is enough for my purpose since I will be using it for things like ( [abc] , \s , \W , \D )

I will keep monitoring the question in case someone provides a better/faster/cleaner/more generic implementation that works on any regular expression.

VB.NET Connection string (Web.Config, App.Config)

I don't know if this still is an issue, but i prefere just to use the My.Settings in my code.

Visual Studio generates a simple class with functions for reading settings from the app.config file.

You can simply access it using My.Settings.ConnectionString.

    Using Context As New Data.Context.DataClasses()
        Context.Connection.ConnectionString = My.Settings.ConnectionString
    End Using

Getting an odd error, SQL Server query using `WITH` clause

In some cases this also occurs if you have table hints and you have spaces between WITH clause and your hint, so best to type it like:

SELECT Column1 FROM Table1 t1 WITH(NOLOCK)
INNER JOIN Table2 t2 WITH(NOLOCK) ON t1.Column1 = t2.Column1

And not:

SELECT Column1 FROM Table1 t1 WITH (NOLOCK)
INNER JOIN Table2 t2 WITH (NOLOCK) ON t1.Column1 = t2.Column1

How to clear Flutter's Build cache?

I found a way to automate running the clean before you debug your code. (Warning, this runs everytime you hit the button, even for hot restart)

  1. First, find the Run > Edit Configurations Menu

  2. Click the External tool '+' icon under Before launch: External tool, Activate tool window.

  3. Run External Tool
  4. Configure it like so. Put the working directory as a directory in your project.

Edit Configurations. Configurations

Run External Tool Add Flutter Clean

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

Dim f as Range

Set f=ActiveSheet.Cells.Find(...)

If Not f Is Nothing then
    msgbox "Row=" & f.Row & vbcrlf & "Column=" & f.Column
Else
    msgbox "value not found!"
End If

How to get all keys with their values in redis

I refined the bash solution a bit, so that the more efficient scan is used instead of keys, and printing out array and hash values is supported. My solution also prints out the key name.

redis_print.sh:

#!/bin/bash

# Default to '*' key pattern, meaning all redis keys in the namespace
REDIS_KEY_PATTERN="${REDIS_KEY_PATTERN:-*}"
for key in $(redis-cli --scan --pattern "$REDIS_KEY_PATTERN")
do
    type=$(redis-cli type $key)
    if [ $type = "list" ]
    then
        printf "$key => \n$(redis-cli lrange $key 0 -1 | sed 's/^/  /')\n"
    elif [ $type = "hash" ]
    then
        printf "$key => \n$(redis-cli hgetall $key | sed 's/^/  /')\n"
    else
        printf "$key => $(redis-cli get $key)\n"
    fi
done

Note: you can formulate a one-liner of this script by removing the first line of redis_print.sh and commanding: cat redis_print.sh | tr '\n' ';' | awk '$1=$1'

Detect if a jQuery UI dialog box is open

jQuery dialog has an isOpen property that can be used to check if a jQuery dialog is open or not.

You can see example at this link: http://www.codegateway.com/2012/02/detect-if-jquery-dialog-box-is-open.html

AsyncTask Android example

Change your code as given below:

@Override
protected void onPostExecute(String result) {

    runOnUiThread(new Runnable() {
        public void run() {
            TextView txt = (TextView) findViewById(R.id.output);
            txt.setText("Executed");
        }
    });
}

How to analyse the heap dump using jmap in java

MAT, jprofiler,jhat are possible options. since jhat comes with jdk, you can easily launch it to do some basic analysis. check this out

Converting HTML string into DOM elements?

You typically create a temporary parent element to which you can write the innerHTML, then extract the contents:

var wrapper= document.createElement('div');
wrapper.innerHTML= '<div><a href="#"></a><span></span></div>';
var div= wrapper.firstChild;

If the element whose outer-HTML you've got is a simple <div> as here, this is easy. If it might be something else that can't go just anywhere, you might have more problems. For example if it were a <li>, you'd have to have the parent wrapper be a <ul>.

But IE can't write innerHTML on elements like <tr> so if you had a <td> you'd have to wrap the whole HTML string in <table><tbody><tr>...</tr></tbody></table>, write that to innerHTML and extricate the actual <td> you wanted from a couple of levels down.

Rails - passing parameters in link_to

First of all, link_to is a html tag helper, its second argument is the url, followed by html_options. What you would like is to pass account_id as a url parameter to the path. If you have set up named routes correctly in routes.rb, you can use path helpers.

link_to "+ Service", new_my_service_path(:account_id => acct.id)

I think the best practice is to pass model values as a param nested within :

link_to "+ Service", new_my_service_path(:my_service => { :account_id => acct.id })

# my_services_controller.rb
def new
  @my_service = MyService.new(params[:my_service])
end

And you need to control that account_id is allowed for 'mass assignment'. In rails 3 you can use powerful controls to filter valid params within the controller where it belongs. I highly recommend.

http://apidock.com/rails/ActiveModel/MassAssignmentSecurity/ClassMethods

Also note that if account_id is not freely set by the user (e.g., a user can only submit a service for the own single account_id, then it is better practice not to send it via the request, but set it within the controller by adding something like:

@my_service.account_id = current_user.account_id 

You can surely combine the two if you only allow users to create service on their own account, but allow admin to create anyone's by using roles in attr_accessible.

hope this helps

Export table data from one SQL Server to another

Yet another option if you have it available: c# .net. In particular, the Microsoft.SqlServer.Management.Smo namespace.

I use code similar to the following in a Script Component of one of my SSIS packages.

var tableToTransfer = "someTable";
var transferringTableSchema = "dbo";

var srvSource = new Server("sourceServer");
var dbSource = srvSource.Databases["sourceDB"];

var srvDestination = new Server("destinationServer"); 
var dbDestination = srvDestination.Databases["destinationDB"];

var xfr = 
    new Transfer(dbSource) {
        DestinationServer = srvDestination.Name,
        DestinationDatabase = dbDestination.Name,
        CopyAllObjects = false,
        DestinationLoginSecure = true,
        DropDestinationObjectsFirst = true,
        CopyData = true
    };

xfr.Options.ContinueScriptingOnError = false; 
xfr.Options.WithDependencies = false; 

xfr.ObjectList.Add(dbSource.Tables[tableToTransfer,transferringTableSchema]);
xfr.TransferData();

I think I had to explicitly search for and add the Microsoft.SqlServer.Smo library to the references. But outside of that, this has been working out for me.

Update: The namespace and libraries were more complicated than I remembered.

For libraries, add references to:

  • Microsoft.SqlServer.Smo.dll
  • Microsoft.SqlServer.SmoExtended.dll
  • Microsoft.SqlServer.ConnectionInfo.dll
  • Microsoft.SqlServer.Management.Sdk.Sfc.dll

For the Namespaces, add:

  • Microsoft.SqlServer.Management.Common
  • Microsoft.SqlServer.Management.Smo

How to get the difference between two arrays in JavaScript?

if you don't care about original arrays and have no problem to edit them then this is quicker algorithm:

let iterator = arrayA.values()
let result = []
for (entryA of iterator) {
    if (!arrayB.includes(entryA)) {
        result.push(entryA)
    } else {
        arrayB.splice(arrayB.indexOf(entryA), 1) 
    }
}

result.push(...arrayB)
return result

Margin while printing html page

I'd personally suggest using a different unit of measurement than px. I don't think that pixels have much relevance in terms of print; ideally you'd use:

  • point (pt)
  • centimetre (cm)

I'm sure there are others, and one excellent article about print-css can be found here: Going to Print, by Eric Meyer.

Creating/writing into a new file in Qt

It can happen that the cause is not that you don't find the right directory. For example, you can read from the file (even without absolute path) but it seems you cannot write into it.

In that case, it might be that you program exits before the writing can be finished.

If your program uses an event loop (like with a GUI application, e.g. QMainWindow) it's not a problem. However, if your program exits immediately after writing to the file, you should flush the text stream, closing the file is not always enough (and it's unnecessary, as it is closed in the destructor).

stream << "something" << endl;
stream.flush();

This guarantees that the changes are committed to the file before the program continues from this instruction.

The problem seems to be that the QFile is destructed before the QTextStream. So, even if the stream is flushed in the QTextStream destructor, it's too late, as the file is already closed.

How to change Windows 10 interface language on Single Language version

Worked for me:

  1. Download package (see links below), name it lp.cab and place it to your C: drive

  2. Run the following commands as Administrator:

2.1 installing new language

dism /Online /Add-Package /PackagePath:C:\lp.cab

2.2 get installed packages

dism /Online /Get-Packages

2.3 remove original package

dism /Online /Remove-Package /PackageName:Microsoft-Windows-Client-LanguagePack-Package~31bf3856ad364e35~amd64~ru-RU~10.0.10240.16384

If you don't know which is your original package you can check your installed packages with this line

dism /Online /Get-Packages | findstr /c:"LanguagePack"

  1. Enjoy your new system language

List of MUI for Windows 10:

For LPs for Windows 10 version 1607 build 14393, follow this link.

Windows 10 x64 (Build 10240):

zh-CN: Chinese download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_9949b0581789e2fc205f0eb005606ad1df12745b.cab

hr-HR: Croatian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_c3bde55e2405874ec8eeaf6dc15a295c183b071f.cab

cs-CZ: Czech download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_d0b2a69faa33d1ea1edc0789fdbb581f5a35ce2d.cab

da-DK: Danish download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_15e50641cef50330959c89c2629de30ef8fd2ef6.cab

nl-NL: Dutch download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_8658b909525f49ab9f3ea9386a0914563ffc762d.cab

en-us: English download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_75d67444a5fc444dbef8ace5fed4cfa4fb3602f0.cab

fr-FR: French download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_206d29867210e84c4ea1ff4d2a2c3851b91b7274.cab

de-DE: German download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_3bb20dd5abc8df218b4146db73f21da05678cf44.cab

hi-IN: Hindi download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_e9deaa6a8d8f9dfab3cb90986d320ff24ab7431f.cab

it-IT: Italian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_42c622dc6957875eab4be9d57f25e20e297227d1.cab

ja-JP: Japanese download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_adc2ec900dd1c5e94fc0dbd8e010f9baabae665f.cab

kk-KZ: Kazakh download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_a03ed475983edadd3eb73069c4873966c6b65daf.cab

ko-KR: Korean download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_24411100afa82ede1521337a07485c65d1a14c1d.cab

pt-BR: Portuguese download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_894199ed72fdf98e4564833f117380e45b31d19f.cab

ru-RU: Russian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_d85bb9f00b5ee0b1ea3256b6e05c9ec4029398f0.cab

es-ES: Spanish download.windowsupdate.com/c/msdownload/update/software/updt/2015/07/lp_7b21648a1df6476b39e02476c2319d21fb708c7d.cab

uk-UA: Ukrainian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_131991188afe0ef668d77c8a9a568cb71b57f09f.cab

Windows 10 x86 (Build 10240):

zh-CN: Chinese download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_e7d13432345bcf589877cd3f0b0dad4479785f60.cab

hr-HR: Croatian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_60856d8b4d643835b30d8524f467d4d352395204.cab

cs-CZ: Czech download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_dfa71b93a76b4500578b67fd3bf6b9f10bf5beaa.cab

da-DK: Danish download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_af0ea4318f43d9cb30bcfa5ce7279647f10bc3b3.cab

nl-NL: Dutch download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_cbcdf4818eac2a15cfda81e37595f8ffeb037fd7.cab

en-us: English download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_41877260829bb5f57a52d3310e326c6828d8ce8f.cab

fr-FR: French download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_80fa697f051a3a949258797a0635a4313a448c29.cab

de-DE: German download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_7ea2648033099f99f87642e47e6d959172c6cab8.cab

hi-IN: Hindi download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_78a11997f4e4bf73bbdb1da8011ebfb218bd1bac.cab

it-IT: Italian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_9e62d9a8b141e0eb6434af5a44c4f9468b60a075.cab

ja-JP: Japanese download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_79bd099ac811cb1771e6d9b03d640e5eca636b23.cab

kk-KZ: Kazakh download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_59e690df497799cacb96ab579a706250e5a0c8b6.cab

ko-KR: Korean download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_a88379b0461479ab8b5b47f65c4c3241ef048c04.cab

pt-BR: Portuguese download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_bb9f192068fe42fde8787591197a53c174dce880.cab

ru-RU: Russian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_280bf97bbe34cec1b0da620fa1b2dfe5bdb3ea07.cab

es-ES: Spanish download.windowsupdate.com/c/msdownload/update/software/updt/2015/07/lp_31400c38ffea2f0a44bb2dfbd80086aa3cad54a9.cab

uk-UA: Ukrainian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_41cd48aa22d21f09fbcedc69197609c1f05f433d.cab

Can I create links with 'target="_blank"' in Markdown?

You can add any attributes using {[attr]="[prop]"}

For example [Google] (http://www.google.com){target="_blank"}

How do I resolve this "ORA-01109: database not open" error?

please run this script

ALTER DATABASE OPEN

How to check if any value is NaN in a Pandas DataFrame

Here is another interesting way of finding null and replacing with a calculated value

    #Creating the DataFrame

    testdf = pd.DataFrame({'Tenure':[1,2,3,4,5],'Monthly':[10,20,30,40,50],'Yearly':[10,40,np.nan,np.nan,250]})
    >>> testdf2
       Monthly  Tenure  Yearly
    0       10       1    10.0
    1       20       2    40.0
    2       30       3     NaN
    3       40       4     NaN
    4       50       5   250.0

    #Identifying the rows with empty columns
    nan_rows = testdf2[testdf2['Yearly'].isnull()]
    >>> nan_rows
       Monthly  Tenure  Yearly
    2       30       3     NaN
    3       40       4     NaN

    #Getting the rows# into a list
    >>> index = list(nan_rows.index)
    >>> index
    [2, 3]

    # Replacing null values with calculated value
    >>> for i in index:
        testdf2['Yearly'][i] = testdf2['Monthly'][i] * testdf2['Tenure'][i]
    >>> testdf2
       Monthly  Tenure  Yearly
    0       10       1    10.0
    1       20       2    40.0
    2       30       3    90.0
    3       40       4   160.0
    4       50       5   250.0

How to solve "java.io.IOException: error=12, Cannot allocate memory" calling Runtime#exec()?

This is the solution but you have to set:

echo 1 > /proc/sys/vm/overcommit_memory

How do I use dataReceived event of the SerialPort Port Object in C#?

I think your issue is the line:**

sp.DataReceived += port_OnReceiveDatazz;

Shouldn't it be:

sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);

**Nevermind, the syntax is fine (didn't realize the shortcut at the time I originally answered this question).

I've also seen suggestions that you should turn the following options on for your serial port:

sp.DtrEnable = true;    // Data-terminal-ready
sp.RtsEnable = true;    // Request-to-send

You may also have to set the handshake to RequestToSend (via the handshake enumeration).


UPDATE:

Found a suggestion that says you should open your port first, then assign the event handler. Maybe it's a bug?

So instead of this:

sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);
sp.Open();

Do this:

sp.Open();
sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);

Let me know how that goes.

jQuery UI autocomplete with JSON

I use this script for autocomplete...

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

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

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

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

Get last n lines of a file, similar to tail

Simple :

with open("test.txt") as f:
data = f.readlines()
tail = data[-2:]
print(''.join(tail)

How can I compare two lists in python and return matches

The following solution works for any order of list items and also supports both lists to be different length.

import numpy as np
def getMatches(a, b):
    matches = []
    unique_a = np.unique(a)
    unique_b = np.unique(b)
    for a in unique_a:
        for b in unique_b:
            if a == b:
                matches.append(a)
    return matches
print(getMatches([1, 2, 3, 4, 5], [9, 8, 7, 6, 5, 9])) # displays [5]
print(getMatches([1, 2, 3], [3, 4, 5, 1])) # displays [1, 3]

'dependencies.dependency.version' is missing error, but version is managed in parent

I had the same error, I forgot to add the child dependencies in the <dependencyManagement>. For example in the parent pom:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.sw.system4</groupId>
            <artifactId>system4-data</artifactId><!-- child artifact id -->
            <version>${project.version}</version>
        <dependency>

        <!-- add all third party libraries ... -->

    </dependencies>
<dependencyManagement>

What does "pending" mean for request in Chrome Developer Window?

Same problem with Chrome : I had in my html page the following code :

<body>
  ...
  <script src="http://myserver/lib/load.js"></script>
  ...
</body>

But the load.js was always in status pending when looking in the Network pannel.

I found a workaround using asynchronous load of load.js:

<body>
  ...
  <script>
    setTimeout(function(){
      var head, script;
      head = document.getElementsByTagName("head")[0];
      script = document.createElement("script");
      script.src = "http://myserver/lib/load.js";
      head.appendChild(script);
    }, 1);
  </script>
  ...
</body>

Now its working fine.

Can IntelliJ IDEA encapsulate all of the functionality of WebStorm and PHPStorm through plugins?

Definitely a great question. I've noted this also as a sub question of the choice for versions within IDEa that this link may help to address...

http://www.jetbrains.com/idea/features/editions_comparison_matrix.html

it as well potentially possesses a ground work for looking at your other IDE choices and the options they provide.

I'm thinking WebStorm is best for JavaScript and Git repo management, meaning the HTML5 CSS Cordova kinds of stacks, which is really where (I believe along with others) the future lies and energies should be focused now... but ya it depends on your needs, etc.

Anyway this tells that story too... http://www.jetbrains.com/products.html

C# : Passing a Generic Object

It doesn't compile because T could be anything, and not everything will have the myvar field.

You could make myvar a property on ITest:

public ITest
{
    string myvar{get;}
}

and implement it on the classes as a property:

public class MyClass1 : ITest
{
    public string myvar{ get { return "hello 1"; } }
}

and then put a generic constraint on your method:

public void PrintGeneric<T>(T test) where T : ITest
{
    Console.WriteLine("Generic : " + test.myvar);
}

but in that case to be honest you are better off just passing in an ITest:

public void PrintGeneric(ITest test)
{
    Console.WriteLine("Generic : " + test.myvar);
}

How to show the Project Explorer window in Eclipse

In the main menu go with following steps

Window -> Show View -> Package Explorer.

Reset Windows Activation/Remove license key

On Windows XP -

  1. Reboot into "Safe mode with Command Prompt"
  2. Type "explorer" in the command prompt that comes up and push [Enter]
  3. Click on Start>Run, and type the following :

    rundll32.exe syssetup,SetupOobeBnk

Reboot, and login as normal.

This will reset the 30 day timer for activation back to 30 days so you can enter in the key normally.

Div Background Image Z-Index Issue

Set your header and footer position to "absolute" and that should do the trick. Hope it helps and good luck with your project!

R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph

First off, your code is a bit off. aes() is an argument in ggplot(), you don't use ggplot(...) + aes(...) + layers

Second, from the help file ?geom_bar:

By default, geom_bar uses stat="count" which makes the height of the bar proportion to the number of cases in each group (or if the weight aethetic is supplied, the sum of the weights). If you want the heights of the bars to represent values in the data, use stat="identity" and map a variable to the y aesthetic.

You want the second case, where the height of the bar is equal to the conversion_rate So what you want is...

data_country <- data.frame(country = c("China", "Germany", "UK", "US"), 
            conversion_rate = c(0.001331558,0.062428188, 0.052612025, 0.037800687))
ggplot(data_country, aes(x=country,y = conversion_rate)) +geom_bar(stat = "identity")

Result:

enter image description here

How to resolve the error "Unable to access jarfile ApacheJMeter.jar errorlevel=1" while initiating Jmeter?

For window if you download scr folder say apache-jmeter-5.3_src then you won't find ApacheJMeter.jar file insider bin folder.One might have downloaded zip file under source section. Form this link download zip file under binaries section and click on ApacheJMeter.jar from bin folder https://jmeter.apache.org/download_jmeter.cgi

vba listbox multicolumn add

Simplified example (with counter):

With Me.lstbox
    .ColumnCount = 2
    .ColumnWidths = "60;60"
    .AddItem
    .List(i, 0) = Company_ID
    .List(i, 1) = Company_name 
    i = i + 1

end with

Make sure to start the counter with 0, not 1 to fill up a listbox.

How can I mock an ES6 module import using Jest?

I solved this another way. Let's say you have your dependency.js

export const myFunction = () => { }

I create a depdency.mock.js file besides it with the following content:

export const mockFunction = jest.fn();

jest.mock('dependency.js', () => ({ myFunction: mockFunction }));

And in the test, before I import the file that has the dependency, I use:

import { mockFunction } from 'dependency.mock'
import functionThatCallsDep from './tested-code'

it('my test', () => {
    mockFunction.returnValue(false);

    functionThatCallsDep();

    expect(mockFunction).toHaveBeenCalled();

})

max(length(field)) in mysql

In case you need both max and min from same table:

    select * from (
(select city, length(city) as maxlen from station
order by maxlen desc limit 1)
union
(select city, length(city) as minlen from station
order by minlen,city limit 1))a;

Merge (Concat) Multiple JSONObjects in Java

Merging typed data structure trees is not trivial, you need to define the precedence, handle incompatible types, define how they will be casted and merged...

So in my opinion, you won't avoid

... pulling them all apart and individually adding in by puts`.

If your question is: Has someone done it for me yet? Then I think you can have a look at this YAML merging library/tool I revived. (YAML is a superset of JSON), and the principles are applicable to both.
(However, this particular code returns YAML objects, not JSON. Feel free to extend the project and send a PR.)

How can I post data as form data instead of a request payload?

In your app config -

$httpProvider.defaults.transformRequest = function (data) {
        if (data === undefined)
            return data;
        var clonedData = $.extend(true, {}, data);
        for (var property in clonedData)
            if (property.substr(0, 1) == '$')
                delete clonedData[property];

        return $.param(clonedData);
    };

With your resource request -

 headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }

Java POI : How to read Excel cell value and not the formula computing it?

If you want to extract a raw-ish value from a HSSF cell, you can use something like this code fragment:

CellBase base = (CellBase) cell;
CellType cellType = cell.getCellType();
base.setCellType(CellType.STRING);
String result = cell.getStringCellValue();
base.setCellType(cellType);

At least for strings that are completely composed of digits (and automatically converted to numbers by Excel), this returns the original string (e.g. "12345") instead of a fractional value (e.g. "12345.0"). Note that setCellType is available in interface Cell(as of v. 4.1) but deprecated and announced to be eliminated in v 5.x, whereas this method is still available in class CellBase. Obviously, it would be nicer either to have getRawValue in the Cell interface or at least to be able use getStringCellValue on non STRING cell types. Unfortunately, all replacements of setCellType mentioned in the description won't cover this use case (maybe a member of the POI dev team reads this answer).

Reference — What does this symbol mean in PHP?

Type Operators

instanceof is used to determine whether a PHP variable is an instantiated object of a certain class.

<?php
class mclass { }
class sclass { }
$a = new mclass;
var_dump($a instanceof mclass);
var_dump($a instanceof sclass);

The above example will output:

bool(true)
bool(false)

Reason: Above Example $a is a object of the mclass so use only a mclass data not instance of with the sclass

Example with inheritance

<?php 
class pclass { } 
class childclass extends pclass { } 
$a = new childclass; 
var_dump($a instanceof childclass); 
var_dump($a instanceof pclass);

The above example will output:

bool(true)
bool(true)

Example with Clone

<?php 
class cloneable { } 
$a = new cloneable;
$b = clone $a; 
var_dump($a instanceof cloneable); 
var_dump($b instanceof cloneable);

The above example will output:

bool(true)
bool(true)

HTTP 401 - what's an appropriate WWW-Authenticate header value?

When the user session times out, I send back an HTTP 204 status code. Note that the HTTP 204 status contains no content. On the client-side I do this:

xhr.send(null);
if (xhr.status == 204) 
    Reload();
else 
    dropdown.innerHTML = xhr.responseText;

Here is the Reload() function:

function Reload() {
    var oForm = document.createElement("form");
    document.body.appendChild(oForm);
    oForm.submit();
    }

How to remove last n characters from every element in the R vector

Although this is mostly the same with the answer by @nfmcclure, I prefer using stringr package as it provdies a set of functions whose names are most consistent and descriptive than those in base R (in fact I always google for "how to get the number of characters in R" as I can't remember the name nchar()).

library(stringr)
str_sub(iris$Species, end=-4)
#or 
str_sub(iris$Species, 1, str_length(iris$Species)-3)

This removes the last 3 characters from each value at Species column.

Java optional parameters

Default arguments can not be used in Java. Where in C#, C++ and Python, we can use them..

In Java, we must have to use 2 methods (functions) instead of one with default parameters.

Example:

Stash(int size); 

Stash(int size, int initQuantity);

http://parvindersingh.webs.com/apps/forums/topics/show/8856498-java-how-to-set-default-parameters-values-like-c-

Installing SQL Server 2012 - Error: Prior Visual Studio 2010 instances requiring update

Only install the Service Pack (VS10sp1-KB983509.msp) wasn't enough to me.

I had to uninstall the Visual Studio Team Explorer 2010 to continue the installation :)

Loop through each cell in a range of cells when given a Range object

I'm resurrecting the dead here, but because a range can be defined as "A:A", using a for each loop ends up with a potential infinite loop. The solution, as far as I know, is to use the Do Until loop.

Do Until Selection.Value = ""
  Rem Do things here...
Loop

Adding a collaborator to my free GitHub account?

FYI for future readers. The instructions above are outdated, in particular step 2:
2. Click on Settings button

Delete all rows in table

You can rename the table in question, create a table with an identical schema, and then drop the original table at your leisure.

See the MySQL 5.1 Reference Manual for the [RENAME TABLE][1] and [CREATE TABLE][2] commands.

RENAME TABLE tbl TO tbl_old;

CREATE TABLE tbl LIKE tbl_old;

DROP TABLE tbl_old; -- at your leisure

This approach can help minimize application downtime.

DateTime.MinValue and SqlDateTime overflow

If you use DATETIME2 you may find you have to pass the parameter in specifically as DATETIME2, otherwise it may helpfully convert it to DATETIME and have the same issue.

command.Parameters.Add("@FirstRegistration",SqlDbType.DateTime2).Value = installation.FirstRegistration;

List comprehension vs. lambda + filter

In addition to the accepted answer, there is a corner case when you should use filter instead of a list comprehension. If the list is unhashable you cannot directly process it with a list comprehension. A real world example is if you use pyodbc to read results from a database. The fetchAll() results from cursor is an unhashable list. In this situation, to directly manipulating on the returned results, filter should be used:

cursor.execute("SELECT * FROM TABLE1;")
data_from_db = cursor.fetchall()
processed_data = filter(lambda s: 'abc' in s.field1 or s.StartTime >= start_date_time, data_from_db) 

If you use list comprehension here you will get the error:

TypeError: unhashable type: 'list'

Backup a single table with its data from a database in sql server 2008

You can use the "Generate script for database objects" feature on SSMS.

  1. Right click on the target database
  2. Select Tasks > Generate Scripts
  3. Choose desired table or specific object
  4. Hit the Advanced button
  5. Under General, choose value on the Types of data to script. You can select Data only, Schema only, and Schema and data. Schema and data includes both table creation and actual data on the generated script.
  6. Click Next until wizard is done

This one solved my challenge.
Hope this will help you as well.

AJAX jQuery refresh div every 5 seconds

Try to not use setInterval.
You can resend request to server after successful response with timeout.
jQuery:

sendRequest(); //call function

function sendRequest(){
    $.ajax({
        url: "test.php",
        success: 
        function(result){
            $('#links').text(result); //insert text of test.php into your div
            setTimeout(function(){
                sendRequest(); //this will send request again and again;
            }, 5000);
        }
    });
}

sql server #region

Not out of the box in Sql Server Management Studio, but it is a feature of the very good SSMS Tools Pack

Select distinct rows from datatable in Linq

If it's not a typed dataset, then you probably want to do something like this, using the Linq-to-DataSet extension methods:

var distinctValues = dsValues.AsEnumerable()
                        .Select(row => new {
                            attribute1_name = row.Field<string>("attribute1_name"),
                            attribute2_name = row.Field<string>("attribute2_name")
                         })
                        .Distinct();

Make sure you have a using System.Data; statement at the beginning of your code in order to enable the Linq-to-Dataset extension methods.

Hope this helps!

Use <Image> with a local file

ES6 solution:

import DefaultImage from '../assets/image.png';

const DEFAULT_IMAGE = Image.resolveAssetSource(DefaultImage).uri;

and then:

<Image source={{uri: DEFAULT_IMAGE}} />

Command /Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 1

In my case it was a duplicate Swift Flag entry inside my Target's Build Settings > Other Swift Flags. I had two -Xfrontend entries in it.

Sibling package imports

You need to look to see how the import statements are written in the related code. If examples/example_one.py uses the following import statement:

import api.api

...then it expects the root directory of the project to be in the system path.

The easiest way to support this without any hacks (as you put it) would be to run the examples from the top level directory, like this:

PYTHONPATH=$PYTHONPATH:. python examples/example_one.py 

What is the most "pythonic" way to iterate over a list in chunks?

Quite pythonic here (you may also inline the body of the split_groups function)

import itertools
def split_groups(iter_in, group_size):
    return ((x for _, x in item) for _, item in itertools.groupby(enumerate(iter_in), key=lambda x: x[0] // group_size))

for x, y, z, w in split_groups(range(16), 4):
    foo += x * y + z * w

How to read a line from a text file in c/c++?

getline() is what you're looking for. You use strings in C++, and you don't need to know the size ahead of time.

Assuming std namespace:

 ifstream file1("myfile.txt");
 string stuff;

 while (getline(file1, stuff, '\n')) {
      cout << stuff << endl;
 }

 file1.close();

How to get POSTed JSON in Flask?

Assuming that you have posted valid JSON,

@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
    content = request.json
    print content['uuid']
    # Return data as JSON
    return jsonify(content)

How can you strip non-ASCII characters from a string? (in C#)

no need for regex. just use encoding...

sOutput = System.Text.Encoding.ASCII.GetString(System.Text.Encoding.ASCII.GetBytes(sInput));

How to handle button clicks using the XML onClick within Fragments

Adding to Blundell's answer,
If you have more fragments, with plenty of onClicks:

Activity:

Fragment someFragment1 = (Fragment)getFragmentManager().findFragmentByTag("someFragment1 "); 
Fragment someFragment2 = (Fragment)getFragmentManager().findFragmentByTag("someFragment2 "); 
Fragment someFragment3 = (Fragment)getFragmentManager().findFragmentByTag("someFragment3 "); 

...onCreate etc instantiating your fragments

public void myClickMethod(View v){
  if (someFragment1.isVisible()) {
       someFragment1.myClickMethod(v);
  }else if(someFragment2.isVisible()){
       someFragment2.myClickMethod(v);
  }else if(someFragment3.isVisible()){
       someFragment3.myClickMethod(v); 
  }

} 

In Your Fragment:

  public void myClickMethod(View v){
     switch(v.getid()){
       // Just like you were doing
     }
  } 

Plot multiple columns on the same graph in R

To select columns to plot, I added 2 lines to Vincent Zoonekynd's answer:

#convert to tall/long format(from wide format)
col_plot = c("A","B")
dlong <- melt(d[,c("Xax", col_plot)], id.vars="Xax")  

#"value" and "variable" are default output column names of melt()
ggplot(dlong, aes(Xax,value, col=variable)) +
  geom_point() + 
  geom_smooth()

Google "tidy data" to know more about tall(or long)/wide format.

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given

This means that the first parameter you passed is a boolean (true or false).

The first parameter is $result, and it is false because there is a syntax error in the query.

" ... WHERE PartNumber = $partid';"

You should never directly include a request variable in a SQL query, else the users are able to inject SQL in your queries. (See SQL injection.)

You should escape the variable:

" ... WHERE PartNumber = '" . mysqli_escape_string($conn,$partid) . "';"

Or better, use Prepared Statements.

Missing artifact com.microsoft.sqlserver:sqljdbc4:jar:4.0

You can also create a project repository. It's useful if more developers are working on the same project, and the library must be included in the project.

  • First, create a repository structure in your project's lib directory, and then copy the library into it. The library must have following name-format: <artifactId>-<version>.jar

    <your_project_dir>/lib/com/microsoft/sqlserver/<artifactId>/<version>/

  • Create pom file next to the library file, and put following information into it:

    <?xml version="1.0" encoding="UTF-8"?>
     <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
         <modelVersion>4.2.0</modelVersion>
         <groupId>com.microsoft.sqlserver</groupId>
         <artifactId>sqljdbc4</artifactId>
         <version>4.2</version>
     </project>
     
  • At this point, you should have this directory structure:

    <your_project_dir>/lib/com/microsoft/sqlserver/sqljdbc4/4.2/sqljdbc4-4.2.jar <your_project_dir>/lib/com/microsoft/sqlserver/sqljdbc4/4.2/sqljdbc4-4.2.pom

  • Go to your project's pom file and add new repository:

    <repositories>
         <repository>
             <id>Project repository</id>
             <url>file://${basedir}/lib</url>
         </repository>
     </repositories>
     
  • Finally, add a dependency on the library:

    <dependencies>
         <dependency>
             <groupId>com.microsoft.sqlserver</groupId>
             <artifactId>sqljdbc4</artifactId>
             <version>4.2</version>
         </dependency>
     </dependencies>
     

Update 2017-03-04

It seems like the library can be obtained from publicly available repository. @see nirmal's and Jacek Grzelaczyk's answers for more details.

Update 2020-11-04

Currently Maven has a convenient target install which allow you to deploy an existing package into a project / file repository without the need of creating POM files manually. It will generate those files for you.

mvn install:install-file \
    -Dfile=sqljdbc4.jar \
    -DgroupId=com.microsoft.sqlserver \
    -DartifactId=sqljdbc4 \
    -Dversion=4.2 \
    -Dpackaging=jar \
    -DlocalRepositoryPath=${your_project_dir}/lib

Laravel 5: Display HTML with Blade

For who using tinymce and markup within textarea:

{{ htmlspecialchars($text) }}

Get webpage contents with Python?

A solution with works with Python 2.X and Python 3.X:

try:
    # For Python 3.0 and later
    from urllib.request import urlopen
except ImportError:
    # Fall back to Python 2's urllib2
    from urllib2 import urlopen

url = 'http://hiscore.runescape.com/index_lite.ws?player=zezima'
response = urlopen(url)
data = str(response.read())

Can I write or modify data on an RFID tag?

I did some development with Mifare Classic (ISO 14443A) cards about 7-8 years ago. You can read and write to all sectors of the card, IIRC the only data you can't change is the serial number. Back then we used a proprietary library from Philips Semiconductors. The command interface to the card was quite alike the ISO 7816-4 (used with standard Smart Cards).

I'd recomment that you look at the OpenPCD platform if you are into development.

This is also of interest regarding the cryptographic functions in some RFID cards.

Git Ignores and Maven targets

It is possible to use patterns in a .gitignore file. See the gitignore man page. The pattern */target/* should ignore any directory named target and anything under it. Or you may try */target/** to ignore everything under target.

How to efficiently calculate a running standard deviation?

How big is your array? Unless it is zillions of elements long, don't worry about looping through it twice. The code is simple and easily tested.

My preference would be to use the numpy array maths extension to convert your array of arrays into a numpy 2D array and get the standard deviation directly:

>>> x = [ [ 1, 2, 4, 3, 4, 5 ], [ 3, 4, 5, 6, 7, 8 ] ] * 10
>>> import numpy
>>> a = numpy.array(x)
>>> a.std(axis=0) 
array([ 1. ,  1. ,  0.5,  1.5,  1.5,  1.5])
>>> a.mean(axis=0)
array([ 2. ,  3. ,  4.5,  4.5,  5.5,  6.5])

If that's not an option and you need a pure Python solution, keep reading...

If your array is

x = [ 
      [ 1, 2, 4, 3, 4, 5 ],
      [ 3, 4, 5, 6, 7, 8 ],
      ....
]

Then the standard deviation is:

d = len(x[0])
n = len(x)
sum_x = [ sum(v[i] for v in x) for i in range(d) ]
sum_x2 = [ sum(v[i]**2 for v in x) for i in range(d) ]
std_dev = [ sqrt((sx2 - sx**2)/N)  for sx, sx2 in zip(sum_x, sum_x2) ]

If you are determined to loop through your array only once, the running sums can be combined.

sum_x  = [ 0 ] * d
sum_x2 = [ 0 ] * d
for v in x:
   for i, t in enumerate(v):
   sum_x[i] += t
   sum_x2[i] += t**2

This isn't nearly as elegant as the list comprehension solution above.

How to pass a parameter to routerLink that is somewhere inside the URL?

In your particular example you'd do the following routerLink:

[routerLink]="['user', user.id, 'details']"

To do so in a controller, you can inject Router and use:

router.navigate(['user', user.id, 'details']);

More info in the Angular docs Link Parameters Array section of Routing & Navigation

How to save all files from source code of a web site?

In Chrome, go to options (Customize and Control, the 3 dots/bars at top right) ---> More Tools ---> save page as

save page as  
filename     : any_name.html 
save as type : webpage complete.

Then you will get any_name.html and any_name folder.

Python JSON serialize a Decimal object

For Django users:

Recently came across TypeError: Decimal('2337.00') is not JSON serializable while JSON encoding i.e. json.dumps(data)

Solution:

# converts Decimal, Datetime, UUIDs to str for Encoding
from django.core.serializers.json import DjangoJSONEncoder  

json.dumps(response.data, cls=DjangoJSONEncoder)

But, now the Decimal value will be a string, now we can explicitly set the decimal/float value parser when decoding data, using parse_float option in json.loads:

import decimal 

data = json.loads(data, parse_float=decimal.Decimal) # default is float(num_str)

AngularJS UI Router - change url without reloading state

I don't think you need ui-router at all for this. The documentation available for the $location service says in the first paragraph, "...changes to $location are reflected into the browser address bar." It continues on later to say, "What does it not do? It does not cause a full page reload when the browser URL is changed."

So, with that in mind, why not simply change the $location.path (as the method is both a getter and setter) with something like the following:

var newPath = IdFromService;
$location.path(newPath);

The documentation notes that the path should always begin with a forward slash, but this will add it if it's missing.

How do I find out my python path using python?

PYTHONPATH is an environment variable whose value is a list of directories. Once set, it is used by Python to search for imported modules, along with other std. and 3rd-party library directories listed in Python's "sys.path".

As any other environment variables, you can either export it in shell or in ~/.bashrc, see here. You can query os.environ['PYTHONPATH'] for its value in Python as shown below:

$ python3 -c "import os, sys; print(os.environ['PYTHONPATH']); print(sys.path) if 'PYTHONPATH' in sorted(os.environ) else print('PYTHONPATH is not defined')"

IF defined in shell as

$ export PYTHONPATH=$HOME/Documents/DjangoTutorial/mysite

THEN result =>

/home/Documents/DjangoTutorial/mysite
['', '/home/Documents/DjangoTutorial/mysite', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages']

ELSE result =>

PYTHONPATH is not defined

To set PYTHONPATH to multiple paths, see here.

Note that one can add or delete a search path via sys.path.insert(), del or remove() at run-time, but NOT through os.environ[]. Example:

>>> os.environ['PYTHONPATH']="$HOME/Documents/DjangoTutorial/mysite"
>>> 'PYTHONPATH' in sorted(os.environ)
True
>>> sys.path // but Not there
['', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages']

>>> sys.path.insert(0,os.environ['PYTHONPATH'])
>>> sys.path // It's there
['$HOME/Documents/DjangoTutorial/mysite', '', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages']
>>> 

In summary, PYTHONPATH is one way of specifying the Python search path(s) for imported modules in sys.path. You can also apply list operations directly to sys.path without the aid of PYTHONPATH.

DataTable: Hide the Show Entries dropdown but keep the Search box

To hide "show entries" but still have pagination. I used the code below and it worked.

"bPaginate": true,
"bLengthChange": false,
"bFilter": true,
"bInfo": false,
"bAutoWidth": false

How can I Convert HTML to Text in C#?

What you are looking for is a text-mode DOM renderer that outputs text, much like Lynx or other Text browsers...This is much harder to do than you would expect.

Combining multiple condition in single case statement in Sql Server

select ROUND(CASE 

WHEN  CONVERT( float, REPLACE( isnull( value1,''),',',''))='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))='' then  CONVERT( float, REPLACE( isnull( value3,''),',',''))

WHEN  CONVERT( float, REPLACE( isnull( value1,''),',',''))='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))!='' then  CONVERT( float, REPLACE( isnull( value3,''),',',''))

WHEN  CONVERT( float, REPLACE( isnull( value1,''),',',''))!='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))='' then  CONVERT( float, REPLACE( isnull( value3,''),',',''))

else CONVERT( float, REPLACE(isnull( value1,''),',','')) end,0)  from Tablename where    ID="123" 

Convert float to string with precision & number of decimal digits specified?

Another option is snprintf:

double pi = 3.1415926;

std::string s(16, '\0');
auto written = std::snprintf(&s[0], s.size(), "%.2f", pi);
s.resize(written);

Demo. Error handling should be added, i.e. checking for written < 0.

Why does modulus division (%) only work with integers?

Because the normal mathematical notion of "remainder" is only applicable to integer division. i.e. division that is required to generate integer quotient.

In order to extend the concept of "remainder" to real numbers you have to introduce a new kind of "hybrid" operation that would generate integer quotient for real operands. Core C language does not support such operation, but it is provided as a standard library fmod function, as well as remainder function in C99. (Note that these functions are not the same and have some peculiarities. In particular, they do not follow the rounding rules of integer division.)

How do I add PHP code/file to HTML(.html) files?

You can't run PHP in .html files because the server does not recognize that as a valid PHP extension unless you tell it to. To do this you need to create a .htaccess file in your root web directory and add this line to it:

AddType application/x-httpd-php .htm .html

This will tell Apache to process files with a .htm or .html file extension as PHP files.

Using IQueryable with Linq

In essence its job is very similar to IEnumerable<T> - to represent a queryable data source - the difference being that the various LINQ methods (on Queryable) can be more specific, to build the query using Expression trees rather than delegates (which is what Enumerable uses).

The expression trees can be inspected by your chosen LINQ provider and turned into an actual query - although that is a black art in itself.

This is really down to the ElementType, Expression and Provider - but in reality you rarely need to care about this as a user. Only a LINQ implementer needs to know the gory details.


Re comments; I'm not quite sure what you want by way of example, but consider LINQ-to-SQL; the central object here is a DataContext, which represents our database-wrapper. This typically has a property per table (for example, Customers), and a table implements IQueryable<Customer>. But we don't use that much directly; consider:

using(var ctx = new MyDataContext()) {
    var qry = from cust in ctx.Customers
              where cust.Region == "North"
              select new { cust.Id, cust.Name };
    foreach(var row in qry) {
        Console.WriteLine("{0}: {1}", row.Id, row.Name);
    }
}

this becomes (by the C# compiler):

var qry = ctx.Customers.Where(cust => cust.Region == "North")
                .Select(cust => new { cust.Id, cust.Name });

which is again interpreted (by the C# compiler) as:

var qry = Queryable.Select(
              Queryable.Where(
                  ctx.Customers,
                  cust => cust.Region == "North"),
              cust => new { cust.Id, cust.Name });

Importantly, the static methods on Queryable take expression trees, which - rather than regular IL, get compiled to an object model. For example - just looking at the "Where", this gives us something comparable to:

var cust = Expression.Parameter(typeof(Customer), "cust");
var lambda = Expression.Lambda<Func<Customer,bool>>(
                  Expression.Equal(
                      Expression.Property(cust, "Region"),
                      Expression.Constant("North")
                  ), cust);

... Queryable.Where(ctx.Customers, lambda) ...

Didn't the compiler do a lot for us? This object model can be torn apart, inspected for what it means, and put back together again by the TSQL generator - giving something like:

 SELECT c.Id, c.Name
 FROM [dbo].[Customer] c
 WHERE c.Region = 'North'

(the string might end up as a parameter; I can't remember)

None of this would be possible if we had just used a delegate. And this is the point of Queryable / IQueryable<T>: it provides the entry-point for using expression trees.

All this is very complex, so it is a good job that the compiler makes it nice and easy for us.

For more information, look at "C# in Depth" or "LINQ in Action", both of which provide coverage of these topics.

Time complexity of Euclid's Algorithm

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

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

It is not O(a%b).

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

jquery change div text

best and simple way is to put title inside a span and replace then.

'<div id="'+div_id+'" class="widget" style="height:60px;width:110px">\n\
        <div class="widget-head ui-widget-header" 
                style="cursor:move;height:20px;width:130px">'+
     '<span id="'+span_id+'" style="float:right; cursor:pointer" 
            class="dialog_link ui-icon ui-icon-newwin ui-icon-pencil"></span>' +
      '<span id="spTitle">'+
      dialog_title+ '</span>'
 '</div></div>

now you can simply use this:

$('#'+div_id+' .widget-head sp#spTitle').text("new dialog title");

Flutter - Layout a Grid

Please visit this repo.

Widget _gridView() {
    return GridView.count(
      crossAxisCount: 4,
      padding: EdgeInsets.all(4.0),
      childAspectRatio: 8.0 / 9.0,
      children: itemList
          .map(
            (Item) => ItemList(item: Item),
          )
          .toList(),
    );
  }

Below screenshot contains crossAxisCount: 2 this screenshot is for grid count 2

Error: unexpected symbol/input/string constant/numeric constant/SPECIAL in my code

For me the error was:

Error: unexpected input in "?"

and the fix was opening the script in a hex editor and removing the first 3 characters from the file. The file was starting with an UTF-8 BOM and it seems that Rscript can't read that.

EDIT: OP requested an example. Here it goes.

?  ~ cat a.R
cat('hello world\n')
?  ~ xxd a.R
00000000: efbb bf63 6174 2827 6865 6c6c 6f20 776f  ...cat('hello wo
00000010: 726c 645c 6e27 290a                      rld\n').
?  ~ R -f a.R        

R version 3.4.4 (2018-03-15) -- "Someone to Lean On"
Copyright (C) 2018 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

  Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

> cat('hello world\n')
Error: unexpected input in "?"
Execution halted

How to instantiate a File object in JavaScript?

Now you can!

_x000D_
_x000D_
var parts = [_x000D_
  new Blob(['you construct a file...'], {type: 'text/plain'}),_x000D_
  ' Same way as you do with blob',_x000D_
  new Uint16Array([33])_x000D_
];_x000D_
_x000D_
// Construct a file_x000D_
var file = new File(parts, 'sample.txt', {_x000D_
    lastModified: new Date(0), // optional - default = now_x000D_
    type: "overide/mimetype" // optional - default = ''_x000D_
});_x000D_
_x000D_
var fr = new FileReader();_x000D_
_x000D_
fr.onload = function(evt){_x000D_
   document.body.innerHTML = evt.target.result + "<br><a href="+URL.createObjectURL(file)+" download=" + file.name + ">Download " + file.name + "</a><br>type: "+file.type+"<br>last modified: "+ file.lastModifiedDate_x000D_
}_x000D_
_x000D_
fr.readAsText(file);
_x000D_
_x000D_
_x000D_

ToList()-- does it create a new list?

The accepted answer correctly addresses the OP's question based on his example. However, it only applies when ToList is applied to a concrete collection; it does not hold when the elements of the source sequence have yet to be instantiated (due to deferred execution). In case of the latter, you might get a new set of items each time you call ToList (or enumerate the sequence).

Here is an adaptation of the OP's code to demonstrate this behaviour:

public static void RunChangeList()
{
    var objs = Enumerable.Range(0, 10).Select(_ => new MyObject() { SimpleInt = 0 });
    var whatInt = ChangeToList(objs);   // whatInt gets 0
}

public static int ChangeToList(IEnumerable<MyObject> objects)
{
    var objectList = objects.ToList();
    objectList.First().SimpleInt = 5;
    return objects.First().SimpleInt;
}

Whilst the above code may appear contrived, this behaviour can appear as a subtle bug in other scenarios. See my other example for a situation where it causes tasks to get spawned repeatedly.

send checkbox value in PHP form

if(isset($_POST["newsletter"]) && $_POST["newsletter"] == "newsletter"){
    //checked
}

How to use WPF Background Worker

I found this (WPF Multithreading: Using the BackgroundWorker and Reporting the Progress to the UI. link) to contain the rest of the details which are missing from @Andrew's answer.

The one thing I found very useful was that the worker thread couldn't access the MainWindow's controls (in it's own method), however when using a delegate inside the main windows event handler it was possible.

worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
{
    pd.Close();
    // Get a result from the asynchronous worker
    T t = (t)args.Result
    this.ExampleControl.Text = t.BlaBla;
};

How to load GIF image in Swift?

//
//  iOSDevCenters+GIF.swift
//  GIF-Swift
//
//  Created by iOSDevCenters on 11/12/15.
//  Copyright © 2016 iOSDevCenters. All rights reserved.
//
import UIKit
import ImageIO


extension UIImage {

public class func gifImageWithData(data: NSData) -> UIImage? {
    guard let source = CGImageSourceCreateWithData(data, nil) else {
        print("image doesn't exist")
        return nil
    }

    return UIImage.animatedImageWithSource(source: source)
}

public class func gifImageWithURL(gifUrl:String) -> UIImage? {
    guard let bundleURL = NSURL(string: gifUrl)
        else {
            print("image named \"\(gifUrl)\" doesn't exist")
            return nil
    }
    guard let imageData = NSData(contentsOf: bundleURL as URL) else {
        print("image named \"\(gifUrl)\" into NSData")
        return nil
    }

    return gifImageWithData(data: imageData)
}

public class func gifImageWithName(name: String) -> UIImage? {
    guard let bundleURL = Bundle.main
        .url(forResource: name, withExtension: "gif") else {
            print("SwiftGif: This image named \"\(name)\" does not exist")
            return nil
    }

    guard let imageData = NSData(contentsOf: bundleURL) else {
        print("SwiftGif: Cannot turn image named \"\(name)\" into NSData")
        return nil
    }

    return gifImageWithData(data: imageData)
}

class func delayForImageAtIndex(index: Int, source: CGImageSource!) -> Double {
    var delay = 0.1

    let cfProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil)
    let gifProperties: CFDictionary = unsafeBitCast(CFDictionaryGetValue(cfProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDictionary).toOpaque()), to: CFDictionary.self)

    var delayObject: AnyObject = unsafeBitCast(CFDictionaryGetValue(gifProperties, Unmanaged.passUnretained(kCGImagePropertyGIFUnclampedDelayTime).toOpaque()), to: AnyObject.self)

    if delayObject.doubleValue == 0 {
        delayObject = unsafeBitCast(CFDictionaryGetValue(gifProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDelayTime).toOpaque()), to: AnyObject.self)
    }

    delay = delayObject as! Double

    if delay < 0.1 {
        delay = 0.1
    }

    return delay
}

class func gcdForPair(a: Int?, _ b: Int?) -> Int {
    var a = a
    var b = b
    if b == nil || a == nil {
        if b != nil {
            return b!
        } else if a != nil {
            return a!
        } else {
            return 0
        }
    }

    if a! < b! {
        let c = a!
        a = b!
        b = c
    }

    var rest: Int
    while true {
        rest = a! % b!

        if rest == 0 {
            return b!
        } else {
            a = b!
            b = rest
        }
    }
}

class func gcdForArray(array: Array<Int>) -> Int {
    if array.isEmpty {
        return 1
    }

    var gcd = array[0]

    for val in array {
        gcd = UIImage.gcdForPair(a: val, gcd)
    }

    return gcd
}

class func animatedImageWithSource(source: CGImageSource) -> UIImage? {
    let count = CGImageSourceGetCount(source)
    var images = [CGImage]()
    var delays = [Int]()

    for i in 0..<count {
        if let image = CGImageSourceCreateImageAtIndex(source, i, nil) {
            images.append(image)
        }

        let delaySeconds = UIImage.delayForImageAtIndex(index: Int(i), source: source)
        delays.append(Int(delaySeconds * 1000.0)) // Seconds to ms
    }

    let duration: Int = {
        var sum = 0

        for val: Int in delays {
            sum += val
        }

        return sum
    }()

    let gcd = gcdForArray(array: delays)
    var frames = [UIImage]()

    var frame: UIImage
    var frameCount: Int
    for i in 0..<count {
        frame = UIImage(cgImage: images[Int(i)])
        frameCount = Int(delays[Int(i)] / gcd)

        for _ in 0..<frameCount {
            frames.append(frame)
        }
    }

    let animation = UIImage.animatedImage(with: frames, duration: Double(duration) / 1000.0)

    return animation
}
}

Here is the file updated for Swift 3

.NET Core vs Mono

This is no more .NET Core vs. Mono. It's unified.

Update as of November 2020 - .NET 5 released that unifies .NET Framework and .NET Core

.NET and Mono will be unified under .NET 6 that would be released in November 2021

  • .NET 6.0 will add net6.0-ios and net6.0-android.
  • The OS-specific names can include OS version numbers, like net6.0-ios14.

Check below articles:

javascript clear field value input

do like

<input name="name" id="name" type="text" value="Name" 
   onblur="fillField(this,'Name');" onfocus="clearField(this,'Name');"/>

and js

function fillField(input,val) {
      if(input.value == "")
         input.value=val;
};

function clearField(input,val) {
      if(input.value == val)
         input.value="";
};

update

here is a demo fiddle of the same

Query an object array using linq

Add:

using System.Linq;

to the top of your file.

And then:

Car[] carList = ...
var carMake = 
    from item in carList
    where item.Model == "bmw" 
    select item.Make;

or if you prefer the fluent syntax:

var carMake = carList
    .Where(item => item.Model == "bmw")
    .Select(item => item.Make);

Things to pay attention to:

  • The usage of item.Make in the select clause instead if s.Make as in your code.
  • You have a whitespace between item and .Model in your where clause

Python Script execute commands in Terminal

You should also look into commands.getstatusoutput

This returns a tuple of length 2.. The first is the return integer ( 0 - when the commands is successful ) second is the whole output as will be shown in the terminal.

For ls

    import commands
    s=commands.getstatusoutput('ls')
    print s
    >> (0, 'file_1\nfile_2\nfile_3')
    s[1].split("\n")
    >> ['file_1', 'file_2', 'file_3']

How do I lock the orientation to portrait mode in a iPhone Web Application?

The following code was used in our html5 game.

$(document).ready(function () {
     $(window)    
          .bind('orientationchange', function(){
               if (window.orientation % 180 == 0){
                   $(document.body).css("-webkit-transform-origin", "")
                       .css("-webkit-transform", "");               
               } 
               else {                   
                   if ( window.orientation > 0) { //clockwise
                     $(document.body).css("-webkit-transform-origin", "200px 190px")
                       .css("-webkit-transform",  "rotate(-90deg)");  
                   }
                   else {
                     $(document.body).css("-webkit-transform-origin", "280px 190px")
                       .css("-webkit-transform",  "rotate(90deg)"); 
                   }
               }
           })
          .trigger('orientationchange'); 
});

PHP Redirect with POST data

$_SESSION is your friend if you don't want to mess with Javascript

Let's say you're trying to pass an email:

On page A:

// Start the session
session_start();

// Set session variables
$_SESSION["email"] = "[email protected]";

header('Location: page_b.php');

And on Page B:

// Start the session
session_start();

// Show me the session!  
echo "<pre>";
print_r($_SESSION);
echo "</pre>";

To destroy the session

unset($_SESSION['email']);
session_destroy();

How can I display just a portion of an image in HTML/CSS?

Another alternative is the following, although not the cleanest as it assumes the image to be the only element in a container, such as in this case:

<header class="siteHeader">
  <img src="img" class="siteLogo" />
</header>

You can then use the container as a mask with the desired size, and surround the image with a negative margin to move it into the right position:

.siteHeader{
    width: 50px;
    height: 50px;
    overflow: hidden;
}

.siteHeader .siteLogo{
    margin: -100px;
}

Demo can be seen in this JSFiddle.

Only seems to work in IE>9, and probably all significant versions of all other browsers.

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

Right click on your service reference and choose Configure Service Reference...

Configure Service Reference

Then uncheck Reuse types in referenced assemblies

Reuse Types

Click OK, clean and rebuild your solution.

How can I get the latest JRE / JDK as a zip file rather than EXE or MSI installer?

This link

http://www.java.com/en/download/manual.jsp

helps you at least avoid the obnoxious preload installer getting straight to the SDK.

From there, I would install this in a throw-away VM, on your old crufty PC or elsewhere, then transfer the resulting

C:\Program Files (x86)\Java\jre7

(or similar) to your new machine, set the very few usual ENV variables, and there you ideally go, w/o all the marketing junk and potential tie-ins. Of course, also w/o the security from frequent automatic updates.

What is the purpose of the var keyword and when should I use it (or omit it)?

Inside a code you if you use a variable without using var, then what happens is the automatically var var_name is placed in the global scope eg:

someFunction() {
    var a = some_value; /*a has local scope and it cannot be accessed when this
    function is not active*/
    b = a; /*here it places "var b" at top of script i.e. gives b global scope or
    uses already defined global variable b */
}

Create a button with rounded border

new OutlineButton(  
 child: new Text("blue outline") ,
   borderSide: BorderSide(color: Colors.blue),
  ),

// this property adds outline border color

error: unknown type name ‘bool’

C99 does, if you have

#include <stdbool.h> 

If the compiler does not support C99, you can define it yourself:

// file : myboolean.h
#ifndef MYBOOLEAN_H
#define MYBOOLEAN_H

#define false 0
#define true 1
typedef int bool; // or #define bool int

#endif

(but note that this definition changes ABI for bool type so linking against external libraries which were compiled with properly defined bool may cause hard-to-diagnose runtime errors).

How can I specify working directory for popen

subprocess.Popen takes a cwd argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'), or use r'd:\test\local' so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t part will be translated to a tab.

So, your new line should look like:

subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')

To use your Python script path as cwd, import os and define cwd using this:

os.path.dirname(os.path.realpath(__file__)) 

How to use order by with union all in sql?

select CONCAT(Name, '(',substr(occupation, 1, 1), ')') AS f1
from OCCUPATIONS
union
select temp.str AS f1 from 
(select count(occupation) AS counts, occupation, concat('There are a total of ' ,count(occupation) ,' ', lower(occupation),'s.') As str  from OCCUPATIONS group by occupation order by counts ASC, occupation ASC
 ) As temp
 order by f1

web-api POST body object always null

In my case (.NET Core 3.0) I had to configure JSON serialization to resolve camelCase properties using AddNewtonsoftJson():

services.AddMvc(options =>
{
    // (Irrelevant for the answer)
})
.AddNewtonsoftJson(options =>
{
    options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});

Do this in your Startup / Dependency Injection setup.

Git pull till a particular commit

This works for me:

git pull origin <sha>

e.g.

[dbn src]$ git fetch
[dbn src]$ git status
On branch current_feature
Your branch and 'origin/master' have diverged,
and have 2 and 7 different commits each, respectively.
...
[dbn src]$ git log -3 --pretty=oneline origin/master
f4d10ad2a5eda447bea53fed0b421106dbecea66 CASE-ID1: some descriptive msg
28eb00a42e682e32bdc92e5753a4a9c315f62b42 CASE-ID2: I'm so good at writing commit titles
ff39e46b18a66b21bc1eed81a0974e5c7de6a3e5 CASE-ID2: woooooo
[dbn src]$ git pull origin 28eb00a42e682e32bdc92e5753a4a9c315f62b42
[dbn src]$ git status
On branch current_feature
Your branch and 'origin/master' have diverged,
and have 2 and 1 different commits each, respectively.
...

This pulls 28eb00, ff39e4, and everything before, but doesn't pull f4d10ad. It allows the use of pull --rebase, and honors pull settings in your gitconfig. This works because you're basically treating 28eb00 as a branch.

For the version of git that I'm using, this method requires a full commit hash - no abbreviations or aliases are allowed. You could do something like:

[dbn src]$ git pull origin `git rev-parse origin/master^`

python pandas: Remove duplicates by columns A, keeping the row with the highest value in column B

The top answer is doing too much work and looks to be very slow for larger data sets. apply is slow and should be avoided if possible. ix is deprecated and should be avoided as well.

df.sort_values('B', ascending=False).drop_duplicates('A').sort_index()

   A   B
1  1  20
3  2  40
4  3  10

Or simply group by all the other columns and take the max of the column you need. df.groupby('A', as_index=False).max()

How can I save a base64-encoded image to disk?

I think you are converting the data a bit more than you need to. Once you create the buffer with the proper encoding, you just need to write the buffer to the file.

var base64Data = req.rawBody.replace(/^data:image\/png;base64,/, "");

require("fs").writeFile("out.png", base64Data, 'base64', function(err) {
  console.log(err);
});

new Buffer(..., 'base64') will convert the input string to a Buffer, which is just an array of bytes, by interpreting the input as a base64 encoded string. Then you can just write that byte array to the file.

Update

As mentioned in the comments, req.rawBody is no longer a thing. If you are using express/connect then you should use the bodyParser() middleware and use req.body, and if you are doing this using standard Node then you need to aggregate the incoming data event Buffer objects and do this image data parsing in the end callback.

How to get my activity context?

You can use Application class(public class in android.application package),that is:

Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's tag, which will cause that class to be instantiated for you when the process for your application/package is created.

To use this class do:

public class App extends Application {

    private static Context mContext;

    public static Context getContext() {
        return mContext;
    }

    public static void setContext(Context mContext) {
        this.mContext = mContext;
    }

    ...

}

In your manifest:

<application
        android:icon="..."
        android:label="..."
        android:name="com.example.yourmainpackagename.App" >
                       class that extends Application ^^^

In Activity B:

public class B extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sampleactivitylayout);

        App.setContext(this);
                  ...
        }
...
}

In class A:

Context c = App.getContext();

Note:

There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.

How do I set the selenium webdriver get timeout?

try

driver.executeScript("window.location.href='http://www.sina.com.cn'")

this statement will return immediately.

And after that , you can add a WebDriverWait with timeout to check if the page title or any element is ok.

Hope this will help you.

Getting "type or namespace name could not be found" but everything seems ok?

I was working on VS 2017 community edition and had the same issue with CefSharp nuget packages.

Packages were downloaded and restored successfully, project could be built and run successfully - only the markup indicated that the namespaces were not recognized.

All I had to do was to open the References section and click on one of the yellow exclamation signs.

enter image description here

After a few seconds the markup errors went away.

enter image description here

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

If you changed my.ini and restarted mysql and you still get this error please check your file path and replace "\" to "/". I solved my proplem after replacing.

How to center and crop an image to always appear in square shape with CSS?

With the caveat of it not working in IE and some older mobile browsers, a simple object-fit: cover; is often the best option.

.cropper {
  position: relative;
  width: 100px;
  height: 100px;
  overflow: hidden;
}
.cropper img {
  position: absolute;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

Without the object-fit: cover support, the image will be stretched oddly to fit the box so, if support for IE is needed, I'd recommend using one of the other answers' approach with -100% top, left, right and bottom values as a fallback.

http://caniuse.com/#feat=object-fit

Remove characters from a String in Java

Can't you use

id = id.substring(0, id.length()-4);

And what Eric said, ofcourse.

How does the 'binding' attribute work in JSF? When and how should it be used?

How does it work?

When a JSF view (Facelets/JSP file) get built/restored, a JSF component tree will be produced. At that moment, the view build time, all binding attributes are evaluated (along with id attribtues and taghandlers like JSTL). When the JSF component needs to be created before being added to the component tree, JSF will check if the binding attribute returns a precreated component (i.e. non-null) and if so, then use it. If it's not precreated, then JSF will autocreate the component "the usual way" and invoke the setter behind binding attribute with the autocreated component instance as argument.

In effects, it binds a reference of the component instance in the component tree to a scoped variable. This information is in no way visible in the generated HTML representation of the component itself. This information is in no means relevant to the generated HTML output anyway. When the form is submitted and the view is restored, the JSF component tree is just rebuilt from scratch and all binding attributes will just be re-evaluated like described in above paragraph. After the component tree is recreated, JSF will restore the JSF view state into the component tree.

Component instances are request scoped!

Important to know and understand is that the concrete component instances are effectively request scoped. They're newly created on every request and their properties are filled with values from JSF view state during restore view phase. So, if you bind the component to a property of a backing bean, then the backing bean should absolutely not be in a broader scope than the request scope. See also JSF 2.0 specitication chapter 3.1.5:

3.1.5 Component Bindings

...

Component bindings are often used in conjunction with JavaBeans that are dynamically instantiated via the Managed Bean Creation facility (see Section 5.8.1 “VariableResolver and the Default VariableResolver”). It is strongly recommend that application developers place managed beans that are pointed at by component binding expressions in “request” scope. This is because placing it in session or application scope would require thread-safety, since UIComponent instances depends on running inside of a single thread. There are also potentially negative impacts on memory management when placing a component binding in “session” scope.

Otherwise, component instances are shared among multiple requests, possibly resulting in "duplicate component ID" errors and "weird" behaviors because validators, converters and listeners declared in the view are re-attached to the existing component instance from previous request(s). The symptoms are clear: they are executed multiple times, one time more with each request within the same scope as the component is been bound to.

And, under heavy load (i.e. when multiple different HTTP requests (threads) access and manipulate the very same component instance at the same time), you may face sooner or later an application crash with e.g. Stuck thread at UIComponent.popComponentFromEL, or Java Threads at 100% CPU utilization using richfaces UIDataAdaptorBase and its internal HashMap, or even some "strange" IndexOutOfBoundsException or ConcurrentModificationException coming straight from JSF implementation source code while JSF is busy saving or restoring the view state (i.e. the stack trace indicates saveState() or restoreState() methods and like).

Using binding on a bean property is bad practice

Regardless, using binding this way, binding a whole component instance to a bean property, even on a request scoped bean, is in JSF 2.x a rather rare use case and generally not the best practice. It indicates a design smell. You normally declare components in the view side and bind their runtime attributes like value, and perhaps others like styleClass, disabled, rendered, etc, to normal bean properties. Then, you just manipulate exactly that bean property you want instead of grabbing the whole component and calling the setter method associated with the attribute.

In cases when a component needs to be "dynamically built" based on a static model, better is to use view build time tags like JSTL, if necessary in a tag file, instead of createComponent(), new SomeComponent(), getChildren().add() and what not. See also How to refactor snippet of old JSP to some JSF equivalent?

Or, if a component needs to be "dynamically rendered" based on a dynamic model, then just use an iterator component (<ui:repeat>, <h:dataTable>, etc). See also How to dynamically add JSF components.

Composite components is a completely different story. It's completely legit to bind components inside a <cc:implementation> to the backing component (i.e. the component identified by <cc:interface componentType>. See also a.o. Split java.util.Date over two h:inputText fields representing hour and minute with f:convertDateTime and How to implement a dynamic list with a JSF 2.0 Composite Component?

Only use binding in local scope

However, sometimes you'd like to know about the state of a different component from inside a particular component, more than often in use cases related to action/value dependent validation. For that, the binding attribute can be used, but not in combination with a bean property. You can just specify an in the local EL scope unique variable name in the binding attribute like so binding="#{foo}" and the component is during render response elsewhere in the same view directly as UIComponent reference available by #{foo}. Here are several related questions where such a solution is been used in the answer:

See also:

Task<> does not contain a definition for 'GetAwaiter'

I had this problem because I was calling a method

await myClass.myStaticMethod(myString);

but I was setting myString with

var myString = String.Format({some dynamic-type values})

which resulted in a dynamic type, not a string, thus when I tried to await on myClass.myStaticMethod(myString), the compiler thought I meant to call myClass.myStaticMethod(dynamic myString). This compiled fine because, again, in a dynamic context, it's all good until it blows up at run-time, which is what happened because there is no implementation of the dynamic version of myStaticMethod, and this error message didn't help whatsoever, and the fact that Intellisense would take me to the correct definition didn't help either.
Tricky!

However, by forcing the result type to string, like:

var myString = String.Format({some dynamic-type values})

to

string myString = String.Format({some dynamic-type values})

my call to myStaticMethod routed properly

Define static method in source-file with declaration in header-file in C++

Probably the best course of action is "do it as std lib does it". That is: All inline, all in headers.

// in the header
namespase my_namespace {

   class my_standard_named_class final {
public:
         static void standard_declared_defined_method () {
            // even the comment is standard
         }
   } ;

} // namespase my_namespace 

As simple as that ...

How can I remove a child node in HTML using JavaScript?

A jQuery solution

HTML

<select id="foo">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

Javascript

// remove child "option" element with a "value" attribute equal to "2"
$("#foo > option[value='2']").remove();

// remove all child "option" elements
$("#foo > option").remove();

References:

Attribute Equals Selector [name=value]

Selects elements that have the specified attribute with a value exactly equal to a certain value.

Child Selector (“parent > child”)

Selects all direct child elements specified by "child" of elements specified by "parent"

.remove()

Similar to .empty(), the .remove() method takes elements out of the DOM. We use .remove() when we want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

Create Elasticsearch curl query for not null and not empty("")

On elasticsearch 5.6, I have to use command below to filter out empty string:

    GET /_search
    {
        "query" : {
            "regexp":{
                "<your_field_name_here>": ".+"
            }
        }
    }  

Assert a function/method was not called using Mock

You can check the called attribute, but if your assertion fails, the next thing you'll want to know is something about the unexpected call, so you may as well arrange for that information to be displayed from the start. Using unittest, you can check the contents of call_args_list instead:

self.assertItemsEqual(my_var.call_args_list, [])

When it fails, it gives a message like this:

AssertionError: Element counts were not equal:
First has 0, Second has 1:  call('first argument', 4)

Count all occurrences of a string in lots of files with grep

Instead of using -c, just pipe it to wc -l.

grep string * | wc -l

This will list each occurrence on a single line and then count the number of lines.

This will miss instances where the string occurs 2+ times on one line, though.

Does PHP have threading?

I know this is a way old question, but you could look at http://phpthreadlib.sourceforge.net/

Bi-directional communication, support for Win32, and no extensions required.

How to identify which columns are not "NA" per row in a matrix?

Try:

which( !is.na(p), arr.ind=TRUE)

Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:

> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3

[[2]]
[1] 4 7

[[3]]
integer(0)

[[4]]
[1] 5

[[5]]
integer(0)

Or even with smushing together with paste:

lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")

The output from which function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:

> which( !is.na(p), arr.ind=TRUE)
     row col
[1,]   1   2
[2,]   1   3
[3,]   2   4
[4,]   4   5
[5,]   2   7

Without the arr.ind parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".

> which( !is.na(p) )
[1]  6 11 17 24 32

How do you load custom UITableViewCells from Xib files?

Here is my method for that: Loading Custom UITableViewCells from XIB Files… Yet Another Method

The idea is to create a SampleCell subclass of the UITableViewCell with a IBOutlet UIView *content property and a property for each custom subview you need to configure from the code. Then to create a SampleCell.xib file. In this nib file, change the file owner to SampleCell. Add a content UIView sized to fit your needs. Add and configure all the subviews (label, image views, buttons, etc) you want. Finally, link the content view and the subviews to the file owner.

Python's equivalent of && (logical-and) in an if-statement

maybe with & instead % is more fast and mantain readibility

other tests even/odd

x is even ? x % 2 == 0

x is odd ? not x % 2 == 0

maybe is more clear with bitwise and 1

x is odd ? x & 1

x is even ? not x & 1 (not odd)

def front_back(a, b):
    # +++your code here+++
    if not len(a) & 1 and not len(b) & 1:
        return a[:(len(a)/2)] + b[:(len(b)/2)] + a[(len(a)/2):] + b[(len(b)/2):] 
    else:
        #todo! Not yet done. :P
    return

Multiple input in JOptionPane.showInputDialog

this is my solution

JTextField username = new JTextField();
JTextField password = new JPasswordField();
Object[] message = {
    "Username:", username,
    "Password:", password
};

int option = JOptionPane.showConfirmDialog(null, message, "Login", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
    if (username.getText().equals("h") && password.getText().equals("h")) {
        System.out.println("Login successful");
    } else {
        System.out.println("login failed");
    }
} else {
    System.out.println("Login canceled");
}

Android : Check whether the phone is dual SIM

I have a Samsung Duos device with Android 4.4.4 and the method suggested by Seetha in the accepted answer (i.e. call getDeviceIdDs) does not work for me, as the method does not exist. I was able to recover all the information I needed by calling method "getDefault(int slotID)", as shown below:

public static void samsungTwoSims(Context context) {
    TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

    try{

        Class<?> telephonyClass = Class.forName(telephony.getClass().getName());

        Class<?>[] parameter = new Class[1];
        parameter[0] = int.class;
        Method getFirstMethod = telephonyClass.getMethod("getDefault", parameter);

        Log.d(TAG, getFirstMethod.toString());

        Object[] obParameter = new Object[1];
        obParameter[0] = 0;
        TelephonyManager first = (TelephonyManager) getFirstMethod.invoke(null, obParameter);

        Log.d(TAG, "Device Id: " + first.getDeviceId() + ", device status: " + first.getSimState() + ", operator: " + first.getNetworkOperator() + "/" + first.getNetworkOperatorName());

        obParameter[0] = 1;
        TelephonyManager second = (TelephonyManager) getFirstMethod.invoke(null, obParameter);

        Log.d(TAG, "Device Id: " + second.getDeviceId() + ", device status: " + second.getSimState()+ ", operator: " + second.getNetworkOperator() + "/" + second.getNetworkOperatorName());
    } catch (Exception e) {
        e.printStackTrace();
    }   
}

Also, I rewrote the code that iteratively tests for methods to recover this information so that it uses an array of method names instead of a sequence of try/catch. For instance, to determine if we have two active SIMs we could do:

private static String[] simStatusMethodNames = {"getSimStateGemini", "getSimState"};


public static boolean hasTwoActiveSims(Context context) {
    boolean first = false, second = false;

    for (String methodName: simStatusMethodNames) {
        // try with sim 0 first
        try {
            first = getSIMStateBySlot(context, methodName, 0);
            // no exception thrown, means method exists
            second = getSIMStateBySlot(context, methodName, 1);
           return first && second;
        } catch (GeminiMethodNotFoundException e) {
            // method does not exist, nothing to do but test the next
        }
    }
    return false;
}

This way, if a new method name is suggested for some device, you can simply add it to the array and it should work.

NodeJS: How to decode base64 encoded string back to binary?

As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:

var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da

For Node.js v5.11.1 and below

Construct a new Buffer and pass 'base64' as the second argument:

var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da

If you want to be clean, you can check whether from exists :

if (typeof Buffer.from === "function") {
    // Node 5.10+
    buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
    // older Node versions, now deprecated
    buf = new Buffer(b64string, 'base64'); // Ta-da
}

Cannot find Dumpbin.exe

Visual Studio Commmunity 2017 - dumpbin.exe became available once I installed the C++ profiling tools in Modify menu from the Visual Studio Installer.

enter image description here

How to mount host volumes into docker containers in Dockerfile during build

First, to answer "why doesn't VOLUME work?" When you define a VOLUME in the Dockerfile, you can only define the target, not the source of the volume. During the build, you will only get an anonymous volume from this. That anonymous volume will be mounted at every RUN command, prepopulated with the contents of the image, and then discarded at the end of the RUN command. Only changes to the container are saved, not changes to the volume.


Since this question has been asked, a few features have been released that may help. First is multistage builds allowing you to build a disk space inefficient first stage, and copy just the needed output to the final stage that you ship. And the second feature is Buildkit which is dramatically changing how images are built and new capabilities are being added to the build.

For a multi-stage build, you would have multiple FROM lines, each one starting the creation of a separate image. Only the last image is tagged by default, but you can copy files from previous stages. The standard use is to have a compiler environment to build a binary or other application artifact, and a runtime environment as the second stage that copies over that artifact. You could have:

FROM debian:sid as builder
COPY export /export
RUN compile command here >/result.bin

FROM debian:sid
COPY --from=builder /result.bin /result.bin
CMD ["/result.bin"]

That would result in a build that only contains the resulting binary, and not the full /export directory.


Buildkit is coming out of experimental in 18.09. It's a complete redesign of the build process, including the ability to change the frontend parser. One of those parser changes has has implemented the RUN --mount option which lets you mount a cache directory for your run commands. E.g. here's one that mounts some of the debian directories (with a reconfigure of the debian image, this could speed up reinstalls of packages):

# syntax = docker/dockerfile:experimental
FROM debian:latest
RUN --mount=target=/var/lib/apt/lists,type=cache \
    --mount=target=/var/cache/apt,type=cache \
    apt-get update \
 && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
      git

You would adjust the cache directory for whatever application cache you have, e.g. $HOME/.m2 for maven, or /root/.cache for golang.


TL;DR: Answer is here: With that RUN --mount syntax, you can also bind mount read-only directories from the build-context. The folder must exist in the build context, and it is not mapped back to the host or the build client:

# syntax = docker/dockerfile:experimental
FROM debian:latest
RUN --mount=target=/export,type=bind,source=export \
    process export directory here...

Note that because the directory is mounted from the context, it's also mounted read-only, and you cannot push changes back to the host or client. When you build, you'll want an 18.09 or newer install and enable buildkit with export DOCKER_BUILDKIT=1.

If you get an error that the mount flag isn't supported, that indicates that you either didn't enable buildkit with the above variable, or that you didn't enable the experimental syntax with the syntax line at the top of the Dockerfile before any other lines, including comments. Note that the variable to toggle buildkit will only work if your docker install has buildkit support built in, which requires version 18.09 or newer from Docker, both on the client and server.

How to sort an array of associative arrays by value of a given key in PHP?

Here is a method that I found long ago and cleaned up a bit. This works great, and can be quickly changed to accept objects as well.

/**
 * A method for sorting arrays by a certain key:value.
 * SortByKey is the key you wish to sort by
 * Direction can be ASC or DESC.
 *
 * @param $array
 * @param $sortByKey
 * @param $sortDirection
 * @return array
 */
private function sortArray($array, $sortByKey, $sortDirection) {

    $sortArray = array();
    $tempArray = array();

    foreach ( $array as $key => $value ) {
        $tempArray[] = strtolower( $value[ $sortByKey ] );
    }

    if($sortDirection=='ASC'){ asort($tempArray ); }
        else{ arsort($tempArray ); }

    foreach ( $tempArray as $key => $temp ){
        $sortArray[] = $array[ $key ];
    }

    return $sortArray;

}

to change the method to sort objects simply change the following line:

$tempArray[] = strtolower( $value[ $sortByKey ] ); to $tempArray[] = strtolower( $value->$sortByKey );

To run the method simply do

sortArray($inventory,'price','ASC');

Where are the recorded macros stored in Notepad++?

Notepad++ will forget your macros unless you map them to hotkeys via Settings - Shortcut mapper - Macros before exiting Notepad++ (as per https://superuser.com/questions/332481/how-can-i-add-a-macro-in-notepad. Tested with Notepad v6.8.3 on Windows7.)

Difference between getContext() , getApplicationContext() , getBaseContext() and "this"

A Context is:

  • an abstract class whose implementation is provided by the Android system.
  • It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.

Git Stash vs Shelve in IntelliJ IDEA

When using JetBrains IDE's with Git, "stashing and unstashing actions are supported in addition to shelving and unshelving. These features have much in common; the major difference is in the way patches are generated and applied. Shelve can operate with either individual files or bunch of files, while Stash can only operate with a whole bunch of changed files at once. Here are some more details on the differences between them."

Is there a Google Keep API?

No there isn't. If you watch the http traffic and dump the page source you can see that there is an API below the covers, but it's not published nor available for 3rd party apps.

Check this link: https://developers.google.com/gsuite/products for updates.

However, there is an unofficial Python API under active development: https://github.com/kiwiz/gkeepapi

Computational complexity of Fibonacci Sequence

The proof answers are good, but I always have to do a few iterations by hand to really convince myself. So I drew out a small calling tree on my whiteboard, and started counting the nodes. I split my counts out into total nodes, leaf nodes, and interior nodes. Here's what I got:

IN | OUT | TOT | LEAF | INT
 1 |   1 |   1 |   1  |   0
 2 |   1 |   1 |   1  |   0
 3 |   2 |   3 |   2  |   1
 4 |   3 |   5 |   3  |   2
 5 |   5 |   9 |   5  |   4
 6 |   8 |  15 |   8  |   7
 7 |  13 |  25 |  13  |  12
 8 |  21 |  41 |  21  |  20
 9 |  34 |  67 |  34  |  33
10 |  55 | 109 |  55  |  54

What immediately leaps out is that the number of leaf nodes is fib(n). What took a few more iterations to notice is that the number of interior nodes is fib(n) - 1. Therefore the total number of nodes is 2 * fib(n) - 1.

Since you drop the coefficients when classifying computational complexity, the final answer is ?(fib(n)).

How to call a JavaScript function, declared in <head>, in the body when I want to call it

Just drop

<script>
myfunction();
</script>

in the body where you want it to be called, understanding that when the page loads and the browser reaches that point, that's when the call will occur.

How do I format my oracle queries so the columns don't wrap?

set linesize 3000

set wrap off

set termout off

set pagesize 0 embedded on

set trimspool on

Try with all above values.

Display text from .txt file in batch file

Ok I wonder when's the use but, here are two snipets you could use:

lastlog.cmd

@echo off
for /f "delims=" %%l in (log.txt) do set TimeStamp=%%l
echo %TimeStamp%

Change the "echo.." line, but the last log time is within %TimeStamp%. No temp files used, no clutter and reusable as it is in a variable.

On the other hand, if you need to know this WITHIN your code, and not from another batch, change your logging for:

set TimeStamp=%date%, %time%
echo %TimeStamp% >> log.txt

so that the variable %TimeStamp% is usable later when you need it.

How can I install an older version of a package via NuGet?

As of NuGet 2.8, there is a feature to downgrade a package.

NuGet 2.8 Release Notes

Example:

The following command entered into the Package Manager Console will downgrade the Couchbase client to version 1.3.1.0.

Update-Package CouchbaseNetClient -Version 1.3.1.0

Result:

Updating 'CouchbaseNetClient' from version '1.3.3' to '1.3.1.0' in project [project name].
Removing 'CouchbaseNetClient 1.3.3' from [project name].
Successfully removed 'CouchbaseNetClient 1.3.3' from [project name].

Something to note as per crimbo below:

This approach doesn't work for downgrading from one prerelease version to other prerelease version - it only works for downgrading to a release version

Map a 2D array onto a 1D array

It's important to store the data in a way that it can be retrieved in the languages used. C-language stores in row-major order (all of first row comes first, then all of second row,...) with every index running from 0 to it's dimension-1. So the order of array x[2][3] is x[0][0], x[0][1], x[0][2], x[1][0], x[1][1], x[1][2]. So in C language, x[i][j] is stored the same place as a 1-dimensional array entry x1dim[ i*3 +j]. If the data is stored that way, it is easy to retrieve in C language.

Fortran and MATLAB are different. They store in column-major order (all of first column comes first, then all of second row,...) and every index runs from 1 to it's dimension. So the index order is the reverse of C and all the indices are 1 greater. If you store the data in the C language order, FORTRAN can find X_C_language[i][j] using X_FORTRAN(j+1, i+1). For instance, X_C_language[1][2] is equal to X_FORTRAN(3,2). In 1-dimensional arrays, that data value is at X1dim_C_language[2*Cdim2 + 3], which is the same position as X1dim_FORTRAN(2*Fdim1 + 3 + 1). Remember that Cdim2 = Fdim1 because the order of indices is reversed.

MATLAB is the same as FORTRAN. Ada is the same as C except the indices normally start at 1. Any language will have the indices in one of those C or FORTRAN orders and the indices will start at 0 or 1 and can be adjusted accordingly to get at the stored data.

Sorry if this explanation is confusing, but I think it is accurate and important for a programmer to know.