Programs & Examples On #Cjk

CJK stands for Chinese, Japanese and Korean and is used to label issues common to these East Asian languages and their large character repertoires.

Convert or extract TTC font to TTF - how to?

Assuming that Windows doesn't really know how to deal with TTC files (which I honestly find strange), you can "split" the combined fonts in an easy way if you use fontforge.

The steps are:

  1. Download the file.
  2. Unzip it (e.g., unzip "STHeiti Medium.ttc.zip").
  3. Load Fontforge.
  4. Open it with Fontforge (e.g., File > Open).
  5. Fontforge will tell you that there are two fonts "packed" in this particular TTC file (at least as of 2014-01-29) and ask you to choose one.
  6. After the font is loaded (it may take a while, as this font is very large), you can ask Fontforge to generate the TTF file via the menu File > Generate Fonts....

Repeat the steps of loading 4--6 for the other font and you will have your TTFs readily usable for you.

Note that I emphasized generating instead of saving above: saving the font will create a file in Fontforge's specific SFD format, which is probably useless to you, unless you want to develop fonts with Fontforge.

If you want to have a more programmatic/automatic way of manipulating fonts, then you might be interested in my answer to a similar (but not exactly the same) question.

Addenda

Further comments: One reason why some people may be interested in performing the splitting mentioned above (or using a font converter after all) is to convert the fonts to web formats (like WOFF). That's great, but be careful to see if the license of the fonts that you are splitting/converting allows such wide redistribution.

Of course, for Free ("as in Freedom") fonts, you don't need to worry (and one of the most prominent licenses of such fonts is the OFL).

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

Unicode currently has 74605 CJK characters. CJK characters not only includes characters used by Chinese, but also Japanese Kanji, Korean Hanja, and Vietnamese Chu Nom. Some CJK characters are not Chinese characters.

1) 20941 characters from the CJK Unified Ideographs block.

Code points U+4E00 to U+9FCC.

  1. U+4E00 - U+62FF
  2. U+6300 - U+77FF
  3. U+7800 - U+8CFF
  4. U+8D00 - U+9FCC

2) 6582 characters from the CJKUI Ext A block.

Code points U+3400 to U+4DB5. Unicode 3.0 (1999).

3) 42711 characters from the CJKUI Ext B block.

Code points U+20000 to U+2A6D6. Unicode 3.1 (2001).

  1. U+20000 - U+215FF
  2. U+21600 - U+230FF
  3. U+23100 - U+245FF
  4. U+24600 - U+260FF
  5. U+26100 - U+275FF
  6. U+27600 - U+290FF
  7. U+29100 - U+2A6DF

3) 4149 characters from the CJKUI Ext C block.

Code points U+2A700 to U+2B734. Unicode 5.2 (2009).

4) 222 characters from the CJKUI Ext D block.

Code points U+2B740 to U+2B81D. Unicode 6.0 (2010).

5) CJKUI Ext E block.

Coming soon

If the above is not spaghetti enough, take a look at known issues. Have fun =)

What tools do you use to test your public REST API?

We use Groovy and Spock for writing highly expressive BDD style tests. Unbeatable combo! Jersey Client API or HttpClient is used for handling the HTTP requests.

For manual/acceptance testing we use Curl or Chrome apps as Postman or Dev HTTP Client.

How to measure elapsed time in Python?

Here's a pretty well documented and fully type hinted decorator I use as a general utility:

from functools import wraps
from time import perf_counter
from typing import Any, Callable, Optional, TypeVar, cast

F = TypeVar("F", bound=Callable[..., Any])


def timer(prefix: Optional[str] = None, precision: int = 6) -> Callable[[F], F]:
    """Use as a decorator to time the execution of any function.

    Args:
        prefix: String to print before the time taken.
            Default is the name of the function.
        precision: How many decimals to include in the seconds value.

    Examples:
        >>> @timer()
        ... def foo(x):
        ...     return x
        >>> foo(123)
        foo: 0.000...s
        123
        >>> @timer("Time taken: ", 2)
        ... def foo(x):
        ...     return x
        >>> foo(123)
        Time taken: 0.00s
        123

    """
    def decorator(func: F) -> F:
        @wraps(func)
        def wrapper(*args: Any, **kwargs: Any) -> Any:
            nonlocal prefix
            prefix = prefix if prefix is not None else f"{func.__name__}: "
            start = perf_counter()
            result = func(*args, **kwargs)
            end = perf_counter()
            print(f"{prefix}{end - start:.{precision}f}s")
            return result
        return cast(F, wrapper)
    return decorator

Example usage:

from timer import timer


@timer(precision=9)
def takes_long(x: int) -> bool:
    return x in (i for i in range(x + 1))


result = takes_long(10**8)
print(result)

Output:

takes_long: 4.942629056s
True

The doctests can be checked with:

$ python3 -m doctest --verbose -o=ELLIPSIS timer.py

And the type hints with:

$ mypy timer.py

Using a custom (ttf) font in CSS

You need to use the css-property font-face to declare your font. Have a look at this fancy site: http://www.font-face.com/

Example:

@font-face {
  font-family: MyHelvetica;
  src: local("Helvetica Neue Bold"),
       local("HelveticaNeue-Bold"),
       url(MgOpenModernaBold.ttf);
  font-weight: bold;
}

See also: MDN @font-face

How can I set the request header for curl?

Just use the -H parameter several times:

curl -H "Accept-Charset: utf-8" -H "Content-Type: application/x-www-form-urlencoded" http://www.some-domain.com

Is Laravel really this slow?

Yes - Laravel IS really that slow. I built a POC app for this sake. Simple router, with a login form. I could only get 60 RPS with 10 concurrent connections on a $20 digital ocean server (few GB ram);

Setup:

2gb RAM
Php7.0
apache2.4
mysql 5.7
memcached server (for laravel session)

I ran optimizations, composer dump autoload etc, and it actually lowered the RPS to 43-ish.

The problem is the app responds in 200-400ms. I ran AB test from the local machine laravel was on (ie, not through web traffic); and I got only 112 RPS; with 200ms faster response time with an average of 300ms.

Comparatively, I tested my production PHP Native app running a few million requests a day on a AWS t2.medium (x3, load balanced). When I AB'd 25 concurrent connections from my local machine to that over web, through ELB, I got roughly 1200 RPS. Huge difference on a machine with load vs a laravel "login" page.

These are pages with Sessions (elasticache / memcached), Live DB lookups (cached queries via memcached), Assets pulled over CDNs, etc, etc, etc.

What I can tell, laravel sticks about 200-300ms load over things. Its fine for PHP Generated views, after all, that type of delay is tolerable on load. However, for PHP views that use Ajax/JS to handle small updates, it begins to feel sluggish.

I cant imagine what this system would look like with a multi tenant app while 200 bots crawl 100 pages each all at the same time.

Laravel is great for simple apps. Lumen is tolerable if you dont need to do anything fancy that would require middleware nonsense (IE, no multi tenant apps and custom domains, etc);

However, I never like starting with something that can bind and cause 300ms load for a "hello world" post.

If youre thinking "Who cares?"

.. Write a predictive search that relies on quick queries to respond to autocomplete suggestions across a few hundred thousand results. That 200-300ms lag will drive your users absolutely insane.

Find the number of columns in a table

SELECT count(*) FROM information_schema.`COLUMNS` C
WHERE table_name = 'your_table_name'
AND TABLE_SCHEMA = "your_db_name"

Getting windbg without the whole WDK?

Try the MSDN archive link at http://archive.msdn.microsoft.com/debugtoolswindows/Release/ProjectReleases.aspx?ReleaseId=4912. It has the WinDbg MSI for both 32- and 64-bit (Version 6.12.2.633).

How to check is Apache2 is stopped in Ubuntu?

In the command line type service apache2 status then hit enter. The result should say:

Apache2 is running (pid xxxx)

c++ parse int from string

You can use boost::lexical_cast:

#include <iostream>
#include <boost/lexical_cast.hpp>

int main( int argc, char* argv[] ){
std::string s1 = "10";
std::string s2 = "abc";
int i;

   try   {
      i = boost::lexical_cast<int>( s1 );
   }
   catch( boost::bad_lexical_cast & e ){
      std::cout << "Exception caught : " << e.what() << std::endl;
   }

   try   {
      i = boost::lexical_cast<int>( s2 );
   }
   catch( boost::bad_lexical_cast & e ){
      std::cout << "Exception caught : " << e.what() << std::endl;
   }

   return 0;
}

CSS3 Fade Effect

It's possible, use the structure below:

<li><a><span></span></a></li>
<li><a><span></span></a></li>

etc...

Where the <li> contains an <a> anchor tag that contains a span as shown above. Then insert the following css:

  • LI get position: relative;
  • Give <a> tag a height, width
  • Set <span> width & height to 100%, so that both <a> and <span> have same dimensions
  • Both <a> and <span> get position: relative;.
  • Assign the same background image to each element
  • <a> tag will have the 'OFF' background-position, and the <span> will have the 'ON' background-poisiton.
  • For 'OFF' state use opacity 0 for <span>
  • For 'ON' :hover state use opacity 1 for <span>
  • Set the -webkit or -moz transition on the <span> element

You'll have the ability to use the transition effect while still defaulting to the old background-position swap. Don't forget to insert IE alpha filter.

How to create a file on Android Internal Storage?

Hi try this it will create directory + file inside it

File mediaDir = new File("/sdcard/download/media");
if (!mediaDir.exists()){
    mediaDir.mkdir();
}

File resolveMeSDCard = new File("/sdcard/download/media/hello_file.txt");
resolveMeSDCard.createNewFile();
FileOutputStream fos = new FileOutputStream(resolveMeSDCard);
fos.write(string.getBytes());
fos.close();

System.out.println("Your file has been written");  

Selenium and xpath: finding a div with a class/id and verifying text inside

To verify this:-

<div class="Caption">
  Model saved
</div>

Write this -

//div[contains(@class, 'Caption') and text()='Model saved']

And to verify this:-

<div id="alertLabel" class="gwt-HTML sfnStandardLeftMargin sfnStandardRightMargin sfnStandardTopMargin">
  Save to server successful
</div>

Write this -

//div[@id='alertLabel' and text()='Save to server successful']

Best Java obfuscator?

Check out my article Protect Your Java Code - Through Obfuscators And Beyond [Archived] for a discussion of obfuscation vs three other ways to make the reverse engineering of your apps more expensive, and a collection of links to tools and further reading materials.

nvarchar(max) still being truncated

I have encountered the same problem today and found that beyond that 4000 character limit, I had to split the dynamic query into two strings and concatenate them when executing the query.

DECLARE @Query NVARCHAR(max);
DECLARE @Query2 NVARCHAR(max);
SET @Query = 'SELECT...' -- some of the query gets set here
SET @Query2 = '...' -- more query gets added on, etc.

EXEC (@Query + @Query2)

json.net has key method?

JObject implements IDictionary<string, JToken>, so you can use:

IDictionary<string, JToken> dictionary = x;
if (dictionary.ContainsKey("error_msg"))

... or you could use TryGetValue. It implements both methods using explicit interface implementation, so you can't use them without first converting to IDictionary<string, JToken> though.

Installing OpenCV 2.4.3 in Visual C++ 2010 Express

1. Installing OpenCV 2.4.3

First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\.

OpenCV self-extractor

Wait until all files get extracted. It will create a new directory C:\opencv which contains OpenCV header files, libraries, code samples, etc.

Now you need to add the directory C:\opencv\build\x86\vc10\bin to your system PATH. This directory contains OpenCV DLLs required for running your code.

Open Control PanelSystemAdvanced system settingsAdvanced Tab → Environment variables...

enter image description here

On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin; (3), then click Ok.

On some computers, you may need to restart your computer for the system to recognize the environment path variables.

This will completes the OpenCV 2.4.3 installation on your computer.


2. Create a new project and set up Visual C++

Open Visual C++ and select FileNewProject...Visual C++Empty Project. Give a name for your project (e.g: cvtest) and set the project location (e.g: c:\projects).

New project dialog

Click Ok. Visual C++ will create an empty project.

VC++ empty project

Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest and select PropertiesVC++ Directories.

Project property dialog

Select Include Directories to add a new entry and type C:\opencv\build\include.

Include directories dialog

Click Ok to close the dialog.

Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib.

Library directories dialog

Click Ok to close the dialog.

Back to the property dialog, select LinkerInputAdditional Dependencies to add new entries. On the popup dialog, type the files below:

opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib

Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).

enter image description here

Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.

NOTE:

These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:

opencv_core243.lib
opencv_imgproc243.lib
...

instead of:

opencv_core243d.lib
opencv_imgproc243d.lib
...

You've done setting up Visual C++, now is the time to write the real code. Right click your project and select AddNew Item...Visual C++C++ File.

Add new source file

Name your file (e.g: loadimg.cpp) and click Ok. Type the code below in the editor:

#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main()
{
    Mat im = imread("c:/full/path/to/lena.jpg");
    if (im.empty()) 
    {
        cout << "Cannot load image!" << endl;
        return -1;
    }
    imshow("Image", im);
    waitKey(0);
}

