Programs & Examples On #Wxauitoolbar

wxpython AUI toolbar widget, a pure Python implementation of an advanced toolbar

How to use JNDI DataSource provided by Tomcat in Spring?

Assuming you have a "sampleDS" datasource definition inside your tomcat configuration, you can add following lines to your applicationContext.xml to access the datasource using JNDI.

<jee:jndi-lookup expected-type="javax.sql.DataSource" id="springBeanIdForSampleDS" jndi-name="sampleDS"/>

You have to define the namespace and schema location for jee prefix using:

xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd"

How to remove all .svn directories from my application directories

In Windows, you can use the following registry script to add "Delete SVN Folders" to your right click context menu. Run it on any directory containing those pesky files.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\DeleteSVN]
@="Delete SVN Folders"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\DeleteSVN\command]
@="cmd.exe /c \"TITLE Removing SVN Folders in %1 && COLOR 9A && FOR /r \"%1\" %%f IN (.svn) DO RD /s /q \"%%f\" \""

json_decode returns NULL after webservice call

In Notepad++, select Encoding (from the top menu) and then ensure that "Encode in UTF-8" is selected.

This will display any characters that shouldn't be in your json that would cause json_decode to fail.

AngularJS: Insert HTML from a string

Have a look at the example in this link :

http://docs.angularjs.org/api/ngSanitize.$sanitize

Basically, angular has a directive to insert html into pages. In your case you can insert the html using the ng-bind-html directive like so :

If you already have done all this :

// My magic HTML string function.
function htmlString (str) {
    return "<h1>" + str + "</h1>";
}

function Ctrl ($scope) {
  var str = "HELLO!";
  $scope.htmlString = htmlString(str);
}
Ctrl.$inject = ["$scope"];

Then in your html within the scope of that controller, you could

<div ng-bind-html="htmlString"></div>

Making a list of evenly spaced numbers in a certain range in python

Similar to Howard's answer but a bit more efficient:

def my_func(low, up, leng):
    step = ((up-low) * 1.0 / leng)
    return [low+i*step for i in xrange(leng)]

How to Solve Max Connection Pool Error

Before you begin to curse your application you need to check this:

  1. Is your application the only one using that instance of SQL Server. a. If the answer to that is NO then you need to investigate how the other applications are consuming resources on your SQl Server.run b. If the answer is yes then you must investigate your application.

  2. Run SQL Server Profiler and check what activity is happening in other applications (1a) using SQL Server and check your application as well (1b).

  3. If indeed your application is starved off of resources then you need to make farther investigations. For more read on this http://sqlserverplanet.com/troubleshooting/sql-server-slowness

How to get htaccess to work on MAMP

  1. In httpd.conf on /Applications/MAMP/conf/apache, find:

    <Directory />
        Options Indexes FollowSymLinks
        AllowOverride None
    </Directory>
    
  2. Replace None with All.

  3. Restart MAMP servers.

Java Compare Two List's object values?

You can subtract one list from the other using CollectionUtils.subtract, if the result is an empty collection, it means both lists are the same. Another approach is using CollectionUtils.isSubCollection or CollectionUtils.isProperSubCollection.

For any case you should implement equals and hashCode methods for your object.

How can I debug a .BAT script?

you can use cmd \k at the end of your script to see the error. it won't close your command prompt after the execution is done

How do you create a temporary table in an Oracle database?

Just a tip.. Temporary tables in Oracle are different to SQL Server. You create it ONCE and only ONCE, not every session. The rows you insert into it are visible only to your session, and are automatically deleted (i.e., TRUNCATE, not DROP) when you end you session ( or end of the transaction, depending on which "ON COMMIT" clause you use).

C++: constructor initializer for arrays

This is my solution for your reference:

struct Foo
{
    Foo(){}//used to make compiler happy!
    Foo(int x){/*...*/}
};

struct Bar
{
    Foo foo[3];

    Bar()
    {
        //initialize foo array here:
        for(int i=0;i<3;++i)
        {
            foo[i]=Foo(4+i);
        }
    }
};

This project references NuGet package(s) that are missing on this computer

Is it possible that the packages have been restored to the wrong folder? Check that the paths in the csproj files are correct.

If they are different it could be caused by the packages now being restored to a different location. This could be caused by a NuGet.Config file being checked in specifying a node like this:

<add key="repositoryPath" value="..\..\Packages" />

The packages are being restored, by the projects are still looking at the old location.

How can I display a pdf document into a Webview?

Opening a pdf using google docs is a bad idea in terms of user experience. It is really slow and unresponsive.

Solution after API 21

Since api 21, we have PdfRenderer which helps converting a pdf to Bitmap. I've never used it but is seems easy enough.

Solution for any api level

Other solution is to download the PDF and pass it via Intent to a dedicated PDF app which will do a banger job displaying it. Fast and nice user experience, especially if this feature is not central in your app.

Use this code to download and open the PDF

