Programs & Examples On #Adview

Google Adview is an API to show advertisements from Google Admob / AdSense on smartphones and tablets on the Android, iOS and Windows Mobile platforms.

How to fix Error: this class is not key value coding-compliant for the key tableView.'

You have your storyboard set up to expect an outlet called tableView but the actual outlet name is myTableView.

If you delete the connection in the storyboard and reconnect to the right variable name, it should fix the problem.

failed to load ad : 3

Your ad units are not displaying ads because you haven't yet verified your address (PIN).

Maybe it helps to others, i received this notification on my AdSense account. enter image description here

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

Swift 4:

I was getting this error because of a change in the UIVisualEffectView api. In Swift 3 it was ok to do this: myVisuallEffectView.addSubview(someSubview)

But in Swift 4 I had to change it to this: myVisualEffectView.contentView.addSubview(someSubview)

Error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported

For me it turned out that I had a @JsonManagedReferece in one entity without a @JsonBackReference in the other referenced entity. This caused the marshaller to throw an error.

Android Studio - Importing external Library/Jar

Easy way and it works for me. Using Android Studio 0.8.2.

  1. Drag jar file under libs.
  2. Press "Sync Project with Gradle Files" button.

enter image description here

Set View Width Programmatically

in code add below line:

spin27.setLayoutParams(new LinearLayout.LayoutParams(200, 120));

How can I load Partial view inside the view?

If you do it with a @Html.ActionLink() then loading the PartialView is handled as a normal request when clicking a anchor-element, i.e. load new page with the reponse of the PartialViewResult method.
If you want to load it immedialty, then you use @Html.RenderPartial("_LoadView") or @Html.RenderAction("Load").
If you want to do it upon userinteraction (i.e. clicking a link) then you need to use AJAX --> @Ajax.ActionLink()

android: how to change layout on button click?

I would add an android:onClick to the layout and then change the layout in the activity.

So in the layout

<ImageView
(Other things like source etc.)
android:onClick="changelayout"
/>

Then in the activity add the following:

public void changelayout(View view){
    setContentView(R.layout.second_layout);
}

jQuery returning "parsererror" for ajax request

I had the same problem, turned out my web.config was not the same with my teammates. So please check your web.config.

Hope this helps someone.

Loaded nib but the 'view' outlet was not set

Just spent more than hour trying to find out why my view property is not set in my view controller upon initiating it from nib. Remember to call "[super initWithNibName...]" inside your view controller's initWithNibName.

How to load a UIView using a nib file created with Interface Builder

I found this blog posting by Aaron Hillegass (author, instructor, Cocoa ninja) to be very enlightening. Even if you don't adopt his modified approach to loading NIB files through a designated initializer you will probably at least get a better understanding of the process that's going on. I've been using this method lately to great success!

iPhone UIView Animation Best Practice

let's do try and checkout For Swift 3...

UIView.transition(with: mysuperview, duration: 0.75, options:UIViewAnimationOptions.transitionFlipFromRight , animations: {
    myview.removeFromSuperview()
}, completion: nil)

Display filename before matching line

This is a slight modification from a previous solution. My example looks for stderr redirection in bash scripts: grep '2>' $(find . -name "*.bash")

I just discovered why all ASP.Net websites are slow, and I am trying to work out what to do about it

If you are using the updated Microsoft.Web.RedisSessionStateProvider(starting from 3.0.2) you can add this to your web.config to allow concurrent sessions.

<appSettings>
    <add key="aspnet:AllowConcurrentRequestsPerSession" value="true"/>
</appSettings>

Source

Eclipse change project files location

If you have your project saved as a local copy of a repository, it may be better to import from git. Select local, and then browse to your git repository folder. That worked better for me than importing it as an existing project. Attempting the latter did not allow me to "finish".

How to list the tables in a SQLite database file that was opened with ATTACH?

There are a few steps to see the tables in an SQLite database:

  1. List the tables in your database:

    .tables
    
  2. List how the table looks:

    .schema tablename
    
  3. Print the entire table:

    SELECT * FROM tablename;
    
  4. List all of the available SQLite prompt commands:

    .help
    

Cell spacing in UICollectionView

Try this code to ensure you have a spacing of 5px between each item:

- (UIEdgeInsets)collectionView:(UICollectionView *) collectionView 
                        layout:(UICollectionViewLayout *) collectionViewLayout 
        insetForSectionAtIndex:(NSInteger) section {

    return UIEdgeInsetsMake(0, 0, 0, 5); // top, left, bottom, right
}

- (CGFloat)collectionView:(UICollectionView *) collectionView
                   layout:(UICollectionViewLayout *) collectionViewLayout
  minimumInteritemSpacingForSectionAtIndex:(NSInteger) section {    
    return 5.0;
}

Is it possible to access to google translate api for free?

Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.

UPD 19.03.2019 Here is a version for browser on GitHub.

How to change row color in datagridview?

If you are the second dumbest developer on the planet (me being the dumbest), all of the above solutions seem to work: CellFormatting, DataSourceChanged, and RowPrePaint. I prefer RowPrePaint.

I struggled with this (for way too long) because I needed to override my SelectionBackColor and SelectionForeColor instead of BackColor and ForeColor as I was changing the selected row.

Is it possible to run selenium (Firefox) web driver without a GUI?

Yes. You can use HTMLUnitDriver instead for FirefoxDriver while starting webdriver. This is headless browser setup. Details can be found here.

How to stop VMware port error of 443 on XAMPP Control Panel v3.2.1

Say you let vmware use port 443, and use another ssl port in XAMPP Apache (httpd-ssl.conf) :

The red error will keep popping in XAMPP Control Panel. You also need to change the port in the XAMPP Control Panel configuration :

In XAMPP Control Panel, click the "Config" button (top-left). Then click "Service and Port Settings". There you can set the ports to match the ports used by Apache.

How to put a symbol above another in LaTeX?