The code above will load c:\full\path\to\lena.jpg and display the image. You can use any image you like, just make sure the path to the image is correct.

Type F5 to compile the code, and it will display the image in a nice window.

First OpenCV program

And that is your first OpenCV program!


3. Where to go from here?

Now that your OpenCV environment is ready, what's next?

  1. Go to the samples dir → c:\opencv\samples\cpp.
  2. Read and compile some code.
  3. Write your own code.

Select and trigger click event of a radio button in jquery

In my case i had to load images on radio button click, I just uses the regular onclick event and it worked for me.

 <input type="radio" name="colors" value="{{color.id}}" id="{{color.id}}-option" class="color_radion"  onclick="return get_images(this, {{color.id}})">

<script>
  function get_images(obj, color){
    console.log($("input[type='radio'][name='colors']:checked").val());

  }
  </script>

scrollTop jquery, scrolling to div with id?

My solution was the following:

document.getElementById("agent_details").scrollIntoView();

SSIS how to set connection string dynamically from a config file

Some options:

  1. You can use the Execute Package Utility to change your datasource, before running the package.

  2. You can run your package using DTEXEC, and change your connection by passing in a /CONNECTION parameter. Probably save it as a batch so next time you don't need to type the whole thing and just change the datasource as required.

  3. You can use the SSIS XML package configuration file. Here is a walk through.

  4. You can save your configrations in a database table.

Could not find folder 'tools' inside SDK

If you get the "Failed to find DDMS files..." do this:

  1. Open eclipse
  2. Open install new software
  3. Click "Add..." -> type in (e.g.) "Android_over_HTTP" and in address put "http://dl-ssl.google.com/android/eclipse/".

Don't be alarmed that its not https, this helps to fetch stuff over http. This trick helped me to resolve the issue on MAC, I believe that this also should work on Windows / Linux

Hope this helps !

Row count with PDO

If you just want to get a count of rows (not the data) ie. using COUNT(*) in a prepared statement then all you need to do is retrieve the result and read the value:

$sql = "SELECT count(*) FROM `table` WHERE foo = bar";
$statement = $con->prepare($sql); 
$statement->execute(); 
$count = $statement->fetch(PDO::FETCH_NUM); // Return array indexed by column number
return reset($count); // Resets array cursor and returns first value (the count)

Actually retrieving all the rows (data) to perform a simple count is a waste of resources. If the result set is large your server may choke on it.

How to get number of rows using SqlDataReader in C#

There are only two options:

  • Find out by reading all rows (and then you might as well store them)

  • run a specialized SELECT COUNT(*) query beforehand.

Going twice through the DataReader loop is really expensive, you would have to re-execute the query.

And (thanks to Pete OHanlon) the second option is only concurrency-safe when you use a transaction with a Snapshot isolation level.

Since you want to end up storing all rows in memory anyway the only sensible option is to read all rows in a flexible storage (List<> or DataTable) and then copy the data to any format you want. The in-memory operation will always be much more efficient.

Angular JS: Full example of GET/POST/DELETE/PUT client for a REST/CRUD backend?

Because your update uses PUT method, {entryId: $scope.entryId} is considered as data, to tell angular generate from the PUT data, you need to add params: {entryId: '@entryId'} when you define your update, which means

return $resource('http://localhost\\:3000/realmen/:entryId', {}, {
  query: {method:'GET', params:{entryId:''}, isArray:true},
  post: {method:'POST'},
  update: {method:'PUT', params: {entryId: '@entryId'}},
  remove: {method:'DELETE'}
});

Fix: Was missing a closing curly brace on the update line.

Where do I find the Instagram media ID of a image

edit

The iOS Instagram app has now registered for regular http links to open in the Instagram app and this deeplink methodology is no longer necessary.

old

Swift 4 short-code parsing solution

private static func instagramDeepLinkFromHTTPLink(_ link: String) -> String? {
    guard let shortcode = link.components(separatedBy: "/").last else { return nil }

    // algorithm from https://stackoverflow.com/a/37246231/337934
    let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
    var mediaId: Int = 0
    for (_, char) in shortcode.enumerated() {
        guard let index = alphabet.index(of: char) else { continue }
        mediaId = (mediaId * 64) + index.encodedOffset
    }

    return "instagram://media?id=\(mediaId)"
}

How to use KeyListener

In addition to using KeyListener (as shown by others' answers), sometimes you have to ensure that the JComponent you are using is Focusable. This can be set by adding this to your component(if you are subclassing):

@Override
public void setFocusable(boolean b) {
    super.setFocusable(b);
}

And by adding this to your constructor:

setFocusable(true);

Or, if you are calling the function from a parent class/container:

JComponent childComponent = new JComponent();
childComponent.setFocusable(true);

And then doing all the KeyListener stuff mentioned by others.

Another Repeated column in mapping for entity error

If you are stuck with a legacy database where someone already placed JPA annotations on but did NOT define the relationships and you are now trying to define them for use in your code, then you might NOT be able to delete the customerId @Column since other code may directly reference it already. In that case, define the relationships as follows:

@ManyToOne(optional=false)
@JoinColumn(name="productId",referencedColumnName="id_product", insertable=false, updatable=false)
private Product product;

@ManyToOne(optional=false)
@JoinColumn(name="customerId",referencedColumnName="id_customer", insertable=false, updatable=false)
private Customer customer;

This allows you to access the relationships. However, to add/update to the relationships you will have to manipulate the foreign keys directly via their defined @Column values. It's not an ideal situation, but if you are handed this sort of situation, at least you can define the relationships so that you can use JPQL successfully.

Is there a better alternative than this to 'switch on type'?

Try to go that way:

public void Test(BaseType @base)
{
    switch (@base)
    {
        case ConcreteType concrete:
            DoSomething(concrete);
            break;

        case AnotherConcrete concrete:
            DoSomething(concrete);
            break;
    }
}

Changing background color of selected item in recyclerview

Create Drawable file in Drawable foloder

<item android:drawable="@color/SelectedColor" android:state_pressed="true"></item>
<item android:drawable="@color/SelectedColor" android:state_selected="true"></item>
<item android:drawable="@color/DefultColor"></item>

And in xml file

android:background="@drawable/Drawable file"

In RecyclerView onBindViewHolder

holder.button.setSelected(holder.button.isSelected()?true:false);

Like toggle button

Sending email through Gmail SMTP server with C#

I was getting the same error and none of the above solutions helped.

My problem was that I was running the code from a remote server, which had never been used to log into the gmail account.

I opened a browser on the remote server and logged into gmail from there. It asked a security question to verify it was me since this was a new location. After doing the security check I was able to authenticate through code.

Simple tool to 'accept theirs' or 'accept mine' on a whole file using git

Try this:

To accept theirs changes: git merge --strategy-option theirs

To accept yours: git merge --strategy-option ours

How to tell whether a point is to the right or left side of a line

You look at the sign of the determinant of

| x2-x1  x3-x1 |
| y2-y1  y3-y1 |

It will be positive for points on one side, and negative on the other (and zero for points on the line itself).

HikariCP - connection is not available

From stack trace:

HikariPool: Timeout failure pool HikariPool-0 stats (total=20, active=20, idle=0, waiting=0) Means pool reached maximum connections limit set in configuration.

The next line: HikariPool-0 - Connection is not available, request timed out after 30000ms. Means pool waited 30000ms for free connection but your application not returned any connection meanwhile.

Mostly it is connection leak (connection is not closed after borrowing from pool), set leakDetectionThreshold to the maximum value that you expect SQL query would take to execute.

otherwise, your maximum connections 'at a time' requirement is higher than 20 !

How to subtract days from a plain Date?

var daysToSubtract = 3;
$.datepicker.formatDate('yy/mm/dd', new Date() - daysToSubtract) ;

Is there any way to configure multiple registries in a single npmrc file

I encounter the same problem when my company set up its own registry, so I heavily rework on proxy-registry into proxy-multi-registries to solve this problem. Hope it will also helps you.

Best way to work with transactions in MS SQL Server Management Studio

The easisest thing to do is to wrap your code in a transaction, and then execute each batch of T-SQL code line by line.

For example,

Begin Transaction

         -Do some T-SQL queries here.

Rollback transaction -- OR commit transaction

If you want to incorporate error handling you can do so by using a TRY...CATCH BLOCK. Should an error occur you can then rollback the tranasction within the catch block.

For example:

USE AdventureWorks;
GO
BEGIN TRANSACTION;

BEGIN TRY
    -- Generate a constraint violation error.
    DELETE FROM Production.Product
    WHERE ProductID = 980;
END TRY
BEGIN CATCH
    SELECT 
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;
GO

See the following link for more details.

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

Hope this helps but please let me know if you need more details.

Drop all tables whose names begin with a certain string

I would like to post my proposal of the solution which DROP (not just generate and select a drop commands) all tables based on the wildcard (e.g. "table_20210114") older than particular amount of days.

DECLARE 
    @drop_command NVARCHAR(MAX) = '',
    @system_time date,
    @table_date nvarchar(8),
    @older_than int = 7
    
Set @system_time = (select getdate() - @older_than)
Set @table_date = (SELECT CONVERT(char(8), @system_time, 112))

SELECT @drop_command += N'DROP TABLE ' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' + QUOTENAME([Name]) + ';'
FROM <your_database_name>.sys.tables
WHERE [Name] LIKE 'table_%' AND RIGHT([Name],8) < @table_date

SELECT @drop_command
 
EXEC sp_executesql @drop_command

Python Pylab scatter plot error bars (the error on each point is unique)

>>> import matplotlib.pyplot as plt
>>> a = [1,3,5,7]
>>> b = [11,-2,4,19]
>>> plt.pyplot.scatter(a,b)
>>> plt.scatter(a,b)
<matplotlib.collections.PathCollection object at 0x00000000057E2CF8>
>>> plt.show()
>>> c = [1,3,2,1]
>>> plt.errorbar(a,b,yerr=c, linestyle="None")
<Container object of 3 artists>
>>> plt.show()

where a is your x data b is your y data c is your y error if any

note that c is the error in each direction already

How do search engines deal with AngularJS applications?

This has drastically changed.

http://searchengineland.com/bing-offers-recommendations-for-seo-friendly-ajax-suggests-html5-pushstate-152946

If you use: $locationProvider.html5Mode(true); you are set.

No more rendering pages.

How to change scroll bar position with CSS?

Try this out. Hope this helps

<div id="single" dir="rtl">
    <div class="common">Single</div>
</div>

<div id="both" dir="ltr">
    <div class="common">Both</div>
</div>



#single, #both{
    width: 100px;
    height: 100px;
    overflow: auto;
    margin: 0 auto;
    border: 1px solid gray;
}


.common{
    height: 150px;
    width: 150px;
}

Update Row if it Exists Else Insert Logic with Entity Framework

As of Entity Framework 4.3, there is an AddOrUpdate method at namespace System.Data.Entity.Migrations:

public static void AddOrUpdate<TEntity>(
    this IDbSet<TEntity> set,
    params TEntity[] entities
)
where TEntity : class

which by the doc:

Adds or updates entities by key when SaveChanges is called. Equivalent to an "upsert" operation from database terminology. This method can be useful when seeding data using Migrations.


To answer the comment by @Smashing1978, I will paste relevant parts from link provided by @Colin

The job of AddOrUpdate is to ensure that you don’t create duplicates when you seed data during development.

First, it will execute a query in your database looking for a record where whatever you supplied as a key (first parameter) matches the mapped column value (or values) supplied in the AddOrUpdate. So this is a little loosey-goosey for matching but perfectly fine for seeding design time data.

More importantly, if a match is found then the update will update all and null out any that weren’t in your AddOrUpdate.

That said, I have a situation where I am pulling data from an external service and inserting or updating existing values by primary key (and my local data for consumers is read-only) - been using AddOrUpdate in production for more than 6 months now and so far no problems.

Find a commit on GitHub given the commit hash

The ability to search commits has recently been added to GitHub.

To search for a hash, just enter at least the first 7 characters in the search box. Then on the results page, click the "Commits" tab to see matching commits (but only on the default branch, usually master), or the "Issues" tab to see pull requests containing the commit.

To be more explicit you can add the hash: prefix to the search, but it's not really necessary.

There is also a REST API (at the time of writing it is still in preview).

Check if PHP-page is accessed from an iOS device

In response to Haim Evgi's code, I added !== false to the end for it to work for me

$iPod    = stripos($_SERVER['HTTP_USER_AGENT'],"iPod") !== false;
$iPhone  = stripos($_SERVER['HTTP_USER_AGENT'],"iPhone") !== false;
$iPad    = stripos($_SERVER['HTTP_USER_AGENT'],"iPad") !== false;
$Android = stripos($_SERVER['HTTP_USER_AGENT'],"Android") !== false;

Excel VBA - Pass a Row of Cell Values to an Array and then Paste that Array to a Relative Reference of Cells

Since you are copying tha same data to all rows, you don't actually need to loop at all. Try this:

Sub ARRAYER()
    Dim Number_of_Sims As Long
    Dim rng As Range

    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False
    Number_of_Sims = 100000

    Set rng = Range("C4:G4")
    rng.Offset(1, 0).Resize(Number_of_Sims) = rng.Value

    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
End Sub

