Programs & Examples On #Tr24731

TR 24731 is a technical report prepared by the ISO C standardization committee, now partially incorporated as optional Annex K in the ISO/IEC 9899:2011 C Standard. Part 1 standardizes some safer bounds-checking functions for use in C and Part 2 relates to functions that do dynamic memory allocation.

error C4996: 'scanf': This function or variable may be unsafe in c programming

It sounds like it's just a compiler warning.

Usage of scanf_s prevents possible buffer overflow.
See: http://code.wikia.com/wiki/Scanf_s

Good explanation as to why scanf can be dangerous: Disadvantages of scanf

So as suggested, you can try replacing scanf with scanf_s or disable the compiler warning.

How to use foreach with a hash reference?

As others have stated, you have to dereference the reference. The keys function requires that its argument starts with a %:

My preference:

foreach my $key (keys %{$ad_grp_ref}) {

According to Conway:

foreach my $key (keys %{ $ad_grp_ref }) {

Guess who you should listen to...

You might want to read through the Perl Reference Documentation.

If you find yourself doing a lot of stuff with references to hashes and hashes of lists and lists of hashes, you might want to start thinking about using Object Oriented Perl. There's a lot of nice little tutorials in the Perl documentation.

Python how to plot graph sine wave

  • Setting the x-axis with np.arange(0, 1, 0.001) gives an array from 0 to 1 in 0.001 increments.
    • x = np.arange(0, 1, 0.001) returns an array of 1000 points from 0 to 1, and y = np.sin(2*np.pi*x) you will get the sin wave from 0 to 1 sampled 1000 times

I hope this will help:

import matplotlib.pyplot as plt
import numpy as np


Fs = 8000
f = 5
sample = 8000
x = np.arange(sample)
y = np.sin(2 * np.pi * f * x / Fs)
plt.plot(x, y)
plt.xlabel('sample(n)')
plt.ylabel('voltage(V)')
plt.show()

enter image description here

P.S.: For comfortable work you can use The Jupyter Notebook.

Fixed positioning in Mobile Safari

<meta name="viewport" content="width=320, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/> 

Also making sure height=device-height is not present in this meta tag helps prevent additional footer padding that normally would not exist on the page. The menubar height adds to the viewport height causing a fixed background to become scrollable.

Difference between HttpModule and HttpClientModule

Use the HttpClient class from HttpClientModule if you're using Angular 4.3.x and above:

import { HttpClientModule } from '@angular/common/http';

@NgModule({
 imports: [
   BrowserModule,
   HttpClientModule
 ],
 ...

 class MyService() {
    constructor(http: HttpClient) {...}

It's an upgraded version of http from @angular/http module with the following improvements:

  • Interceptors allow middleware logic to be inserted into the pipeline
  • Immutable request/response objects
  • Progress events for both request upload and response download

You can read about how it works in Insider’s guide into interceptors and HttpClient mechanics in Angular.

  • Typed, synchronous response body access, including support for JSON body types
  • JSON is an assumed default and no longer needs to be explicitly parsed
  • Post-request verification & flush based testing framework

Going forward the old http client will be deprecated. Here are the links to the commit message and the official docs.

Also pay attention that old http was injected using Http class token instead of the new HttpClient:

import { HttpModule } from '@angular/http';

@NgModule({
 imports: [
   BrowserModule,
   HttpModule
 ],
 ...

 class MyService() {
    constructor(http: Http) {...}

Also, new HttpClient seem to require tslib in runtime, so you have to install it npm i tslib and update system.config.js if you're using SystemJS:

map: {
     ...
    'tslib': 'npm:tslib/tslib.js',

And you need to add another mapping if you use SystemJS:

'@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',

Make ABC Ordered List Items Have Bold Style

I know this question is a little old, but it still comes up first in a lot of Google searches. I wanted to add in a solution that doesn't involve editing the style sheet (in my case, I didn't have access):

_x000D_
_x000D_
<ol type="A">_x000D_
  <li style="font-weight: bold;">_x000D_
    <p><span style="font-weight: normal;">Text</span></p>_x000D_
  </li>_x000D_
  <li style="font-weight: bold;">_x000D_
    <p><span style="font-weight: normal;">More text</span></p>_x000D_
  </li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

JavaScript: IIF like statement

If your end goal is to add elements to your page, just manipulate the DOM directly. Don't use string concatenation to try to create HTML - what a pain! See how much more straightforward it is to just create your element, instead of the HTML that represents your element:

var x = document.createElement("option");
x.value = col;
x.text = "Very roomy";
x.selected = col == "screwdriver";

Then, later when you put the element in your page, instead of setting the innerHTML of the parent element, call appendChild():

mySelectElement.appendChild(x);

SqlException: DB2 SQL error: SQLCODE: -302, SQLSTATE: 22001, SQLERRMC: null

As a general point when using a search engine to search for SQL codes make sure you put the sqlcode e.g. -302 in quote marks - like "-302" otherwise the search engine will exclude all search results including the text 302, since the - sign is used to exclude results.

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

I also get this when using the HTTPS everywhere plugin. This plugin has a list of sites that also have https instead of http. So I assume before the actual request is made it is already being cancelled somehow.

So for example when I go to http://stackexchange.com, in Developer I first see a request with status (terminated). This request has some headers, but only the GET, User-Agent, and Accept. No response as well.

Then there is request to https://stackexchange.com with full headers etc.

So I assume it is used for requests that aren't sent.

How do you run multiple programs in parallel from a bash script?

You can use wait:

some_command &
P1=$!
other_command &
P2=$!
wait $P1 $P2

It assigns the background program PIDs to variables ($! is the last launched process' PID), then the wait command waits for them. It is nice because if you kill the script, it kills the processes too!

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder"

For me the issue was: Using Hibernate, I saw that it already used slf4j, and it was in my classpath already, so I decided to use it. The next step - adding imlementor for slf4j, so I added to maven:

<dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-jdk14</artifactId>
        <version>1.7.25</version>
</dependency>

But it failed with error! SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”

The solution was: Hibernate's dependency of slf4j was version 1.7.26, and I added minor version dependency 1.7.25. So when I fixed this - all became OK

What is the difference between a field and a property?

If you are going to use thread primitives you are forced to use fields. Properties can break your threaded code. Apart from that, what cory said is correct.

How to remove margin space around body or clear default css styles

I found this problem continued even when setting the BODY MARGIN to zero.

However it turns out there is an easy fix. All you need to do is give your HEADER tag a 1px border, aswell as setting the BODY MARGIN to zero, as shown below.

body { margin:0px; }

header { border:1px black solid; }

If you have any H1, H2, tags within your HEADER you will also need to set the MARGIN for these tags to zero, this will get rid of any extra space which may show up.

Not sure why this works, but I use Chrome browser. Obviously you can also change the colour of the border to match your header colour.

Using CSS to affect div style inside iframe

Yes. Take a look at this other thread for details: How to apply CSS to iframe?

var cssLink = document.createElement("link");
cssLink.href = "style.css";  
cssLink.rel = "stylesheet";  
cssLink.type = "text/css";  
frames['frame1'].document.body.appendChild(cssLink); 

Adjusting HttpWebRequest Connection Timeout in C#

Something I found later which helped, is the .ReadWriteTimeout property. This, in addition to the .Timeout property seemed to finally cut down on the time threads would spend trying to download from a problematic server. The default time for .ReadWriteTimeout is 5 minutes, which for my application was far too long.

So, it seems to me:

.Timeout = time spent trying to establish a connection (not including lookup time) .ReadWriteTimeout = time spent trying to read or write data after connection established

More info: HttpWebRequest.ReadWriteTimeout Property

Edit:

Per @KyleM's comment, the Timeout property is for the entire connection attempt, and reading up on it at MSDN shows:

Timeout is the number of milliseconds that a subsequent synchronous request made with the GetResponse method waits for a response, and the GetRequestStream method waits for a stream. The Timeout applies to the entire request and response, not individually to the GetRequestStream and GetResponse method calls. If the resource is not returned within the time-out period, the request throws a WebException with the Status property set to WebExceptionStatus.Timeout.

(Emphasis mine.)

Email address validation in C# MVC 4 application: with or without using Regex

You need a regular expression for this. Look here. If you are using .net Framework4.5 then you can also use this. As it is built in .net Framework 4.5. Example

[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }

How to update fields in a model without creating a new record in django?

Sometimes it may be required to execute the update atomically that is using one update request to the database without reading it first.

Also get-set attribute-save may cause problems if such updates may be done concurrently or if you need to set the new value based on the old field value.

In such cases query expressions together with update may by useful:

TemperatureData.objects.filter(id=1).update(value=F('value') + 1)

Could not find or load main class

I had almost the same problem, but with the following variation:

  1. I've imported a ready-to-use maven project into Eclipse IDE from PC1 (project was working there perfectly) to another PC2
  2. when was trying to run the project on PC 2 got the same error "Could not find or load main class"
  3. I've checked PATH variable (it had many values in my case) and added JAVA_HOME variable (in my case it was JAVA_HOME = C:\Program Files\Java\jdk1.7.0_03) After restarting Ecplise it still didn't work
  4. I've tried to run simple HelloWorld.java on PC2 (in another project) - it worked
  5. So I've added HelloWorld class to the imported recently project, executed it there and - huh - my main class in that project started to run normally also.

That's quite odd behavour, I cannot completely understand it. Hope It'll help somebody. too.

Best way to remove duplicate entries from a data table

Heres a easy and fast way using AsEnumerable().Distinct()

private DataTable RemoveDuplicatesRecords(DataTable dt)
{
    //Returns just 5 unique rows
    var UniqueRows = dt.AsEnumerable().Distinct(DataRowComparer.Default);
    DataTable dt2 = UniqueRows.CopyToDataTable();
    return dt2;
}

My Blog Article: Remove duplicate rows from datatable

how to sort an ArrayList in ascending order using Collections and Comparator

This might work?

Comparator mycomparator = 
    Collections.reverseOrder(Collections.reverseOrder());

Secure FTP using Windows batch script

    ftps -a -z -e:on -pfxfile:"S-PID.p12" -pfxpwfile:"S-PID.p12.pwd" -user:<S-PID number> -s:script <RemoteServerName> 2121

S-PID.p12 => certificate file name ;
S-PID.p12.pwd => certificate password file name ; 
RemoteServerName =>  abcd123 ; 
2121 => port number ; 
ftps => command is part of ftps client software ; 

PHP multidimensional array search by value

No one else has used array_reduce yet, so thought I'd add this approach...

$find_by_uid = '100';
$is_in_array = array_reduce($userdb, function($carry, $user) use ($find_by_uid){
    return $carry ? $carry : $user['uid'] === $find_by_uid;
}); 
// Returns true

Gives you more fine control over the 'search' logic than array_search().

Note that I have used strict equality here but you could opt for different comparison logic. The $carry means the comparison needs to be true once, and the final result will be TRUE.

REST API Login Pattern

Principled Design of the Modern Web Architecture by Roy T. Fielding and Richard N. Taylor, i.e. sequence of works from all REST terminology came from, contains definition of client-server interaction:

All REST interactions are stateless. That is, each request contains all of the information necessary for a connector to understand the request, independent of any requests that may have preceded it.

This restriction accomplishes four functions, 1st and 3rd are important in this particular case:

  • 1st: it removes any need for the connectors to retain application state between requests, thus reducing consumption of physical resources and improving scalability;
  • 3rd: it allows an intermediary to view and understand a request in isolation, which may be necessary when services are dynamically rearranged;

And now lets go back to your security case. Every single request should contains all required information, and authorization/authentication is not an exception. How to achieve this? Literally send all required information over wires with every request.

One of examples how to archeive this is hash-based message authentication code or HMAC. In practice this means adding a hash code of current message to every request. Hash code calculated by cryptographic hash function in combination with a secret cryptographic key. Cryptographic hash function is either predefined or part of code-on-demand REST conception (for example JavaScript). Secret cryptographic key should be provided by server to client as resource, and client uses it to calculate hash code for every request.

There are a lot of examples of HMAC implementations, but I'd like you to pay attention to the following three:

How it works in practice

If client knows the secret key, then it's ready to operate with resources. Otherwise he will be temporarily redirected (status code 307 Temporary Redirect) to authorize and to get secret key, and then redirected back to the original resource. In this case there is no need to know beforehand (i.e. hardcode somewhere) what the URL to authorize the client is, and it possible to adjust this schema with time.

Hope this will helps you to find the proper solution!

How to convert an ASCII character into an int in C

It is not possible with the C99 standard library, unless you manually write a map from character constants to the corresponding ASCII int value.

Character constants in C like 'a' are not guaranteed to be ASCII.

C99 only makes some guarantees about those constants, e.g. that digits be contiguous.

The word ASCII only appears on the C99 N1256 standard draft in footer notes, and footer note 173) says:

In an implementation that uses the seven-bit US ASCII character set, the printing characters are those whose values lie from 0x20 (space) through 0x7E (tilde); the control characters are those whose values lie from 0 (NUL) through 0x1F (US), and the character 0x7F (DEL).

implying that ASCII is not the only possibility

Validation to check if password and confirm password are same is not working

if((pswd.length<6 || pswd.length>12) || pswd == ""){
        document.getElementById("passwordloc").innerHTML="character should be between 6-12 characters"; status=false;

} 

else {  
    if(pswd != pswdcnf) {
        document.getElementById("passwordconfirm").innerHTML="password doesnt matched"; status=true;
    } else {
        document.getElementById("passwordconfirm").innerHTML="password  matche";
        document.getElementById("passwordloc").innerHTML = '';
    }

}

How to get the unique ID of an object which overrides hashCode()?

I had the same issue and was not satisfied with any of the answers so far since none of them guaranteed unique IDs.

I too wanted to print object IDs for debugging purposed. I knew there must be some way to do it, because in the Eclipse debugger, it specifies unique IDs for each object.

I came up with a solution based on the fact that the "==" operator for objects only returns true if the two objects are actually the same instance.

import java.util.HashMap;
import java.util.Map;

/**
 *  Utility for assigning a unique ID to objects and fetching objects given
 *  a specified ID
 */
public class ObjectIDBank {

    /**Singleton instance*/
    private static ObjectIDBank instance;

    /**Counting value to ensure unique incrementing IDs*/
    private long nextId = 1;

    /** Map from ObjectEntry to the objects corresponding ID*/
    private Map<ObjectEntry, Long> ids = new HashMap<ObjectEntry, Long>();

    /** Map from assigned IDs to their corresponding objects */
    private Map<Long, Object> objects = new HashMap<Long, Object>();

    /**Private constructor to ensure it is only instantiated by the singleton pattern*/
    private ObjectIDBank(){}

    /**Fetches the singleton instance of ObjectIDBank */
    public static ObjectIDBank instance() {
        if(instance == null)
            instance = new ObjectIDBank();

        return instance;
    }

    /** Fetches a unique ID for the specified object. If this method is called multiple
     * times with the same object, it is guaranteed to return the same value. It is also guaranteed
     * to never return the same value for different object instances (until we run out of IDs that can
     * be represented by a long of course)
     * @param obj The object instance for which we want to fetch an ID
     * @return Non zero unique ID or 0 if obj == null
     */
    public long getId(Object obj) {

        if(obj == null)
            return 0;

        ObjectEntry objEntry = new ObjectEntry(obj);

        if(!ids.containsKey(objEntry)) {
            ids.put(objEntry, nextId);
            objects.put(nextId++, obj);
        }

        return ids.get(objEntry);
    }

    /**
     * Fetches the object that has been assigned the specified ID, or null if no object is
     * assigned the given id
     * @param id Id of the object
     * @return The corresponding object or null
     */
    public Object getObject(long id) {
        return objects.get(id);
    }


    /**
     * Wrapper around an Object used as the key for the ids map. The wrapper is needed to
     * ensure that the equals method only returns true if the two objects are the same instance
     * and to ensure that the hash code is always the same for the same instance.
     */
    private class ObjectEntry {
        private Object obj;

        /** Instantiates an ObjectEntry wrapper around the specified object*/
        public ObjectEntry(Object obj) {
            this.obj = obj;
        }


        /** Returns true if and only if the objects contained in this wrapper and the other
         * wrapper are the exact same object (same instance, not just equivalent)*/
        @Override
        public boolean equals(Object other) {
            return obj == ((ObjectEntry)other).obj;
        }


        /**
         * Returns the contained object's identityHashCode. Note that identityHashCode values
         * are not guaranteed to be unique from object to object, but the hash code is guaranteed to
         * not change over time for a given instance of an Object.
         */
        @Override
        public int hashCode() {
            return System.identityHashCode(obj);
        }
    }
}

I believe that this should ensure unique IDs throughout the lifetime of the program. Note, however, that you probably don't want to use this in a production application because it maintains references to all of the objects for which you generate IDs. This means that any objects for which you create an ID will never be garbage collected.

Since I'm using this for debug purposes, I'm not too concerned with the memory being freed.

You could modify this to allow clearing Objects or removing individual objects if freeing memory is a concern.

How do I detect if a user is already logged in Firebase?

This works:

async function IsLoggedIn(): Promise<boolean> {
  try {
    await new Promise((resolve, reject) =>
      app.auth().onAuthStateChanged(
        user => {
          if (user) {
            // User is signed in.
            resolve(user)
          } else {
            // No user is signed in.
            reject('no user logged in')
          }
        },
        // Prevent console error
        error => reject(error)
      )
    )
    return true
  } catch (error) {
    return false
  }
}

Unable to Connect to GitHub.com For Cloning

I had the same error because I was using proxy. As the answer is given but in case you are using proxy then please set your proxy first using these commands:

git config --global http.proxy http://proxy_username:proxy_password@proxy_ip:port
git config --global https.proxy https://proxy_username:proxy_password@proxy_ip:port

Disable validation of HTML5 form elements

Instead of trying to do an end run around the browser's validation, you could put the http:// in as placeholder text. This is from the very page you linked:

Placeholder Text

The first improvement HTML5 brings to web forms is the ability to set placeholder text in an input field. Placeholder text is displayed inside the input field as long as the field is empty and not focused. As soon as you click on (or tab to) the input field, the placeholder text disappears.

You’ve probably seen placeholder text before. For example, Mozilla Firefox 3.5 now includes placeholder text in the location bar that reads “Search Bookmarks and History”:

enter image description here

When you click on (or tab to) the location bar, the placeholder text disappears:

enter image description here

Ironically, Firefox 3.5 does not support adding placeholder text to your own web forms. C’est la vie.

Placeholder Support

IE  FIREFOX SAFARI  CHROME  OPERA   IPHONE  ANDROID
·   3.7+    4.0+    4.0+    ·       ·       ·

Here’s how you can include placeholder text in your own web forms:

<form>
  <input name="q" placeholder="Search Bookmarks and History">
  <input type="submit" value="Search">
</form>

Browsers that don’t support the placeholder attribute will simply ignore it. No harm, no foul. See whether your browser supports placeholder text.

It wouldn't be exactly the same since it wouldn't provide that "starting point" for the user, but it's halfway there at least.

Case objects vs Enumerations in Scala

I think the biggest advantage of having case classes over enumerations is that you can use type class pattern a.k.a ad-hoc polymorphysm. Don't need to match enums like:

someEnum match {
  ENUMA => makeThis()
  ENUMB => makeThat()
}

instead you'll have something like:

def someCode[SomeCaseClass](implicit val maker: Maker[SomeCaseClass]){
  maker.make()
}

implicit val makerA = new Maker[CaseClassA]{
  def make() = ...
}
implicit val makerB = new Maker[CaseClassB]{
  def make() = ...
}

What is the easiest way to initialize a std::vector with hardcoded elements?

If you don't want to use boost, but want to enjoy syntax like

std::vector<int> v;
v+=1,2,3,4,5;

just include this chunk of code

template <class T> class vector_inserter{
public:
    std::vector<T>& v;
    vector_inserter(std::vector<T>& v):v(v){}
    vector_inserter& operator,(const T& val){v.push_back(val);return *this;}
};
template <class T> vector_inserter<T> operator+=(std::vector<T>& v,const T& x){
    return vector_inserter<T>(v),x;
}

Multiline strings in VB.NET

I figured out how to use both <![CDATA[ along with <%= for variables, which allows you to code without worry.

You basically have to terminate the CDATA tags before the VB variable and then re-add it after so the CDATA does not capture the VB code. You need to wrap the entire code block in a tag because you will you have multiple CDATA blocks.

Dim script As String = <code><![CDATA[
  <script type="text/javascript">
    var URL = ']]><%= domain %><![CDATA[/mypage.html';
  </script>]]>
</code>.value

How to make HTML open a hyperlink in another window or tab?

use target="_blank"

<a target='_blank' href="http://www.starfall.com/">Starfall</a>

Where is a log file with logs from a container?

A container's logs can be found in :

/var/lib/docker/containers/<container id>/<container id>-json.log

(if you use the default log format which is json)

What is the difference between a stored procedure and a view?

First you need to understand, that both are different things. Stored Procedures are best used for INSERT-UPDATE-DELETE statements. Whereas Views are used for SELECT statements. You should use both of them.

In views you cannot alter the data. Some databases have updatable Views where you can use INSERT-UPDATE-DELETE on Views.

MySQL Select Multiple VALUES

Try or:

WHERE id = 3 or id = 4

Or the equivalent in:

WHERE id in (3,4)

How to display Oracle schema size with SQL query?

select T.TABLE_NAME, T.TABLESPACE_NAME, t.avg_row_len*t.num_rows from dba_tables t
order by T.TABLE_NAME asc

See e.g. http://www.dba-oracle.com/t_script_oracle_table_size.htm for more options

Using column alias in WHERE clause of MySQL query produces an error

Maybe my answer is too late but this can help others.

You can enclose it with another select statement and use where clause to it.

SELECT * FROM (Select col1, col2,...) as t WHERE t.calcAlias > 0

calcAlias is the alias column that was calculated.

java.math.BigInteger cannot be cast to java.lang.Long

I'm lacking context, but this is working just fine:

List<BigInteger> nums = new ArrayList<BigInteger>();
Long max = Collections.max(nums).longValue(); // from BigInteger to Long...

How to check if std::map contains a key without doing insert?

Your desideratum,map.contains(key), is scheduled for the draft standard C++2a. In 2017 it was implemented by gcc 9.2. It's also in the current clang.

CSS Circle with border

You are missing the border width and the border style properties in the Border shorthand property :

_x000D_
_x000D_
.circle {
    border: 2px solid red;
    background-color: #FFFFFF;
    height: 100px;
    border-radius:50%;
    width: 100px;
}
_x000D_
<div class="circle"></div>
_x000D_
_x000D_
_x000D_


Also, You can use percentages for the border-radius property so that the value isn't dependent of the circle width/height. That is why I used 50% for border-radius (more info on border-radius in pixels and percent).

Side note : In your example, you didn't specify the border-radius property without vendor prefixes whitch you propably don't need as only browsers before chrome 4 safari 4 and Firefox 3.6 use them (see canIuse).

Hibernate - A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance

Mine was completely different with Spring Boot! For me it was not due to setting collection property.

In my tests I was trying to create an entity and was getting this error for another collection that was unused!

After so much trying I just added a @Transactional on the test method and it solved it. Don't no the reason though.

jQuery Validation plugin: validate check box

You had several issues with your code.

1) Missing a closing brace, }, within your rules.

2) In this case, there is no reason to use a function for the required rule. By default, the plugin can handle checkbox and radio inputs just fine, so using true is enough. However, this will simply do the same logic as in your original function and verify that at least one is checked.

3) If you also want only a maximum of two to be checked, then you'll need to apply the maxlength rule.

4) The messages option was missing the rule specification. It will work, but the one custom message would apply to all rules on the same field.

5) If a name attribute contains brackets, you must enclose it within quotes.

DEMO: http://jsfiddle.net/K6Wvk/

$(document).ready(function () {

    $('#formid').validate({ // initialize the plugin
        rules: {
            'test[]': {
                required: true,
                maxlength: 2
            }
        },
        messages: {
            'test[]': {
                required: "You must check at least 1 box",
                maxlength: "Check no more than {0} boxes"
            }
        }
    });

});

Creating a copy of a database in PostgreSQL

Using pgAdmin, disconnect the database that you want to use as a template. Then you select it as the template to create the new database, this avoids getting the already in use error.

Display only 10 characters of a long string?

html

<p id='longText'>Some very very very very very very very very very very very long string</p>

javascript (on doc ready)

var longText = $('#longText');
longText.text(longText.text().substr(0, 10));

If you have multiple words in the text, and want each to be limited to at most 10 chars, you could do:

var longText = $('#longText');
var text = longText.text();
var regex = /\w{11}\w*/, match;
while(match = regex.exec(text)) {
    text = text.replace(match[0], match[0].substr(0, 10));
}
longText.text(text);

Paging with LINQ for objects

   ( for o in objects
    where ...
    select new
   {
     A=o.a,
     B=o.b
   })
.Skip((page-1)*pageSize)
.Take(pageSize)

How to change the text of a button in jQuery?

The correct way of changing the button text if it was "buttonized" using JQuery is to use .button() method:

$( ".selector" ).button( "option", "label", "new text" );

how we add or remove readonly attribute from textbox on clicking radion button in cakephp using jquery?

In your Case you can write the following jquery code:

$(document).ready(function(){

   $('.staff_on_site').click(function(){

     var rBtnVal = $(this).val();

     if(rBtnVal == "yes"){
         $("#no_of_staff").attr("readonly", false); 
     }
     else{ 
         $("#no_of_staff").attr("readonly", true); 
     }
   });
});

Here is the Fiddle: http://jsfiddle.net/P4QWx/3/

TensorFlow not found using pip

If you're trying to install tensorflow in anaconda and it isn't working, then you may need to downgrade python version because only 3.6.x is currently supported while anaconda has the latest version.

  1. check python version: python --version

  2. if version > 3.6.x then follow step 3, otherwise stop, the problem may be somewhere else

  3. conda search python

  4. conda install python=3.6.6

  5. Check version again: python --version

  6. If version is correct, install tensorflow (step 7)

  7. pip install tensorflow

Can I grep only the first n lines of a file?

Or use awk for a single process without |:

awk '/your_regexp/ && NR < 11' INPUTFILE

On each line, if your_regexp matches, and the number of records (lines) is less than 11, it executes the default action (which is printing the input line).

Or use sed:

sed -n '/your_regexp/p;10q' INPUTFILE 

Checks your regexp and prints the line (-n means don't print the input, which is otherwise the default), and quits right after the 10th line.

error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

You have to use the encoding as latin1 to read this file as there are some special character in this file, use the below code snippet to read the file.

The problem here is the encoding type. When Python can't convert the data to be read, it gives an error.

You can you latin1 or other encoding values.

I say try and test to find the right one for your dataset.

MySql Inner Join with WHERE clause

You could only write one where clause.

 SELECT table1.f_id  FROM table1
 INNER JOIN table2
 ON table2.f_id = table1.f_id
 where table1.f_com_id = '430' AND      
 table1.f_status = 'Submitted' AND table2.f_type = 'InProcess'

How to setup virtual environment for Python in VS Code?

I had the same problem and it was because PowerShell was not updated. Sometimes Windows preserve version 2.* and I had to manually download and install version 3. After that problem solved and I could use virtual environments very well.

How to use __DATE__ and __TIME__ predefined macros in as two integers, then stringify?

For anyone just looking to replace the extra ' ' (space) if day is less than 10 then use:

#define BUILD_DATE (char const[]) { __DATE__[0], __DATE__[1], __DATE__[2], __DATE__[3], (__DATE__[4] == ' ' ?  '0' : __DATE__[4]), __DATE__[5], __DATE__[6], __DATE__[7], __DATE__[8], __DATE__[9], __DATE__[10], __DATE__[11] }

Output: Sep 06 2019

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

i don't see any for loop to initalize the variables.you can do something like this.

for(i=0;i<50;i++){
 /* Code which is necessary with a simple if statement*/

   }

Check if inputs are empty using jQuery

The :empty pseudo-selector is used to see if an element contains no childs, you should check the value :

$('#apply-form input').blur(function() {
     if(!this.value) { // zero-length string
            $(this).parents('p').addClass('warning');
     }
});

Calling startActivity() from outside of an Activity context

In your Activity (where you're calling the adapter) just change getActivityContext() with YourActivity.this. Here's an exemple:

yourAdapter = new YourAdapter(yourList, YourActivity.this); // Here YourActivity.this is the Context instead of getActivityContext()
recyclerView.setAdapter(yourAdapter);

Spring Security redirect to previous page after successful login

I've custom OAuth2 authorization and request.getHeader("Referer") is not available at poit of decision. But security request already saved in ExceptionTranslationFilter.sendStartAuthentication:

protected void sendStartAuthentication(HttpServletRequest request,...
    ...
    requestCache.saveRequest(request, response);

So, all what we need is share requestCache as Spring bean:

@Bean
public RequestCache requestCache() {
   return new HttpSessionRequestCache();
}

@Override
protected void configure(HttpSecurity http) throws Exception {
   http.authorizeRequests()
   ... 
   .requestCache().requestCache(requestCache()).and()
   ...
}     

and use it wheen authorization is finished:

@Autowired
private RequestCache requestCache;

public void authenticate(HttpServletRequest req, HttpServletResponse resp){
    ....
    SavedRequest savedRequest = requestCache.getRequest(req, resp);
    resp.sendRedirect(savedRequest != null && "GET".equals(savedRequest.getMethod()) ?  
    savedRequest.getRedirectUrl() : "defaultURL");
}

Asp.net - Add blank item at top of dropdownlist

Like "Whisk" Said, the trick is in "AppendDataBoundItems" property

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DropDownList1.AppendDataBoundItems = true;
        DropDownList1.Items.Insert(0, new ListItem(String.Empty, String.Empty));
        DropDownList1.SelectedIndex = 0;
    }
}

Thanks "Whisk"

Scripting Language vs Programming Language

Scripting languages are a subset of programming languages.

  1. Scripting languages are not compiled to machine code by the user (python, perl, shell, etc.). Rather, another program (called the interpreter, runs the program and simulates its behavior)
  2. Some programming languages that are not scripting (C, C++, Haskell, and other 'compiled' languages), are compiled to machine code, and is subsequently run.

Getting first and last day of the current month

DateTime now = DateTime.Now;
var startDate = new DateTime(now.Year, now.Month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);

Check if a record exists in the database

sda = new SqlCeDataAdapter("SELECT COUNT(regNumber) AS i FROM  tblAttendance",con);
sda.Fill(dt);

string i = dt.Rows[0]["i"].ToString();
int bar = Convert.ToInt32(i);

if (bar >= 1){

    dt.Clear();
    MetroFramework.MetroMessageBox.Show(this, "something");
}
else if(bar <= 0) {

    dt.Clear();
    MetroFramework.MetroMessageBox.Show(this, "empty");
}

setContentView(R.layout.main); error

if you have multiple packages with different classes then it will be confusing: try this:

import package_name_from_AndroidManifest.R;

error while loading shared libraries: libncurses.so.5:

To install ncurses-compat-libs on Fedora 24 helped me on this issue (unable to start adb error while loading shared libraries: libncurses.so.5)

Create Table from View

If you just want to snag the schema and make an empty table out of it, use a false predicate, like so:

SELECT * INTO myNewTable FROM myView WHERE 1=2

Can I animate absolute positioned element with CSS transition?

Please Try this code margin-left:60px instead of left:60px

please take a look: http://jsfiddle.net/hbirjand/2LtBh/2/

as @Shomz said,transition must be changed to transition:margin 1s linear; instead of transition:all 1s linear;

How to put a List<class> into a JSONObject and then read that object?

Just to update this thread, here is how to add a list (as a json array) into JSONObject. Plz substitute YourClass with your class name;

List<YourClass> list = new ArrayList<>();
JSONObject jsonObject = new JSONObject();

org.codehaus.jackson.map.ObjectMapper objectMapper = new 
org.codehaus.jackson.map.ObjectMapper();
org.codehaus.jackson.JsonNode listNode = objectMapper.valueToTree(list);
org.json.JSONArray request = new org.json.JSONArray(listNode.toString());
jsonObject.put("list", request);

React-Router open Link in new tab

I think Link component does not have the props for it.

You can have alternative way by create a tag and use the makeHref method of Navigation mixin to create your url

<a target='_blank' href={this.makeHref(routeConsts.CHECK_DOMAIN, {},
   { realm: userStore.getState().realms[0].name })}>
        Share this link to your webmaster
</a>

What is the syntax to insert one list into another list in python?

If you want to add the elements in a list (list2) to the end of other list (list), then you can use the list extend method

list = [1, 2, 3]
list2 = [4, 5, 6]
list.extend(list2)
print list
[1, 2, 3, 4, 5, 6]

Or if you want to concatenate two list then you can use + sign

list3 = list + list2
print list3
[1, 2, 3, 4, 5, 6]

Base64 decode snippet in C++

There are several snippets here. However, this one is compact, efficient, and C++11 friendly:

static std::string base64_encode(const std::string &in) {

    std::string out;

    int val = 0, valb = -6;
    for (uchar c : in) {
        val = (val << 8) + c;
        valb += 8;
        while (valb >= 0) {
            out.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(val>>valb)&0x3F]);
            valb -= 6;
        }
    }
    if (valb>-6) out.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[((val<<8)>>(valb+8))&0x3F]);
    while (out.size()%4) out.push_back('=');
    return out;
}

static std::string base64_decode(const std::string &in) {

    std::string out;

    std::vector<int> T(256,-1);
    for (int i=0; i<64; i++) T["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[i]] = i;

    int val=0, valb=-8;
    for (uchar c : in) {
        if (T[c] == -1) break;
        val = (val << 6) + T[c];
        valb += 6;
        if (valb >= 0) {
            out.push_back(char((val>>valb)&0xFF));
            valb -= 8;
        }
    }
    return out;
}

When to use Hadoop, HBase, Hive and Pig?

Pig: it is better to handle files and cleaning data example: removing null values,string handling,unnecessary values Hive: for querying on cleaned data

Get the current year in JavaScript

Here is another method to get date

new Date().getDate()          // Get the day as a number (1-31)
new Date().getDay()           // Get the weekday as a number (0-6)
new Date().getFullYear()      // Get the four digit year (yyyy)
new Date().getHours()         // Get the hour (0-23)
new Date().getMilliseconds()  // Get the milliseconds (0-999)
new Date().getMinutes()       // Get the minutes (0-59)
new Date().getMonth()         // Get the month (0-11)
new Date().getSeconds()       // Get the seconds (0-59)
new Date().getTime()          // Get the time (milliseconds since January 1, 1970)

How to get out of while loop in java with Scanner method "hasNext" as condition?

Modify the while loop as below. Declare s1 as String s1; one time outside the loop. To end the loop, simply use ctrl+z.

  while (sc.hasNext())
  {    
    s1 = sc.next();
    System.out.println(s1);
    System.out.print("Enter your sentence: ");
  }

Get filename from input [type='file'] using jQuery

var file = $('#YOURID > input[type="file"]'); file.value; // filename will be,

In Chrome, it will be something like C:\fakepath\FILE_NAME or undefined if no file was selected.

It is a limitation or intention that the browser does not reveal the file structure of the local machine.

Using wire or reg with input or output in Verilog

seeing it in digital circuit domain

  1. A Wire will create a wire output which can only be assigned any input by using assign statement as assign statement creates a port/pin connection and wire can be joined to the port/pin
  2. A reg will create a register(D FLIP FLOP ) which gets or recieve inputs on basis of sensitivity list either it can be clock (rising or falling ) or combinational edge .

so it completely depends on your use whether you need to create a register and tick it according to sensitivity list or you want to create a port/pin assignment

Trying to add adb to PATH variable OSX

Add to PATH for every login

Total control version:

in your terminal, navigate to home directory

cd

create file .bash_profile

touch .bash_profile

open file with TextEdit

open -e .bash_profile

insert line into TextEdit

export PATH=$PATH:/Users/username/Library/Android/sdk/platform-tools/

save file and reload file

source ~/.bash_profile

check if adb was set into path

adb version


One liner version

Echo your export command and redirect the output to be appended to .bash_profile file and restart terminal. (have not verified this but should work)

echo "export PATH=$PATH:/Users/username/Library/Android/sdk/platform-tools/ sdk/platform-tools/" >> ~/.bash_profile

Replace multiple whitespaces with single whitespace in JavaScript string

You can augment String to implement these behaviors as methods, as in:

String.prototype.killWhiteSpace = function() {
    return this.replace(/\s/g, '');
};

String.prototype.reduceWhiteSpace = function() {
    return this.replace(/\s+/g, ' ');
};

This now enables you to use the following elegant forms to produce the strings you want:

"Get rid of my whitespaces.".killWhiteSpace();
"Get rid of my extra        whitespaces".reduceWhiteSpace();

Rails Active Record find(:all, :order => ) issue

I just ran into the same problem, but I manage to have my query working in SQLite like this:

@shows = Show.order("datetime(date) ASC, attending DESC")

I hope this might help someone save some time

Referring to the null object in Python

In Python, to represent the absence of a value, you can use the None value (types.NoneType.None) for objects and "" (or len() == 0) for strings. Therefore:

if yourObject is None:  # if yourObject == None:
    ...

if yourString == "":  # if yourString.len() == 0:
    ...

Regarding the difference between "==" and "is", testing for object identity using "==" should be sufficient. However, since the operation "is" is defined as the object identity operation, it is probably more correct to use it, rather than "==". Not sure if there is even a speed difference.

Anyway, you can have a look at:

How to lazy load images in ListView in Android

You must try this Universal Loader is best. I am using this after done many RnD on lazy loading .

Universal Image Loader

Features

  • Multithread image loading (async or sync)
  • Wide customization of ImageLoader's configuration (thread executors, downloader, decoder, memory and disk cache, display image options, etc.)
  • Many customization options for every display image call (stub images, caching switch, decoding options, Bitmap processing and displaying, etc.)
  • Image caching in memory and/or on disk (device's file system or SD card)
  • Listening loading process (including downloading progress)

Android 2.0+ support

enter image description here

How to add to the PYTHONPATH in Windows, so it finds my modules/packages?

For anyone trying to achieve this with Python 3.3+, the Windows installer now includes an option to add python.exe to the system search path. Read more in the docs.

Python: List vs Dict for look up table

if data are unique set() will be the most efficient, but of two - dict (which also requires uniqueness, oops :)

Finding the source code for built-in Python functions?

The iPython shell makes this easy: function? will give you the documentation. function?? shows also the code. BUT this only works for pure python functions.

Then you can always download the source code for the (c)Python.

If you're interested in pythonic implementations of core functionality have a look at PyPy source.

How to add a line break within echo in PHP?

\n is a line break. /n is not.


use of \n with

1. echo directly to page

Now if you are trying to echo string to the page:

echo  "kings \n garden";

output will be:

kings garden

you won't get garden in new line because PHP is a server-side language, and you are sending output as HTML, you need to create line breaks in HTML. HTML doesn't understand \n. You need to use the nl2br() function for that.

What it does is:

Returns string with <br /> or <br> inserted before all newlines (\r\n, \n\r, \n and \r).

echo  nl2br ("kings \n garden");

Output

kings
garden

Note Make sure you're echoing/printing \n in double quotes, else it will be rendered literally as \n. because php interpreter parse string in single quote with concept of as is

so "\n" not '\n'

2. write to text file

Now if you echo to text file you can use just \n and it will echo to a new line, like:

$myfile = fopen("test.txt", "w+")  ;

$txt = "kings \n garden";
fwrite($myfile, $txt);
fclose($myfile);
 

output will be:

kings
 garden

Understanding Popen.communicate

Do not use communicate(input=""). It writes input to the process, closes its stdin and then reads all output.

Do it like this:

p=subprocess.Popen(["python","1st.py"],stdin=PIPE,stdout=PIPE)

# get output from process "Something to print"
one_line_output = p.stdout.readline()

# write 'a line\n' to the process
p.stdin.write('a line\n')

# get output from process "not time to break"
one_line_output = p.stdout.readline() 

# write "n\n" to that process for if r=='n':
p.stdin.write('n\n') 

# read the last output from the process  "Exiting"
one_line_output = p.stdout.readline()

What you would do to remove the error:

all_the_process_will_tell_you = p.communicate('all you will ever say to this process\nn\n')[0]

But since communicate closes the stdout and stdin and stderr, you can not read or write after you called communicate.

Change the background color in a twitter bootstrap modal?

For Bootstrap 4 you may have to use .modal-backdrop.show and play around with !important flag on both background-color and opacity.

E.g.

.modal-backdrop.show {
   background-color: #f00;
   opacity: 0.75;
}

Java: How can I compile an entire directory structure of code ?

With Bash 4+, you can just enable globstar

shopt -s globstar

and then do

javac **/*.java

How to resize the jQuery DatePicker control

I can't add a comment, so this is in reference to the accepted answer by Keijro. I actually added the following to my stylesheet instead:

    div.ui-datepicker {
    font-size: 62.5%;
}

and it worked as well. This might be preferable to the absolute value of 10px.

Remove a fixed prefix/suffix from a string in Bash

Small and universal solution:

expr "$string" : "$prefix\(.*\)$suffix"

Should each and every table have a primary key?

To make it future proof you really should. If you want to replicate it you'll need one. If you want to join it to another table your life (and that of the poor fools who have to maintain it next year) will be so much easier.

Can Json.NET serialize / deserialize to / from a stream?

I arrived at this question looking for a way to stream an open ended list of objects onto a System.IO.Stream and read them off the other end, without buffering the entire list before sending. (Specifically I'm streaming persisted objects from MongoDB over Web API.)

@Paul Tyng and @Rivers did an excellent job answering the original question, and I used their answers to build a proof of concept for my problem. I decided to post my test console app here in case anyone else is facing the same issue.

using System;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace TestJsonStream {
    class Program {
        static void Main(string[] args) {
            using(var writeStream = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.None)) {
                string pipeHandle = writeStream.GetClientHandleAsString();
                var writeTask = Task.Run(() => {
                    using(var sw = new StreamWriter(writeStream))
                    using(var writer = new JsonTextWriter(sw)) {
                        var ser = new JsonSerializer();
                        writer.WriteStartArray();
                        for(int i = 0; i < 25; i++) {
                            ser.Serialize(writer, new DataItem { Item = i });
                            writer.Flush();
                            Thread.Sleep(500);
                        }
                        writer.WriteEnd();
                        writer.Flush();
                    }
                });
                var readTask = Task.Run(() => {
                    var sw = new Stopwatch();
                    sw.Start();
                    using(var readStream = new AnonymousPipeClientStream(pipeHandle))
                    using(var sr = new StreamReader(readStream))
                    using(var reader = new JsonTextReader(sr)) {
                        var ser = new JsonSerializer();
                        if(!reader.Read() || reader.TokenType != JsonToken.StartArray) {
                            throw new Exception("Expected start of array");
                        }
                        while(reader.Read()) {
                            if(reader.TokenType == JsonToken.EndArray) break;
                            var item = ser.Deserialize<DataItem>(reader);
                            Console.WriteLine("[{0}] Received item: {1}", sw.Elapsed, item);
                        }
                    }
                });
                Task.WaitAll(writeTask, readTask);
                writeStream.DisposeLocalCopyOfClientHandle();
            }
        }

        class DataItem {
            public int Item { get; set; }
            public override string ToString() {
                return string.Format("{{ Item = {0} }}", Item);
            }
        }
    }
}

Note that you may receive an exception when the AnonymousPipeServerStream is disposed, I ignored this as it isn't relevant to the problem at hand.

Spark - load CSV file as DataFrame?

To read from relative path on the system use System.getProperty method to get current directory and further uses to load the file using relative path.

scala> val path = System.getProperty("user.dir").concat("/../2015-summary.csv")
scala> val csvDf = spark.read.option("inferSchema","true").option("header", "true").csv(path)
scala> csvDf.take(3)

spark:2.4.4 scala:2.11.12

session handling in jquery

In my opinion you should not load and use plugins you don't have to. This particular jQuery plugin doesn't give you anything since directly using the JavaScript sessionStorage object is exactly the same level of complexity. Nor, does the plugin provide some easier way to interact with other jQuery functionality. In addition the practice of using a plugin discourages a deep understanding of how something works. sessionStorage should be used only if its understood. If its understood, then using the jQuery plugin is actually MORE effort.

Consider using sessionStorage directly: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#sessionStorage

How can I make a JUnit test wait?

Thread.sleep() could work in most cases, but usually if you're waiting, you are actually waiting for a particular condition or state to occur. Thread.sleep() does not guarantee that whatever you're waiting for has actually happened.

If you are waiting on a rest request for example maybe it usually return in 5 seconds, but if you set your sleep for 5 seconds the day your request comes back in 10 seconds your test is going to fail.

To remedy this JayWay has a great utility called Awatility which is perfect for ensuring that a specific condition occurs before you move on.

It has a nice fluent api as well

await().until(() -> 
{
    return yourConditionIsMet();
});  

https://github.com/jayway/awaitility

Replace all particular values in a data frame

Since PikkuKatja and glallen asked for a more general solution and I cannot comment yet, I'll write an answer. You can combine statements as in:

> df[df=="" | df==12] <- NA
> df
     A    B
1  <NA> <NA>
2  xyz  <NA>
3  jkl  100

For factors, zxzak's code already yields factors:

> df <- data.frame(list(A=c("","xyz","jkl"), B=c(12,"",100)))
> str(df)
'data.frame':   3 obs. of  2 variables:
 $ A: Factor w/ 3 levels "","jkl","xyz": 1 3 2
 $ B: Factor w/ 3 levels "","100","12": 3 1 2

If in trouble, I'd suggest to temporarily drop the factors.

df[] <- lapply(df, as.character)

CSS image resize percentage of itself?

This is a not-hard approach:

<div>
    <img src="sample.jpg" />
</div>

then in css:
div {
    position: absolute;
}

img, div {
   width: ##%;
   height: ##%;
}

Is it possible to return empty in react render function?

Returning falsy value in the render() function will render nothing. So you can just do

 render() {
    let finalClasses = "" + (this.state.classes || "");
    return !isTimeout && <div>{this.props.children}</div>;
  }

iPad Safari scrolling causes HTML elements to disappear and reappear with a delay

There are cases where a rotation is applied and/or a Z index is used.

Rotation: An existing declaration of -webkit-transform to rotate an element might not be enough to tackle the appearance problem as well (like -webkit-transform: rotate(-45deg)). In this case you can use -webkit-transform: translateZ(0px) rotateZ(-45deg) as a trick (mind the rotateZ).

Z index: Together with the rotation you might define a positive z-index property, like z-index: 42. The above steps described under "Rotation" were in my case enough to resolve the issue, even with the empty translateZ(0px). I suspect though that the Z index in this case may have caused the disappearing and reappearing in the first place. In any case the z-index: 42 property needs to be kept -- -webkit-transform: translateZ(42px) only is not enough.

Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources

In my case, my problem was environmental. Meaning, I did something wrong in my bash session. After attempting nearly everything in this thread, I opened a new bash session and everything was back to normal.

GET and POST methods with the same Action name in the same Controller

Today I was checking some resources about the same question and I got an example very interesting.

It is possible to call the same method by GET and POST protocol, but you need to overload the parameters like that:

@using (Ajax.BeginForm("Index", "MyController", ajaxOptions, new { @id = "form-consulta" }))
{
//code
}

The action:

[ActionName("Index")]
public async Task<ActionResult> IndexAsync(MyModel model)
{
//code
}

By default a method without explicit protocol is GET, but in that case there is a declared parameter which allows the method works like a POST.

When GET is executed the parameter does not matter, but when POST is executed the parameter is required on your request.

How can I run a function from a script in command line?

If the script only defines the functions and does nothing else, you can first execute the script within the context of the current shell using the source or . command and then simply call the function. See help source for more information.

How can I print using JQuery

function printResult() {
    var DocumentContainer = document.getElementById('your_div_id');
    var WindowObject = window.open('', "PrintWindow", "width=750,height=650,top=50,left=50,toolbars=no,scrollbars=yes,status=no,resizable=yes");
    WindowObject.document.writeln(DocumentContainer.innerHTML);
    WindowObject.document.close();
    WindowObject.focus();
    WindowObject.print();
    WindowObject.close();
}

How to save as a new file and keep working on the original one in Vim?

The following command will create a copy in a new window. So you can continue see both original file and the new file.

:w {newfilename} | sp #

Defining static const integer members in class definition

Here's another way to work around the problem:

std::min(9, int(test::N));

(I think Crazy Eddie's answer correctly describes why the problem exists.)

List<object>.RemoveAll - How to create an appropriate Predicate

A predicate in T is a delegate that takes in a T and returns a bool. List<T>.RemoveAll will remove all elements in a list where calling the predicate returns true. The easiest way to supply a simple predicate is usually a lambda expression, but you can also use anonymous methods or actual methods.

{
    List<Vehicle> vehicles;
    // Using a lambda
    vehicles.RemoveAll(vehicle => vehicle.EnquiryID == 123);
    // Using an equivalent anonymous method
    vehicles.RemoveAll(delegate(Vehicle vehicle)
    {
        return vehicle.EnquiryID == 123;
    });
    // Using an equivalent actual method
    vehicles.RemoveAll(VehiclePredicate);
}

private static bool VehiclePredicate(Vehicle vehicle)
{
    return vehicle.EnquiryID == 123;
}

IOCTL Linux device driver

An ioctl, which means "input-output control" is a kind of device-specific system call. There are only a few system calls in Linux (300-400), which are not enough to express all the unique functions devices may have. So a driver can define an ioctl which allows a userspace application to send it orders. However, ioctls are not very flexible and tend to get a bit cluttered (dozens of "magic numbers" which just work... or not), and can also be insecure, as you pass a buffer into the kernel - bad handling can break things easily.

An alternative is the sysfs interface, where you set up a file under /sys/ and read/write that to get information from and to the driver. An example of how to set this up:

static ssize_t mydrvr_version_show(struct device *dev,
        struct device_attribute *attr, char *buf)
{
    return sprintf(buf, "%s\n", DRIVER_RELEASE);
}

static DEVICE_ATTR(version, S_IRUGO, mydrvr_version_show, NULL);

And during driver setup:

device_create_file(dev, &dev_attr_version);

You would then have a file for your device in /sys/, for example, /sys/block/myblk/version for a block driver.

Another method for heavier use is netlink, which is an IPC (inter-process communication) method to talk to your driver over a BSD socket interface. This is used, for example, by the WiFi drivers. You then communicate with it from userspace using the libnl or libnl3 libraries.

Select2() is not a function

Put config.assets.debug = false in config/environments/development.rb.

Blurring an image via CSS?

This code is working for blur effect for all browsers.

filter: blur(10px);
-webkit-filter: blur(10px);
-moz-filter: blur(10px);
-o-filter: blur(10px);
-ms-filter: blur(10px);

Can't access Tomcat using IP address

Firewalls are often the problem in these situations. Personally, the Mcafee enterprise firewall was causing this issue even for requests within the network.

Disable your firewalls or add a rule for tomcat and see if this helps.

Error while waiting for device: Time out after 300seconds waiting for emulator to come online

I've face this problem, i fixed it by deleting the emulator then created a new one with higher API level.

In my case I've created API-30

Numpy: Divide each row by a vector element

JoshAdel's solution uses np.newaxis to add a dimension. An alternative is to use reshape() to align the dimensions in preparation for broadcasting.

data = np.array([[1,1,1],[2,2,2],[3,3,3]])
vector = np.array([1,2,3])

data
# array([[1, 1, 1],
#        [2, 2, 2],
#        [3, 3, 3]])
vector
# array([1, 2, 3])

data.shape
# (3, 3)
vector.shape
# (3,)

data / vector.reshape((3,1))
# array([[1, 1, 1],
#        [1, 1, 1],
#        [1, 1, 1]])

Performing the reshape() allows the dimensions to line up for broadcasting:

data:            3 x 3
vector:              3
vector reshaped: 3 x 1

Note that data/vector is ok, but it doesn't get you the answer that you want. It divides each column of array (instead of each row) by each corresponding element of vector. It's what you would get if you explicitly reshaped vector to be 1x3 instead of 3x1.

data / vector
# array([[1, 0, 0],
#        [2, 1, 0],
#        [3, 1, 1]])
data / vector.reshape((1,3))
# array([[1, 0, 0],
#        [2, 1, 0],
#        [3, 1, 1]])

Parse JSON from JQuery.ajax success data

I recommend you use:

var returnedData = JSON.parse(response);

to convert the JSON string (if it is just text) to a JavaScript object.

How to connect android emulator to the internet

Have you tried starting the emulator with administrative privileges? It worked for me, I'm running Windows 7 64bit)

Does MS SQL Server's "between" include the range boundaries?

if you hit this, and don't really want to try and handle adding a day in code, then let the DB do it..

myDate >= '20090101 00:00:00' AND myDate < DATEADD(day,1,'20090101 00:00:00')

If you do include the time portion: make sure it references midnight. Otherwise you can simply omit the time:

myDate >= '20090101' AND myDate < DATEADD(day,1,'20090101')

and not worry about it.

Set element focus in angular way

Another option would be to use Angular's built-in pub-sub architecture in order to notify your directive to focus. Similar to the other approaches, but it's then not directly tied to a property, and is instead listening in on it's scope for a particular key.

Directive:

angular.module("app").directive("focusOn", function($timeout) {
  return {
    restrict: "A",
    link: function(scope, element, attrs) {
      scope.$on(attrs.focusOn, function(e) {
        $timeout((function() {
          element[0].focus();
        }), 10);
      });
    }
  };
});

HTML:

<input type="text" name="text_input" ng-model="ctrl.model" focus-on="focusTextInput" />

Controller:

//Assume this is within your controller
//And you've hit the point where you want to focus the input:
$scope.$broadcast("focusTextInput");

How to create custom config section in app.config?

Import namespace :

using System.Configuration;

Create ConfigurationElement Company :

public class Company : ConfigurationElement
{

        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get
            {
                return this["name"] as string;
            }
        }
            [ConfigurationProperty("code", IsRequired = true)]
        public string Code
        {
            get
            {
                return this["code"] as string;
            }
        }
}

ConfigurationElementCollection:

public class Companies
        : ConfigurationElementCollection
    {
        public Company this[int index]
        {
            get
            {
                return base.BaseGet(index) as Company ;
            }
            set
            {
                if (base.BaseGet(index) != null)
                {
                    base.BaseRemoveAt(index);
                }
                this.BaseAdd(index, value);
            }
        }

       public new Company this[string responseString]
       {
            get { return (Company) BaseGet(responseString); }
            set
            {
                if(BaseGet(responseString) != null)
                {
                    BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
                }
                BaseAdd(value);
            }
        }

        protected override System.Configuration.ConfigurationElement CreateNewElement()
        {
            return new Company();
        }

        protected override object GetElementKey(System.Configuration.ConfigurationElement element)
        {
            return ((Company)element).Name;
        }
    }

and ConfigurationSection:

public class RegisterCompaniesConfig
        : ConfigurationSection
    {

        public static RegisterCompaniesConfig GetConfig()
        {
            return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
        }

        [System.Configuration.ConfigurationProperty("Companies")]
            [ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
        public Companies Companies
        {
            get
            {
                object o = this["Companies"];
                return o as Companies ;
            }
        }

    }

and you must also register your new configuration section in web.config (app.config):

<configuration>       
    <configSections>
          <section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>

then you load your config with

var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
   do something ..
}

SELECT query with CASE condition and SUM()

Use an "Or"

Select SUM(CAmount) as PaymentAmount 
from TableOrderPayment 
where (CPaymentType='Check' Or CPaymentType='Cash')
   and CDate <= case CPaymentType When 'Check' Then SYSDATETIME() else CDate End
   and CStatus='" & "Active" & "'"

or an "IN"

Select SUM(CAmount) as PaymentAmount 
from TableOrderPayment 
where CPaymentType IN ('Check', 'Cash')
   and CDate <= case CPaymentType When 'Check' Then SYSDATETIME() else CDate End
   and CStatus='" & "Active" & "'"

How can I extract a predetermined range of lines from a text file on Unix?

I was about to post the head/tail trick, but actually I'd probably just fire up emacs. ;-)

  1. esc-x goto-line ret 16224
  2. mark (ctrl-space)
  3. esc-x goto-line ret 16482
  4. esc-w

open the new output file, ctl-y save

Let's me see what's happening.

How to pattern match using regular expression in Scala?

As delnan pointed out, the match keyword in Scala has nothing to do with regexes. To find out whether a string matches a regex, you can use the String.matches method. To find out whether a string starts with an a, b or c in lower or upper case, the regex would look like this:

word.matches("[a-cA-C].*")

You can read this regex as "one of the characters a, b, c, A, B or C followed by anything" (. means "any character" and * means "zero or more times", so ".*" is any string).

How do I make a dotted/dashed line in Android?

Best Solution for Dotted Background working perfect

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
  <stroke
    android:dashGap="3dp"
    android:dashWidth="2dp"
    android:width="1dp"
    android:color="@color/colorBlack" />
</shape>

Can't install nuget package because of "Failed to initialize the PowerShell host"

My problem solved, because in this time .Net Core not supported EF 6.2.0.

change project from Core and EF installed successfully.

How to get english language word database?

You didn't say what you needed this list for. If something used as a blacklist for password checks is enough cracklib might be good for you. It contains over 1.5M words.

Inserting multiple rows in mysql

// db table name / blog_post / menu /  site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO product_cate (site_title, sub_title) 
  VALUES ('$site_title', '$sub_title')";

// db table name / blog_post / menu /  site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO menu (menu_title, sub_menu)
  VALUES ('$menu_title', '$sub_menu', )";

// db table name / blog_post /  menu /  site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO blog_post (post_title, post_des, post_img)
  VALUES ('$post_title ', '$post_des', '$post_img')";

"Could not find Developer Disk Image"

1) I have experienced same issue, my Xcode version was 7.0.1, and I updated my iPhone to version 9.2, then upon using Xcode, my iPhone was shown in the section of unavailable device. Just like in image below:

enter image description here

2) But then I somehow managed to select my iPhone by clicking at
Product -> Destination -> Unavailable Device

enter image description here

3) But that didn't solved my problem, and it started showing:

Could not find Developer Disk Image

enter image description here

Solution) Then finally I downloaded latest version of Xcode version 7.2 from here and everything has worked fine for me.

Update: Whenever version of iPhone device is higher than version of Xcode, you may experience same issue, so you should update your Xcode version to remove this error.

HttpWebRequest-The remote server returned an error: (400) Bad Request

What type of authentication do you use? Send the credentials using the properties Ben said before and setup a cookie handler. You already allow redirection, check your webserver if any redirection occurs (NTLM auth does for sure). If there is a redirection you need to store the session which is mostly stored in a session cookie.

How to call a vue.js function on page load

You can call this function in beforeMount section of a Vue component: like following:

 ....
 methods:{
     getUnits: function() {...}
 },
 beforeMount(){
    this.getUnits()
 },
 ......

Working fiddle: https://jsfiddle.net/q83bnLrx/1/

There are different lifecycle hooks Vue provide:

I have listed few are :

  1. beforeCreate: Called synchronously after the instance has just been initialized, before data observation and event/watcher setup.
  2. created: Called synchronously after the instance is created. At this stage, the instance has finished processing the options which means the following have been set up: data observation, computed properties, methods, watch/event callbacks. However, the mounting phase has not been started, and the $el property will not be available yet.
  3. beforeMount: Called right before the mounting begins: the render function is about to be called for the first time.
  4. mounted: Called after the instance has just been mounted where el is replaced by the newly created vm.$el.
  5. beforeUpdate: Called when the data changes, before the virtual DOM is re-rendered and patched.
  6. updated: Called after a data change causes the virtual DOM to be re-rendered and patched.

You can have a look at complete list here.

You can choose which hook is most suitable to you and hook it to call you function like the sample code provided above.

ORA-00060: deadlock detected while waiting for resource

I was testing a function that had multiple UPDATE statements within IF-ELSE blocks.

I was testing all possible paths, so I reset the tables to their previous values with 'manual' UPDATE statements each time before running the function again.

I noticed that the issue would happen just after those UPDATE statements;

I added a COMMIT; after the UPDATE statement I used to reset the tables and that solved the problem.

So, caution, the problem was not the function itself...

How do I send a file as an email attachment using Linux command line?

This is how I am doing with one large log file in CentOS:

#!/bin/sh
MAIL_CMD="$(which mail)"
WHOAMI="$(whoami)"
HOSTNAME="$(hostname)"
EMAIL"[email protected]"
LOGDIR="/var/log/aide"
LOGNAME="$(basename "$0")_$(date "+%Y%m%d_%H%M")"

if cd ${LOGDIR}; then
  /bin/tar -zcvf "${LOGDIR}/${LOGNAME}".tgz "${LOGDIR}/${LOGNAME}.log" > /dev/null 2>&1
  if [ -n "${MAIL_CMD}" ]; then
  # This works too. The message content will be taken from text file below
  # echo 'Hello!' >/root/scripts/audit_check.sh.txt
  # echo "Attachment" | ${MAIL_CMD} -s "${HOSTNAME} Aide report" -q /root/scripts/audit_check.sh.txt -a ${LOGNAME}.tgz -S from=${WHOAMI}@${HOSTNAME} ${EMAIL}
    echo "Attachment" | ${MAIL_CMD} -s "${HOSTNAME} Aide report" -a "${LOGNAME}.tgz" -S from="${WHOAMI}@${HOSTNAME}" "${EMAIL}"
    /bin/rm "${LOGDIR}/${LOGNAME}.log"
  fi
fi

How can I get the current contents of an element in webdriver

I know when you said "contents" you didn't mean this, but if you want to find all the values of all the attributes of a webelement this is a pretty nifty way to do that with javascript in python:

everything = b.execute_script(
    'var element = arguments[0];'
    'var attributes = {};'
    'for (index = 0; index < element.attributes.length; ++index) {'
    '    attributes[element.attributes[index].name] = element.attributes[index].value };'
    'var properties = [];'
    'properties[0] = attributes;'
    'var element_text = element.textContent;'
    'properties[1] = element_text;'
    'var styles = getComputedStyle(element);'
    'var computed_styles = {};'
    'for (index = 0; index < styles.length; ++index) {'
    '    var value_ = styles.getPropertyValue(styles[index]);'
    '    computed_styles[styles[index]] = value_ };'
    'properties[2] = computed_styles;'
    'return properties;', element)

you can also get some extra data with element.__dict__.

I think this is about all the data you'd ever want to get from a webelement.

Form Submit jQuery does not work

The NUMBER ONE error is having ANYTHING with the reserved word submit as ID or NAME in your form.

If you plan to call .submit() on the form AND the form has submit as id or name on any form element, then you need to rename that form element, since the form’s submit method/handler is shadowed by the name/id attribute.


Several other things:

As mentioned, you need to submit the form using a simpler event than the jQuery one

BUT you also need to cancel the clicks on the links

Why, by the way, do you have two buttons? Since you use jQuery to submit the form, you will never know which of the two buttons were clicked unless you set a hidden field on click.

<form action="deletprofil.php" id="form_id" method="post">
  <div data-role="controlgroup" data-filter="true" data-input="#filterControlgroup-input">
  <button type="submit" value="1" class="ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Anlegen</button>
  <button type="submit" value="2" class="ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Bnlegen</button>
  </div>
</form> 

 $(function(){
    $("#NOlink, #OKlink").on("click", function(e) {
        e.preventDefault(); // cancel default action
        $("#popupDialog").popup('close');
        if (this.id=="OKlink") { 
          document.getElementById("form_id").submit(); // or $("#form_id")[0].submit();
        }
    });

    $('#form_id').on('submit', function(e){
      e.preventDefault();
      $("#popupDialog").popup('open');
    });
});    

Judging from your comments, I think you really want to do this:

<form action="deletprofil.php" id="form_id" method="post">
  <input type="hidden" id="whichdelete" name="whichdelete" value="" />
  <div data-role="controlgroup" data-filter="true" data-input="#filterControlgroup-input">
  <button type="button" value="1" class="delete ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Anlegen</button>
  <button type="button" value="2" class="delete ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Bnlegen</button>
  </div>
</form> 

 $(function(){
    $("#NOlink, #OKlink").on("click", function(e) {
        e.preventDefault(); // cancel default action
        $("#popupDialog").popup('close');
        if (this.id=="OKlink") { 
          // trigger the submit event, not the event handler
          document.getElementById("form_id").submit(); // or $("#form_id")[0].submit();
        }
    });
    $(".delete").on("click", function(e) {
        $("#whichdelete").val(this.value);
    });
    $('#form_id').on('submit', function(e){
      e.preventDefault();
      $("#popupDialog").popup('open');
    });
});  

Button Width Match Parent

This is working for me in a self contained widget.

  Widget signinButton() {
    return ButtonTheme(
      minWidth: double.infinity,
      child: new FlatButton(
        onPressed: () {},
        color: Colors.green[400],
        textColor: Colors.white,
        child: Text('Flat Button'),
      ),
    );
  }

// It can then be used in a class that contains a widget tree.

How to check if internet connection is present in Java?

This code should do the job reliably.

Note that when using the try-with-resources statement we don't need to close the resources.

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class InternetAvailabilityChecker
{
    public static boolean isInternetAvailable() throws IOException
    {
        return isHostAvailable("google.com") || isHostAvailable("amazon.com")
                || isHostAvailable("facebook.com")|| isHostAvailable("apple.com");
    }

    private static boolean isHostAvailable(String hostName) throws IOException
    {
        try(Socket socket = new Socket())
        {
            int port = 80;
            InetSocketAddress socketAddress = new InetSocketAddress(hostName, port);
            socket.connect(socketAddress, 3000);

            return true;
        }
        catch(UnknownHostException unknownHost)
        {
            return false;
        }
    }
}

Are HTTP cookies port specific?

The current cookie specification is RFC 6265, which replaces RFC 2109 and RFC 2965 (both RFCs are now marked as "Historic") and formalizes the syntax for real-world usages of cookies. It clearly states:

  1. Introduction

...

For historical reasons, cookies contain a number of security and privacy infelicities. For example, a server can indicate that a given cookie is intended for "secure" connections, but the Secure attribute does not provide integrity in the presence of an active network attacker. Similarly, cookies for a given host are shared across all the ports on that host, even though the usual "same-origin policy" used by web browsers isolates content retrieved via different ports.

And also:

8.5. Weak Confidentiality

Cookies do not provide isolation by port. If a cookie is readable by a service running on one port, the cookie is also readable by a service running on another port of the same server. If a cookie is writable by a service on one port, the cookie is also writable by a service running on another port of the same server. For this reason, servers SHOULD NOT both run mutually distrusting services on different ports of the same host and use cookies to store security sensitive information.

How to write LaTeX in IPython Notebook?

You can choose a cell to be markdown, then write latex code which gets interpreted by mathjax, as one of the responders say above.

Alternatively, Latex section of the iPython notebook tutorial explains this well.

You can either do:

from IPython.display import Latex
Latex(r"""\begin{eqnarray}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0 
\end{eqnarray}""")

or do this:

%%latex
\begin{align}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{align}

More info found in this link

Numpy - add row to array

I use numpy.insert(arr, i, the_object_to_be_added, axis) in order to insert object_to_be_added at the i'th row(axis=0) or column(axis=1)

import numpy as np

a = np.array([[1, 2, 3], [5, 4, 6]])
# array([[1, 2, 3],
#        [5, 4, 6]])

np.insert(a, 1, [55, 66], axis=1)
# array([[ 1, 55,  2,  3],
#        [ 5, 66,  4,  6]])

np.insert(a, 2, [50, 60, 70], axis=0)
# array([[ 1,  2,  3],
#        [ 5,  4,  6],
#        [50, 60, 70]])

Too old discussion, but I hope it helps someone.

rand() between 0 and 1

This is the right way:

double randd() {
  return (double)rand() / ((double)RAND_MAX + 1);
}

or

double randd() {
  return (double)rand() / (RAND_MAX + 1.0);
}

How to search in a List of Java object

I modifie this list and add a List to the samples try this

Pseudocode

Sample {
   List<String> values;
   List<String> getList() {
   return values}
}



for(Sample s : list) {
   if(s.getString.getList.contains("three") {
      return s;
   }
}

How to create .ipa file using Xcode?

In Xcode Version 10.0


  1. Go to Window -> Organizer
  2. Then select your app archive from archives
  3. Then click the "Distribute App" button on right panel

enter image description here

  1. Then follow the below steps

Step 1

enter image description here

Step 2

enter image description here

Step 3

enter image description here

Step 4

enter image description here

Step 5

enter image description here

Step 6 : Finally select the place you want to save the .ipa file

enter image description here

In Xcode Version 9.2


  1. Go to Window -> Organizer
  2. Then select your app archive from archives
  3. Then click the "Upload to App Store" button on right panel
  4. Then follow the following steps

Step 1 enter image description here

Step 2 enter image description here

Step 3 enter image description here

Step 4 Finally select the place you want to save the .ipa file

enter image description here

JavaScript style.display="none" or jQuery .hide() is more efficient?

Efficiency isn't going to matter for something like this in 99.999999% of situations. Do whatever is easier to read and or maintain.

In my apps I usually rely on classes to provide hiding and showing, for example .addClass('isHidden')/.removeClass('isHidden') which would allow me to animate things with CSS3 if I wanted to. It provides more flexibility.

Is there an ignore command for git like there is for svn?

I hope it's not too late.

If you are on Windows you can just do the following to create a .gitignore file

echo name_of_the_file_you_want_to_ignore.extension > .gitignore

In order to edit .gitignore you can run

notepad .gitignore

What does collation mean?

http://en.wikipedia.org/wiki/Collation

Collation is the assembly of written information into a standard order. (...) A collation algorithm such as the Unicode collation algorithm defines an order through the process of comparing two given character strings and deciding which should come before the other.

How do I remove all .pyc files from a project?

First run:

find . -type f -name "*.py[c|o]" -exec rm -f {} +

Then add:

export PYTHONDONTWRITEBYTECODE=1

To ~/.profile

SQL Server 2000: How to exit a stored procedure?

This seems like a lot of code but the best way i've found to do it.

    ALTER PROCEDURE Procedure
    AS

    BEGIN TRY
        EXEC AnotherProcedure
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMessage NVARCHAR(4000);
        DECLARE @ErrorSeverity INT;
        DECLARE @ErrorState INT;

        SELECT 
            @ErrorMessage = ERROR_MESSAGE(),
            @ErrorSeverity = ERROR_SEVERITY(),
            @ErrorState = ERROR_STATE();

        RAISERROR (@ErrorMessage, -- Message text.
                   @ErrorSeverity, -- Severity.
                   @ErrorState -- State.
                   );
        RETURN --this forces it out
    END CATCH

--Stuff here that you do not want to execute if the above failed.    

    END --end procedure

What is the size of an enum in C?

While the previous answers are correct, some compilers have options to break the standard and use the smallest type that will contain all values.

Example with GCC (documentation in the GCC Manual):

enum ord {
    FIRST = 1,
    SECOND,
    THIRD
} __attribute__ ((__packed__));
STATIC_ASSERT( sizeof(enum ord) == 1 )

Moment js date time comparison

It is important that your datetime is in the correct ISO format when using any of the momentjs queries: isBefore, isAfter, isSameOrBefore, isSameOrAfter, isBetween

So instead of 2014-03-24T01:14:000, your datetime should be either:

2014-03-24T01:14:00 or 2014-03-24T01:14:00.000Z

otherwise you may receive the following deprecation warning and the condition will evaluate to false:

Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.

_x000D_
_x000D_
// https://momentjs.com/docs/#/query/_x000D_
_x000D_
const dateIsAfter = moment('2014-03-24T01:15:00.000Z').isAfter(moment('2014-03-24T01:14:00.000Z'));_x000D_
_x000D_
const dateIsSame = moment('2014-03-24T01:15:00.000Z').isSame(moment('2014-03-24T01:14:00.000Z'));_x000D_
_x000D_
const dateIsBefore = moment('2014-03-24T01:15:00.000Z').isBefore(moment('2014-03-24T01:14:00.000Z'));_x000D_
_x000D_
console.log(`Date is After: ${dateIsAfter}`);_x000D_
console.log(`Date is Same: ${dateIsSame}`);_x000D_
console.log(`Date is Before: ${dateIsBefore}`);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.0/moment.min.js"_x000D_
></script>
_x000D_
_x000D_
_x000D_

How to call two methods on button's onclick method in HTML or JavaScript?

As stated by Harry Joy, you can do it on the onclick attr like so:

<input type="button" onclick="func1();func2();" value="Call2Functions" />

Or, in your JS like so:

document.getElementById( 'Call2Functions' ).onclick = function()
{
    func1();
    func2();
};

Or, if you are assigning an onclick programmatically, and aren't sure if a previous onclick existed (and don't want to overwrite it):

var Call2FunctionsEle = document.getElementById( 'Call2Functions' ),
    func1 = Call2FunctionsEle.onclick;

Call2FunctionsEle.onclick = function()
{
    if( typeof func1 === 'function' )
    {
        func1();
    }
    func2();
};

If you need the functions run in scope of the element which was clicked, a simple use of apply could be made:

document.getElementById( 'Call2Functions' ).onclick = function()
{
    func1.apply( this, arguments );
    func2.apply( this, arguments );
};

typedef fixed length array

To use the array type properly as a function argument or template parameter, make a struct instead of a typedef, then add an operator[] to the struct so you can keep the array like functionality like so:

typedef struct type24 {
  char& operator[](int i) { return byte[i]; }
  char byte[3];
} type24;

type24 x;
x[2] = 'r';
char c = x[2];

Count number of objects in list

Advice for R newcomers like me : beware, the following is a list of a single object :

> mylist <- list (1:10)
> length (mylist)
[1] 1

In such a case you are not looking for the length of the list, but of its first element :

> length (mylist[[1]])
[1] 10

This is a "true" list :

> mylist <- list(1:10, rnorm(25), letters[1:3])
> length (mylist)
[1] 3

Also, it seems that R considers a data.frame as a list :

> df <- data.frame (matrix(0, ncol = 30, nrow = 2))
> typeof (df)
[1] "list"

In such a case you may be interested in ncol() and nrow() rather than length() :

> ncol (df)
[1] 30
> nrow (df)
[1] 2

Though length() will also work (but it's a trick when your data.frame has only one column) :

> length (df)
[1] 30
> length (df[[1]])
[1] 2

MAX function in where clause mysql

Do you want the first and last name of the row with the largest id?

If so (and you were missing a FROM clause):

SELECT firstname, lastname, id
FROM foo
ORDER BY id DESC
LIMIT 1;

Multiple conditions in an IF statement in Excel VBA

In VBA we can not use if jj = 5 or 6 then we must use if jj = 5 or jj = 6 then

maybe this:

If inputWks.Range("d9") > 0 And (inputWks.Range("d11") = "Restricted_Expenditure" Or inputWks.Range("d11") = "Unrestricted_Expenditure") Then

How to embed a Facebook page's feed into my website

The Like Box/ Page plugin is basically an iframe and ugly :D

So I created my own free plugin that I call Famax plugin to display FanPage feeds. It's similar to the like box but has a better UI and is more customizable.

Also because the Like box is shown in an iframe with a fixed width and height etc, its not really responsive.

How to query GROUP BY Month in a Year

I would be inclined to include the year in the output. One way:

select to_char(DATE_CREATED, 'YYYY-MM'), sum(Num_of_Pictures)
from pictures_table
group by to_char(DATE_CREATED, 'YYYY-MM')
order by 1

Another way (more standard SQL):

select extract(year from date_created) as yr, extract(month from date_created) as mon,
       sum(Num_of_Pictures)
from pictures_table
group by extract(year from date_created), extract(month from date_created)
order by yr, mon;

Remember the order by, since you presumably want these in order, and there is no guarantee about the order that rows are returned in after a group by.

Defining TypeScript callback type

To go one step further, you could declare a type pointer to a function signature like:

interface myCallbackType { (myArgument: string): void }

and use it like this:

public myCallback : myCallbackType;

Splitting on first occurrence

You can also use str.partition:

>>> text = "123mango abcd mango kiwi peach"

>>> text.partition("mango")
('123', 'mango', ' abcd mango kiwi peach')

>>> text.partition("mango")[-1]
' abcd mango kiwi peach'

>>> text.partition("mango")[-1].lstrip()  # if whitespace strip-ing is needed
'abcd mango kiwi peach'

The advantage of using str.partition is that it's always gonna return a tuple in the form:

(<pre>, <separator>, <post>)

So this makes unpacking the output really flexible as there's always going to be 3 elements in the resulting tuple.

What is HTML5 ARIA?

What is ARIA?

ARIA emerged as a way to address the accessibility problem of using a markup language intended for documents, HTML, to build user interfaces (UI). HTML includes a great many features to deal with documents (P, h3,UL,TABLE) but only basic UI elements such as A, INPUT and BUTTON. Windows and other operating systems support APIs that allow (Assistive Technology) AT to access the functionality of UI controls. Internet Explorer and other browsers map the native HTML elements to the accessibility API, but the html controls are not as rich as the controls common on desktop operating systems, and are not enough for modern web applications Custom controls can extend html elements to provide the rich UI needed for modern web applications. Before ARIA, the browser had no way to expose this extra richness to the accessibility API or AT. The classic example of this issue is adding a click handler to an image. It creates what appears to be a clickable button to a mouse user, but is still just an image to a keyboard or AT user.

The solution was to create a set of attributes that allow developers to extend HTML with UI semantics. The ARIA term for a group of HTML elements that have custom functionality and use ARIA attributes to map these functions to accessibility APIs is a “Widget. ARIA also provides a means for authors to document the role of content itself, which in turn, allows AT to construct alternate navigation mechanisms for the content that are much easier to use than reading the full text or only iterating over a list of the links.

It is important to remember that in simple cases, it is much preferred to use native HTML controls and style them rather than using ARIA. That is don’t reinvent wheels, or checkboxes, if you don’t have to.

Fortunately, ARIA markup can be added to existing sites without changing the behavior for mainstream users. This greatly reduces the cost of modifying and testing the website or application.

How to handle login pop up window using Selenium WebDriver?

This is a solution for Python based selenium, after going through the source code (here). I found this 3 steps as useful.

obj = driver.switch_to.alert
obj.send_keys(keysToSend="username\ue004password")
obj.accept()

Here \ue004 is the value for TAB which you can find in Keys class in the source code.

I guess the same approach can be used in JAVA as well but not sure.

Can you center a Button in RelativeLayout?

Arcadia, just try the code below. There are several ways to get the result you're looking for, this is one of the easier ways.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relative_layout"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:gravity="center">

    <Button
        android:id="@+id/the_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Centered Button"/>
</RelativeLayout>

Setting the gravity of the RelativeLayout itself will affect all of the objects placed inside of it. In this case, it's just the button. You can use any of the gravity settings here, of course (e.g. center_horizontal, top, right, and so on).

You could also use this code below:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relative_layout"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent">

    <Button
        android:id="@+id/the_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Centered Button"
        android:layout_centerInParent="true"/>
</RelativeLayout>

Adding external library in Android studio

There are some changes in new gradle 4.1

instead of compile we should use implementation

implementation 'com.android.support:appcompat-v7:26.0.0'

How to tell git to use the correct identity (name and email) for a given project?

You need to use the local set command below:

local set

git config user.email [email protected]
git config user.name 'Mahmoud Zalt'

local get

git config --get user.email
git config --get user.name

The local config file is in the project directory: .git/config.

global set

git config --global user.email [email protected]
git config --global user.name 'Mahmoud Zalt'

global get

git config --global --get user.email
git config --global --get user.name

The global config file in in your home directory: ~/.gitconfig.

Remember to quote blanks, etc, for example: 'FirstName LastName'

Android Paint: .measureText() vs .getTextBounds()

DISCLAIMER: This solution is not 100% accurate in terms of determining the minimal width.

I was also figuring out how to measure text on a canvas. After reading the great post from mice i had some problems on how to measure multiline text. There is no obvious way from these contributions but after some research i cam across the StaticLayout class. It allows you to measure multiline text (text with "\n") and configure much more properties of your text via the associated Paint.

Here is a snippet showing how to measure multiline text:

private StaticLayout measure( TextPaint textPaint, String text, Integer wrapWidth ) {
    int boundedWidth = Integer.MAX_VALUE;
    if (wrapWidth != null && wrapWidth > 0 ) {
       boundedWidth = wrapWidth;
    }
    StaticLayout layout = new StaticLayout( text, textPaint, boundedWidth, Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false );
    return layout;
}

The wrapwitdh is able to determin if you want to limit your multiline text to a certain width.

Since the StaticLayout.getWidth() only returns this boundedWidth you have to take another step to get the maximum width required by your multiline text. You are able to determine each lines width and the max width is the highest line width of course:

private float getMaxLineWidth( StaticLayout layout ) {
    float maxLine = 0.0f;
    int lineCount = layout.getLineCount();
    for( int i = 0; i < lineCount; i++ ) {
        if( layout.getLineWidth( i ) > maxLine ) {
            maxLine = layout.getLineWidth( i );
        }
    }
    return maxLine;
}

What is the difference between require_relative and require in Ruby?

require_relative is a convenient subset of require

require_relative('path')

equals:

require(File.expand_path('path', File.dirname(__FILE__)))

if __FILE__ is defined, or it raises LoadError otherwise.

This implies that:

  • require_relative 'a' and require_relative './a' require relative to the current file (__FILE__).

    This is what you want to use when requiring inside your library, since you don't want the result to depend on the current directory of the caller.

  • eval('require_relative("a.rb")') raises LoadError because __FILE__ is not defined inside eval.

    This is why you can't use require_relative in RSpec tests, which get evaled.

The following operations are only possible with require:

  • require './a.rb' requires relative to the current directory

  • require 'a.rb' uses the search path ($LOAD_PATH) to require. It does not find files relative to current directory or path.

    This is not possible with require_relative because the docs say that path search only happens when "the filename does not resolve to an absolute path" (i.e. starts with / or ./ or ../), which is always the case for File.expand_path.

The following operation is possible with both, but you will want to use require as it is shorter and more efficient:

  • require '/a.rb' and require_relative '/a.rb' both require the absolute path.

Reading the source

When the docs are not clear, I recommend that you take a look at the sources (toggle source in the docs). In some cases, it helps to understand what is going on.

require:

VALUE rb_f_require(VALUE obj, VALUE fname) {
  return rb_require_safe(fname, rb_safe_level());
}

require_relative:

VALUE rb_f_require_relative(VALUE obj, VALUE fname) {
    VALUE base = rb_current_realfilepath();
    if (NIL_P(base)) {
        rb_loaderror("cannot infer basepath");
    }
    base = rb_file_dirname(base);
    return rb_require_safe(rb_file_absolute_path(fname, base), rb_safe_level());
}

This allows us to conclude that

require_relative('path')

is the same as:

require(File.expand_path('path', File.dirname(__FILE__)))

because:

rb_file_absolute_path   =~ File.expand_path
rb_file_dirname1        =~ File.dirname
rb_current_realfilepath =~ __FILE__

Push method in React Hooks (useState)?

if you want to push after specific index you can do as below:

   const handleAddAfterIndex = index => {
       setTheArray(oldItems => {
            const copyItems = [...oldItems];
            const finalItems = [];
            for (let i = 0; i < copyItems.length; i += 1) {
                if (i === index) {
                    finalItems.push(copyItems[i]);
                    finalItems.push(newItem);
                } else {
                    finalItems.push(copyItems[i]);
                }
            }
            return finalItems;
        });
    };

Prevent onmouseout when hovering child element of the parent absolute div WITHOUT jQuery

For a simpler pure CSS solution that works in most cases, one could remove children's pointer-events by setting them to none

.parent * {
     pointer-events: none;
}

Browser support: IE11+

Python non-greedy regexes

As the others have said using the ? modifier on the * quantifier will solve your immediate problem, but be careful, you are starting to stray into areas where regexes stop working and you need a parser instead. For instance, the string "(foo (bar)) baz" will cause you problems.

How do I fix a compilation error for unhandled exception on call to Thread.sleep()?

Thread.sleep can throw an InterruptedException which is a checked exception. All checked exceptions must either be caught and handled or else you must declare that your method can throw it. You need to do this whether or not the exception actually will be thrown. Not declaring a checked exception that your method can throw is a compile error.

You either need to catch it:

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
    // handle the exception...        
    // For example consider calling Thread.currentThread().interrupt(); here.
}

Or declare that your method can throw an InterruptedException:

public static void main(String[]args) throws InterruptedException

Related

Loop through JSON object List

This will work!

$(document).ready(function ()
    {
        $.ajax(
            {
            type: 'POST',
            url: "/Home/MethodName",
            success: function (data) {
                //data is the string that the method returns in a json format, but in string
                var jsonData = JSON.parse(data); //This converts the string to json

                for (var i = 0; i < jsonData.length; i++) //The json object has lenght
                {
                    var object = jsonData[i]; //You are in the current object
                    $('#olListId').append('<li class="someclass>' + object.Atributte  + '</li>'); //now you access the property.

                }

                /* JSON EXAMPLE
                [{ "Atributte": "value" }, 
                { "Atributte": "value" }, 
                { "Atributte": "value" }]
                */
            }
        });
    });