public class PdfOpenHelper {

public static void openPdfFromUrl(final String pdfUrl, final Activity activity){
    Observable.fromCallable(new Callable<File>() {
        @Override
        public File call() throws Exception {
            try{
                URL url = new URL(pdfUrl);
                URLConnection connection = url.openConnection();
                connection.connect();

                // download the file
                InputStream input = new BufferedInputStream(connection.getInputStream());
                File dir = new File(activity.getFilesDir(), "/shared_pdf");
                dir.mkdir();
                File file = new File(dir, "temp.pdf");
                OutputStream output = new FileOutputStream(file);

                byte data[] = new byte[1024];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();
                return file;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<File>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(File file) {
                    String authority = activity.getApplicationContext().getPackageName() + ".fileprovider";
                    Uri uriToFile = FileProvider.getUriForFile(activity, authority, file);

                    Intent shareIntent = new Intent(Intent.ACTION_VIEW);
                    shareIntent.setDataAndType(uriToFile, "application/pdf");
                    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    if (shareIntent.resolveActivity(activity.getPackageManager()) != null) {
                        activity.startActivity(shareIntent);
                    }
                }
            });
}

}

For the Intent to work, you need to create a FileProvider to grant permission to the receiving app to open the file.

Here is how you implement it: In your Manifest:

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">

        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />

    </provider>

Finally create a file_paths.xml file in the resources foler

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <files-path name="shared_pdf" path="shared_pdf"/>
</paths>

Hope this helps =)

Is there a color code for transparent in HTML?

All you need is this:

#ffffff00

Here the ffffff is the color and 00 is the transparency

Also, if you want 50% transparent color, then sure you can do... #ffffff80

Where 80 is the hexadecimal equivalent of 50%. Since the scale is 0-255 in RGB Colors, the half would be 255/2 = 128, which when converted to hex becomes 80

And since in transparent we want 0 opacity, we write 00

Why am I seeing "TypeError: string indices must be integers"?

As a rule of thumb, when I receive this error in Python I compare the function signature with the function execution.

For example:

def print_files(file_list, parent_id):
    for file in file_list:
        print(title: %s, id: %s' % (file['title'], file['id']

So if I'll call this function with parameters placed in the wrong order and pass the list as the 2nd argument and a string as the 1st argument:

print_files(parent_id, list_of_files) # <----- Accidentally switching arguments location

The function will try to iterate over the parent_id string instead of file_list and it will expect to see the index as an integer pointing to the specific character in string and not an index which is a string (title or id).

This will lead to the TypeError: string indices must be integers error.

Due to its dynamic nature (as opposed to languages like Java, C# or Typescript), Python will not inform you about this syntax error.

Print content of JavaScript object?

If you just want to have a string representation of an object, you could use the JSON.stringify function, using a JSON library.

SQL Current month/ year question

select * from your_table where MONTH(mont_year) = MONTH(NOW()) and YEAR(mont_year) = YEAR(NOW());

Note: (month_year) means your column that contain date format. I think that will solve your problem. Let me know if that query doesn't works.

Find and replace with a newline in Visual Studio Code

In version 1.1.1:

  • Ctrl+H
  • Check the regular exp icon .*
  • Search: ><
  • Replace: >\n<

Ignore 'Security Warning' running script from command line

This is touched in "PowerShell Execution Policies in Standard Images" on Lee Holmes' Blog and "PowerShell’s Security Guiding Principles" on the Windows Power Shell Blog .

Summary Some machines treat UNC paths as the big bad internet, so PowerShell treats them as remote files. You can either disable this feature on those servers (UncAsIntranet = 0,) or add the remote machines to your trusted hosts.

If you want to do neither, PowerShell v2 supports an -ExecutionPolicy parameter that does exactly what your pseudocode wants. PowerShell -ExecutionPolicy Bypass -File (...).

How to check variable type at runtime in Go language

What's wrong with

func (e *Easy)SetStringOption(option Option, param string)
func (e *Easy)SetLongOption(option Option, param long)

and so on?

'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll

I think you will have fewer problems if you declared a Property that implements INotifyPropertyChanged, then databind IsChecked, SelectedIndex(using IValueConverter) and Fill(using IValueConverter) to it instead of using the Checked Event to toggle SelectedIndex and Fill.

How to Customize the time format for Python logging?

From the official documentation regarding the Formatter class:

The constructor takes two optional arguments: a message format string and a date format string.

So change

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s")

to

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s",
                              "%Y-%m-%d %H:%M:%S")

Get image dimensions

Using getimagesize function, we can also get these properties of that specific image-

<?php

list($width, $height, $type, $attr) = getimagesize("image_name.jpg");

echo "Width: " .$width. "<br />";
echo "Height: " .$height. "<br />";
echo "Type: " .$type. "<br />";
echo "Attribute: " .$attr. "<br />";

//Using array
$arr = array('h' => $height, 'w' => $width, 't' => $type, 'a' => $attr);
?>


Result like this -

Width: 200
Height: 100
Type: 2
Attribute: width='200' height='100'


Type of image consider like -

1 = GIF
2 = JPG
3 = PNG
4 = SWF
5 = PSD
6 = BMP
7 = TIFF(intel byte order)
8 = TIFF(motorola byte order)
9 = JPC
10 = JP2
11 = JPX
12 = JB2
13 = SWC
14 = IFF
15 = WBMP
16 = XBM

functional way to iterate over range (ES6/7)

Here's an approach using generators:

function* square(n) {
    for (var i = 0; i < n; i++ ) yield i*i;
}

Then you can write

console.log(...square(7));

Another idea is:

[...Array(5)].map((_, i) => i*i)

Array(5) creates an unfilled five-element array. That's how Array works when given a single argument. We use the spread operator to create an array with five undefined elements. That we can then map. See http://ariya.ofilabs.com/2013/07/sequences-using-javascript-array.html.

Alternatively, we could write

Array.from(Array(5)).map((_, i) => i*i)

or, we could take advantage of the second argument to Array#from to skip the map and write

Array.from(Array(5), (_, i) => i*i)

A horrible hack which I saw recently, which I do not recommend you use, is

[...1e4+''].map((_, i) => i*i)

Batch - If, ElseIf, Else

@echo off

set "language=de"

IF "%language%" == "de" (
    goto languageDE
) ELSE (
    IF "%language%" == "en" (
        goto languageEN
    ) ELSE (
    echo Not found.
    )
)

:languageEN
:languageDE

echo %language%

This works , but not sure how your language variable is defined.Does it have spaces in its definition.

How to override the path of PHP to use the MAMP path?

This is not an ideal solution as you have to manage two ini files however, I managed to work around this on windows by copying the php ini file in mamp from the conf folder to your active php version in the bin folder.

[MAMP INSTALL]\conf\[ACTIVE PHP VERSION]\php.ini

copy to

[MAMP INSTALL]\bin\php\[ACTIVE PHP VERSION]

What Ruby IDE do you prefer?

Most IDEs present the project structure in a top down manner. This is great way to explore at a high level when joining an existing project. However, after working on the same project for more than a year, I realized that this approach can become counter-productive.

After Oracle declared the end of Ruby in NetBeans, I switched to Vim. By using a command line and an editor as the only tools, I was forced to mentally switch to a bottom-up perspective. To my amazement, I discovered that this made me more focused and productive. As a bonus, I got first class HAML and SASS syntax support.

I recommend Vim + Rails plugin for anyone that will work on a single project for an extended period of time.

Singleton design pattern vs Singleton beans in Spring container

"singleton" in spring is using bean factory get instance, then cache it; which singleton design pattern is strictly, the instance can only be retrieved from static get method, and the object can never be publicly instantiated.

Get Root Directory Path of a PHP project

You could also use realpath.

realpath(".") returns your document root.

You can call realpath with your specific path. Note that it will NOT work if the target folder or file does not exist. In such case it will return false, which could be useful for testing if a file exists.

In my case I needed to specify a path for a new file to be written to disk, and the solution was to append the path relative to document root:

$filepath = realpath(".") . "/path/to/newfile.txt";

Hope this helps anyone.

Flutter position stack widget in center

A Stack allows you to stack elements on top of each other, with the last element in the array taking the highest priority. You can use Align, Positioned, or Container to position the children of a stack.

Align

Widgets are moved by setting the alignment with Alignment, which has static properties like topCenter, bottomRight, and so on. Or you can take full control and set Alignment(1.0, -1.0), which takes x,y values ranging from 1.0 to -1.0, with (0,0) being the center of the screen.

  Stack(
      children: [
        Align(
          alignment: Alignment.topCenter,
          child: Container(
              height: 80,
              width: 80, color: Colors.blueAccent
          ),
        ),
        Align(
          alignment: Alignment.center,
          child: Container(
              height: 80,
              width: 80, color: Colors.deepPurple
          ),
        ),
        Container(
          alignment: Alignment.bottomCenter,
          // alignment: Alignment(1.0, -1.0),
          child: Container(
              height: 80,
              width: 80, color: Colors.amber
          ),
        )
      ]
  )

enter image description here

Symfony 2 EntityManager injection in service

For modern reference, in Symfony 2.4+, you cannot name the arguments for the Constructor Injection method anymore. According to the documentation You would pass in:

services:
    test.common.userservice:
        class:  Test\CommonBundle\Services\UserService
        arguments: [ "@doctrine.orm.entity_manager" ]

And then they would be available in the order they were listed via the arguments (if there are more than 1).

public function __construct(EntityManager $entityManager) {
    $this->em = $entityManager;
}

How to fit Windows Form to any screen resolution?

Can't you start maximized?

Set the System.Windows.Forms.Form.WindowState property to FormWindowState.Maximized

Angular HttpPromise: difference between `success`/`error` methods and `then`'s arguments

There are some good answers here already. But it's worthwhile to drive home the difference in parallelism offered:

  • success() returns the original promise
  • then() returns a new promise

The difference is then() drives sequential operations, since each call returns a new promise.

$http.get(/*...*/).
  then(function seqFunc1(response){/*...*/}).
  then(function seqFunc2(response){/*...*/})
  1. $http.get()
  2. seqFunc1()
  3. seqFunc2()

success() drives parallel operations, since handlers are chained on the same promise.

$http(/*...*/).
  success(function parFunc1(data){/*...*/}).
  success(function parFunc2(data){/*...*/})
  1. $http.get()
  2. parFunc1(), parFunc2() in parallel

Cast IList to List

How about this:

List<SubProduct> subProducts = Model.subproduct.ToList();

Relative Paths in Javascript in an external file

I used pekka's pattern. I think yet another pattern.

<script src="<% = Url.Content("~/Site/Scripts/myjsfile.js") %>?root=<% = Page.ResolveUrl("~/Site/images") %>">

and parsed querystring in myjsfile.js.

Plugins | jQuery Plugins

What is the regex for "Any positive integer, excluding 0"

This should only allow decimals > 0

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

Best/Most Comprehensive API for Stocks/Financial Data

Last I looked -- a couple of years ago -- there wasn't an easy option and the "solution" (which I did not agree with) was screen-scraping a number of websites. It may be easier now but I would still be surprised to see something, well, useful.

The problem here is that the data is immensely valuable (and very expensive), so while defining a method of retrieving it would be easy, getting the trading venues to part with their data would be next to impossible. Some of the MTFs (currently) provide their data for free but I'm not sure how you would get it without paying someone else, like Reuters, for it.

When to use pthread_exit() and when to use pthread_join() in Linux?

Hmm.

POSIX pthread_exit description from http://pubs.opengroup.org/onlinepubs/009604599/functions/pthread_exit.html:

After a thread has terminated, the result of access to local (auto) variables of the thread is 
undefined. Thus, references to local variables of the exiting thread should not be used for 
the pthread_exit() value_ptr parameter value.

Which seems contrary to the idea that local main() thread variables will remain accessible.

How to play videos in android from assets folder or raw folder?

VideoView myVideo = (VideoView) rootView.findViewById(R.id.definition_video_view);

//Set video name (no extension)
String myVideoName = "my_video";

//Set app package
String myAppPackage = "com.myapp";

//Get video URI from raw directory
Uri myVideoUri = Uri.parse("android.resource://"+myAppPackage+"/raw/"+myVideoName);

//Set the video URI
myVideo.setVideoURI(myVideoUri);

//Play the video
myVideo.start();

https://gist.github.com/jrejaud/b5eb1b013c27a1f3ae5f

Convert integer to hex and hex to integer

It is possible using the function FORMAT available on SQL Server 2012 and above

select FORMAT(10,'x2')

Results in:

0a

Arduino IDE can't find ESP8266WiFi.h file

When programming the NODEMCU card with the Arduino IDE, you need to customize it and you must have selected the correct card.

Open Arduino IDE and go to files and click on the preference in the Arduino IDE.

Add the following link to the Additional Manager URLS section: "http://arduino.esp8266.com/stable/package_esp8266com_index.json" and press the OK button.

Then click Tools> Board Manager. Type "ESP8266" in the text box to search and install the ESP8266 software for Arduino IDE.

You will be successful when you try to program again by selecting the NodeMCU card after these operations. I hope I could help.

Button Center CSS

Consider adding this to your CSS to resolve the problem:

button {
    margin: 0 auto;
    display: block;
}

Auto increment in phpmyadmin

(a)Simply click on your database, select your table. Click on 'Operations'. Under the 'table options' section change the AUTO_INCREMENT value to your desired value, in this case: 10000 the click 'Go'. (See the image attached)

(b)Alternatively, you can run a SQL command under the SQL tab after selecting your table. Simply type 'ALTER TABLE table_name AUTO_INCREMENT = 10000;' then click 'Go'. That's it!! SETTING AUTO INCREMENT VALUE image(a)

SETTING AUTO INCREMENT VALUE image(B)

Is there a <meta> tag to turn off caching in all browsers?

I noticed some caching issues with service calls when repeating the same service call (long polling). Adding metadata didn't help. One solution is to pass a timestamp to ensure ie thinks it's a different http service request. That worked for me, so adding a server side scripting code snippet to automatically update this tag wouldn't hurt:

<meta http-equiv="expires" content="timestamp">

PDF Blob - Pop up window not showing content

You need to set the responseType to arraybuffer if you would like to create a blob from your response data:

$http.post('/fetchBlobURL',{myParams}, {responseType: 'arraybuffer'})
   .success(function (data) {
       var file = new Blob([data], {type: 'application/pdf'});
       var fileURL = URL.createObjectURL(file);
       window.open(fileURL);
});

more information: Sending_and_Receiving_Binary_Data

How to write inline if statement for print?

The 'else' statement is mandatory. You can do stuff like this :

>>> b = True
>>> a = 1 if b else None
>>> a
1
>>> b = False
>>> a = 1 if b else None
>>> a
>>> 

EDIT:

Or, depending of your needs, you may try:

>>> if b: print(a)

delete vs delete[] operators in C++

When I asked this question, my real question was, "is there a difference between the two? Doesn't the runtime have to keep information about the array size, and so will it not be able to tell which one we mean?" This question does not appear in "related questions", so just to help out those like me, here is the answer to that: "why do we even need the delete[] operator?"

Color theme for VS Code integrated terminal

Add workbench.colorCustomizations to user settings

"workbench.colorCustomizations": {
  "terminal.background":"#FEFBEC",
  "terminal.foreground":"#6E6B5E",
  ...
}

Check https://glitchbone.github.io/vscode-base16-term for some presets.

How can I find all of the distinct file extensions in a folder hierarchy?

Since there's already another solution which uses Perl:

If you have Python installed you could also do (from the shell):

python -c "import os;e=set();[[e.add(os.path.splitext(f)[-1]) for f in fn]for _,_,fn in os.walk('/home')];print '\n'.join(e)"

How to create a delay in Swift?

I agree with Palle that using dispatch_after is a good choice here. But you probably don't like the GCD calls as they are quite annoying to write. Instead you can add this handy helper:

public func delay(bySeconds seconds: Double, dispatchLevel: DispatchLevel = .main, closure: @escaping () -> Void) {
    let dispatchTime = DispatchTime.now() + seconds
    dispatchLevel.dispatchQueue.asyncAfter(deadline: dispatchTime, execute: closure)
}

public enum DispatchLevel {
    case main, userInteractive, userInitiated, utility, background
    var dispatchQueue: DispatchQueue {
        switch self {
        case .main:                 return DispatchQueue.main
        case .userInteractive:      return DispatchQueue.global(qos: .userInteractive)
        case .userInitiated:        return DispatchQueue.global(qos: .userInitiated)
        case .utility:              return DispatchQueue.global(qos: .utility)
        case .background:           return DispatchQueue.global(qos: .background)
        }
    }
}

Now you simply delay your code on a background thread like this:

delay(bySeconds: 1.5, dispatchLevel: .background) { 
    // delayed code that will run on background thread
}

Delaying code on the main thread is even simpler:

delay(bySeconds: 1.5) { 
    // delayed code, by default run in main thread
}

If you prefer a Framework that also has some more handy features then checkout HandySwift. You can add it to your project via SwiftPM then use it exactly like in the examples above:

import HandySwift    

delay(by: .seconds(1.5)) { 
    // delayed code
}

Jenkins Pipeline Wipe Out Workspace

Currently both deletedir() and cleanWs() do not work properly when using Jenkins kubernetes plugin, the pod workspace is deleted but the master workspace persists

it should not be a problem for persistant branches, when you have a step to clean the workspace prior to checkout scam. It will basically reuse the same workspace over and over again: but when using multibranch pipelines the master keeps the whole workspace and git directory

I believe this should be an issue with Jenkins, any enlightenment here?

SQL Server: What is the difference between CROSS JOIN and FULL OUTER JOIN?

Cross Join: http://www.dba-oracle.com/t_garmany_9_sql_cross_join.htm

TLDR; Generates a all possible combinations between 2 tables (Carthesian product)

(Full) Outer Join: http://www.w3schools.com/Sql/sql_join_full.asp

TLDR; Returns every row in both tables and also results that have the same values (matches in CONDITION)

What's the complete range for Chinese characters in Unicode?

May be you would find a complete list through the CJK Unicode FAQ (which does include "Chinese, Japanese, and Korean" characters)

The "East Asian Script" document does mention:

Blocks Containing Han Ideographs

Han ideographic characters are found in five main blocks of the Unicode Standard, as shown in Table 12-2

Table 12-2. Blocks Containing Han Ideographs

Block                                   Range       Comment
CJK Unified Ideographs                  4E00-9FFF   Common
CJK Unified Ideographs Extension A      3400-4DBF   Rare
CJK Unified Ideographs Extension B      20000-2A6DF Rare, historic
CJK Unified Ideographs Extension C      2A700–2B73F Rare, historic
CJK Unified Ideographs Extension D      2B740–2B81F Uncommon, some in current use
CJK Unified Ideographs Extension E      2B820–2CEAF Rare, historic
CJK Compatibility Ideographs            F900-FAFF   Duplicates, unifiable variants, corporate characters
CJK Compatibility Ideographs Supplement 2F800-2FA1F Unifiable variants

Note: the block ranges can evolve over time: latest is in CJK Unified Ideographs.

See also Wikipedia:

error CS0234: The type or namespace name 'Script' does not exist in the namespace 'System.Web'

Since JsonSerializer is deprecated in .Net 4.0+ I used http://www.newtonsoft.com/json to solve this issue.

NuGet- > Install-Package Newtonsoft.Json

Python pandas insert list into a cell

Pandas >= 0.21

set_value has been deprecated. You can now use DataFrame.at to set by label, and DataFrame.iat to set by integer position.

Setting Cell Values with at/iat

# Setup
df = pd.DataFrame({'A': [12, 23], 'B': [['a', 'b'], ['c', 'd']]})
df

    A       B
0  12  [a, b]
1  23  [c, d]

df.dtypes

A     int64
B    object
dtype: object

If you want to set a value in second row of the "B" to some new list, use DataFrane.at:

df.at[1, 'B'] = ['m', 'n']
df

    A       B
0  12  [a, b]
1  23  [m, n]

You can also set by integer position using DataFrame.iat

df.iat[1, df.columns.get_loc('B')] = ['m', 'n']
df

    A       B
0  12  [a, b]
1  23  [m, n]

What if I get ValueError: setting an array element with a sequence?

I'll try to reproduce this with:

df

    A   B
0  12 NaN
1  23 NaN

df.dtypes

A      int64
B    float64
dtype: object

df.at[1, 'B'] = ['m', 'n']
# ValueError: setting an array element with a sequence.

This is because of a your object is of float64 dtype, whereas lists are objects, so there's a mismatch there. What you would have to do in this situation is to convert the column to object first.

df['B'] = df['B'].astype(object)
df.dtypes

A     int64
B    object
dtype: object

Then, it works:

df.at[1, 'B'] = ['m', 'n']
df

    A       B
0  12     NaN
1  23  [m, n]

Possible, But Hacky

Even more wacky, I've found you can hack through DataFrame.loc to achieve something similar if you pass nested lists.

df.loc[1, 'B'] = [['m'], ['n'], ['o'], ['p']]
df

    A             B
0  12        [a, b]
1  23  [m, n, o, p]

You can read more about why this works here.

Multiple conditions in ngClass - Angular 4

You are trying to assign an array to ngClass, but the syntax for the array elements is wrong since you separate them with a || instead of a ,.

Try this:

<section [ngClass]="[menu1 ? 'class1' : '',  menu2 ? 'class1' : '', (something && (menu1 || menu2)) ? 'class2' : '']">

This other option should also work:

<section [ngClass.class1]="menu1 || menu2" [ngClass.class2] = "(menu1 || menu2) && something">    

SQL variable to hold list of integers

For SQL Server 2016+ and Azure SQL Database, the STRING_SPLIT function was added that would be a perfect solution for this problem. Here is the documentation: https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql

Here is an example:

/*List of ids in a comma delimited string
  Note: the ') WAITFOR DELAY ''00:00:02''' is a way to verify that your script 
        doesn't allow for SQL injection*/
DECLARE @listOfIds VARCHAR(MAX) = '1,3,a,10.1,) WAITFOR DELAY ''00:00:02''';

--Make sure the temp table was dropped before trying to create it
IF OBJECT_ID('tempdb..#MyTable') IS NOT NULL DROP TABLE #MyTable;

--Create example reference table
CREATE TABLE #MyTable
([Id] INT NOT NULL);

--Populate the reference table
DECLARE @i INT = 1;
WHILE(@i <= 10)
BEGIN
    INSERT INTO #MyTable
    SELECT @i;

    SET @i = @i + 1;
END

/*Find all the values
  Note: I silently ignore the values that are not integers*/
SELECT t.[Id]
FROM #MyTable as t
    INNER JOIN 
        (SELECT value as [Id] 
        FROM STRING_SPLIT(@listOfIds, ',')
        WHERE ISNUMERIC(value) = 1 /*Make sure it is numeric*/
            AND ROUND(value,0) = value /*Make sure it is an integer*/) as ids
    ON t.[Id] = ids.[Id];

--Clean-up
DROP TABLE #MyTable;

The result of the query is 1,3

~Cheers

How to run an EXE file in PowerShell with parameters with spaces and quotes

When PowerShell sees a command starting with a string it just evaluates the string, that is, it typically echos it to the screen, for example:

PS> "Hello World"
Hello World

If you want PowerShell to interpret the string as a command name then use the call operator (&) like so:

PS> & 'C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe'

After that you probably only need to quote parameter/argument pairs that contain spaces and/or quotation chars. When you invoke an EXE file like this with complex command line arguments it is usually very helpful to have a tool that will show you how PowerShell sends the arguments to the EXE file. The PowerShell Community Extensions has such a tool. It is called echoargs. You just replace the EXE file with echoargs - leaving all the arguments in place, and it will show you how the EXE file will receive the arguments, for example:

PS> echoargs -verb:sync -source:dbfullsql="Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;" -dest:dbfullsql="Data Source=.\mydestsource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;",computername=10.10.10.10,username=administrator,password=adminpass

Arg 0 is <-verb:sync>
Arg 1 is <-source:dbfullsql=Data>
Arg 2 is <Source=mysource;Integrated>
Arg 3 is <Security=false;User>
Arg 4 is <ID=sa;Pwd=sapass!;Database=mydb;>
Arg 5 is <-dest:dbfullsql=Data>
Arg 6 is <Source=.\mydestsource;Integrated>
Arg 7 is <Security=false;User>
Arg 8 is <ID=sa;Pwd=sapass!;Database=mydb; computername=10.10.10.10 username=administrator password=adminpass>

Using echoargs you can experiment until you get it right, for example:

PS> echoargs -verb:sync "-source:dbfullsql=Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;"
Arg 0 is <-verb:sync>
Arg 1 is <-source:dbfullsql=Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;>

It turns out I was trying too hard before to maintain the double quotes around the connection string. Apparently that isn't necessary because even cmd.exe will strip those out.

BTW, hats off to the PowerShell team. They were quite helpful in showing me the specific incantation of single & double quotes to get the desired result - if you needed to keep the internal double quotes in place. :-) They also realize this is an area of pain, but they are driven by the number of folks are affected by a particular issue. If this is an area of pain for you, then please vote up this PowerShell bug submission.

For more information on how PowerShell parses, check out my Effective PowerShell blog series - specifically item 10 - "Understanding PowerShell Parsing Modes"

UPDATE 4/4/2012: This situation gets much easier to handle in PowerShell V3. See this blog post for details.

Enable/Disable Anchor Tags using AngularJS

For people not wanting a complicated answer, I used Ng-If to solve this for something similar:

<div style="text-align: center;">
 <a ng-if="ctrl.something != null" href="#" ng-click="ctrl.anchorClicked();">I'm An Anchor</a>
 <span ng-if="ctrl.something == null">I'm just text</span>
</div>

where to place CASE WHEN column IS NULL in this query

Thanks for all your help! @Svetoslav Tsolov had it very close, but I was still getting an error, until I figured out the closing parenthesis was in the wrong place. Here's the final query that works:

SELECT dbo.AdminID.CountryID, dbo.AdminID.CountryName, dbo.AdminID.RegionID, 
dbo.AdminID.[Region name], dbo.AdminID.DistrictID, dbo.AdminID.DistrictName,
dbo.AdminID.ADMIN3_ID, dbo.AdminID.ADMIN3,
(CASE WHEN dbo.EU_Admin3.EUID IS NULL THEN dbo.EU_Admin2.EUID ELSE dbo.EU_Admin3.EUID END) AS EUID
FROM dbo.AdminID 

LEFT OUTER JOIN dbo.EU_Admin2
ON dbo.AdminID.DistrictID = dbo.EU_Admin2.DistrictID

LEFT OUTER JOIN dbo.EU_Admin3
ON dbo.AdminID.ADMIN3_ID = dbo.EU_Admin3.ADMIN3_ID

Is there any way I can define a variable in LaTeX?

I think you probably want to use a token list for this purpose: to set up the token list \newtoks\packagename to assign the name: \packagename={New Name for the package} to put the name into your output: \the\packagename.

Adding value to input field with jQuery

You have to escape [ and ]. Try this:

$('.button').click(function(){
    var fieldID = $(this).prev().attr("id");
    fieldID = fieldID.replace(/([\[\]]+)/g, "\\$1");
    $('#' + fieldID).val("hello world");
});

Demo: http://jsfiddle.net/7RJtf/1/

Using setTimeout to delay timing of jQuery actions

You can also use jQuery's delay() method instead of setTimeout(). It'll give you much more readable code. Here's an example from the docs:

$( "#foo" ).slideUp( 300 ).delay( 800 ).fadeIn( 400 );

The only limitation (that I'm aware of) is that it doesn't give you a way to clear the timeout. If you need to do that then you're better off sticking with all the nested callbacks that setTimeout thrusts upon you.

Get position/offset of element relative to a parent container?

Add the offset of the event to the parent element offset to get the absolute offset position of the event.

An example :

HTMLElement.addEventListener('mousedown',function(e){

    var offsetX = e.offsetX;
    var offsetY = e.offsetY;

    if( e.target != this ){ // 'this' is our HTMLElement

        offsetX = e.target.offsetLeft + e.offsetX;
        offsetY = e.target.offsetTop + e.offsetY;

    }
}

When the event target is not the element which the event was registered to, it adds the offset of the parent to the current event offset in order to calculate the "Absolute" offset value.

According to Mozilla Web API: "The HTMLElement.offsetLeft read-only property returns the number of pixels that the upper left corner of the current element is offset to the left within the HTMLElement.offsetParent node."

This mostly happens when you registered an event on a parent which is containing several more children, for example: a button with an inner icon or text span, an li element with inner spans. etc...

insert password into database in md5 format?

Don't use MD5 as it is insecure. I would recommend using SHA or bcrypt with a salt:

SHA256('".$password."')

http://en.wikipedia.org/wiki/Salt_(cryptography)

How to select all the columns of a table except one column?

I just wanted to echo @Luann's comment as I use this approach always.

Just right click on the table > Script table as > Select to > New Query window.

You will see the select query. Just take out the column you want to exclude and you have your preferred select query. enter image description here

find all subsets that sum to a particular value

While it is straightforward to find if their is a subset or not that sums to the target, implementation gets tricky when you need to keep track of the partial subsets under consideration.

If you use a linked list, a hash set or any another generic collection, you would be tempted to add an item to this collection before the call that includes the item, and then remove it before the call that excludes the item. This does not work as expected, as the stack frames in which the add will occur is not the same as the one in which remove will occur.

Solution is to use a string to keep track of the sequence. Appends to the string can be done inline in the function call; thereby maintaining the same stack frame and your answer would then conform beautifully to the original hasSubSetSum recursive structure.

import java.util.ArrayList;

public class Solution {

public static boolean hasSubSet(int [] A, int target) {
    ArrayList<String> subsets = new ArrayList<>();
    helper(A, target, 0, 0, subsets, "");
    // Printing the contents of subsets is straightforward
    return !subsets.isEmpty();
}

private static void helper(int[] A, int target, int sumSoFar, int i, ArrayList<String> subsets, String curr) {
    if(i == A.length) {
        if(sumSoFar == target) {
            subsets.add(curr);
        }
        return;
    }
    helper(A, target, sumSoFar, i+1, subsets, curr);
    helper(A, target, sumSoFar + A[i], i+1, subsets, curr + A[i]);
}

public static void main(String [] args) {
    System.out.println(hasSubSet(new int[] {1,2,4,5,6}, 8));
}

}

How to see the actual Oracle SQL statement that is being executed

I had (have) a similar problem in a Java application. I wrote a JDBC driver wrapper around the Oracle driver so all output is sent to a log file.

Why is enum class preferred over plain enum?

Because, as said in other answers, class enum are not implicitly convertible to int/bool, it also helps to avoid buggy code like:

enum MyEnum {
  Value1,
  Value2,
};
...
if (var == Value1 || Value2) // Should be "var == Value2" no error/warning

How to _really_ programmatically change primary and accent color in Android Lollipop?

I used the Dahnark's code but I also need to change the ToolBar background:

if (dark_ui) {
    this.setTheme(R.style.Theme_Dark);

    if (Build.VERSION.SDK_INT >= 21) {
        getWindow().setNavigationBarColor(getResources().getColor(R.color.Theme_Dark_primary));
        getWindow().setStatusBarColor(getResources().getColor(R.color.Theme_Dark_primary_dark));
    }
} else {
    this.setTheme(R.style.Theme_Light);
}

setContentView(R.layout.activity_main);

toolbar = (Toolbar) findViewById(R.id.app_bar);

if(dark_ui) {
    toolbar.setBackgroundColor(getResources().getColor(R.color.Theme_Dark_primary));
}

ES6 Class Multiple inheritance

Here's an awesome/really crappy way of extending multiple classes. I'm utilizing a couple functions that Babel put into my transpiled code. The function creates a new class that inherits class1, and class1 inherits class2, and so on. It has its issues, but a fun idea.

var _typeof = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? function (obj) {
  return typeof obj
} : function (obj) {
  return obj && typeof Symbol === 'function' && obj.constructor === Symbol ? 'symbol' : typeof obj
}

function _inherits (subClass, superClass) {
  if (typeof superClass !== 'function' && superClass !== null) {
    throw new TypeError('Super expression must either be null or a function, not ' + (
      typeof superClass === 'undefined' ? 'undefined' : _typeof(superClass)))
  }
  subClass.prototype = Object.create(
    superClass && superClass.prototype,
    {
      constructor: {
        value: subClass,
        enumerable: false,
        writable: true,
        configurable: true
      }
    })
  if (superClass) {
    Object.setPrototypeOf
    ? Object.setPrototypeOf(subClass, superClass)
    : subClass.__proto__ = superClass.__proto__  // eslint-disable-line no-proto
  }
}

function _m (...classes) {
  let NewSuperClass = function () {}
  let c1 = NewSuperClass
  for (let c of classes) {
    _inherits(c1, c)
    c1 = c
  }
  return NewSuperClass
}

import React from 'react'

/**
 * Adds `this.log()` to your component.
 * Log message will be prefixed with the name of the component and the time of the message.
 */
export default class LoggingComponent extends React.Component {
  log (...msgs) {
    if (__DEBUG__) {
      console.log(`[${(new Date()).toLocaleTimeString()}] [${this.constructor.name}]`, ...msgs)
    }
  }
}

export class MyBaseComponent extends _m(LoggingComponent, StupidComponent) {}

How to remove specific substrings from a set of strings in Python?

When there are multiple substrings to remove, one simple and effective option is to use re.sub with a compiled pattern that involves joining all the substrings-to-remove using the regex OR (|) pipe.

import re

to_remove = ['.good', '.bad']
strings = ['Apple.good','Orange.good','Pear.bad']

p = re.compile('|'.join(map(re.escape, to_remove))) # escape to handle metachars
[p.sub('', s) for s in strings]
# ['Apple', 'Orange', 'Pear']

Difference of keywords 'typename' and 'class' in templates?

This piece of snippet is from c++ primer book. Although I am sure this is wrong.

Each type parameter must be preceded by the keyword class or typename:

// error: must precede U with either typename or class
template <typename T, U> T calc(const T&, const U&);

These keywords have the same meaning and can be used interchangeably inside a template parameter list. A template parameter list can use both keywords:

// ok: no distinction between typename and class in a template parameter list
template <typename T, class U> calc (const T&, const U&);

It may seem more intuitive to use the keyword typename rather than class to designate a template type parameter. After all, we can use built-in (nonclass) types as a template type argument. Moreover, typename more clearly indicates that the name that follows is a type name. However, typename was added to C++ after templates were already in widespread use; some programmers continue to use class exclusively

html form - make inputs appear on the same line

Try just putting a div around the first and last name inputs/labels like this:

<div class="name">
        <label for="First_Name">First Name:</label>
        <input name="first_name" id="First_Name" type="text" />

        <label for="Name">Last Name:</label>
        <input name="last_name" id="Last_Name" type="text" /> 
</div>

Look at the fiddle here: http://jsfiddle.net/XAkXg/

How to return a class object by reference in C++?

Well, it is maybe not a really beautiful solution in the code, but it is really beautiful in the interface of your function. And it is also very efficient. It is ideal if the second is more important for you (for example, you are developing a library).

The trick is this:

  1. A line A a = b.make(); is internally converted to a constructor of A, i.e. as if you had written A a(b.make());.
  2. Now b.make() should result a new class, with a callback function.
  3. This whole thing can be fine handled only by classes, without any template.

Here is my minimal example. Check only the main(), as you can see it is simple. The internals aren't.

From the viewpoint of the speed: the size of a Factory::Mediator class is only 2 pointers, which is more that 1 but not more. And this is the only object in the whole thing which is transferred by value.

#include <stdio.h>

class Factory {
  public:
    class Mediator;

    class Result {
      public:
        Result() {
          printf ("Factory::Result::Result()\n");
        };

        Result(Mediator fm) {
          printf ("Factory::Result::Result(Mediator)\n");
          fm.call(this);
        };
    };

    typedef void (*MakeMethod)(Factory* factory, Result* result);

    class Mediator {
      private:
        Factory* factory;
        MakeMethod makeMethod;

      public:
        Mediator(Factory* factory, MakeMethod makeMethod) {
          printf ("Factory::Mediator::Mediator(Factory*, MakeMethod)\n");
          this->factory = factory;
          this->makeMethod = makeMethod;
        };

        void call(Result* result) {
          printf ("Factory::Mediator::call(Result*)\n");
          (*makeMethod)(factory, result);
        };
    };
};

class A;

class B : private Factory {
  private:
    int v;

  public:
    B(int v) {
      printf ("B::B()\n");
      this->v = v;
    };

    int getV() const {
      printf ("B::getV()\n");
      return v;
    };

    static void makeCb(Factory* f, Factory::Result* a);

    Factory::Mediator make() {
      printf ("Factory::Mediator B::make()\n");
      return Factory::Mediator(static_cast<Factory*>(this), &B::makeCb);
    };
};

class A : private Factory::Result {
  friend class B;

  private:
    int v;

  public:
    A() {
      printf ("A::A()\n");
      v = 0;
    };

    A(Factory::Mediator fm) : Factory::Result(fm) {
      printf ("A::A(Factory::Mediator)\n");
    };

    int getV() const {
      printf ("A::getV()\n");
      return v;
    };

    void setV(int v) {
      printf ("A::setV(%i)\n", v);
      this->v = v;
    };
};

void B::makeCb(Factory* f, Factory::Result* r) {
      printf ("B::makeCb(Factory*, Factory::Result*)\n");
      B* b = static_cast<B*>(f);
      A* a = static_cast<A*>(r);
      a->setV(b->getV()+1);
    };

int main(int argc, char **argv) {
  B b(42);
  A a = b.make();
  printf ("a.v = %i\n", a.getV());
  return 0;
}

Get content of a DIV using JavaScript

simply you can use jquery plugin to get/set the content of the div.

var divContent = $('#'DIV1).html(); $('#'DIV2).html(divContent );

for this you need to include jquery library.

T-SQL and the WHERE LIKE %Parameter% clause

It should be:

...
WHERE LastName LIKE '%' + @LastName + '%';

Instead of:

...
WHERE LastName LIKE '%@LastName%'

How to convert a std::string to const char* or char*?

char* result = strcpy((char*)malloc(str.length()+1), str.c_str());

curl: (6) Could not resolve host: application

In my case, putting space after colon was wrong.

# Not work
curl -H Content-Type: application/json ~
# OK
curl -H Content-Type:application/json ~

ASP.NET - How to write some html in the page? With Response.Write?

why don't you give LiteralControl a try?

 myLitCtrl.Text="<h2><p>Notify:</p> Alert</h2>";

How to protect Excel workbook using VBA?

To lock whole workbook from opening, Thisworkbook.password option can be used in VBA.

If you want to Protect Worksheets, then you have to first Lock the cells with option Thisworkbook.sheets.cells.locked = True and then use the option Thisworkbook.sheets.protect password:="pwd".

Primarily search for these keywords: Thisworkbook.password or Thisworkbook.Sheets.Cells.Locked

How to export SQL Server 2005 query to CSV

I think the simplest way to do this is from Excel.

  1. Open a new Excel file.
  2. Click on the Data tab
  3. Select Other Data Sources
  4. Select SQL Server
  5. Enter your server name, database, table name, etc.

If you have a newer version of Excel you could bring the data in from PowerPivot and then insert this data into a table.

get the margin size of an element with jquery

Exemple, for :

<div id="myBlock" style="margin: 10px 0px 15px 5px:"></div>

In this js code :

var myMarginTop = $("#myBlock").css("marginBottom");

The var becomes "15px", a string.

If you want an Integer, to avoid NaN (Not a Number), there is multiple ways.

The fastest is to use native js method :

var myMarginTop = parseInt( $("#myBlock").css("marginBottom") );

How to use ng-if to test if a variable is defined

You can still use angular.isDefined()

You just need to set

$rootScope.angular = angular;

in the "run" phase.

See update plunkr: http://plnkr.co/edit/h4ET5dJt3e12MUAXy1mS?p=preview

Is there a css cross-browser value for "width: -moz-fit-content;"?

In similar case I used: white-space: nowrap;

java.lang.ClassNotFoundException: org.apache.log4j.Level

In my environment, I just added the two files to class path. And is work fine.

slf4j-jdk14-1.7.25.jar
slf4j-api-1.7.25.jar

How to get video duration, dimension and size in PHP?

https://github.com/JamesHeinrich/getID3 download getid3 zip and than only getid3 named folder copy paste in project folder and use it as below show...

<?php
        require_once('/fire/scripts/lib/getid3/getid3/getid3.php');
        $getID3 = new getID3();
        $filename="/fire/My Documents/video/ferrari1.mpg";
        $fileinfo = $getID3->analyze($filename);

        $width=$fileinfo['video']['resolution_x'];
        $height=$fileinfo['video']['resolution_y'];

        echo $fileinfo['video']['resolution_x']. 'x'. $fileinfo['video']['resolution_y'];
        echo '<pre>';print_r($fileinfo);echo '</pre>';
?>

What does functools.wraps do?

I very often use classes, rather than functions, for my decorators. I was having some trouble with this because an object won't have all the same attributes that are expected of a function. For example, an object won't have the attribute __name__. I had a specific issue with this that was pretty hard to trace where Django was reporting the error "object has no attribute '__name__'". Unfortunately, for class-style decorators, I don't believe that @wrap will do the job. I have instead created a base decorator class like so:

class DecBase(object):
    func = None

    def __init__(self, func):
        self.__func = func

    def __getattribute__(self, name):
        if name == "func":
            return super(DecBase, self).__getattribute__(name)

        return self.func.__getattribute__(name)

    def __setattr__(self, name, value):
        if name == "func":
            return super(DecBase, self).__setattr__(name, value)

        return self.func.__setattr__(name, value)

This class proxies all the attribute calls over to the function that is being decorated. So, you can now create a simple decorator that checks that 2 arguments are specified like so:

class process_login(DecBase):
    def __call__(self, *args):
        if len(args) != 2:
            raise Exception("You can only specify two arguments")

        return self.func(*args)

How do I install imagemagick with homebrew?

You could do:

brew reinstall php55-imagick

Where php55 is your PHP version.

Fitting empirical distribution to theoretical ones with Scipy (Python)?

It sounds like probability density estimation problem to me.

from scipy.stats import gaussian_kde
occurences = [0,0,0,0,..,1,1,1,1,...,2,2,2,2,...,47]
values = range(0,48)
kde = gaussian_kde(map(float, occurences))
p = kde(values)
p = p/sum(p)
print "P(x>=1) = %f" % sum(p[1:])

Also see http://jpktd.blogspot.com/2009/03/using-gaussian-kernel-density.html.

c++ string array initialization

In C++11 and above, you can also initialize std::vector with an initializer list. For example:

using namespace std; // for example only

for (auto s : vector<string>{"one","two","three"} ) 
    cout << s << endl;

So, your example would become:

void foo(vector<string> strArray){
  // some code
}

vector<string> s {"hi", "there"}; // Works
foo(s); // Works

foo(vector<string> {"hi", "there"}); // also works

Using C# to check if string contains a string in string array

try this, here the example : To check if the field contains any of the words in the array. To check if the field(someField) contains any of the words in the array.

String[] val = { "helloword1", "orange", "grape", "pear" };   

Expression<Func<Item, bool>> someFieldFilter = i => true;

someFieldFilter = i => val.Any(s => i.someField.Contains(s));

How to style the UL list to a single line

in bootstrap use .list-inline css class

<ul class="list-inline">
    <li>Coffee</li>
    <li>Tea</li>
    <li>Milk</li>
</ul>

Ref: https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_txt_list-inline&stacked=h

Using Position Relative/Absolute within a TD?

also works if you do a "display: block;" on the td, destroying the td identity, but works!

How to check if a string is null in python

In python, bool(sequence) is False if the sequence is empty. Since strings are sequences, this will work:

cookie = ''
if cookie:
    print "Don't see this"
else:
    print "You'll see this"

Get statistics for each group (such as count, mean, etc) using pandas GroupBy?

Please try this code

new_column=df[['col1', 'col2', 'col3', 'col4']].groupby(['col1', 'col2']).count()
df['count_it']=new_column
df

I think that code will add a column called 'count it' which count of each group

How many socket connections possible?

Realistically for an application, more then 4000-5000 open sockets on a single machine becomes impractical. Just checking for activity on all the sockets and managing them starts to become a performance issue - especially in real-time environments.

XAMPP Apache won't start

I am using Window 7 and It was same problem with me,I am using Skype and Not start Apache, but finally solved this problem, and It's working now

Check connection setting In Skype click tools -> click option -> click Advanced -> click connection Unchecked port number and click Save.

Android LinearLayout Gradient Background

With Kotlin you can do that in just 2 lines

Change color values in the array

                  val gradientDrawable = GradientDrawable(
                        GradientDrawable.Orientation.TOP_BOTTOM,
                        intArrayOf(Color.parseColor("#008000"),
                                   Color.parseColor("#ADFF2F"))
                    );
                    gradientDrawable.cornerRadius = 0f;

                   //Set Gradient
                   linearLayout.setBackground(gradientDrawable);

Result

enter image description here

HttpContext.Current.Session is null when routing requests

It seems that you have forgotten to add your state server address in the config file.

 <sessionstate mode="StateServer" timeout="20" server="127.0.0.1" port="42424" />

how to create 100% vertical line in css

As bookcasey said, height: 100%; will only make the DIV 100% of its parent. For this reason you will need to make html, body {height: 100%; min-height: 100%} as stated by Marko, but also, make the same change on every parent DIV of #menu.

Because you have a bottom border, then apply the right border to the parent DIV at height: 100%; and apply the bottom-border to your #menu at whatever height you want the bottom border to show up.

How to convert integer to char in C?

To convert int to char use:

int a=8;  
char c=a+'0';
printf("%c",c);       //prints 8  

To Convert char to int use:

char c='5';
int a=c-'0';
printf("%d",a);        //prints 5

Sorting a DropDownList? - C#, ASP.NET

If you are adding options to the dropdown one by one without a dataset and you want to sort it later after adding items, here's a solution:

DataTable dtOptions = new DataTable();
DataColumn[] dcColumns = { new DataColumn("Text", Type.GetType("System.String")), 
                           new DataColumn("Value", Type.GetType("System.String"))};
dtOptions.Columns.AddRange(dcColumns);
foreach (ListItem li in ddlOperation.Items)
{
   DataRow dr = dtOptions.NewRow();
   dr["Text"] = li.Text;
   dr["Value"] = li.Value;
   dtOptions.Rows.Add(dr);
}
DataView dv = dtOptions.DefaultView;
dv.Sort = "Text";
ddlOperation.Items.Clear();
ddlOperation.DataSource = dv;
ddlOperation.DataTextField = "Text";
ddlOperation.DataValueField = "Value";
ddlOperation.DataBind();

This would sort the dropdown items in alphabetical order.

How to fix 'Microsoft Excel cannot open or save any more documents'

I too encountered the same scenario and found out two solutions after googling for several times. Hope this helps.

Way 01:

Before trying to open the file in Excel, find it in Windows' File Explorer. Right-click the file and select Properties. At the bottom of the General tab, click the Unblock button. Once you unblock a file, Windows should remember and Excel should not ask you again. This option is available for some file types, but not others. If you don't have an Unblock button, use Way 2.

Way 02:

This option is better if you usually store your downloaded Excel files in one folder. In Excel, click File » Options » Trust Center » Trust Center Settings » Trusted Locations. Click Add new location. Browse to the folder where you store your Excel files, select Subfolders of this location are also trusted, and click OK.

How do I shut down a python simpleHTTPserver?

Hitting ctrl + c once(wait for traceback), then hitting ctrl+c again did the trick for me :)

How to calculate rolling / moving average using NumPy / SciPy?

If you just want a straightforward non-weighted moving average, you can easily implement it with np.cumsum, which may be is faster than FFT based methods:

EDIT Corrected an off-by-one wrong indexing spotted by Bean in the code. EDIT

def moving_average(a, n=3) :
    ret = np.cumsum(a, dtype=float)
    ret[n:] = ret[n:] - ret[:-n]
    return ret[n - 1:] / n

>>> a = np.arange(20)
>>> moving_average(a)
array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,  11.,
        12.,  13.,  14.,  15.,  16.,  17.,  18.])
