Programs & Examples On #Jalopy

How to turn off the Eclipse code formatter for certain sections of Java code?

Instead of turning the formatting off, you can configure it not to join already wrapped lines. Similar to Jitter's response, here's for Eclipse STS:

Properties ? Java Code Style ? Formatter ? Enable project specific settings OR Configure Workspace Settings ? Edit ? Line Wrapping (tab) ? check "Never join already wrapped lines"

Save, apply.

enter image description here

Find the files existing in one directory but not in the other

Another (maybe faster for large directories) approach:

$ find dir1 | sed 's,^[^/]*/,,' | sort > dir1.txt && find dir2 | sed 's,^[^/]*/,,' | sort > dir2.txt
$ diff dir1.txt dir2.txt

The sed command removes the first directory component thanks to Erik`s post)

Checking whether a variable is an integer or not

If the variable is entered like a string (e.g. '2010'):

if variable and variable.isdigit():
    return variable #or whatever you want to do with it. 
else: 
    return "Error" #or whatever you want to do with it.

Before using this I worked it out with try/except and checking for (int(variable)), but it was longer code. I wonder if there's any difference in use of resources or speed.

Changing file permission in Python

Simply include permissions integer in octal (works for both python 2 and python3):

os.chmod(path, 0o444)

How can I compile my Perl script so it can be executed on systems without perl installed?

From perlfaq3's answer to How can I compile my Perl program into byte code or C?:


(contributed by brian d foy)

In general, you can't do this. There are some things that may work for your situation though. People usually ask this question because they want to distribute their works without giving away the source code, and most solutions trade disk space for convenience. You probably won't see much of a speed increase either, since most solutions simply bundle a Perl interpreter in the final product (but see How can I make my Perl program run faster?).

The Perl Archive Toolkit ( http://par.perl.org/ ) is Perl's analog to Java's JAR. It's freely available and on CPAN ( http://search.cpan.org/dist/PAR/ ).

There are also some commercial products that may work for you, although you have to buy a license for them.

The Perl Dev Kit ( http://www.activestate.com/Products/Perl_Dev_Kit/ ) from ActiveState can "Turn your Perl programs into ready-to-run executables for HP-UX, Linux, Solaris and Windows."

Perl2Exe ( http://www.indigostar.com/perl2exe.htm ) is a command line program for converting perl scripts to executable files. It targets both Windows and unix platforms.

git ignore vim temporary files

If You are using source control. vim temp files are quite useless.
So You might want to configure vim not to create them.

Just edit Your ~/.vimrc and add these lines:

set nobackup
set noswapfile

The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)

In WCF serive project this issue may be due to Reference of System.Web.Mvc.dll 's different version or may be any other DLL's different version issue. So this may be compatibility issue of DLL's different version

When I use

System.Web.Mvc.dll version 5.2.2.0 -> it thorows the Error The content type text/html; charset=utf-8 of the response message

but when I use

System.Web.Mvc.dll version 4.0.0.0 or lower -> That's works fine in my project and not have an Error.

I don't know the reason of this different version of DLL's issue but when I change the DLL's verison which is compatible with your WCF Project than it works fine.

This Error even generate when you add reference of other Project in your WCF Project and this reference project has different version of System.Web.Mvc DLL or could be any other DLL.

Remove duplicate rows in MySQL

If the IGNORE statement won't work like in my case, you can use the below statement:

CREATE TABLE your_table_deduped LIKE your_table;


INSERT your_table_deduped
SELECT *
FROM your_table
GROUP BY index1_id,
         index2_id;

RENAME TABLE your_table TO your_table_with_dupes;

RENAME TABLE your_table_deduped TO your_table;

#OPTIONAL
ALTER TABLE `your_table` ADD UNIQUE `unique_index` (`index1_id`, `index2_id`);

#OPTIONAL
DROP TABLE your_table_with_dupes;

How to use UIScrollView in Storyboard

Here's how to setup a scrollview using Xcode 11

1 - Add scrollview and set top,bottom,leading and trailing constraints

enter image description here

2 - Add a Content View to the scrollview, drag a connection to the Content Layout Guide and select Leading, Top, Bottom and Trailing. Make sure to set its' values to 0 or the constants you want.

enter image description here

3 - Drag from the Content View to the Frame Layout Guide and select Equal Widths

enter image description here

4 - Set a height constraint constant to the Content View

Python: Split a list into sub-lists based on index ranges

If you already know the indices:

list1 = ['x','y','z','a','b','c','d','e','f','g']
indices = [(0, 4), (5, 9)]
print [list1[s:e+1] for s,e in indices]

Note that we're adding +1 to the end to make the range inclusive...

How to check if a .txt file is in ASCII or UTF-8 format in Windows environment?

Open the file in Notepad. Click 'Save As...'. In the 'Encoding:' combo box you will see the current file format.

package javax.mail and javax.mail.internet do not exist

You need to download the JavaMail API, and put the relevant jar files in your classpath.

How do I get the current location of an iframe?

You can access the src property of the iframe but that will only give you the initially loaded URL. If the user is navigating around in the iframe via you'll need to use an HTA to solve the security problem.

http://msdn.microsoft.com/en-us/library/ms536474(VS.85).aspx

Check out the link, using an HTA and setting the "application" property of an iframe will allow you to access the document.href property and parse out all of the information you want, including DOM elements and their values if you so choose.

Run a task every x-minutes with Windows Task Scheduler

You can also create a batch file like the following if you need finer granularity between calls:

:loop
CallYour.Exe
timeout /t timeToWaitBetweenCallsInSeconds /nobreak
goto :loop

Uncaught TypeError: Cannot read property 'value' of null

My mistake was that I was keeping the Javascript file ( tag) above the html declaration.

It worked by placing the js script tag at the bottom of the body inside the body. (I did not the script on load of the page.)

MySQL: can't access root account

There is a section in the MySQL manual on how to reset the root password which will solve your problem.

CSS3 Spin Animation

As of latest Chrome/FF and on IE11 there's no need for -ms/-moz/-webkit prefix. Here's a shorter code (based on previous answers):

div {
    margin: 20px;
    width: 100px;
    height: 100px;
    background: #f00;

    /* The animation part: */
    animation-name: spin;
    animation-duration: 4000ms;
    animation-iteration-count: infinite;
    animation-timing-function: linear;
}
@keyframes spin {
    from {transform:rotate(0deg);}
    to {transform:rotate(360deg);}
}

Live Demo: http://jsfiddle.net/9Ryvs/3057/

How do I call REST API from an android app?

  1. If you want to integrate Retrofit (all steps defined here):

Goto my blog : retrofit with kotlin

  1. Please use android-async-http library.

the link below explains everything step by step.

http://loopj.com/android-async-http/

Here are sample apps:

  1. http://www.techrepublic.com/blog/software-engineer/calling-restful-services-from-your-android-app/

  2. http://blog.strikeiron.com/bid/73189/Integrate-a-REST-API-into-Android-Application-in-less-than-15-minutes

Create a class :

public class HttpUtils {
  private static final String BASE_URL = "http://api.twitter.com/1/";
 
  private static AsyncHttpClient client = new AsyncHttpClient();

  public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(getAbsoluteUrl(url), params, responseHandler);
  }

  public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(getAbsoluteUrl(url), params, responseHandler);
  }
      
  public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(url, params, responseHandler);
  }

  public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(url, params, responseHandler);
  }

  private static String getAbsoluteUrl(String relativeUrl) {
      return BASE_URL + relativeUrl;
  }
}

Call Method :

    RequestParams rp = new RequestParams();
    rp.add("username", "aaa"); rp.add("password", "aaa@123");
                    
    HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            // If the response is JSONObject instead of expected JSONArray
            Log.d("asd", "---------------- this is response : " + response);
            try {
                JSONObject serverResp = new JSONObject(response.toString());                                                
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }                   
        }
            
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
            // Pull out the first event on the public timeline
                    
        }
    });

Please grant internet permission in your manifest file.

 <uses-permission android:name="android.permission.INTERNET" />

you can add compile 'com.loopj.android:android-async-http:1.4.9' for Header[] and compile 'org.json:json:20160212' for JSONObject in build.gradle file if required.

How to add items to a spinner in Android?

<string-array name="array_name">
<item>Array Item One</item>
<item>Array Item Two</item>
<item>Array Item Three</item>
</string-array>

In your layout:

<Spinner 
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:drawSelectorOnTop="true"
        android:entries="@array/array_name"
    />

Matlab: Running an m-file from command-line

Since R2019b, there is a new command line option, -batch. It replaces -r, which is no longer recommended. It also unifies the syntax across platforms. See for example the documentation for Windows, for the other platforms the description is identical.

matlab -batch "statement to run"

This starts MATLAB without the desktop or splash screen, logs all output to stdout and stderr, exits automatically when the statement completes, and provides an exit code reporting success or error.

It is thus no longer necessary to use try/catch around the code to run, and it is no longer necessary to add an exit statement.

Read the package name of an Android APK

Based on @hackbod answer ... but related to windows.

aapt command is located on Android\SDK\build-tools\version. If you need more info about what is appt command (Android Asset Packaging Tool) read this https://stackoverflow.com/a/28234956/812915

The dump sub-command of aapt is used to display the values of individual elements or parts of a package:

aapt dump badging <path-to-apk>

If you want see only the line with package: name info, use findstr

aapt dump badging <path-to-apk> | findstr -n "package: name" | findstr "1:"

Hope it help other windows user!

.htaccess 301 redirect of single page

If you prefer to use the simplest possible solution to a problem, an alternative to RedirectMatch is, the more basic, Redirect directive.

It does not use pattern matching and so is more explicit and easier for others to understand.

i.e

<IfModule mod_alias.c>

#Repoint old contact page to new contact page:
Redirect 301 /contact.php http://example.com/contact-us.php

</IfModule>

Query strings should be carried over because the docs say:

Additional path information beyond the matched URL-path will be appended to the target URL.

What is Unicode, UTF-8, UTF-16?

Unicode is a fairly complex standard. Don’t be too afraid, but be prepared for some work! [2]

Because a credible resource is always needed, but the official report is massive, I suggest reading the following:

  1. The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) An introduction by Joel Spolsky, Stack Exchange CEO.
  2. To the BMP and beyond! A tutorial by Eric Muller, Technical Director then, Vice President later, at The Unicode Consortium. (first 20 slides and you are done)

A brief explanation:

Computers read bytes and people read characters, so we use encoding standards to map characters to bytes. ASCII was the first widely used standard, but covers only Latin (7 bits/character can represent 128 different characters). Unicode is a standard with the goal to cover all possible characters in the world (can hold up to 1,114,112 characters, meaning 21 bits/character max. Current Unicode 8.0 specifies 120,737 characters in total, and that's all).

The main difference is that an ASCII character can fit to a byte (8 bits), but most Unicode characters cannot. So encoding forms/schemes (like UTF-8 and UTF-16) are used, and the character model goes like this:

Every character holds an enumerated position from 0 to 1,114,111 (hex: 0-10FFFF) called code point.
An encoding form maps a code point to a code unit sequence. A code unit is the way you want characters to be organized in memory, 8-bit units, 16-bit units and so on. UTF-8 uses 1 to 4 units of 8 bits, and UTF-16 uses 1 or 2 units of 16 bits, to cover the entire Unicode of 21 bits max. Units use prefixes so that character boundaries can be spotted, and more units mean more prefixes that occupy bits. So, although UTF-8 uses 1 byte for the Latin script it needs 3 bytes for later scripts inside Basic Multilingual Plane, while UTF-16 uses 2 bytes for all these. And that's their main difference.
Lastly, an encoding scheme (like UTF-16BE or UTF-16LE) maps (serializes) a code unit sequence to a byte sequence.

character: p
code point: U+03C0
encoding forms (code units):
      UTF-8: CF 80
      UTF-16: 03C0
encoding schemes (bytes):
      UTF-8: CF 80
      UTF-16BE: 03 C0
      UTF-16LE: C0 03

Tip: a hex digit represents 4 bits, so a two-digit hex number represents a byte
Also take a look at Plane maps in Wikipedia to get a feeling of the character set layout

How to specify new GCC path for CMake

Change CMAKE_<LANG>_COMPILER path without triggering a reconfigure

I wanted to compile with an alternate compiler, but also pass -D options on the command-line which would get wiped out by setting a different compiler. This happens because it triggers a re-configure. The trick is to disable the compiler detection with NONE, set the paths with FORCE, then enable_language.

project( sample_project NONE )

set( COMPILER_BIN /opt/compiler/bin )
set( CMAKE_C_COMPILER ${COMPILER_BIN}/clang CACHE PATH "clang" FORCE )
set( CMAKE_CXX_COMPILER ${COMPILER_BIN}/clang++ CACHE PATH "clang++" FORCE )

enable_language( C CXX )

Use a Toolchain file

The more sensible choice is to create a toolchain file.

set( CMAKE_SYSTEM_NAME Darwin )

set( COMPILER_BIN /opt/compiler/bin )
set( CMAKE_C_COMPILER ${COMPILER_BIN}/clang CACHE PATH "clang" )
set( CMAKE_CXX_COMPILER ${COMPILER_BIN}/clang++ CACHE PATH "clang++" )

Then you invoke Cmake with an additional flag

cmake -D CMAKE_TOOLCHAIN_FILE=/path/to/toolchain_file.cmake ...

How to save select query results within temporary table?

In Sqlite:

CREATE TABLE T AS
SELECT * FROM ...;
-- Use temporary table `T`
DROP TABLE T;

Reflection - get attribute name and value on property

Just looking for the right place to put this piece of code.

let's say you have the following property:

[Display(Name = "Solar Radiation (Average)", ShortName = "SolarRadiationAvg")]
public int SolarRadiationAvgSensorId { get; set; }

And you want to get the ShortName value. You can do:

((DisplayAttribute)(typeof(SensorsModel).GetProperty(SolarRadiationAvgSensorId).GetCustomAttribute(typeof(DisplayAttribute)))).ShortName;

Or to make it general:

internal static string GetPropertyAttributeShortName(string propertyName)
{
    return ((DisplayAttribute)(typeof(SensorsModel).GetProperty(propertyName).GetCustomAttribute(typeof(DisplayAttribute)))).ShortName;
}

How do I drop a MongoDB database from the command line?

Drop a MongoDB database using python:

import argparse

import pymongo


if __name__ == "__main__":
    """
    Drop a Database.
    """

    parser = argparse.ArgumentParser()
    parser.add_argument("--host", default='mongodb://localhost:27017',
                        help="mongodb URI [default: %(default)s]")
    parser.add_argument("--database", default=None,
                        help="database name: %(default)s]")

    args = parser.parse_args()

    client = pymongo.MongoClient(host=args.host)

    if args.database in client.list_database_names():
        client.drop_database(args.database)
        print(f"Dropped: '{args.database}'")
    else:
        print(f"Database '{args.database}' does not exist")

Clear variable in python

I used a few options mentioned above :

del self.left

or setting value to None using

self.left = None

It's important to know the differences and put a few exception handlers in place when you use set the value to None. If you're printing the value of the conditional statements using a template, say,

print("The value of the variable is {}".format(self.left))

you might see the value of the variable printing "The value of the variable is None". Thus, you'd have to put a few exception handlers there :

if self.left:
    #Then only print stuff

The above command will only print values if self.left is not None

How to search for a string in text files?

Here's another. Takes an absolute file path and a given string and passes it to word_find(), uses readlines() method on the given file within the enumerate() method which gives an iterable count as it traverses line by line, in the end giving you the line with the matching string, plus the given line number. Cheers.

  def word_find(file, word):
    with open(file, 'r') as target_file:
        for num, line in enumerate(target_file.readlines(), 1):
            if str(word) in line:
                print(f'<Line {num}> {line}')
            else:
                print(f'> {word} not found.')


  if __name__ == '__main__':
      file_to_process = '/path/to/file'
      string_to_find = input()
      word_find(file_to_process, string_to_find)

Any good, visual HTML5 Editor or IDE?

for online solution try maqetta and aloha editor

for offline solution (download-able) try blue griffon

they are free :) oh yeah, one more, my favorite editor :) and game editor also: construct2

How to display an unordered list in two columns?

With Bootstrap... This answer (https://stackoverflow.com/a/23005046/1128742) got me pointed towards this solution:

<ul class="list-unstyled row">
   <li class="col-xs-6">Item 1</li>
   <li class="col-xs-6">Item 2</li>
   <li class="col-xs-6">Item 3</li>
</ul>

http://jsfiddle.net/patrickbad767/472r0ynf/

Calling startActivity() from outside of an Activity?

When you want to open an activity within your app then you can call the startActivity() method with an Intent as parameter. That intent would be the activity that you want to open. First you have to create an object of that intent with first parameter to be the context and second parameter to be the targeted activity class.

Intent intent = new Intent(this, Activity_a.class);
startActivity(intent);

Hope this will help.

pandas python how to count the number of records or rows in a dataframe

Simply, row_num = df.shape[0] # gives number of rows, here's the example:

import pandas as pd
import numpy as np

In [322]: df = pd.DataFrame(np.random.randn(5,2), columns=["col_1", "col_2"])

In [323]: df
Out[323]: 
      col_1     col_2
0 -0.894268  1.309041
1 -0.120667 -0.241292
2  0.076168 -1.071099
3  1.387217  0.622877
4 -0.488452  0.317882

In [324]: df.shape
Out[324]: (5, 2)

In [325]: df.shape[0]   ## Gives no. of rows/records
Out[325]: 5

In [326]: df.shape[1]   ## Gives no. of columns
Out[326]: 2

Laravel 4 Eloquent Query Using WHERE with OR AND OR?

$a, $b, $c, $d can be dynamic values by the query

 ->where(function($query) use ($a, $b)
        {
            $query->where('a', $a)
                  ->orWhere('b',$b);
        })
 ->where(function($query) use ($c, $d)
        {
            $query->where('c', $c)
                  ->orWhere('d',$d);
        })

What is the curl error 52 "empty reply from server"?

I've had this problem before. Figured out I had another application using the same port (3000).

Easy way to find this out:

In the terminal, type netstat -a -p TCP -n | grep 3000 (substitute the port you're using for the '3000'). If there is more than one listening, something else is already occupying that port. You should stop that process or change the port for your new process.

Javascript: console.log to html

Create an ouput

<div id="output"></div>

Write to it using JavaScript

var output = document.getElementById("output");
output.innerHTML = "hello world";

If you would like it to handle more complex output values, you can use JSON.stringify

var myObj = {foo: "bar"};
output.innerHTML = JSON.stringify(myObj);

Where can I get a virtual machine online?

Try this:

http://aws.amazon.com/free/

one year free. I do use this for a while.

How to re-enable right click so that I can inspect HTML elements in Chrome?

If they have just changed the oncontextmenu handler (which is the most straightforward way to do it), then you can remove their override thus:

window.oncontextmenu = null;

Otherwise, if it is attached to individual elements, you can get all the page's elements, and then remove the handler on each one:

var elements = document.getElementsByTagName("*");
for(var id = 0; id < elements.length; ++id) { elements[id].oncontextmenu = null; }

Or, it seems you can turn off such scripts; via an extension in Chrome or an option in Firefox - in the advanced box for javascript options, switch off 'Disable or replace context menus'.

SQL Server - Adding a string to a text column (concat equivalent)

Stop using the TEXT data type in SQL Server!

It's been deprecated since the 2005 version. Use VARCHAR(MAX) instead, if you need more than 8000 characters.

The TEXT data type doesn't support the normal string functions, while VARCHAR(MAX) does - your statement would work just fine, if you'd be using just VARCHAR types.

In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file?

A .pl is a single script.

In .pm (Perl Module) you have functions that you can use from other Perl scripts:

A Perl module is a self-contained piece of Perl code that can be used by a Perl program or by other Perl modules. It is conceptually similar to a C link library, or a C++ class.

Parsing PDF files (especially with tables) with PDFBox

This works fine if PDF file has "Only Rectangular table" using pdfbox 2.0.6. Won't work with any other table only Rectangular table.

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.PDFTextStripperByArea;
public class PDFTableExtractor {
    public static void main(String[] args) throws IOException {
        ArrayList<String[]> objTableList = readParaFromPDF("C:\\sample1.pdf", 1,1,6);
        //Enter Filepath, startPage, EndPage, Number of columns in Rectangular table
    }
    public static ArrayList<String[]> readParaFromPDF(String pdfPath, int pageNoStart, int pageNoEnd, int noOfColumnsInTable) {
        ArrayList<String[]> objArrayList = new ArrayList<>();
        try {
            PDDocument document = PDDocument.load(new File(pdfPath));
            document.getClass();
            if (!document.isEncrypted()) {
                PDFTextStripperByArea stripper = new PDFTextStripperByArea();
                stripper.setSortByPosition(true);
                PDFTextStripper tStripper = new PDFTextStripper();
                tStripper.setStartPage(pageNoStart);
                tStripper.setEndPage(pageNoEnd);
                String pdfFileInText = tStripper.getText(document);
                // split by whitespace
                String Documentlines[] = pdfFileInText.split("\\r?\\n");
                for (String line : Documentlines) {
                    String lineArr[] = line.split("\\s+");
                    if (lineArr.length == noOfColumnsInTable) {
                        for (String linedata : lineArr) {
                            System.out.print(linedata + "             ");
                        }
                        System.out.println("");
                        objArrayList.add(lineArr);
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("Exception " +e);
        }
            return objArrayList;
    }
}

Measure execution time for a Java method

Nanotime is in fact not even good for elapsed time because it drifts away signficantly more than currentTimeMillis. Furthermore nanotime tends to provide excessive precision at the expense of accuracy. It is therefore highly inconsistent,and needs refinement.

For any time measuring process,currentTimeMillis (though almost as bad), does better in terms of balancing accuracy and precision.

How to use mouseover and mouseout in Angular 6

The Angular6 equivalent code should be:

app.component.html

<div (mouseover)="changeText=true" (mouseout)="changeText=false">
  <span *ngIf="!changeText">Hide</span>
  <span *ngIf="changeText">Show</span>
</div>

app.component.ts

@Component({
   selector: 'app-main',
   templateUrl: './app.component.html'
})
export class AppComponent {
    changeText: boolean;
    constructor() {
       this.changeText = false;
    }
}

Notice that there is no such thing as $scope anymore as it existed in AngularJS. Its been replaced with member variables from the component class. Also, there is no scope resolution algorithm based on prototypical inheritance either - it either resolves to a component class member, or it doesn't.

Can a constructor in Java be private?

I expected that someone would've mentioned this (the 2nd point), but.. there are three uses of private constructors:

  • to prevent instantiation outside of the object, in the following cases:

    • singleton
    • factory method
    • static-methods-only (utility) class
    • constants-only class
      .
  • to prevent sublcassing (extending). If you make only a private constructor, no class can extend your class, because it can't call the super() constructor. This is some kind of a synonym for final

  • overloaded constructors - as a result of overloading methods and constructors, some may be private and some public. Especially in case when there is a non-public class that you use in your constructors, you may create a public constructor that creates an instance of that class and then passes it to a private constructor.

Java Replace Character At Specific Position Of String?

Petar Ivanov's answer to replace a character at a specific index in a string question

String are immutable in Java. You can't change them.

You need to create a new string with the character replaced.

String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);

Or you can use a StringBuilder:

StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');

System.out.println(myName);

undefined reference to `std::ios_base::Init::Init()'