Circular (or cyclic) imports in Python

Suppose you are running a test python file named request.py In request.py, you write

import request

so this also most likely a circular import.

Solution:

Just change your test file to another name such as aaa.py, other than request.py.

Do not use names that are already used by other libs.

How to add conditional attribute in Angular 2?

I wanted to have tooltip only for a particular field as added below in code but you want to have tooltip on multiplent you can have an array valdidate using:

Multiple Elements haveing custom data-tooltip attribute:

1: ['key1ToHaveTooltip', `key2ToHaveTooltip'].includes(key)

2: ['key1ToHaveTooltip', 'key2ToHaveTooltip'].indexOf(key) > -1

to have tooltip attribute on more than 1 element.

   <div *ngFor="let key of Keys"
             [attr.data-tooltip]="key === 'IwantOnlyThisKeyToHaveTooltipAttribute' 
                                           ? 'Hey! I am a tooltip on key matched'
                                           : null">
   </div>

How can I make sticky headers in RecyclerView? (Without external lib)

You can check and take the implementation of the class StickyHeaderHelper in my FlexibleAdapter project, and adapt it to your use case.

But, I suggest to use the library since it simplifies and reorganizes the way you usually implement the Adapters for RecyclerView: Don't reinvent the wheel.

I would also say, don't use Decorators or deprecated libraries, as well as don't use libraries that do only 1 or 3 things, you will have to merge implementations of others libraries yourself.

bash: Bad Substitution

I have found that this issue is either caused by the marked answer or you have a line or space before the bash declaration

How do I create a message box with "Yes", "No" choices and a DialogResult?

DialogResult dr = MessageBox.Show("Are you happy now?", 
                      "Mood Test", MessageBoxButtons.YesNo);
switch(dr)
{
   case DialogResult.Yes:
      break;
   case DialogResult.No:
      break;
}

MessageBox class is what you are looking for.

How can I escape a single quote?

If for some reason you cannot escape the apostrophe character and you can't change it into a HTML entity (as it was in my case for a specific Vue.js property) you can use replace to change it into different apostrophe character from the UTF8 characters set, for instance:

' - U+02BC
’ - U+2019

How to publish a Web Service from Visual Studio into IIS?

If using Visual Studio 2010 you can right-click on the project for the service, and select properties. Then select the Web tab. Under the Servers section you can configure the URL. There is also a button to create the virtual directory.

How to get the caret column (not pixels) position in a textarea, in characters, from the start?

Updated 5 September 2010

Seeing as everyone seems to get directed here for this issue, I'm adding my answer to a similar question, which contains the same code as this answer but with full background for those who are interested:

IE's document.selection.createRange doesn't include leading or trailing blank lines

To account for trailing line breaks is tricky in IE, and I haven't seen any solution that does this correctly, including any other answers to this question. It is possible, however, using the following function, which will return you the start and end of the selection (which are the same in the case of a caret) within a <textarea> or text <input>.

Note that the textarea must have focus for this function to work properly in IE. If in doubt, call the textarea's focus() method first.

function getInputSelection(el) {
    var start = 0, end = 0, normalizedValue, range,
        textInputRange, len, endRange;

    if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
        start = el.selectionStart;
        end = el.selectionEnd;
    } else {
        range = document.selection.createRange();

        if (range && range.parentElement() == el) {
            len = el.value.length;
            normalizedValue = el.value.replace(/\r\n/g, "\n");

            // Create a working TextRange that lives only in the input
            textInputRange = el.createTextRange();
            textInputRange.moveToBookmark(range.getBookmark());

            // Check if the start and end of the selection are at the very end
            // of the input, since moveStart/moveEnd doesn't return what we want
            // in those cases
            endRange = el.createTextRange();
            endRange.collapse(false);

            if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
                start = end = len;
            } else {
                start = -textInputRange.moveStart("character", -len);
                start += normalizedValue.slice(0, start).split("\n").length - 1;

                if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
                    end = len;
                } else {
                    end = -textInputRange.moveEnd("character", -len);
                    end += normalizedValue.slice(0, end).split("\n").length - 1;
                }
            }
        }
    }

    return {
        start: start,
        end: end
    };
}

Range of values in C Int and Long 32 - 64 bits

In fact, unsigned int on most modern processors (ARM, Intel/AMD, Alpha, SPARC, Itanium ,PowerPC) will have a range of 0 to 2^32 - 1 which is 4,294,967,295 = 0xffffffff because int (both signed and unsigned) will be 32 bits long and the largest one is as stated.

(unsigned short will have maximal value 2^16 - 1 = 65,535 )

(unsigned) long long int will have a length of 64 bits (long int will be enough under most 64 bit Linuxes, etc, but the standard promises 64 bits for long long int). Hence these have the range 0 to 2^64 - 1 = 18446744073709551615

How to serve up images in Angular2?

In angular only one page is requested from server, that is index.html. And index.html and assets folder are on same directory. while putting image in any component give src value like assets\image.png. This will work fine because browser will make request to server for that image and webpack will be able serve that image.

jQuery '.each' and attaching '.click' event

No need to use .each. click already binds to all div occurrences.

$('div').click(function(e) {
    ..    
});

See Demo

Note: use hard binding such as .click to make sure dynamically loaded elements don't get bound.

PHP and MySQL Select a Single Value

When you use mysql_fetch_object, you get an object (of class stdClass) with all fields for the row inside of it.

Use mysql_fetch_field instead of mysql_fetch_object, that will give you the first field of the result set (id in your case). The docs are here

Case-Insensitive List Search

You can use StringComparer:

    var list = new List<string>();
    list.Add("cat");
    list.Add("dog");
    list.Add("moth");

    if (list.Contains("MOTH", StringComparer.OrdinalIgnoreCase))
    {
        Console.WriteLine("found");
    }

How to style UITextview to like Rounded Rect text field?

If you want to keep your controller code clean, you can subclass UITextView like below, and change the class name in the Interface Builder.

RoundTextView.h

#import <UIKit/UIKit.h>
@interface RoundTextView : UITextView
@end

RoundTextView.m

#import "RoundTextView.h"
#import <QuartzCore/QuartzCore.h>
@implementation RoundTextView
-(id) initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self.layer setBorderColor:[[[UIColor grayColor] colorWithAlphaComponent:0.333] CGColor]];
        [self.layer setBorderWidth:1.0];
        self.layer.cornerRadius = 5;
        self.clipsToBounds = YES;
    }
    return self;
}
@end

How to find index of list item in Swift?

Just use firstIndex method.

array.firstIndex(where: { $0 == searchedItem })

Editable text to string

Based on this code (which you provided in response to Alex's answer):

Editable newTxt=(Editable)userName1.getText(); 
String newString = newTxt.toString();

It looks like you're trying to get the text out of a TextView or EditText. If that's the case then this should work:

String newString = userName1.getText().toString(); 

How to use http.client in Node.js if there is basic authorization

You have to set the Authorization field in the header.

It contains the authentication type Basic in this case and the username:password combination which gets encoded in Base64:

var username = 'Test';
var password = '123';
var auth = 'Basic ' + Buffer.from(username + ':' + password).toString('base64');
// new Buffer() is deprecated from v6

// auth is: 'Basic VGVzdDoxMjM='

var header = {'Host': 'www.example.com', 'Authorization': auth};
var request = client.request('GET', '/', header);

How to create a cron job using Bash automatically without the interactive editor?

Thanks everybody for your help. Piecing together what I found here and elsewhere I came up with this:

The Code

command="php $INSTALL/indefero/scripts/gitcron.php"
job="0 0 * * 0 $command"
cat <(fgrep -i -v "$command" <(crontab -l)) <(echo "$job") | crontab -

I couldn't figure out how to eliminate the need for the two variables without repeating myself.

command is obviously the command I want to schedule. job takes $command and adds the scheduling data. I needed both variables separately in the line of code that does the work.

Details

  1. Credit to duckyflip, I use this little redirect thingy (<(*command*)) to turn the output of crontab -l into input for the fgrep command.
  2. fgrep then filters out any matches of $command (-v option), case-insensitive (-i option).
  3. Again, the little redirect thingy (<(*command*)) is used to turn the result back into input for the cat command.
  4. The cat command also receives echo "$job" (self explanatory), again, through use of the redirect thingy (<(*command*)).
  5. So the filtered output from crontab -l and the simple echo "$job", combined, are piped ('|') over to crontab - to finally be written.
  6. And they all lived happily ever after!

In a nutshell:

This line of code filters out any cron jobs that match the command, then writes out the remaining cron jobs with the new one, effectively acting like an "add" or "update" function. To use this, all you have to do is swap out the values for the command and job variables.

How to download image from url

For anyone who wants to download an image WITHOUT saving it to a file:

Image DownloadImage(string fromUrl)
{
    using (System.Net.WebClient webClient = new System.Net.WebClient())
    {
        using (Stream stream = webClient.OpenRead(fromUrl))
        {
            return Image.FromStream(stream);
        }
    }
}

How to get value of a div using javascript

As I said in the comments, a <div> element does not have a value attribute. Although (very) bad, it can be accessed as:

console.log(document.getElementById('demo').getAttribute);

I suggest using HTML5 data-* attributes rather. Something like this:

<div id="demo" data-myValue="1">...</div>

in which case you could access it using:

element.getAttribute('data-myValue');
//Or using jQuery:
$('#demo').data('myValue');

How to remove an element slowly with jQuery?

$('#ur_id').slideUp("slow", function() { $('#ur_id').remove();});

PHP cURL HTTP PUT

You have mixed 2 standard.

The error is in $header = "Content-Type: multipart/form-data; boundary='123456f'";

The function http_build_query($filedata) is only for "Content-Type: application/x-www-form-urlencoded", or none.

how to convert integer to string?

If you really want to use String:

NSString *number = [[NSString alloc] initWithFormat:@"%d", 123];

But I would recommend using NSNumber:

NSNumber *number = [[NSNumber alloc] initWithInt:123];

Then just add it to the array.

[array addObject:number];

Don't forget to release it after that, since you created it above.

[number release];

How do I run a spring boot executable jar in a Production environment?

I start applications that I want to run persistently or at least semi-permanently via screen -dmS NAME /path/to/script. As far as I am informed this is the most elegant solution.

What is context in _.each(list, iterator, [context])?

The context parameter just sets the value of this in the iterator function.

var someOtherArray = ["name","patrick","d","w"];

_.each([1, 2, 3], function(num) { 
    // In here, "this" refers to the same Array as "someOtherArray"

    alert( this[num] ); // num is the value from the array being iterated
                        //    so this[num] gets the item at the "num" index of
                        //    someOtherArray.
}, someOtherArray);

Working Example: http://jsfiddle.net/a6Rx4/

It uses the number from each member of the Array being iterated to get the item at that index of someOtherArray, which is represented by this since we passed it as the context parameter.

If you do not set the context, then this will refer to the window object.

How do I select elements of an array given condition?

Add one detail to @J.F. Sebastian's and @Mark Mikofski's answers:
If one wants to get the corresponding indices (rather than the actual values of array), the following code will do:

For satisfying multiple (all) conditions:

select_indices = np.where( np.logical_and( x > 1, x < 5) )[0] #   1 < x <5

For satisfying multiple (or) conditions:

select_indices = np.where( np.logical_or( x < 1, x > 5 ) )[0] # x <1 or x >5

Raise warning in Python without interrupting program

By default, unlike an exception, a warning doesn't interrupt.

After import warnings, it is possible to specify a Warnings class when generating a warning. If one is not specified, it is literally UserWarning by default.

>>> warnings.warn('This is a default warning.')
<string>:1: UserWarning: This is a default warning.

To simply use a preexisting class instead, e.g. DeprecationWarning:

>>> warnings.warn('This is a particular warning.', DeprecationWarning)
<string>:1: DeprecationWarning: This is a particular warning.

Creating a custom warning class is similar to creating a custom exception class:

>>> class MyCustomWarning(UserWarning):
...     pass
... 
... warnings.warn('This is my custom warning.', MyCustomWarning)

<string>:1: MyCustomWarning: This is my custom warning.

For testing, consider assertWarns or assertWarnsRegex.


As an alternative, especially for standalone applications, consider the logging module. It can log messages having a level of debug, info, warning, error, etc. Log messages having a level of warning or higher are by default printed to stderr.

How do I read / convert an InputStream into a String in Java?

You can use Cactoos:

String text = new TextOf(inputStream).asString();

UTF-8 encoding is the default one. If you need another one:

String text = new TextOf(inputStream, "UTF-16").asString();

Removing special characters VBA Excel

In the case that you not only want to exclude a list of special characters, but to exclude all characters that are not letters or numbers, I would suggest that you use a char type comparison approach.

For each character in the String, I would check if the unicode character is between "A" and "Z", between "a" and "z" or between "0" and "9". This is the vba code:

Function cleanString(text As String) As String
    Dim output As String
    Dim c 'since char type does not exist in vba, we have to use variant type.
    For i = 1 To Len(text)
        c = Mid(text, i, 1) 'Select the character at the i position
        If (c >= "a" And c <= "z") Or (c >= "0" And c <= "9") Or (c >= "A" And c <= "Z") Then
            output = output & c 'add the character to your output.
        Else
            output = output & " " 'add the replacement character (space) to your output
        End If
    Next
    cleanString = output
End Function

The Wikipedia list of Unicode characers is a good quick-start if you want to customize this function a little more.

This solution has the advantage to be functionnal even if the user finds a way to introduce new special characters. It also faster than comparing two lists together.

Add alternating row color to SQL Server Reporting services report

I tried all these solutions on a Grouped Tablix with row spaces and none worked across the entire report. The result was duplicate colored rows and other solutions resulted in alternating columns!

Here is the function I wrote that worked for me using a Column Count:

Private bOddRow As Boolean
Private cellCount as Integer

Function AlternateColorByColumnCount(ByVal OddColor As String, ByVal EvenColor As String, ByVal ColCount As Integer) As String

if cellCount = ColCount Then 
bOddRow = Not bOddRow
cellCount = 0
End if 

cellCount  = cellCount  + 1

if bOddRow Then
 Return OddColor
Else
 Return EvenColor
End If

End Function

For a 7 Column Tablix I use this expression for Row (of Cells) Backcolour:

=Code.AlternateColorByColumnCount("LightGrey","White", 7)

How do I reset a sequence in Oracle?

Here is a good procedure for resetting any sequence to 0 from Oracle guru Tom Kyte. Great discussion on the pros and cons in the links below too.

[email protected]> 
create or replace
procedure reset_seq( p_seq_name in varchar2 )
is
    l_val number;
begin
    execute immediate
    'select ' || p_seq_name || '.nextval from dual' INTO l_val;

    execute immediate
    'alter sequence ' || p_seq_name || ' increment by -' || l_val || 
                                                          ' minvalue 0';

    execute immediate
    'select ' || p_seq_name || '.nextval from dual' INTO l_val;

    execute immediate
    'alter sequence ' || p_seq_name || ' increment by 1 minvalue 0';
end;
/

From this page: Dynamic SQL to reset sequence value
Another good discussion is also here: How to reset sequences?

Interface defining a constructor signature?

Beginning with C# 8.0, an interface member may declare a body. This is called a default implementation. Members with bodies permit the interface to provide a "default" implementation for classes and structs that don't provide an overriding implementation. In addition, beginning with C# 8.0, an interface may include:

Constants Operators Static constructor. Nested types Static fields, methods, properties, indexers, and events Member declarations using the explicit interface implementation syntax. Explicit access modifiers (the default access is public).

How do you make a div follow as you scroll?

A better JQuery answer would be:

$('#ParentContainer').scroll(function() { 
    $('#FixedDiv').animate({top:$(this).scrollTop()});
});

You can also add a number after scrollTop i.e .scrollTop() + 5 to give it buff.

A good suggestion would also to limit the duration to 100 and go from default swing to linear easing.

$('#ParentContainer').scroll(function() { 
    $('#FixedDiv').animate({top:$(this).scrollTop()},100,"linear");
})

How to call JavaScript function instead of href in HTML

I use a little CSS on a span to make it look like a link like so:

CSS:

.link {
    color:blue;
    text-decoration:underline;
    cursor:pointer;
}

HTML:

<span class="link" onclick="javascript:showWindow('url');">Click Me</span>

JAVASCRIPT:

function showWindow(url) {
    window.open(url, "_blank", "directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes");
}

How to check if a Java 8 Stream is empty?

If you can live with limited parallel capablilities, the following solution will work:

private static <T> Stream<T> nonEmptyStream(
    Stream<T> stream, Supplier<RuntimeException> e) {

    Spliterator<T> it=stream.spliterator();
    return StreamSupport.stream(new Spliterator<T>() {
        boolean seen;
        public boolean tryAdvance(Consumer<? super T> action) {
            boolean r=it.tryAdvance(action);
            if(!seen && !r) throw e.get();
            seen=true;
            return r;
        }
        public Spliterator<T> trySplit() { return null; }
        public long estimateSize() { return it.estimateSize(); }
        public int characteristics() { return it.characteristics(); }
    }, false);
}

Here is some example code using it:

List<String> l=Arrays.asList("hello", "world");
nonEmptyStream(l.stream(), ()->new RuntimeException("No strings available"))
  .forEach(System.out::println);
nonEmptyStream(l.stream().filter(s->s.startsWith("x")),
               ()->new RuntimeException("No strings available"))
  .forEach(System.out::println);

The problem with (efficient) parallel execution is that supporting splitting of the Spliterator requires a thread-safe way to notice whether either of the fragments has seen any value in a thread-safe manner. Then the last of the fragments executing tryAdvance has to realize that it is the last one (and it also couldn’t advance) to throw the appropriate exception. So I didn’t add support for splitting here.

SQL Server r2 installation error .. update Visual Studio 2008 to SP1

Finally, I solved it. Even though the solution is a bit lengthy, I think its the simplest. The solution is as follows:

  1. Install Visual Studio 2008
  2. Install the service Package 1 (SP1)
  3. Install SQL Server 2008 r2

How to add an element to Array and shift indexes?

Jrad solution is good but I don't like that he doesn't use array copy. Internally System.arraycopy() does a native call so you will a get faster results.

public static int[] addPos(int[] a, int index, int num) {
    int[] result = new int[a.length];
    System.arraycopy(a, 0, result, 0, index);
    System.arraycopy(a, index, result, index + 1, a.length - index - 1);
    result[index] = num;
    return result;
}

Run class in Jar file

There are two types of JAR files available in Java:

  1. Runnable/Executable jar file which contains manifest file. To run a Runnable jar you can use java -jar fileName.jar or java -jar -classpath abc.jar fileName.jar

  2. Simple jar file that does not contain a manifest file so you simply run your main class by giving its path java -cp ./fileName.jar MainClass

how to get html content from a webview?

Android WebView is just another render engine that render HTML contents downloaded from a HTTP server, much like Chrome or FireFox. I don't know the reason why you need get the rendered page (or screenshot) from WebView. For most of situation, this is not necessary. You can always get the raw HTML content from HTTP server directly.

There are already answers posted talking about getting the raw stream using HttpUrlConnection or HttpClient. Alternatively, there is a very handy library when dealing with HTML content parse/process on Android: JSoup, it provide very simple API to get HTML contents form HTTP server, and provide an abstract representation of HTML document to help us manage HTML parsing not only in a more OO style but also much easily:

// Single line of statement to get HTML document from HTTP server.
Document doc = Jsoup.connect("http://en.wikipedia.org/").get();

It is handy when, for example, you want to download HTML document first then add some custom css or javascript to it before passing it to WebView for rendering. Much more on their official web site, worth to check it out.

How to reload .bashrc settings without logging out and back in again?

I used easyengine to set up my vultr cloud based server.
I found my bash file at /etc/bash.bashrc.

So source /etc/bash.bashrc did the trick for me!

update

When setting up a bare server (ubuntu 16.04), you can use the above info, when you have not yet set up a username, and are logging in via root.

It's best to create a user (with sudo privledges), and login as this username instead.
This will create a directory for your settings, including .profile and .bashrc files.
https://linuxize.com/post/how-to-create-a-sudo-user-on-ubuntu/

Now, you will edit and (and "source") the ~/.bashrc file.

On my server, this was located at /home/your_username/.bashrc
(where your_username is actually the new username you created above, and now login with)

CentOS: Copy directory to another directory

This works for me.

cp -r /home/server/folder/test/. /home/server

Create a remote branch on GitHub

It looks like github has a simple UI for creating branches. I opened the branch drop-down and it prompts me to "Find or create a branch ...". Type the name of your new branch, then click the "create" button that appears.

To retrieve your new branch from github, use the standard git fetch command.

create branch github ui

I'm not sure this will help your underlying problem, though, since the underlying data being pushed to the server (the commit objects) is the same no matter what branch it's being pushed to.

Efficient way to insert a number into a sorted array of numbers?

Simple (Demo):

function sortedIndex(array, value) {
    var low = 0,
        high = array.length;

    while (low < high) {
        var mid = (low + high) >>> 1;
        if (array[mid] < value) low = mid + 1;
        else high = mid;
    }
    return low;
}

What is initial scale, user-scalable, minimum-scale, maximum-scale attribute in meta tag?

user-scalable:

user-scalable=yes (default) to allow the user to zoom in or out on the web page;

user-scalable=no to prevent the user from zooming in or out.

You can get more detailed information by reading the following articles.

Demo Code (recommended)

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="UTF-8">_x000D_
    <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=0.5, maximum-scale=3.0">_x000D_
</head>_x000D_
<body>_x000D_
    <header>_x000D_
    </header>_x000D_
    <main>_x000D_
        <section>_x000D_
            <h1>do not using <mark>user-scalable=no</mark></h1>_x000D_
        </section>_x000D_
    </main>_x000D_
    <footer>_x000D_
    </footer>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Plot a legend outside of the plotting area in base graphics?

Maybe what you need is par(xpd=TRUE) to enable things to be drawn outside the plot region. So if you do the main plot with bty='L' you'll have some space on the right for a legend. Normally this would get clipped to the plot region, but do par(xpd=TRUE) and with a bit of adjustment you can get a legend as far right as it can go:

 set.seed(1) # just to get the same random numbers
 par(xpd=FALSE) # this is usually the default

 plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2), bty='L')
 # this legend gets clipped:
 legend(2.8,0,c("group A", "group B"), pch = c(1,2), lty = c(1,2))

 # so turn off clipping:
 par(xpd=TRUE)
 legend(2.8,-1,c("group A", "group B"), pch = c(1,2), lty = c(1,2))

Finding last occurrence of substring in string, replacing that

Naïve approach:

a = "A long string with a . in the middle ending with ."
fchar = '.'
rchar = '. -'
a[::-1].replace(fchar, rchar[::-1], 1)[::-1]

Out[2]: 'A long string with a . in the middle ending with . -'

Aditya Sihag's answer with a single rfind:

pos = a.rfind('.')
a[:pos] + '. -' + a[pos+1:]

Most efficient way to get table row count

Next to the information_schema suggestion, this:

SELECT id FROM table ORDER BY id DESC LIMIT 1

should also be very fast, provided there's an index on the id field (which I believe must be the case with auto_increment)

What's the difference between interface and @interface in java?

interface: defines the contract for a class which implements it

@interface: defines the contract for an annotation

Correct way to use get_or_create?

Following @Tobu answer and @mipadi comment, in a more pythonic way, if not interested in the created flag, I would use:

customer.source, _ = Source.objects.get_or_create(name="Website")

Drop a temporary table if it exists

Check for the existence by retrieving its object_id:

if object_id('tempdb..##clients_keyword') is not null
    drop table ##clients_keyword

How to paste yanked text into the Vim command line

OS X

If you are using Vim in Mac OS X, unfortunately it comes with older version, and not complied with clipboard options. Luckily, Homebrew can easily solve this problem.

Install Vim:

brew install vim --with-lua --with-override-system-vi

Install the GUI version of Vim:

brew install macvim --with-lua --with-override-system-vi

Restart the terminal for it to take effect.


Append the following line to ~/.vimrc
set clipboard=unnamed

Now you can copy the line in Vim with yy and paste it system-wide.

Gradle store on local file system

Gradle's local repository folder is:

  • $USER_HOME/.gradle/caches/modules-2/files-2.1

Defined dependencies will be loaded from remote repositories into gradle's local repository folder. For each loaded file, gradle will be create a new folder named with md5 value of the original file (pom,jar,..). Full path for the dependency file is made up from :

  • groupid + artifactid + version + FILE_MD5_VALUE + FILE_NAME

If our defined dependency is:

  • compile 'org.springframework:spring-jdbc:4.3.4.RELEASE'

Then the library will be loaded into :

  • /$USER_HOME/.gradle/caches/modules-2/files-2.1/org.springframework/spring-jdbc/4.3.4.RELEASE/42175d194cf6aa7c716c0887f30255e5c0a5262c/spring-jdbc-4.3.4.RELEASE.jar

org.hibernate.QueryException: could not resolve property: filename

Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity).

Make sure you refer to the property as fileName in the Criteria query, not filename.

Specifically, Hibernate will call the getter method of the filename property when executing that Criteria query, so it will look for a method called getFilename(). But the property is called FileName and the getter getFileName().

So, change the projection like so:

criteria.setProjection(Projections.property("fileName"));

Explain why constructor inject is better than other options

Constructor injection is used when the class cannot function without the dependent class.

Property injection is used when the class can function without the dependent class.

As a concrete example, consider a ServiceRepository which depends on IService to do its work. Since ServiceRepository cannot function usefully without IService, it makes sense to have it injected via the constructor.

The same ServiceRepository class may use a Logger to do tracing. The ILogger can be injected via Property injection.

Other common examples of Property injection are ICache (another aspect in AOP terminology) or IBaseProperty (a property in the base class).

Apply .gitignore on an existing repository already tracking large number of files

Use git clean
Get help on this running

git clean -h

If you want to see what would happen first, make sure to pass the -n switch for a dry run:

git clean -xn

To remove gitingnored garbage

git clean -xdf

Careful: You may be ignoring local config files like database.yml which would also be removed. Use at your own risk.

Then

git add .
git commit -m ".gitignore is now working"
git push

How to determine whether a year is a leap year?

The whole formula can be contained in a single expression:

def is_leap_year(year):
    return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0

print n, " is a leap year" if is_leap_year(n) else " is not a leap year"

Sorting data based on second column of a file

You can use the sort command:

sort -k2 -n yourfile

-n, --numeric-sort compare according to string numerical value

For example:

$ cat ages.txt 
Bob 12
Jane 48
Mark 3
Tashi 54

$ sort -k2 -n ages.txt 
Mark 3
Bob 12
Jane 48
Tashi 54

Simulate Keypress With jQuery

Another option:

$(el).trigger({type: 'keypress', which: 13, keyCode: 13});

http://api.jquery.com/trigger/

How to display multiple images in one figure correctly?

Here is my approach that you may try:

import numpy as np
import matplotlib.pyplot as plt

w=10
h=10
fig=plt.figure(figsize=(8, 8))
columns = 4
rows = 5
for i in range(1, columns*rows +1):
    img = np.random.randint(10, size=(h,w))
    fig.add_subplot(rows, columns, i)
    plt.imshow(img)
plt.show()

The resulting image:

output_image

(Original answer date: Oct 7 '17 at 4:20)

Edit 1

Since this answer is popular beyond my expectation. And I see that a small change is needed to enable flexibility for the manipulation of the individual plots. So that I offer this new version to the original code. In essence, it provides:-

  1. access to individual axes of subplots
  2. possibility to plot more features on selected axes/subplot

New code:

import numpy as np
import matplotlib.pyplot as plt

w = 10
h = 10
fig = plt.figure(figsize=(9, 13))
columns = 4
rows = 5

# prep (x,y) for extra plotting
xs = np.linspace(0, 2*np.pi, 60)  # from 0 to 2pi
ys = np.abs(np.sin(xs))           # absolute of sine

# ax enables access to manipulate each of subplots
ax = []

for i in range(columns*rows):
    img = np.random.randint(10, size=(h,w))
    # create subplot and append to ax
    ax.append( fig.add_subplot(rows, columns, i+1) )
    ax[-1].set_title("ax:"+str(i))  # set title
    plt.imshow(img, alpha=0.25)

# do extra plots on selected axes/subplots
# note: index starts with 0
ax[2].plot(xs, 3*ys)
ax[19].plot(ys**2, xs)

plt.show()  # finally, render the plot

The resulting plot:

enter image description here

Edit 2

In the previous example, the code provides access to the sub-plots with single index, which is inconvenient when the figure has many rows/columns of sub-plots. Here is an alternative of it. The code below provides access to the sub-plots with [row_index][column_index], which is more suitable for manipulation of array of many sub-plots.

import matplotlib.pyplot as plt
import numpy as np

# settings
h, w = 10, 10        # for raster image
nrows, ncols = 5, 4  # array of sub-plots
figsize = [6, 8]     # figure size, inches

# prep (x,y) for extra plotting on selected sub-plots
xs = np.linspace(0, 2*np.pi, 60)  # from 0 to 2pi
ys = np.abs(np.sin(xs))           # absolute of sine

# create figure (fig), and array of axes (ax)
fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize)

# plot simple raster image on each sub-plot
for i, axi in enumerate(ax.flat):
    # i runs from 0 to (nrows*ncols-1)
    # axi is equivalent with ax[rowid][colid]
    img = np.random.randint(10, size=(h,w))
    axi.imshow(img, alpha=0.25)
    # get indices of row/column
    rowid = i // ncols
    colid = i % ncols
    # write row/col indices as axes' title for identification
    axi.set_title("Row:"+str(rowid)+", Col:"+str(colid))

# one can access the axes by ax[row_id][col_id]
# do additional plotting on ax[row_id][col_id] of your choice
ax[0][2].plot(xs, 3*ys, color='red', linewidth=3)
ax[4][3].plot(ys**2, xs, color='green', linewidth=3)

plt.tight_layout(True)
plt.show()

The resulting plot:

plot3

mysqldump Error 1045 Access denied despite correct passwords etc

The access being denied is probably to the Windows file system not to the MySQL database; try redirecting the output file to a location where your account is allowed to create files.

Javascript: Extend a Function

The other methods are great but they don't preserve any prototype functions attached to init. To get around that you can do the following (inspired by the post from Nick Craver).

(function () {
    var old_prototype = init.prototype;
    var old_init = init;
    init = function () {
        old_init.apply(this, arguments);
        // Do something extra
    };
    init.prototype = old_prototype;
}) ();

Parsing boolean values with argparse

This works for everything I expect it to:

add_boolean_argument(parser, 'foo', default=True)
parser.parse_args([])                   # Whatever the default was
parser.parse_args(['--foo'])            # True
parser.parse_args(['--nofoo'])          # False
parser.parse_args(['--foo=true'])       # True
parser.parse_args(['--foo=false'])      # False
parser.parse_args(['--foo', '--nofoo']) # Error

The code:

def _str_to_bool(s):
    """Convert string to bool (in argparse context)."""
    if s.lower() not in ['true', 'false']:
        raise ValueError('Need bool; got %r' % s)
    return {'true': True, 'false': False}[s.lower()]

def add_boolean_argument(parser, name, default=False):                                                                                               
    """Add a boolean argument to an ArgumentParser instance."""
    group = parser.add_mutually_exclusive_group()
    group.add_argument(
        '--' + name, nargs='?', default=default, const=True, type=_str_to_bool)
    group.add_argument('--no' + name, dest=name, action='store_false')

Check if any ancestor has a class using jQuery

if ($elem.parents('.left').length) {

}

Conda activate not working?

Just use this command in your cmd:

activate <envname>

Works like charm! (worked for windows, don't know about mac)

Automate scp file transfer using a shell script

here's bash code for SCP with a .pem key file. Just save it to a script.sh file then run with 'sh script.sh'

Enjoy

#!/bin/bash
#Error function
function die(){
echo "$1"
exit 1
}

Host=ec2-53-298-45-63.us-west-1.compute.amazonaws.com
User=ubuntu
#Directory at sent destination
SendDirectory=scp
#File to send at host
FileName=filetosend.txt
#Key file
Key=MyKeyFile.pem

echo "Aperture in Process...";

#The code that will send your file scp
scp -i $Key $FileName $User@$Host:$SendDirectory || \
die "@@@@@@@Houston we have problem"

echo "########Aperture Complete#########";

How to handle change text of span

You could use the function that changes the text of span1 to change the text of the others.

As a work around, if you really want it to have a change event, then don't asign text to span 1. Instead asign an input variable in jQuery, write a change event to it, and whever ur changing the text of span1 .. instead change the value of your input variable, thus firing change event, like so:

var spanChange = $("<input />");
function someFuncToCalculateAndSetTextForSpan1() {
    //  do work
    spanChange.val($newText).change();
};

$(function() {
    spanChange.change(function(e) {
        var $val = $(this).val(),
            $newVal = some*calc-$val;
        $("#span1").text($val);
        $("#spanWhatever").text($newVal);
    });
});

Though I really feel this "work-around", while useful in some aspects of creating a simple change event, is very overextended, and you'd best be making the changes to other spans at the same time you change span1.

Can not run Java Applets in Internet Explorer 11 using JRE 7u51

I had this problem on a client's pc in IE 11 with Java installed. It worked fine in Chrome, but wouldn't work in IE. After several days of TS, I just tried unchecking ActiveX Filtering in settings->safety. Now Java works fine.

How can I get onclick event on webview in android?

WebViewClient.shouldOverrideUrlLoading might be helpful. We are having a similar requirement in one of our app. Not tried yet.

Difference between readFile() and readFileSync()

fs.readFile takes a call back which calls response.send as you have shown - good. If you simply replace that with fs.readFileSync, you need to be aware it does not take a callback so your callback which calls response.send will never get called and therefore the response will never end and it will timeout.

You need to show your readFileSync code if you're not simply replacing readFile with readFileSync.

Also, just so you're aware, you should never call readFileSync in a node express/webserver since it will tie up the single thread loop while I/O is performed. You want the node loop to process other requests until the I/O completes and your callback handling code can run.

How can I check if a string only contains letters in Python?

The str.isalpha() function works. ie.

if my_string.isalpha():
    print('it is letters')

jQuery UI Dialog with ASP.NET button postback

The exact solution is;

$("#dialogDiv").dialog({ other options...,
    open: function (type, data) {
        $(this).parent().appendTo("form");
    }
});

html cellpadding the left side of a cell

I use inline css all the time BECAUSE.... I want absolute control of the design and place different things aligned differently from cell to cell.

It is not hard to understand...

Anyway, I just put something like this inside my tag:

style='padding:5px 10px 5px 5px'

Where the order represents top, right, bottom and left.

Value Change Listener to JTextField

Just create an interface that extends DocumentListener and implements all DocumentListener methods:

@FunctionalInterface
public interface SimpleDocumentListener extends DocumentListener {
    void update(DocumentEvent e);

    @Override
    default void insertUpdate(DocumentEvent e) {
        update(e);
    }
    @Override
    default void removeUpdate(DocumentEvent e) {
        update(e);
    }
    @Override
    default void changedUpdate(DocumentEvent e) {
        update(e);
    }
}

and then:

jTextField.getDocument().addDocumentListener(new SimpleDocumentListener() {
    @Override
    public void update(DocumentEvent e) {
        // Your code here
    }
});

or you can even use lambda expression:

jTextField.getDocument().addDocumentListener((SimpleDocumentListener) e -> {
    // Your code here
});

Removing duplicate values from a PowerShell array

In case you want to be fully bomb prove, this is what I would advice:

@('Apples', 'Apples ', 'APPLES', 'Banana') | 
    Sort-Object -Property @{Expression={$_.Trim()}} -Unique

Output:

Apples
Banana

This uses the Property parameter to first Trim() the strings, so extra spaces are removed and then selects only the -Unique values.

More info on Sort-Object:

Get-Help Sort-Object -ShowWindow

toBe(true) vs toBeTruthy() vs toBeTrue()

In javascript there are trues and truthys. When something is true it is obviously true or false. When something is truthy it may or may not be a boolean, but the "cast" value of is a boolean.

Examples.

true == true; // (true) true
1 == true; // (true) truthy
"hello" == true;  // (true) truthy
[1, 2, 3] == true; // (true) truthy
[] == false; // (true) truthy
false == false; // (true) true
0 == false; // (true) truthy
"" == false; // (true) truthy
undefined == false; // (true) truthy
null == false; // (true) truthy

This can make things simpler if you want to check if a string is set or an array has any values.

var users = [];

if(users) {
  // this array is populated. do something with the array
}

var name = "";

if(!name) {
  // you forgot to enter your name!
}

And as stated. expect(something).toBe(true) and expect(something).toBeTrue() is the same. But expect(something).toBeTruthy() is not the same as either of those.

Transfer data from one HTML file to another

HI im going to leave this here cz i cant comment due to restrictions but i found AlexFitiskin's answer perfect, but a small correction was needed

document.getElementById('here').innerHTML = data.name; 

This needed to be changed to

document.getElementById('here').innerHTML = data.n;

I know that after five years the owner of the post will not find it of any importance but this is for people who might come across in the future .

Item frequency count in Python

Use reduce() to convert the list to a single dict.

words = "apple banana apple strawberry banana lemon"
reduce( lambda d, c: d.update([(c, d.get(c,0)+1)]) or d, words.split(), {})

returns

{'strawberry': 1, 'lemon': 1, 'apple': 2, 'banana': 2}

.ps1 cannot be loaded because the execution of scripts is disabled on this system

I had a similar issue and noted that the default cmd on Windows Server 2012 was running the x64 one.

For Windows 7, Windows 8, Windows Server 2008 R2 or Windows Server 2012, run the following commands as Administrator:

x86

Open C:\Windows\SysWOW64\cmd.exe Run the command: powershell Set-ExecutionPolicy RemoteSigned

x64

Open C:\Windows\system32\cmd.exe Run the command powershell Set-ExecutionPolicy RemoteSigned

You can check mode using

In CMD: echo %PROCESSOR_ARCHITECTURE% In Powershell: [Environment]::Is64BitProcess

I hope this help you.

How do I prompt for Yes/No/Cancel input in a Linux shell script?

At least five answers for one generic question.

Depending on

  • compliant: could work on poor systems with generic environments
  • specific: using so called bashisms

and if you want

  • simple ``in line'' question / answer (generic solutions)
  • pretty formatted interfaces, like or more graphical using libgtk or libqt...
  • use powerful readline history capability

1. POSIX generic solutions

You could use the read command, followed by if ... then ... else:

echo -n "Is this a good question (y/n)? "
read answer

# if echo "$answer" | grep -iq "^y" ;then

if [ "$answer" != "${answer#[Yy]}" ] ;then
    echo Yes
else
    echo No
fi

(Thanks to Adam Katz's comment: Replaced the test above with one that is more portable and avoids one fork:)

POSIX, but single key feature

But if you don't want the user to have to hit Return, you could write:

(Edited: As @JonathanLeffler rightly suggest, saving stty's configuration could be better than simply force them to sane.)

echo -n "Is this a good question (y/n)? "
old_stty_cfg=$(stty -g)
stty raw -echo ; answer=$(head -c 1) ; stty $old_stty_cfg # Careful playing with stty
if echo "$answer" | grep -iq "^y" ;then
    echo Yes
else
    echo No
fi

Note: This was tested under , , , and !

Same, but waiting explicitly for y or n:

#/bin/sh
echo -n "Is this a good question (y/n)? "
old_stty_cfg=$(stty -g)
stty raw -echo
answer=$( while ! head -c 1 | grep -i '[ny]' ;do true ;done )
stty $old_stty_cfg
if echo "$answer" | grep -iq "^y" ;then
    echo Yes
else
    echo No
fi

Using dedicated tools

There are many tools which were built using libncurses, libgtk, libqt or other graphical libraries. For example, using whiptail:

if whiptail --yesno "Is this a good question" 20 60 ;then
    echo Yes
else
    echo No
fi

Depending on your system, you may need to replace whiptail with another similiar tool:

dialog --yesno "Is this a good question" 20 60 && echo Yes

gdialog --yesno "Is this a good question" 20 60 && echo Yes

kdialog --yesno "Is this a good question" 20 60 && echo Yes

where 20 is height of dialog box in number of lines and 60 is width of the dialog box. These tools all have near same syntax.

DIALOG=whiptail
if [ -x /usr/bin/gdialog ] ;then DIALOG=gdialog ; fi
if [ -x /usr/bin/xdialog ] ;then DIALOG=xdialog ; fi
...
$DIALOG --yesno ...

2. Bash specific solutions

Basic in line method

read -p "Is this a good question (y/n)? " answer
case ${answer:0:1} in
    y|Y )
        echo Yes
    ;;
    * )
        echo No
    ;;
esac

I prefer to use case so I could even test for yes | ja | si | oui if needed...

in line with single key feature

Under bash, we can specify the length of intended input for for the read command:

read -n 1 -p "Is this a good question (y/n)? " answer

Under bash, read command accepts a timeout parameter, which could be useful.

read -t 3 -n 1 -p "Is this a good question (y/n)? " answer
[ -z "$answer" ] && answer="Yes"  # if 'yes' have to be default choice

3. Some tricks for dedicated tools

More sophisticated dialog boxes, beyond simple yes - no purposes:

dialog --menu "Is this a good question" 20 60 12 y Yes n No m Maybe

Progress bar:

dialog --gauge "Filling the tank" 20 60 0 < <(
    for i in {1..100};do
        printf "XXX\n%d\n%(%a %b %T)T progress: %d\nXXX\n" $i -1 $i
        sleep .033
    done
) 

Little demo:

#!/bin/sh
while true ;do
    [ -x "$(which ${DIALOG%% *})" ] || DIALOG=dialog
    DIALOG=$($DIALOG --menu "Which tool for next run?" 20 60 12 2>&1 \
            whiptail       "dialog boxes from shell scripts" >/dev/tty \
            dialog         "dialog boxes from shell with ncurses" \
            gdialog        "dialog boxes from shell with Gtk" \
            kdialog        "dialog boxes from shell with Kde" ) || exit
    clear;echo "Choosed: $DIALOG."
    for i in `seq 1 100`;do
        date +"`printf "XXX\n%d\n%%a %%b %%T progress: %d\nXXX\n" $i $i`"
        sleep .0125
      done | $DIALOG --gauge "Filling the tank" 20 60 0
    $DIALOG --infobox "This is a simple info box\n\nNo action required" 20 60
    sleep 3
    if $DIALOG --yesno  "Do you like this demo?" 20 60 ;then
        AnsYesNo=Yes; else AnsYesNo=No; fi
    AnsInput=$($DIALOG --inputbox "A text:" 20 60 "Text here..." 2>&1 >/dev/tty)
    AnsPass=$($DIALOG --passwordbox "A secret:" 20 60 "First..." 2>&1 >/dev/tty)
    $DIALOG --textbox /etc/motd 20 60
    AnsCkLst=$($DIALOG --checklist "Check some..." 20 60 12 \
        Correct "This demo is useful"        off \
        Fun        "This demo is nice"        off \
        Strong        "This demo is complex"        on 2>&1 >/dev/tty)
    AnsRadio=$($DIALOG --radiolist "I will:" 20 60 12 \
        " -1" "Downgrade this answer"        off \
        "  0" "Not do anything"                on \
        " +1" "Upgrade this anser"        off 2>&1 >/dev/tty)
    out="Your answers:\nLike: $AnsYesNo\nInput: $AnsInput\nSecret: $AnsPass"
    $DIALOG --msgbox "$out\nAttribs: $AnsCkLst\nNote: $AnsRadio" 20 60
  done

More sample? Have a look at Using whiptail for choosing USB device and USB removable storage selector: USBKeyChooser

5. Using readline's history

Example:

#!/bin/bash

set -i
HISTFILE=~/.myscript.history
history -c
history -r

myread() {
    read -e -p '> ' $1
    history -s ${!1}
}
trap 'history -a;exit' 0 1 2 3 6

while myread line;do
    case ${line%% *} in
        exit )  break ;;
        *    )  echo "Doing something with '$line'" ;;
      esac
  done

This will create a file .myscript.history in your $HOME directory, than you could use readline's history commands, like Up, Down, Ctrl+r and others.

How can I define a composite primary key in SQL?

Just for clarification: a table can have at most one primary key. A primary key consists of one or more columns (from that table). If a primary key consists of two or more columns it is called a composite primary key. It is defined as follows:

CREATE TABLE voting (
  QuestionID NUMERIC,
  MemberID NUMERIC,
  PRIMARY KEY (QuestionID, MemberID)
);

The pair (QuestionID,MemberID) must then be unique for the table and neither value can be NULL. If you do a query like this:

SELECT * FROM voting WHERE QuestionID = 7

it will use the primary key's index. If however you do this:

SELECT * FROM voting WHERE MemberID = 7

it won't because to use a composite index requires using all the keys from the "left". If an index is on fields (A,B,C) and your criteria is on B and C then that index is of no use to you for that query. So choose from (QuestionID,MemberID) and (MemberID,QuestionID) whichever is most appropriate for how you will use the table.

If necessary, add an index on the other:

CREATE UNIQUE INDEX idx1 ON voting (MemberID, QuestionID);

iPhone Debugging: How to resolve 'failed to get the task for process'?

If you are getting such error, the only reason could be you using a Distribution profile rather than a development profile in Xcode or a missing Entitlement property. If you are not using the Entitlements.plist, then the only possible error could be the app is getting packaged with a distribution profile. You could verify this confirming the build logs. To change this, go to Build Setting of the project and verify Code Signing Entity setting. For debugging to work, this setting should be a developer profile for the configuration that you are currently using.

https://developer.apple.com/library/ios/#qa/qa1682/_index.html

For instant results, delete all mobile provisioning profiles from xcode and install the developer profile that you intend to use.

How do I show a console output/window in a forms application?

//From your application set the Console to write to your RichTextkBox 
//object:
Console.SetOut(new RichTextBoxWriter(yourRichTextBox));

//To ensure that your RichTextBox object is scrolled down when its text is 
//changed add this event:
private void yourRichTextBox_TextChanged(object sender, EventArgs e)
{
    yourRichTextBox.SelectionStart = yourRichTextBox.Text.Length;
    yourRichTextBox.ScrollToCaret();
}

public delegate void StringArgReturningVoidDelegate(string text);
public class RichTextBoxWriter : TextWriter
{
    private readonly RichTextBox _richTextBox;
    public RichTextBoxWriter(RichTextBox richTexttbox)
    {
        _richTextBox = richTexttbox;
    }

    public override void Write(char value)
    {
        SetText(value.ToString());
    }

    public override void Write(string value)
    {
        SetText(value);
    }

    public override void WriteLine(char value)
    {
        SetText(value + Environment.NewLine);
    }

    public override void WriteLine(string value)
    {
        SetText(value + Environment.NewLine);
    }

    public override Encoding Encoding => Encoding.ASCII;

    //Write to your UI object in thread safe way:
    private void SetText(string text)
    {
        // InvokeRequired required compares the thread ID of the  
        // calling thread to the thread ID of the creating thread.  
        // If these threads are different, it returns true.  
        if (_richTextBox.InvokeRequired)
        {
            var d = new StringArgReturningVoidDelegate(SetText);
            _richTextBox.Invoke(d, text);
        }
        else
        {
            _richTextBox.Text += text;
        }
    }
}

nginx - nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)

I had several *.save files (emergency dumps from nano) from different NGINX config files in my sites-avilable dir. Once I deleted these .save files, NGINX restarted fine. I assumed these were harmless since there were no corresponding symlinks, but I guess I was wrong.

Splitting string with pipe character ("|")

split takes regex as a parameter.| has special meaning in regex.. use \\| instead of | to escape it.

Get Application Directory

I got this

String appPath = App.getApp().getApplicationContext().getFilesDir().getAbsolutePath();

from here:

Single vs double quotes in JSON

demjson is also a good package to solve the problem of bad json syntax:

pip install demjson

Usage:

from demjson import decode
bad_json = "{'username':'dfdsfdsf'}"
python_dict = decode(bad_json)

Edit:

demjson.decode is a great tool for damaged json, but when you are dealing with big amourt of json data ast.literal_eval is a better match and much faster.

Using Python's list index() method on a list of tuples or objects?

Python's list.index(x) returns index of the first occurrence of x in the list. So we can pass objects returned by list compression to get their index.

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> [tuple_list.index(t) for t in tuple_list if t[1] == 7]
[1]
>>> [tuple_list.index(t) for t in tuple_list if t[0] == 'kumquat']
[2]

With the same line, we can also get the list of index in case there are multiple matched elements.

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11), ("banana", 7)]
>>> [tuple_list.index(t) for t in tuple_list if t[1] == 7]
[1, 4]

How to parse json string in Android?

Use JSON classes for parsing e.g

JSONObject mainObject = new JSONObject(Your_Sring_data);
JSONObject uniObject = mainObject.getJSONObject("university");
String  uniName = uniObject.getString("name");
String uniURL = uniObject.getString("url");

JSONObject oneObject = mainObject.getJSONObject("1");
String id = oneObject.getString("id");
....

What's is the difference between train, validation and test set, in neural networks?

Would appreciate any thoughts on the situation with 3 data sets. Say a logistic regression model is fitted yielding the following accuracy (Gini): Train: 70%; Test 58% and Out-of-time validation: 66%.

Actually all the possible combinations of predictors bring the same results with quite a huge drop between train and test data sets. The sample size is around 8k divided into train and test 70/30. OOT sample contains a few thousands of cases. Regularization, ensembles didn't help in solving this.

I doubt whether this is something I should concern if OOT performance is acceptable and close to train sample performance?

"undefined" function declared in another file?

If you're using go run, do go run *.go. It will automatically find all go files in the current working directory, compile and then run your main function.

Session variables not working php

Just talked to the hosting service, it was an issue at their end. he said " your account session.save_path was not set as a result issue arise. I set it for you now."

And it works fine after that :)

How do I add a newline to a windows-forms TextBox?

make sure you textbox is set for multiline then you wont need any extra dims vbnewline will work just fine

Foreach with JSONArray and JSONObject

Seems like you can't iterate through JSONArray with a for each. You can loop through your JSONArray like this:

for (int i=0; i < arr.length(); i++) {
    arr.getJSONObject(i);
}

Source

Google MAP API Uncaught TypeError: Cannot read property 'offsetWidth' of null

  • Setup ng-init=init() in your HTML
  • And in the controller

    use $scope.init = function() {...} instead of google.maps.event.addDomListener(window, "load", init){...}

Hope this will help you.

Regex: Use start of line/end of line signs (^ or $) in different context

Just use look-arounds to solve this:

(?<=^|,)garp(?=$|,)

The difference with look-arounds and just regular groups are that with regular groups the comma would be part of the match, and with look-arounds it wouldn't. In this case it doesn't make a difference though.

Html.Textbox VS Html.TextboxFor

Ultimately they both produce the same HTML but Html.TextBoxFor() is strongly typed where as Html.TextBox isn't.

1:  @Html.TextBox("Name")
2:  Html.TextBoxFor(m => m.Name)

will both produce

<input id="Name" name="Name" type="text" />

So what does that mean in terms of use?

Generally two things:

  1. The typed TextBoxFor will generate your input names for you. This is usually just the property name but for properties of complex types can include an underscore such as 'customer_name'
  2. Using the typed TextBoxFor version will allow you to use compile time checking. So if you change your model then you can check whether there are any errors in your views.

It is generally regarded as better practice to use the strongly typed versions of the HtmlHelpers that were added in MVC2.

Python: Tuples/dictionaries as keys, select, sort

You want to use two keys independently, so you have two choices:

  1. Store the data redundantly with two dicts as {'banana' : {'blue' : 4, ...}, .... } and {'blue': {'banana':4, ...} ...}. Then, searching and sorting is easy but you have to make sure you modify the dicts together.

  2. Store it just one dict, and then write functions that iterate over them eg.:

    d = {'banana' : {'blue' : 4, 'yellow':6}, 'apple':{'red':1} }
    
    blueFruit = [(fruit,d[fruit]['blue']) if d[fruit].has_key('blue') for fruit in d.keys()]
    

Checking for duplicate strings in JavaScript array

Using some function on arrays: If any item in the array has an index number from the beginning is not equals to index number from the end, then this item exists in the array more than once.

// vanilla js
function hasDuplicates(arr) {
    return arr.some( function(item) {
        return arr.indexOf(item) !== arr.lastIndexOf(item);
    });
}

Set multiple system properties Java command line

There's nothing on the Documentation that mentions about anything like that.

Here's a quote:

-Dproperty=value Set a system property value. If value is a string that contains spaces, you must enclose the string in double quotes:

java -Dfoo="some string" SomeClass

How do I group Windows Form radio buttons?

I like the concept of grouping RadioButtons in WPF. There is a property GroupName that specifies which RadioButton controls are mutually exclusive (http://msdn.microsoft.com/de-de/library/system.windows.controls.radiobutton.aspx).

So I wrote a derived class for WinForms that supports this feature:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Windows.Forms.VisualStyles;
using System.Drawing;
using System.ComponentModel;

namespace Use.your.own
{
    public class AdvancedRadioButton : CheckBox
    {
        public enum Level { Parent, Form };

        [Category("AdvancedRadioButton"),
        Description("Gets or sets the level that specifies which RadioButton controls are affected."),
        DefaultValue(Level.Parent)]
        public Level GroupNameLevel { get; set; }

        [Category("AdvancedRadioButton"),
        Description("Gets or sets the name that specifies which RadioButton controls are mutually exclusive.")]
        public string GroupName { get; set; }

        protected override void OnCheckedChanged(EventArgs e)
        {
            base.OnCheckedChanged(e);

            if (Checked)
            {
                var arbControls = (dynamic)null;
                switch (GroupNameLevel)
                {
                    case Level.Parent:
                        if (this.Parent != null)
                            arbControls = GetAll(this.Parent, typeof(AdvancedRadioButton));
                        break;
                    case Level.Form:
                        Form form = this.FindForm();
                        if (form != null)
                            arbControls = GetAll(this.FindForm(), typeof(AdvancedRadioButton));
                        break;
                }
                if (arbControls != null)
                    foreach (Control control in arbControls)
                        if (control != this &&
                            (control as AdvancedRadioButton).GroupName == this.GroupName)
                            (control as AdvancedRadioButton).Checked = false;
            }
        }

        protected override void OnClick(EventArgs e)
        {
            if (!Checked)
                base.OnClick(e);
        }

        protected override void OnPaint(PaintEventArgs pevent)
        {
            CheckBoxRenderer.DrawParentBackground(pevent.Graphics, pevent.ClipRectangle, this);

            RadioButtonState radioButtonState;
            if (Checked)
            {
                radioButtonState = RadioButtonState.CheckedNormal;
                if (Focused)
                    radioButtonState = RadioButtonState.CheckedHot;
                if (!Enabled)
                    radioButtonState = RadioButtonState.CheckedDisabled;
            }
            else
            {
                radioButtonState = RadioButtonState.UncheckedNormal;
                if (Focused)
                    radioButtonState = RadioButtonState.UncheckedHot;
                if (!Enabled)
                    radioButtonState = RadioButtonState.UncheckedDisabled;
            }

            Size glyphSize = RadioButtonRenderer.GetGlyphSize(pevent.Graphics, radioButtonState);
            Rectangle rect = pevent.ClipRectangle;
            rect.Width -= glyphSize.Width;
            rect.Location = new Point(rect.Left + glyphSize.Width, rect.Top);

            RadioButtonRenderer.DrawRadioButton(pevent.Graphics, new System.Drawing.Point(0, rect.Height / 2 - glyphSize.Height / 2), rect, this.Text, this.Font, this.Focused, radioButtonState);
        }

        private IEnumerable<Control> GetAll(Control control, Type type)
        {
            var controls = control.Controls.Cast<Control>();

            return controls.SelectMany(ctrl => GetAll(ctrl, type))
                                      .Concat(controls)
                                      .Where(c => c.GetType() == type);
        }
    }
}

Creating a directory in /sdcard fails

Restart your Android device. Things started to work for me after I restarted the device.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

This error can also occur if you try to change the directory where the database is stored, but imput the wrong directory in the configuration file (like a typo in the second drive as D instead of the accurate D_). Instead of telling you the typo directory does not exist, it will tell you that you lack permission to access it (leading you to try to change the permissions for the typo directory, which it will let you do). So if you get this error while changing directories, double check the configuration file and make sure you don't have a typo.

Erase the current printed console line

You can use a \r (carriage return) to return the cursor to the beginning of the line:

printf("hello");
printf("\rbye");

This will print bye on the same line. It won't erase the existing characters though, and because bye is shorter than hello, you will end up with byelo. To erase it you can make your new print longer to overwrite the extra characters:

printf("hello");
printf("\rbye  ");

Or, first erase it with a few spaces, then print your new string:

printf("hello");
printf("\r          ");
printf("\rbye");

That will print hello, then go to the beginning of the line and overwrite it with spaces, then go back to the beginning again and print bye.

Cannot get Kerberos service ticket: KrbException: Server not found in Kerberos database (7)

Consider adding

[appdefaults]
validate=false

to your /etc/krb5.conf. This can work around mismatching DNS.

copying all contents of folder to another folder using batch file?

@echo off
xcopy /s C:\yourfile C:\anotherfile\

This is how it is done! Simple, right?

How do I escape spaces in path for scp copy in Linux?

Use 3 backslashes to escape spaces in names of directories:

scp user@host:/path/to/directory\\\ with\\\ spaces/file ~/Downloads

should copy to your Downloads directory the file from the remote directory called directory with spaces.

Checking to see if one array's elements are in another array in PHP

Performance test for in_array vs array_intersect:

$a1 = array(2,4,8,11,12,13,14,15,16,17,18,19,20);

$a2 = array(3,20);

$intersect_times = array();
$in_array_times = array();
for($j = 0; $j < 10; $j++)
{
    /***** TEST ONE array_intersect *******/
    $t = microtime(true);
    for($i = 0; $i < 100000; $i++)
    {
        $x = array_intersect($a1,$a2);
        $x = empty($x);
    }
    $intersect_times[] = microtime(true) - $t;


    /***** TEST TWO in_array *******/
    $t2 = microtime(true);
    for($i = 0; $i < 100000; $i++)
    {
        $x = false;
        foreach($a2 as $v){
            if(in_array($v,$a1))
            {
                $x = true;
                break;
            }
        }
    }
    $in_array_times[] = microtime(true) - $t2;
}

echo '<hr><br>'.implode('<br>',$intersect_times).'<br>array_intersect avg: '.(array_sum($intersect_times) / count($intersect_times));
echo '<hr><br>'.implode('<br>',$in_array_times).'<br>in_array avg: '.(array_sum($in_array_times) / count($in_array_times));
exit;

Here are the results:

0.26520013809204
0.15600109100342
0.15599989891052
0.15599989891052
0.1560001373291
0.1560001373291
0.15599989891052
0.15599989891052
0.15599989891052
0.1560001373291
array_intersect avg: 0.16692011356354

0.015599966049194
0.031199932098389
0.031200170516968
0.031199932098389
0.031200885772705
0.031199932098389
0.031200170516968
0.031201124191284
0.031199932098389
0.031199932098389
in_array avg: 0.029640197753906

in_array is at least 5 times faster. Note that we "break" as soon as a result is found.

Update only specific fields in a models.Model

To update a subset of fields, you can use update_fields:

survey.save(update_fields=["active"]) 

The update_fields argument was added in Django 1.5. In earlier versions, you could use the update() method instead:

Survey.objects.filter(pk=survey.pk).update(active=True)

Which MySQL datatype to use for an IP address?

Since IPv4 addresses are 4 byte long, you could use an INT (UNSIGNED) that has exactly 4 bytes:

`ipv4` INT UNSIGNED

And INET_ATON and INET_NTOA to convert them:

INSERT INTO `table` (`ipv4`) VALUES (INET_ATON("127.0.0.1"));
SELECT INET_NTOA(`ipv4`) FROM `table`;

For IPv6 addresses you could use a BINARY instead:

`ipv6` BINARY(16)

And use PHP’s inet_pton and inet_ntop for conversion:

'INSERT INTO `table` (`ipv6`) VALUES ("'.mysqli_real_escape_string(inet_pton('2001:4860:a005::68')).'")'
'SELECT `ipv6` FROM `table`'
$ipv6 = inet_pton($row['ipv6']);

How to change value of ArrayList element in java

Change it to for(int i=0;i<=9;i++)

How to right align widget in horizontal linear layout Android?

With Linear Layout

<LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/select_car_book_tabbar"
        android:gravity="right" >

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:src="@drawable/my_booking_icon" />
    </LinearLayout>

enter image description here

with FrameLayout

<FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/select_car_book_tabbar">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|right"
            android:src="@drawable/my_booking_icon" />
    </FrameLayout>

with RelativeLayout

<RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/select_car_book_tabbar">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerInParent="true"
            android:src="@drawable/my_booking_icon" />
    </RelativeLayout>

IE throws JavaScript Error: The value of the property 'googleMapsQuery' is null or undefined, not a Function object (works in other browsers)

Have you tried adding the semicolon to onclick="googleMapsQuery(422111);". I don't have enough of your code to test if the missing semicolon would cause the error, but ie is more picky about syntax.

find -mtime files older than 1 hour

What about -mmin?

find /var/www/html/audio -daystart -maxdepth 1 -mmin +59 -type f -name "*.mp3" \
    -exec rm -f {} \;

From man find:

-mmin n
        File's data was last modified n minutes ago.

Also, make sure to test this first!

... -exec echo rm -f '{}' \;
          ^^^^ Add the 'echo' so you just see the commands that are going to get
               run instead of actual trying them first.

'No JUnit tests found' in Eclipse

The solution was, after making a backup of the src/test folder, removing it from the filesystem, then creating it again.

That's after I did the "Remove from build path" hint and it screwed the folders when opening the project in STS 4.

Firefox "ssl_error_no_cypher_overlap" error

I've had the same problem; to solve was enough to enable all the SSL schemas in "about:config". I was finding them by filtering with ssl. First I anabled all options for afret disabling the unnecessary ones.

How to set Highcharts chart maximum yAxis value

Alternatively one can use the setExtremes method also,

yAxis.setExtremes(0, 100);

Or if only one value is needed to be set, just leave other as null

yAxis.setExtremes(null, 100);

Timestamp conversion in Oracle for YYYY-MM-DD HH:MM:SS format

INSERT INTO AM_PROGRAM_TUNING_EVENT_TMP1 
VALUES(TO_DATE('2012-03-28 11:10:00','yyyy/mm/dd hh24:mi:ss'));

http://www.sqlfiddle.com/#!4/22115/1

How to find the socket buffer size of linux

If you want see your buffer size in terminal, you can take a look at:

  • /proc/sys/net/ipv4/tcp_rmem (for read)
  • /proc/sys/net/ipv4/tcp_wmem (for write)

They contain three numbers, which are minimum, default and maximum memory size values (in byte), respectively.

PHP Foreach Arrays and objects

Recursive traverse object or array with array or objects elements:

function traverse(&$objOrArray)
{
    foreach ($objOrArray as $key => &$value)
    {
        if (is_array($value) || is_object($value))
        {
            traverse($value);
        }
        else
        {
            // DO SOMETHING
        }
    }
}

Displaying a 3D model in JavaScript/HTML5

I have not played with 3D yet, but I know a good place for ressources on 3D for HTML5.

http://www.html5rocks.com/en/gaming

And here is a tutorial on how to create your 3D models with the Three.js Framework.

http://www.html5rocks.com/en/tutorials/three/intro/

This may help you. Good luck.

How to check what user php is running as?

Proposal

A tad late, but even though the following is a work-around, it solves the requirement as this works just fine:

<?
    function get_sys_usr()
    {
        $unique_name = uniqid();  // not-so-unique id
        $native_path = "./temp/$unique_name.php";
        $public_path = "http://example.com/temp/$unique_name.php";
        $php_content = "<? echo get_current_user(); ?>";
        $process_usr = "apache";  // fall-back

        if (is_readable("./temp") && is_writable("./temp"))
        {
            file_put_contents($native_path,$php_content);
            $process_usr = trim(file_get_contents($public_path));
            unlink($native_path);
        }

        return $process_usr;
    }


    echo get_sys_usr();  // www-data
?>


Description

The code-highlighting above is not accurate, please copy & paste in your favorite editor and view as PHP code, or save and test it yourself.

As you probably know, get_current_user() returns the owner of the "current running script" - so if you did not "chown" a script on the server to the web-server-user it will most probably be "nobody", or if the developer-user exists on the same OS, it will rather display that username.

To work around this, we create a file with the current running process. If you just require() this into the current running script, it will return the same as the parent-script as mentioned; so, we need to run it as a separate request to take effect.

Process-flow

In order to make this effective, consider running a design pattern that incorporates "runtime-mode", so when the server is in "development-mode or test-mode" then only it could run this function and save its output somewhere in an include, -or just plain text or database, or whichever.

Of course you can change some particulars of the code above as you wish to make it more dynamic, but the logic is as follows:

  • define a unique reference to limit interference with other users
  • define a local file-path for writing a temporary file
  • define a public url/path to run this file in its own process
  • write the temporary php file that outputs the script owner name
  • get the output of this script by making a request to it
  • delete the file as it is no longer needed - or leave it if you want
  • return the output of the request as return-value of the function

Display all views on oracle database

for all views (you need dba privileges for this query)

select view_name from dba_views

for all accessible views (accessible by logged user)

select view_name from all_views

for views owned by logged user

select view_name from user_views

Why can't I use switch statement on a String?

Switches based on integers can be optimized to very efficent code. Switches based on other data type can only be compiled to a series of if() statements.

For that reason C & C++ only allow switches on integer types, since it was pointless with other types.

The designers of C# decided that the style was important, even if there was no advantage.

The designers of Java apparently thought like the designers of C.

Vue Js - Loop via v-for X times (in a range)

In 2.2.0+, when using v-for with a component, a key is now required.

<div v-for="item in items" :key="item.id">

Source

Disable cache for some images

Simple, send one header location.

My site, contains one image, and after upload the image, there not change, then I add this code:

<?php header("Location: pagelocalimage.php"); ?>

Work's for me.

How to check if curl is enabled or disabled

<?php

// Script to test if the CURL extension is installed on this server

// Define function to test
function _is_curl_installed() {
    if  (in_array  ('curl', get_loaded_extensions())) {
        return true;
    }
    else {
        return false;
    }
}

// Ouput text to user based on test
if (_is_curl_installed()) {
  echo "cURL is <span style=\"color:blue\">installed</span> on this server";
} else {
  echo "cURL is NOT <span style=\"color:red\">installed</span> on this server";
}
?>

or a simple one -

<?
phpinfo();
?>

Just search for curl

source - http://www.mattsbits.co.uk/item-164.html

Volatile vs. Interlocked vs. lock

I did some test to see how the theory actually works: kennethxu.blogspot.com/2009/05/interlocked-vs-monitor-performance.html. My test was more focused on CompareExchnage but the result for Increment is similar. Interlocked is not necessary faster in multi-cpu environment. Here is the test result for Increment on a 2 years old 16 CPU server. Bare in mind that the test also involves the safe read after increase, which is typical in real world.

D:\>InterlockVsMonitor.exe 16
Using 16 threads:
          InterlockAtomic.RunIncrement         (ns):   8355 Average,   8302 Minimal,   8409 Maxmial
    MonitorVolatileAtomic.RunIncrement         (ns):   7077 Average,   6843 Minimal,   7243 Maxmial

D:\>InterlockVsMonitor.exe 4
Using 4 threads:
          InterlockAtomic.RunIncrement         (ns):   4319 Average,   4319 Minimal,   4321 Maxmial
    MonitorVolatileAtomic.RunIncrement         (ns):    933 Average,    802 Minimal,   1018 Maxmial

What is the difference between <html lang="en"> and <html lang="en-US">?

You can use any country code, yes, but that doesn't mean a browser or other software will recognize it or do anything differently because of it. For example, a screen reader might deal with "en-US" and "en-GB" the same if they only support an American accent in English. Another piece of software that has two distinct voices, though, could adjust according to the country code.

How can I kill a process by name instead of PID?

A bit longer alternative:

kill `pidof firefox`

How to implement a property in an interface

  • but i already assigned values such that irp.WrmVersion = "10.4";

J.Random Coder's answer and initialize version field.


private string version = "10.4';

How to find the cumulative sum of numbers in a list?

In Python 2 you can define your own generator function like this:

def accumu(lis):
    total = 0
    for x in lis:
        total += x
        yield total

In [4]: list(accumu([4,6,12]))
Out[4]: [4, 10, 22]

And in Python 3.2+ you can use itertools.accumulate():

In [1]: lis = [4,6,12]

In [2]: from itertools import accumulate

In [3]: list(accumulate(lis))
Out[3]: [4, 10, 22]

Bootstrap 3 jquery event for active tab change

Thanks to @Gerben's post came to know there are two events show.bs.tab (before the tab is shown) and shown.bs.tab (after the tab is shown) as explained in the docs - Bootstrap Tab usage

An additional solution if we're only interested in a specific tab, and maybe add separate functions without having to add an if - else block in one function, is to use the a href selector (maybe along with additional selectors if required)

 $("a[href='#tab_target_id']").on('shown.bs.tab', function(e) {
      console.log('shown - after the tab has been shown');
 });

 // or even this one if we want the earlier event
 $("a[href='#tab_target_id']").on('show.bs.tab', function(e) {
      console.log('show - before the new tab has been shown');
 });

demo

Short circuit Array.forEach like calling break

var Book = {"Titles":[                          
    {
    "Book3" : "BULLETIN 3"
    }   
    ,
    {
    "Book1" : "BULLETIN 1"
    }
    ,
    {
    "Book2" : "BULLETIN 2"
    }    
]}

var findbystr = function(str) { 
    var return_val;
    Book.Titles.forEach(function(data){ 
        if(typeof data[str] != 'undefined')
        {
            return_val = data[str];
        } 
    }, str) 

    return return_val;
}

book = findbystr('Book1');
console.log(book);

openssl s_client -cert: Proving a client certificate was sent to the server

I know this is an old question but it does not yet appear to have an answer. I've duplicated this situation, but I'm writing the server app, so I've been able to establish what happens on the server side as well. The client sends the certificate when the server asks for it and if it has a reference to a real certificate in the s_client command line. My server application is set up to ask for a client certificate and to fail if one is not presented. Here is the command line I issue:

Yourhostname here -vvvvvvvvvv s_client -connect <hostname>:443 -cert client.pem -key cckey.pem -CAfile rootcert.pem -cipher ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH -tls1 -state

When I leave out the "-cert client.pem" part of the command the handshake fails on the server side and the s_client command fails with an error reported. I still get the report "No client certificate CA names sent" but I think that has been answered here above.

The short answer then is that the server determines whether a certificate will be sent by the client under normal operating conditions (s_client is not normal) and the failure is due to the server not recognizing the CA in the certificate presented. I'm not familiar with many situations in which two-way authentication is done although it is required for my project.

You are clearly sending a certificate. The server is clearly rejecting it.

The missing information here is the exact manner in which the certs were created and the way in which the provider loaded the cert, but that is probably all wrapped up by now.

How do I set a variable to the output of a command in Bash?

$(sudo run command)

If you're going to use an apostrophe, you need `, not '. This character is called "backticks" (or "grave accent"):

#!/bin/bash

VAR1="$1"
VAR2="$2"

MOREF=`sudo run command against "$VAR1" | grep name | cut -c7-`

echo "$MOREF"

HTML: can I display button text in multiple lines?

Yes it is, and you can also use it like this

<button>Click here to<br/> start playing</button>

if you want to make the break yourself.

CSS opacity only to background color, not the text on it?

Use:

background:url("location of image"); // Use an image with opacity

This method will work in all browsers.

Reducing the gap between a bullet and text in a list item

You could try the following. But it requires you to put a <span> element inside the <li> elements

<html>
<head>
<style type="text/css">
ul.a li span{
position:relative;
left:-0.5em;

}
</style>
</head>

<body>

<ul class="a">
  <li><span>Coffee</span></li>
  <li><span>Tea</span></li>
  <li><span>Coca Cola</span></li>
</ul>
</body>
</html>

Excel 2010 VBA - Close file No Save without prompt

If you're not wanting to save changes set savechanges to false

    Sub CloseBook2()
        ActiveWorkbook.Close savechanges:=False
    End Sub

for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used

    ActiveWorkbook.Close False

How do I fix PyDev "Undefined variable from import" errors?

It is possible you just need to re-configure your python path within Eclipse. See my answer to a similar question.

SQL, How to Concatenate results?

In SQL Server 2005 and up, you could do something like this:

SELECT 
    (SELECT ModuleValue + ','
     FROM dbo.Modules
     FOR XML PATH('')
    ) 
FROM dbo.Modules
WHERE ModuleID = 1

This should give you something like what you're looking for.

Marc

Make a Bash alias that takes a parameter?

To give specific answer to the Question posed about creating the alias to move the files to Trash folder instead of deleting them:

alias rm="mv "$1" -t ~/.Trash/"

Offcourse you have to create dir ~/.Trash first.

Then just give following command:

$rm <filename>
$rm <dirname>

How do I dump the data of some SQLite3 tables?

You can do this getting difference of .schema and .dump commands. for example with grep:

sqlite3 some.db .schema > schema.sql
sqlite3 some.db .dump > dump.sql
grep -vx -f schema.sql dump.sql > data.sql

data.sql file will contain only data without schema, something like this:

BEGIN TRANSACTION;
INSERT INTO "table1" VALUES ...;
...
INSERT INTO "table2" VALUES ...;
...
COMMIT;

I hope this helps you.

How to debug apk signed for release?

I tried with the following and it's worked:

release {
            debuggable true
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

Couldn't connect to server 127.0.0.1:27017

Check your filesystem free space and increase it if its less. This also could cause the mongo not to start. Check the /var/log/mongodb/mongodb.log file.

ERROR: Insufficient free space for journal files
Please make at least 3379MB available in /var/lib/mongodb/journal or use --smallfiles

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

I had a similar issue but from reading this question I figured I could run on UI thread:

YourActivity.this.runOnUiThread(new Runnable() {
    public void run() {
        alertDialog.show();
    }
});

Seems to do the trick for me.

JOIN queries vs multiple queries

Yes, one query using JOINS would be quicker. Although without knowing the relationships of the tables you are querying, the size of your dataset, or where the primary keys are, it's almost impossible to say how much faster.

Why not test both scenarios out, then you'll know for sure...

Getting NetworkCredential for current user (C#)

You can get the user name using System.Security.Principal.WindowsIdentity.GetCurrent() but there is not way to get current user password!

Get button click inside UITableViewCell

Its Work For me.

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     UIButton *Btn_Play = (UIButton *)[cell viewWithTag:101];
     [Btn_Play addTarget:self action:@selector(ButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)ButtonClicked:(UIButton*)sender {
     CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.Tbl_Name];
     NSIndexPath *indexPath = [self.Tbl_Name indexPathForRowAtPoint:buttonPosition];
}

How do I use PHP namespaces with autoload?

Class1 is not in the global scope.

See below for a working example:

<?php

function __autoload($class)
{
    $parts = explode('\\', $class);
    require end($parts) . '.php';
}

use Person\Barnes\David as MyPerson;

$class = new MyPerson\Class1();

Edit (2009-12-14):

Just to clarify, my usage of "use ... as" was to simplify the example.

The alternative was the following:

$class = new Person\Barnes\David\Class1();

or

use Person\Barnes\David\Class1;

// ...

$class = new Class1();

jQuery Ajax POST example with PHP

HTML:

    <form name="foo" action="form.php" method="POST" id="foo">
        <label for="bar">A bar</label>
        <input id="bar" class="inputs" name="bar" type="text" value="" />
        <input type="submit" value="Send" onclick="submitform(); return false;" />
    </form>

JavaScript:

   function submitform()
   {
       var inputs = document.getElementsByClassName("inputs");
       var formdata = new FormData();
       for(var i=0; i<inputs.length; i++)
       {
           formdata.append(inputs[i].name, inputs[i].value);
       }
       var xmlhttp;
       if(window.XMLHttpRequest)
       {
           xmlhttp = new XMLHttpRequest;
       }
       else
       {
           xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
       }
       xmlhttp.onreadystatechange = function()
       {
          if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
          {

          }
       }
       xmlhttp.open("POST", "insert.php");
       xmlhttp.send(formdata);
   }

How to JOIN three tables in Codeigniter

public function getdata(){
        $this->db->select('c.country_name as country, s.state_name as state, ct.city_name as city, t.id as id');
        $this->db->from('tblmaster t'); 
        $this->db->join('country c', 't.country=c.country_id');
        $this->db->join('state s', 't.state=s.state_id');
        $this->db->join('city ct', 't.city=ct.city_id');
        $this->db->order_by('t.id','desc');
        $query = $this->db->get();      
        return $query->result();
}

Add new line in text file with Windows batch file

Suppose you want to insert a particular line of text (not an empty line):

@echo off
FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C
set /a totallines+=1

@echo off
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
  SETLOCAL EnableDelayedExpansion
  SET /p L=
  IF %%i==%insertat% ECHO(!TL!
  ECHO(!L!
  ENDLOCAL
)
) >%tempfile%

COPY /Y %tempfile% %origfile% >NUL

DEL %tempfile%

Can't push to the heroku

Specify the buildpack while creating the app.

heroku create appname --buildpack heroku/python

How can I get an object's absolute position on the page in Javascript?

var cumulativeOffset = function(element) {
    var top = 0, left = 0;
    do {
        top += element.offsetTop  || 0;
        left += element.offsetLeft || 0;
        element = element.offsetParent;
    } while(element);

    return {
        top: top,
        left: left
    };
};

(Method shamelessly stolen from PrototypeJS; code style, variable names and return value changed to protect the innocent)