${a \atop \#}$

or

${a \above 0pt \#}$

take(1) vs first()

Here are three Observables A, B, and C with marble diagrams to explore the difference between first, take, and single operators:

first vs take vs single operators comparison

* Legend:
--o-- value
----! error
----| completion

Play with it at https://thinkrx.io/rxjs/first-vs-take-vs-single/ .

Already having all the answers, I wanted to add a more visual explanation

Hope it helps someone

How can I delay a :hover effect in CSS?

You can use transitions to delay the :hover effect you want, if the effect is CSS-based.

For example

div{
    transition: 0s background-color;
}

div:hover{
    background-color:red;    
    transition-delay:1s;
}

this will delay applying the the hover effects (background-color in this case) for one second.


Demo of delay on both hover on and off:

_x000D_
_x000D_
div{_x000D_
    display:inline-block;_x000D_
    padding:5px;_x000D_
    margin:10px;_x000D_
    border:1px solid #ccc;_x000D_
    transition: 0s background-color;_x000D_
    transition-delay:1s;_x000D_
}_x000D_
div:hover{_x000D_
    background-color:red;_x000D_
}
_x000D_
<div>delayed hover</div>
_x000D_
_x000D_
_x000D_

Demo of delay only on hover on:

_x000D_
_x000D_
div{_x000D_
    display:inline-block;_x000D_
    padding:5px;_x000D_
    margin:10px;_x000D_
    border:1px solid #ccc;_x000D_
    transition: 0s background-color;_x000D_
}_x000D_
div:hover{_x000D_
    background-color:red;    _x000D_
    transition-delay:1s;_x000D_
}
_x000D_
<div>delayed hover</div>
_x000D_
_x000D_
_x000D_


Vendor Specific Extentions for Transitions and W3C CSS3 transitions

Excel Define a range based on a cell value

Here is an option. It works by using making an INDIRECT(ADDRESS(...)) from the ROW and COLUMN of the start cell, A1, down to the initial row + the number of rows held in B1.

SUM(INDIRECT(ADDRESS(ROW(A1),COLUMN(A1))):INDIRECT(ADDRESS(ROW(A1)+B1,COLUMN(A1))))

A1: is the start of data in a the "A" column

B1: is the number of rows to sum

Programmatically get own phone number in iOS

At the risk of getting negative marks, I want to suggest that the highest ranking solution (currently the first response) violates the latest SDK Agreement as of Nov 5, 2009. Our application was just rejected for using it. Here's the response from Apple:

"For security reasons, iPhone OS restricts an application (including its preferences and data) to a unique location in the file system. This restriction is part of the security feature known as the application's "sandbox." The sandbox is a set of fine-grained controls limiting an application's access to files, preferences, network resources, hardware, and so on."

The device's phone number is not available within your application's container. You will need to revise your application to read only within your directory container and resubmit your binary to iTunes Connect in order for your application to be reconsidered for the App Store.

This was a real disappointment since we wanted to spare the user having to enter their own phone number.

Could not connect to React Native development server on Android

Basically this error comes when npm server is not started.

So at first check the npm server status, if it's not running then start npm with command npm start and you can see in terminal:

Loading dependency graph done.

Now npm is started and run your app in another terminal with command

react-native run-android

Xcode: failed to get the task for process

Just get the same problem by installing my app on iPhone 5S with Distribution Profile

-> my solution was to activate Capabilities wich are set in Distribution Profile(in my case "Keychain Sharing","In-App Purchase" and "Game Center")

Hope this helps someone...

WARNING: Setting property 'source' to 'org.eclipse.jst.jee.server:appname' did not find a matching property

You can change the eclipse tomcat server configuration. Open the server view, double click on you server to open server configuration. Then click to activate "Publish module contents to separate XML files". Finally, restart your server, the message must disappear.

Source: http://www.albeesonline.com/blog/2008/11/29/warning-setpropertiesruleserverserviceenginehostcontext-setting-property/

android studio 0.4.2: Gradle project sync failed error

I am facing this problem many times from last few days, the answer above works perfectly fine. I was looking for the exact reason for this problem and in my case I found slow internet or no internet on your machine(assuming you are taking project to windows from mac, that may not be required).

I've noticed while doing build it stopped fetching a URL(http://.maven.org/). I don't know why android studio doing these things again, but that seems to be the only problem in my case.

SQL Server Management Studio alternatives to browse/edit tables and run queries

I have been using Atlantis SQL Enywhere, a free software, for almost 6 months and has been working really well. Works with SQL 2005 and SQL 2008 versions. I am really impressed with its features and keyboard shortcuts are similar to VS, so makes the transition really smooth to a new editor.

Some of the features that are worth mentioning:

  • Intellisense that actually works when using multiple tables and joins with aliases
  • Suggestion of joins when using multiple tables (reduces time on typing, really neat)
  • Rich formatting of sql code, AutoIndent using Ctrl K, Ctrl D.
  • Better representation of SQL plans
  • Highlights variables declarations while they are used.
  • Table definition on mouse hover.

All these features have saved me lot of time.

Chrome DevTools Devices does not detect device when plugged in

I know this is an old question but here is my answer that solved it for me. I had gone through all of the articles I could find and tried everything. It would not work for me on a mac or PC.

Solution: Use another USB cable.

I must have grabbed a poor quality cable that did not support file transfers. I used a different USB cable and immediately got prompted for ptp mode and authorization for remote debugging.

generate days from date range

Generate dates between two date fields

If you are aware with SQL CTE query, then this solution will helps you to solve your question

Here is example

We have dates in one table

Table Name: “testdate”

STARTDATE   ENDDATE
10/24/2012  10/24/2012
10/27/2012  10/29/2012
10/30/2012  10/30/2012

Require Result:

STARTDATE
10/24/2012
10/27/2012
10/28/2012
10/29/2012
10/30/2012

Solution:

WITH CTE AS
  (SELECT DISTINCT convert(varchar(10),StartTime, 101) AS StartTime,
                   datediff(dd,StartTime, endTime) AS diff
   FROM dbo.testdate
   UNION ALL SELECT StartTime,
                    diff - 1 AS diff
   FROM CTE
   WHERE diff<> 0)
SELECT DISTINCT DateAdd(dd,diff, StartTime) AS StartTime
FROM CTE

Explanation: CTE Recursive query explanation

  • First part of query:

    SELECT DISTINCT convert(varchar(10), StartTime, 101) AS StartTime, datediff(dd, StartTime, endTime) AS diff FROM dbo.testdate

    Explanation: firstcolumn is “startdate”, second column is difference of start and end date in days and it will be consider as “diff” column

  • Second part of query:

    UNION ALL SELECT StartTime, diff-1 AS diff FROM CTE WHERE diff<>0

    Explanation: Union all will inherit result of above query until result goes null, So “StartTime” result is inherit from generated CTE query, and from diff, decrease - 1, so its looks like 3, 2, and 1 until 0

For example

STARTDATE   DIFF
10/24/2012  0
10/27/2012  0
10/27/2012  1
10/27/2012  2
10/30/2012  0

Result Specification

STARTDATE       Specification
10/24/2012  --> From Record 1
10/27/2012  --> From Record 2
10/27/2012  --> From Record 2
10/27/2012  --> From Record 2
10/30/2012  --> From Record 3
  • 3rd Part of Query

    SELECT DISTINCT DateAdd(dd,diff, StartTime) AS StartTime FROM CTE

    It will add day “diff” in “startdate” so result should be as below

Result

STARTDATE
10/24/2012
10/27/2012
10/28/2012
10/29/2012
10/30/2012

What does the "~" (tilde/squiggle/twiddle) CSS selector mean?

It is General sibling combinator and is explained in @Salaman's answer very well.

What I did miss is Adjacent sibling combinator which is + and is closely related to ~.

example would be

.a + .b {
  background-color: #ff0000;
}

<ul>
  <li class="a">1st</li>
  <li class="b">2nd</li>
  <li>3rd</li>
  <li class="b">4th</li>
  <li class="a">5th</li>
</ul>
  • Matches elements that are .b
  • Are adjacent to .a
  • After .a in HTML

In example above it will mark 2nd li but not 4th.

_x000D_
_x000D_
   .a + .b {_x000D_
     background-color: #ff0000;_x000D_
   }
_x000D_
<ul>_x000D_
  <li class="a">1st</li>_x000D_
  <li class="b">2nd</li>_x000D_
  <li>3rd</li>_x000D_
  <li class="b">4th</li>_x000D_
  <li class="a">5th</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

JSFiddle

How to list files using dos commands?

Try dir /b, for bare format.

dir /? will show you documentation of what you can do with the dir command. Here is the output from my Windows 7 machine:

C:\>dir /?
Displays a list of files and subdirectories in a directory.

DIR [drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D] [/L] [/N]
  [/O[[:]sortorder]] [/P] [/Q] [/R] [/S] [/T[[:]timefield]] [/W] [/X] [/4]

  [drive:][path][filename]
              Specifies drive, directory, and/or files to list.

  /A          Displays files with specified attributes.
  attributes   D  Directories                R  Read-only files
               H  Hidden files               A  Files ready for archiving
               S  System files               I  Not content indexed files
               L  Reparse Points             -  Prefix meaning not
  /B          Uses bare format (no heading information or summary).
  /C          Display the thousand separator in file sizes.  This is the
              default.  Use /-C to disable display of separator.
  /D          Same as wide but files are list sorted by column.
  /L          Uses lowercase.
  /N          New long list format where filenames are on the far right.
  /O          List by files in sorted order.
  sortorder    N  By name (alphabetic)       S  By size (smallest first)
               E  By extension (alphabetic)  D  By date/time (oldest first)
               G  Group directories first    -  Prefix to reverse order
  /P          Pauses after each screenful of information.
  /Q          Display the owner of the file.
  /R          Display alternate data streams of the file.
  /S          Displays files in specified directory and all subdirectories.
  /T          Controls which time field displayed or used for sorting
  timefield   C  Creation
              A  Last Access
              W  Last Written
  /W          Uses wide list format.
  /X          This displays the short names generated for non-8dot3 file
              names.  The format is that of /N with the short name inserted
              before the long name. If no short name is present, blanks are
              displayed in its place.
  /4          Displays four-digit years

Switches may be preset in the DIRCMD environment variable.  Override
preset switches by prefixing any switch with - (hyphen)--for example, /-W.

How do I pipe or redirect the output of curl -v?

The answer above didn't work for me, what did eventually was this syntax:

curl https://${URL} &> /dev/stdout | tee -a ${LOG}

tee puts the output on the screen, but also appends it to my log.

Most efficient conversion of ResultSet to JSON?

First pre-generate column names, second use rs.getString(i) instead of rs.getString(column_name).

The following is an implementation of this:

    /*
     * Convert ResultSet to a common JSON Object array
     * Result is like: [{"ID":"1","NAME":"Tom","AGE":"24"}, {"ID":"2","NAME":"Bob","AGE":"26"}, ...]
     */
    public static List<JSONObject> getFormattedResult(ResultSet rs) {
        List<JSONObject> resList = new ArrayList<JSONObject>();
        try {
            // get column names
            ResultSetMetaData rsMeta = rs.getMetaData();
            int columnCnt = rsMeta.getColumnCount();
            List<String> columnNames = new ArrayList<String>();
            for(int i=1;i<=columnCnt;i++) {
                columnNames.add(rsMeta.getColumnName(i).toUpperCase());
            }

            while(rs.next()) { // convert each object to an human readable JSON object
                JSONObject obj = new JSONObject();
                for(int i=1;i<=columnCnt;i++) {
                    String key = columnNames.get(i - 1);
                    String value = rs.getString(i);
                    obj.put(key, value);
                }
                resList.add(obj);
            }
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return resList;
    }

python pandas convert index to datetime

In my case, my dataframe has the following characteristics

<class 'pandas.core.frame.DataFrame'>
Index: 3040 entries, 15/12/2008 to  
Data columns (total 1 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   Close   3038 non-null   float64
dtypes: float64(1)
memory usage: 47.5+ KB

enter image description here

The first option data.index = pd.to_datetime(data.index) returned

ParserError: String does not contain a date: ParserError: String does not contain a date:

The second option: data.index.to_datetime() returned

AttributeError: 'Index' object has no attribute 'to_datetime'

It returned

Another option I have tested is. data.index = pd.to_datetime(data.index)

It returned: ParserError: String does not contain a date:

What could be my problem? Thanks

How to localise a string inside the iOS info.plist file?

In my case everything was set up correctly but still the InfoPlist.strings file was not found.

The only thing that really worked was, to remove and add the InfoPlist.strings files again to the project.

Swift - encode URL

Swift 3

In Swift 3 there is addingPercentEncoding

let originalString = "test/test"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
print(escapedString!)

Output:

test%2Ftest

Swift 1

In iOS 7 and above there is stringByAddingPercentEncodingWithAllowedCharacters

var originalString = "test/test"
var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
println("escapedString: \(escapedString)")

Output:

test%2Ftest

The following are useful (inverted) character sets:

URLFragmentAllowedCharacterSet  "#%<>[\]^`{|}
URLHostAllowedCharacterSet      "#%/<>?@\^`{|}
URLPasswordAllowedCharacterSet  "#%/:<>?@[\]^`{|}
URLPathAllowedCharacterSet      "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet     "#%<>[\]^`{|}
URLUserAllowedCharacterSet      "#%/:<>?@[\]^`

If you want a different set of characters to be escaped create a set:
Example with added "=" character:

var originalString = "test/test=42"
var customAllowedSet =  NSCharacterSet(charactersInString:"=\"#%/<>?@\\^`{|}").invertedSet
var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet)
println("escapedString: \(escapedString)")

Output:

test%2Ftest%3D42

Example to verify ascii characters not in the set:

func printCharactersInSet(set: NSCharacterSet) {
    var characters = ""
    let iSet = set.invertedSet
    for i: UInt32 in 32..<127 {
        let c = Character(UnicodeScalar(i))
        if iSet.longCharacterIsMember(i) {
            characters = characters + String(c)
        }
    }
    print("characters not in set: \'\(characters)\'")
}

How to insert an item into an array at a specific index (JavaScript)?

i like little safety and i use this

_x000D_
_x000D_
   Array.prototype.Insert = function (item, before) {
        if (!item) return;
        if (before == null || before < 0 || before > this.length - 1) {
            this.push(item);
            return;
        }
        this.splice(before, 0,item );
    }
    
    
   var t = ["a","b"]
   
   t.Insert("v",1)
    
    console.log(t )
_x000D_
_x000D_
_x000D_

XML Carriage return encoding

To insert a CR into XML, you need to use its character entity &#13;.

This is because compliant XML parsers must, before parsing, translate CRLF and any CR not followed by a LF to a single LF. This behavior is defined in the End-of-Line handling section of the XML 1.0 specification.

How can I split a text into sentences?

You can also use sentence tokenization function in NLTK:

from nltk.tokenize import sent_tokenize
sentence = "As the most quoted English writer Shakespeare has more than his share of famous quotes.  Some Shakespare famous quotes are known for their beauty, some for their everyday truths and some for their wisdom. We often talk about Shakespeare’s quotes as things the wise Bard is saying to us but, we should remember that some of his wisest words are spoken by his biggest fools. For example, both ‘neither a borrower nor a lender be,’ and ‘to thine own self be true’ are from the foolish, garrulous and quite disreputable Polonius in Hamlet."

sent_tokenize(sentence)

What process is listening on a certain port on Solaris?

If you have access to netstat, that can do precisely that.

Split text with '\r\n'

I took a more compact approach to split an input resulting from a text area into a list of string . You can use this if suits your purpose.

the problem is you cannot split by \r\n so i removed the \n beforehand and split only by \r

var serials = model.List.Replace("\n","").Split('\r').ToList<string>();

I like this approach because you can do it in just one line.

Remove element by id

you can just use element.remove()

MVC which submit button has been pressed

<input name="submit" type="submit" id="submit" value="Save" />
<input name="process" type="submit" id="process" value="Process" />

And in your controller action:

public ActionResult SomeAction(string submit)
{
    if (!string.IsNullOrEmpty(submit))
    {
        // Save was pressed
    }
    else
    {
        // Process was pressed
    }
}

Facebook page automatic "like" URL (for QR Code)

For a hyperlink just use www.facebook.com/++page ID++/like

Eg: www.facebook.com/MYPAGEISAWESOME/like

To make it work with m.facebook.com here's what you do:

Open the Facebook page you're looking for then change the URL to the mobile URL ( which is www.m.facebook.com/MYPAGEISAWESOME ).

Now you should see a big version of the mobile Facebook page. Copy the target URL of the like button.

Pop that URL into the QR generator to make a "scan to like" barcode. This will open the m.Facebook page in the browser of most mobiles directly from the QR reader. If they are not logged into Facebook then they will be prompted to log in and then click 'like'. If logged in, it will auto like.

Hope this helps!

Also, definitely include something with a "click here/scan here to like us on Facebook"

How to split a comma-separated value to columns

ALTER FUNCTION [dbo].[StringListTo] (@StringList Nvarchar(max),@Separators char(1),@start int, @index int )
RETURNS nvarchar(max)
AS
BEGIN
declare @out Nvarchar(max)
declare @i int
declare @start_old int
set @start=@start+1
set @i=1
while(@i<=@index)
begin
    set @start_old=@start
    set @start=CHARINDEX('.',@StringList,@start+1)
    if (@start>0)
    begin
        set @out=Substring(@StringList,@start_old+1,@start-@start_old-1)
    end
else
begin
    set @out=Substring(@StringList,@start_old+1,len(@StringList)-1)
end
set @i=@i+1
end
RETURN @out
END;

TypeError: unhashable type: 'list' when using built-in set function

    python 3.2


    >>>> from itertools import chain
    >>>> eg=sorted(list(set(list(chain(*eg)))), reverse=True)
        [7, 6, 5, 4, 3, 2, 1]


   ##### eg contain 2 list within a list. so if you want to use set() function
   you should flatten the list like [1, 2, 3, 4, 4, 5, 6, 7]

   >>> res= list(chain(*eg))       # [1, 2, 3, 4, 4, 5, 6, 7]                   
   >>> res1= set(res)                    #   [1, 2, 3, 4, 5, 6, 7]
   >>> res1= sorted(res1,reverse=True)

How can I put CSS and HTML code in the same file?

Or also you can do something like this.

<div style="background=#aeaeae; float: right">

</div>

We can add any CSS inside the style attribute of HTML tags.

Linq select objects in list where exists IN (A,B,C)

Try with Contains function;

Determines whether a sequence contains a specified element.

var allowedStatus = new[]{ "A", "B", "C" };
var filteredOrders = orders.Order.Where(o => allowedStatus.Contains(o.StatusCode));

Char array declaration and initialization in C

This is another C example of where the same syntax has different meanings (in different places). While one might be able to argue that the syntax should be different for these two cases, it is what it is. The idea is that not that it is "not allowed" but that the second thing means something different (it means "pointer assignment").

How can I get javascript to read from a .json file?

Instead of storing the data as pure JSON store it instead as a JavaScript Object Literal; E.g.

_x000D_
_x000D_
window.portalData = [_x000D_
  {_x000D_
    "kpi" : "NDAR",_x000D_
    "data": [15,152,2,45,0,2,0,16,88,0,174,0,30,63,0,0,0,0,448,4,0,139,1,7,12,0,211,37,182,154]_x000D_
  },_x000D_
  {_x000D_
     "kpi" : "NTI",_x000D_
     "data" : [195,299,31,32,438,12,0,6,136,31,71,5,40,40,96,46,4,49,106,127,43,366,23,36,7,34,196,105,30,77]_x000D_
  },_x000D_
  {_x000D_
     "kpi" : "BS",_x000D_
     "data" : [745,2129,1775,1089,517,720,2269,334,1436,517,3219,1167,2286,266,1813,509,1409,988,1511,972,730,2039,1067,1102,1270,1629,845,1292,1107,1800]_x000D_
  },_x000D_
  {_x000D_
     "kpi" : "SISS",_x000D_
     "data" :  [75,547,260,430,397,91,0,0,217,105,563,136,352,286,244,166,287,319,877,230,100,437,108,326,145,749,0,92,191,469]_x000D_
  },_x000D_
  {_x000D_
 "kpi" : "MID",_x000D_
 "data" : [6,17,14,8,13,7,4,6,8,5,72,15,6,3,1,13,17,32,9,3,25,21,7,49,23,10,13,18,36,9,12]_x000D_
  }_x000D_
];
_x000D_
_x000D_
_x000D_

You can then do the following in your HTML

<script src="server_data.js"> </script>


function getServerData(kpiCode)
{
    var elem = $(window.portalData).filter(function(idx){
        return window.portalData[idx].kpi == kpiCode;
     });

    return elem[0].data;
};

var defData = getServerData('NDAR');

Import python package from local directory into interpreter

A bit late to the party, but this is what worked for me:

>>> import sys
>>> sys.path.insert(0, '')

Apparently, if there is an empty string, Python knows that it should look in the current directory. I did not have the empty string in sys.path, which caused this error.

How to draw a circle with given X and Y coordinates as the middle spot of the circle?

This draws an arc with the center in the specified rectangle. You can draw, half-circles, quarter-circles, etc.

g.drawArc(x - r, y - r, r * 2, r * 2, 0, 360)

lvalue required as left operand of assignment

I found that an answer to this issue when dealing with math is that the operator on the left hand side must be the variable you are trying to change. The logic cannot come first.

coin1 + coin2 + coin3 = coinTotal; // Wrong

coinTotal = coin1 + coin2 + coin3; // Right

This isn't a direct answer to your question but it might be helpful to future people who google the same thing I googled.

Count all values in a matrix greater than a value

To count the number of values larger than x in any numpy array you can use:

n = len(matrix[matrix > x])

The boolean indexing returns an array that contains only the elements where the condition (matrix > x) is met. Then len() counts these values.

How to set the min and max height or width of a Frame?

There is no single magic function to force a frame to a minimum or fixed size. However, you can certainly force the size of a frame by giving the frame a width and height. You then have to do potentially two more things: when you put this window in a container you need to make sure the geometry manager doesn't shrink or expand the window. Two, if the frame is a container for other widget, turn grid or pack propagation off so that the frame doesn't shrink or expand to fit its own contents.

Note, however, that this won't prevent you from resizing a window to be smaller than an internal frame. In that case the frame will just be clipped.

import Tkinter as tk

root = tk.Tk()
frame1 = tk.Frame(root, width=100, height=100, background="bisque")
frame2 = tk.Frame(root, width=50, height = 50, background="#b22222")

frame1.pack(fill=None, expand=False)
frame2.place(relx=.5, rely=.5, anchor="c")

root.mainloop()

How to include *.so library in Android Studio?

This is my build.gradle file, Please note the line

jniLibs.srcDirs = ['libs']

This will include libs's *.so file to apk.

sourceSets {
    main {
        manifest.srcFile 'AndroidManifest.xml'
        java.srcDirs = ['src']
        resources.srcDirs = ['src']
        aidl.srcDirs = ['src']
        renderscript.srcDirs = ['src']
        res.srcDirs = ['res']
        assets.srcDirs = ['assets']
        jniLibs.srcDirs = ['libs']
    }

    // Move the tests to tests/java, tests/res, etc...
    instrumentTest.setRoot('tests')

    // Move the build types to build-types/<type>
    // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
    // This moves them out of them default location under src/<type>/... which would
    // conflict with src/ being used by the main source set.
    // Adding new build types or product flavors should be accompanied
    // by a similar customization.
    debug.setRoot('build-types/debug')
    release.setRoot('build-types/release')
}

Make a UIButton programmatically in Swift

You're just missing the colon at the end of the selector name. Since pressed takes a parameter the colon must be there. Also your pressed function shouldn't be nested inside viewDidLoad.

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let myFirstLabel = UILabel()
    let myFirstButton = UIButton()
    myFirstLabel.text = "I made a label on the screen #toogood4you"
    myFirstLabel.font = UIFont(name: "MarkerFelt-Thin", size: 45)
    myFirstLabel.textColor = UIColor.redColor()
    myFirstLabel.textAlignment = .Center
    myFirstLabel.numberOfLines = 5
    myFirstLabel.frame = CGRectMake(15, 54, 300, 500)
    myFirstButton.setTitle("?", forState: .Normal)
    myFirstButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
    myFirstButton.frame = CGRectMake(15, -50, 300, 500)
    myFirstButton.addTarget(self, action: #selector(myClass.pressed(_:)), forControlEvents: .TouchUpInside)
    self.view.addSubview(myFirstLabel)
    self.view.addSubview(myFirstButton)
}

@objc func pressed(sender: UIButton!) {
    var alertView = UIAlertView()
    alertView.addButtonWithTitle("Ok")
    alertView.title = "title"
    alertView.message = "message"
    alertView.show()
}

EDIT: Updated to reflect best practices in Swift 2.2. #selector() should be used rather than a literal string which is deprecated.

Embedding JavaScript engine into .NET

There is an implementation of an ActiveX Scripting Engine Host in C# available here: parse and execute JS by C#

It allows to use Javascript (or VBScript) directly from C#, in native 32-bit or 64-bit processes. The full source is ~500 lines of C# code. It only has an implicit dependency on the installed JScript (or VBScript) engine DLL.

For example, the following code:

Console.WriteLine(ScriptEngine.Eval("jscript", "1+2/3"));

will display 1.66666666666667

set height of imageview as matchparent programmatically

I had same issue. Resolved by firstly setting :

imageView.setMinHeight(0);
imageView.setMinimumHeight(0);

And then :

imageView.getLayoutParams().height= ViewGroup.LayoutParams.MATCH_PARENT;

setMinHeight is defined by ImageView, while setMinimumHeight is defined by View. According to the docs, the greater of the two values is used, so both must be set.

The operation cannot be completed because the DbContext has been disposed error

Here you are trying to execute IQueryable object on inactive DBContext. your DBcontext is already disposed of. you can only execute IQueryable object before DBContext is disposed of. Means you need to write users.Select(x => x.ToInfo()).ToList() statement inside using scope

What is the significance of #pragma marks? Why do we need #pragma marks?

Just to add the information I was looking for: pragma mark is Xcode specific, so if you deal with a C++ project that you open in different IDEs, it does not have any effect there. In Qt Creator, for example, it does not add categories for methods, nor generate any warnings/errors.

EDIT

#pragma is a preprocessor directive which comes from C programming language. Its purpose is to specify implementation-dependent information to the compiler - that is, each compiler might choose to interpret this directive as it wants. That said, it is rather considered an extension which does not change/influence the code itself. So compilers might as well ignore it.

Xcode is an IDE which takes advantage of #pragma and uses it in its own specific way. The point is, #pragma is not Xcode and even Objective-C specific.

wp_nav_menu change sub-menu class name?

replace class:

echo str_replace('sub-menu', 'menu menu_sub', wp_nav_menu( array(
    'echo' => false,
    'theme_location' => 'sidebar-menu',
    'items_wrap' => '<ul class="menu menu_sidebar">%3$s</ul>' 
  ) )
);

Link to all Visual Studio $ variables

While there does not appear to be one complete list, the following may also be helpful:

How to use Environment properties:
  http://msdn.microsoft.com/en-us/library/ms171459.aspx

MSBuild reserved properties:
  http://msdn.microsoft.com/en-us/library/ms164309.aspx

Well-known item properties (not sure how these are used):
  http://msdn.microsoft.com/en-us/library/ms164313.aspx

Resizing SVG in html?

Try these:

  1. Set the missing viewbox and fill in the height and width values of the set height and height attributes in the svg tag

  2. Then scale the picture simply by setting the height and width to the desired percent values. Good luck.

  3. Set a fixed aspect ratio with preserveAspectRatio="X200Y200 meet (e.g. 200px), but it's not necessary

e.g.

 <svg
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:cc="http://creativecommons.org/ns#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:xlink="http://www.w3.org/1999/xlink"
   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
   width="10%" 
   height="10%"
   preserveAspectRatio="x200Y200 meet"
   viewBox="0 0 350 350"
   id="svg2"
   version="1.1"
   inkscape:version="0.48.0 r9654"
   sodipodi:docname="namesvg.svg">

HTML input field hint

If you mean like a text in the background, I'd say you use a label with the input field and position it on the input using CSS, of course. With JS, you fade out the label when the input receives values and fade it in when the input is empty. In this way, it is not possible for the user to submit the description, whether by accident or intent.

Converting float to char*

char array[10];
sprintf(array, "%f", 3.123);

sprintf: (from MSDN)

python xlrd unsupported format, or corrupt file.

I had the same issue. Those old files are formatted like a tab-delimited file. I've been able to open my problem files with read_table; ie df = pd.read_table('trouble_maker.xls').

Remove Backslashes from Json Data in JavaScript

Your string is invalid, but assuming it was valid, you'd have to do:

var finalData = str.replace(/\\/g, "");

When you want to replace all the occurences with .replace, the first parameter must be a regex, if you supply a string, only the first occurrence will be replaced, that's why your replace wouldn't work.

Cheers

Maven build debug in Eclipse

Easiest way I find is to:

  1. Right click project

  2. Debug as -> Maven build ...

  3. In the goals field put -Dmaven.surefire.debug test

  4. In the parameters put a new parameter called forkCount with a value of 0 (previously was forkMode=never but it is deprecated and doesn't work anymore)

Set your breakpoints down and run this configuration and it should hit the breakpoint.

Laravel blade check empty foreach

I think you are trying to check whether the array is empty or not.You can do like this :

@if(!$result->isEmpty())
     // $result is not empty
@else
    // $result is empty
@endif

Reference isEmpty()

If REST applications are supposed to be stateless, how do you manage sessions?

The fundamental explanation is:

No client session state on the server.

By stateless it means that the server does not store any state about the client session on the server side.

The client session is stored on the client. The server is stateless means that every server can service any client at any time, there is no session affinity or sticky sessions. The relevant session information is stored on the client and passed to the server as needed.

That does not preclude other services that the web server talks to from maintaining state about business objects such as shopping carts, just not about the client's current application/session state.

The client's application state should never be stored on the server, but passed around from the client to every place that needs it.

That is where the ST in REST comes from, State Transfer. You transfer the state around instead of having the server store it. This is the only way to scale to millions of concurrent users. If for no other reason than because millions of sessions is millions of sessions.

The load of session management is amortized across all the clients, the clients store their session state and the servers can service many orders of magnitude or more clients in a stateless fashion.

Even for a service that you think will only need in the 10's of thousands of concurrent users, you still should make your service stateless. Tens of thousands is still tens of thousands and there will be time and space cost associated with it.

Stateless is how the HTTP protocol and the web in general was designed to operate and is an overall simpler implementation and you have a single code path instead of a bunch of server side logic to maintain a bunch of session state.

There are some very basic implementation principles:

These are principles not implementations, how you meet these principles may vary.

In summary, the five key principles are:

  1. Give every “thing” an ID
  2. Link things together
  3. Use standard methods
  4. Resources with multiple representations
  5. Communicate statelessly

There is nothing about authentication or authorization in the REST dissertation.

Because there is nothing different from authenticating a request that is RESTful from one that is not. Authentication is irrelevant to the RESTful discussion.

Explaining how to create a stateless application for your particular requirements, is too-broad for StackOverflow.

Implementing Authentication and Authorization as it pertains to REST is even more so too-broad and various approaches to implementations are explained in great detail on the internet in general.

Comments asking for help/info on this will/should just be flagged as No Longer Needed.

Calling pylab.savefig without display in ipython

We don't need to plt.ioff() or plt.show() (if we use %matplotlib inline). You can test above code without plt.ioff(). plt.close() has the essential role. Try this one:

%matplotlib inline
import pylab as plt

# It doesn't matter you add line below. You can even replace it by 'plt.ion()', but you will see no changes.
## plt.ioff()

# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('test0.png')
plt.close(fig)

# Create a new figure, plot into it, then don't close it so it does get displayed
fig2 = plt.figure()
plt.plot([1,3,2])
plt.savefig('test1.png')

If you run this code in iPython, it will display a second plot, and if you add plt.close(fig2) to the end of it, you will see nothing.

In conclusion, if you close figure by plt.close(fig), it won't be displayed.

Malformed String ValueError ast.literal_eval() with String representation of Tuple

ast.literal_eval (located in ast.py) parses the tree with ast.parse first, then it evaluates the code with quite an ugly recursive function, interpreting the parse tree elements and replacing them with their literal equivalents. Unfortunately the code is not at all expandable, so to add Decimal to the code you need to copy all the code and start over.

For a slightly easier approach, you can use ast.parse module to parse the expression, and then the ast.NodeVisitor or ast.NodeTransformer to ensure that there is no unwanted syntax or unwanted variable accesses. Then compile with compile and eval to get the result.

The code is a bit different from literal_eval in that this code actually uses eval, but in my opinion is simpler to understand and one does not need to dig too deep into AST trees. It specifically only allows some syntax, explicitly forbidding for example lambdas, attribute accesses (foo.__dict__ is very evil), or accesses to any names that are not deemed safe. It parses your expression fine, and as an extra I also added Num (float and integer), list and dictionary literals.

Also, works the same on 2.7 and 3.3

import ast
import decimal

source = "(Decimal('11.66985'), Decimal('1e-8'),"\
    "(1,), (1,2,3), 1.2, [1,2,3], {1:2})"

tree = ast.parse(source, mode='eval')

# using the NodeTransformer, you can also modify the nodes in the tree,
# however in this example NodeVisitor could do as we are raising exceptions
# only.
class Transformer(ast.NodeTransformer):
    ALLOWED_NAMES = set(['Decimal', 'None', 'False', 'True'])
    ALLOWED_NODE_TYPES = set([
        'Expression', # a top node for an expression
        'Tuple',      # makes a tuple
        'Call',       # a function call (hint, Decimal())
        'Name',       # an identifier...
        'Load',       # loads a value of a variable with given identifier
        'Str',        # a string literal

        'Num',        # allow numbers too
        'List',       # and list literals
        'Dict',       # and dicts...
    ])

    def visit_Name(self, node):
        if not node.id in self.ALLOWED_NAMES:
            raise RuntimeError("Name access to %s is not allowed" % node.id)

        # traverse to child nodes
        return self.generic_visit(node)

    def generic_visit(self, node):
        nodetype = type(node).__name__
        if nodetype not in self.ALLOWED_NODE_TYPES:
            raise RuntimeError("Invalid expression: %s not allowed" % nodetype)

        return ast.NodeTransformer.generic_visit(self, node)


transformer = Transformer()

# raises RuntimeError on invalid code
transformer.visit(tree)

# compile the ast into a code object
clause = compile(tree, '<AST>', 'eval')

# make the globals contain only the Decimal class,
# and eval the compiled object
result = eval(clause, dict(Decimal=decimal.Decimal))

print(result)

ErrorActionPreference and ErrorAction SilentlyContinue for Get-PSSessionConfiguration

Tip #2

Can't you use the classical 2> redirection operator.

(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue) 2> $NULL
if(!$?){
   'foo'
}

I don't like errors so I avoid them at all costs.

Dynamically load a JavaScript file

i've used yet another solution i found on the net ... this one is under creativecommons and it checks if the source was included prior to calling the function ...

you can find the file here: include.js

/** include - including .js files from JS - [email protected] - 2005-02-09
 ** Code licensed under Creative Commons Attribution-ShareAlike License 
 ** http://creativecommons.org/licenses/by-sa/2.0/
 **/              
var hIncludes = null;
function include(sURI)
{   
  if (document.getElementsByTagName)
  {   
    if (!hIncludes)
    {
      hIncludes = {}; 
      var cScripts = document.getElementsByTagName("script");
      for (var i=0,len=cScripts.length; i < len; i++)
        if (cScripts[i].src) hIncludes[cScripts[i].src] = true;
    }
    if (!hIncludes[sURI])
    {
      var oNew = document.createElement("script");
      oNew.type = "text/javascript";
      oNew.src = sURI;
      hIncludes[sURI]=true;
      document.getElementsByTagName("head")[0].appendChild(oNew);
    }
  }   
} 

Nginx: stat() failed (13: permission denied)

By default the static data, when you install the nginx, will be in /var/www/html. So you can just copy your static folder into /var/html/ and set the

root /var/www/<your static folder>

in ngix.conf (or /etc/nginx/sites-available/default)

This worked for me on ubuntu but I guess it should not be much different for other distros.

Hope it helps.

How do I dump the data of some SQLite3 tables?

Not the best way, but at lease does not need external tools (except grep, which is standard on *nix boxes anyway)

sqlite3 database.db3 .dump | grep '^INSERT INTO "tablename"'

but you do need to do this command for each table you are looking for though.

Note that this does not include schema.

Proper way to empty a C-String

I'm a beginner but...Up to my knowledge,the best way is

strncpy(dest_string,"",strlen(dest_string));

How to remove duplicate white spaces in string using Java?

Like this:

yourString = yourString.replaceAll("\\s+", " ");

For example

System.out.println("lorem  ipsum   dolor \n sit.".replaceAll("\\s+", " "));

outputs

lorem ipsum dolor sit.

What does that \s+ mean?

\s+ is a regular expression. \s matches a space, tab, new line, carriage return, form feed or vertical tab, and + says "one or more of those". Thus the above code will collapse all "whitespace substrings" longer than one character, with a single space character.


Source: Java: Removing duplicate white spaces in strings

Random Number Between 2 Double Numbers

Watch out: if you're generating the random inside a loop like for example for(int i = 0; i < 10; i++), do not put the new Random() declaration inside the loop.

From MSDN:

The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value...

So based on this fact, do something as:

var random = new Random();

for(int d = 0; d < 7; d++)
{
    // Actual BOE
    boes.Add(new LogBOEViewModel()
    {
        LogDate = criteriaDate,
        BOEActual = GetRandomDouble(random, 100, 1000),
        BOEForecast = GetRandomDouble(random, 100, 1000)
    });
}

double GetRandomDouble(Random random, double min, double max)
{
     return min + (random.NextDouble() * (max - min));
}

Doing this way you have the guarantee you'll get different double values.

get current page from url

Try this:

path.Substring(path.LastIndexOf("/");

How to modify existing XML file with XmlDocument and XmlNode in C#

You need to do something like this:

// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");

// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");

// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
   // grab the "id" attribute
   XmlAttribute idAttribute = aNode.Attributes["id"];

   // check if that attribute even exists...
   if (idAttribute != null)
   {
      // if yes - read its current value
      string currentValue = idAttribute.Value;

      // here, you can now decide what to do - for demo purposes,
      // I just set the ID value to a fixed value if it was empty before
      if (string.IsNullOrEmpty(currentValue))
      {
         idAttribute.Value = "515";
      }
   }
}

// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");

SVN check out linux

You can use checkout or co

$ svn co http://example.com/svn/app-name directory-name

Some short codes:-

  1. checkout (co)
  2. commit (ci)
  3. copy (cp)
  4. delete (del, remove,rm)
  5. diff (di)

Using Excel as front end to Access database (with VBA)

To connect Excel to Access using VBA is very useful I use it in my profession everyday. The connection string I use is according to the program found in the link below. The program can be automated to do multiple connections or tasks in on shot but the basic connection code looks the same. Good luck!

http://vbaexcel.eu/vba-macro-code/database-connection-retrieve-data-from-database-querying-data-into-excel-using-vba-dao

How can I generate a 6 digit unique number?

Here's another one:

substr(number_format(time() * rand(),0,'',''),0,6);

m2e lifecycle-mapping not found

Suprisingly these 3 steps helped me:

mvn clean
mvn package
mvn spring-boot:run

Meaning of @classmethod and @staticmethod for beginner?

In short, @classmethod turns a normal method to a factory method.

Let's explore it with an example:

class PythonBook:
    def __init__(self, name, author):
        self.name = name
        self.author = author
    def __repr__(self):
        return f'Book: {self.name}, Author: {self.author}'

Without a @classmethod,you should labor to create instances one by one and they are scattered.

book1 = PythonBook('Learning Python', 'Mark Lutz')
In [20]: book1
Out[20]: Book: Learning Python, Author: Mark Lutz
book2 = PythonBook('Python Think', 'Allen B Dowey')
In [22]: book2
Out[22]: Book: Python Think, Author: Allen B Dowey

As for example with @classmethod

class PythonBook:
    def __init__(self, name, author):
        self.name = name
        self.author = author
    def __repr__(self):
        return f'Book: {self.name}, Author: {self.author}'
    @classmethod
    def book1(cls):
        return cls('Learning Python', 'Mark Lutz')
    @classmethod
    def book2(cls):
        return cls('Python Think', 'Allen B Dowey')

Test it:

In [31]: PythonBook.book1()
Out[31]: Book: Learning Python, Author: Mark Lutz
In [32]: PythonBook.book2()
Out[32]: Book: Python Think, Author: Allen B Dowey

See? Instances are successfully created inside a class definition and they are collected together.

In conclusion, @classmethod decorator convert a conventional method to a factory method,Using classmethods makes it possible to add as many alternative constructors as necessary.

ISO time (ISO 8601) in Python

I agree with Jarek, and I furthermore note that the ISO offset separator character is a colon, so I think the final answer should be:

isodate.datetime_isoformat(datetime.datetime.now()) + str.format('{0:+06.2f}', -float(time.timezone) / 3600).replace('.', ':')

Split string into array of character strings

An efficient way of turning a String into an array of one-character Strings would be to do this:

String[] res = new String[str.length()];
for (int i = 0; i < str.length(); i++) {
    res[i] = Character.toString(str.charAt(i));
}

However, this does not take account of the fact that a char in a String could actually represent half of a Unicode code-point. (If the code-point is not in the BMP.) To deal with that you need to iterate through the code points ... which is more complicated.

This approach will be faster than using String.split(/* clever regex*/), and it will probably be faster than using Java 8+ streams. It is probable faster than this:

String[] res = new String[str.length()];
int 0 = 0;
for (char ch: str.toCharArray[]) {
    res[i++] = Character.toString(ch);
}  

because toCharArray has to copy the characters to a new array.

Content Security Policy "data" not working for base64 Images in Chrome 28

Try this

data to load:

<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'><path fill='#343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/></svg>

get a utf8 to base64 convertor and convert the "svg" string to:

PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=

and the CSP is

img-src data: image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=

Call child component method from parent class - Angular

user6779899's answer is neat and more generic However, based on the request by Imad El Hitti, a light weight solution is proposed here. This can be used when a child component is tightly connected to one parent only.

Parent.component.ts

export class Notifier {
    valueChanged: (data: number) => void = (d: number) => { };
}

export class Parent {
    notifyObj = new Notifier();
    tellChild(newValue: number) {
        this.notifyObj.valueChanged(newValue); // inform child
    }
}

Parent.component.html

<my-child-comp [notify]="notifyObj"></my-child-comp>

Child.component.ts

export class ChildComp implements OnInit{
    @Input() notify = new Notifier(); // create object to satisfy typescript
    ngOnInit(){
      this.notify.valueChanged = (d: number) => {
            console.log(`Parent has notified changes to ${d}`);
            // do something with the new value 
        };
    }
 }

How to Copy Contents of One Canvas to Another Canvas Locally

Actually you don't have to create an image at all. drawImage() will accept a Canvas as well as an Image object.

//grab the context from your destination canvas
var destCtx = destinationCanvas.getContext('2d');

//call its drawImage() function passing it the source canvas directly
destCtx.drawImage(sourceCanvas, 0, 0);

Way faster than using an ImageData object or Image element.

Note that sourceCanvas can be a HTMLImageElement, HTMLVideoElement, or a HTMLCanvasElement. As mentioned by Dave in a comment below this answer, you cannot use a canvas drawing context as your source. If you have a canvas drawing context instead of the canvas element it was created from, there is a reference to the original canvas element on the context under context.canvas.

Here is a jsPerf to demonstrate why this is the only right way to clone a canvas: http://jsperf.com/copying-a-canvas-element

Android: How to stretch an image to the screen width while maintaining aspect ratio?

In the end, I generated the dimensions manually, which works great:

DisplayMetrics dm = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = width * mainImage.getHeight() / mainImage.getWidth(); //mainImage is the Bitmap I'm drawing
addView(mainImageView,new LinearLayout.LayoutParams( 
        width, height));

Find all files with name containing string

grep -R "somestring" | cut -d ":" -f 1

Exception 'open failed: EACCES (Permission denied)' on Android

Solution for Android Q:

<application ...
    android:requestLegacyExternalStorage="true" ... >

How do I resolve a TesseractNotFoundError?

I'm running on a Mac OS and installed tesseract with brew so here's my take on this. Since pytesseract is just how you can access tesseract from python, you have to specify where tesseract is already on your computer.

For Mac OS

Try finding where the tesseract.exe is- if you installed it using brew, on your the terminal use:

>brew list tesseract

This should list where your tesseract.exe is, somewhere more or less like

> /usr/local/Cellar/tesseract/3.05.02/bin/tesseract

Then following their instructions:

pytesseract.pytesseract.tesseract_cmd = r'<full_path_to_your_tesseract_executable>'

pytesseract.pytesseract.tesseract_cmd = r'/usr/local/Cellar/tesseract/3.05.02/bin/tesseract'

should do the trick!

Android: how to make keyboard enter button say "Search" and handle its click?

This answer is for TextInputEditText :

In the layout XML file set your input method options to your required type. for example done.

<com.google.android.material.textfield.TextInputLayout
        android:id="@+id/textInputLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:imeOptions="actionGo"/>

</com.google.android.material.textfield.TextInputLayout>

Similarly, you can also set imeOptions to actionSubmit, actionSearch, etc

In the java add the editor action listener.

TextInputLayout textInputLayout = findViewById(R.id.textInputLayout);

textInputLayout.getEditText().setOnEditorActionListener(new 

    TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_GO) {
                performYourAction();
                return true;
            }
            return false;
        }
    });

If you're using kotlin :

textInputLayout.editText.setOnEditorActionListener { _, actionId, _ ->
    if (actionId == EditorInfo.IME_ACTION_GO) {
        performYourAction()
    }
    true
}

String to decimal conversion: dot separation instead of comma

I had faced the similar issue while using Convert.ToSingle(my_value) If the OS language settings is English 2.5 (example) will be taken as 2.5 If the OS language is German, 2.5 will be treated as 2,5 which is 25 I used the invariantculture IFormat provided and it works. It always treats '.' as '.' instead of ',' irrespective of the system language.

float var = Convert.ToSingle(my_value, System.Globalization.CultureInfo.InvariantCulture);

Serial Port (RS -232) Connection in C++

For the answer above, the default serial port is

        serialParams.BaudRate = 9600;
        serialParams.ByteSize = 8;
        serialParams.StopBits = TWOSTOPBITS;
        serialParams.Parity = NOPARITY;

Document Root PHP

<a href="<?php echo $_SERVER['DOCUMENT_ROOT'].'/hello.html'; ?>">go with php</a>
    <br />
<a href="/hello.html">go to with html</a>

Try this yourself and find that they are not exactly the same.

$_SERVER['DOCUMENT_ROOT'] renders an actual file path (on my computer running as it's own server, C:/wamp/www/

HTML's / renders the root of the server url, in my case, localhost/

But C:/wamp/www/hello.html and localhost/hello.html are in fact the same file

Tool to Unminify / Decompress JavaScript

In Firefox, SpiderMonkey and Rhino you can wrap any code into an anonymous function and call its toSource method, which will give you a nicely formatted source of the function.

toSource also strips comments.

E. g.:

(function () { /* Say hello. */ var x = 'Hello!'; print(x); }).toSource()

Will be converted to a string:

function () {
    var x = "Hello!";
    print(x);
}

P. S.: It's not an "online tool", but all questions about general beautifying techniques are closed as duplicates of this one.

Java - Opposite of .contains (does not contain)

It seems that Luiggi Mendoza and joey rohan both already answered this, but I think it can be clarified a little.

You can write it as a single if statement:

if (inventory.contains("bread") && !inventory.contains("water")) {
    // do something
}

How to fix: "HAX is not working and emulator runs in emulation mode"

Download HAXM from SDK Manager

Open your SDK Manager from Android Studio, click the icon shown in the screen shot.

enter image description here

Click on "Launch Standalone SDK Manager" on the "Default Settings" Dialog.

enter image description here

Check node "Extras > Intel x86 Emulator Accelerator (HAXM installer)" and proceed with HAXM download.

enter image description here

Installing or Modifying HAXM

You can now access with installation (or modifying existing installtino) of HAXM by accessing the download location. Enter this path in "run"

%localappdata%\Android\sdk\extras\intel\Hardware_Accelerated_Execution_Manager

and double click the file "intelhaxm-android.exe"

You can increase the size of memory allocated to HAXM while modifying existing HAXM install. I have a machine with 32 GB of RAM and would like to launch multiple AVDs at same time (for automated testing etc.) so I have allocated 8 GB to HAXM.

Caveat

If you are running one AVD of one 1 GB and allocated 2 GB to HAXM, you cannot run another AVD with RAM more than 1 GB. Please make sure that Android Device Monitor is not running when you are modifying or installing HAXM (just to avoid any suprises).

enter image description here

These steps are tested on Windows platform, but generally could be applied to other platforms too with slight modification.

How to put more than 1000 values into an Oracle IN clause

Use ...from table(... :

create or replace type numbertype
as object
(nr number(20,10) )
/ 

create or replace type number_table
as table of numbertype
/ 

create or replace procedure tableselect
( p_numbers in number_table
, p_ref_result out sys_refcursor)
is
begin
  open p_ref_result for
    select *
    from employees , (select /*+ cardinality(tab 10) */ tab.nr from table(p_numbers) tab) tbnrs 
    where id = tbnrs.nr; 
end; 
/ 

This is one of the rare cases where you need a hint, else Oracle will not use the index on column id. One of the advantages of this approach is that Oracle doesn't need to hard parse the query again and again. Using a temporary table is most of the times slower.

edit 1 simplified the procedure (thanks to jimmyorr) + example

create or replace procedure tableselect
( p_numbers in number_table
, p_ref_result out sys_refcursor)
is
begin
  open p_ref_result for
    select /*+ cardinality(tab 10) */ emp.*
    from  employees emp
    ,     table(p_numbers) tab
    where tab.nr = id;
end;
/

Example:

set serveroutput on 

create table employees ( id number(10),name varchar2(100));
insert into employees values (3,'Raymond');
insert into employees values (4,'Hans');
commit;

declare
  l_number number_table := number_table();
  l_sys_refcursor sys_refcursor;
  l_employee employees%rowtype;
begin
  l_number.extend;
  l_number(1) := numbertype(3);
  l_number.extend;
  l_number(2) := numbertype(4);
  tableselect(l_number, l_sys_refcursor);
  loop
    fetch l_sys_refcursor into l_employee;
    exit when l_sys_refcursor%notfound;
    dbms_output.put_line(l_employee.name);
  end loop;
  close l_sys_refcursor;
end;
/

This will output:

Raymond
Hans

How to create a global variable?

From the official Swift programming guide:

Global variables are variables that are defined outside of any function, method, closure, or type context. Global constants and variables are always computed lazily.

You can define it in any file and can access it in current module anywhere. So you can define it somewhere in the file outside of any scope. There is no need for static and all global variables are computed lazily.

 var yourVariable = "someString"

You can access this from anywhere in the current module.

However you should avoid this as Global variables are not good for application state and mainly reason of bugs.

As shown in this answer, in Swift you can encapsulate them in struct and can access anywhere. You can define static variables or constant in Swift also. Encapsulate in struct

struct MyVariables {
    static var yourVariable = "someString"
}

You can use this variable in any class or anywhere

let string = MyVariables.yourVariable
println("Global variable:\(string)")

//Changing value of it
MyVariables.yourVariable = "anotherString"

Getting query parameters from react-router hash fragment

OLD (pre v4):

Writing in es6 and using react 0.14.6 / react-router 2.0.0-rc5. I use this command to lookup the query params in my components:

this.props.location.query

It creates a hash of all available query params in the url.

UPDATE (React Router v4+):

this.props.location.query in React Router 4 has been removed (currently using v4.1.1) more about the issue here: https://github.com/ReactTraining/react-router/issues/4410

Looks like they want you to use your own method to parse the query params, currently using this library to fill the gap: https://github.com/sindresorhus/query-string

Maximum length of the textual representation of an IPv6 address?

I think @Deepak answer in this link is more close to correct answer. Max length for client ip address. So correct size is 45 not 39. Sometimes we try to scrounge in fields size but it seems to better if we prepare enough storage size.

How to use basic authorization in PHP curl

Can you try this,

 $ch = curl_init($url);
 ...
 curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);  
 ...

REF: http://php.net/manual/en/function.curl-setopt.php

Error: Address already in use while binding socket with address but the port number is shown free by `netstat`

As already said, your socket probably enter in TIME_WAIT state. This issue is well described by Thomas A. Fine here.

To summary, socket closing process follow diagram below:

Socket closing process

Thomas says:

Looking at the diagram above, it is clear that TIME_WAIT can be avoided if the remote end initiates the closure. So the server can avoid problems by letting the client close first. The application protocol must be designed so that the client knows when to close. The server can safely close in response to an EOF from the client, however it will also need to set a timeout when it is expecting an EOF in case the client has left the network ungracefully. In many cases simply waiting a few seconds before the server closes will be adequate.

Using SO_REUSEADDR is commonly suggested on internet, but Thomas add:

Oddly, using SO_REUSEADDR can actually lead to more difficult "address already in use" errors. SO_REUSADDR permits you to use a port that is stuck in TIME_WAIT, but you still can not use that port to establish a connection to the last place it connected to. What? Suppose I pick local port 1010, and connect to foobar.com port 300, and then close locally, leaving that port in TIME_WAIT. I can reuse local port 1010 right away to connect to anywhere except for foobar.com port 300.

All inclusive Charset to avoid "java.nio.charset.MalformedInputException: Input length = 1"?

try this.. i had the same issue, below implementation worked for me

Reader reader = Files.newBufferedReader(Paths.get(<yourfilewithpath>), StandardCharsets.ISO_8859_1);

then use Reader where ever you want.

foreg:

CsvToBean<anyPojo> csvToBean = null;
    try {
        Reader reader = Files.newBufferedReader(Paths.get(csvFilePath), 
                        StandardCharsets.ISO_8859_1);
        csvToBean = new CsvToBeanBuilder(reader)
                .withType(anyPojo.class)
                .withIgnoreLeadingWhiteSpace(true)
                .withSkipLines(1)
                .build();

    } catch (IOException e) {
        e.printStackTrace();
    }

Querying date field in MongoDB with Mongoose

{ "date" : "1000000" } in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }

It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback) and if that works, you have a typing issue.