>>> moving_average(a, n=4)
array([  1.5,   2.5,   3.5,   4.5,   5.5,   6.5,   7.5,   8.5,   9.5,
        10.5,  11.5,  12.5,  13.5,  14.5,  15.5,  16.5,  17.5])

So I guess the answer is: it is really easy to implement, and maybe numpy is already a little bloated with specialized functionality.

How do I do logging in C# without using 3rd party libraries?

If you are looking for a real simple way to log, you can use this one liner. If the file doesn't exist, it's created.

System.IO.File.AppendAllText(@"c:\log.txt", "mymsg\n");

Execute ssh with password authentication via windows command prompt

The sshpass utility is meant for exactly this. First, install sshpass by typing this command:

sudo apt-get install sshpass

Then prepend your ssh/scp command with

sshpass -p '<password>' <ssh/scp command>

This program is easiest to install when using Linux.

User should consider using SSH's more secure public key authentication (with the ssh command) instead.

How to implement a ConfigurationSection with a ConfigurationElementCollection

This is generic code for configuration collection :

public class GenericConfigurationElementCollection<T> :   ConfigurationElementCollection, IEnumerable<T> where T : ConfigurationElement, new()
{
    List<T> _elements = new List<T>();

    protected override ConfigurationElement CreateNewElement()
    {
        T newElement = new T();
        _elements.Add(newElement);
        return newElement;
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return _elements.Find(e => e.Equals(element));
    }