The main thing about this is using the property exactly the same as the attribute of the JSON key-value pair.

SELECT INTO Variable in MySQL DECLARE causes syntax error?

In the end a stored procedure was the solution for my problem. Here´s what helped:

DELIMITER //
CREATE PROCEDURE test ()
  BEGIN
  DECLARE myvar DOUBLE;
  SELECT somevalue INTO myvar FROM mytable WHERE uid=1;
  SELECT myvar;
  END
  //

DELIMITER ;

call test ();

Rename Pandas DataFrame Index

You can also use Index.set_names as follows:

In [25]: x = pd.DataFrame({'year':[1,1,1,1,2,2,2,2],
   ....:                   'country':['A','A','B','B','A','A','B','B'],
   ....:                   'prod':[1,2,1,2,1,2,1,2],
   ....:                   'val':[10,20,15,25,20,30,25,35]})

In [26]: x = x.set_index(['year','country','prod']).squeeze()

In [27]: x
Out[27]: 
year  country  prod
1     A        1       10
               2       20
      B        1       15
               2       25
2     A        1       20
               2       30
      B        1       25
               2       35
Name: val, dtype: int64
In [28]: x.index = x.index.set_names('foo', level=1)

In [29]: x
Out[29]: 
year  foo  prod
1     A    1       10
           2       20
      B    1       15
           2       25