Cannot drop database because it is currently in use

I wanted to call out that I used a script that is derived from two of the answers below.

Props to @Hitesh Mistry and @unruledboy

DECLARE @DatabaseName nvarchar(50)
SET @DatabaseName = N'[[[DatabaseName]]]'

DECLARE @SQL varchar(max)

SELECT @SQL = COALESCE(@SQL,'') + 'Kill ' + Convert(varchar, SPId) + ';'
FROM MASTER..SysProcesses
WHERE DBId = DB_ID(@DatabaseName) AND SPId <> @@SPId

EXEC(@SQL)

alter database [[[DatabaseName]]] set single_user with rollback immediate

DROP DATABASE [[[DatabaseName]]]

Connect to Oracle DB using sqlplus

Different ways to connect Oracle Database from Unix user are:

[oracle@OLE1 ~]$ sqlplus scott/tiger

[oracle@OLE1 ~]$ sqlplus scott/tiger@orcl

[oracle@OLE1 ~]$ sqlplus scott/[email protected]:1521/orcl

[oracle@OLE1 ~]$ sqlplus scott/tiger@//192.168.244.128:1521/orcl

[oracle@OLE1 ~]$ sqlplus "scott/tiger@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=ole1)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=orcl)))"

Please see the explanation at link: https://stackoverflow.com/a/45064809/6332029