    public new IEnumerator<T> GetEnumerator()
    {
        return _elements.GetEnumerator();
    }
}

After you have GenericConfigurationElementCollection, you can simple use it in the config section (this is an example from my Dispatcher):

public class  DispatcherConfigurationSection: ConfigurationSection
{
    [ConfigurationProperty("maxRetry", IsRequired = false, DefaultValue = 5)]
    public int MaxRetry
    {
        get
        {
            return (int)this["maxRetry"];
        }
        set
        {
            this["maxRetry"] = value;
        }
    }

    [ConfigurationProperty("eventsDispatches", IsRequired = true)]
    [ConfigurationCollection(typeof(EventsDispatchConfigurationElement), AddItemName = "add", ClearItemsName = "clear", RemoveItemName = "remove")]
    public GenericConfigurationElementCollection<EventsDispatchConfigurationElement> EventsDispatches
    {
        get { return (GenericConfigurationElementCollection<EventsDispatchConfigurationElement>)this["eventsDispatches"]; }
    }
}

The Config Element is config Here:

public class EventsDispatchConfigurationElement : ConfigurationElement
{
    [ConfigurationProperty("name", IsRequired = true)]
    public string Name
    {
        get
        {
            return (string) this["name"];
        }
        set
        {
            this["name"] = value;
        }
    }
}