2     A    1       20
           2       30
      B    1       25
           2       35
Name: val, dtype: int64

Import Excel spreadsheet columns into SQL Server database

Excel + SQLCMD + Perl = exceltomssqlinsert

and you can use your Excel as frond-end to MSSQL db ... Note the truncate table at the beginning of each generated sql insert file ...

How to determine MIME type of file in android?

MimeTypeMap may not recognize some file extensions like flv,mpeg,3gpp,cpp. So you need to think how to expand the MimeTypeMap for maintaining your code. Here is such an example.

http://grepcode.com/file/repo1.maven.org/maven2/com.google.okhttp/okhttp/20120626/libcore/net/MimeUtils.java#MimeUtils

Plus, here is a complete list of mime types

http: //www.sitepoint.com/web-foundations/mime-types-complete-list/

Android: Proper Way to use onBackPressed() with Toast

You can also use onBackPressed by following ways using customized Toast:

enter image description here

customized_toast.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/txtMessage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:drawableStart="@drawable/ic_white_exit_small"
    android:drawableLeft="@drawable/ic_white_exit_small"
    android:drawablePadding="8dp"
    android:paddingTop="8dp"
    android:paddingBottom="8dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:gravity="center"
    android:textColor="@android:color/white"
    android:textSize="16sp"
    android:text="Press BACK again to exit.."
    android:background="@drawable/curve_edittext"/>