Thanks!

Equivalent of typedef in C#

I think there is no typedef. You could only define a specific delegate type instead of the generic one in the GenericClass, i.e.

public delegate GenericHandler EventHandler<EventData>

This would make it shorter. But what about the following suggestion:

Use Visual Studio. This way, when you typed

gcInt.MyEvent += 

it already provides the complete event handler signature from Intellisense. Press TAB and it's there. Accept the generated handler name or change it, and then press TAB again to auto-generate the handler stub.

How to create a TextArea in Android

Defining an Android Mulitline EditText Field is done via the inputType=”textMultiline”. Unfortunately the text looks strangely aligned. To solve that also use the gravity=”left|top” attribute.

<EditText
   android:id="@+id/editText1"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:ems="10"
   android:gravity="left|top"
   android:inputType="textMultiLine" >

   <requestFocus />

check this vogella blog

OpenVPN failed connection / All TAP-Win32 adapters on this system are currently in use

I found a solution to this. It's bloody witchcraft, but it works.

When you install the client, open Control Panel > Network Connections.

You'll see a disabled network connection that was added by the TAP installer (Local Area Connection 3 or some such).

Right Click it, click Enable.

The device will not reset itself to enabled, but that's ok; try connecting w/ the client again. It'll work.

Is #pragma once a safe include guard?