Most of these linker errors occur because of missing libraries.

I added the libstdc++.6.dylib in my Project->Targets->Build Phases-> Link Binary With Libraries.

That solved it for me on Xcode 6.3.2 for iOS 8.3

Cheers!

Getting content/message from HttpResponseMessage

I think the easiest approach is just to change the last line to

txtBlock.Text = await response.Content.ReadAsStringAsync(); //right!

This way you don't need to introduce any stream readers and you don't need any extension methods.

Echo tab characters in bash script

res="\t\tx"
echo -e "[${res}]"

How to upgrade safely php version in wamp server

  1. Simply Download the PHP version that you want from this url: http://wampserver.aviatechno.net/
  2. Goto your wamp\bin\php directory and extract it like this(Note: you need to rename your folder to phpversionOfPhp list of installed version in the directory
  3. Start wamp and click wamp icon and choose the version of php you want to use: https://gyazo.com/de5727d7e254795e238422783dec3758

jQuery multiple events to trigger the same function

The answer by Tatu is how I would intuitively do it, but I have experienced some problems in Internet Explorer with this way of nesting/binding the events, even though it is done through the .on() method.

I havn't been able to pinpoint exactly which versions of jQuery this is the problem with. But I sometimes see the problem in the following versions:

  • 2.0.2
  • 1.10.1
  • 1.6.4
  • Mobile 1.3.0b1
  • Mobile 1.4.2
  • Mobile 1.2.0

My workaround have been to first define the function,

function myFunction() {
    ...
}

and then handle the events individually

// Call individually due to IE not handling binds properly
$(window).on("scroll", myFunction);
$(window).on("resize", myFunction);

This is not the prettiest solution, but it works for me, and I thought I would put it out there to help others that might stumble upon this issue

An Iframe I need to refresh every 30 seconds (but not the whole page)

add "id='myiframe'" to the iframe, then use this script :

<script>

function f1()
{
 var x=document.getElementById("myiframe");
   x.src=x.src+Math.floor(random()%100000);
}

setInterval(f1,30*1000);

</script>

String array initialization in Java

First up, this has got nothing to do with String, it is about arrays.. and that too specifically about declarative initialization of arrays.

As discussed by everyone in almost every answer here, you can, while declaring a variable, use:

String names[] = {"x","y","z"};

However, post declaration, if you want to assign an instance of an Array:

names = new String[] {"a","b","c"};

AFAIK, the declaration syntax is just a syntactic sugar and it is not applicable anymore when assigning values to variables because when values are assigned you need to create an instance properly.

However, if you ask us why it is so? Well... good luck getting an answer to that. Unless someone from the Java committee answers that or there is explicit documentation citing the said syntactic sugar.

Filename too long in Git for Windows

The better solution is enable the longpath parameter from Git.

git config --system core.longpaths true

But a workaround that works is remove the node_modules folder from Git:

$ git rm -r --cached node_modules
$ vi .gitignore

Add node_modules in a new row inside the .gitignore file. After doing this, push your modifications:

$ git add .gitignore
$ git commit -m "node_modules removed"
$ git push

How to get name of calling function/method in PHP?

The simplest way is:

echo debug_backtrace()[1]['function'];

How to change the color of an svg element?

here the fast&furious way :)