MainActivity.java

@Override
public void onBackPressed() {

    if (doubleBackToExitPressedOnce) {
        android.os.Process.killProcess(Process.myPid());
        System.exit(1);
        return;
    }

    this.doubleBackToExitPressedOnce = true;
    Toast toast = new Toast(Dashboard.this);
    View view = getLayoutInflater().inflate(R.layout.toast_view,null);
    toast.setView(view);
    toast.setDuration(Toast.LENGTH_SHORT);
    int margin = getResources().getDimensionPixelSize(R.dimen.toast_vertical_margin);
    toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_VERTICAL, 0, margin);
    toast.show();

    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            doubleBackToExitPressedOnce=false;
        }
    }, 2000);
}

HashMap to return default value for non-found keys?

Use Commons' DefaultedMap if you don't feel like reinventing the wheel, e.g.,

Map<String, String> map = new DefaultedMap<>("[NO ENTRY FOUND]");
String surname = map.get("Surname"); 
// surname == "[NO ENTRY FOUND]"

You can also pass in an existing map if you're not in charge of creating the map in the first place.

Should I use <i> tag for icons instead of <span>?

Why are they using <i> tag to display icons ?

Because it is:

  • Short
  • i stands for icon (although not in HTML)

Is it not a bad practice ?

Awful practice. It is a triumph of performance over semantics.