The performance benefit is from not having to reopen the file once the #pragma once have been read. With guards, the compiler have to open the file (that can be costly in time) to get the information that it shouldn't include it's content again.

That is theory only because some compilers will automatically not open files that didn't have any read code in, for each compilation unit.

Anyway, it's not the case for all compilers, so ideally #pragma once have to be avoided for cross-platform code has it's not standard at all / have no standardized definition and effect. However, practically, it's really better than guards.

In the end, the better suggestion you can get to be sure to have the best speed from your compiler without having to check the behavior of each compiler in this case, is to use both pragma once and guards.

#ifndef NR_TEST_H
#define NR_TEST_H
#pragma once

#include "Thing.h"

namespace MyApp
{
 // ...
}

#endif

That way you get the best of both (cross-platform and help compilation speed).

As it's longer to type, I personally use a tool to help generate all that in a very wick way (Visual Assist X).

"Logging out" of phpMyAdmin?

This happens because the current account you have used to log in probably has very limited priviledges.

To fix this problem, you can change your the AllowNoPassword config setting to false in config.inc.php. You may also force the authentication to use the config file and specify the default username and password .

$cfg['Servers'][$i]['AllowNoPassword'] = false;
$cfg['Servers'][$i]['auth_type'] = 'config';

$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = ''; // leave blank if no password

After this, the PhPMyAdmin login page should show up when you refresh the page. You can then log in with the default root password.

More details can be found on this post ..

How to calculate md5 hash of a file using javascript

I've made a library that implements incremental md5 in order to hash large files efficiently. Basically you read a file in chunks (to keep memory low) and hash it incrementally. You got basic usage and examples in the readme.

Be aware that you need HTML5 FileAPI, so be sure to check for it. There is a full example in the test folder.

https://github.com/satazor/SparkMD5

Use sudo with password as parameter

You can set the s bit for your script so that it does not need sudo and runs as root (and you do not need to write your root password in the script):

sudo chmod +s myscript

Save the console.log in Chrome to a file

the other solutions in this thread weren't working on my mac. Here's a logger that saves a string representation intermittently using ajax. use it with console.save instead of console.log

var logFileString="";
var maxLogLength=1024*128;

console.save=function(){
  var logArgs={};

  for(var i=0; i<arguments.length; i++) logArgs['arg'+i]=arguments[i];
  console.log(logArgs);

  // keep a string representation of every log
  logFileString+=JSON.stringify(logArgs,null,2)+'\n';

  // save the string representation when it gets big
  if(logFileString.length>maxLogLength){
    // send a copy in case race conditions change it mid-save
    saveLog(logFileString);
    logFileString="";
  }
};

depending on what you need, you can save that string or just console.log it and copy and paste. here's an ajax for you in case you want to save it:

function saveLog(data){
  // do some ajax stuff with data.
  var xhttp = new XMLHttpRequest();

  xhttp.onreadystatechange = function(){
    if (this.readyState == 4 && this.status == 200) {}
  }

  xhttp.open("POST", 'saveLog.php', true);
  xhttp.send(data);
}

the saveLog.php should append the data to a log file somewhere. I didn't need that part so I'm not including it here. :)

https://www.google.com/search?q=php+append+to+log

How to remove leading and trailing whitespace in a MySQL field?

Please understand the use case before using this solution:

trim does not work while doing select query

This works

select replace(name , ' ','') from test;

While this doesn't

select trim(name) from test;

Can you append strings to variables in PHP?

PHP syntax is little different in case of concatenation from JavaScript. Instead of (+) plus a (.) period is used for string concatenation.

<?php

$selectBox = '<select name="number">';
for ($i=1;$i<=100;$i++)
{
    $selectBox += '<option value="' . $i . '">' . $i . '</option>'; // <-- (Wrong) Replace + with .
    $selectBox .= '<option value="' . $i . '">' . $i . '</option>'; // <-- (Correct) Here + is replaced .
}
$selectBox += '</select>'; // <-- (Wrong) Replace + with .
$selectBox .= '</select>'; // <-- (Correct) Here + is replaced .
echo $selectBox;

?>

Java 8 method references: provide a Supplier capable of supplying a parameterized result

It appears that you can throw only RuntimeException from the method orElseThrow. Otherwise you will get an error message like MyException cannot be converted to java.lang.RuntimeException

Update:- This was an issue with an older version of JDK. I don't see this issue with the latest versions.

Find where python is installed (if it isn't default dir)

On windows search python,then right click and click on "Open file location".That's how I did

iterating through json object javascript

You use a for..in loop for this. Be sure to check if the object owns the properties or all inherited properties are shown as well. An example is like this:

var obj = {a: 1, b: 2};
for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    var val = obj[key];
    console.log(val);
  }
}

Or if you need recursion to walk through all the properties:

var obj = {a: 1, b: 2, c: {a: 1, b: 2}};
function walk(obj) {
  for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
      var val = obj[key];
      console.log(val);
      walk(val);
    }
  }
}
walk(obj);

Force update of an Android app when a new version is available

You shouldn't stop supporting an older version as soon as a new version comes out. This will result in a terrible user experience. I don't know of any software vendor in existence that does this, for good reason.

What happens if the user can't update or doesn't want to at that time? They simply can't use your app, which is bad.

Google don't provide any option for version tracking like that so you would have to roll your own. A simple web service to return the current live version that your app can check would be sufficient. You can then update the version and the app will know it is outdated. I would only recommend using this to let your users know there is an update more quickly than depending on Google Play. It should not really be used to prevent the app from working, just to prompt the user to update.

Pick a random value from an enum?