The config file would look like this:

<?xml version="1.0" encoding="utf-8" ?>
  <dispatcherConfigurationSection>
    <eventsDispatches>
      <add name="Log" ></add>
      <add name="Notification" ></add>
      <add name="tester" ></add>
    </eventsDispatches>
  </dispatcherConfigurationSection>

Hope it help !

Can you delete data from influxdb?

You can only delete with your time field, which is a number.

Delete from <measurement> where time=123456

will work. Remember not to give single quotes or double quotes. Its a number.

How to change color and font on ListView

You need to create a CustomListAdapter.

public class CustomListAdapter extends ArrayAdapter <String> {

    private Context mContext;
    private int id;
    private List <String>items ;

    public CustomListAdapter(Context context, int textViewResourceId , List<String> list ) 
    {
        super(context, textViewResourceId, list);           
        mContext = context;
        id = textViewResourceId;
        items = list ;
    }

    @Override
    public View getView(int position, View v, ViewGroup parent)
    {
        View mView = v ;
        if(mView == null){
            LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            mView = vi.inflate(id, null);
        }

        TextView text = (TextView) mView.findViewById(R.id.textView);

        if(items.get(position) != null )
        {
            text.setTextColor(Color.WHITE);
            text.setText(items.get(position));
            text.setBackgroundColor(Color.RED); 
            int color = Color.argb( 200, 255, 64, 64 );
                text.setBackgroundColor( color );

        }

        return mView;
    }

}

The list item looks like this (custom_list.xml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content">
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/textView"
    android:textSize="20px" android:paddingTop="10dip" android:paddingBottom="10dip"/>
</LinearLayout>

Use the TextView api's to decorate your text to your liking

and you will be using it like this

listAdapter = new CustomListAdapter(YourActivity.this , R.layout.custom_list , mList);
mListView.setAdapter(listAdapter);

Timeout function if it takes too long to finish

I rewrote David's answer using the with statement, it allows you do do this:

with timeout(seconds=3):
    time.sleep(4)

Which will raise a TimeoutError.

The code is still using signal and thus UNIX only:

import signal

class timeout:
    def __init__(self, seconds=1, error_message='Timeout'):
        self.seconds = seconds
        self.error_message = error_message
    def handle_timeout(self, signum, frame):
        raise TimeoutError(self.error_message)
    def __enter__(self):
        signal.signal(signal.SIGALRM, self.handle_timeout)
        signal.alarm(self.seconds)
    def __exit__(self, type, value, traceback):
        signal.alarm(0)

PostgreSQL error: Fatal: role "username" does not exist

Installing postgres using apt-get does not create a user role or a database.

To create a superuser role and a database for your personal user account:

sudo -u postgres createuser -s $(whoami); createdb $(whoami)

Visual Studio loading symbols

In my case Visual Studio was looking for 3rd-party PDBs in paths that, on my machine, referenced an optical drive. Without a disc in the tray it took about Windows about ~30 to fail, which in turn slowed down Visual Studio as it tried to load the PDBs from that location. More detail is available in my complete answer here: https://stackoverflow.com/a/17457581/85196

Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS

< one-way binding

= two-way binding

& function binding

@ pass only strings

What is a typedef enum in Objective-C?

A typedef allows the programmer to define one Objective-C type as another. For example,

typedef int Counter; defines the type Counter to be equivalent to the int type. This drastically improves code readability.

Why I am getting Cannot pass parameter 2 by reference error when I am using bindParam with a constant value?

If you want to insert NULL only when the value is empty or '', but insert the value when it is available.

A) Receives the form data using POST method, and calls function insert with those values.

insert( $_POST['productId'], // Will be set to NULL if empty    
        $_POST['productName'] ); // Will be to NULL if empty                                

B) Evaluates if a field was not filled up by the user, and inserts NULL if that's the case.

public function insert( $productId, $productName )
{ 
    $sql = "INSERT INTO products (  productId, productName ) 
                VALUES ( :productId, :productName )";

    //IMPORTANT: Repace $db with your PDO instance
    $query = $db->prepare($sql); 

    //Works with INT, FLOAT, ETC.
    $query->bindValue(':productId',  !empty($productId)   ? $productId   : NULL, PDO::PARAM_INT); 

    //Works with strings.
    $query->bindValue(':productName',!empty($productName) ? $productName : NULL, PDO::PARAM_STR);   

    $query->execute();      
}

For instance, if the user doesn't input anything on the productName field of the form, then $productName will be SET but EMPTY. So, you need check if it is empty(), and if it is, then insert NULL.

Tested on PHP 5.5.17

Good luck,

Unable to Cast from Parent Class to Child Class

You can't cast a mammal into a dog - it might be a cat.

You can't cast a food into a sandwich - it might be a cheeseburger.

You can't cast a car into a Ferrari - it might be a Honda, or more specifically, You can't cast a Ferrari 360 Modena to a Ferrari 360 Challange Stradale - there are differnt parts, even though they are both Ferrari 360s.

Video 100% width and height

You can use Javascript to dynamically set the height to 100% of the window and then center it using a negative left margin based on the ratio of video width to window width.

http://jsfiddle.net/RfV5C/

var $video  = $('video'),
    $window = $(window); 

$(window).resize(function(){
    var height = $window.height();
    $video.css('height', height);

    var videoWidth = $video.width(),
        windowWidth = $window.width(),
    marginLeftAdjust =   (windowWidth - videoWidth) / 2;

    $video.css({
        'height': height, 
        'marginLeft' : marginLeftAdjust
    });
}).resize();

Mask for an Input to allow phone numbers?

Combining Günter Zöchbauer's answer with good-old vanilla-JS, here is a directive with two lines of logic that supports (123) 456-7890 format.

Reactive Forms: Plunk

import { Directive, Output, EventEmitter } from "@angular/core";
import { NgControl } from "@angular/forms";

@Directive({
  selector: '[formControlName][phone]',
  host: {
    '(ngModelChange)': 'onInputChange($event)'
  }
})
export class PhoneMaskDirective {

  @Output() rawChange:EventEmitter<string> = new EventEmitter<string>();

  constructor(public model: NgControl) {}

  onInputChange(value) {
        var x = value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
        var y = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');

        this.model.valueAccessor.writeValue(y);
        this.rawChange.emit(rawValue); 
  }
}

Template-driven Forms: Plunk

import { Directive } from "@angular/core";
import { NgControl } from "@angular/forms";

@Directive({
  selector: '[ngModel][phone]',
  host: {
    '(ngModelChange)': 'onInputChange($event)'
  }
})
export class PhoneMaskDirective {

  constructor(public model: NgControl) {}

  onInputChange(value) {
        var x = value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
        value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');

        this.model.valueAccessor.writeValue(value);       
  }
}

What exactly is Python's file.flush() doing?

Basically, flush() cleans out your RAM buffer, its real power is that it lets you continue to write to it afterwards - but it shouldn't be thought of as the best/safest write to file feature. It's flushing your RAM for more data to come, that is all. If you want to ensure data gets written to file safely then use close() instead.

How can I "disable" zoom on a mobile web page?

Possible Solution for Web Apps: While zooming can not be disabled in iOS Safari anymore, it will be disabled when opening the site from a home screen shortcut.

Add these meta tags to declare your App as "Web App capable":

    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" >
    <meta name="apple-mobile-web-app-capable" content="yes" >

However only use this feature if your app is self sustaining, as the forward/backward buttons and URL bar as well as the sharing options are disabled. (You can still swipe left and right though) This approach however enables quite the app like ux. The fullscreen browser only starts when the site is loaded from the homescreen. I also only got it to work after I included an apple-touch-icon-180x180.png in my root folder.

As a bonus, you probably also want to include a variant of this as well:

<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

How can I start InternetExplorerDriver using Selenium WebDriver

1---Enable protected mode for all zones You need to enable protected mode for all zones from Internet Options -> Security tab. To enable protected mode for all zones