ORA-12154: TNS:could not resolve the connect identifier specified (PLSQL Developer)

I had the same issue with a VM running CentOS7 and Oracle 11GR2 accesible from Windows 7, the solution were weird, at my local machine the tnsnames pointing to the DB had a space before the service name, I just deleted the space and then I was able to connect.

A quick example.

Wrong tnsnames.

[this is a empty space]XE = (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = 127.0.0.1)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = XE) ) )

EXTPROC_CONNECTION_DATA = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC_FOR_XE)) ) (CONNECT_DATA = (SID = PLSExtProc) (PRESENTATION = RO) ) )

Right tnsnames.

XE = (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = 127.0.0.1)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = XE) ) )

EXTPROC_CONNECTION_DATA = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC_FOR_XE)) ) (CONNECT_DATA = (SID = PLSExtProc) (PRESENTATION = RO) ) )

Is it possible to set a timeout for an SQL query on Microsoft SQL server?

It sounds like more of an architectual issue, and any timeout/disconnect you can do would be more or less a band-aid. This has to be solved on SQL server side, by the way of read-only replica, transaction log shipping (to give you a read-only server to connect to), replication and such. Basically you give the DMZ sql server that heavy read can go to without killing stuff. This is very common. A well-designed SQL system won't be taken down by DDoS - that'd be like a car that dies if you step on the gas.