A single method is all you need for all your random enums:

    public static <T extends Enum<?>> T randomEnum(Class<T> clazz){
        int x = random.nextInt(clazz.getEnumConstants().length);
        return clazz.getEnumConstants()[x];
    }

Which you'll use:

randomEnum(MyEnum.class);

I also prefer to use SecureRandom as:

private static final SecureRandom random = new SecureRandom();

How to keep Docker container running after starting services?

I just had the same problem and I found out that if you are running your container with the -t and -d flag, it keeps running.

docker run -td <image>

Here is what the flags do (according to docker run --help):

-d, --detach=false         Run container in background and print container ID
-t, --tty=false            Allocate a pseudo-TTY

The most important one is the -t flag. -d just lets you run the container in the background.

Strip out HTML and Special Characters

Strip out tags, leave only alphanumeric characters and space:

$clear = preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags($des));

Edit: all credit to DaveRandom for the perfect solution...

$clear = preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags(html_entity_decode($des)));

How to find out which JavaScript events fired?

Regarding Chrome, checkout the monitorEvents() via the command line API.

  • Open the console via Menu > Tools > JavaScript Console.

  • Enter monitorEvents(window);

  • View the console flooded with events

     ...
     mousemove MouseEvent {dataTransfer: ...}
     mouseout MouseEvent {dataTransfer: ...}
     mouseover MouseEvent {dataTransfer: ...}
     change Event {clipboardData: ...}
     ...
    

There are other examples in the documentation. I'm guessing this feature was added after the previous answer.

Share link on Google+

<meta property="og:title" content="Ali Umair"/>
<meta property="og:description" content="Ali UMair is a web developer"/><meta property="og:image" content="../image" />

<a target="_blank" href="https://plus.google.com/share?url=<? echo urlencode('http://www..'); ?>"><img src="../gplus-black_icon.png" alt="" /></a>

this code will work with image text and description please put meta into head tag

Implement Stack using Two Queues

The easiest (and maybe only) way of doing this is by pushing new elements into the empty queue, and then dequeuing the other and enqeuing into the previously empty queue. With this way the latest is always at the front of the queue. This would be version B, for version A you just reverse the process by dequeuing the elements into the second queue except for the last one.

Step 0:

"Stack"
+---+---+---+---+---+
|   |   |   |   |   |
+---+---+---+---+---+

Queue A                Queue B
+---+---+---+---+---+  +---+---+---+---+---+
|   |   |   |   |   |  |   |   |   |   |   |
+---+---+---+---+---+  +---+---+---+---+---+

Step 1:

"Stack"
+---+---+---+---+---+
| 1 |   |   |   |   |
+---+---+---+---+---+

Queue A                Queue B
+---+---+---+---+---+  +---+---+---+---+---+
| 1 |   |   |   |   |  |   |   |   |   |   |
+---+---+---+---+---+  +---+---+---+---+---+

Step 2:

"Stack"
+---+---+---+---+---+
| 2 | 1 |   |   |   |
+---+---+---+---+---+

Queue A                Queue B
+---+---+---+---+---+  +---+---+---+---+---+
|   |   |   |   |   |  | 2 | 1 |   |   |   |
+---+---+---+---+---+  +---+---+---+---+---+

Step 3:

"Stack"
+---+---+---+---+---+
| 3 | 2 | 1 |   |   |
+---+---+---+---+---+

Queue A                Queue B
+---+---+---+---+---+  +---+---+---+---+---+
| 3 | 2 | 1 |   |   |  |   |   |   |   |   |
+---+---+---+---+---+  +---+---+---+---+---+

How to format html table with inline styles to look like a rendered Excel table?

Add cellpadding and cellspacing to solve it. Edit: Also removed double pixel border.

<style>
td
{border-left:1px solid black;
border-top:1px solid black;}
table
{border-right:1px solid black;
border-bottom:1px solid black;}
</style>
<html>
    <body>
        <table cellpadding="0" cellspacing="0">
            <tr>
                <td width="350" >
                    Foo
                </td>
                <td width="80" >
                    Foo1
                </td>
                <td width="65" >
                    Foo2
                </td>
            </tr>
            <tr>
                <td>
                    Bar1
                </td>
                <td>
                    Bar2
                </td>
                <td>
                    Bar3
                </td>
            </tr>
            <tr >
                <td>
                    Bar1
                </td>
                <td>
                    Bar2
                </td>
                <td>
                    Bar3
                </td>
            </tr>
        </table>
    </body>
</html>

Remove non-numeric characters (except periods and commas) from a string

You could use preg_replace to swap out all non-numeric characters and the comma and period/full stop as follows:

$testString = '12.322,11T';
echo preg_replace('/[^0-9,.]+/', '', $testString);

The pattern can also be expressed as /[^\d,.]+/

How do you specify a debugger program in Code::Blocks 12.11?

Download codeblocks-13.12mingw-setup.exe instead of codeblocks-13.12setup.exe from the official site. Here 13.12 is the latest version so far.

Timestamp with a millisecond precision: How to save them in MySQL

You need to be at MySQL version 5.6.4 or later to declare columns with fractional-second time datatypes. Not sure you have the right version? Try SELECT NOW(3). If you get an error, you don't have the right version.

For example, DATETIME(3) will give you millisecond resolution in your timestamps, and TIMESTAMP(6) will give you microsecond resolution on a *nix-style timestamp.

Read this: https://dev.mysql.com/doc/refman/8.0/en/fractional-seconds.html

NOW(3) will give you the present time from your MySQL server's operating system with millisecond precision.

If you have a number of milliseconds since the Unix epoch, try this to get a DATETIME(3) value

FROM_UNIXTIME(ms * 0.001)

Javascript timestamps, for example, are represented in milliseconds since the Unix epoch.

(Notice that MySQL internal fractional arithmetic, like * 0.001, is always handled as IEEE754 double precision floating point, so it's unlikely you'll lose precision before the Sun becomes a white dwarf star.)

If you're using an older version of MySQL and you need subsecond time precision, your best path is to upgrade. Anything else will force you into doing messy workarounds.

If, for some reason you can't upgrade, you could consider using BIGINT or DOUBLE columns to store Javascript timestamps as if they were numbers. FROM_UNIXTIME(col * 0.001) will still work OK. If you need the current time to store in such a column, you could use UNIX_TIMESTAMP() * 1000

Update multiple tables in SQL Server using INNER JOIN

You can update with a join if you only affect one table like this:

UPDATE table1 
SET table1.name = table2.name 
FROM table1, table2 
WHERE table1.id = table2.id 
AND table2.foobar ='stuff'

But you are trying to affect multiple tables with an update statement that joins on multiple tables. That is not possible.

However, updating two tables in one statement is actually possible but will need to create a View using a UNION that contains both the tables you want to update. You can then update the View which will then update the underlying tables.

SQL JOINS

But this is a really hacky parlor trick, use the transaction and multiple updates, it's much more intuitive.

How to view UTF-8 Characters in VIM or Gvim

On Microsoft Windows, gvim wouldn't allow you to select non-monospaced fonts. Unfortunately Latha is a non-monospaced font.

There is a hack way to make it happen: Using FontForge (you can download Windows binary from http://www.geocities.jp/meir000/fontforge/) to edit the Latha.ttf and mark it as a monospaced font. Doing like this:

  1. Load fontforge, select latha.ttf.
  2. Menu: Element -> Font Info
  3. Select "OS/2" from left-hand list on Font Info dialog
  4. Select "Panose" tab
  5. Set Proportion = Monospaced
  6. Save new TTF version of this font, try it out!

Good luck!

Seaborn plots not showing up

This worked for me

import matplotlib.pyplot as plt
import seaborn as sns
.
.
.
plt.show(sns)

Eclipse Intellisense?

I once had the same problem, and then I searched and found this and it worked for me:

I had got some of the boxes unchecked, so I checked them again, then it worked. Just go to

Windows > Preferences > Java > Editor > Content Assist > Advanced

and check the boxes which you want .

Unique Key constraints for multiple columns in Entity Framework

I found three ways to solve the problem.

Unique indexes in EntityFramework Core:

First approach:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   modelBuilder.Entity<Entity>()
   .HasIndex(p => new {p.FirstColumn , p.SecondColumn}).IsUnique();
}

The second approach to create Unique Constraints with EF Core by using Alternate Keys.

Examples

One column:

modelBuilder.Entity<Blog>().HasAlternateKey(c => c.SecondColumn).HasName("IX_SingeColumn");

Multiple columns:

modelBuilder.Entity<Entity>().HasAlternateKey(c => new [] {c.FirstColumn, c.SecondColumn}).HasName("IX_MultipleColumns");

EF 6 and below:


First approach:

dbContext.Database.ExecuteSqlCommand(string.Format(
                        @"CREATE UNIQUE INDEX LX_{0} ON {0} ({1})", 
                                 "Entitys", "FirstColumn, SecondColumn"));

This approach is very fast and useful but the main problem is that Entity Framework doesn't know anything about those changes!


Second approach:
I found it in this post but I did not tried by myself.

CreateIndex("Entitys", new string[2] { "FirstColumn", "SecondColumn" },
              true, "IX_Entitys");

The problem of this approach is the following: It needs DbMigration so what do you do if you don't have it?


Third approach:
I think this is the best one but it requires some time to do it. I will just show you the idea behind it: In this link http://code.msdn.microsoft.com/CSASPNETUniqueConstraintInE-d357224a you can find the code for unique key data annotation:

[UniqueKey] // Unique Key 
public int FirstColumn  { get; set;}
[UniqueKey] // Unique Key 
public int SecondColumn  { get; set;}

// The problem hier
1, 1  = OK 
1 ,2  = NO OK 1 IS UNIQUE

The problem for this approach; How can I combine them? I have an idea to extend this Microsoft implementation for example:

[UniqueKey, 1] // Unique Key 
public int FirstColumn  { get; set;}
[UniqueKey ,1] // Unique Key 
public int SecondColumn  { get; set;}

Later in the IDatabaseInitializer as described in the Microsoft example you can combine the keys according to the given integer. One thing has to be noted though: If the unique property is of type string then you have to set the MaxLength.

What does %~dp0 mean, and how does it work?

Another tip that would help a lot is that to set the current directory to a different drive one would have to use %~d0 first, then cd %~dp0. This will change the directory to the batch file's drive, then change to its folder.

Alternatively, for #oneLinerLovers, as @Omni pointed out in the comments cd /d %~dp0 will change both the drive and directory :)

Hope this helps someone.

How do I view cookies in Internet Explorer 11 using Developer Tools

Sorry to break the news to ya, but there is no way to do this in IE11. I have been troubling with this for some time, but I finally had to see it as a lost course, and just navigate to the files manually.

But where are the files? That depends on a lot of things, I have found them these places on different machines:

In the the Internet Explorer cache.