Open Internet Explorer browser.
Go to menu Tools -> Internet Options.
Click on Security tab.
Select Internet from "Select a zone to view or change security settings" and Select(check) check box "Enable Protected Mode" from In the "Security level for this zone" block .
Apply same thing for all other 3 zones -> Local Internet, Trusted Sites and Restricted Sites

This setting will resolve error related to "Protected Mode settings are not the same for all zones.

2-- Set IE browser's zoom level 100%

Open Internet Explorer browser.
Go to menu View -> Zoom -> Select 100%

How to open maximized window with Javascript?

Checkout this jquery window plugin: http://fstoke.me/jquery/window/

// create a window
sampleWnd = $.window({
   .....
});

// resize the window by passed w,h parameter
sampleWnd.resize(screen.width, screen.height);

How to debug JavaScript / jQuery event bindings with Firebug or similar tools?

Using DevTools in the latest Chrome (v29) I find these two tips very helpful for debugging events:

  1. Listing jQuery events of the last selected DOM element

    • Inspect an element on the page
    • type the following in the console:

      $._data($0, "events") //assuming jQuery 1.7+

    • It will list all jQuery event objects associated with it, expand the interested event, right-click on the function of the "handler" property and choose "Show function definition". It will open the file containing the specified function.

  2. Utilizing the monitorEvents() command

What is the difference between buffer and cache memory in Linux?

Explained by Red Hat:

Cache Pages:

A cache is the part of the memory which transparently stores data so that future requests for that data can be served faster. This memory is utilized by the kernel to cache disk data and improve i/o performance.

The Linux kernel is built in such a way that it will use as much RAM as it can to cache information from your local and remote filesystems and disks. As the time passes over various reads and writes are performed on the system, kernel tries to keep data stored in the memory for the various processes which are running on the system or the data that of relevant processes which would be used in the near future. The cache is not reclaimed at the time when process get stop/exit, however when the other processes requires more memory then the free available memory, kernel will run heuristics to reclaim the memory by storing the cache data and allocating that memory to new process.

When any kind of file/data is requested then the kernel will look for a copy of the part of the file the user is acting on, and, if no such copy exists, it will allocate one new page of cache memory and fill it with the appropriate contents read out from the disk.

The data that is stored within a cache might be values that have been computed earlier or duplicates of original values that are stored elsewhere in the disk. When some data is requested, the cache is first checked to see whether it contains that data. The data can be retrieved more quickly from the cache than from its source origin.

SysV shared memory segments are also accounted as a cache, though they do not represent any data on the disks. One can check the size of the shared memory segments using ipcs -m command and checking the bytes column.

Buffers:

Buffers are the disk block representation of the data that is stored under the page caches. Buffers contains the metadata of the files/data which resides under the page cache. Example: When there is a request of any data which is present in the page cache, first the kernel checks the data in the buffers which contain the metadata which points to the actual files/data contained in the page caches. Once from the metadata the actual block address of the file is known, it is picked up by the kernel for processing.

HTML form submit to PHP script

<form method="POST" action="chk_kw.php">
    <select name="website_string"> 
        <option selected="selected"></option>
        <option value="abc">abc</option>
        <option value="def">def</option>
        <option value="hij">hij</option>   
    </select>
    <input type="submit">
</form>


  • As your form gets more complex, you can a quick check at top of your php script using print_r($_POST);, it'll show what's being submitted an the respective element name.
  • To get the submitted value of the element in question do:

    $website_string = $_POST['website_string'];

How to sort a data frame by date

You can use order() to sort date data.

# Sort date ascending order
d[order(as.Date(d$V3, format = "%d/%m/%Y")),]

# Sort date descending order
d[rev(order(as.Date(d$V3, format = "%d/%m/%y"))),]

Hope this helps,

Link to my quora answer https://qr.ae/TWngCe

Thanks

Check Whether a User Exists

I was using it in that way:

if [ $(getent passwd $user) ] ; then
        echo user $user exists
else
        echo user $user doesn\'t exists
fi

Java null check why use == instead of .equals()

They're two completely different things. == compares the object reference, if any, contained by a variable. .equals() checks to see if two objects are equal according to their contract for what equality means. It's entirely possible for two distinct object instances to be "equal" according to their contract. And then there's the minor detail that since equals is a method, if you try to invoke it on a null reference, you'll get a NullPointerException.

For instance:

class Foo {
    private int data;

    Foo(int d) {
        this.data = d;
    }

    @Override
    public boolean equals(Object other) {
        if (other == null || other.getClass() != this.getClass()) {
           return false;
        }
        return ((Foo)other).data == this.data;
    }

    /* In a real class, you'd override `hashCode` here as well */
}

Foo f1 = new Foo(5);
Foo f2 = new Foo(5);
System.out.println(f1 == f2);
// outputs false, they're distinct object instances

System.out.println(f1.equals(f2));
// outputs true, they're "equal" according to their definition

Foo f3 = null;
System.out.println(f3 == null);
// outputs true, `f3` doesn't have any object reference assigned to it

System.out.println(f3.equals(null));
// Throws a NullPointerException, you can't dereference `f3`, it doesn't refer to anything

System.out.println(f1.equals(f3));
// Outputs false, since `f1` is a valid instance but `f3` is null,
// so one of the first checks inside the `Foo#equals` method will
// disallow the equality because it sees that `other` == null

How to remove a virtualenv created by "pipenv run"

I know that question is a bit old but

In root of project where Pipfile is located you could run

pipenv --venv

which returns

/Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU

and then remove this env by typing

rm -rf /Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU

How to synchronize or lock upon variables in Java?

Use the synchronized keyword.

class sample {
    private String msg=null;

    public synchronized void newmsg(String x){
        msg=x;
    }

    public synchronized string getmsg(){
        String temp=msg;
        msg=null;
        return msg;
    }
}

Using the synchronized keyword on the methods will require threads to obtain a lock on the instance of sample. Thus, if any one thread is in newmsg(), no other thread will be able to get a lock on the instance of sample, even if it were trying to invoke getmsg().

On the other hand, using synchronized methods can become a bottleneck if your methods perform long-running operations - all threads, even if they want to invoke other methods in that object that could be interleaved, will still have to wait.

IMO, in your simple example, it's ok to use synchronized methods since you actually have two methods that should not be interleaved. However, under different circumstances, it might make more sense to have a lock object to synchronize on, as shown in Joh Skeet's answer.

nginx: how to create an alias url route?

server {
  server_name example.com;
  root /path/to/root;
  location / {
    # bla bla
  }
  location /demo {
    alias /path/to/root/production/folder/here;
  }
}

If you need to use try_files inside /demo you'll need to replace alias with a root and do a rewrite because of the bug explained here

Comparing two hashmaps for equal values and same key sets?

if you have two maps lets say map1 and map2 then using java8 Streams,we can compare maps using code below.But it is recommended to use equals rather then != or ==

boolean b = map1.entrySet().stream().filter(value -> 
            map2.entrySet().stream().anyMatch(value1 -> 
            (value1.getKey().equals(value.getKey()) && 
  value1.getValue().equals(value.getValue())))).findAny().isPresent();   


System.out.println("comparison  "+b);

Post a json object to mvc controller with jquery and ajax

What am I doing incorrectly?

You have to convert html to javascript object, and then as a second step to json throug JSON.Stringify.

How can I receive a json object in the controller?

View:

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://raw.githubusercontent.com/marioizquierdo/jquery.serializeJSON/master/jquery.serializejson.js"></script>

var obj = $("#form1").serializeJSON({ useIntKeysAsArrayIndex: true });
$.post("http://localhost:52161/Default/PostRawJson/", { json: JSON.stringify(obj) });

<form id="form1" method="post">
<input name="OrderDate" type="text" /><br />
<input name="Item[0][Id]" type="text" /><br />
<input name="Item[1][Id]" type="text" /><br />
<button id="btn" onclick="btnClick()">Button</button>
</form>

Controller:

public void PostRawJson(string json)
{
    var order = System.Web.Helpers.Json.Decode(json);
    var orderDate = order.OrderDate;
    var secondOrderId = order.Item[1].Id;
}

nodeJs callbacks simple example

A callback is a function passed as an parameter to a Higher Order Function (wikipedia). A simple implementation of a callback would be:

const func = callback => callback('Hello World!');

To call the function, simple pass another function as argument to the function defined.

func(string => console.log(string));

Spring Boot Rest Controller how to return different HTTP status codes?

There are different ways to return status code, 1 : RestController class should extends BaseRest class, in BaseRest class we can handle exception and return expected error codes. for example :

@RestController
@RequestMapping
class RestController extends BaseRest{

}

@ControllerAdvice
public class BaseRest {
@ExceptionHandler({Exception.class,...})
    @ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR)
    public ErrorModel genericError(HttpServletRequest request, 
            HttpServletResponse response, Exception exception) {
        
        ErrorModel error = new ErrorModel();
        resource.addError("error code", exception.getLocalizedMessage());
        return error;
    }

How to keep :active css style after clicking an element

I FIGURED IT OUT. SIMPLE, EFFECTIVE NO jQUERY

We're going to to be using a hidden checkbox.
This example includes one "on click - off click 'hover / active' state"

--

To make content itself clickable:

_x000D_
_x000D_
#activate-div{display:none}