That said, if you are at the liberty to change the code, you could guesstimate if the query is too heavy and you could either reject or return only X rows in your stored procedure. If you are mated to some reporting tool and such and can't control the SELECT it generates, you could point it to a view and then do the safety valve in the view.

Also, if up-to-the-minute freshness isn't critical and you could compromise on that, like monthly sales data, then compiling a physical table of complex joins by job to avoid complex joins might do the trick - that way everything would be sub-second per query.

It entirely depends on what you are doing, but there is always a solution. Sometimes it takes extra coding to optimize it, sometimes it takes extra money to get you the secondary read-only DB, sometimes it needs time and attention in index tuning.

So it entirely depends, but I'd start with "what can I compromise? what can I change?" and go from there.

Java : How to determine the correct charset encoding of a stream

You can certainly validate the file for a particular charset by decoding it with a CharsetDecoder and watching out for "malformed-input" or "unmappable-character" errors. Of course, this only tells you if a charset is wrong; it doesn't tell you if it is correct. For that, you need a basis of comparison to evaluate the decoded results, e.g. do you know beforehand if the characters are restricted to some subset, or whether the text adheres to some strict format? The bottom line is that charset detection is guesswork without any guarantees.

When to catch java.lang.Error?

If you are crazy enough to be creating a new unit test framework, your test runner will probably need to catch java.lang.AssertionError thrown by any test cases.