This can be done via "run" (Windows+r) and then typing in shell:cache or by navigating to it through the internet options in IE11 (AskLeo has a fine guide to this, I'm not affiliated in any way).

  • Click on the gear icon, then Internet options.
  • In the General tab, underneath “Browsing history”, click on Settings.
  • In the resulting “Website Data” dialog, click on View files.
  • This will open the folder we’re interested in: your Internet Explorer cache.

Make a search for "cookie" to see the cookies only

In the Cookies folder

The path for cookies can be found here via regedit:

HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Cookies

Common path (in 7 & 8)

%APPDATA%\Microsoft\Windows\Cookies

%APPDATA%\Microsoft\Windows\Cookies\Low

Common path (Win 10)

shell:cookies

shell:cookies\low

%userprofile%\AppData\Local\Microsoft\Windows\INetCookies

%userprofile%\AppData\Local\Microsoft\Windows\INetCookies\Low

How can I fix assembly version conflicts with JSON.NET after updating NuGet package references in a new ASP.NET MVC 5 project?

Remember that with the binding redirection

oldVersion="0.0.0.0-6.0.0.0"

You are saying that the old versions of the dll are between version 0.0.0.0 and version 6.0.0.0.

AngularJS: ng-model not binding to ng-checked for checkboxes

You don't need ng-checked when you use ng-model. If you're performing CRUD on your HTML Form, just create a model for CREATE mode that is consistent with your EDIT mode during the data-binding:

CREATE Mode: Model with default values only

$scope.dataModel = {
   isItemSelected: true,
   isApproved: true,
   somethingElse: "Your default value"
}

EDIT Mode: Model from database

$scope.dataModel = getFromDatabaseWithSameStructure()

Then whether EDIT or CREATE mode, you can consistently make use of your ng-model to sync with your database.

No module named MySQLdb

Try this.

pip install MySQL-python

Converting String to Int using try/except in Python

Firstly, try / except are not functions, but statements.

To convert a string (or any other type that can be converted) to an integer in Python, simply call the int() built-in function. int() will raise a ValueError if it fails and you should catch this specifically:

In Python 2.x:

>>> for value in '12345', 67890, 3.14, 42L, 0b010101, 0xFE, 'Not convertible':
...     try:
...         print '%s as an int is %d' % (str(value), int(value))
...     except ValueError as ex:
...         print '"%s" cannot be converted to an int: %s' % (value, ex)
...
12345 as an int is 12345
67890 as an int is 67890
3.14 as an int is 3
42 as an int is 42
21 as an int is 21
254 as an int is 254
"Not convertible" cannot be converted to an int: invalid literal for int() with base 10: 'Not convertible'

In Python 3.x

the syntax has changed slightly:

>>> for value in '12345', 67890, 3.14, 42, 0b010101, 0xFE, 'Not convertible':
...     try:
...         print('%s as an int is %d' % (str(value), int(value)))
...     except ValueError as ex:
...         print('"%s" cannot be converted to an int: %s' % (value, ex))
...
12345 as an int is 12345
67890 as an int is 67890
3.14 as an int is 3
42 as an int is 42
21 as an int is 21
254 as an int is 254
"Not convertible" cannot be converted to an int: invalid literal for int() with base 10: 'Not convertible'

MySQL: How to reset or change the MySQL root password?

To reset or change the password enter sudo dpkg-reconfigure mysql-server-X.X (X.X is mysql version you have installed i.e. 5.6, 5.7) and then you will prompt a screen where you have to set the new password and then in next step confirm the password and just wait for a moment. That's it.

Import Excel Data into PostgreSQL 9.3

For python you could use openpyxl for all 2010 and newer file formats (xlsx).

Al Sweigart has a full tutorial from automate the boring parts on working with excel spreadsheets its very indepth and the whole book and accompanying Udemy course are great resources.

From his example

>>> import openpyxl
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> wb.get_sheet_names()
['Sheet1', 'Sheet2', 'Sheet3']
>>> sheet = wb.get_sheet_by_name('Sheet3')
>>> sheet
<Worksheet "Sheet3">

Understandably once you have this access you can now use psycopg to parse the data to postgres as you normally would do.

This is a link to a list of python resources at python-excel also xlwings provides a large array of features for using python in place of vba in excel.

auto refresh for every 5 mins

Install an interval:

<script type="text/javascript">    
    setInterval(page_refresh, 5*60000); //NOTE: period is passed in milliseconds
</script>

How to check for file lock?

Instead of using interop you can use the .NET FileStream class methods Lock and Unlock:

FileStream.Lock http://msdn.microsoft.com/en-us/library/system.io.filestream.lock.aspx

FileStream.Unlock http://msdn.microsoft.com/en-us/library/system.io.filestream.unlock.aspx

Prevent users from submitting a form by hitting Enter

Something I have not seen answered here: when you tab through the elements on the page, pressing Enter when you get to the submit button will trigger the onsubmit handler on the form, but it will record the event as a MouseEvent. Here is my short solution to cover most bases:

This is not a jQuery-related answer

HTML

<form onsubmit="return false;" method=post>
  <input type="text" /><br />
  <input type="button" onclick="this.form.submit()" value="submit via mouse or keyboard" />
  <input type="button" onclick="submitMouseOnly(event)" value="submit via mouse only" />
</form>

JavaScript

window.submitMouseOnly=function(evt){
    let allow=(evt instanceof MouseEvent) && evt.x>0 && evt.y>0 && evt.screenX > 0 && evt.screenY > 0;
    if(allow)(evt.tagName=='FORM'?evt.target:evt.target.form).submit();
}

To find a working example: https://jsfiddle.net/nemesarial/6rhogva2/

Enum "Inheritance"

This is not possible (as @JaredPar already mentioned). Trying to put logic to work around this is a bad practice. In case you have a base class that have an enum, you should list of all possible enum-values there, and the implementation of class should work with the values that it knows.

E.g. Supposed you have a base class BaseCatalog, and it has an enum ProductFormats (Digital, Physical). Then you can have a MusicCatalog or BookCatalog that could contains both Digital and Physical products, But if the class is ClothingCatalog, it should only contains Physical products.

Embed image in a <button> element

Buttons don't directly support images. Moreover the way you're doing is for links ()

Images are added over buttons using the BACKGROUND-IMAGE property in style

you can also specify the repeats and other properties using tag

For example: a basic image added to a button would have this code:

    <button style="background-image:url(myImage.png)">

Peace

Executing Javascript from Python

You can use requests-html which will download and use chromium underneath.

from requests_html import HTML

html = HTML(html="<a href='http://www.example.com/'>")

script = """
function escramble_758(){
    var a,b,c
    a='+1 '
    b='84-'
    a+='425-'
    b+='7450'
    c='9'
    return a+c+b;
}
"""

val = html.render(script=script, reload=False)
print(val)
# +1 425-984-7450

More on this read here

ModelState.AddModelError - How can I add an error that isn't for a property?

I eventually stumbled upon an example of the usage I was looking for - to assign an error to the Model in general, rather than one of it's properties, as usual you call:

ModelState.AddModelError(string key, string errorMessage);

but use an empty string for the key:

ModelState.AddModelError(string.Empty, "There is something wrong with Foo.");

The error message will present itself in the <%: Html.ValidationSummary() %> as you'd expect.

How to check if a Unix .tar.gz file is a valid file without uncompressing?

A nice option is to use tar -tvvf <filePath> which adds a line that reports the kind of file.

Example in a valid .tar file:

> tar -tvvf filename.tar 
drwxr-xr-x  0 diegoreymendez staff       0 Jul 31 12:46 ./testfolder2/
-rw-r--r--  0 diegoreymendez staff      82 Jul 31 12:46 ./testfolder2/._.DS_Store
-rw-r--r--  0 diegoreymendez staff    6148 Jul 31 12:46 ./testfolder2/.DS_Store
drwxr-xr-x  0 diegoreymendez staff       0 Jul 31 12:42 ./testfolder2/testfolder/
-rw-r--r--  0 diegoreymendez staff      82 Jul 31 12:42 ./testfolder2/testfolder/._.DS_Store
-rw-r--r--  0 diegoreymendez staff    6148 Jul 31 12:42 ./testfolder2/testfolder/.DS_Store
-rw-r--r--  0 diegoreymendez staff  325377 Jul  5 09:50 ./testfolder2/testfolder/Scala.pages
Archive Format: POSIX ustar format,  Compression: none

Corrupted .tar file:

> tar -tvvf corrupted.tar 
tar: Unrecognized archive format
Archive Format: (null),  Compression: none
tar: Error exit delayed from previous errors.

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) on dispatch_semaphore_dispose

My issue was that I was creating objects that I wanted to be stored in a NSMutableDictionary but I never initialized the dictionary. Therefore the objects were getting deleted by garbage collection and breaking later. Check that you have at least one strong reference to the objects youre interacting with.

How to read AppSettings values from a .json file in ASP.NET Core

For ASP.NET Core 3.1 you can follow this documentation:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1

When you create a new ASP.NET Core 3.1 project you will have the following configuration line in Program.cs:

Host.CreateDefaultBuilder(args)

This enables the following:

  1. ChainedConfigurationProvider : Adds an existing IConfiguration as a source. In the default configuration case, adds the host configuration and setting it as the first source for the app configuration.
  2. appsettings.json using the JSON configuration provider.
  3. appsettings.Environment.json using the JSON configuration provider. For example, appsettings.Production.json and appsettings.Development.json.
  4. App secrets when the app runs in the Development environment.
  5. Environment variables using the Environment Variables configuration provider.
  6. Command-line arguments using the Command-line configuration provider.

This means you can inject IConfiguration and fetch values with a string key, even nested values. Like IConfiguration ["Parent:Child"];

Example:

appsettings.json

{
  "ApplicationInsights":
    {
        "Instrumentationkey":"putrealikeyhere"
    }
}

WeatherForecast.cs

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;
    private readonly IConfiguration _configuration;

    public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration)
    {
        _logger = logger;
        _configuration = configuration;
    }

    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        var key = _configuration["ApplicationInsights:InstrumentationKey"];

        var rng = new Random();
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

Sum up a column from a specific row down

=Sum(C:C)-Sum(C1:C5)

Sum everything then remove the sum of the values in the cells you don't want, no Volatile Offset's, Indirect's, or Array's needed.

Just for fun if you don't like that method you could also use:

=SUM($C$6:INDEX($C:$C,MATCH(9.99999999999999E+307,$C:$C))

The above formula will Sum only from C6 through the last cell in C:C where a match of a number is found. This is also non-volatile, but I believe more costly and sloppy. Just added it in case you'd prefer this anyways.

If you would like to do function like CountA for text using the last text value in a column you could use.

=COUNTIF(C6:INDEX($C:$C,MATCH(REPT("Z",255),$C:$C)),"T")

you could also use other combinations like:

=Sum($C$6:$C$65536) 

or

=CountIF($C$6:$C$65536,"T") 

The above would do what you ask in Excel 2003 and lower

=Sum($C$6:$C$1048576) 

or

=CountIF($C$6:$C$1048576,"T")

Would both work for Excel 2007+

All above functions would simply ignore all the blank values under the last value.

How to check if a double is null?

To say that something "is null" means that it is a reference to the null value. Primitives (int, double, float, etc) are by definition not reference types, so they cannot have null values. You will need to find out what your database wrapper will do in this case.

Question mark characters displaying within text, why is this?

Your browser hasn't interpretted the encoding of the page correctly (either because you've forced it to a particular setting, or the page is set incorrectly), and thus cannot display some of the characters.

Which Ruby version am I really running?

The ruby version 1.8.7 seems to be your system ruby.

Normally you can choose the ruby version you'd like, if you are using rvm with following. Simple change into your directory in a new terminal and type in:

rvm use 2.0.0

You can find more details about rvm here: http://rvm.io Open the website and scroll down, you will see a few helpful links. "Setting up default rubies" for example could help you.

Update: To set the ruby as default:

rvm use 2.0.0 --default

jQuery .val() vs .attr("value")

Since jQuery 1.6, attr() will return the original value of an attribute (the one in the markup itself). You need to use prop() to get the current value:

var currentValue = $obj.prop("value");

However, using val() is not always the same. For instance, the value of <select> elements is actually the value of their selected option. val() takes that into account, but prop() does not. For this reason, val() is preferred.

How to use sudo inside a docker container?

The other answers didn't work for me. I kept searching and found a blog post that covered how a team was running non-root inside of a docker container.

Here's the TL;DR version:

RUN apt-get update \
 && apt-get install -y sudo

RUN adduser --disabled-password --gecos '' docker
RUN adduser docker sudo
RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers

USER docker

# this is where I was running into problems with the other approaches
RUN sudo apt-get update 

I was using FROM node:9.3 for this, but I suspect that other similar container bases would work as well.

Eloquent ORM laravel 5 Get Array of ids

You could use lists() :

test::where('id' ,'>' ,0)->lists('id')->toArray();

NOTE : Better if you define your models in Studly Case format, e.g Test.


You could also use get() :

test::where('id' ,'>' ,0)->get('id');

UPDATE: (For versions >= 5.2)

The lists() method was deprecated in the new versions >= 5.2, now you could use pluck() method instead :

test::where('id' ,'>' ,0)->pluck('id')->toArray();

NOTE: If you need a string, for example in a blade, you can use function without the toArray() part, like:

test::where('id' ,'>' ,0)->pluck('id');

How do I revert an SVN commit?

It is impossible to "uncommit" a revision, but you can revert your working copy to version 1943 and commit that as version 1945. The versions 1943 and 1945 will be identical, effectively reverting the changes.

How to terminate a python subprocess launched with shell=True

None of these answers worked for me so Im leaving the code that did work. In my case even after killing the process with .kill() and getting a .poll() return code the process didn't terminate.

Following the subprocess.Popen documentation:

"...in order to cleanup properly a well-behaved application should kill the child process and finish communication..."

proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()

In my case I was missing the proc.communicate() after calling proc.kill(). This cleans the process stdin, stdout ... and does terminate the process.

Checking if a number is an Integer in Java

// in C language.. but the algo is same

#include <stdio.h>

int main(){
  float x = 77.6;

  if(x-(int) x>0)
    printf("True! it is float.");
  else
    printf("False! not float.");        

  return 0;
}

Javascript querySelector vs. getElementById

"Better" is subjective.

querySelector is the newer feature.

getElementById is better supported than querySelector.

querySelector is better supported than getElementsByClassName.

querySelector lets you find elements with rules that can't be expressed with getElementById and getElementsByClassName

You need to pick the appropriate tool for any given task.

(In the above, for querySelector read querySelector / querySelectorAll).

What do 'lazy' and 'greedy' mean in the context of regular expressions?

From Regular expression

The standard quantifiers in regular expressions are greedy, meaning they match as much as they can, only giving back as necessary to match the remainder of the regex.

By using a lazy quantifier, the expression tries the minimal match first.

How can I declare a Boolean parameter in SQL statement?

SQL Server recognizes 'TRUE' and 'FALSE' as bit values. So, use a bit data type!

declare @var bit
set @var = 'true'
print @var

That returns 1.

How to make sure that a certain Port is not occupied by any other process

netstat -ano|find ":port_no" will give you the list.
a: Displays all connections and listening ports.
n: Displays addresses and port numbers in numerical form.
o: Displays the owning process ID associated with each connection .

example : netstat -ano | find ":1900" This gives you the result like this.

UDP    107.109.121.196:1900   *:*                                    1324  
UDP    127.0.0.1:1900         *:*                                    1324  
UDP    [::1]:1900             *:*                                    1324  
UDP    [fe80::8db8:d9cc:12a8:2262%13]:1900  *:*                      1324

Colorplot of 2D array matplotlib

I'm afraid your posted example is not working, since X and Y aren't defined. So instead of pcolormesh let's use imshow:

import numpy as np
import matplotlib.pyplot as plt

H = np.array([[1, 2, 3, 4],
              [5, 6, 7, 8],
              [9, 10, 11, 12],
              [13, 14, 15, 16]])  # added some commas and array creation code

fig = plt.figure(figsize=(6, 3.2))

ax = fig.add_subplot(111)
ax.set_title('colorMap')
plt.imshow(H)
ax.set_aspect('equal')

cax = fig.add_axes([0.12, 0.1, 0.78, 0.8])
cax.get_xaxis().set_visible(False)
cax.get_yaxis().set_visible(False)
cax.patch.set_alpha(0)
cax.set_frame_on(False)
plt.colorbar(orientation='vertical')
plt.show()

How do I find the date a video (.AVI .MP4) was actually recorded?

The best way I found of getting the "dateTaken" date for either video or pictures is to use:

 Imports Microsoft.WindowsAPICodePack.Shell
 Imports Microsoft.WindowsAPICodePack.Shell.PropertySystem
 Imports System.IO
 Dim picture As ShellObject = ShellObject.FromParsingName(path)
 Dim picture As ShellObject = ShellObject.FromParsingName(path)
 Dim ItemDate=picture.Properties.System.ItemDate