.my-div{background-color:#FFF}

#activate-div:checked ~ label
.my-div{background-color:#000}
_x000D_
<input type="checkbox" id="activate-div">
<label for="activate-div">
  <div class="my-div">
    //MY DIV CONTENT
  </div>
</label>
_x000D_
_x000D_
_x000D_

To make button change content:

_x000D_
_x000D_
#activate-div{display:none}

.my-div{background-color:#FFF}

#activate-div:checked +
.my-div{background-color:#000}
_x000D_
<input type="checkbox" id="activate-div">
<div class="my-div">
  //MY DIV CONTENT
</div>

<label for="activate-div">
  //MY BUTTON STUFF
</label>
_x000D_
_x000D_
_x000D_

Hope it helps!!

jQuery - on change input text

Seems to me like you are updating the value of the text field in javascript. onchange event will be triggered only when you key-in data and tab out of the text field.

One workaround is to trigger the textbox change event when modifying the textbox value from the script. See below,

$("#kat").change(function(){ 
    alert("Hello");
});


$('<tab_cell>').click (function () {
   $('#kat')
      .val($(this).text()) //updating the value of the textbox 
      .change();           //trigger change event.
});

VBA setting the formula for a cell

If Cells(1, 1).Formula gives a 1004 error, like in my case, changes it to:

Cells(1, 1).FormulaLocal

vertical-align: middle with Bootstrap 2

i use this

<style>
html, body{height:100%;margin:0;padding:0 0} 
.container-fluid{height:100%;display:table;width:100%;padding-right:0;padding-left: 0}   
.row-fluid{height:100%;display:table-cell;vertical-align:middle;width:100%}
.centering{float:none;margin:0 auto} 
</style>
<body>
<div class="container-fluid">
     <div class="row-fluid">
     <div class="offset3 span6 centering">
            content here
         </div>
    </div>
 </div>
</body>

How can I programmatically invoke an onclick() event from a anchor tag while keeping the ‘this’ reference in the onclick function?

To trigger an event you basically just call the event handler for that element. Slight change from your code.

var a = document.getElementById("element");
var evnt = a["onclick"];

if (typeof(evnt) == "function") {
    evnt.call(a);
}

How do I enable the column selection mode in Eclipse?

  • Press Alt + Shift + A
  • Observe that the screen zooms out
  • Make selection using the mouse
  • Press Alt + Shift + A to go back to the old mode. enter image description here

Invalid http_host header

settings.py

ALLOWED_HOSTS = ['*']

Seaborn plots not showing up

My advice is just to give a

plt.figure() and give some sns plot. For example

sns.distplot(data).

Though it will look it doesnt show any plot, When you maximise the figure, you will be able to see the plot.

Determining type of an object in ruby

Oftentimes in Ruby, you don't actually care what the object's class is, per se, you just care that it responds to a certain method. This is known as Duck Typing and you'll see it in all sorts of Ruby codebases.

So in many (if not most) cases, its best to use Duck Typing using #respond_to?(method):

object.respond_to?(:to_i)

How to ignore SSL certificate errors in Apache HttpClient 4.0

Tested with HttpClient 4.5.5 with Fluent API

final SSLContext sslContext = new SSLContextBuilder()
    .loadTrustMaterial(null, (x509CertChain, authType) -> true).build();

CloseableHttpClient httpClient = HttpClients.custom()
    .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
    .setSSLContext(sslContext).build();

String result = Executor.newInstance(httpClient)
    .execute(Request.Get("https://localhost:8080/someapi")
    .connectTimeout(1000).socketTimeout(1000))
    .returnContent().asString();

Read only the first line of a file?

Use the .readline() method (Python 2 docs, Python 3 docs):

with open('myfile.txt') as f:
    first_line = f.readline()

Some notes:

  1. As noted in the docs, unless it is the only line in the file, the string returned from f.readline() will contain a trailing newline. You may wish to use f.readline().strip() instead to remove the newline.
  2. The with statement automatically closes the file again when the block ends.
  3. The with statement only works in Python 2.5 and up, and in Python 2.5 you need to use from __future__ import with_statement
  4. In Python 3 you should specify the file encoding for the file you open. Read more...

jQuery's .on() method combined with the submit event

I had a problem with the same symtoms. In my case, it turned out that my submit function was missing the "return" statement.

For example:

 $("#id_form").on("submit", function(){
   //Code: Action (like ajax...)
   return false;
 })

PHP's array_map including keys

This is how I've implemented this in my project.

function array_map_associative(callable $callback, $array) {
    /* map original array keys, and call $callable with $key and value of $key from original array. */
    return array_map(function($key) use ($callback, $array){
        return $callback($key, $array[$key]);
    }, array_keys($array));
}

React passing parameter via onclick event using ES6 syntax

I am using React-Bootstrap. The onSelect trigger for dropdowns were not allowing me to pass data. Just the event. So remember you can just set any values as attributes and pick them up from the function using javascript. Picking up those attributes you set in that event target.

    let currentTarget = event.target;
    let currentId = currentTarget.getAttribute('data-id');
    let currentValue = currentTarget.getAttribute('data-value');

What command shows all of the topics and offsets of partitions in Kafka?

Kafka ships with some tools you can use to accomplish this.

List topics:

# ./bin/kafka-topics.sh --list --zookeeper localhost:2181
test_topic_1
test_topic_2
...

List partitions and offsets:

# ./bin/kafka-run-class.sh kafka.tools.ConsumerOffsetChecker --broker-info --group test_group --topic test_topic --zookeeper localhost:2181
Group           Topic                  Pid Offset          logSize         Lag             Owner
test_group      test_topic             0   698020          698021          1              test_group-0
test_group      test_topic             1   235699          235699          0               test_group-1
test_group      test_topic             2   117189          117189          0               test_group-2

Update for 0.9 (and higher) consumer APIs

If you're using the new apis, there's a new tool you can use: kafka-consumer-groups.sh.

./bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group count_errors --describe
GROUP                          TOPIC                          PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             OWNER
count_errors                   logs                           2          2908278         2908278         0               consumer-1_/10.8.0.55
count_errors                   logs                           3          2907501         2907501         0               consumer-1_/10.8.0.43
count_errors                   logs                           4          2907541         2907541         0               consumer-1_/10.8.0.177
count_errors                   logs                           1          2907499         2907499         0               consumer-1_/10.8.0.115
count_errors                   logs                           0          2907469         2907469         0               consumer-1_/10.8.0.126

Find package name for Android apps to use Intent to launch Market app from web

It depends where exactly you want to get the information from. You have a bunch of options:

  • If you have a copy of the .apk, it's just a case of opening it as a zip file and looking at the AndroidManifest.xml file. The top level <manifest> element will have a package attribute.
  • If you have the app installed on a device and can connect using adb, you can launch adb shell and execute pm list packages -f, which shows the package name for each installed apk.
  • If you just want to manually find a couple of package names, you can search for the app on http://www.cyrket.com/m/android/, and the package name is shown in the URL
  • You can also do it progmatically from an Android app using the PackageManager

Once you've got the package name, you simply link to market://search?q=pname:<package_name> or http://market.android.com/search?q=pname:<package_name>. Both will open the market on an Android device; the latter obviously has the potential to work on other hardware as well (it doesn't at the minute).

How to access form methods and controls from a class in C#?

I'm relatively new to c# and brand new to stackoverflow. Anyway, regarding the question on how to access controls on a form from a class: I just used the ControlCollection (Controls) class of the form.

        //Add a new form called frmEditData to project.
        //Draw a textbox on it named txtTest; set the text to
        //something in design as a test.
        Form frmED =  new frmEditData();
        MessageBox.Show(frmED.Controls["txtTest"].Text);

Worked for me, maybe it will be of assistance in both questions.

Git says remote ref does not exist when I delete remote branch

git push origin --delete origin/test 

should work as well

Pandas group-by and sum

Both the other answers accomplish what you want.

You can use the pivot functionality to arrange the data in a nice table

df.groupby(['Fruit','Name'],as_index = False).sum().pivot('Fruit','Name').fillna(0)



Name    Bob     Mike    Steve   Tom    Tony
Fruit                   
Apples  16.0    9.0     10.0    0.0     0.0
Grapes  35.0    0.0     0.0     87.0    15.0
Oranges 67.0    57.0    0.0     15.0    1.0

join on multiple columns

tableB.col1 = tableA.col1 
OR tableB.col2 = tableA.col1  
OR tableB.col1 = tableA.col2  
OR tableB.col1 = tableA.col2

How to find elements by class

Concerning @Wernight's comment on the top answer about partial matching...

You can partially match:

  • <div class="stylelistrow"> and
  • <div class="stylelistrow button">

with gazpacho:

from gazpacho import Soup

my_divs = soup.find("div", {"class": "stylelistrow"}, partial=True)

Both will be captured and returned as a list of Soup objects.

Return value in a Bash function

The return statement sets the exit code of the function, much the same as exit will do for the entire script.

The exit code for the last command is always available in the $? variable.

function fun1(){
  return 34
}

function fun2(){
  local res=$(fun1)
  echo $? # <-- Always echos 0 since the 'local' command passes.

  res=$(fun1)
  echo $?  #<-- Outputs 34
}

Create new project on Android, Error: Studio Unknown host 'services.gradle.org'

I tried above answers and they didn't help in my case.

I solved it with this link help: http://vjscrazzy.blogspot.co.il/2016/02/failed-to-sync-gradle-project.html

step 1) file>Setttings>appearance and behaviour> system setttings>HTTP proxy> set No Proxy

step 2) build,execution and deployment> Build tools > gradle> now under project level settings > select local gradle distribution> gradle home = F:/Program Files/Android/Android Studio/gradle/gradle-2.4

After that, I did these changes(because it still wrote me some other errors)

Android Studio asked me:

  1. Android Studio asked me to update my Gradle version (which he didn't before)

  2. Enable - Tools> Android> Enable ADB integration.

Also, if your working in a team with repositories, it's important to check that the version of the Andorid Studio is the same.

Using putty to scp from windows to Linux

Use scp priv_key.pem source user@host:target if you need to connect using a private key.

or if using pscp then use pscp -i priv_key.ppk source user@host:target

Transport endpoint is not connected

There is a segmentation fault problem which was introduced in 0.1.39. You may check my repository that fixed this one in meanwhile: https://github.com/vdudouyt/mhddfs-nosegfault

line breaks in a textarea

Some wrong answers are posted here. instead of replacing \n to <br />, they are replacing <br /> to \n

So here is a good answer to store <br /> in your mysql when you entered in textarea:

str_replace("\n", '<br />',  $textarea);

List files committed for a revision

svn log --verbose -r 42

How to filter by string in JSONPath?

Your query looks fine, and your data and query work for me using this JsonPath parser. Also see the example queries on that page for more predicate examples.

The testing tool that you're using seems faulty. Even the examples from the JsonPath site are returning incorrect results:

e.g., given:

{
    "store":
    {
        "book":
        [ 
            { "category": "reference",
              "author": "Nigel Rees",
              "title": "Sayings of the Century",
              "price": 8.95
            },
            { "category": "fiction",
              "author": "Evelyn Waugh",
              "title": "Sword of Honour",
              "price": 12.99
            },
            { "category": "fiction",
              "author": "Herman Melville",
              "title": "Moby Dick",
              "isbn": "0-553-21311-3",
              "price": 8.99
            },
            { "category": "fiction",
              "author": "J. R. R. Tolkien",
              "title": "The Lord of the Rings",
              "isbn": "0-395-19395-8",
              "price": 22.99
            }
        ],
        "bicycle":
        {
            "color": "red",
            "price": 19.95
        }
    }
}

And the expression: $.store.book[?(@.length-1)].title, the tool returns a list of all titles.

Why am I getting a " Traceback (most recent call last):" error?

At the beginning of your file you set raw_input to 0. Do not do this, at it modifies the built-in raw_input() function. Therefore, whenever you call raw_input(), it is essentially calling 0(), which raises the error. To remove the error, remove the first line of your code:

M = 1.6
# Miles to Kilometers 
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54


def intro():
    print("Welcome! This program will convert measures for you.")
    main()

def main():
    print("Select operation.")
    print("1.Miles to Kilometers")
    print("2.Fahrenheit to Celsius")
    print("3.Gallons to liters")
    print("4.Pounds to kilograms")
    print("5.Inches to centimeters")

    choice = input("Enter your choice by number: ")

    if choice == '1':
        convertMK()

    elif choice == '2':
        converCF()

    elif choice == '3':
        convertGL()

    elif choice == '4':
        convertPK()

    elif choice == '5':
        convertPK()

    else:
        print("Error")


def convertMK():
    input_M = float(raw_input(("Miles: ")))
    M_conv = (M) * input_M
    print("Kilometers: %f\n" % M_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def converCF():
    input_F = float(raw_input(("Fahrenheit: ")))
    F_conv = (input_F - 32) * 5/9
    print("Celcius: %f\n") % F_conv
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def convertGL():
    input_G = float(raw_input(("Gallons: ")))
    G_conv = input_G * 3.6
    print("Centimeters: %f\n" % G_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertPK():
    input_P = float(raw_input(("Pounds: ")))
    P_conv = input_P * 0.45
    print("Centimeters: %f\n" % P_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertIC():
    input_cm = float(raw_input(("Inches: ")))
    inches_conv = input_cm * 2.54
    print("Centimeters: %f\n" % inches_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def end():
    print("This program will close.")
    exit()

intro()

How to determine whether a given Linux is 32 bit or 64 bit?

lscpu will list out these among other information regarding your CPU:

Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
...

'cout' was not declared in this scope

Put the following code before int main():

using namespace std;

And you will be able to use cout.

For example:

#include<iostream>
using namespace std;
int main(){
    char t = 'f';
    char *t1;
    char **t2;
    cout<<t;        
    return 0;
}

Now take a moment and read up on what cout is and what is going on here: http://www.cplusplus.com/reference/iostream/cout/


Further, while its quick to do and it works, this is not exactly a good advice to simply add using namespace std; at the top of your code. For detailed correct approach, please read the answers to this related SO question.

Returning a regex match in VBA (excel)

You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).

For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.

Function ExtractSDI(ByVal text As String) As String

Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)

If allMatches.count <> 0 Then
    result = allMatches.Item(0).submatches.Item(0)
End If

ExtractSDI = result

End Function

If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:

Ex) =RegexExtract(A1, "(sdi \d+)", ", ")

Here is:

Function RegexExtract(ByVal text As String, _
                      ByVal extract_what As String, _
                      Optional seperator As String = "") As String

Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)

For i = 0 To allMatches.count - 1
    For j = 0 To allMatches.Item(i).submatches.count - 1
        result = result & seperator & allMatches.Item(i).submatches.Item(j)
    Next
Next

If Len(result) <> 0 Then
    result = Right(result, Len(result) - Len(seperator))
End If

RegexExtract = result

End Function

*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.

How to call a function after a div is ready?

To do something after certain div load from function .load(). I think this exactly what you need:

  $('#divIDer').load(document.URL +  ' #divIDer',function() {

       // call here what you want .....


       //example
       $('#mydata').show();
  });

Flutter: Setting the height of the AppBar

You can use the toolbarHeight property of Appbar, it does exactly what you want.

SQL Server IN vs. EXISTS Performance

Off the top of my head and not guaranteed to be correct: I believe the second will be faster in this case.

  1. In the first, the correlated subquery will likely cause the subquery to be run for each row.
  2. In the second example, the subquery should only run once, since not correlated.
  3. In the second example, the IN will short-circuit as soon as it finds a match.

What data type to use for money in Java?

I would use Joda Money

It's still at version 0.6 but looks very promising

Check if current date is between two dates Oracle SQL

TSQL: Dates- need to look for gaps in dates between Two Date

select
distinct
e1.enddate,
e3.startdate,
DATEDIFF(DAY,e1.enddate,e3.startdate)-1 as [Datediff]
from #temp e1 
   join #temp e3 on e1.enddate < e3.startdate          
       /* Finds the next start Time */
and e3.startdate = (select min(startdate) from #temp e5
where e5.startdate > e1.enddate)
and not exists (select *  /* Eliminates e1 rows if it is overlapped */
from #temp e5 
where e5.startdate < e1.enddate and e5.enddate > e1.enddate);

PHP - remove all non-numeric characters from a string

You can use preg_replace in this case;

$res = preg_replace("/[^0-9]/", "", "Every 6 Months" );

$res return 6 in this case.

If want also to include decimal separator or thousand separator check this example:

$res = preg_replace("/[^0-9.]/", "", "$ 123.099");

$res returns "123.099" in this case

Include period as decimal separator or thousand separator: "/[^0-9.]/"

Include coma as decimal separator or thousand separator: "/[^0-9,]/"

Include period and coma as decimal separator and thousand separator: "/[^0-9,.]/"

How do I detect if I am in release or debug mode?

Yes, you will have no problems using:

if (BuildConfig.DEBUG) {
   //It's not a release version.
}

Unless you are importing the wrong BuildConfig class. Make sure you are referencing your project's BuildConfig class, not from any of your dependency libraries.

enter image description here

Shell script : How to cut part of a string

Assuming input of

{Anything}id={ID}{space}{Anything} 
{Anything}id={ID}{space}{Anything}

--

#! /bin/sh
while read s; do
   rhs=${s##*id=}
   id=${rhs%% *}
   echo $id # Do what you will with $id here
done <so.txt 

Or if it's always the 7th field

#! /bin/sh
while read f1 f2 f3 f4 f5 f6 f7 rest
do
echo ${f7##id=}
done <so.txt

See Also

Shell Parameter Expansion

Fastest way to serialize and deserialize .NET objects

You can try Salar.Bois serializer which has a decent performance. Its focus is on payload size but it also offers good performance.

There are benchmarks in the Github page if you wish to see and compare the results by yourself.

https://github.com/salarcode/Bois

Sass .scss: Nesting and multiple classes?

You can use the parent selector reference &, it will be replaced by the parent selector after compilation:

For your example:

.container {
    background:red;
    &.desc{
       background:blue;
    }
}

/* compiles to: */
.container {
    background: red;
}
.container.desc {
    background: blue;
}

The & will completely resolve, so if your parent selector is nested itself, the nesting will be resolved before replacing the &.

This notation is most often used to write pseudo-elements and -classes:

.element{
    &:hover{ ... }
    &:nth-child(1){ ... }
}

However, you can place the & at virtually any position you like*, so the following is possible too:

.container {
    background:red;
    #id &{
       background:blue;
    }
}

/* compiles to: */
.container {
    background: red;
}
#id .container {
    background: blue;
}

However be aware, that this somehow breaks your nesting structure and thus may increase the effort of finding a specific rule in your stylesheet.

*: No other characters than whitespaces are allowed in front of the &. So you cannot do a direct concatenation of selector+& - #id& would throw an error.

Get sum of MySQL column in PHP

MySQL 5.6 (LAMP) . column_value is the column you want to add up. table_name is the table.

Method #1

$qry = "SELECT column_value AS count
        FROM table_name ";

$res = $db->query($qry);

$total = 0;
while ($rec = $db->fetchAssoc($res)) {
    $total += $rec['count'];
}
echo "Total: " . $total . "\n";

Method #2

$qry = "SELECT SUM(column_value) AS count 
        FROM table_name ";

$res = $db->query($qry);

$total = 0;
$rec = $db->fetchAssoc($res);
$total = $rec['count'];

echo "Total: " . $total . "\n";

Method #3 -SQLi

$qry = "SELECT SUM(column_value) AS count 
        FROM table_name ";

$res = $conn->query($sql);

$total = 0;
$rec = row = $res->fetch_assoc();
$total = $rec['count'];

echo "Total: " . $total . "\n";

Method #4: Depreciated (don't use)

$res = mysql_query('SELECT SUM(column_value) AS count FROM table_name'); 
$row = mysql_fetch_assoc($res); 
$sum = $row['count'];

Converting from Integer, to BigInteger

The method you want is BigInteger#valueOf(long val).

E.g.,

BigInteger bi = BigInteger.valueOf(myInteger.intValue());

Making a String first is unnecessary and undesired.

Conditionally Remove Dataframe Rows with R

Use the which function:

A <- c('a','a','b','b','b')
B <- c(1,0,1,1,0)
d <- data.frame(A, B)

r <- with(d, which(B==0, arr.ind=TRUE))
newd <- d[-r, ]

C# Syntax - Split String into Array by Comma, Convert To Generic List, and Reverse Order

What your missing here is that .Reverse() is a void method. It's not possible to assign the result of .Reverse() to a variable. You can however alter the order to use Enumerable.Reverse() and get your result

var x = "Tom,Scott,Bob".Split(',').Reverse().ToList<string>()

The difference is that Enumerable.Reverse() returns an IEnumerable<T> instead of being void return

Get nth character of a string in Swift programming language

Swift 2.0 as of Xcode 7 GM Seed

var text = "Hello, world!"

let firstChar = text[text.startIndex.advancedBy(0)] // "H"

For the nth character, replace 0 with n-1.

Edit: Swift 3.0

text[text.index(text.startIndex, offsetBy: 0)]


n.b. there are simpler ways of grabbing certain characters in the string

e.g. let firstChar = text.characters.first

Arrays in unix shell?

Bourne shell doesn't support arrays. However, there are two ways to handle the issue.

Use positional shell parameters $1, $2, etc.:

$ set one two three
$ echo $*
one two three
$ echo $#
3
$ echo $2
two

Use variable evaluations:

$ n=1 ; eval a$n="one" 
$ n=2 ; eval a$n="two" 
$ n=3 ; eval a$n="three"
$ n=2
$ eval echo \$a$n
two

How can I detect the encoding/codepage of a text file

If you're looking to detect non-UTF encodings (i.e. no BOM), you're basically down to heuristics and statistical analysis of the text. You might want to take a look at the Mozilla paper on universal charset detection (same link, with better formatting via Wayback Machine).

How to do Base64 encoding in node.js?

crypto now supports base64 (reference):

cipher.final('base64') 

So you could simply do:

var cipher = crypto.createCipheriv('des-ede3-cbc', encryption_key, iv);
var ciph = cipher.update(plaintext, 'utf8', 'base64');
ciph += cipher.final('base64');

var decipher = crypto.createDecipheriv('des-ede3-cbc', encryption_key, iv);
var txt = decipher.update(ciph, 'base64', 'utf8');
txt += decipher.final('utf8');

Deleting records before a certain date

This helped me delete data based on different attributes. This is dangerous so make sure you back up database or the table before doing it:

mysqldump -h hotsname -u username -p password database_name > backup_folder/backup_filename.txt

Now you can perform the delete operation:

delete from table_name where column_name < DATE_SUB(NOW() , INTERVAL 1 DAY)

This will remove all the data from before one day. For deleting data from before 6 months:

delete from table_name where column_name < DATE_SUB(NOW() , INTERVAL 6 MONTH)

Basic calculator in Java

import java.util.Scanner;
public class AdditionGame {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    int num1;
    int num2;
    String operation;

    Scanner input = new Scanner(System.in);

    System.out.println("Please Enter The First Number");
    num1 = input.nextInt();

    System.out.println("Please Enter The Second Number");
    num2 = input.nextInt();

    Scanner op = new Scanner (System.in);

    System.out.println("Please Enter The Operation");
    operation = op.next();

    if (operation.equals("+"))
    {
        System.out.println("Your Answer is "+(num1 + num2));
    }
    else if (operation.equals("-"))
    {
        System.out.println("Your Answer is "+(num1 - num2));
    }       
    else if (operation.equals("*"))
    {
        System.out.println("Your Answer is "+(num1 * num2));
    }   
    else if (operation.equals("/"))
    {
        System.out.println("Your Answer is "+(num1 / num2));
    }
}

}

What REALLY happens when you don't free after malloc?

It is completely fine to leave memory unfreed when you exit; malloc() allocates the memory from the memory area called "the heap", and the complete heap of a process is freed when the process exits.

That being said, one reason why people still insist that it is good to free everything before exiting is that memory debuggers (e.g. valgrind on Linux) detect the unfreed blocks as memory leaks, and if you have also "real" memory leaks, it becomes more difficult to spot them if you also get "fake" results at the end.

c#: getter/setter

These are called auto properties.

http://msdn.microsoft.com/en-us/library/bb384054.aspx

Functionally (and in terms of the compiled IL), they are the same as properties with backing fields.

Unable to generate an explicit migration in entity framework

I had a simpler problem. VS erroneously reported this error when I had a VPN connection to a client's site connected on my workstation. The problem was that the DBMS security was set to accept requests only from my real local IP. Simply turning off the VPN resolved the problem.

Object not found! The requested URL was not found on this server. localhost

First check what your php error reports tells you. And define application wide root at the biginning of your index.php

define ('APPROOT', realpath(dirname(__FILE__)));

and then use it to include you files

include(APPROOT.'templates/header.php');

and so on... And to you have you .htaccess rewrite rule?

Best way to alphanumeric check in JavaScript

Check it with a regex.

Javascript regexen don't have POSIX character classes, so you have to write character ranges manually:

if (!input_string.match(/^[0-9a-z]+$/))
  show_error_or_something()

Here ^ means beginning of string and $ means end of string, and [0-9a-z]+ means one or more of character from 0 to 9 OR from a to z.

More information on Javascript regexen here: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions

How to get height of entire document with JavaScript?

This cross browser code below evaluates all possible heights of the body and html elements and returns the max found:

            var body = document.body;
            var html = document.documentElement;
            var bodyH = Math.max(body.scrollHeight, body.offsetHeight, body.getBoundingClientRect().height, html.clientHeight, html.scrollHeight, html.offsetHeight); // The max height of the body

A working example:

_x000D_
_x000D_
function getHeight()_x000D_
{_x000D_
  var body = document.body;_x000D_
  var html = document.documentElement; _x000D_
  var bodyH = Math.max(body.scrollHeight, body.offsetHeight, body.getBoundingClientRect().height, html.clientHeight, html.scrollHeight, html.offsetHeight);_x000D_
  return bodyH;_x000D_
}_x000D_
_x000D_
document.getElementById('height').innerText = getHeight();
_x000D_
body,html_x000D_
{_x000D_
  height: 3000px;_x000D_
}_x000D_
_x000D_
#posbtm_x000D_
{_x000D_
  bottom: 0;_x000D_
  position: fixed;_x000D_
  background-color: Yellow;_x000D_
}
_x000D_
<div id="posbtm">The max Height of this document is: <span id="height"></span> px</div>_x000D_
_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />
_x000D_
_x000D_
_x000D_

Use of True, False, and None as return values in Python functions

You can directly check that a variable contains a value or not, like if var or not var.

How to get a microtime in Node.js?

new Date().getTime()? This gives you a timestamp in milliseconds, which is the most accurate that JS will give you.

Update: As stated by vaughan, process.hrtime() is available within Node.js - its resolution are nanoseconds and therefore its much higher, also this doesn't mean it has to be more exact.

PS.: Just to be clearer, process.hrtime() returns you a tuple Array containing the current high-resolution real time in a [seconds, nanoseconds]

How to add custom Http Header for C# Web Service Client consuming Axis 1.4 Web service

Instead of modding the auto-generated code or wrapping every call in duplicate code, you can inject your custom HTTP headers by adding a custom message inspector, it's easier than it sounds:

public class CustomMessageInspector : IClientMessageInspector
{
    readonly string _authToken;

    public CustomMessageInspector(string authToken)
    {
        _authToken = authToken;
    }

    public object BeforeSendRequest(ref Message request, IClientChannel channel)
    {
        var reqMsgProperty = new HttpRequestMessageProperty();
        reqMsgProperty.Headers.Add("Auth-Token", _authToken);
        request.Properties[HttpRequestMessageProperty.Name] = reqMsgProperty;
        return null;
    }

    public void AfterReceiveReply(ref Message reply, object correlationState)
    { }
}


public class CustomAuthenticationBehaviour : IEndpointBehavior
{
    readonly string _authToken;

    public CustomAuthenticationBehaviour (string authToken)
    {
        _authToken = authToken;
    }
    public void Validate(ServiceEndpoint endpoint)
    { }

    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    { }

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    { }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.ClientMessageInspectors.Add(new CustomMessageInspector(_authToken));
    }
}

And when instantiating your client class you can simply add it as a behavior:

this.Endpoint.EndpointBehaviors.Add(new CustomAuthenticationBehaviour("Auth Token"));

This will make every outgoing service call to have your custom HTTP header.

Best way to do multiple constructors in PHP

PHP is a dynamic language, so you can't overload methods. You have to check the types of your argument like this:

class Student 
{
   protected $id;
   protected $name;
   // etc.

   public function __construct($idOrRow){
    if(is_int($idOrRow))
    {
        $this->id = $idOrRow;
        // other members are still uninitialized
    }
    else if(is_array($idOrRow))
    {
       $this->id = $idOrRow->id;
       $this->name = $idOrRow->name;
       // etc.  
    }
}

Printing list elements on separated lines in Python

Use the print function (Python 3.x) or import it (Python 2.6+):

from __future__ import print_function

print(*sys.path, sep='\n')