Otherwise, see other answers.

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

For Intellij Idea sometime localhost.log file generated at different location. For e.g. you can find it at homedirectory\ .IntelliJIdea14\system\tomcat.

IF you are using spring then start ur server in debug mode and put debug point in catch block of org.springframework.context.support.AbstractApplicationContext's refresh() method. If bean creation fails you would be able to see the exception.

Check whether specific radio button is checked

$("input[@name='<%=test2.ClientID%>']:checked");

use this and here ClientID fetch random id created by .net.

How do I get the number of elements in a list?

The len() function can be used with several different types in Python - both built-in types and library types. For example:

>>> len([1, 2, 3])
3

Pyspark: display a spark data frame in a table format

The show method does what you're looking for.

For example, given the following dataframe of 3 rows, I can print just the first two rows like this:

df = sqlContext.createDataFrame([("foo", 1), ("bar", 2), ("baz", 3)], ('k', 'v'))
df.show(n=2)

which yields:

+---+---+
|  k|  v|
+---+---+
|foo|  1|
|bar|  2|
+---+---+
only showing top 2 rows

laravel-5 passing variable to JavaScript

$langs = Language::all()->toArray();
return View::make('NAATIMockTest.Admin.Language.index', [
    'langs' => $langs
]);

then in view

<script type="text/javascript">
    var langs = {{json_encode($langs)}};
    console.log(langs);