The above code requires the shell api, which is internal to Microsoft, and does not depend on any other external dll.

What does appending "?v=1" to CSS and JavaScript URLs in link and script tags do?

As you can read before, the ?v=1 ensures that your browser gets the version 1 of the file. When you have a new version, you just have to append a different version number and the browser will forget about the old version and loads the new one.

There is a gulp plugin which takes care of version your files during the build phase, so you don't have to do it manually. It's handy and you can easily integrate it in you build process. Here's the link: gulp-annotate

Change a HTML5 input's placeholder color with CSS

For SASS/SCSS user using Bourbon, it has a built-in function.

//main.scss
@import 'bourbon';

input {
  width: 300px;

  @include placeholder {
    color: red;
  }
}

CSS Output, you can also grab this portion and paste into your code.

//main.css

input {
  width: 300px;
}

input::-webkit-input-placeholder {
  color: red;
}
input:-moz-placeholder {
  color: red;
}
input::-moz-placeholder {
  color: red;
}
input:-ms-input-placeholder {
  color: red;
}

JavaScript OR (||) variable assignment explanation

According to the Bill Higgins' Blog post; the Javascript logical OR assignment idiom (Feb. 2007), this behavior is true as of v1.2 (at least)

He also suggests another use for it (quoted): "lightweight normalization of cross-browser differences"

// determine upon which element a Javascript event (e) occurred
var target = /*w3c*/ e.target || /*IE*/ e.srcElement;

PHP: How to get referrer URL?

$_SERVER['HTTP_REFERER'];

But if you run a file (that contains the above code) by directly hitting the URL in the browser then you get the following error.

Notice: Undefined index: HTTP_REFERER

Insert Update trigger how to determine if insert or update

I'm using the following, it also correctly detect delete statements that delete nothing:

CREATE TRIGGER dbo.TR_TableName_TriggerName
    ON dbo.TableName
    AFTER INSERT, UPDATE, DELETE
AS
BEGIN
    SET NOCOUNT ON;

    IF NOT EXISTS(SELECT * FROM INSERTED)
        -- DELETE
        PRINT 'DELETE';
    ELSE
    BEGIN
        IF NOT EXISTS(SELECT * FROM DELETED)
            -- INSERT
            PRINT 'INSERT';
        ELSE
            -- UPDATE
            PRINT 'UPDATE';
    END
END;

What is the most compatible way to install python modules on a Mac?

Please see Python OS X development environment. The best way is to use MacPorts. Download and install MacPorts, then install Python via MacPorts by typing the following commands in the Terminal:

sudo port install python26 python_select
sudo port select --set python python26

OR

sudo port install python30 python_select
sudo port select --set python python30

Use the first set of commands to install Python 2.6 and the second set to install Python 3.0. Then use:

sudo port install py26-packagename

OR

sudo port install py30-packagename

In the above commands, replace packagename with the name of the package, for example:

sudo port install py26-setuptools

These commands will automatically install the package (and its dependencies) for the given Python version.

For a full list of available packages for Python, type:

port list | grep py26-

OR

port list | grep py30-

Which command you use depends on which version of Python you chose to install.

Set margins in a LinearLayout programmatically

/*
 * invalid margin
 */
private void invalidMarginBottom() {
    RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) frameLayoutContent.getLayoutParams();
    lp.setMargins(0, 0, 0, 0);
    frameLayoutContent.setLayoutParams(lp);
}

you should be ware of the type of the view's viewGroup.In the code above, for example,I want to change the frameLayout's margin,and the frameLayout's view group is a RelativeLayout,so you need to covert to (RelativeLayout.LayoutParams)

How to read file with async/await properly?

Since Node v11.0.0 fs promises are available natively without promisify:

const fs = require('fs').promises;
async function loadMonoCounter() {
    const data = await fs.readFile("monolitic.txt", "binary");
    return new Buffer(data);
}

C# Macro definitions in Preprocessor

There is no direct equivalent to C-style macros in C#, but inlined static methods - with or without #if/#elseif/#else pragmas - is the closest you can get:

        /// <summary>
        /// Prints a message when in debug mode
        /// </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static unsafe void Log(object message) {
#if DEBUG
            Console.WriteLine(message);
#endif
        }

        /// <summary>
        /// Prints a formatted message when in debug mode
        /// </summary>
        /// <param name="format">A composite format string</param>
        /// <param name="args">An array of objects to write using format</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static unsafe void Log(string format, params object[] args) {
#if DEBUG
            Console.WriteLine(format, args);
#endif
        }

        /// <summary>
        /// Computes the square of a number
        /// </summary>
        /// <param name="x">The value</param>
        /// <returns>x * x</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static double Square(double x) {
            return x * x;
        }

        /// <summary>
        /// Wipes a region of memory
        /// </summary>
        /// <param name="buffer">The buffer</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static unsafe void ClearBuffer(ref byte[] buffer) {
            ClearBuffer(ref buffer, 0, buffer.Length);
        }

        /// <summary>
        /// Wipes a region of memory
        /// </summary>
        /// <param name="buffer">The buffer</param>
        /// <param name="offset">Start index</param>
        /// <param name="length">Number of bytes to clear</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static unsafe void ClearBuffer(ref byte[] buffer, int offset, int length) {
            fixed(byte* ptrBuffer = &buffer[offset]) {
                for(int i = 0; i < length; ++i) {
                    *(ptrBuffer + i) = 0;
                }
            }
        }

This works perfectly as a macro, but comes with a little drawback: Methods marked as inlined will be copied to the reflection part of your assembly like any other "normal" method.

Is there an easy way to convert Android Application to IPad, IPhone

In the box is working on being able to convert android projects to iOS

https://code.google.com/p/in-the-box/

"Application tried to present modally an active controller"?

In my case, I was presenting the rootViewController of an UINavigationController when I was supposed to present the UINavigationController itself.

How to uncheck a checkbox in pure JavaScript?

You will need to assign an ID to the checkbox:

<input id="checkboxId" type="checkbox" checked="" name="copyNewAddrToBilling">

and then in JavaScript:

document.getElementById("checkboxId").checked = false;

What version of JBoss I am running?

This URL (JMX-Console) should provide you the informations

http://localhost:8080/jmx-console/HtmlAdaptor?action=inspectMBean&name=jboss.system%3Atype%3DServer

The tomcat version is implied by the jboss server version.

EDIT:

A complete list of versions you find here VersionOfTomcatInJBossAS

Where you reach your JBoss depends on the interface it is bound, using -b hostname If you start using JBoss with -b 0.0.0.0 option. That way, you can access the system using localhost, machineName and even the IP address. By default it's localhost, if you use th -b option you need to replace localhost by yourhostname.

Insert value into a string at a certain position?

You can't modify strings; they're immutable. You can do this instead:

txtBox.Text = txtBox.Text.Substring(0, i) + "TEXT" + txtBox.Text.Substring(i);

Android set height and width of Custom view programmatically

You can set height and width like this:

myGraphView.setLayoutParams(new LayoutParams(width, height));

Get a list of checked checkboxes in a div using jQuery

This works for me.

var selecteditems = [];

$("#Div").find("input:checked").each(function (i, ob) { 
    selecteditems.push($(ob).val());
});

Elegant way to create empty pandas DataFrame with NaN of type float

Hope this can help!

 pd.DataFrame(np.nan, index = np.arange(<num_rows>), columns = ['A'])

How can I append a string to an existing field in MySQL?

Update image field to add full URL, ignoring null fields:

UPDATE test SET image = CONCAT('https://my-site.com/images/',image) WHERE image IS NOT NULL;

".addEventListener is not a function" why does this error occur?

The first line of your code returns an array and assigns it to the var comment, when what you want is an element assigned to the var comment...

var comment = document.getElementsByClassName("button");

So you are trying to use the method addEventListener() on the array when you need to use the method addEventListener() on the actual element within the array. You need to return an element not an array by accessing the element within the array so the var comment itself is assigned an element not an array.

Change...

var comment = document.getElementsByClassName("button");

to...

var comment = document.getElementsByClassName("button")[0];

Why use argparse rather than optparse?

Why should I use it instead of optparse? Are their new features I should know about?

@Nicholas's answer covers this well, I think, but not the more "meta" question you start with:

Why has yet another command-line parsing module been created?

That's the dilemma number one when any useful module is added to the standard library: what do you do when a substantially better, but backwards-incompatible, way to provide the same kind of functionality emerges?

Either you stick with the old and admittedly surpassed way (typically when we're talking about complicated packages: asyncore vs twisted, tkinter vs wx or Qt, ...) or you end up with multiple incompatible ways to do the same thing (XML parsers, IMHO, are an even better example of this than command-line parsers -- but the email package vs the myriad old ways to deal with similar issues isn't too far away either;-).

You may make threatening grumbles in the docs about the old ways being "deprecated", but (as long as you need to keep backwards compatibility) you can't really take them away without stopping large, important applications from moving to newer Python releases.

(Dilemma number two, not directly related to your question, is summarized in the old saying "the standard library is where good packages go to die"... with releases every year and a half or so, packages that aren't very, very stable, not needing releases any more often than that, can actually suffer substantially by being "frozen" in the standard library... but, that's really a different issue).

How to change button background image on mouseOver?

You can create a class based on a Button with specific images for MouseHover and MouseDown like this:

public class AdvancedImageButton : Button {

public Image HoverImage { get; set; }
public Image PlainImage { get; set; }
public Image PressedImage { get; set; }

protected override void OnMouseEnter(System.EventArgs e)
{
  base.OnMouseEnter(e);
  if (HoverImage == null) return;
  if (PlainImage == null) PlainImage = base.Image;
  base.Image = HoverImage;
}

protected override void OnMouseLeave(System.EventArgs e)
{
  base.OnMouseLeave(e);
  if (HoverImage == null) return;
  base.Image = PlainImage;
}

protected override void OnMouseDown(MouseEventArgs e)
{
  base.OnMouseDown(e);
  if (PressedImage == null) return;
  if (PlainImage == null) PlainImage = base.Image;
  base.Image = PressedImage;
}

}

This solution has a small drawback that I am sure can be fixed: when you need for some reason change the Image property, you will also have to change the PlainImage property also.

.htaccess not working on localhost with XAMPP

I had a similar problem. But the problem was in the file name '.htaccess', because the Windows doesn't let the file's name begin with a ".", the solution was rename the file with a CMD command. "rename c:\xampp\htdocs\htaccess.txt .htaccess"

Paste a multi-line Java String in Eclipse

As far as i know this seems out of scope of an IDE. Copyin ,you can copy the string and then try to format it using ctrl+shift+ F Most often these multiline strings are not used hard coded,rather they shall be used from property or xml files.which can be edited at later point of time without the need for code change

typesafe select onChange event using reactjs and typescript

As far as I can tell, this is currently not possible - a cast is always needed.

To make it possible, the .d.ts of react would need to be modified so that the signature of the onChange of a SELECT element used a new SelectFormEvent. The new event type would expose target, which exposes value. Then the code could be typesafe.

Otherwise there will always be the need for a cast to any.

I could encapsulate all that in a MYSELECT tag.

Copy all values from fields in one class to another through reflection

This is a late post, but can still be effective for people in future.

Spring provides a utility BeanUtils.copyProperties(srcObj, tarObj) which copies values from source object to target object when the names of the member variables of both classes are the same.

If there is a date conversion, (eg, String to Date) 'null' would be copied to the target object. We can then, explicitly set the values of the date as required.

The BeanUtils from Apache Common throws an error when there is a mismatch of data-types (esp. conversion to and from Date)

Hope this helps!

How to delete an instantiated object Python?

What do you mean by delete? In Python, removing a reference (or a name) can be done with the del keyword, but if there are other names to the same object that object will not be deleted.

--> test = 3
--> print(test)
3
--> del test
--> print(test)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'test' is not defined

compared to:

--> test = 5
--> other is test  # check that both name refer to the exact same object
True
--> del test       # gets rid of test, but the object is still referenced by other
--> print(other)
5

Adding Multiple Values in ArrayList at a single index

Use two dimensional array instead. For instance, int values[][] = new int[2][5]; Arrays are faster, when you are not manipulating much.

Android "hello world" pushnotification example

Firebase: https://firebase.google.com/docs/cloud-messaging/

GCM(Deprecated): http://developer.android.com/google/gcm/index.html

I don't have much knowledge about C2DM. Use GCM, it's very easy to implement and configure.

CSS3 transform: rotate; in IE9

Try this

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
body {
    margin-left: 50px;
    margin-top: 50px;
    margin-right: 50px;
    margin-bottom: 50px;
}
.rotate {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 16px;
    -webkit-transform: rotate(-10deg);
    -moz-transform: rotate(-10deg);
    -o-transform: rotate(-10deg);
    -ms-transform: rotate(-10deg);
    -sand-transform: rotate(10deg);
    display: block;
    position: fixed;
}
</style>
</head>

<body>
<div class="rotate">Alpesh</div>
</body>
</html>

Deploy a project using Git push

Sounds like you should have two copies on your server. A bare copy, that you can push/pull from, which your would push your changes when you're done, and then you would clone this into you web directory and set up a cronjob to update git pull from your web directory every day or so.

How to set the background image of a html 5 canvas to .png image

You can give the background image in css :

#canvas { background:url(example.jpg) }

it will show you canvas back ground image

Find largest and smallest number in an array

You can initialize after filling the array or you can write:

 small =~ unsigned(0)/2; // Using the bit-wise complement to flip 0's bits and dividing by 2 because unsigned can hold twice the +ve value an

integer can hold.

 big =- 1*(small) - 1;

instead of:

big = small = values[0]

because when you write this line before filling the array, big and small values will equal to a random leftover value (as integer is a POD) from the memory and if those numbers are either bigger or smaller than any other value in you array, you will get them as an output.