_x000D_
_x000D_
 body{
 background-color: #deff05;
 }
 
 svg{
   width: 30%;
    height: auto;
 }
 
 svg path {
    color:red;
    fill: currentcolor;
}
_x000D_
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" id="Capa_1" x="0px" y="0px" viewBox="0 0 514.666 514.666"><path d="M514.666,210.489L257.333,99.353L0,210.489l45.933,19.837v123.939h30V243.282l33.052,14.274v107.678l4.807,4.453  c2.011,1.862,50.328,45.625,143.542,45.625c93.213,0,141.53-43.763,143.541-45.626l4.807-4.452V257.557L514.666,210.489z   M257.333,132.031L439,210.489l-181.667,78.458L75.666,210.489L257.333,132.031z M375.681,351.432  c-13.205,9.572-53.167,33.881-118.348,33.881c-65.23,0-105.203-24.345-118.348-33.875v-80.925l118.348,51.112l118.348-51.111  V351.432z"></path></svg>
_x000D_
_x000D_
_x000D_

LaTeX table too wide. How to make it fit?

You have to take whole columns under resizebox. This code worked for me

\begin{table}[htbp]
\caption{Sample Table.}\label{tab1}
\resizebox{\columnwidth}{!}{\begin{tabular}{|l|l|l|l|l|}
\hline
URL &  First Time Visit & Last Time Visit & URL Counts & Value\\
\hline
https://web.facebook.com/ & 1521241972 & 1522351859 & 177 & 56640\\
http://localhost/phpmyadmin/ & 1518413861 & 1522075694 & 24 & 39312\\
https://mail.google.com/mail/u/ & 1516596003 & 1522352010 & 36 & 33264\\
https://github.com/shawon100& 1517215489 & 1522352266 & 37 & 27528\\
https://www.youtube.com/ & 1517229227 & 1521978502 & 24 & 14792\\
\hline
\end{tabular}}
\end{table}

In Java, can you modify a List while iterating through it?

Use Java 8's removeIf(),

To remove safely,

letters.removeIf(x -> !x.equals("A"));

Detect all Firefox versions in JS

This will detect any version of Firefox:

var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;

more specifically:

if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1){
     // Do Firefox-related activities
}

You may want to consider using feature-detection ala Modernizr, or a related tool, to accomplish what you need.

nodemon not found in npm

--save, -g and changing package.json scripts did not work for me. Here's what did: running npm start (or using npx nodemon) within the command line. I use visual studio code terminal. When it is successful you will see this message:

[nodemon] 1.18.9
[nodemon] to restart at any time, enter rs
[nodemon] watching: .
[nodemon] starting node app.js

Good luck!

What is the incentive for curl to release the library for free?

I'm Daniel Stenberg.

I made curl

I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.

I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.

Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.

Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.

Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.

At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.

Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.

Why do I still work on curl?

Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?

  1. I can't speak for my fellow project team members. We all participate in this for our own reasons.
  2. I think it's still the right thing to do. I'm proud of what we've accomplished and I truly want to make the world a better place and I think curl does its little part in this.
  3. There are still bugs to fix and features to add!
  4. curl is free but my time is not. I still have a job and someone still has to pay someone for me to get paid every month so that I can put food on the table for my family. I charge customers and companies to help them with curl. You too can get my help for a fee, which then indirectly helps making sure that curl continues to evolve, remain free and the kick-ass product it is.
  5. curl was my spare time project for twenty years before I started working with it full time. I've had great jobs and worked on awesome projects. I've been in a position of luxury where I could continue to work on curl on my spare time and keep shipping a quality product for free. My work on curl has given me friends, boosted my career and taken me to places I would not have been at otherwise.
  6. I would not do it differently if I could back and do it again.

Am I proud of what we've done?

Yes. So insanely much.

But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.

We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.

Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.

For real?

Yeah. For real.

Do I ever get tired? Is it ever done?

Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.

But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.

curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.

Insert node at a certain position in a linked list C++

I had some problems with the insertion process just like you, so here is the code how I have solved the problem:

void add_by_position(int data, int pos)
  {
        link *node = new link;
        link *linker = head;

        node->data = data;
        for (int i = 0; i < pos; i++){
            linker = linker->next;
        }
        node->next = linker;
        linker = head;
        for (int i = 0; i < pos - 1; i++){
            linker = linker->next;
        }
        linker->next = node;
        boundaries++;
    }

Retrieving Android API version programmatically

Got it. Its using the getApplicationInfo() method of the Context class.

How to get the innerHTML of selectable jquery element?

The parameter ui has a property called selected which is a reference to the selected dom element, you can call innerHTML on that element.

Your code $('.ui-selected').innerHTML tries to return the innerHTML property of a jQuery wrapper element for a dom element with class ui-selected

$(function () {
    $("#select-image").selectable({
        selected: function (event, ui) {
            var $variable = ui.selected.innerHTML; // or $(ui.selected).html()
            console.log($variable);
        }
    });
});

Demo: Fiddle

Get Root Directory Path of a PHP project

When you say that

$_SERVER['DOCUMENT_ROOT']

contains this path:

D:/workspace

Then D: is what you are looking for, isn't it? In that case you could explode the string by slashes and return the first one:

$pathInPieces = explode('/', $_SERVER['DOCUMENT_ROOT']);
echo $pathInPieces[0];

This will output the server's root directory.

Update: When you use the constant DIRECTORY_SEPARATOR instead of the hardcoded slash ('/') this code is also working under Windows.

Update 2: The $_SERVER global variable is not always available. On command line (cli) for example. So you should use __DIR__ instead of $_SERVER['DOCUMENT_ROOT']. __DIR__ returns the path of the php file itself.

PyCharm import external library

Since PyCharm 3.4 the path tab in the 'Project Interpreter' settings has been replaced. In order to add paths to a project you need to select the cogwheel, click on 'More...' and then select the "Show path for the selected interpreter" icon. This allows you to add paths to your project as before.

My project is now behaving as I would expect.

These are the windows you would see while following the instructions

How to test an SQL Update statement before running it?

One more option is to ask MySQL for the query plan. This tells you two things:

  • Whether there are any syntax errors in the query, if so the query plan command itself will fail
  • How MySQL is planning to execute the query, e.g. what indexes it will use

In MySQL and most SQL databases the query plan command is describe, so you would do:

describe update ...;

How do Python functions handle the types of the parameters that you pass in?

As Alex Martelli explains,

The normal, Pythonic, preferred solution is almost invariably "duck typing": try using the argument as if it was of a certain desired type, do it in a try/except statement catching all exceptions that could arise if the argument was not in fact of that type (or any other type nicely duck-mimicking it;-), and in the except clause, try something else (using the argument "as if" it was of some other type).

Read the rest of his post for helpful information.

Run a php app using tomcat?

tomcat is designed as JSP servlet container. Apache is designed PHP web server. Use apache as web server, responding for PHP request, and direct JSP servlet request to tomcat container. should be better implementation.

Reminder - \r\n or \n\r?

New line depends on your OS:

DOS & Windows: \r\n 0D0A (hex), 13,10 (decimal)
Unix & Mac OS X: \n, 0A, 10
Macintosh (OS 9): \r, 0D, 13

More details here: https://ccrma.stanford.edu/~craig/utility/flip/

When in doubt, use any freeware hex viewer/editor to see how a file encodes its new line.

For me, I use following guide to help me remember: 0D0A = \r\n = CR,LF = carriage return, line feed

What does the 'static' keyword do in a class?

Static makes the clock member a class member instead of an instance member. Without the static keyword you would need to create an instance of the Hello class (which has a clock member variable) - e.g.

Hello hello = new Hello();
hello.clock.sayTime();

Check cell for a specific letter or set of letters

Just use = IF(A1="Bla*","YES","NO"). When you insert the asterisk, it acts as a wild card for any amount of characters after the specified text.

ORA-12170: TNS:Connect timeout occurred

open sqlnet.ora  

NAMES.DIRECTORY_PATH= (TNSNAMES, EZCONNECT)
SQLNET.INBOUND_CONNECT_TIMEOUT=360
SQLNET.RECV_TIMEOUT=10
SQLNET.SEND_TIMEOUT=10

http://docs.oracle.com/cd/B19306_01/network.102/b14213/sqlnet.htm

Get current index from foreach loop

Use Enumerable.Select<TSource, TResult> Method (IEnumerable<TSource>, Func<TSource, Int32, TResult>)

list = list.Cast<object>().Select( (v, i) => new {Value= v, Index = i});

foreach(var row in list)
{
    bool IsChecked = (bool)((CheckBox)DataGridDetail.Columns[0].GetCellContent(row.Value)).IsChecked;
    row.Index ...
}

Opposite of %in%: exclude rows with values specified in a vector

The help for %in%, help("%in%"), includes, in the Examples section, this definition of not in,

"%w/o%" <- function(x, y) x[!x %in% y] #-- x without y

Lets try it:

c(2,3,4) %w/o% c(2,8,9)
[1] 3 4

Alternatively

"%w/o%" <- function(x, y) !x %in% y #--  x without y
c(2,3,4) %w/o% c(2,8,9)
# [1] FALSE  TRUE  TRUE

gdb fails with "Unable to find Mach task port for process-id" error

Following the instructions here Codesign gdb on macOS seemed to resolve this issue, for me, on macOS High Sierra (10.13.3).

Arguments to main in C

Siamore, I keep seeing everyone using the command line to compile programs. I use x11 terminal from ide via code::blocks, a gnu gcc compiler on my linux box. I have never compiled a program from command line. So Siamore, if I want the programs name to be cp, do I initialize argv[0]="cp"; Cp being a string literal. And anything going to stdout goes on the command line??? The example you gave me Siamore I understood! Even though the string you entered was a few words long, it was still only one arg. Because it was encased in double quotations. So arg[0], the prog name, is actually your string literal with a new line character?? So I understand why you use if(argc!=3) print error. Because the prog name = argv[0] and there are 2 more args after that, and anymore an error has occured. What other reason would I use that? I really think that my lack of understanding about how to compile from the command line or terminal is my reason for lack understanding in this area!! Siamore, you have helped me understand cla's much better! Still don't fully understand but I am not oblivious to the concept. I'm gonna learn to compile from the terminal then re-read what you wrote. I bet, then I will fully understand! With a little more help from you lol

<> Code that I have not written myself, but from my book.

#include <stdio.h>

int main(int argc, char *argv[])
{
    int i;

    printf("The following arguments were passed to main(): ");
    for(i=1; i<argc; i++) printf("%s ", argv[i]);
    printf("\n");

    return 0;
} 

This is the output:

anthony@anthony:~\Documents/C_Programming/CLA$ ./CLA hey man
The follow arguments were passed to main(): hey man
anthony@anthony:~\Documents/C_Programming/CLA$ ./CLA hi how are you doing?
The follow arguments were passed to main(): hi how are you doing?

So argv is a table of string literals, and argc is the number of them. Now argv[0] is the name of the program. So if I type ./CLA to run the program ./CLA is argv[0]. The above program sets the command line to take an infinite amount of arguments. I can set them to only take 3 or 4 if I wanted. Like one or your examples showed, Siamore... if(argc!=3) printf("Some error goes here"); Thank you Siamore, couldn't have done it without you! thanks to the rest of the post for their time and effort also!

PS in case there is a problem like this in the future...you never know lol the problem was because I was using the IDE AKA Code::Blocks. If I were to run that program above it would print the path/directory of the program. Example: ~/Documents/C/CLA.c it has to be ran from the terminal and compiled using the command line. gcc -o CLA main.c and you must be in the directory of the file.

'python' is not recognized as an internal or external command

i solved this by running CMD in administration mode, so try this.

Store List to session

public class ProductList
{
   public string product{get;set;}
   public List<ProductList> objList{get;set;}
}

ProductList obj=new ProductList();
obj.objList=new List<ProductList>();
obj.objList.add(new ProductList{product="Football"});

now assign obj to session

Session["Product"]=obj;

for retrieval of session.

ProductList objLst = (ProductList)Session["Product"];

indexOf method in an object array?

This is the way to find the object's index in array

    var myArray = [{  hello: 'world',
        foo: 'bar'
    },{
        hello: 'stevie',
        foo: 'baz'
    }];



    for (i = 0; i < myArray.length; i++) {
        if (myArray[i].hello === 'stevie') {
            alert('position: ' + i);
            return;
        }
    }

How to launch PowerShell (not a script) from the command line

Set the default console colors and fonts:

http://poshcode.org/2220
From Windows PowerShell Cookbook (O'Reilly)
by Lee Holmes (http://www.leeholmes.com/guide)

Set-StrictMode -Version Latest

Push-Location
Set-Location HKCU:\Console
New-Item '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'
Set-Location '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'

New-ItemProperty . ColorTable00 -type DWORD -value 0x00562401
New-ItemProperty . ColorTable07 -type DWORD -value 0x00f0edee
New-ItemProperty . FaceName -type STRING -value "Lucida Console"
New-ItemProperty . FontFamily -type DWORD -value 0x00000036
New-ItemProperty . FontSize -type DWORD -value 0x000c0000
New-ItemProperty . FontWeight -type DWORD -value 0x00000190
New-ItemProperty . HistoryNoDup -type DWORD -value 0x00000000
New-ItemProperty . QuickEdit -type DWORD -value 0x00000001
New-ItemProperty . ScreenBufferSize -type DWORD -value 0x0bb80078
New-ItemProperty . WindowSize -type DWORD -value 0x00320078
Pop-Location

What is the difference between dict.items() and dict.iteritems() in Python2?

dict.iteritems() in python 2 is equivalent to dict.items() in python 3.

How to use zIndex in react-native

Use elevation instead of zIndex for android devices

elevatedElement: {
  zIndex: 3, // works on ios
  elevation: 3, // works on android
}

This worked fine for me!

Convert to binary and keep leading zeros in Python

Sometimes you just want a simple one liner:

binary = ''.join(['{0:08b}'.format(ord(x)) for x in input])

Python 3

vbscript output to console

I came across this post and went back to an approach that I used some time ago which is similar to @MadAntrax's.

The main difference is that it uses a VBScript user-defined class to wrap all the logic for switching to CScript and outputting text to the console, so it makes the main script a bit cleaner.

This assumes that your objective is to stream output to the console, rather than having output go to message boxes.

The cCONSOLE class is below. To use it, include the complete class at the end of your script, and then instantiate it right at the beginning of the script. Here is an example:

    Option Explicit

'// Instantiate the console object, this automatically switches to CSCript if required
Dim CONS: Set CONS = New cCONSOLE

'// Now we can use the Consol object to write to and read from the console
With CONS

    '// Simply write a line
     .print "CSCRIPT Console demo script"

     '// Arguments are passed through correctly, if present
     .Print "Arg count=" & wscript.arguments.count

     '// List all the arguments on the console log
     dim ix
     for ix = 0 to wscript.arguments.count -1
        .print "Arg(" & ix & ")=" & wscript.arguments(ix)
     next

     '// Prompt for some text from the user
     dim sMsg : sMsg = .prompt( "Enter any text:" )

     '// Write out the text in a box
     .Box sMsg

     '// Pause with the message "Hit enter to continue"
     .Pause

End With     




'= =========== End of script - the cCONSOLE class code follows here

Here is the code for the cCONSOLE class

     CLASS cCONSOLE
 '= =================================================================
 '= 
 '=    This class provides automatic switch to CScript and has methods
 '=    to write to and read from the CSCript console. It transparently
 '=    switches to CScript if the script has been started in WScript.
 '=
 '= =================================================================

    Private oOUT
    Private oIN


    Private Sub Class_Initialize()
    '= Run on creation of the cCONSOLE object, checks for cScript operation


        '= Check to make sure we are running under CScript, if not restart
        '= then run using CScript and terminate this instance.
        dim oShell
        set oShell = CreateObject("WScript.Shell")

        If InStr( LCase( WScript.FullName ), "cscript.exe" ) = 0 Then
            '= Not running under CSCRIPT

            '= Get the arguments on the command line and build an argument list
            dim ArgList, IX
            ArgList = ""

            For IX = 0 to wscript.arguments.count - 1
                '= Add the argument to the list, enclosing it in quotes
                argList = argList & " """ & wscript.arguments.item(IX) & """"
            next

            '= Now restart with CScript and terminate this instance
            oShell.Run "cscript.exe //NoLogo """ & WScript.ScriptName & """ " & arglist
            WScript.Quit

        End If

        '= Running under CScript so OK to continue
        set oShell = Nothing

        '= Save references to stdout and stdin for use with Print, Read and Prompt
        set oOUT = WScript.StdOut
        set oIN = WScript.StdIn

        '= Print out the startup box 
            StartBox
            BoxLine Wscript.ScriptName
            BoxLine "Started at " & Now()
            EndBox


    End Sub

    '= Utility methods for writing a box to the console with text in it

            Public Sub StartBox()

                Print "  " & String(73, "_") 
                Print " |" & Space(73) & "|"
            End Sub

            Public Sub BoxLine(sText)

                Print Left(" |" & Centre( sText, 74) , 75) & "|"
            End Sub

            Public Sub EndBox()
                Print " |" & String(73, "_") & "|"
                Print ""
            End Sub

            Public Sub Box(sMsg)
                StartBox
                BoxLine sMsg
                EndBox
            End Sub

    '= END OF Box utility methods


            '= Utility to center given text padded out to a certain width of text
            '= assuming font is monospaced
            Public Function Centre(sText, nWidth)
                dim iLen
                iLen = len(sText)

                '= Check for overflow
                if ilen > nwidth then Centre = sText : exit Function

                '= Calculate padding either side
                iLen = ( nWidth - iLen ) / 2

                '= Generate text with padding
                Centre = left( space(iLen) & sText & space(ilen), nWidth )
            End Function



    '= Method to write a line of text to the console
    Public Sub Print( sText )

        oOUT.WriteLine sText
    End Sub

    '= Method to prompt user input from the console with a message
    Public Function Prompt( sText )
        oOUT.Write sText
        Prompt = Read()
    End Function

    '= Method to read input from the console with no prompting
    Public Function Read()
        Read = oIN.ReadLine
    End Function

    '= Method to provide wait for n seconds
    Public Sub Wait(nSeconds)
        WScript.Sleep  nSeconds * 1000 
    End Sub

    '= Method to pause for user to continue
    Public Sub Pause
        Prompt "Hit enter to continue..."
    End Sub


 END CLASS

Ordering by specific field value first

do this:

SELECT * FROM table ORDER BY column `name`+0 ASC

Appending the +0 will mean that:

0, 10, 11, 2, 3, 4

becomes :

0, 2, 3, 4, 10, 11

Writing binary number system in C code

Use BOOST_BINARY (Yes, you can use it in C).

#include <boost/utility/binary.hpp>
...
int bin = BOOST_BINARY(110101);

This macro is expanded to an octal literal during preprocessing.

Capitalize or change case of an NSString in Objective-C

Here ya go:

viewNoteDateMonth.text  = [[displayDate objectAtIndex:2] uppercaseString];

Btw:
"april" is lowercase ? [NSString lowercaseString]
"APRIL" is UPPERCASE ? [NSString uppercaseString]
"April May" is Capitalized/Word Caps ? [NSString capitalizedString]
"April may" is Sentence caps ? (method missing; see workaround below)

Hence what you want is called "uppercase", not "capitalized". ;)

As for "Sentence Caps" one has to keep in mind that usually "Sentence" means "entire string". If you wish for real sentences use the second method, below, otherwise the first:

@interface NSString ()

- (NSString *)sentenceCapitalizedString; // sentence == entire string
- (NSString *)realSentenceCapitalizedString; // sentence == real sentences

@end

@implementation NSString

- (NSString *)sentenceCapitalizedString {
    if (![self length]) {
        return [NSString string];
    }
    NSString *uppercase = [[self substringToIndex:1] uppercaseString];
    NSString *lowercase = [[self substringFromIndex:1] lowercaseString];
    return [uppercase stringByAppendingString:lowercase];
}

- (NSString *)realSentenceCapitalizedString {
    __block NSMutableString *mutableSelf = [NSMutableString stringWithString:self];
    [self enumerateSubstringsInRange:NSMakeRange(0, [self length])
                             options:NSStringEnumerationBySentences
                          usingBlock:^(NSString *sentence, NSRange sentenceRange, NSRange enclosingRange, BOOL *stop) {
        [mutableSelf replaceCharactersInRange:sentenceRange withString:[sentence sentenceCapitalizedString]];
    }];
    return [NSString stringWithString:mutableSelf]; // or just return mutableSelf.
}

@end

curl_exec() always returns false

In my case I need to set VERIFYHOST and VERIFYPEER to false, like this:

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

before the call to curl_exec($ch).

Because i am working between two development environments with self-assigned certificates. With valid certificates there is no need to set VERIFYHOST and VERIFYPEER to false because the curl_exec($ch) method will work and return the response you expect.

Commenting multiple lines in DOS batch file

If you want to add REM at the beginning of each line instead of using GOTO, you can use Notepad++ to do this easily following these steps:

  1. Select the block of lines
  2. hit Ctrl-Q

Repeat steps to uncomment

How to format code in Xcode?

Key combination to format all text on open file:

Cmd ? A + Ctrl I

Javascript getElementsByName.value not working

You have mentioned Wrong id

alert(document.getElementById("name").value);

if you want to use name attribute then

alert(document.getElementsByName("username")[0].value);

Updates:

input type="text" id="name" name="username"  

id is different from name

npm behind a proxy fails with status 403

In my case, I read the registry that npm using:

 npm config get registry

and I got

http://registry.npmjs.org/

then I had just changed http to https like this:

npm config set registry https://registry.npmjs.org/

How to install python modules without root access?

You can run easy_install to install python packages in your home directory even without root access. There's a standard way to do this using site.USER_BASE which defaults to something like $HOME/.local or $HOME/Library/Python/2.7/bin and is included by default on the PYTHONPATH

To do this, create a .pydistutils.cfg in your home directory:

cat > $HOME/.pydistutils.cfg <<EOF
[install]
user=1
EOF

Now you can run easy_install without root privileges:

easy_install boto

Alternatively, this also lets you run pip without root access:

pip install boto

This works for me.

Source from Wesley Tanaka's blog : http://wtanaka.com/node/8095

How to enable named/bind/DNS full logging?

I usually expand each log out into it's own channel and then to a separate log file, certainly makes things easier when you are trying to debug specific issues. So my logging section looks like the following:

logging {
    channel default_file {
        file "/var/log/named/default.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel general_file {
        file "/var/log/named/general.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel database_file {
        file "/var/log/named/database.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel security_file {
        file "/var/log/named/security.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel config_file {
        file "/var/log/named/config.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel resolver_file {
        file "/var/log/named/resolver.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel xfer-in_file {
        file "/var/log/named/xfer-in.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel xfer-out_file {
        file "/var/log/named/xfer-out.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel notify_file {
        file "/var/log/named/notify.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel client_file {
        file "/var/log/named/client.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel unmatched_file {
        file "/var/log/named/unmatched.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel queries_file {
        file "/var/log/named/queries.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel network_file {
        file "/var/log/named/network.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel update_file {
        file "/var/log/named/update.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel dispatch_file {
        file "/var/log/named/dispatch.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel dnssec_file {
        file "/var/log/named/dnssec.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel lame-servers_file {
        file "/var/log/named/lame-servers.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };

    category default { default_file; };
    category general { general_file; };
    category database { database_file; };
    category security { security_file; };
    category config { config_file; };
    category resolver { resolver_file; };
    category xfer-in { xfer-in_file; };
    category xfer-out { xfer-out_file; };
    category notify { notify_file; };
    category client { client_file; };
    category unmatched { unmatched_file; };
    category queries { queries_file; };
    category network { network_file; };
    category update { update_file; };
    category dispatch { dispatch_file; };
    category dnssec { dnssec_file; };
    category lame-servers { lame-servers_file; };
};

Hope this helps.

Use dynamic (variable) string as regex pattern in JavaScript

You don't need the " to define a regular expression so just:

var regex = /(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is; // this is valid syntax

If value is a variable and you want a dynamic regular expression then you can't use this notation; use the alternative notation.

String.replace also accepts strings as input, so you can do "fox".replace("fox", "bear");

Alternative:

var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(.*?)\b/", "is");

Keep in mind that if value contains regular expressions characters like (, [ and ? you will need to escape them.

How to click an element in Selenium WebDriver using JavaScript

Another easiest solution is to use Key.RETUEN

Click here for solution in detail

driver.findElement(By.name("q")).sendKeys("Selenium Tutorial", Key.RETURN);

How can I reset eclipse to default settings?

Delete the .metadata folder in your workspace.

How to export data with Oracle SQL Developer?

In SQL Developer, from the top menu choose Tools > Data Export. This launches the Data Export wizard. It's pretty straightforward from there.

There is a tutorial on the OTN site. Find it here.

CSS flex, how to display one item on first line and two on the next line

The answer given by Nico O is correct. However this doesn't get the desired result on Internet Explorer 10 to 11 and Firefox.

For IE, I found that changing

.flex > div
{
   flex: 1 0 50%;
}

to

.flex > div
{
   flex: 1 0 45%;
}

seems to do the trick. Don't ask me why, I haven't gone any further into this but it might have something to do with how IE renders the border-box or something.

In the case of Firefox I solved it by adding

display: inline-block;

to the items.

What's the best way to center your HTML email content in the browser window (or email client preview pane)?

I was struggling with Outlook and Office365. Surprisingly the thing that seemed to work was:

<table align='center' style='text-align:center'>
  <tr>
    <td align='center' style='text-align:center'>
      <!-- AMAZING CONTENT! -->
    </td>
  </tr>
</table>

I only listed some of the key things that resolved my Microsoft email issues.

Might I add that building an email that looks nice on all emails is a pain. This website was super nice for testing: https://putsmail.com/

It allows you to list all the emails you'd like to send your test email to. You can paste your code right into the window, edit, send, and resend. It helped me a ton.

Javascript loop through object array?

In your script, data is your whole object.

key is "messages", which is an array you need to iterate through like this:

    for (var key in data) {
       var arr = data[key];
       for( var i = 0; i < arr.length; i++ ) {
           var obj = arr[ i ];
           for (var prop in obj) {
               if(obj.hasOwnProperty(prop)){
                   console.log(prop + " = " + obj[prop]);
               }
           }
       }
    }

Best way to do multiple constructors in PHP

I created this method to let use it not only on constructors but in methods:

My constructor:

function __construct() {
    $paramsNumber=func_num_args();
    if($paramsNumber==0){
        //do something
    }else{
        $this->overload('__construct',func_get_args());
    }
}

My doSomething method:

public function doSomething() {
    $paramsNumber=func_num_args();
    if($paramsNumber==0){
        //do something
    }else{
        $this->overload('doSomething',func_get_args());
    }
}

Both works with this simple method:

public function overloadMethod($methodName,$params){
    $paramsNumber=sizeof($params);
    //methodName1(), methodName2()...
    $methodNameNumber =$methodName.$paramsNumber;
    if (method_exists($this,$methodNameNumber)) {
        call_user_func_array(array($this,$methodNameNumber),$params);
    }
}

So you can declare

__construct1($arg1), __construct2($arg1,$arg2)...

or

methodName1($arg1), methodName2($arg1,$arg2)...

and so on :)

And when using:

$myObject =  new MyClass($arg1, $arg2,..., $argN);

it will call __constructN, where you defined N args

then $myObject -> doSomething($arg1, $arg2,..., $argM)

it will call doSomethingM, , where you defined M args;

How to get an ASP.NET MVC Ajax response to redirect to new page instead of inserting view into UpdateTargetId?

The accepted answer works well except for the fact that the javascript is briefly displayed in whatever the ajax target element is. To get around this, create a partial view called _Redirect with the following code:

@model string
<script>
   window.location = '@Model';
</script>

Then, in the controller replace

return Redirect(Url.Action("Index", "Home"));

with

return PartialView("_Redirect",Url.Action("Index", "Home"));

The effect is the same as the accepted answer, but without the brief artifact in the display. Place the _Redirect.cshtml in the shared folder so it can be used from anywhere.

How to declare a constant map in Golang?

Your syntax is incorrect. To make a literal map (as a pseudo-constant), you can do:

var romanNumeralDict = map[int]string{
  1000: "M",
  900 : "CM",
  500 : "D",
  400 : "CD",
  100 : "C",
  90  : "XC",
  50  : "L",
  40  : "XL",
  10  : "X",
  9   : "IX",
  5   : "V",
  4   : "IV",
  1   : "I",
}

Inside a func you can declare it like:

romanNumeralDict := map[int]string{
...

And in Go there is no such thing as a constant map. More information can be found here.

Try it out on the Go playground.

How to properly add 1 month from now to current date in moment.js

You could try

moment().add(1, 'M').subtract(1, 'day').format('DD-MM-YYYY')

What's the -practical- difference between a Bare and non-Bare repository?

I'm certainly not a Git "expert". I have used TortoiseGit for a while, and wondered what it was talking about when it asked me if I wanted to make a "bare" repo whenever I created one. I was reading this tutorial: https://www.atlassian.com/git/tutorials/setting-up-a-repository/git-init and it addresses the issue, but I still was not quite understanding the concept. This one helped a lot: http://bitflop.com/tutorials/git-bare-vs-non-bare-repositories.html. Now, the first one makes sense too!

According to these sources, in a nutshell a "bare" repo is used on a server where you want to setup a distribution point. It's not intented for use on your local machine. You generally push commits from your local machine to a bare repo on a remote server, and you and/or others pull from that bare repo to your local machine. So your GitHub, Assembla, etc. remote storage / distribution repo is an example where a "bare" repo is created. You would make one yourself if you were setting up your own analogous "sharing center".

How to implement common bash idioms in Python?

You can use python instead of bash with the ShellPy library.

Here is an example that downloads avatar of Python user from Github:

import json
import os
import tempfile

# get the api answer with curl
answer = `curl https://api.github.com/users/python
# syntactic sugar for checking returncode of executed process for zero
if answer:
    answer_json = json.loads(answer.stdout)
    avatar_url = answer_json['avatar_url']

    destination = os.path.join(tempfile.gettempdir(), 'python.png')

    # execute curl once again, this time to get the image
    result = `curl {avatar_url} > {destination}
    if result:
        # if there were no problems show the file
        p`ls -l {destination}
    else:
        print('Failed to download avatar')

    print('Avatar downloaded')
else:
    print('Failed to access github api')

As you can see, all expressions inside of grave accent ( ` ) symbol are executed in shell. And in Python code, you can capture results of this execution and perform actions on it. For example:

log = `git log --pretty=oneline --grep='Create'

This line will first execute git log --pretty=oneline --grep='Create' in shell and then assign the result to the log variable. The result has the following properties:

stdout the whole text from stdout of the executed process

stderr the whole text from stderr of the executed process

returncode returncode of the execution

This is general overview of the library, more detailed description with examples can be found here.

How to set CATALINA_HOME variable in windows 7?

In order to set CATALINA_HOME:

  1. First, unzip and paste the apache-tomcat-7.1.100 folder in your C:// drive folder.

NOTE: Do not place your apache tomcat folder within any other folder or drive, place it directly in C:// drive folder only. (I did this mistake and none of the above-mentioned solutions were working).

  1. Open environment variable dialog box (windows key+ pause-break key --> advanced setting).

  2. Add a new variable name as "CATALINA_HOME" and add the variable path as "C://apache-tomcat-7.1.100"(as in my case), in System Variables.

  3. Edit PATH variable name add "%CATALINA_HOME%\bin" and press OK.

  4. Close the window and it will be saved.

  5. Open Command Prompt window and type command- "%CATALINA_HOME%\bin\startup.bat" to run and start the Tomcat server.

  6. END!

Best way to check if a character array is empty

if (text[0] == '\0')
{
    /* Code... */
}

Use this if you're coding for micro-controllers with little space on flash and/or RAM. You will waste a lot more flash using strlen than checking the first byte.

The above example is the fastest and less computation is required.

Custom circle button

if you want use VectorDrawable and ConstraintLayout

<FrameLayout
            android:id="@+id/ok_button"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:foreground="?attr/selectableItemBackgroundBorderless"
            android:background="@drawable/circle_button">
                <android.support.constraint.ConstraintLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">
                    <ImageView
                        android:id="@+id/icon_of_button"
                        android:layout_width="32dp"
                        android:layout_height="32dp"
                        app:layout_constraintBottom_toBottomOf="parent"
                        app:layout_constraintTop_toTopOf="parent"
                        app:layout_constraintRight_toRightOf="parent"
                        app:layout_constraintLeft_toLeftOf="parent"
                        app:srcCompat="@drawable/ic_thumbs_up"/>
                    <TextView
                        android:id="@+id/text_of_button"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        app:layout_constraintTop_toBottomOf="@+id/icon_of_button"
                        app:layout_constraintRight_toRightOf="parent"
                        app:layout_constraintLeft_toLeftOf="parent"
                        android:layout_marginTop="5dp"
                        android:textColor="@android:color/white"
                        android:text="ok"
                        />
                </android.support.constraint.ConstraintLayout>
            </FrameLayout>

circle background: circle_button.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="1000dp" />
<solid android:color="#41ba7a" />
<stroke
    android:width="2dip"
    android:color="#03ae3c" />
<padding
    android:bottom="4dp"
    android:left="4dp"
    android:right="4dp"
    android:top="4dp" />
</shape>

How can I set the Secure flag on an ASP.NET Session Cookie?

Things get messy quickly if you are talking about checked-in code in an enterprise environment. We've found that the best approach is to have the web.Release.config contain the following:

<system.web>
  <compilation xdt:Transform="RemoveAttributes(debug)" />
  <authentication>
      <forms xdt:Transform="Replace" timeout="20" requireSSL="true" />
  </authentication>
</system.web>

That way, developers are not affected (running in Debug), and only servers that get Release builds are requiring cookies to be SSL.

PHP Curl And Cookies

Here you can find some useful info about cURL & cookies http://docstore.mik.ua/orelly/webprog/pcook/ch11_04.htm .

You can also use this well done method https://github.com/alixaxel/phunction/blob/master/phunction/Net.php#L89 like a function:

function CURL($url, $data = null, $method = 'GET', $cookie = null, $options = null, $retries = 3)
{
    $result = false;

    if ((extension_loaded('curl') === true) && (is_resource($curl = curl_init()) === true))
    {
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_FAILONERROR, true);
        curl_setopt($curl, CURLOPT_AUTOREFERER, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

        if (preg_match('~^(?:DELETE|GET|HEAD|OPTIONS|POST|PUT)$~i', $method) > 0)
        {
            if (preg_match('~^(?:HEAD|OPTIONS)$~i', $method) > 0)
            {
                curl_setopt_array($curl, array(CURLOPT_HEADER => true, CURLOPT_NOBODY => true));
            }

            else if (preg_match('~^(?:POST|PUT)$~i', $method) > 0)
            {
                if (is_array($data) === true)
                {
                    foreach (preg_grep('~^@~', $data) as $key => $value)
                    {
                        $data[$key] = sprintf('@%s', rtrim(str_replace('\\', '/', realpath(ltrim($value, '@'))), '/') . (is_dir(ltrim($value, '@')) ? '/' : ''));
                    }

                    if (count($data) != count($data, COUNT_RECURSIVE))
                    {
                        $data = http_build_query($data, '', '&');
                    }
                }

                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }

            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, strtoupper($method));

            if (isset($cookie) === true)
            {
                curl_setopt_array($curl, array_fill_keys(array(CURLOPT_COOKIEJAR, CURLOPT_COOKIEFILE), strval($cookie)));
            }

            if ((intval(ini_get('safe_mode')) == 0) && (ini_set('open_basedir', null) !== false))
            {
                curl_setopt_array($curl, array(CURLOPT_MAXREDIRS => 5, CURLOPT_FOLLOWLOCATION => true));
            }

            if (is_array($options) === true)
            {
                curl_setopt_array($curl, $options);
            }

            for ($i = 1; $i <= $retries; ++$i)
            {
                $result = curl_exec($curl);

                if (($i == $retries) || ($result !== false))
                {
                    break;
                }

                usleep(pow(2, $i - 2) * 1000000);
            }
        }

        curl_close($curl);
    }

    return $result;
}

And pass this as $cookie parameter:

$cookie_jar = tempnam('/tmp','cookie');

How to get a product's image in Magento?

get product images in magento using product id

    $product_id = $_POST['product_id'];
    $storeId    = Mage::app()->getStore()->getId();
    $loadpro    = Mage::getModel('catalog/product')->load($product_id);

    $mediaApi      =  Mage::getModel("catalog/product_attribute_media_api");
    $mediaApiItems = $mediaApi->items($loadpro->getId());
    foreach ($mediaApiItems as $item) {
            //for getting existing Images
            echo $item['file'];
            }

Why can't Python import Image from PIL?

In Ubuntu OS, I solved it with the followings commands

pip install Pillow
apt-get install python-imaging

And sorry, dont ask me why, it's up to me ;-)

What is an alternative to execfile in Python 3?

As suggested on the python-dev mailinglist recently, the runpy module might be a viable alternative. Quoting from that message:

https://docs.python.org/3/library/runpy.html#runpy.run_path

import runpy
file_globals = runpy.run_path("file.py")

There are subtle differences to execfile:

  • run_path always creates a new namespace. It executes the code as a module, so there is no difference between globals and locals (which is why there is only a init_globals argument). The globals are returned.

    execfile executed in the current namespace or the given namespace. The semantics of locals and globals, if given, were similar to locals and globals inside a class definition.

  • run_path can not only execute files, but also eggs and directories (refer to its documentation for details).

In React Native, how do I put a view on top of another view, with part of it lying outside the bounds of the view behind?

You can use react-native-view-overflow plugin for placing a view on top of another. It works like the CSS z-index property.

import ViewOverflow from 'react-native-view-overflow';

<ViewOverflow />
    <View style={[styles2.cardBox, { marginTop: 50 }]}>
    <View style={[styles2.cardItem]} >
      <Text style={styles2.cardHeader}>userList</Text>
    </View>
      <View style={[styles2.cardContent]}>
        <Text style={styles2.text}>overflow: "visible"</Text>
      </View>
      <View style={[styles2.cardItemFooter]} >
        <Text style={styles2.cardTextFooter}>...</Text>
      </View>
    </View>
  </ViewOverflow>

const styles2 = StyleSheet.create({
  cardBox: {
    borderLeftWidth: 0,
    borderTopWidth: 0,
    backgroundColor: "transparent",
    borderWidth: 1,
    borderColor: "#d0d0d0",
    width: '94%',
    alignSelf: 'center',
    height: 200,
    position: "relative",
    borderRadius: 15,
    overflow: "visible" // doesn't do anything
  },
  cardContent: {
    textAlign: "right",
    backgroundColor: "transparent",
    marginTop: 15,
    alignSelf: 'flex-end',
    padding: 5,
  },
  cardHeader: {
    color: '#fff',
    fontFamily: 'Vazir',
    fontSize: 12
  },
  cardItem: {
    backgroundColor: "#3c4252",
    borderRadius: 3,
    position: "absolute",
    top: -10,
    right: -5,
    width: 50,
    height: 20,
    paddingRight: 5,
  },
})

JUNIT Test class in Eclipse - java.lang.ClassNotFoundException

You may need to do a combination of the above to resolve this problem. I normally get this error when I do

mvn clean install

and see a compile error preventing the my tests from fully compiling.

Assuming the issues resolved by the above have been dealt with, try clicking Project, Clean, and clean the project which contains the test you want to run. Also make sure Build Automatically is checked.

How is a CSS "display: table-column" supposed to work?

The "table-column" display type means it acts like the <col> tag in HTML - i.e. an invisible element whose width* governs the width of the corresponding physical column of the enclosing table.

See the W3C standard for more information about the CSS table model.

* And a few other properties like borders, backgrounds.

How do you change text to bold in Android?

For case where you are using custom fonts, but do not have bold typeface for the font you can use:

myTextView.setText(Html.fromHtml("<b>" + myText + "</b>");

Arithmetic operation resulted in an overflow. (Adding integers)

The result integer value is out of the range which an integer data type can hold.

Try using Int64

Trigger back-button functionality on button click in Android

public boolean onKeyDown(int keyCode, KeyEvent event) {
             if (keyCode == KeyEvent.KEYCODE_BACK) {
                     // your code here
                     return false;
             }
         return super.onKeyDown(keyCode, event);
     }

Submitting form and pass data to controller method of type FileStreamResult

This is because you have specified the form method as GET

Change code in the view to this:

using (@Html.BeginForm("myMethod", "Home", FormMethod.Post, new { id = @item.JobId })){
}

Convert List<String> to List<Integer> directly

No, you will have to iterate over each element:

for(String number : numbers) {
   numberList.add(Integer.parseInt(number)); 
}

The reason this happens is that there is no straightforward way to convert a list of one type into any other type. Some conversions are not possible, or need to be done in a specific way. Essentially the conversion depends on the objects involved and the context of the conversion so there is no "one size fits all" solution. For example, what if you had a Car object and a Person object. You can't convert a List<Car> into a List<Person> directly since it doesn't really make sense.

How do format a phone number as a String in Java?

The easiest way to do this is by using the built in MaskFormatter in the javax.swing.text library.

You can do something like this :

import javax.swing.text.MaskFormatter;

String phoneMask= "###-###-####";
String phoneNumber= "123423452345";

MaskFormatter maskFormatter= new MaskFormatter(phoneMask);
maskFormatter.setValueContainsLiteralCharacters(false);
maskFormatter.valueToString(phoneNumber) ;

Read Post Data submitted to ASP.Net Form

if (!string.IsNullOrEmpty(Request.Form["username"])) { ... }

username is the name of the input on the submitting page. The password can be obtained the same way. If its not null or empty, it exists, then log in the user (I don't recall the exact steps for ASP.NET Membership, assuming that's what you're using).

php error: Class 'Imagick' not found

Debian 9

I just did the following and everything else needed got automatically installed as well.

sudo apt-get -y -f install php-imagick
sudo /etc/init.d/apache2 restart

What does .shape[] do in "for i in range(Y.shape[0])"?

The shape attribute for numpy arrays returns the dimensions of the array. If Y has n rows and m columns, then Y.shape is (n,m). So Y.shape[0] is n.

In [46]: Y = np.arange(12).reshape(3,4)

In [47]: Y
Out[47]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

In [48]: Y.shape
Out[48]: (3, 4)

In [49]: Y.shape[0]
Out[49]: 3

Does Java have something like C#'s ref and out keywords?

Actually there is neither ref nor out keyword equivalent in Java language as far as I know. However I've just transformed a C# code into Java that uses out parameter and will advise what I've just done. You should wrap whatever object into a wrapper class and pass the values wrapped in wrapper object instance as follows;

A Simple Example For Using Wrapper

Here is the Wrapper Class;

public class Wrapper {
    public Object ref1; // use this as ref
    public Object ref2; // use this as out

    public Wrapper(Object ref1) {
        this.ref1 = ref1;
    }
}

And here is the test code;

public class Test {

    public static void main(String[] args) {
        String abc = "abc";
        changeString(abc);
        System.out.println("Initial object: " + abc); //wont print "def"

        Wrapper w = new Wrapper(abc);
        changeStringWithWrapper(w);
        System.out.println("Updated object: " + w.ref1);
        System.out.println("Out     object: " + w.ref2);
    }

    // This won't work
    public static void changeString(String str) {
        str = "def";
    }

    // This will work
    public static void changeStringWithWrapper(Wrapper w) {
        w.ref1 = "def";
        w.ref2 = "And this should be used as out!";
    }

}

A Real World Example

A C#.NET method using out parameter

Here there is a C#.NET method that is using out keyword;

public bool Contains(T value)
{
    BinaryTreeNode<T> parent;
    return FindWithParent(value, out parent) != null;
}

private BinaryTreeNode<T> FindWithParent(T value, out BinaryTreeNode<T> parent)
{
    BinaryTreeNode<T> current = _head;
    parent = null;

    while(current != null)
    {
        int result = current.CompareTo(value);

        if (result > 0)
        {
            parent = current;
            current = current.Left;
        }
        else if (result < 0)
        {
            parent = current;
            current = current.Right;
        }
        else
        {
            break;
        }
    }

    return current;
}

Java Equivalent of the C# code that is using the out parameter

And the Java equivalent of this method with the help of wrapper class is as follows;

public boolean contains(T value) {
    BinaryTreeNodeGeneration<T> result = findWithParent(value);

    return (result != null);
}

private BinaryTreeNodeGeneration<T> findWithParent(T value) {
    BinaryTreeNode<T> current = head;
    BinaryTreeNode<T> parent = null;
    BinaryTreeNodeGeneration<T> resultGeneration = new BinaryTreeNodeGeneration<T>();
    resultGeneration.setParentNode(null);

    while(current != null) {
        int result = current.compareTo(value);

        if(result >0) {
            parent = current;
            current = current.left;
        } else if(result < 0) {
            parent = current;
            current = current.right;
        } else {
            break;
        }
    }

    resultGeneration.setChildNode(current);
    resultGeneration.setParentNode(parent);

    return resultGeneration;
}

Wrapper Class

And the wrapper class used in this Java code is as below;

public class BinaryTreeNodeGeneration<TNode extends Comparable<TNode>>  {

    private BinaryTreeNode<TNode>   parentNode;
    private BinaryTreeNode<TNode>   childNode;

    public BinaryTreeNodeGeneration() {
        this.parentNode = null;
        this.childNode = null;
    }

    public BinaryTreeNode<TNode> getParentNode() {
        return parentNode;
    }

    public void setParentNode(BinaryTreeNode<TNode> parentNode) {
        this.parentNode = parentNode;
    }

    public BinaryTreeNode<TNode> getChildNode() {
        return childNode;
    }

    public void setChildNode(BinaryTreeNode<TNode> childNode) {
        this.childNode = childNode;
    }

}

Clearing UIWebview cache

You can disable the caching by doing the following:

NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
[sharedCache release];

ARC:

NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];

How to cast int to enum in C++?

Test e = static_cast<Test>(1);

Error #2032: Stream Error

This error also occurs if you did not upload the various rsl/swc/flash-library that your swf file might expect. You may upload this RSL or missing swc or tweak your compiler options cf. http://help.adobe.com/en_US/flashbuilder/using/WSe4e4b720da9dedb5-1a92eab212e75b9d8b2-7ffe.html#WSe4e4b720da9dedb5-1a92eab212e75b9d8b2-7ff5

App.Config Transformation for projects which are not Web Projects in Visual Studio?

In my experience, the things I need to make environment-specific are things like connection strings, appsettings and often smpt settings. The config system allows to specify these things in separate files. So you can use this in your app.config/web.config:

 <appSettings configSource="appsettings.config" />
 <connectionStrings configSource="connection.config" />
 <system.net>
    <mailSettings>
       <smtp configSource="smtp.config"/>
    </mailSettings>
 </system.net>

What I typically do is to put these config-specific sections in separate files, in a subfolder called ConfigFiles (either in the solution root or at the project level, depends). I define a file per configuration, e.g. smtp.config.Debug and smtp.config.Release.

Then you can define a pre-build event like so:

copy $(ProjectDir)ConfigFiles\smtp.config.$(ConfigurationName) $(TargetDir)smtp.config

In team development, you can tweak this further by including the %COMPUTERNAME% and/or %USERNAME% in the convention.

Of course, this implies that the target files (x.config) should NOT be put in source control (since they are generated). You should still add them to the project file and set their output type property to 'copy always' or 'copy if newer' though.

Simple, extensible, and it works for all types of Visual Studio projects (console, winforms, wpf, web).

Show values from a MySQL database table inside a HTML table on a webpage

Example taken from W3Schools: PHP Select Data from MySQL

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM Persons");

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";

while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";

mysqli_close($con);
?>

It's a good place to learn from!

How to pass credentials to the Send-MailMessage command for sending emails

PSH> $cred = Get-Credential

PSH> $cred | Export-CliXml c:\temp\cred.clixml

PSH> $cred2 = Import-CliXml c:\temp\cred.clixml

That hashes it against your SID and the machine's SID, so the file is useless on any other machine, or in anyone else's hands.

How to make a simple image upload using Javascript/HTML

Try this, It supports multi file uploading,

$('#multi_file_upload').change(function(e) {
    var file_id = e.target.id;

    var file_name_arr = new Array();
    var process_path = site_url + 'public/uploads/';

    for (i = 0; i < $("#" + file_id).prop("files").length; i++) {

        var form_data = new FormData();
        var file_data = $("#" + file_id).prop("files")[i];
        form_data.append("file_name", file_data);

        if (check_multifile_logo($("#" + file_id).prop("files")[i]['name'])) {
            $.ajax({
                //url         :   site_url + "inc/upload_image.php?width=96&height=60&show_small=1",
                url: site_url + "inc/upload_contact_info.php",
                cache: false,
                contentType: false,
                processData: false,
                async: false,
                data: form_data,
                type: 'post',
                success: function(data) {
                    // display image
                }
            });
        } else {
            $("#" + html_div).html('');
            alert('We only accept JPG, JPEG, PNG, GIF and BMP files');
        }

    }
});

function check_multifile_logo(file) {
    var extension = file.substr((file.lastIndexOf('.') + 1))
    if (extension === 'jpg' || extension === 'jpeg' || extension === 'gif' || extension === 'png' || extension === 'bmp') {
        return true;
    } else {
        return false;
    }
}

Here #multi_file_upload is the ID of image upload field.

Complete list of reasons why a css file might not be working

I had the same problem, chinese characters were appearing in firefox when uploaded to web server, but not on localhost. I copied the contents of the css file to a new text file. All working now. Must have been a unicode/encoding error of some sort.

JavaScript closures vs. anonymous functions

You are both using closures.

I 'm going with the Wikipedia definition here:

In computer science, a closure (also lexical closure or function closure) is a function or reference to a function together with a referencing environment—a table storing a reference to each of the non-local variables (also called free variables) of that function. A closure—unlike a plain function pointer—allows a function to access those non-local variables even when invoked outside of its immediate lexical scope.

Your friend's attempt clearly uses the variable i, which is non-local, by taking its value and making a copy to store into the local i2.

Your own attempt passes i (which at the call site is in scope) to an anonymous function as an argument. This is not a closure so far, but then that function returns another function that references the same i2. Since inside the inner anonymous function i2 is not a local, this creates a closure.

How to initialize a variable of date type in java?

To parse a Date from a String you can choose which format you would like it to have. For example:

public Date StringToDate(String s){

    Date result = null;
    try{
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        result  = dateFormat.parse(s);
    }

    catch(ParseException e){
        e.printStackTrace();

    }
    return result ;
}

If you would like to use this method now, you will have to use something like this

Date date = StringToDate("2015-12-06 17:03:00");

For more explanation you should check out http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

How to split CSV files as per number of rows specified?

Made it into a function. You can now call splitCsv <Filename> [chunkSize]

splitCsv() {
    HEADER=$(head -1 $1)
    if [ -n "$2" ]; then
        CHUNK=$2
    else 
        CHUNK=1000
    fi
    tail -n +2 $1 | split -l $CHUNK - $1_split_
    for i in $1_split_*; do
        sed -i -e "1i$HEADER" "$i"
    done
}

Found on: http://edmondscommerce.github.io/linux/linux-split-file-eg-csv-and-keep-header-row.html

How to recover deleted rows from SQL server table?

What is gone is gone. The only protection I know of is regular backup.

Android - How To Override the "Back" button so it doesn't Finish() my Activity?

It was easier to implement it only with one line of code:

@Override
public void onBackPressed() {
   moveTaskToBack(true);
}

SecurityException during executing jnlp file (Missing required Permissions manifest attribute in main jar)

JAR File Manifest Attributes for Security

The JAR file manifest contains information about the contents of the JAR file, including security and configuration information.

Add the attributes to the manifest before the JAR file is signed.
See Modifying a Manifest File in the Java Tutorial for information on adding attributes to the JAR manifest file.

Permissions Attribute

The Permissions attribute is used to verify that the permissions level requested by the RIA when it runs matches the permissions level that was set when the JAR file was created.

Use this attribute to help prevent someone from re-deploying an application that is signed with your certificate and running it at a different privilege level. Set this attribute to one of the following values:

  • sandbox - runs in the security sandbox and does not require additional permissions.

  • all-permissions - requires access to the user's system resources.

Changes to Security Slider:

The following changes to Security Slider were included in this release(7u51):

  • Block Self-Signed and Unsigned applets on High Security Setting
  • Require Permissions Attribute for High Security Setting
  • Warn users of missing Permissions Attributes for Medium Security Setting

For more information, see Java Control Panel documentation.

enter image description here

sample MANIFEST.MF

Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.3
Created-By: 1.7.0_51-b13 (Oracle Corporation)
Trusted-Only: true
Class-Path: lib/plugin.jar
Permissions: sandbox
Codebase: http://myweb.de http://www.myweb.de
Application-Name: summary-applet

How to replace text in a column of a Pandas dataframe?

For anyone else arriving here from Google search on how to do a string replacement on all columns (for example, if one has multiple columns like the OP's 'range' column): Pandas has a built in replace method available on a dataframe object.

df.replace(',', '-', regex=True)

Source: Docs

How to Get the HTTP Post data in C#?

In my case because I assigned the post data to the header, this is how I get it:

protected void Page_Load(object sender, EventArgs e){
    ...
    postValue = Request.Headers["Key"];

This is how I attached the value and key to the POST:

var request = new NSMutableUrlRequest(url){
    HttpMethod = "POST", 
    Headers = NSDictionary.FromObjectAndKey(FromObject(value), FromObject("key"))
};
webView.LoadRequest(request);

installing requests module in python 2.7 windows

There are four options here:

  1. Get virtualenv set up. Each virtual environment you create will automatically have pip.

  2. Get pip set up globally.

  3. Learn how to install Python packages manually—in most cases it's as simple as download, unzip, python setup.py install, but not always.

  4. Use Christoph Gohlke's binary installers.

Restoring Nuget References?

I had the same issue with missing references. Below my scenario:

  • Fresh Windows 10 machine and VS Community 2015 install
  • Just checked out repository code via TFS
  • One solution built just fine, one solution had one project with missing references (EF, System.Http, as instance), but the relative nuget packages were properly installed.

All version numbers in project and packages match, doing nuget restore (in all its ways) did not work.

How I fixed it: simply delete the package folders in the solution root and execute nuget restore. At this point the dlls are correctly downloaded and can be added for the missing references.

DLL load failed error when importing cv2

Recently I have faced the similar issue in Azure Windows Server 2012 r2 . Tried all option with and without Anaconda but none of them helped. After lot of findings I found that mfplat.dll was missing which is related to Window Media Service.

Hence you have to manually install the features so that you can get dll related to window media service.

1.Turn windows features on or off

2.Skip the roles screen and directly go to Feature screen

3.Select "Desktop Experience" under "User Interfaces and Infrastructure"

After this all required dll of media services for opencv would be available.

So if you are planning to run your code in cloud(Window Server) then please dont forget to select Desktop Experience feature.

mysql: get record count between two date-time

for speed you can do this

WHERE date(created_at) ='2019-10-21'

What's the difference between emulation and simulation?

Please forgive me if I'm wrong. And I have to admit upfront that I haven't done any research on these 2 terms. Anyway...

Emulation is to mimic something with detailed known results, whatever the internal behaviors actually are. We only try to get things done and don't care much about what goes on inside.

Simulation, on the other hand, is to mimic something with some known behaviors to study something not being known yet.

my 2cents

What is the SQL command to return the field names of a table?

Just for completeness, since MySQL and Postgres have already been mentioned: With SQLite, use "pragma table_info()"

sqlite> pragma table_info('table_name');
cid         name        type        notnull     dflt_value  pk        
----------  ----------  ----------  ----------  ----------  ----------
0           id          integer     99                      1         
1           name                    0                       0         

How do I import global modules in Node? I get "Error: Cannot find module <module>"?

You can use npm link to create a symbolic link to your global package in your projects folder.

Example:

$ npm install -g express
$ cd [local path]/project
$ npm link express

All it does is create a local node_modules folder and then create a symlink express -> [global directory]/node_modules/express which can then be resolved by require('express')

You are trying to add a non-nullable field 'new_field' to userprofile without a default

You need to provide a default value:

new_field = models.CharField(max_length=140, default='SOME STRING')

Basic Authentication Using JavaScript

After Spending quite a bit of time looking into this, i came up with the solution for this; In this solution i am not using the Basic authentication but instead went with the oAuth authentication protocol. But to use Basic authentication you should be able to specify this in the "setHeaderRequest" with minimal changes to the rest of the code example. I hope this will be able to help someone else in the future:

var token_ // variable will store the token
var userName = "clientID"; // app clientID
var passWord = "secretKey"; // app clientSecret
var caspioTokenUrl = "https://xxx123.caspio.com/oauth/token"; // Your application token endpoint  
var request = new XMLHttpRequest(); 

function getToken(url, clientID, clientSecret) {
    var key;           
    request.open("POST", url, true); 
    request.setRequestHeader("Content-type", "application/json");
    request.send("grant_type=client_credentials&client_id="+clientID+"&"+"client_secret="+clientSecret); // specify the credentials to receive the token on request
    request.onreadystatechange = function () {
        if (request.readyState == request.DONE) {
            var response = request.responseText;
            var obj = JSON.parse(response); 
            key = obj.access_token; //store the value of the accesstoken
            token_ = key; // store token in your global variable "token_" or you could simply return the value of the access token from the function
        }
    }
}
// Get the token
getToken(caspioTokenUrl, userName, passWord);

If you are using the Caspio REST API on some request it may be imperative that you to encode the paramaters for certain request to your endpoint; see the Caspio documentation on this issue;

NOTE: encodedParams is NOT used in this example but was used in my solution.

Now that you have the token stored from the token endpoint you should be able to successfully authenticate for subsequent request from the caspio resource endpoint for your application

function CallWebAPI() {
    var request_ = new XMLHttpRequest();        
    var encodedParams = encodeURIComponent(params);
    request_.open("GET", "https://xxx123.caspio.com/rest/v1/tables/", true);
    request_.setRequestHeader("Authorization", "Bearer "+ token_);
    request_.send();
    request_.onreadystatechange = function () {
        if (request_.readyState == 4 && request_.status == 200) {
            var response = request_.responseText;
            var obj = JSON.parse(response); 
            // handle data as needed... 

        }
    }
} 

This solution does only considers how to successfully make the authenticated request using the Caspio API in pure javascript. There are still many flaws i am sure...

How do I download and save a file locally on iOS using objective C?

Sometime ago I implemented an easy to use "download manager" library: PTDownloadManager. You could give it a shot!

Python String and Integer concatenation

If we want output like 'string0123456789' then we can use map function and join method of string.

>>> 'string'+"".join(map(str,xrange(10)))
'string0123456789'

If we want List of string values then use list comprehension method.

>>> ['string'+i for i in map(str,xrange(10))]
['string0', 'string1', 'string2', 'string3', 'string4', 'string5', 'string6', 'string7', 'string8', 'string9']

Note:

Use xrange() for Python 2.x

USe range() for Python 3.x

LaTeX: remove blank page after a \part or \chapter

A solution that works:

Wrap the part of the document that needs this modified behavior with the code provided below. In my case the portion to wrap is a \part{} and some text following it.

\makeatletter\@openrightfalse
\part{Whatever}

Some text

\chapter{Foo}
\@openrighttrue\makeatother 

The wrapped portion should also include the chapter at the beginning of which this behavior needs to stop. Otherwise LaTeX may generate an empty page before this chapter.

Source: folks at the #latex IRC channel on irc.freenode.net

Is there a naming convention for MySQL?

Consistency is the key to any naming standard. As long as it's logical and consistent, you're 99% there.

The standard itself is very much personal preference - so if you like your standard, then run with it.

To answer your question outright - no, MySQL doesn't have a preferred naming convention/standard, so rolling your own is fine (and yours seems logical).

sum two columns in R

It could be that one or two of your columns may have a factor in them, or what is more likely is that your columns may be formatted as factors. Please would you give str(col1) and str(col2) a try? That should tell you what format those columns are in.

I am unsure if you're trying to add the rows of a column to produce a new column or simply all of the numbers in both columns to get a single number.

Can I set the height of a div based on a percentage-based width?

This can be done with a CSS hack (see the other answers), but it can also be done very easily with JavaScript.

Set the div's width to (for example) 50%, use JavaScript to check its width, and then set the height accordingly. Here's a code example using jQuery:

_x000D_
_x000D_
$(function() {_x000D_
    var div = $('#dynamicheight');_x000D_
    var width = div.width();_x000D_
    _x000D_
    div.css('height', width);_x000D_
});
_x000D_
#dynamicheight_x000D_
{_x000D_
    width: 50%;_x000D_
    _x000D_
    /* Just for looks: */_x000D_
    background-color: cornflowerblue;_x000D_
    margin: 25px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dynamicheight"></div>
_x000D_
_x000D_
_x000D_

If you want the box to scale with the browser window on resize, move the code to a function and call it on the window resize event. Here's a demonstration of that too (view example full screen and resize browser window):

_x000D_
_x000D_
$(window).ready(updateHeight);_x000D_
$(window).resize(updateHeight);_x000D_
_x000D_
function updateHeight()_x000D_
{_x000D_
    var div = $('#dynamicheight');_x000D_
    var width = div.width();_x000D_
    _x000D_
    div.css('height', width);_x000D_
}
_x000D_
#dynamicheight_x000D_
{_x000D_
    width: 50%;_x000D_
    _x000D_
    /* Just for looks: */_x000D_
    background-color: cornflowerblue;_x000D_
    margin: 25px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dynamicheight"></div>
_x000D_
_x000D_
_x000D_

How to get a list of sub-folders and their files, ordered by folder-names

Command to put list of all files and folders into a text file is as below:

Eg: dir /b /s | sort > ListOfFilesFolders.txt

How to add display:inline-block in a jQuery show() function?

Best way is to add !important suffix to the selector .

Example:

 #selector{
     display: inline-block !important;                   
}

RegEx - Match Numbers of Variable Length

You can specify how many times you want the previous item to match by using {min,max}.

{[0-9]{1,3}:[0-9]{1,3}}

Also, you can use \d for digits instead of [0-9] for most regex flavors:

{\d{1,3}:\d{1,3}}

You may also want to consider escaping the outer { and }, just to make it clear that they are not part of a repetition definition.

How to make external HTTP requests with Node.js

You can use node.js http module to do that. You could check the documentation at Node.js HTTP.

You would need to pass the query string as well to the other HTTP Server. You should have that in ServerRequest.url.

Once you have those info, you could pass in the backend HTTP Server and port in the options that you will provide in the http.request()

Selecting an element in iFrame jQuery

when your document is ready that doesn't mean that your iframe is ready too,
so you should listen to the iframe load event then access your contents:

$(function() {
    $("#my-iframe").bind("load",function(){
        $(this).contents().find("[tokenid=" + token + "]").html();
    });
});

Ping all addresses in network, windows

Open the Command Prompt and type in the following:

FOR /L %i IN (1,1,254) DO ping -n 1 192.168.10.%i | FIND /i "Reply">>c:\ipaddresses.txt

Change 192.168.10 to match you own network.

By using -n 1 you are asking for only 1 packet to be sent to each computer instead of the usual 4 packets.

The above command will ping all IP Addresses on the 192.168.10.0 network and create a text document in the C:\ drive called ipaddresses.txt. This text document should only contain IP Addresses that replied to the ping request.

Although it will take quite a bit longer to complete, you can also resolve the IP Addresses to HOST names by simply adding -a to the ping command.

FOR /L %i IN (1,1,254) DO ping -a -n 1 192.168.10.%i | FIND /i "Reply">>c:\ipaddresses.txt

This is from Here

Hope this helps

Angular: date filter adds timezone, how to output UTC?

The date filter always formats the dates using the local timezone. You'll have to write your own filter, based on the getUTCXxx() methods of Date, or on a library like moment.js.

PHP Error: Function name must be a string

It will be $_COOKIE['CaptchaResponseValue'], not $_COOKIE('CaptchaResponseValue')

How to import JsonConvert in C# application?

JsonConvert is from the namespace Newtonsoft.Json, not System.ServiceModel.Web

Use NuGet to download the package

"Project" -> "Manage NuGet packages" -> "Search for "newtonsoft json". -> click "install".

Why do people say that Ruby is slow?

Obviously, talking about speed Ruby loses. Even though benchmark tests suggest that Ruby is not so much slower than PHP. But in return, you are getting easy-to-maintain DRY code, the best out of all frameworks in various languages.

For a small project, you wont feel any slowness (I mean until like <50K users) given that no complex calculations are used in the code, just the mainstream stuff.

For a bigger project, paying for resources pays off and is cheaper than developer wages. In addition, writing code on RoR turns out to be much faster than any other.

In 2014 this magnitude of speed difference you're talking about is for most websites insignificant.

Storing sex (gender) in database

Option 3 is your best bet, but not all DB engines have a "bit" type. If you don't have a bit, then TinyINT would be your best bet.

AttributeError: 'module' object has no attribute 'urlretrieve'

A Python 2+3 compatible solution is:

import sys

if sys.version_info[0] >= 3:
    from urllib.request import urlretrieve
else:
    # Not Python 3 - today, it is most likely to be Python 2
    # But note that this might need an update when Python 4
    # might be around one day
    from urllib import urlretrieve

# Get file from URL like this:
urlretrieve("http://www-scf.usc.edu/~chiso/oldspice/m-b1-hello.mp3")

ASP MVC href to a controller/view

Here '~' refers to the root directory ,where Home is controller and Download_Excel_File is actionmethod

 <a href="~/Home/Download_Excel_File" />

Double.TryParse or Convert.ToDouble - which is faster and safer?

If you aren't going to be handling the exception go with TryParse. TryParse is faster because it doesn't have to deal with the whole exception stack trace.

Radio button checked event handling

Update in 2017: Hey. This is a terrible answer. Don't use it. Back in the old days this type of jQuery use was common. And it probably worked back then. Just read it, realize it's terrible, then move on (or downvote or, whatever) to one of the other answers that are better for today's jQuery.


$("input[type=radio]").change(function(){
    alert( $("input[type=radio][name="+ this.name + "]").val() );
});

Adding Access-Control-Allow-Origin header response in Laravel 5.3 Passport

The simple answer is to set the Access-Control-Allow-Origin header to localhost or *. Here's how I usually do it:

Add the following code to bootstrap/app.php:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Headers: *');

write() versus writelines() and concatenated strings

Exercise 16 from Zed Shaw's book? You can use escape characters as follows:

paragraph1 = "%s \n %s \n %s \n" % (line1, line2, line3)
target.write(paragraph1)
target.close()

Checkout old commit and make it a new commit

This is exactly what I wanted to do. I was not sure of the previous command git cherry-pick C, it sounds nice but it seems you do this to get changes from another branch but not on same branch, has anyone tried it?

So I did something else which also worked : I got the files I wanted back from the old commit file by file

git checkout <commit-hash> <filename>

ex : git checkout 08a6497b76ad098a5f7eda3e4ec89e8032a4da51 file.css

-> this takes the files as they were from the old commit

Then I did my changes. And I committed again.

git status (to check which files were modified)
git diff (to check the changes you made)
git add .
git commit -m "my message"

I checked my history with git log, and I still have my history along with my new changes made from the old files. And I could push too.

Note that to go back to the state you want you need to put the hash of the commit before the unwanted changes. Also make sure you don't have uncommitted changes before you do that.

What is the best way to get the count/length/size of an iterator?

Using Guava library, another option is to convert the Iterable to a List.

List list = Lists.newArrayList(some_iterator);
int count = list.size();

Use this if you need also to access the elements of the iterator after getting its size. By using Iterators.size() you no longer can access the iterated elements.

Wait until ActiveWorkbook.RefreshAll finishes - VBA

Try executing:

ActiveSheet.Calculate

I use it in a worksheet in which control buttons change values of a dataset. On each click, Excel runs through this command and the graph updates immediately.

How to completely hide the navigation bar in iPhone / HTML5

Try the following:

  1. Add this meta tag in the head of your HTML file:

    <meta name="apple-mobile-web-app-capable" content="yes" />
    
  2. Open your site with Safari on iPhone, and use the bookmark feature to add your site to the home screen.

  3. Go back to home screen and open the bookmarked site. The URL and status bar will be gone.

As long as you only need to work with the iPhone, you should be fine with this solution.

In addition, your sample on the warnerbros.com site uses the Sencha touch framework. You can Google it for more information or check out their demos.

How to go to each directory and execute a command?

  #!/bin.bash
for folder_to_go in $(find . -mindepth 1 -maxdepth 1 -type d \( -name "*" \) ) ; 
                                    # you can add pattern insted of * , here it goes to any folder 
                                    #-mindepth / maxdepth 1 means one folder depth   
do
cd $folder_to_go
  echo $folder_to_go "########################################## "
  
  whatever you want to do is here

cd ../ # if maxdepth/mindepath = 2,  cd ../../
done

#you can try adding many internal for loops with many patterns, this will sneak anywhere you want

Getting started with Haskell

I'd suggest joining the #haskell irc channel and asking questions there. That's how I learned Haskell. If you go through Real World Haskell as suggested above, real time answers to your questions will help greatly. Lots of smart people on #haskell write Haskell for fun and for profit, so you'll get lots of good input. Try it!

How can I provide multiple conditions for data trigger in WPF?

To elaborate on @serine's answer and illustrate working with non-trivial multi-valued condition: I had a need to show a "dim-out" overlay on an item for the boolean condition NOT a AND (b OR NOT c).

For background, this is a "Multiple Choice" question. If the user picks a wrong answer it becomes disabled (dimmed out and cannot be selected again). An automated agent has the ability to focus on any particular choice to give an explanation (border highlighted). When the agent focuses on an item, it should not be dimmed out even if it is disabled. All items that are not in focused are marked de-focused, and should be dimmed out.

The logic for dimming is thus:

NOT IsFocused AND (IsDefocused OR NOT Enabled)

To implement this logic, I made a generic IMultiValueConverter named (awkwardly) to match my logic

// 'P' represents a parenthesis
//     !  a &&  ( b ||  !  c )
class NOT_a_AND_P_b_OR_NOT_c_P : IMultiValueConverter
{
    // redacted [...] for brevity
    public object Convert(object[] values, ...)
    {
        bool a = System.Convert.ToBoolean(values[0]);
        bool b = System.Convert.ToBoolean(values[1]);
        bool c = System.Convert.ToBoolean(values[2]);

        return !a && (b || !c);
    }
    ...
}

In the XAML I use this in a MultiDataTrigger in a <Style><Style.Triggers> resource

<MultiDataTrigger>
    <MultiDataTrigger.Conditions>
        <!-- when the equation is TRUE ... -->
        <Condition Value="True">
            <Condition.Binding>
                <MultiBinding Converter="{StaticResource NOT_a_AND_P_b_OR_NOT_c_P}">
                    <!-- NOT IsFocus AND ( IsDefocused OR NOT Enabled ) -->
                    <Binding Path="IsFocus"/>
                    <Binding Path="IsDefocused" />
                    <Binding Path="Enabled" />
                </MultiBinding>
            </Condition.Binding>
        </Condition>
    </MultiDataTrigger.Conditions>
    <MultiDataTrigger.Setters>
        <!-- ... show the 'dim-out' overlay -->
        <Setter Property="Visibility" Value="Visible" />
    </MultiDataTrigger.Setters>
</MultiDataTrigger>

And for completeness sake, my converter is defined in a ResourceDictionary

<ResourceDictionary xmlns:conv="clr-namespace:My.Converters" ...>
    <conv:NOT_a_AND_P_b_OR_NOT_c_P x:Key="NOT_a_AND_P_b_OR_NOT_c_P" />
</ResourceDictionary>

How do I properly compare strings in C?

How do I properly compare strings?

char input[40];
char check[40];
strcpy(input, "Hello"); // input assigned somehow
strcpy(check, "Hello"); // check assigned somehow

// insufficient
while (check != input)

// good
while (strcmp(check, input) != 0)
// or 
while (strcmp(check, input))

Let us dig deeper to see why check != input is not sufficient.

In C, string is a standard library specification.

A string is a contiguous sequence of characters terminated by and including the first null character.
C11 §7.1.1 1

input above is not a string. input is array 40 of char.

The contents of input can become a string.

In most cases, when an array is used in an expression, it is converted to the address of its 1st element.

The below converts check and input to their respective addresses of the first element, then those addresses are compared.

check != input   // Compare addresses, not the contents of what addresses reference

To compare strings, we need to use those addresses and then look at the data they point to.
strcmp() does the job. §7.23.4.2

int strcmp(const char *s1, const char *s2);

The strcmp function compares the string pointed to by s1 to the string pointed to by s2.

The strcmp function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2.

Not only can code find if the strings are of the same data, but which one is greater/less when they differ.

The below is true when the string differ.

strcmp(check, input) != 0

For insight, see Creating my own strcmp() function

OpenSSL: unable to verify the first certificate for Experian URL

Here is what you can do:-

Exim SSL certificates

By default, the /etc/exim.conf will use the cert/key files:

/etc/exim.cert
/etc/exim.key

so if you're wondering where to set your files, that's where.

They're controlled by the exim.conf's options:

tls_certificate = /etc/exim.cert
tls_privatekey = /etc/exim.key

Intermediate Certificates

If you have a CA Root certificate (ca bundle, chain, etc.) you'll add the contents of your CA into the exim.cert, after your actual certificate.

Probably a good idea to make sure you have a copy of everything elsewhere in case you make an error.

Dovecot and ProFtpd should also read it correctly, so dovecot no longer needs the ssl_ca option. So for both cases, there is no need to make any changes to either the exim.conf or dovecot.conf(/etc/dovecot/conf/ssl.conf)

Pythonic way to check if a list is sorted or not

Definitely works in Python 3 and above for integers or strings:

def tail(t):
    return t[:]

letters = ['a', 'b', 'c', 'd', 'e']
rest = tail(letters)
rest.sort()
if letters == rest:
    print ('Given list is SORTED.')
else:
    print ('List NOT Sorted.')

=====================================================================

Another way of finding if the given list is sorted or not

trees1 = list ([1, 4, 5, 3, 2])
trees2 = list (trees1)
trees2.sort()
if trees1 == trees2:
    print ('trees1 is SORTED')
else:
    print ('Not sorted')

how to draw smooth curve through N points using javascript HTML5 canvas?

The problem with joining subsequent sample points together with disjoint "curveTo" type functions, is that where the curves meet is not smooth. This is because the two curves share an end point but are influenced by completely disjoint control points. One solution is to "curve to" the midpoints between the next 2 subsequent sample points. Joining the curves using these new interpolated points gives a smooth transition at the end points (what is an end point for one iteration becomes a control point for the next iteration.) In other words the two disjointed curves have much more in common now.

This solution was extracted out of the book "Foundation ActionScript 3.0 Animation: Making things move". p.95 - rendering techniques: creating multiple curves.

Note: this solution does not actually draw through each of the points, which was the title of my question (rather it approximates the curve through the sample points but never goes through the sample points), but for my purposes (a drawing application), it's good enough for me and visually you can't tell the difference. There is a solution to go through all the sample points, but it is much more complicated (see http://www.cartogrammar.com/blog/actionscript-curves-update/)

Here is the the drawing code for the approximation method:

// move to the first point
   ctx.moveTo(points[0].x, points[0].y);


   for (i = 1; i < points.length - 2; i ++)
   {
      var xc = (points[i].x + points[i + 1].x) / 2;
      var yc = (points[i].y + points[i + 1].y) / 2;
      ctx.quadraticCurveTo(points[i].x, points[i].y, xc, yc);
   }
 // curve through the last two points
 ctx.quadraticCurveTo(points[i].x, points[i].y, points[i+1].x,points[i+1].y);

How to git clone a specific tag

Use the command

git clone --help

to see whether your git supports the command

git clone --branch tag_name

If not, just do the following:

git clone repo_url 
cd repo
git checkout tag_name

How does HttpContext.Current.User.Identity.Name know which usernames exist?

The HttpContext.Current.User.Identity.Name returns null

This depends on whether the authentication mode is set to Forms or Windows in your web.config file.

For example, if I write the authentication like this:

<authentication mode="Forms"/>

Then because the authentication mode="Forms", I will get null for the username. But if I change the authentication mode to Windows like this:

<authentication mode="Windows"/>

I can run the application again and check for the username, and I will get the username successfully.

For more information, see System.Web.HttpContext.Current.User.Identity.Name Vs System.Environment.UserName in ASP.NET.

How to count items in JSON data

import json

json_data = json.dumps({
  "result":[
    {
      "run":[
        {
          "action":"stop"
        },
        {
          "action":"start"
        },
        {
          "action":"start"
        }
      ],
      "find": "true"
    }
  ]
})

item_dict = json.loads(json_data)
print len(item_dict['result'][0]['run'])

Convert it in dict.

Two onClick actions one button

<input type="button" value="..." onClick="fbLikeDump(); WriteCookie();" />

Flask-SQLalchemy update a row's information

This does not work if you modify a pickled attribute of the model. Pickled attributes should be replaced in order to trigger updates:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from pprint import pprint

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqllite:////tmp/users.db'
db = SQLAlchemy(app)


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True)
    data = db.Column(db.PickleType())

    def __init__(self, name, data):
        self.name = name
        self.data = data

    def __repr__(self):
        return '<User %r>' % self.username

db.create_all()

# Create a user.
bob = User('Bob', {})
db.session.add(bob)
db.session.commit()

# Retrieve the row by its name.
bob = User.query.filter_by(name='Bob').first()
pprint(bob.data)  # {}

# Modifying data is ignored.
bob.data['foo'] = 123
db.session.commit()
bob = User.query.filter_by(name='Bob').first()
pprint(bob.data)  # {}

# Replacing data is respected.
bob.data = {'bar': 321}
db.session.commit()
bob = User.query.filter_by(name='Bob').first()
pprint(bob.data)  # {'bar': 321}

# Modifying data is ignored.
bob.data['moo'] = 789
db.session.commit()
bob = User.query.filter_by(name='Bob').first()
pprint(bob.data)  # {'bar': 321}

Connection to SQL Server Works Sometimes

Solved this problem by blocking/ blacklisting IP address that were trying to brute force user accounts. Check your SQL access logs for large numbers of failed login attempts (usually for the 'sa' account).

installing vmware tools: location of GCC binary?

Install prerequisites VMware Tools for LinuxOS:

If you have RHEL/CentOS:

yum install perl gcc make kernel-headers kernel-devel -y

If you have Ubuntu/Debian:

sudo apt-get -y install linux-headers-server build-essential
  • build-essential, also install: dpkg-dev, g++, gcc, lib6-dev, libc-dev, make

Extracted from: http://www.sysadmit.com/2016/01/vmware-tools-linux-instalar-requisitos.html

What are the benefits of using C# vs F# or F# vs C#?

  • F# Has Better Performance than C# in Math
  • You could use F# projects in the same solution with C# (and call from one to another)
  • F# is really good for complex algorithmic programming, financial and scientific applications
  • F# logically is really good for the parallel execution (it is easier to make F# code execute on parallel cores, than C#)

Decimal number regular expression, where digit after decimal is optional

Use the following:

/^\d*\.?\d*$/
  • ^ - Beginning of the line;
  • \d* - 0 or more digits;
  • \.? - An optional dot (escaped, because in regex, . is a special character);
  • \d* - 0 or more digits (the decimal part);
  • $ - End of the line.

This allows for .5 decimal rather than requiring the leading zero, such as 0.5