</script>

Its not pretty tho

Display number with leading zeros

The Pythonic way to do this:

str(number).rjust(string_width, fill_char)

This way, the original string is returned unchanged if its length is greater than string_width. Example:

a = [1, 10, 100]
for num in a:
    print str(num).rjust(2, '0')

Results:

01
10
100

How to handle command-line arguments in PowerShell

You are reinventing the wheel. Normal PowerShell scripts have parameters starting with -, like script.ps1 -server http://devserver

Then you handle them in param section in the beginning of the file.

You can also assign default values to your params, read them from console if not available or stop script execution:

 param (
    [string]$server = "http://defaultserver",
    [Parameter(Mandatory=$true)][string]$username,
    [string]$password = $( Read-Host "Input password, please" )
 )

Inside the script you can simply

write-output $server

since all parameters become variables available in script scope.

In this example, the $server gets a default value if the script is called without it, script stops if you omit the -username parameter and asks for terminal input if -password is omitted.

Update: You might also want to pass a "flag" (a boolean true/false parameter) to a PowerShell script. For instance, your script may accept a "force" where the script runs in a more careful mode when force is not used.

The keyword for that is [switch] parameter type:

 param (
    [string]$server = "http://defaultserver",
    [string]$password = $( Read-Host "Input password, please" ),
    [switch]$force = $false
 )

Inside the script then you would work with it like this:

if ($force) {
  //deletes a file or does something "bad"
}

Now, when calling the script you'd set the switch/flag parameter like this:

.\yourscript.ps1 -server "http://otherserver" -force

If you explicitly want to state that the flag is not set, there is a special syntax for that

.\yourscript.ps1 -server "http://otherserver" -force:$false

Links to relevant Microsoft documentation (for PowerShell 5.0; tho versions 3.0 and 4.0 are also available at the links):

How to run a method every X seconds

The solution you will use really depends on how long you need to wait between each execution of your function.

If you are waiting for longer than 10 minutes, I would suggest using AlarmManager.

// Some time when you want to run
Date when = new Date(System.currentTimeMillis());

try {
    Intent someIntent = new Intent(someContext, MyReceiver.class); // intent to be launched

    // Note: this could be getActivity if you want to launch an activity
    PendingIntent pendingIntent = PendingIntent.getBroadcast(
        context,
        0, // id (optional)
        someIntent, // intent to launch
        PendingIntent.FLAG_CANCEL_CURRENT // PendingIntent flag
    );

    AlarmManager alarms = (AlarmManager) context.getSystemService(
        Context.ALARM_SERVICE
    );

    alarms.setRepeating(
        AlarmManager.RTC_WAKEUP,
        when.getTime(),
        AlarmManager.INTERVAL_FIFTEEN_MINUTES,
        pendingIntent
    );
} catch(Exception e) {
    e.printStackTrace();
}

Once you have broadcasted the above Intent, you can receive your Intent by implementing a BroadcastReceiver. Note that this will need to be registered either in your application manifest or via the context.registerReceiver(receiver, intentFilter); method. For more information on BroadcastReceiver's please refer to the official documentation..

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent)
    {
        System.out.println("MyReceiver: here!") // Do your work here
    }
}

If you are waiting for shorter than 10 minutes then I would suggest using a Handler.

final Handler handler = new Handler();
final int delay = 1000; // 1000 milliseconds == 1 second

handler.postDelayed(new Runnable() {
    public void run() {
        System.out.println("myHandler: here!"); // Do your work here
        handler.postDelayed(this, delay);
    }
}, delay);

How can I test that a variable is more than eight characters in PowerShell?

Use the length property of the [String] type:

if ($dbUserName.length -gt 8) {
    Write-Output "Please enter more than 8 characters."
    $dbUserName = Read-Host "Re-enter database username"
}

Please note that you have to use -gt instead of > in your if condition. PowerShell uses the following comparison operators to compare values and test conditions:

  • -eq = equals
  • -ne = not equals
  • -lt = less than
  • -gt = greater than
  • -le = less than or equals
  • -ge = greater than or equals

Git status shows files as changed even though contents are the same

Have you changed the mode of the files? I did it on my machine and the local dev machine had 777 given to all the files whereas the repo had 755 which showed every file as modified. I did git diff and it showed the old mode and new mode are different. If that is the problem then you can easily ignore them by git config core.filemode false
Cheers

How to use a wildcard in the classpath to add multiple jars?

This works on Windows:

java -cp "lib/*" %MAINCLASS%

where %MAINCLASS% of course is the class containing your main method.

Alternatively:

java -cp "lib/*" -jar %MAINJAR%

where %MAINJAR% is the jar file to launch via its internal manifest.

Javascript String to int conversion

This is to do with JavaScript's + in operator - if a number and a string are "added" up, the number is converted into a string:

0 + 1; //1
'0' + 1; // '01'

To solve this, use the + unary operator, or use parseInt():

+'0' + 1; // 1
parseInt('0', 10) + 1; // 1

The unary + operator converts it into a number (however if it's a decimal it will retain the decimal places), and parseInt() is self-explanatory (converts into number, ignoring decimal places).

The second argument is necessary for parseInt() to use the correct base when leading 0s are placed:

parseInt('010'); // 8 in older browsers, 10 in newer browsers
parseInt('010', 10); // always 10 no matter what

There's also parseFloat() if you need to convert decimals in strings to their numeric value - + can do that too but it behaves slightly differently: that's another story though.

Change the default editor for files opened in the terminal? (e.g. set it to TextEdit/Coda/Textmate)

For anyone coming here in 2018:

  • go to iTerm -> Preferences -> Profiles -> Advanced -> Semantic History
  • from the dropdown, choose Open with Editor and from the right dropdown choose your editor of choice

Display string multiple times

Python 2.x:

print '-' * 3

Python 3.x:

print('-' * 3)

git pull error "The requested URL returned error: 503 while accessing"

A 50X error is an internal server error. There's nothing wrong on your end, but something's up on the server's end.

http://www.checkupdown.com/status/E503.html

The Web server (running the Web site) is currently unable to handle the HTTP request due to a temporary overloading or maintenance of the server. The implication is that this is a temporary condition which will be alleviated after some delay.

Just be patient and wait. :-)

How to properly create composite primary keys - MYSQL

CREATE  TABLE `mom`.`sec_subsection` (

  `idsec_sub` INT(11) NOT NULL ,

  `idSubSections` INT(11) NOT NULL ,

  PRIMARY KEY (`idsec_sub`, `idSubSections`) 

);

What is the Swift equivalent of isEqualToString in Objective-C?

In Swift, the == operator is equivalent to Objective C's isEqual: method (it calls the isEqual method instead of just comparing pointers, and there's a new === method for testing that the pointers are the same), so you can just write this as:

if username == "" || password == ""
{
    println("Sign in failed. Empty character")
}

Remove item from list based on condition

prods.Remove(prods.Single(p=>p.ID == 1));

you can't modify collection in foreach, as Vincent suggests