Programs & Examples On #Performance estimation

UnicodeDecodeError when reading CSV file in Pandas with Python

You can try with:

df = pd.read_csv('./file_name.csv', encoding='gbk')

"The semaphore timeout period has expired" error for USB connection

I had this problem as well on two different Windows computers when communicating with a Arduino Leonardo. The reliable solution was:

  • Find the COM port in device manager and open the device properties.
  • Open the "Port Settings" tab, and click the advanced button.
  • There, uncheck the box "Use FIFO buffers (required 16550 compatible UART), and press OK.

Unfortunately, I don't know what this feature does, or how it affects this issue. After several PC restarts and a dozen device connection cycles, this is the only thing that reliably fixed the issue.

Format an Integer using Java String Format

String.format("%03d", 1)  // => "001"
//              ¦¦¦   +-- print the number one
//              ¦¦+------ ... as a decimal integer
//              ¦+------- ... minimum of 3 characters wide
//              +-------- ... pad with zeroes instead of spaces

See java.util.Formatter for more information.

Text blinking jQuery

$.fn.blink = function (delay) {
  delay = delay || 500;
  return this.each(function () {
    var element = $(this);
    var interval = setInterval(function () {
      element.fadeOut((delay / 3), function() {
        element.fadeIn(delay / 3);
      })
    }, delay);
    element.data('blinkInterval', interval);
  });
};

$.fn.stopBlinking = function() {
  return this.each(function() {
    var element = $(this);
    element.stop(true, true);
    clearInterval(element.data('blinkInterval'));
  });
};

How to allow Cross domain request in apache2

OS=GNU/Linux Debian
Httpd=Apache/2.4.10

Change in /etc/apache2/apache2.conf

<Directory /var/www/html>
     Order Allow,Deny
     Allow from all
     AllowOverride all
     Header set Access-Control-Allow-Origin "*"
</Directory>

Add/activate module

 a2enmod headers 

Restart service

/etc/init.d/apache2 restart

What does "SyntaxError: Missing parentheses in call to 'print'" mean in Python?

This error message means that you are attempting to use Python 3 to follow an example or run a program that uses the Python 2 print statement:

print "Hello, World!"

The statement above does not work in Python 3. In Python 3 you need to add parentheses around the value to be printed:

print("Hello, World!")

“SyntaxError: Missing parentheses in call to 'print'” is a new error message that was added in Python 3.4.2 primarily to help users that are trying to follow a Python 2 tutorial while running Python 3.

In Python 3, printing values changed from being a distinct statement to being an ordinary function call, so it now needs parentheses:

>>> print("Hello, World!")
Hello, World!

In earlier versions of Python 3, the interpreter just reports a generic syntax error, without providing any useful hints as to what might be going wrong:

>>> print "Hello, World!"
  File "<stdin>", line 1
    print "Hello, World!"
                        ^
SyntaxError: invalid syntax

As for why print became an ordinary function in Python 3, that didn't relate to the basic form of the statement, but rather to how you did more complicated things like printing multiple items to stderr with a trailing space rather than ending the line.

In Python 2:

>>> import sys
>>> print >> sys.stderr, 1, 2, 3,; print >> sys.stderr, 4, 5, 6
1 2 3 4 5 6

In Python 3:

>>> import sys
>>> print(1, 2, 3, file=sys.stderr, end=" "); print(4, 5, 6, file=sys.stderr)
1 2 3 4 5 6

Starting with the Python 3.6.3 release in September 2017, some error messages related to the Python 2.x print syntax have been updated to recommend their Python 3.x counterparts:

>>> print "Hello!"
  File "<stdin>", line 1
    print "Hello!"
                 ^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello!")?

Since the "Missing parentheses in call to print" case is a compile time syntax error and hence has access to the raw source code, it's able to include the full text on the rest of the line in the suggested replacement. However, it doesn't currently try to work out the appropriate quotes to place around that expression (that's not impossible, just sufficiently complicated that it hasn't been done).

The TypeError raised for the right shift operator has also been customised:

>>> print >> sys.stderr
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for >>: 'builtin_function_or_method' and '_io.TextIOWrapper'. Did you mean "print(<message>, file=<output_stream>)"?

Since this error is raised when the code runs, rather than when it is compiled, it doesn't have access to the raw source code, and hence uses meta-variables (<message> and <output_stream>) in the suggested replacement expression instead of whatever the user actually typed. Unlike the syntax error case, it's straightforward to place quotes around the Python expression in the custom right shift error message.

How to create a BKS (BouncyCastle) format Java Keystore that contains a client certificate chain

Detailed Step by Step instructions I followed to achieve this

  • Download bouncycastle JAR from http://repo2.maven.org/maven2/org/bouncycastle/bcprov-ext-jdk15on/1.46/bcprov-ext-jdk15on-1.46.jar or take it from the "doc" folder.
  • Configure BouncyCastle for PC using one of the below methods.
    • Adding the BC Provider Statically (Recommended)
      • Copy the bcprov-ext-jdk15on-1.46.jar to each
        • D:\tools\jdk1.5.0_09\jre\lib\ext (JDK (bundled JRE)
        • D:\tools\jre1.5.0_09\lib\ext (JRE)
        • C:\ (location to be used in env variable)
      • Modify the java.security file under
        • D:\tools\jdk1.5.0_09\jre\lib\security
        • D:\tools\jre1.5.0_09\lib\security
        • and add the following entry
          • security.provider.7=org.bouncycastle.jce.provider.BouncyCastleProvider
      • Add the following environment variable in "User Variables" section
        • CLASSPATH=%CLASSPATH%;c:\bcprov-ext-jdk15on-1.46.jar
    • Add bcprov-ext-jdk15on-1.46.jar to CLASSPATH of your project and Add the following line in your code
      • Security.addProvider(new BouncyCastleProvider());
  • Generate the Keystore using Bouncy Castle
    • Run the following command
      • keytool -genkey -alias myproject -keystore C:/myproject.keystore -storepass myproject -storetype BKS -provider org.bouncycastle.jce.provider.BouncyCastleProvider
    • This generates the file C:\myproject.keystore
    • Run the following command to check if it is properly generated or not
      • keytool -list -keystore C:\myproject.keystore -storetype BKS
  • Configure BouncyCastle for TOMCAT

    • Open D:\tools\apache-tomcat-6.0.35\conf\server.xml and add the following entry

      • <Connector port="8443" keystorePass="myproject" alias="myproject" keystore="c:/myproject.keystore" keystoreType="BKS" SSLEnabled="true" clientAuth="false" protocol="HTTP/1.1" scheme="https" secure="true" sslProtocol="TLS" sslImplementationName="org.bouncycastle.jce.provider.BouncyCastleProvider"/>
    • Restart the server after these changes.

  • Configure BouncyCastle for Android Client
    • No need to configure since Android supports Bouncy Castle Version 1.46 internally in the provided "android.jar".
    • Just implement your version of HTTP Client (MyHttpClient.java can be found below) and set the following in code
      • SSLSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    • If you don't do this, it gives an exception as below
      • javax.net.ssl.SSLException: hostname in certificate didn't match: <192.168.104.66> !=
    • In production mode, change the above code to
      • SSLSocketFactory.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);

MyHttpClient.java

package com.arisglobal.aglite.network;

import java.io.InputStream;
import java.security.KeyStore;

import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;

import com.arisglobal.aglite.activity.R;

import android.content.Context;

public class MyHttpClient extends DefaultHttpClient {

    final Context context;

    public MyHttpClient(Context context) {
        this.context = context;
    }

    @Override
    protected ClientConnectionManager createClientConnectionManager() {
        SchemeRegistry registry = new SchemeRegistry();

        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

        // Register for port 443 our SSLSocketFactory with our keystore to the ConnectionManager
        registry.register(new Scheme("https", newSslSocketFactory(), 443));
        return new SingleClientConnManager(getParams(), registry);
    }

    private SSLSocketFactory newSslSocketFactory() {
        try {
            // Get an instance of the Bouncy Castle KeyStore format
            KeyStore trusted = KeyStore.getInstance("BKS");

            // Get the raw resource, which contains the keystore with your trusted certificates (root and any intermediate certs)
            InputStream in = context.getResources().openRawResource(R.raw.aglite);
            try {
                // Initialize the keystore with the provided trusted certificates.
                // Also provide the password of the keystore
                trusted.load(in, "aglite".toCharArray());
            } finally {
                in.close();
            }

            // Pass the keystore to the SSLSocketFactory. The factory is responsible for the verification of the server certificate.
            SSLSocketFactory sf = new SSLSocketFactory(trusted);

            // Hostname verification from certificate
            // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            return sf;
        } catch (Exception e) {
            throw new AssertionError(e);
        }
    }
}

How to invoke the above code in your Activity class:

DefaultHttpClient client = new MyHttpClient(getApplicationContext());
HttpResponse response = client.execute(...);

Compile Views in ASP.NET MVC

Next release of ASP.NET MVC (available in January or so) should have MSBuild task that compiles views, so you might want to wait.

See announcement

Printing object properties in Powershell

# Json to object
$obj = $obj | ConvertFrom-Json
Write-host $obj.PropertyName

Java Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable

In my case this error was not related to the DISPLAY port. I was trying to load an XML into Windchill (a PLM-software) and received only the above error on the terminal. In a logfile I found the report that my XML-file was corrupt. Maybe someone has a similar problem and can use this answer.

What is stdClass in PHP?

You can also use object to cast arrays to an object of your choice:

Class Example
{
   public $name;
   public $age;
}

Now to create an object of type Example and to initialize it you can do either of these:

$example = new Example();
$example->name = "some name";
$example->age = 22;

OR

$example = new Example();
$example = (object) ['name' => "some name", 'age' => 22];

The second method is mostly useful for initializing objects with many properties.

Bootstrap 3 offset on right not left

I'm using the following simple custom CSS I wrote to achieve this.

.col-xs-offset-right-12 {
  margin-right: 100%;
}
.col-xs-offset-right-11 {
  margin-right: 91.66666667%;
}
.col-xs-offset-right-10 {
  margin-right: 83.33333333%;
}
.col-xs-offset-right-9 {
  margin-right: 75%;
}
.col-xs-offset-right-8 {
  margin-right: 66.66666667%;
}
.col-xs-offset-right-7 {
  margin-right: 58.33333333%;
}
.col-xs-offset-right-6 {
  margin-right: 50%;
}
.col-xs-offset-right-5 {
  margin-right: 41.66666667%;
}
.col-xs-offset-right-4 {
  margin-right: 33.33333333%;
}
.col-xs-offset-right-3 {
  margin-right: 25%;
}
.col-xs-offset-right-2 {
  margin-right: 16.66666667%;
}
.col-xs-offset-right-1 {
  margin-right: 8.33333333%;
}
.col-xs-offset-right-0 {
  margin-right: 0;
}
@media (min-width: 768px) {
  .col-sm-offset-right-12 {
    margin-right: 100%;
  }
  .col-sm-offset-right-11 {
    margin-right: 91.66666667%;
  }
  .col-sm-offset-right-10 {
    margin-right: 83.33333333%;
  }
  .col-sm-offset-right-9 {
    margin-right: 75%;
  }
  .col-sm-offset-right-8 {
    margin-right: 66.66666667%;
  }
  .col-sm-offset-right-7 {
    margin-right: 58.33333333%;
  }
  .col-sm-offset-right-6 {
    margin-right: 50%;
  }
  .col-sm-offset-right-5 {
    margin-right: 41.66666667%;
  }
  .col-sm-offset-right-4 {
    margin-right: 33.33333333%;
  }
  .col-sm-offset-right-3 {
    margin-right: 25%;
  }
  .col-sm-offset-right-2 {
    margin-right: 16.66666667%;
  }
  .col-sm-offset-right-1 {
    margin-right: 8.33333333%;
  }
  .col-sm-offset-right-0 {
    margin-right: 0;
  }
}
@media (min-width: 992px) {
  .col-md-offset-right-12 {
    margin-right: 100%;
  }
  .col-md-offset-right-11 {
    margin-right: 91.66666667%;
  }
  .col-md-offset-right-10 {
    margin-right: 83.33333333%;
  }
  .col-md-offset-right-9 {
    margin-right: 75%;
  }
  .col-md-offset-right-8 {
    margin-right: 66.66666667%;
  }
  .col-md-offset-right-7 {
    margin-right: 58.33333333%;
  }
  .col-md-offset-right-6 {
    margin-right: 50%;
  }
  .col-md-offset-right-5 {
    margin-right: 41.66666667%;
  }
  .col-md-offset-right-4 {
    margin-right: 33.33333333%;
  }
  .col-md-offset-right-3 {
    margin-right: 25%;
  }
  .col-md-offset-right-2 {
    margin-right: 16.66666667%;
  }
  .col-md-offset-right-1 {
    margin-right: 8.33333333%;
  }
  .col-md-offset-right-0 {
    margin-right: 0;
  }
}
@media (min-width: 1200px) {
  .col-lg-offset-right-12 {
    margin-right: 100%;
  }
  .col-lg-offset-right-11 {
    margin-right: 91.66666667%;
  }
  .col-lg-offset-right-10 {
    margin-right: 83.33333333%;
  }
  .col-lg-offset-right-9 {
    margin-right: 75%;
  }
  .col-lg-offset-right-8 {
    margin-right: 66.66666667%;
  }
  .col-lg-offset-right-7 {
    margin-right: 58.33333333%;
  }
  .col-lg-offset-right-6 {
    margin-right: 50%;
  }
  .col-lg-offset-right-5 {
    margin-right: 41.66666667%;
  }
  .col-lg-offset-right-4 {
    margin-right: 33.33333333%;
  }
  .col-lg-offset-right-3 {
    margin-right: 25%;
  }
  .col-lg-offset-right-2 {
    margin-right: 16.66666667%;
  }
  .col-lg-offset-right-1 {
    margin-right: 8.33333333%;
  }
  .col-lg-offset-right-0 {
    margin-right: 0;
  }
}

Including JavaScript class definition from another file in Node.js

You can simply do this:

user.js

class User {
    //...
}

module.exports = User

server.js

const User = require('./user.js')

// Instantiate User:
let user = new User()

This is called CommonJS module.

Export multiple values

Sometimes it could be useful to export more than one value. For example it could be classes, functions or constants. This is an alternative version of the same functionality:

user.js

class User {}

exports.User = User //  Spot the difference

server.js

const {User} = require('./user.js') //  Destructure on import

// Instantiate User:
let user = new User()

ES Modules

Since Node.js version 14 it's possible to use ES Modules with CommonJS. Read more about it in the ESM documentation.

?? Don't use globals, it creates potential conflicts with the future code.

How to define a circle shape in an Android XML drawable file?

I couldn't draw a circle inside my ConstraintLayout for some reason, I just couldn't use any of the answers above.

What did work perfectly is a simple TextView with the text that comes out, when you press "Alt+7":

 <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#0075bc"
            android:textSize="40dp"
            android:text="•"></TextView>

Join two data frames, select all columns from one and some columns from the other

Here is the code snippet that does the inner join and select the columns from both dataframe and alias the same column to different column name.

emp_df  = spark.read.csv('Employees.csv', header =True);
dept_df = spark.read.csv('dept.csv', header =True)


emp_dept_df = emp_df.join(dept_df,'DeptID').select(emp_df['*'], dept_df['Name'].alias('DName'))
emp_df.show()
dept_df.show()
emp_dept_df.show()
Output  for 'emp_df.show()':

+---+---------+------+------+
| ID|     Name|Salary|DeptID|
+---+---------+------+------+
|  1|     John| 20000|     1|
|  2|    Rohit| 15000|     2|
|  3|    Parth| 14600|     3|
|  4|  Rishabh| 20500|     1|
|  5|    Daisy| 34000|     2|
|  6|    Annie| 23000|     1|
|  7| Sushmita| 50000|     3|
|  8| Kaivalya| 20000|     1|
|  9|    Varun| 70000|     3|
| 10|Shambhavi| 21500|     2|
| 11|  Johnson| 25500|     3|
| 12|     Riya| 17000|     2|
| 13|    Krish| 17000|     1|
| 14| Akanksha| 20000|     2|
| 15|   Rutuja| 21000|     3|
+---+---------+------+------+

Output  for 'dept_df.show()':
+------+----------+
|DeptID|      Name|
+------+----------+
|     1|     Sales|
|     2|Accounting|
|     3| Marketing|
+------+----------+

Join Output:
+---+---------+------+------+----------+
| ID|     Name|Salary|DeptID|     DName|
+---+---------+------+------+----------+
|  1|     John| 20000|     1|     Sales|
|  2|    Rohit| 15000|     2|Accounting|
|  3|    Parth| 14600|     3| Marketing|
|  4|  Rishabh| 20500|     1|     Sales|
|  5|    Daisy| 34000|     2|Accounting|
|  6|    Annie| 23000|     1|     Sales|
|  7| Sushmita| 50000|     3| Marketing|
|  8| Kaivalya| 20000|     1|     Sales|
|  9|    Varun| 70000|     3| Marketing|
| 10|Shambhavi| 21500|     2|Accounting|
| 11|  Johnson| 25500|     3| Marketing|
| 12|     Riya| 17000|     2|Accounting|
| 13|    Krish| 17000|     1|     Sales|
| 14| Akanksha| 20000|     2|Accounting|
| 15|   Rutuja| 21000|     3| Marketing|
+---+---------+------+------+----------+

Paused in debugger in chrome?

Its really a bad experience. if the above answer didn't work for you try this.

Click on the Settings icon and then click on the Restore defaults and reload button.

Press 'F8' until its became normal.

Happy coding!!

How can I change from SQL Server Windows mode to mixed mode (SQL Server 2008)?

You can do it with SQL Management Studio -

Server Properties - Security - [Server Authentication section] you check Sql Server and Windows authentication mode

Here is the msdn source - http://msdn.microsoft.com/en-us/library/ms188670.aspx

Phonegap + jQuery Mobile, real world sample or tutorial

These may not solve exactly your "real-world problems", but perhaps something useful ...

Our web site includes PhoneGap and jQuery Mobile tutorials for a media player, barcode scanner, google maps, and OAuth.

Also, my github page has code, but no tutorial, for two apps:

  • AppLaudApp - a run-control, debugging enabling, download complementary app to a cloud IDE
  • NameTrendz - an app developed in at Android Dev Camp to do a bunch of queries about popular name data. The PhoneGap and jQuery Mobile versions are from March 2011.

File path issues in R using Windows ("Hex digits in character string" error)

I think that R is reading the '\' in the string as an escape character. For example \n creates a new line within a string, \t creates a new tab within the string.

'\' will work because R will recognize this as a normal backslash.

Explaining Python's '__enter__' and '__exit__'

In addition to the above answers to exemplify invocation order, a simple run example

class myclass:
    def __init__(self):
        print("__init__")

    def __enter__(self): 
        print("__enter__")

    def __exit__(self, type, value, traceback):
        print("__exit__")

    def __del__(self):
        print("__del__")

with myclass(): 
    print("body")

Produces the output:

__init__
__enter__
body
__exit__
__del__

A reminder: when using the syntax with myclass() as mc, variable mc gets the value returned by __enter__(), in the above case None! For such use, need to define return value, such as:

def __enter__(self): 
    print('__enter__')
    return self

Can I write into the console in a unit test? If yes, why doesn't the console window open?

In Visual Studio 2017, "TestContext" doesn't show the Output link into Test Explorer.

However, Trace.Writeline() shows the Output link.

Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX

The API can't be loaded after the document has finished loading by default, you'll need to load it asynchronous.

modify the page with the map:

<div id="map_canvas" style="height: 354px; width:713px;"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize"></script>
<script>
var directionsDisplay,
    directionsService,
    map;

function initialize() {
  var directionsService = new google.maps.DirectionsService();
  directionsDisplay = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var mapOptions = { zoom:7, mapTypeId: google.maps.MapTypeId.ROADMAP, center: chicago }
  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
  directionsDisplay.setMap(map);
}

</script>

For more details take a look at: https://stackoverflow.com/questions/14184956/async-google-maps-api-v3-undefined-is-not-a-function/14185834#14185834

Example: http://jsfiddle.net/doktormolle/zJ5em/

Using the "start" command with parameters passed to the started program

None of these answers worked for me.

Instead, I had to use the Call command:

Call "\\Path To Program\Program.exe" <parameters>

I'm not sure this actually waits for completion... the C++ Redistributable I was installing went fast enough that it didn't matter

How do I change the IntelliJ IDEA default JDK?

Download and unpack a JDK archive file (.tar.gz) and add it as a SDK in the 'Project Structure' dialog box ( Ctrl+Alt+Shift+S )

jdk 9 intellij click on the gif to enlarge

Make sure to set the 'Project language level' as well.

Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

In my case has helped to exclude javax.transaction.jta dependency from hibernate:

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate</artifactId>
  <version>3.2.7.ga</version>
  <exclusions>
    <exclusion>
      <groupId>javax.transaction</groupId>
      <artifactId>jta</artifactId>
    </exclusion>
  </exclusions>
</dependency>

How to extract the n-th elements from a list of tuples?

Timings for Python 3.6 for extracting the second element from a 2-tuple list.

Also, added numpy array method, which is simpler to read (but arguably simpler than the list comprehension).

from operator import itemgetter
elements = [(1,1) for _ in range(100000)]

%timeit second = [x[1] for x in elements]
%timeit second = list(map(itemgetter(1), elements))
%timeit second = dict(elements).values()
%timeit second = list(zip(*elements))[1]
%timeit second = np.array(elements)[:,1]

and the timings:

list comprehension:  4.73 ms ± 206 µs per loop
list(map):           5.3 ms ± 167 µs per loop
dict:                2.25 ms ± 103 µs per loop
list(zip)            5.2 ms ± 252 µs per loop
numpy array:        28.7 ms ± 1.88 ms per loop

Note that map() and zip() do not return a list anymore, hence the explicit conversion.

Format ints into string of hex

a = [0,1,2,3,127,200,255]
print str.join("", ("%02x" % i for i in a))

prints

000102037fc8ff

(Also note that your code will fail for integers in the range from 10 to 15.)

Keep CMD open after BAT file executes

Put pause at the end of your .BAT file.

JQuery: detect change in input field

Use jquery change event

Description: Bind an event handler to the "change" JavaScript event, or trigger that event on an element.

An example

$("input[type='text']").change( function() {
  // your code
});

The advantage that .change has over .keypress , .focus , .blur is that .change event will fire only when input has changed

How do I update pip itself from inside my virtual environment?

To get this to work for me I had to drill down in the Python directory using the Python command prompt (on WIN10 from VS CODE). In my case it was in my "AppData\Local\Programs\Python\python35-32" directory. From there now I ran the command...

python -m pip install --upgrade pip

This worked and I'm good to go.

Parsing XML in Python using ElementTree example

If I understand your question correctly:

for elem in doc.findall('timeSeries/values/value'):
    print elem.get('dateTime'), elem.text

or if you prefer (and if there is only one occurrence of timeSeries/values:

values = doc.find('timeSeries/values')
for value in values:
    print value.get('dateTime'), elem.text

The findall() method returns a list of all matching elements, whereas find() returns only the first matching element. The first example loops over all the found elements, the second loops over the child elements of the values element, in this case leading to the same result.

I don't see where the problem with not finding timeSeries comes from however. Maybe you just forgot the getroot() call? (note that you don't really need it because you can work from the elementtree itself too, if you change the path expression to for example /timeSeriesResponse/timeSeries/values or //timeSeries/values)

How do I display an alert dialog on Android?

Use AlertDialog.Builder :

AlertDialog alertDialog = new AlertDialog.Builder(this)
//set icon 
 .setIcon(android.R.drawable.ic_dialog_alert)
//set title
.setTitle("Are you sure to Exit")
//set message
.setMessage("Exiting will call finish() method")
//set positive button
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
   //set what would happen when positive button is clicked    
        finish();
    }
})
//set negative button
.setNegativeButton("No", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
   //set what should happen when negative button is clicked
        Toast.makeText(getApplicationContext(),"Nothing Happened",Toast.LENGTH_LONG).show();
    }
})
.show();

You will get the following output.

android alert dialog

To view alert dialog tutorial use the link below.

Android Alert Dialog Tutorial

delete_all vs destroy_all?

I’ve made a small gem that can alleviate the need to manually delete associated records in some circumstances.

This gem adds a new option for ActiveRecord associations:

dependent: :delete_recursively

When you destroy a record, all records that are associated using this option will be deleted recursively (i.e. across models), without instantiating any of them.

Note that, just like dependent: :delete or dependent: :delete_all, this new option does not trigger the around/before/after_destroy callbacks of the dependent records.

However, it is possible to have dependent: :destroy associations anywhere within a chain of models that are otherwise associated with dependent: :delete_recursively. The :destroy option will work normally anywhere up or down the line, instantiating and destroying all relevant records and thus also triggering their callbacks.

Why should hash functions use a prime number modulus?

Primes are used because you have good chances of obtaining a unique value for a typical hash-function which uses polynomials modulo P. Say, you use such hash-function for strings of length <= N, and you have a collision. That means that 2 different polynomials produce the same value modulo P. The difference of those polynomials is again a polynomial of the same degree N (or less). It has no more than N roots (this is here the nature of math shows itself, since this claim is only true for a polynomial over a field => prime number). So if N is much less than P, you are likely not to have a collision. After that, experiment can probably show that 37 is big enough to avoid collisions for a hash-table of strings which have length 5-10, and is small enough to use for calculations.

How to handle onchange event on input type=file in jQuery?

Demo : http://jsfiddle.net/NbGBj/

$("document").ready(function(){

    $("#upload").change(function() {
        alert('changed!');
    });
});

Rotate label text in seaborn factorplot

Aman is correct that you can use normal matplotlib commands, but this is also built into the FacetGrid:

import seaborn as sns
planets = sns.load_dataset("planets")
g = sns.factorplot("year", data=planets, aspect=1.5, kind="count", color="b")
g.set_xticklabels(rotation=30)

enter image description here

There are some comments and another answer claiming this "doesn't work", however, anyone can run the code as written here and see that it does work. The other answer does not provide a reproducible example of what isn't working, making it very difficult to address, but my guess is that people are trying to apply this solution to the output of functions that return an Axes object instead of a Facet Grid. These are different things, and the Axes.set_xticklabels() method does indeed require a list of labels and cannot simply change the properties of the existing labels on the Axes. The lesson is that it's important to pay attention to what kind of objects you are working with.

How to show a dialog to confirm that the user wishes to exit an Android Activity?

Just put this code in your first activity 

@Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(GravityCompat.END)) {
            drawerLayout.closeDrawer(GravityCompat.END);
        }
        else {
// if your using fragment then you can do this way
            int fragments = getSupportFragmentManager().getBackStackEntryCount();
            if (fragments == 1) {
new AlertDialog.Builder(this)
           .setMessage("Are you sure you want to exit?")
           .setCancelable(false)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    finish();
               }
           })
           .setNegativeButton("No", null)
           .show();


            } else {
                if (getFragmentManager().getBackStackEntryCount() > 1) {
                    getFragmentManager().popBackStack();
                } else {

           super.onBackPressed();
                }
            }
        }
    }

Error in Eclipse: "The project cannot be built until build path errors are resolved"

  1. Open the Problems view. You can open this view by clicking on the small + sign at the left hand bottom corner of eclipse. It's a very tiny plus with a rectangle around it. Click on it and select problems.

  2. The problem view will show you the problems that need to be resolved.

    • If the message says "the project is missing the required libraries...", you need to configure your build path by right clicking on your project, selecting properties, then build path. Add the required jar files using the libraries tab. -If there are other problems other than missing libraries, you need to post the exact problems here to get a precise solution.

How do I compare two strings in Perl?

  • cmp Compare

    'a' cmp 'b' # -1
    'b' cmp 'a' #  1
    'a' cmp 'a' #  0
    
  • eq Equal to

    'a' eq  'b' #  0
    'b' eq  'a' #  0
    'a' eq  'a' #  1
    
  • ne Not-Equal to

    'a' ne  'b' #  1
    'b' ne  'a' #  1
    'a' ne  'a' #  0
    
  • lt Less than

    'a' lt  'b' #  1
    'b' lt  'a' #  0
    'a' lt  'a' #  0
    
  • le Less than or equal to

    'a' le  'b' #  1
    'b' le  'a' #  0
    'a' le  'a' #  1
    
  • gt Greater than

    'a' gt  'b' #  0
    'b' gt  'a' #  1
    'a' gt  'a' #  0
    
  • ge Greater than or equal to

    'a' ge  'b' #  0
    'b' ge  'a' #  1
    'a' ge  'a' #  1
    

See perldoc perlop for more information.

( I'm simplifying this a little bit as all but cmp return a value that is both an empty string, and a numerically zero value instead of 0, and a value that is both the string '1' and the numeric value 1. These are the same values you will always get from boolean operators in Perl. You should really only be using the return values for boolean or numeric operations, in which case the difference doesn't really matter. )

Why does flexbox stretch my image rather than retaining aspect ratio?

The key attribute is align-self: center:

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
_x000D_
img {_x000D_
  max-width: 100%;_x000D_
}_x000D_
_x000D_
img.align-self {_x000D_
  align-self: center;_x000D_
}
_x000D_
<div class="container">_x000D_
    <p>Without align-self:</p>_x000D_
    <img src="http://i.imgur.com/NFBYJ3hs.jpg" />_x000D_
    <p>With align-self:</p>_x000D_
    <img class="align-self" src="http://i.imgur.com/NFBYJ3hs.jpg" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

What's the difference between faking, mocking, and stubbing?

all of them are called Test Doubles and used to inject the dependencies that your test case needs.

Fake

Stub: It already has a predefined behavior to set your expectation for example, stub returns only the success case of your API response Stub

A mock is a smarter stub. You verify your test passes through it. so you could make amock that return either the success or failure success depending on the condition could be changed in your test case. Mock

Dummy

Spy

Check file extension in upload form in PHP

Using if( $ext !== 'gif') might not be efficient. What if you allow like 20 different extensions?

Try:

$allowed = array('gif', 'png', 'jpg');
$filename = $_FILES['video_file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if (!in_array($ext, $allowed)) {
    echo 'error';
}

jQuery post() with serialize and extra data

I like to keep objects as objects and not do any crazy type-shifting. Here's my way

var post_vars = $('#my-form').serializeArray();
$.ajax({
  url: '//site.com/script.php',
  method: 'POST',
  data: post_vars,
  complete: function() {
    $.ajax({
      url: '//site.com/script2.php',
      method: 'POST',
      data: post_vars.concat({
        name: 'EXTRA_VAR',
        value: 'WOW THIS WORKS!'
      })
    });
  }
});

if you can't see from above I used the .concat function and passed in an object with the post variable as 'name' and the value as 'value'!

Hope this helps.

Get the string within brackets in Python

You can use

import re

s = re.search(r"\[.*?]", string)
if s:
    print(s.group(0))

Insert NULL value into INT column

If column is not NOT NULL (nullable).

You just put NULL instead of value in INSERT statement.

Stop Chrome Caching My JS Files

I know this is an "old" question. But the headaches with caching never are. After heaps of trial and errors, I found that one of our web hosting providers had through CPanel this app called Cachewall. I just clicked on Enable Development mode and... voilà!!! It stopped the long suffered pain straight away :) Hope this helps somebody else... R

Create table in SQLite only if it doesn't exist already

Am going to try and add value to this very good question and to build on @BrittonKerin's question in one of the comments under @David Wolever's fantastic answer. Wanted to share here because I had the same challenge as @BrittonKerin and I got something working (i.e. just want to run a piece of code only IF the table doesn't exist).

        # for completeness lets do the routine thing of connections and cursors
        conn = sqlite3.connect(db_file, timeout=1000) 

        cursor = conn.cursor() 

        # get the count of tables with the name  
        tablename = 'KABOOM' 
        cursor.execute("SELECT count(name) FROM sqlite_master WHERE type='table' AND name=? ", (tablename, ))

        print(cursor.fetchone()) # this SHOULD BE in a tuple containing count(name) integer.

        # check if the db has existing table named KABOOM
        # if the count is 1, then table exists 
        if cursor.fetchone()[0] ==1 : 
            print('Table exists. I can do my custom stuff here now.... ')
            pass
        else: 
           # then table doesn't exist. 
           custRET = myCustFunc(foo,bar) # replace this with your custom logic

How do you set a default value for a MySQL Datetime column?

this is indeed terrible news.here is a long pending bug/feature request for this. that discussion also talks about the limitations of timestamp data type.

I am seriously wondering what is the issue with getting this thing implemented.

What exactly is the 'react-scripts start' command?

As Sagiv b.g. pointed out, the npm start command is a shortcut for npm run start. I just wanted to add a real-life example to clarify it a bit more.

The setup below comes from the create-react-app github repo. The package.json defines a bunch of scripts which define the actual flow.

"scripts": {
  "start": "npm-run-all -p watch-css start-js",
  "build": "npm run build-css && react-scripts build",
  "watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive",
  "build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/",
  "start-js": "react-scripts start"
},

For clarity, I added a diagram. enter image description here

The blue boxes are references to scripts, all of which you could executed directly with an npm run <script-name> command. But as you can see, actually there are only 2 practical flows:

  • npm run start
  • npm run build

The grey boxes are commands which can be executed from the command line.

So, for instance, if you run npm start (or npm run start) that actually translate to the npm-run-all -p watch-css start-js command, which is executed from the commandline.

In my case, I have this special npm-run-all command, which is a popular plugin that searches for scripts that start with "build:", and executes all of those. I actually don't have any that match that pattern. But it can also be used to run multiple commands in parallel, which it does here, using the -p <command1> <command2> switch. So, here it executes 2 scripts, i.e. watch-css and start-js. (Those last mentioned scripts are watchers which monitor file changes, and will only finish when killed.)

  • The watch-css makes sure that the *.scss files are translated to *.cssfiles, and looks for future updates.

  • The start-js points to the react-scripts start which hosts the website in a development mode.

In conclusion, the npm start command is configurable. If you want to know what it does, then you have to check the package.json file. (and you may want to make a little diagram when things get complicated).

isset() and empty() - what to use

$var = 'abcdef';
if(isset($var))
{
   if (strlen($var) > 0);
   {
      //do something, string length greater than zero
   }
   else
   {
     //do something else, string length 0 or less
   }
}

This is a simple example. Hope it helps.

edit: added isset in the event a variable isn't defined like above, it would cause an error, checking to see if its first set at the least will help remove some headache down the road.

ffmpeg usage to encode a video to H264 codec format

"C:\Program Files (x86)\ffmpegX86shared\bin\ffmpeg.exe" -y -i "C:\testfile.ts" -an -vcodec libx264 -g 75 -keyint_min 12 -vb 4000k -vprofile high -level 40 -s 1920x1080 -y -threads 0 -r 25 "C:\testfile.h264"

The above worked for me on a Windows machine using a FFmpeg Win32 shared build by Kyle Schwarz. The build was compiled on: Feb 22 2013, at: 01:09:53

Note that -an defines that audio should be skipped.

Enable/Disable Anchor Tags using AngularJS

You may, redefine the a tag using angular directive:

angular.module('myApp').directive('a', function() {
  return {
    restrict: 'E',
    link: function(scope, elem, attrs) {
      if ('disabled' in attrs) {
        elem.on('click', function(e) {
          e.preventDefault(); // prevent link click
        });
      }
    }
  };
});

In html:

<a href="nextPage" disabled>Next</a>

Completely Remove MySQL Ubuntu 14.04 LTS

remove mysql :

sudo apt -y purge mysql*
sudo apt -y autoremove
sudo rm -rf /etc/mysql
sudo rm -rf /var/lib/mysql*

Restart instance :

sudo shutdown -r now

javac option to compile all java files under a given directory recursively

I've been using this in an Xcode JNI project to recursively build my test classes:

find ${PROJECT_DIR} -name "*.java" -print | xargs javac -g -classpath ${BUILT_PRODUCTS_DIR} -d ${BUILT_PRODUCTS_DIR}

How to get current timestamp in milliseconds since 1970 just the way Java gets

Since C++11 you can use std::chrono:

  • get current system time: std::chrono::system_clock::now()
  • get time since epoch: .time_since_epoch()
  • translate the underlying unit to milliseconds: duration_cast<milliseconds>(d)
  • translate std::chrono::milliseconds to integer (uint64_t to avoid overflow)
#include <chrono>
#include <cstdint>
#include <iostream>

uint64_t timeSinceEpochMillisec() {
  using namespace std::chrono;
  return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
}

int main() {
  std::cout << timeSinceEpochMillisec() << std::endl;
  return 0;
}

Django: How can I call a view function from template?

How about this:

<a class="btn btn-primary" href="{% url 'url-name'%}">Button-Text</a>

The class is including bootstrap styles for primary button.

MySQL Select last 7 days

The WHERE clause is misplaced, it has to follow the table references and JOIN operations.

Something like this:

 FROM tartikel p1 
 JOIN tartikelpict p2 
   ON p1.kArtikel = p2.kArtikel 
  AND p2.nNr = 1
WHERE p1.dErstellt >= DATE(NOW()) - INTERVAL 7 DAY
ORDER BY p1.kArtikel DESC

EDIT (three plus years later)

The above essentially answers the question "I tried to add a WHERE clause to my query and now the query is returning an error, how do I fix it?"

As to a question about writing a condition that checks a date range of "last 7 days"...

That really depends on interpreting the specification, what the datatype of the column in the table is (DATE or DATETIME) and what data is available... what should be returned.

To summarize: the general approach is to identify a "start" for the date/datetime range, and "end" of that range, and reference those in a query. Let's consider something easier... all rows for "yesterday".

If our column is DATE type. Before we incorporate an expression into a query, we can test it in a simple SELECT

 SELECT DATE(NOW()) + INTERVAL -1 DAY 

and verify the result returned is what we expect. Then we can use that same expression in a WHERE clause, comparing it to a DATE column like this:

 WHERE datecol = DATE(NOW()) + INTERVAL -1 DAY

For a DATETIME or TIMESTAMP column, we can use >= and < inequality comparisons to specify a range

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -1 DAY
   AND datetimecol <  DATE(NOW()) + INTERVAL  0 DAY

For "last 7 days" we need to know if that mean from this point right now, back 7 days ... e.g. the last 7*24 hours , including the time component in the comparison, ...

 WHERE datetimecol >= NOW() + INTERVAL -7 DAY
   AND datetimecol <  NOW() + INTERVAL  0 DAY

the last seven complete days, not including today

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -7 DAY
   AND datetimecol <  DATE(NOW()) + INTERVAL  0 DAY

or past six complete days plus so far today ...

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -6 DAY
   AND datetimecol <  NOW()       + INTERVAL  0 DAY

I recommend testing the expressions on the right side in a SELECT statement, we can use a user-defined variable in place of NOW() for testing, not being tied to what NOW() returns so we can test borders, across week/month/year boundaries, and so on.

SET @clock = '2017-11-17 11:47:47' ;

SELECT DATE(@clock)
     , DATE(@clock) + INTERVAL -7 DAY 
     , @clock + INTERVAL -6 DAY 

Once we have expressions that return values that work for "start" and "end" for our particular use case, what we mean by "last 7 days", we can use those expressions in range comparisons in the WHERE clause.

(Some developers prefer to use the DATE_ADD and DATE_SUB functions in place of the + INTERVAL val DAY/HOUR/MINUTE/MONTH/YEAR syntax.

And MySQL provides some convenient functions for working with DATE, DATETIME and TIMESTAMP datatypes... DATE, LAST_DAY,

Some developers prefer to calculate the start and end in other code, and supply string literals in the SQL query, such that the query submitted to the database is

  WHERE datetimecol >= '2017-11-10 00:00'
    AND datetimecol <  '2017-11-17 00:00'

And that approach works too. (My preference would be to explicitly cast those string literals into DATETIME, either with CAST, CONVERT or just the + INTERVAL trick...

  WHERE datetimecol >= '2017-11-10 00:00' + INTERVAL 0 SECOND
    AND datetimecol <  '2017-11-17 00:00' + INTERVAL 0 SECOND

The above all assumes we are storing "dates" in appropriate DATE, DATETIME and/or TIMESTAMP datatypes, and not storing them as strings in variety of formats e.g. 'dd/mm/yyyy', m/d/yyyy, julian dates, or in sporadically non-canonical formats, or as a number of seconds since the beginning of the epoch, this answer would need to be much longer.

Forcing anti-aliasing using css: Is this a myth?

There's these exciting new properties in CSS3:

font-smooth:always;
-webkit-font-smoothing: antialiased;

Still not done much testing with them myself though, and they almost definitely won't be any good for IE. Could be useful for Chrome on Windows or maybe Firefox though. Last time I checked, they didn't antialias small stuff automatically like they do in OSX.

UPDATE

These are not supported in IE or Firefox. The font-smooth property is only available in iOS safari as far as I remember

JavaScript Form Submit - Confirm or Cancel Submission Dialog Box

Simple and easy :

_x000D_
_x000D_
<form onSubmit="return confirm('Do you want to submit?') ">_x000D_
  <input type="submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Is there a list of Pytz Timezones?

In my opinion this is a design flaw of pytz library. It should be more reliable to specify a timezone using the offset, e.g.

pytz.construct("UTC-07:00")

which gives you Canada/Pacific timezone.

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

Here are some real-world examples of the types of relationships:

One-to-one (1:1)

A relationship is one-to-one if and only if one record from table A is related to a maximum of one record in table B.

To establish a one-to-one relationship, the primary key of table B (with no orphan record) must be the secondary key of table A (with orphan records).

For example:

CREATE TABLE Gov(
    GID number(6) PRIMARY KEY, 
    Name varchar2(25), 
    Address varchar2(30), 
    TermBegin date,
    TermEnd date
); 

CREATE TABLE State(
    SID number(3) PRIMARY KEY,
    StateName varchar2(15),
    Population number(10),
    SGID Number(4) REFERENCES Gov(GID), 
    CONSTRAINT GOV_SDID UNIQUE (SGID)
);

INSERT INTO gov(GID, Name, Address, TermBegin) 
values(110, 'Bob', '123 Any St', '1-Jan-2009');

INSERT INTO STATE values(111, 'Virginia', 2000000, 110);

One-to-many (1:M)

A relationship is one-to-many if and only if one record from table A is related to one or more records in table B. However, one record in table B cannot be related to more than one record in table A.

To establish a one-to-many relationship, the primary key of table A (the "one" table) must be the secondary key of table B (the "many" table).

For example:

CREATE TABLE Vendor(
    VendorNumber number(4) PRIMARY KEY,
    Name varchar2(20),
    Address varchar2(20),
    City varchar2(15),
    Street varchar2(2),
    ZipCode varchar2(10),
    Contact varchar2(16),
    PhoneNumber varchar2(12),
    Status varchar2(8),
    StampDate date
);

CREATE TABLE Inventory(
    Item varchar2(6) PRIMARY KEY,
    Description varchar2(30),
    CurrentQuantity number(4) NOT NULL,
    VendorNumber number(2) REFERENCES Vendor(VendorNumber),
    ReorderQuantity number(3) NOT NULL
);

Many-to-many (M:M)

A relationship is many-to-many if and only if one record from table A is related to one or more records in table B and vice-versa.

To establish a many-to-many relationship, create a third table called "ClassStudentRelation" which will have the primary keys of both table A and table B.

CREATE TABLE Class(
    ClassID varchar2(10) PRIMARY KEY, 
    Title varchar2(30),
    Instructor varchar2(30), 
    Day varchar2(15), 
    Time varchar2(10)
);

CREATE TABLE Student(
    StudentID varchar2(15) PRIMARY KEY, 
    Name varchar2(35),
    Major varchar2(35), 
    ClassYear varchar2(10), 
    Status varchar2(10)
);  

CREATE TABLE ClassStudentRelation(
    StudentID varchar2(15) NOT NULL,
    ClassID varchar2(14) NOT NULL,
    FOREIGN KEY (StudentID) REFERENCES Student(StudentID), 
    FOREIGN KEY (ClassID) REFERENCES Class(ClassID),
    UNIQUE (StudentID, ClassID)
);

Pandas every nth row

Though @chrisb's accepted answer does answer the question, I would like to add to it the following.

A simple method I use to get the nth data or drop the nth row is the following:

df1 = df[df.index % 3 != 0]  # Excludes every 3rd row starting from 0
df2 = df[df.index % 3 == 0]  # Selects every 3rd raw starting from 0

This arithmetic based sampling has the ability to enable even more complex row-selections.

This assumes, of course, that you have an index column of ordered, consecutive, integers starting at 0.

How to Execute stored procedure from SQL Plus?

You forgot to put z as an bind variable.

The following EXECUTE command runs a PL/SQL statement that references a stored procedure:

SQL> EXECUTE -
> :Z := EMP_SALE.HIRE('JACK','MANAGER','JONES',2990,'SALES')

Note that the value returned by the stored procedure is being return into :Z

Add new column with foreign key constraint in one command

2020 Update

It's pretty old question but people are still returning to it I see. In case the above answers did not help you, make sure that you are using same data type for the new column as the id of the other table.

In my case, I was using Laravel and I use "unsigned integer" for all of my ids as there is no point of having negative id LOL.

So for that, the raw SQL query will change like this:

ALTER TABLE `table_name`
ADD `column_name` INTEGER UNSIGNED,
ADD CONSTRAINT constrain_name FOREIGN KEY(column_name) REFERENCES foreign_table_name(id);

I hope it helps

How do I adb pull ALL files of a folder present in SD Card

Yep, just use the trailing slash to recursively pull the directory. Works for me with Nexus 5 and current version of adb (March 2014).

Object of class stdClass could not be converted to string - laravel

Try this simple in one line of code:-

$data= json_decode( json_encode($data), true);

Hope it helps :)

How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

NodeJS implementation:

/**
* getColumnFromIndex
* Helper that returns a column value (A-XFD) for an index value (integer).
* The column follows the Common Spreadsheet Format e.g., A, AA, AAA.
* See https://stackoverflow.com/questions/181596/how-to-convert-a-column-number-eg-127-into-an-excel-column-eg-aa/3444285#3444285
* @param numVal: Integer
* @return String
*/
getColumnFromIndex: function(numVal){
   var dividend = parseInt(numVal);
   var columnName = '';
   var modulo;
   while (dividend > 0) {
      modulo = (dividend - 1) % 26;
      columnName = String.fromCharCode(65 + modulo) + columnName;
      dividend = parseInt((dividend - modulo) / 26);
   }
   return columnName;
},

Thanks to Convert excel column alphabet (e.g. AA) to number (e.g., 25). And in reverse:

/**
* getIndexFromColumn
* Helper that returns an index value (integer) for a column value (A-XFD).
* The column follows the Common Spreadsheet Format e.g., A, AA, AAA.
* See https://stackoverflow.com/questions/9905533/convert-excel-column-alphabet-e-g-aa-to-number-e-g-25
* @param strVal: String
* @return Integer
*/
getIndexFromColumn: function(val){
   var base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', i, j, result = 0;
   for (i = 0, j = val.length - 1; i < val.length; i += 1, j -= 1) {
      result += Math.pow(base.length, j) * (base.indexOf(val[i]) + 1);
   }
   return result;
}

jQuery ajax upload file in asp.net mvc

Upload files using AJAX in ASP.Net MVC

Things have changed since HTML5

JavaScript

document.getElementById('uploader').onsubmit = function () {
    var formdata = new FormData(); //FormData object
    var fileInput = document.getElementById('fileInput');
    //Iterating through each files selected in fileInput
    for (i = 0; i < fileInput.files.length; i++) {
        //Appending each file to FormData object
        formdata.append(fileInput.files[i].name, fileInput.files[i]);
    }
    //Creating an XMLHttpRequest and sending
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/Home/Upload');
    xhr.send(formdata);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            alert(xhr.responseText);
        }
    }
    return false;
}   

Controller

public JsonResult Upload()
{
    for (int i = 0; i < Request.Files.Count; i++)
    {
        HttpPostedFileBase file = Request.Files[i]; //Uploaded file
        //Use the following properties to get file's name, size and MIMEType
        int fileSize = file.ContentLength;
        string fileName = file.FileName;
        string mimeType = file.ContentType;
        System.IO.Stream fileContent = file.InputStream;
        //To save file, use SaveAs method
        file.SaveAs(Server.MapPath("~/")+ fileName ); //File will be saved in application root
    }
    return Json("Uploaded " + Request.Files.Count + " files");
}

EDIT : The HTML

<form id="uploader">
    <input id="fileInput" type="file" multiple>
    <input type="submit" value="Upload file" />
</form>

Get content uri from file path in android

// This code works for images on 2.2, not sure if any other media types

   //Your file path - Example here is "/sdcard/cats.jpg"
   final String filePathThis = imagePaths.get(position).toString();

   MediaScannerConnectionClient mediaScannerClient = new
   MediaScannerConnectionClient() {
    private MediaScannerConnection msc = null;
    {
        msc = new MediaScannerConnection(getApplicationContext(), this);
        msc.connect();
    }

    public void onMediaScannerConnected(){
        msc.scanFile(filePathThis, null);
    }


    public void onScanCompleted(String path, Uri uri) {
        //This is where you get your content uri
            Log.d(TAG, uri.toString());
        msc.disconnect();
    }
   };

What's the difference between map() and flatMap() methods in Java 8?

Both map and flatMap can be applied to a Stream<T> and they both return a Stream<R>. The difference is that the map operation produces one output value for each input value, whereas the flatMap operation produces an arbitrary number (zero or more) values for each input value.

This is reflected in the arguments to each operation.

The map operation takes a Function, which is called for each value in the input stream and produces one result value, which is sent to the output stream.

The flatMap operation takes a function that conceptually wants to consume one value and produce an arbitrary number of values. However, in Java, it's cumbersome for a method to return an arbitrary number of values, since methods can return only zero or one value. One could imagine an API where the mapper function for flatMap takes a value and returns an array or a List of values, which are then sent to the output. Given that this is the streams library, a particularly apt way to represent an arbitrary number of return values is for the mapper function itself to return a stream! The values from the stream returned by the mapper are drained from the stream and are passed to the output stream. The "clumps" of values returned by each call to the mapper function are not distinguished at all in the output stream, thus the output is said to have been "flattened."

Typical use is for the mapper function of flatMap to return Stream.empty() if it wants to send zero values, or something like Stream.of(a, b, c) if it wants to return several values. But of course any stream can be returned.

How to check if a string contains a specific text

Use the strpos function: http://php.net/manual/en/function.strpos.php

$haystack = "foo bar baz";
$needle   = "bar";

if( strpos( $haystack, $needle ) !== false) {
    echo "\"bar\" exists in the haystack variable";
}

In your case:

if( strpos( $a, 'some text' ) !== false ) echo 'text';

Note that my use of the !== operator (instead of != false or == true or even just if( strpos( ... ) ) {) is because of the "truthy"/"falsy" nature of PHP's handling of the return value of strpos.

As of PHP 8.0.0 you can now use str_contains

<?php
    if (str_contains('abc', '')) {
        echo "Checking the existence of the empty string will always 
        return true";
    }

Trying to detect browser close event

Referring to various articles and doing some trial and error testing, finally I developed this idea which works perfectly for me.

The idea was to detect the unload event that is triggered by closing the browser. In that case, the mouse will be out of the window, pointing out at the close button ('X').

$(window).on('mouseover', (function () {
    window.onbeforeunload = null;
}));
$(window).on('mouseout', (function () {
    window.onbeforeunload = ConfirmLeave;
}));
function ConfirmLeave() {
    return "";
}
var prevKey="";
$(document).keydown(function (e) {            
    if (e.key=="F5") {
        window.onbeforeunload = ConfirmLeave;
    }
    else if (e.key.toUpperCase() == "W" && prevKey == "CONTROL") {                
        window.onbeforeunload = ConfirmLeave;   
    }
    else if (e.key.toUpperCase() == "R" && prevKey == "CONTROL") {
        window.onbeforeunload = ConfirmLeave;
    }
    else if (e.key.toUpperCase() == "F4" && (prevKey == "ALT" || prevKey == "CONTROL")) {
        window.onbeforeunload = ConfirmLeave;
    }
    prevKey = e.key.toUpperCase();
});

The ConfirmLeave function will give the pop up default message, in case there is any need to customize the message, then return the text to be displayed instead of an empty string in function ConfirmLeave().

Java - Find shortest path between 2 points in a distance weighted map

Like SplinterReality said: There's no reason not to use Dijkstra's algorithm here.

The code below I nicked from here and modified it to solve the example in the question.

import java.util.PriorityQueue;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

class Vertex implements Comparable<Vertex>
{
    public final String name;
    public Edge[] adjacencies;
    public double minDistance = Double.POSITIVE_INFINITY;
    public Vertex previous;
    public Vertex(String argName) { name = argName; }
    public String toString() { return name; }
    public int compareTo(Vertex other)
    {
        return Double.compare(minDistance, other.minDistance);
    }

}


class Edge
{
    public final Vertex target;
    public final double weight;
    public Edge(Vertex argTarget, double argWeight)
    { target = argTarget; weight = argWeight; }
}

public class Dijkstra
{
    public static void computePaths(Vertex source)
    {
        source.minDistance = 0.;
        PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
        vertexQueue.add(source);

        while (!vertexQueue.isEmpty()) {
            Vertex u = vertexQueue.poll();

            // Visit each edge exiting u
            for (Edge e : u.adjacencies)
            {
                Vertex v = e.target;
                double weight = e.weight;
                double distanceThroughU = u.minDistance + weight;
                if (distanceThroughU < v.minDistance) {
                    vertexQueue.remove(v);

                    v.minDistance = distanceThroughU ;
                    v.previous = u;
                    vertexQueue.add(v);
                }
            }
        }
    }

    public static List<Vertex> getShortestPathTo(Vertex target)
    {
        List<Vertex> path = new ArrayList<Vertex>();
        for (Vertex vertex = target; vertex != null; vertex = vertex.previous)
            path.add(vertex);

        Collections.reverse(path);
        return path;
    }

    public static void main(String[] args)
    {
        // mark all the vertices 
        Vertex A = new Vertex("A");
        Vertex B = new Vertex("B");
        Vertex D = new Vertex("D");
        Vertex F = new Vertex("F");
        Vertex K = new Vertex("K");
        Vertex J = new Vertex("J");
        Vertex M = new Vertex("M");
        Vertex O = new Vertex("O");
        Vertex P = new Vertex("P");
        Vertex R = new Vertex("R");
        Vertex Z = new Vertex("Z");

        // set the edges and weight
        A.adjacencies = new Edge[]{ new Edge(M, 8) };
        B.adjacencies = new Edge[]{ new Edge(D, 11) };
        D.adjacencies = new Edge[]{ new Edge(B, 11) };
        F.adjacencies = new Edge[]{ new Edge(K, 23) };
        K.adjacencies = new Edge[]{ new Edge(O, 40) };
        J.adjacencies = new Edge[]{ new Edge(K, 25) };
        M.adjacencies = new Edge[]{ new Edge(R, 8) };
        O.adjacencies = new Edge[]{ new Edge(K, 40) };
        P.adjacencies = new Edge[]{ new Edge(Z, 18) };
        R.adjacencies = new Edge[]{ new Edge(P, 15) };
        Z.adjacencies = new Edge[]{ new Edge(P, 18) };


        computePaths(A); // run Dijkstra
        System.out.println("Distance to " + Z + ": " + Z.minDistance);
        List<Vertex> path = getShortestPathTo(Z);
        System.out.println("Path: " + path);
    }
}

The code above produces:

Distance to Z: 49.0
Path: [A, M, R, P, Z]

Put quotes around a variable string in JavaScript

In case of array like

result = [ '2015',  '2014',  '2013',  '2011' ],

it gets tricky if you are using escape sequence like:

result = [ \'2015\',  \'2014\',  \'2013\',  \'2011\' ].

Instead, good way to do it is to wrap the array with single quotes as follows:

result = "'"+result+"'";

What is this date format? 2011-08-12T20:17:46.384Z

If you guys are looking for a solution for Android, you can use the following code to get the epoch seconds from the timestamp string.

public static long timestampToEpochSeconds(String srcTimestamp) {
    long epoch = 0;

    try {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            Instant instant = Instant.parse(srcTimestamp);
            epoch = instant.getEpochSecond();
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSSSS'Z'", Locale.getDefault());
            sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date date = sdf.parse(srcTimestamp);
            if (date != null) {
                epoch = date.getTime() / 1000;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return epoch;
}

Sample input: 2019-10-15T05:51:31.537979Z

Sample output: 1571128673

What are the most widely used C++ vector/matrix math/linear algebra libraries, and their cost and benefit tradeoffs?

What about GLM?

It's based on the OpenGL Shading Language (GLSL) specification and released under the MIT license. Clearly aimed at graphics programmers

How to call loading function with React useEffect only once

we developed a module on GitHub that has hooks for fetching data so you can use it like this for your purpose:

import { useFetching } from "react-concurrent";

const app = () => {
  const { data, isLoading, error , refetch } = useFetching(() =>
    fetch("http://example.com"),
  );
};

You can fork that out, but any PRs are welcome. https://github.com/hosseinmd/react-concurrent#react-concurrent

Uppercase first letter of variable

var country= $('#country').val();

var con=country[0].toUpperCase();

ctr= country.replace(country[0], con);
   

no need to create any function just jugaaar

FragmentActivity to Fragment

first of all;

a Fragment must be inside a FragmentActivity, that's the first rule,

a FragmentActivity is quite similar to a standart Activity that you already know, besides having some Fragment oriented methods

second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView, where you inflate your layout, think of it as the setContentLayout

here is an example:

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     mView       = inflater.inflate(R.layout.fragment_layout, container, false);       return mView; } 

and continu your work based on that mView, so to find a View by id, call mView.findViewById(..);


for the FragmentActivity part:

the xml part "must" have a FrameLayout in order to inflate a fragment in it

        <FrameLayout             android:id="@+id/content_frame"             android:layout_width="match_parent"             android:layout_height="match_parent"  >         </FrameLayout> 

as for the inflation part

getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();


begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site

How to switch a user per task or set of tasks?

You can specify become_method to override the default method set in ansible.cfg (if any), and which can be set to one of sudo, su, pbrun, pfexec, doas, dzdo, ksu.

- name: I am confused
  command: 'whoami'
  become: true
  become_method: su
  become_user: some_user
  register: myidentity

- name: my secret identity
  debug:
    msg: '{{ myidentity.stdout }}'

Should display

TASK [my-task : my secret identity] ************************************************************
ok: [my_ansible_server] => {
    "msg": "some_user"
}

When to use which design pattern?

Learn them and slowly you'll be able to reconize and figure out when to use them. Start with something simple as the singleton pattern :)

if you want to create one instance of an object and just ONE. You use the singleton pattern. Let's say you're making a program with an options object. You don't want several of those, that would be silly. Singleton makes sure that there will never be more than one. Singleton pattern is simple, used a lot, and really effective.

UIAlertController custom font, size, color

For iOS 9.0 and above use this code in app delegate

[[UIView appearanceWhenContainedInInstancesOfClasses:@[[UIAlertController class]]] setTintColor:[UIColor redColor]];

How to get the current location in Google Maps Android API v2?

At the moment GoogleMap.getMyLocation() always returns null under every circumstance.

There are currently two bug reports towards Google, that I know of, Issue 40932 and Issue 4644.

Implementing a LocationListener as brought up earlier would be incorrect because the LocationListener would be out of sync with the LocationOverlay within the new API that you are trying to use.

Following the tutorial on Vogella's Site, linked earlier by Pramod J George, would give you directions for the Older Google Maps API.

So I apologize for not giving you a method to retrieve your location by that means. For now the locationListener may be the only means to do it, but I'm sure Google is working on fixing the issue within the new API.

Also sorry for not posting more links, StackOverlow thinks I'm spam because I have no rep.

---- Update on February 4th, 2013 ----

Google has stated that the issue will be fixed in the next update to the Google Maps API via Issue 4644. I am not sure when the update will occur, but once it does I will edit this post again.

---- Update on April 10th, 2013 ----

Google has stated the issue has been fixed via Issue 4644. It should work now.

MySQL - Operand should contain 1 column(s)

COUNT( posts.solved_post ) AS solved_post,
(SELECT users.username AS posted_by,
    users.id AS posted_by_id
    FROM users
    WHERE users.id = posts.posted_by)

Well, you can’t get multiple columns from one subquery like that. Luckily, the second column is already posts.posted_by! So:

SELECT
topics.id,
topics.name,
topics.post_count,
topics.view_count,
posts.posted_by
COUNT( posts.solved_post ) AS solved_post,
(SELECT users.username AS posted_by_username
    FROM users
    WHERE users.id = posts.posted_by)
...

CASE IN statement with multiple values

If you have more numbers or if you intend to add new test numbers for CASE then you can use a more flexible approach:

DECLARE @Numbers TABLE
(
    Number VARCHAR(50) PRIMARY KEY
    ,Class TINYINT NOT NULL
);
INSERT @Numbers
VALUES ('1121231',1);
INSERT @Numbers
VALUES ('31242323',1);
INSERT @Numbers
VALUES ('234523',2);
INSERT @Numbers
VALUES ('2342423',2);

SELECT c.*, n.Class
FROM   tblClient c  
LEFT OUTER JOIN   @Numbers n ON c.Number = n.Number;

Also, instead of table variable you can use a regular table.

jQuery lose focus event

If the 'Cool Options' are hidden from the view before the field is focused then you would want to create this in JQuery instead of having it in the DOM so anyone using a screen reader wouldn't see unnecessary information. Why should they have to listen to it when we don't have to see it?

So you can setup variables like so:

var $coolOptions= $("<div id='options'></div>").text("Some cool options");

and then append (or prepend) on focus

$("input[name='input_name']").focus(function() {
    $(this).append($coolOptions);
});

and then remove when the focus ends

$("input[name='input_name']").focusout(function() {
    $('#options').remove();
});

How do I escape ampersands in XML so they are rendered as entities in HTML?

In my case I had to change it to %26.

I needed to escape & in a URL. So &amp; did not work out for me. The urlencode function changes & to %26. This way neither XML nor the browser URL mechanism complained about the URL.

Saving image to file

If you are drawing on the Graphics of the Control than you should do something draw on the Bitmap everything you are drawing on the canvas, but have in mind that Bitmap needs to be the exact size of the control you are drawing on:

  Bitmap bmp = new Bitmap(myControl.ClientRectangle.Width,myControl.ClientRectangle.Height);
  Graphics gBmp = Graphics.FromImage(bmp);
  gBmp.DrawEverything(); //this is your code for drawing
  gBmp.Dispose();
  bmp.Save("image.png", ImageFormat.Png);

Or you can use a DrawToBitmap method of the Control. Something like this:

Bitmap bmp = new Bitmap(myControl.ClientRectangle.Width, myControl.ClientRectangle.Height);
myControl.DrawToBitmap(bmp,new Rectangle(0,0,bmp.Width,bmp.Height));
bmp.Save("image.png", ImageFormat.Png);

round() doesn't seem to be rounding properly

round(5.59, 1) is working fine. The problem is that 5.6 cannot be represented exactly in binary floating point.

>>> 5.6
5.5999999999999996
>>> 

As Vinko says, you can use string formatting to do rounding for display.

Python has a module for decimal arithmetic if you need that.

how to implement Interfaces in C++?

C++ has no built-in concepts of interfaces. You can implement it using abstract classes which contains only pure virtual functions. Since it allows multiple inheritance, you can inherit this class to create another class which will then contain this interface (I mean, object interface :) ) in it.

An example would be something like this -

class Interface
{
public:
    Interface(){}
    virtual ~Interface(){}
    virtual void method1() = 0;    // "= 0" part makes this method pure virtual, and
                                   // also makes this class abstract.
    virtual void method2() = 0;
};

class Concrete : public Interface
{
private:
    int myMember;

public:
    Concrete(){}
    ~Concrete(){}
    void method1();
    void method2();
};

// Provide implementation for the first method
void Concrete::method1()
{
    // Your implementation
}

// Provide implementation for the second method
void Concrete::method2()
{
    // Your implementation
}

int main(void)
{
    Interface *f = new Concrete();

    f->method1();
    f->method2();

    delete f;

    return 0;
}

Laravel 5 – Remove Public from URL

I know that are are a lot of solution for this issue. The best and the easiest solution is to add .htaccess file in the root directory.

I tried the answers that we provided for this issue however I faced some issues with auth:api guard in Laravel.

Here's the updated solution:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On
    RewriteCond %{HTTP:Authorization} ^(.*)
    RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

    RewriteCond %{REQUEST_FILENAME} -d [OR]
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule ^ ^$1 [N]

    RewriteCond %{REQUEST_URI} (\.\w+$) [NC]
    RewriteRule ^(.*)$ public/$1

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ server.php
</IfModule>

Create the .htaccess file in your root directory and add this code. And everything goes right

Android Closing Activity Programmatically

What about the Activity.finish() method (quoting) :

Call this when your activity is done and should be closed.

Javamail Could not convert socket to TLS GMail

What helped me fix this, and i have tried everything before this, was to configure my installed jre to JRE 1.8.

Steps in Eclipse: Windows>preferences>java>installed JRE>jre1.8.0

If it is set to jdk, switch to jre(which is what is supposed to be set to by default with the latest java version).

Default string initialization: NULL or Empty?

It depends on the situation. In most cases I use String.Empty because I don't want to be doing null checks every time I attempt to use a string. It makes the code a lot simpler and you are less likely to introduce unwanted NullReferenceException crashes.

I only set the string to null when I need to know if it has been set or not and where an empty string is something valid to set it to. In practice, I find these situations rare.

Minimal web server using netcat

while true; do (echo -e 'HTTP/1.1 200 OK\r\nConnection: close\r\n';) | timeout 1  nc -lp 8080 ; done

Closes connection after 1 sec, so curl doesn't hang on it.

Execute SQLite script

For those using PowerShell

PS C:\> Get-Content create.sql -Raw | sqlite3 auction.db

accepting HTTPS connections with self-signed certificates

I wrote small library ssl-utils-android to trust particular certificate on Android.

You can simply load any certificate by giving the filename from assets directory.

Usage:

OkHttpClient client = new OkHttpClient();
SSLContext sslContext = SslUtils.getSslContextForCertificateFile(context, "BPClass2RootCA-sha2.cer");
client.setSslSocketFactory(sslContext.getSocketFactory());

std::unique_lock<std::mutex> or std::lock_guard<std::mutex>?

They are not really same mutexes, lock_guard<muType> has nearly the same as std::mutex, with a difference that it's lifetime ends at the end of the scope (D-tor called) so a clear definition about these two mutexes :

lock_guard<muType> has a mechanism for owning a mutex for the duration of a scoped block.

And

unique_lock<muType> is a wrapper allowing deferred locking, time-constrained attempts at locking, recursive locking, transfer of lock ownership, and use with condition variables.

Here is an example implemetation :

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <chrono>

using namespace std::chrono;

class Product{

   public:

       Product(int data):mdata(data){
       }

       virtual~Product(){
       }

       bool isReady(){
       return flag;
       }

       void showData(){

        std::cout<<mdata<<std::endl;
       }

       void read(){

         std::this_thread::sleep_for(milliseconds(2000));

         std::lock_guard<std::mutex> guard(mmutex);

         flag = true;

         std::cout<<"Data is ready"<<std::endl;

         cvar.notify_one();

       }

       void task(){

       std::unique_lock<std::mutex> lock(mmutex);

       cvar.wait(lock, [&, this]() mutable throw() -> bool{ return this->isReady(); });

       mdata+=1;

       }

   protected:

    std::condition_variable cvar;
    std::mutex mmutex;
    int mdata;
    bool flag = false;

};

int main(){

     int a = 0;
     Product product(a);

     std::thread reading(product.read, &product);
     std::thread setting(product.task, &product);

     reading.join();
     setting.join();


     product.showData();
    return 0;
}

In this example, i used the unique_lock<muType> with condition variable

Get an object attribute

Use getattr if you have an attribute in string form:

>>> class User(object):
       name = 'John'

>>> u = User()
>>> param = 'name'
>>> getattr(u, param)
'John'

Otherwise use the dot .:

>>> class User(object):
       name = 'John'

>>> u = User()
>>> u.name
'John'

Add Keypair to existing EC2 instance

In my case I used this documentation to associate a key pair with my instance of Elastic Beanstalk

Important

You must create an Amazon EC2 key pair and configure your Elastic Beanstalk–provisioned Amazon EC2 instances to use the Amazon EC2 key pair before you can access your Elastic Beanstalk–provisioned Amazon EC2 instances. You can set up your Amazon EC2 key pairs using the AWS Management Console. For instructions on creating a key pair for Amazon EC2, see the Amazon Elastic Compute Cloud Getting Started Guide.

Configuring Amazon EC2 Server Instances with Elastic Beanstalk

Store boolean value in SQLite

Another way to do it is a TEXT column. And then convert the boolean value between Boolean and String before/after saving/reading the value from the database.

Ex. You have "boolValue = true;"

To String:

//convert to the string "TRUE"
string StringValue = boolValue.ToString;  

And back to boolean:

//convert the string back to boolean
bool Boolvalue = Convert.ToBoolean(StringValue);

Copy files to network computers on windows command line

Below command will work in command prompt:

copy c:\folder\file.ext \\dest-machine\destfolder /Z /Y

To Copy all files:

copy c:\folder\*.* \\dest-machine\destfolder /Z /Y

clearing a char array c

Pls find below where I have explained with data in the array after case 1 & case 2.

char sc_ArrData[ 100 ];
strcpy(sc_ArrData,"Hai" );

Case 1:

sc_ArrData[0] = '\0';

Result:

-   "sc_ArrData"
[0] 0 ''
[1] 97 'a'
[2] 105 'i'
[3] 0 ''

Case 2:

memset(&sc_ArrData[0], 0, sizeof(sc_ArrData));

Result:

-   "sc_ArrData"
[0] 0 ''
[1] 0 ''
[2] 0 ''
[3] 0 ''

Though setting first argument to NULL will do the trick, using memset is advisable

How do I commit only some files?

Some of this seems "incomplete"

Groups of people are NOT going to know if they should use quotes etc..

Add 1 specific file showing the location paths as well

git add JobManager/Controllers/APIs/ProfileApiController.cs

Commit (remember, commit is local only, it is not affecting any other system)

git commit -m "your message"  

Push to remote repo

git push  (this is after the commit and this attempts to Merge INTO the remote location you have instructed it to merge into)

Other answer(s) show the stash etc. which you sometimes will want to do

Understanding colors on Android (six characters)

On Android, colors are can be specified as RGB or ARGB.

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

In RGB you have two characters for every color (red, green, blue), and in ARGB you have two additional chars for the alpha channel.

So, if you have 8 characters, it's ARGB, with the first two characters specifying the alpha channel. If you remove the leading two characters it's only RGB (solid colors, no alpha/transparency). If you want to specify a color in your Java source code, you have to use:

int Color.argb (int alpha, int red, int green, int blue)

alpha  Alpha component [0..255] of the color
red    Red component [0..255] of the color
green  Green component [0..255] of the color
blue   Blue component [0..255] of the color

Reference: argb

Float sum with javascript

Once you read what What Every Computer Scientist Should Know About Floating-Point Arithmetic you could use the .toFixed() function:

var result = parseFloat('2.3') + parseFloat('2.4');
alert(result.toFixed(2));?

SQL Call Stored Procedure for each Row without using a cursor

I like to do something similar to this (though it is still very similar to using a cursor)

[code]

-- Table variable to hold list of things that need looping
DECLARE @holdStuff TABLE ( 
    id INT IDENTITY(1,1) , 
    isIterated BIT DEFAULT 0 , 
    someInt INT ,
    someBool BIT ,
    otherStuff VARCHAR(200)
)

-- Populate your @holdStuff with... stuff
INSERT INTO @holdStuff ( 
    someInt ,
    someBool ,
    otherStuff
)
SELECT  
    1 , -- someInt - int
    1 , -- someBool - bit
    'I like turtles'  -- otherStuff - varchar(200)
UNION ALL
SELECT  
    42 , -- someInt - int
    0 , -- someBool - bit
    'something profound'  -- otherStuff - varchar(200)

-- Loop tracking variables
DECLARE @tableCount INT
SET     @tableCount = (SELECT COUNT(1) FROM [@holdStuff])

DECLARE @loopCount INT
SET     @loopCount = 1

-- While loop variables
DECLARE @id INT
DECLARE @someInt INT
DECLARE @someBool BIT
DECLARE @otherStuff VARCHAR(200)

-- Loop through item in @holdStuff
WHILE (@loopCount <= @tableCount)
    BEGIN

        -- Increment the loopCount variable
        SET @loopCount = @loopCount + 1

        -- Grab the top unprocessed record
        SELECT  TOP 1 
            @id = id ,
            @someInt = someInt ,
            @someBool = someBool ,
            @otherStuff = otherStuff
        FROM    @holdStuff
        WHERE   isIterated = 0

        -- Update the grabbed record to be iterated
        UPDATE  @holdAccounts
        SET     isIterated = 1
        WHERE   id = @id

        -- Execute your stored procedure
        EXEC someRandomSp @someInt, @someBool, @otherStuff

    END

[/code]

Note that you don't need the identity or the isIterated column on your temp/variable table, i just prefer to do it this way so i don't have to delete the top record from the collection as i iterate through the loop.

Align the form to the center in Bootstrap 4

All above answers perfectly gives the solution to center the form using Bootstrap 4. However, if someone wants to use out of the box Bootstrap 4 css classes without help of any additional styles and also not wanting to use flex, we can do like this.

A sample form

enter image description here

HTML

<div class="container-fluid h-100 bg-light text-dark">
  <div class="row justify-content-center align-items-center">
    <h1>Form</h1>    
  </div>
  <hr/>
  <div class="row justify-content-center align-items-center h-100">
    <div class="col col-sm-6 col-md-6 col-lg-4 col-xl-3">
      <form action="">
        <div class="form-group">
          <select class="form-control">
                    <option>Option 1</option>
                    <option>Option 2</option>
                  </select>
        </div>
        <div class="form-group">
          <input type="text" class="form-control" />
        </div>
        <div class="form-group text-center">
          <div class="form-check-inline">
            <label class="form-check-label">
    <input type="radio" class="form-check-input" name="optradio">Option 1
  </label>
          </div>
          <div class="form-check-inline">
            <label class="form-check-label">
    <input type="radio" class="form-check-input" name="optradio">Option 2
  </label>
          </div>
          <div class="form-check-inline">
            <label class="form-check-label">
    <input type="radio" class="form-check-input" name="optradio" disabled>Option 3
  </label>
          </div>
        </div>
        <div class="form-group">
          <div class="container">
            <div class="row">
              <div class="col"><button class="col-6 btn btn-secondary btn-sm float-left">Reset</button></div>
              <div class="col"><button class="col-6 btn btn-primary btn-sm float-right">Submit</button></div>
            </div>
          </div>
        </div>

      </form>
    </div>
  </div>
</div>

Link to CodePen

https://codepen.io/anjanasilva/pen/WgLaGZ

I hope this helps someone. Thank you.

How do I generate random numbers in Dart?

use this library http://dart.googlecode.com/svn/branches/bleeding_edge/dart/lib/math/random.dart provided a good random generator which i think will be included in the sdk soon hope it helps

Taskkill /f doesn't kill a process

If taskkill /F /T /PID <pid> does not work. Try opening your terminal elevated using Run as Administrator.

Search cmd in your windows menu, and right click Run as Administrator, then run the command again. This worked for me.

How to completely DISABLE any MOUSE CLICK

To disable all mouse click

var event = $(document).click(function(e) {
    e.stopPropagation();
    e.preventDefault();
    e.stopImmediatePropagation();
    return false;
});

// disable right click
$(document).bind('contextmenu', function(e) {
    e.stopPropagation();
    e.preventDefault();
    e.stopImmediatePropagation();
    return false;
});

to enable it again:

$(document).unbind('click');
$(document).unbind('contextmenu');

How to read a text file into a string variable and strip newlines?

Regular expression works too:

import re
with open("depression.txt") as f:
     l = re.split(' ', re.sub('\n',' ', f.read()))[:-1]

print (l)

['I', 'feel', 'empty', 'and', 'dead', 'inside']

How to keep Docker container running after starting services?

Along with having something along the lines of : ENTRYPOINT ["tail", "-f", "/dev/null"] in your docker file, you should also run the docker container with -td option. This is particularly useful when the container runs on a remote m/c. Think of it more like you have ssh'ed into a remote m/c having the image and started the container. In this case, when you exit the ssh session, the container will get killed unless it's started with -td option. Sample command for running your image would be: docker run -td <any other additional options> <image name>

This holds good for docker version 20.10.2

How to find the extension of a file in C#?

It is worth to mention how to remove the extension also in parallel with getting the extension:

var name = Path.GetFileNameWithoutExtension(fileFullName); // Get the name only

var extension = Path.GetExtension(fileFullName); // Get the extension only

Capturing standard out and error with Start-Process

To get both stdout and stderr, I use:

Function GetProgramOutput([string]$exe, [string]$arguments)
{
    $process = New-Object -TypeName System.Diagnostics.Process
    $process.StartInfo.FileName = $exe
    $process.StartInfo.Arguments = $arguments

    $process.StartInfo.UseShellExecute = $false
    $process.StartInfo.RedirectStandardOutput = $true
    $process.StartInfo.RedirectStandardError = $true
    $process.Start()

    $output = $process.StandardOutput.ReadToEnd()   
    $err = $process.StandardError.ReadToEnd()

    $process.WaitForExit()

    $output
    $err
}

$exe = "cmd"
$arguments = '/c echo hello 1>&2'   #this writes 'hello' to stderr

$runResult = (GetProgramOutput $exe $arguments)
$stdout = $runResult[-2]
$stderr = $runResult[-1]

[System.Console]::WriteLine("Standard out: " + $stdout)
[System.Console]::WriteLine("Standard error: " + $stderr)

How to make a button redirect to another page using jQuery or just Javascript

You can use window.location

window.location="/newpage.php";

Or you can just make the form that the search button is in have a action of the page you want.

iOS start Background Thread

The default sqlite library that comes with iOS is not compiled using the SQLITE_THREADSAFE macro on. This could be a reason why your code crashes.

A top-like utility for monitoring CUDA activity on a GPU

You can try nvtop, which is similar to the widely-used htop tool but for NVIDIA GPUs. Here is a screenshot of nvtop of it in action.

Screenshot of nvtop in action

Remove warning messages in PHP

You could suppress the warning using error_reporting but the much better way is to fix your script in the first place.

If you don't know how, edit your question and show us the line in question and the warning that is displayed.

Raw_Input() Is Not Defined

For Python 3.x, use input(). For Python 2.x, use raw_input(). Don't forget you can add a prompt string in your input() call to create one less print statement. input("GUESS THAT NUMBER!").

Spring Boot - Loading Initial Data

You can use the below code. In the following code a database insertion occurs during the startup of the spring boot application.

@SpringBootApplication
public class Application implements CommandLineRunner {
    
    @Autowired
    private IService<Car> service;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        for(int i=1; i<=1000; i++) {
            Car car = new Car();
            car.setName("Car Name "+i);
            book.setPrice(50 + i);
            service.saveOrUpdate(car);
        }
    }

}

numpy array TypeError: only integer scalar arrays can be converted to a scalar index

Short answer:

[a[:,:j] for j in i]

What you are trying to do is not a vectorizable operation. Wikipedia defines vectorization as a batch operation on a single array, instead of on individual scalars:

In computer science, array programming languages (also known as vector or multidimensional languages) generalize operations on scalars to apply transparently to vectors, matrices, and higher-dimensional arrays.

...

... an operation that operates on entire arrays can be called a vectorized operation...

In terms of CPU-level optimization, the definition of vectorization is:

"Vectorization" (simplified) is the process of rewriting a loop so that instead of processing a single element of an array N times, it processes (say) 4 elements of the array simultaneously N/4 times.

The problem with your case is that the result of each individual operation has a different shape: (3, 1), (3, 2) and (3, 3). They can not form the output of a single vectorized operation, because the output has to be one contiguous array. Of course, it can contain (3, 1), (3, 2) and (3, 3) arrays inside of it (as views), but that's what your original array a already does.

What you're really looking for is just a single expression that computes all of them:

[a[:,:j] for j in i]

... but it's not vectorized in a sense of performance optimization. Under the hood it's plain old for loop that computes each item one by one.

html5 localStorage error with Safari: "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota."

Don't use it if not supported and to check support just call this function

sharing in Es6 full read and write localStorage Example with support check

const LOCAL_STORAGE_KEY = 'tds_app_localdata';

const isSupported = () => {
  try {
    localStorage.setItem('supported', '1');
    localStorage.removeItem('supported');
    return true;
  } catch (error) {
    return false;
  }
};


const writeToLocalStorage =
  components =>
    (isSupported ?
      localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(components))
      : components);

const isEmpty = component => (!component || Object.keys(component).length === 0);

const readFromLocalStorage =
  () => (isSupported ? JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY)) || {} : null);

This will make sure your keys are set and retrieved properly on all browsers.

Remove duplicated rows using dplyr

When selecting columns in R for a reduced data-set you can often end up with duplicates.

These two lines give the same result. Each outputs a unique data-set with two selected columns only:

distinct(mtcars, cyl, hp);

summarise(group_by(mtcars, cyl, hp));

Need table of key codes for android and presenter

They are ASCII dec codes. A full table can be found here.

Showing an image from an array of images - Javascript

Also, when checking for the last image, you must compare with imgArray.length-1 because, for example, when array length is 2 then I will take the values 0 and 1, it won't reach the value 2, so you must compare with length-1 not with length, here is the fixed line:

if(i == imgArray.length-1)

How to make primary key as autoincrement for Room Persistence lib

This works for me:

@Entity(tableName = "note_table")
data class Note(
    @ColumnInfo(name="title") var title: String,
    @ColumnInfo(name="description") var description: String = "",
    @ColumnInfo(name="priority") var priority: Int,
    @PrimaryKey(autoGenerate = true) var id: Int = 0//last so that we don't have to pass an ID value or named arguments
)

Note that the id is last to avoid having to use named arguments when creating the entity, before inserting it into Room. Once it's been added to room, use the id when updating the entity.

macro for Hide rows in excel 2010

You almost got it. You are hiding the rows within the active sheet. which is okay. But a better way would be add where it is.

Rows("52:55").EntireRow.Hidden = False

becomes

activesheet.Rows("52:55").EntireRow.Hidden = False

i've had weird things happen without it. As for making it automatic. You need to use the worksheet_change event within the sheet's macro in the VBA editor (not modules, double click the sheet1 to the far left of the editor.) Within that sheet, use the drop down menu just above the editor itself (there should be 2 listboxes). The listbox to the left will have the events you are looking for. After that just throw in the macro. It should look like the below code,

Private Sub Worksheet_Change(ByVal Target As Range)
test1
end Sub

That's it. Anytime you change something, it will run the macro test1.

How to auto adjust the div size for all mobile / tablet display formats?

Fiddle

You want to set height which may set for all devices?

Decide upon the design of the site i.e Height on various devices.

Ex:

  • Height-100px for bubbles on device with -min-width: 700px.
  • Height-50px for bubbles on device with < 700px;

Have your css which has height 50px;

and add this media query

  @media only screen and (min-width: 700px) {
    /* Styles */
    .bubble {
        height: 100px;
        margin: 20px;
    }
    .bubble:after {
        bottom: -50px;
        border-width: 50px 50px 0;
    }
    .bubble:before {
        top: 100px;
        border-width: 52px 52px 0;
    }
    .bubble1 {
        height: 100px;
        margin: 20px;
    }
    .bubble1:after {
        bottom: -50px;
        border-width: 50px 50px 0;
    }
    .bubble1:before {
        top: 100px;
        border-width: 52px 52px 0;
    }
    .bubble2 {
        height: 100px;
        margin: 20px;
    }
    .bubble2:after {
        bottom: -50px;
        border-width: 50px 50px 0;
    }
    .bubble2:before {
        top: 100px;
        border-width: 52px 52px 0;
    }
}

This will make your bubbles have Height of 100px on devices greater than 700px and a margin of 20px;

How I can get and use the header file <graphics.h> in my C++ program?

graphics.h appears to something once bundled with Borland and/or Turbo C++, in the 90's.

http://www.daniweb.com/software-development/cpp/threads/17709/88149#post88149

It's unlikely that you will find any support for that file with modern compiler. For other graphics libraries check the list of "related" questions (questions related to this one). E.g., "A Simple, 2d cross-platform graphics library for c or c++?".

curl_exec() always returns false

This happened to me yesterday and in my case was because I was following a PDF manual to develop some module to communicate with an API and while copying the link directly from the manual, for some odd reason, the hyphen from the copied link was in a different encoding and hence the curl_exec() was always returning false because it was unable to communicate with the server.

It took me a couple hours to finally understand the diference in the characters bellow:

https://www.e-example.com/api
https://www.e-example.com/api

Every time I tried to access the link directly from a browser it converted to something likehttps://www.xn--eexample-0m3d.com/api.

It may seem to you that they are equal but if you check the encoding of the hyphens here you'll see that the first hyphen is a unicode characters U+2010 and the other is a U+002D.

Hope this helps someone.

Where/How to getIntent().getExtras() in an Android Fragment?

you can still use

String Item = getIntent().getExtras().getString("name");

in the fragment, you just need call getActivity() first:

String Item = getActivity().getIntent().getExtras().getString("name");

This saves you having to write some code.

append to url and refresh page

Try this

var url = ApiUrl(`/customers`);
  if(data){
   url += '?search='+data; 
  }
  else
  { 
      url +=  `?page=${page}&per_page=${perpage}`;
  }
  console.log(url);

How to remove padding around buttons in Android?

My solution was set to 0 the insetTop and insetBottom properties.

<android.support.design.button.MaterialButton
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:insetTop="0dp"
        android:insetBottom="0dp"
        android:text="@string/view_video"
        android:textColor="@color/white"/>

Convert PDF to clean SVG?

Inkscape is used by many people on Wikipedia to convert PDF to SVG.

http://inkscape.org/

They even have a handy guide on how to do so!

http://en.wikipedia.org/wiki/Wikipedia:Graphic_Lab/Resources/PDF_conversion_to_SVG#Conversion_with_Inkscape

Is there an operator to calculate percentage in Python?

There is no such operator in Python, but it is trivial to implement on your own. In practice in computing, percentages are not nearly as useful as a modulo, so no language that I can think of implements one.

$http get parameters does not work

From $http.get docs, the second parameter is a configuration object:

get(url, [config]);

Shortcut method to perform GET request.

You may change your code to:

$http.get('accept.php', {
    params: {
        source: link, 
        category_id: category
    }
});

Or:

$http({
    url: 'accept.php', 
    method: 'GET',
    params: { 
        source: link, 
        category_id: category
    }
});

As a side note, since Angular 1.6: .success should not be used anymore, use .then instead:

$http.get('/url', config).then(successCallback, errorCallback);

What's the advantage of a Java enum versus a class with public static final fields?

Nobody mentioned the ability to use them in switch statements; I'll throw that in as well.

This allows arbitrarily complex enums to be used in a clean way without using instanceof, potentially confusing if sequences, or non-string/int switching values. The canonical example is a state machine.

Bash checking if string does not contain other string

Use !=.

if [[ ${testmystring} != *"c0"* ]];then
    # testmystring does not contain c0
fi

See help [[ for more information.

PHP errors NOT being displayed in the browser [Ubuntu 10.10]

To make it work you should change the following variables in your php.ini:

; display_errors
; Default Value: On
; Development Value: On
; Production Value: Off

; display_startup_errors
; Default Value: On
; Development Value: On
; Production Value: Off

; error_reporting
; Default Value: E_ALL & ~E_NOTICE
; Development Value: E_ALL | E_STRICT 
; Production Value: E_ALL & ~E_DEPRECATED

; html_errors 
; Default Value: On 
; Development Value: On 
; Production value: Off

; log_errors
; Default Value: On 
; Development Value: On 
; Production Value: On

Search for them as they are already defined and put your desired value. Then restart your apache2 server and everything will work fine. Good luck!

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

it is very simple....

[in make file]

==== 1 ===================

OBJS = ....\

version.o <<== add to your obj lists

==== 2 ===================

DATE = $(shell date +'char szVersionStr[20] = "%Y-%m-%d %H:%M:%S";') <<== add

all:version $(ProgramID) <<== version add at first

version: <<== add

echo '$(DATE)' > version.c  <== add ( create version.c file)

[in program]

=====3 =============

extern char szVersionStr[20];

[ using ]

=== 4 ====

printf( "Version: %s\n", szVersionStr );

Transpose/Unzip Function (inverse of zip)?

>>> original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> tuple([list(tup) for tup in zip(*original)])
(['a', 'b', 'c', 'd'], [1, 2, 3, 4])

Gives a tuple of lists as in the question.

list1, list2 = [list(tup) for tup in zip(*original)]

Unpacks the two lists.

How to display a database table on to the table in the JSP page

Tracking ID Track
    <br>
    <%String id = request.getParameter("track_id");%>
       <%if (id.length() == 0) {%>
    <b><h1>Please Enter Tracking ID</h1></b>
    <% } else {%>
    <div class="container">
        <table border="1" class="table" >
            <thead>
                <tr class="warning" >
                    <td ><h4>Track ID</h4></td>
                    <td><h4>Source</h4></td>
                    <td><h4>Destination</h4></td>
                    <td><h4>Current Status</h4></td>

                </tr>
            </thead>
            <%
                try {
                    connection = DriverManager.getConnection(connectionUrl + database, userid, password);
                    statement = connection.createStatement();
                    String sql = "select * from track where track_id="+ id;
                    resultSet = statement.executeQuery(sql);
                    while (resultSet.next()) {
            %>
            <tr class="info">
                <td><%=resultSet.getString("track_id")%></td>
                <td><%=resultSet.getString("source")%></td>
                <td><%=resultSet.getString("destination")%></td>
                <td><%=resultSet.getString("status")%></td>
            </tr>
            <%
                    }
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            %>
        </table>

        <%}%>
</body>

Find the last time table was updated

If you're talking about last time the table was updated in terms of its structured has changed (new column added, column changed etc.) - use this query:

SELECT name, [modify_date] FROM sys.tables

If you're talking about DML operations (insert, update, delete), then you either need to persist what that DMV gives you on a regular basis, or you need to create triggers on all tables to record that "last modified" date - or check out features like Change Data Capture in SQL Server 2008 and newer.

How to deal with "data of class uneval" error from ggplot2?

This could also occur if you refer to a variable in the data.frame that doesn't exist. For example, recently I forgot to tell ddply to summarize by one of my variables that I used in geom_line to specify line color. Then, ggplot didn't know where to find the variable I hadn't created in the summary table, and I got this error.

How to analyze information from a Java core dump?

Actually, VisualVM can process application core dump.

Just invoke "File/Add VM Coredump" and will add a new application in the application explorer. You can then take thread dump or heap dump of that JVM.

Large WCF web service request failing with (400) HTTP Bad Request

It might be useful to debug the client, turn off Tools\Options\Debugging\General\'Enable Just My Code', click Debug\Exceptions\'catch all first-chance exceptions' for managed CLR exceptions, and see if there is an exception under-the-hood on the client before the protocol exception and before the message hits the wire. (My guess would be some kind of serialization failure.)

Font scaling based on width of container

I just created a demo how to do it. It uses transform:scale() to achieve that with some JS that watches element resizing. Works nicely for my needs.

How to add local .jar file dependency to build.gradle file?

An other way:

Add library in the tree view. Right click on this one. Select menu "Add As Library". A dialog appear, let you select module. OK and it's done.

Child with max-height: 100% overflows parent

Maybe someone else can explain the reasons behind your problem but you can solve it by specifying the height of the container and then setting the height of the image to be 100%. It is important that the width of the image appears before the height.

<html>
    <head>
        <style>
            .container {  
                background: blue; 
                padding: 10px;
                height: 100%;
                max-height: 200px; 
                max-width: 300px; 
            }

            .container img {
                width: 100%;
                height: 100%
            }
        </style>
    </head>
    <body>
        <div class="container">
            <img src="http://placekitten.com/400/500" />
        </div>
    </body>
</html>

Extract a substring using PowerShell

I needed to extract a few lines in a log file and this post was helpful in solving my issue, so i thought of adding it here. If someone needs to extract muliple lines, you can use the script to get the index of the a word matching that string (i'm searching for "Root") and extract content in all lines.

$File_content = Get-Content "Path of the text file"
$result = @()

foreach ($val in $File_content){
    $Index_No = $val.IndexOf("Root")
    $result += $val.substring($Index_No)
}

$result | Select-Object -Unique

Cheers..!

add class with JavaScript

Simply add a class name to the beginning of the funciton and the 2nd and 3rd arguments are optional and the magic is done for you!

function getElementsByClass(searchClass, node, tag) {

  var classElements = new Array();

  if (node == null)

    node = document;

  if (tag == null)

    tag = '*';

  var els = node.getElementsByTagName(tag);

  var elsLen = els.length;

  var pattern = new RegExp('(^|\\\\s)' + searchClass + '(\\\\s|$)');

  for (i = 0, j = 0; i < elsLen; i++) {

    if (pattern.test(els[i].className)) {

      classElements[j] = els[i];

      j++;

    }

  }

  return classElements;

}

Angular2 set value for formGroup

"NgModel doesn't work with new forms api".

That's not true. You just need to use it correctly. If you are using the reactive forms, the NgModel should be used in concert with the reactive directive. See the example in the source.

/*
 * @Component({
 *      selector: "login-comp",
 *      directives: [REACTIVE_FORM_DIRECTIVES],
 *      template: `
 *        <form [formGroup]="myForm" (submit)='onLogIn()'>
 *          Login <input type='text' formControlName='login' [(ngModel)]="credentials.login">
 *          Password <input type='password' formControlName='password'
 *                          [(ngModel)]="credentials.password">
 *          <button type='submit'>Log in!</button>
 *        </form>
 *      `})
 * class LoginComp {
 *  credentials: {login:string, password:string};
 *  myForm = new FormGroup({
 *    login: new Control(this.credentials.login),
 *    password: new Control(this.credentials.password)
 *  });
 *
 *  onLogIn(): void {
 *    // this.credentials.login === "some login"
 *    // this.credentials.password === "some password"
 *  }
 * }
 */

Though it looks like from the TODO comments, this will likely be removed and replaced with a reactive API.

// TODO(kara):  Replace ngModel with reactive API
@Input('ngModel') model: any;

Why is <deny users="?" /> included in the following example?

Example 1 is for asp.net applications using forms authenication. This is common practice for internet applications because user is unauthenticated until it is authentcation against some security module.

Example 2 is for asp.net application using windows authenication. Windows Authentication uses Active Directory to authenticate users. The will prevent access to your application. I use this feature on intranet applications.

MySQL JOIN the most recent row only?

You may want to try the following:

SELECT    CONCAT(title, ' ', forename, ' ', surname) AS name
FROM      customer c
JOIN      (
              SELECT    MAX(id) max_id, customer_id 
              FROM      customer_data 
              GROUP BY  customer_id
          ) c_max ON (c_max.customer_id = c.customer_id)
JOIN      customer_data cd ON (cd.id = c_max.max_id)
WHERE     CONCAT(title, ' ', forename, ' ', surname) LIKE '%Smith%' 
LIMIT     10, 20;

Note that a JOIN is just a synonym for INNER JOIN.

Test case:

CREATE TABLE customer (customer_id int);
CREATE TABLE customer_data (
   id int, 
   customer_id int, 
   title varchar(10),
   forename varchar(10),
   surname varchar(10)
);

INSERT INTO customer VALUES (1);
INSERT INTO customer VALUES (2);
INSERT INTO customer VALUES (3);

INSERT INTO customer_data VALUES (1, 1, 'Mr', 'Bobby', 'Smith');
INSERT INTO customer_data VALUES (2, 1, 'Mr', 'Bob', 'Smith');
INSERT INTO customer_data VALUES (3, 2, 'Mr', 'Jane', 'Green');
INSERT INTO customer_data VALUES (4, 2, 'Miss', 'Jane', 'Green');
INSERT INTO customer_data VALUES (5, 3, 'Dr', 'Jack', 'Black');

Result (query without the LIMIT and WHERE):

SELECT    CONCAT(title, ' ', forename, ' ', surname) AS name
FROM      customer c
JOIN      (
              SELECT    MAX(id) max_id, customer_id 
              FROM      customer_data 
              GROUP BY  customer_id
          ) c_max ON (c_max.customer_id = c.customer_id)
JOIN      customer_data cd ON (cd.id = c_max.max_id);

+-----------------+
| name            |
+-----------------+
| Mr Bob Smith    |
| Miss Jane Green |
| Dr Jack Black   |
+-----------------+
3 rows in set (0.00 sec)

"X does not name a type" error in C++

You must declare the prototype it before using it:

class User;

class MyMessageBox
{
public:
 void sendMessage(Message *msg, User *recvr);
 Message receiveMessage();
 vector<Message> *dataMessageList;
};

class User
{
public:
 MyMessageBox dataMsgBox;
};

edit: Swapped the types

Send private messages to friends

There isn't any graph api for this, you need to use facebook xmpp chat api to send the message, good news is: I have made a php class which is too easy to use,call a function and message will be sent, its open source, check it out: facebook message api php the description says its a closed source but the it was made open source later, see the first comment, you can clone from github. It's a open source now.

Using Ansible set_fact to create a dictionary from register results

Thank you Phil for your solution; in case someone ever gets in the same situation as me, here is a (more complex) variant:

---
# this is just to avoid a call to |default on each iteration
- set_fact:
    postconf_d: {}

- name: 'get postfix default configuration'
  command: 'postconf -d'
  register: command

# the answer of the command give a list of lines such as:
# "key = value" or "key =" when the value is null
- name: 'set postfix default configuration as fact'
  set_fact:
    postconf_d: >
      {{
        postconf_d |
        combine(
          dict([ item.partition('=')[::2]|map('trim') ])
        )
  with_items: command.stdout_lines

This will give the following output (stripped for the example):

"postconf_d": {
    "alias_database": "hash:/etc/aliases", 
    "alias_maps": "hash:/etc/aliases, nis:mail.aliases",
    "allow_min_user": "no", 
    "allow_percent_hack": "yes"
}

Going even further, parse the lists in the 'value':

- name: 'set postfix default configuration as fact'
  set_fact:
    postconf_d: >-
      {% set key, val = item.partition('=')[::2]|map('trim') -%}
      {% if ',' in val -%}
        {% set val = val.split(',')|map('trim')|list -%}
      {% endif -%}
      {{ postfix_default_main_cf | combine({key: val}) }}
  with_items: command.stdout_lines
...
"postconf_d": {
    "alias_database": "hash:/etc/aliases", 
    "alias_maps": [
        "hash:/etc/aliases", 
        "nis:mail.aliases"
    ], 
    "allow_min_user": "no", 
    "allow_percent_hack": "yes"
}

A few things to notice:

  • in this case it's needed to "trim" everything (using the >- in YAML and -%} in Jinja), otherwise you'll get an error like:

    FAILED! => {"failed": true, "msg": "|combine expects dictionaries, got u\"  {u'...
    
  • obviously the {% if .. is far from bullet-proof

  • in the postfix case, val.split(',')|map('trim')|list could have been simplified to val.split(', '), but I wanted to point out the fact you will need to |list otherwise you'll get an error like:

    "|combine expects dictionaries, got u\"{u'...': <generator object do_map at ...
    

Hope this can help.

Why use String.Format?

There's interesting stuff on the performance aspects in this question

However I personally would still recommend string.Format unless performance is critical for readability reasons.

string.Format("{0}: {1}", key, value);

Is more readable than

key + ": " + value

For instance. Also provides a nice separation of concerns. Means you can have

string.Format(GetConfigValue("KeyValueFormat"), key, value);

And then changing your key value format from "{0}: {1}" to "{0} - {1}" becomes a config change rather than a code change.

string.Format also has a bunch of format provision built into it, integers, date formatting, etc.

How to add a new schema to sql server 2008?

Here's a trick to easily check if the schema already exists, and then create it, in it's own batch, to avoid the error message of trying to create a schema when it's not the only command in a batch.

IF NOT EXISTS (SELECT schema_name 
    FROM information_schema.schemata 
    WHERE schema_name = 'newSchemaName' )
BEGIN
    EXEC sp_executesql N'CREATE SCHEMA NewSchemaName;';
END

Read a text file in R line by line

I suggest you check out chunked and disk.frame. They both have functions for reading in CSVs chunk-by-chunk.

In particular, disk.frame::csv_to_disk.frame may be the function you are after?

Please add a @Pipe/@Directive/@Component annotation. Error

In my case I mistakenly added this:

@Component({
    selector: 'app-some-item',
    templateUrl: './some-item.component.html',
    styleUrls: ['./some-item.component.scss'],
    providers: [ConfirmationService]
})

declare var configuration: any;

while the correct form is:

declare var configuration: any;

@Component({
    selector: 'app-some-item',
    templateUrl: './some-item.component.html',
    styleUrls: ['./some-item.component.scss'],
    providers: [ConfirmationService]
})    

Environment variables for java installation

Java SE Development Kit 8u112 on a 64-bit Windows 7 or Windows 8

Set the following user environment variables (== environment variables of type user variables)

  • JAVA_HOME : C:\Program Files\Java\jdk1.8.0_112
  • JDK_HOME : %JAVA_HOME%
  • JRE_HOME : %JAVA_HOME%\jre
  • CLASSPATH : .;%JAVA_HOME%\lib;%JAVA_HOME%\jre\lib
  • PATH : your-unique-entries;%JAVA_HOME%\bin (make sure that the longish your-unique-entries does not contain any other references to another Java installation folder.

Note for Windows users on 64-bit systems:

Progra~1 = 'Program Files'
Progra~2 = 'Program Files(x86)'

Notice that these environment variables are derived from the "root" environment variable JAVA_HOME. This makes it easy to update your environment variables when updating the JDK. Just point JAVA_HOME to the fresh installation.

There is a blogpost explaining the rationale behind all these environment variables.

Optional recommendations

  • Add an user environment variable JAVA_TOOL_OPTIONS with value -Dfile.encoding="UTF-8". This ensures that Java (and tools such as Maven) will run with a Charset.defaultCharset() of UTF-8 (instead of the default Windows-1252). This has saved a lot of headaches when wirking with my own code and that of others, which unfortunately often assume the (sane) default encoding UTF-8.
  • When JDK is installed, it adds to the system environment variable Path an entry C:\ProgramData\Oracle\Java\javapath;. I anecdotally noticed that the links in that directory didn't get updated during an JDK installation update. So it's best to remove C:\ProgramData\Oracle\Java\javapath; from the Path system environment variable in order to have a consistent environment.

CSS3 Transparency + Gradient

The following is the one that I'm using to generate a vertical gradient from completely opaque (top) to 20% in transparency (bottom) for the same color:

background: linear-gradient(to bottom, rgba(0, 64, 122, 1) 0%,rgba(0, 64, 122, 0.8) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
background: -o-linear-gradient(top, rgba(0, 64, 122, 1) 0%, rgba(0, 64, 122, 0.8) 100%); /* Opera 11.10+ */
background: -moz-linear-gradient(top, rgba(0, 64, 122, 1) 0%, rgba(0, 64, 122, 0.8) 100%); /* FF3.6-15 */
background: -webkit-linear-gradient(top, rgba(0, 64, 122, 1) 0%,rgba(0, 64, 122, 0.8) 100%); /* Chrome10-25,Safari5.1-6 */
background: -ms-linear-gradient(top, rgba(0, 64, 122, 1) 0%,rgba(0, 64, 122, 0.8) 100%); /* IE10+ */
-ms-filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00407a', endColorstr='#cc00407a',GradientType=0 ); /* IE8 */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00407a', endColorstr='#cc00407a',GradientType=0 ); /* IE 5.5 - 9 */

Do standard windows .ini files allow comments?

Windows INI API support for:

  • Line comments: yes, using semi-colon ;
  • Trailing comments: No

The authoritative source is the Windows API function that reads values out of INI files

GetPrivateProfileString

Retrieves a string from the specified section in an initialization file.

The reason "full line comments" work is because the requested value does not exist. For example, when parsing the following ini file contents:

[Application]
UseLiveData=1
;coke=zero
pepsi=diet   ;gag
#stackoverflow=splotchy

Reading the values:

  • UseLiveData: 1
  • coke: not present
  • ;coke: not present
  • pepsi: diet ;gag
  • stackoverflow: not present
  • #stackoverflow: splotchy

Update: I used to think that the number sign (#) was a pseudo line-comment character. The reason using leading # works to hide stackoverflow is because the name stackoverflow no longer exists. And it turns out that semi-colon (;) is a line-comment.

But there is no support for trailing comments.

Visual Studio breakpoints not being hit

The issue was resolved by unchecking the

Properties > Build > Optimize Code

setting on the web page properties screen (under General).

Screenshot.

MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

I know that people will probably find this very obvious at first, but really think about this. This can often happen if you've done something wrong.

For instance, I've had this problem because I didn't add a host entry to my hosts file. The real problem was DNS resolution. Or I just got the base URL wrong.

Sometimes I get this error if the identity token came from one server, but I'm trying to use it on another.

Sometimes you'll get this error if you've got the resource wrong.

You might get this if you put the CORS middleware too late in the chain.

The openssl extension is required for SSL/TLS protection

enter image description here You are running Composer with SSL/TLS protection disabled.

 composer config --global disable-tls true
 composer config --global disable-tls false

SQL left join vs multiple tables on FROM line?

To the database, they end up being the same. For you, though, you'll have to use that second syntax in some situations. For the sake of editing queries that end up having to use it (finding out you needed a left join where you had a straight join), and for consistency, I'd pattern only on the 2nd method. It'll make reading queries easier.

Set default host and port for ng serve in config file

This changed in the latest Angular CLI.

The file name changed to angular.json, and the structure also changed.

This is what you should do:

"projects": {
    "project-name": {
        ...
        "architect": {
            "serve": {
                "options": {
                  "host": "foo.bar",
                  "port": 80
                }
            }
        }
        ...
    }
}

jQuery select by attribute using AND and OR operators

How about writing a filter like below,

$('[myc="blue"]').filter(function () {
   return (this.id == '1' || this.id == '3');
});

Edit: @Jack Thanks.. totally missed it..

$('[myc="blue"]').filter(function() {
   var myId = $(this).attr('myid');   
   return (myId == '1' || myId == '3');
});

DEMO

How do I implement basic "Long Polling"?

Below is a long polling solution I have developed for Inform8 Web. Basically you override the class and implement the loadData method. When the loadData returns a value or the operation times out it will print the result and return.

If the processing of your script may take longer than 30 seconds you may need to alter the set_time_limit() call to something longer.

Apache 2.0 license. Latest version on github https://github.com/ryanhend/Inform8/blob/master/Inform8-web/src/config/lib/Inform8/longpoll/LongPoller.php

Ryan

abstract class LongPoller {

  protected $sleepTime = 5;
  protected $timeoutTime = 30;

  function __construct() {
  }


  function setTimeout($timeout) {
    $this->timeoutTime = $timeout;
  }

  function setSleep($sleep) {
    $this->sleepTime = $sleepTime;
  }


  public function run() {
    $data = NULL;
    $timeout = 0;

    set_time_limit($this->timeoutTime + $this->sleepTime + 15);

    //Query database for data
    while($data == NULL && $timeout < $this->timeoutTime) {
      $data = $this->loadData();
      if($data == NULL){

        //No new orders, flush to notify php still alive
        flush();

        //Wait for new Messages
        sleep($this->sleepTime);
        $timeout += $this->sleepTime;
      }else{
        echo $data;
        flush();
      }
    }

  }


  protected abstract function loadData();

}

Express: How to pass app-instance to routes from a different file?

Let's say that you have a folder named "contollers".

In your app.js you can put this code:

console.log("Loading controllers....");
var controllers = {};

var controllers_path = process.cwd() + '/controllers'

fs.readdirSync(controllers_path).forEach(function (file) {
    if (file.indexOf('.js') != -1) {
        controllers[file.split('.')[0]] = require(controllers_path + '/' + file)
    }
});

console.log("Controllers loaded..............[ok]");

... and ...

router.get('/ping', controllers.ping.pinging);

in your controllers forlder you will have the file "ping.js" with this code:

exports.pinging = function(req, res, next){
    console.log("ping ...");
}

And this is it....

Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()'

I installed webapi with it via the helppages nuget package. That package replaced most of the asp.net mvc 4 binaries with beta versions which didn't work well together with the rest of the project. Fix was to restore the original mvc 4 dll's and all was good.

Move seaborn plot legend to a different position?

it seems you can directly call:

g = sns.factorplot("class", "survived", "sex",
                data=titanic, kind="bar",
                size=6, palette="muted",
               legend_out=False)

g._legend.set_bbox_to_anchor((.7, 1.1))

Converting a String to DateTime

String now = DateTime.Now.ToString("YYYY-MM-DD HH:MI:SS");//make it datetime
DateTime.Parse(now);

this one gives you

2019-08-17 11:14:49.000

Definition of int64_t

a) Can you explain to me the difference between int64_t and long (long int)? In my understanding, both are 64 bit integers. Is there any reason to choose one over the other?

The former is a signed integer type with exactly 64 bits. The latter is a signed integer type with at least 32 bits.

b) I tried to look up the definition of int64_t on the web, without much success. Is there an authoritative source I need to consult for such questions?

http://cppreference.com covers this here: http://en.cppreference.com/w/cpp/types/integer. The authoritative source, however, is the C++ standard (this particular bit can be found in §18.4 Integer types [cstdint]).

c) For code using int64_t to compile, I am including <iostream>, which doesn't make much sense to me. Are there other includes that provide a declaration of int64_t?

It is declared in <cstdint> or <cinttypes> (under namespace std), or in <stdint.h> or <inttypes.h> (in the global namespace).

How to update a claim in ASP.NET Identity?

I am using a .net core 2.2 app and used the following solution: in my statup.cs

public void ConfigureServices(IServiceCollection services)
        {
        ...
           services.AddIdentity<IdentityUser, IdentityRole>(options =>
               {
                  ...
               })
               .AddEntityFrameworkStores<AdminDbContext>()
               .AddDefaultTokenProviders()
               .AddSignInManager();

usage

  private readonly SignInManager<IdentityUser> _signInManager;


        public YourController(
                                    ...,
SignInManager<IdentityUser> signInManager)
        {
           ...
            _signInManager = signInManager;
        }

 public async Task<IActionResult> YourMethod() // <-NOTE IT IS ASYNC
        {
                var user = _userManager.FindByNameAsync(User.Identity.Name).Result;
                var claimToUse = ClaimsHelpers.CreateClaim(ClaimTypes.ActiveCompany, JsonConvert.SerializeObject(cc));
                var claimToRemove = _userManager.GetClaimsAsync(user).Result
                    .FirstOrDefault(x => x.Type == ClaimTypes.ActiveCompany.ToString());
                if (claimToRemove != null)
                {
                    var result = _userManager.ReplaceClaimAsync(user, claimToRemove, claimToUse).Result;
                    await _signInManager.RefreshSignInAsync(user); //<--- THIS
                }
                else ...
              

Changing background colour of tr element on mouseover

You can give the tr an id and do it.

tr#element{
    background-color: green;
    cursor: pointer;
    height: 30px;

}

tr#element:hover{
    background-color: blue;
    cursor: pointer;

}

<table width="400px">
<tr id="element">
<td></td>
</tr>
</table>

onclick="location.href='link.html'" does not load page in Safari

You can try this:

 <a href="link.html">
       <input type="button" value="Visit Page" />
    </a>

This will create button inside a link and it works on any browser

Android: No Activity found to handle Intent error? How it will resolve

Generally to avoid this kind of exceptions, you will need to surround your code by try and catch like this

try{

// your intent here

} catch (ActivityNotFoundException e) {
// show message to user 
}

How to connect to mysql with laravel?

I spent a lot of time trying to figure this one out. Finally, I tried shutting down my development server and booting it up again. Frustratingly, this worked for me. I came to the conclusion, that after editing the .env file in Laravel 5, you have to exit the server, and run php artisan serve again.

.htaccess mod_rewrite - how to exclude directory from rewrite rule

We used the following mod_rewrite rule:

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/test/
RewriteCond %{REQUEST_URI} !^/my-folder/
RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]

This redirects (permanently with a 301 redirect) all traffic to the site to http://www.newdomain.com, except requests to resources in the /test and /my-folder directories. We transfer the user to the exact resource they requested by using the (.*) capture group and then including $1 in the new URL. Mind the spaces.

Sending email with PHP from an SMTP server

For Unix users, mail() is actually using Sendmail command to send email. Instead of modifying the application, you can change the environment. msmtp is an SMTP client with Sendmail compatible CLI syntax which means it can be used in place of Sendmail. It only requires a small change to your php.ini.

sendmail_path = "/usr/bin/msmtp -C /path/to/your/config -t"

Then even the lowly mail() function can work with SMTP goodness. It is super useful if you're trying to connect an existing application to mail services like sendgrid or mandrill without modifying the application.

How to get box-shadow on left & right sides only

Another idea could be creating a dark blurred pseudo element eventually with transparency to imitate shadow. Make it with slightly less height and more width i.g.

How to send data in request body with a GET when using jQuery $.ajax()

we all know generally that for sending the data according to the http standards we generally use POST request. But if you really want to use Get for sending the data in your scenario I would suggest you to use the query-string or query-parameters.

1.GET use of Query string as. {{url}}admin/recordings/some_id

here the some_id is mendatory parameter to send and can be used and req.params.some_id at server side.

2.GET use of query string as{{url}}admin/recordings?durationExact=34&isFavourite=true

here the durationExact ,isFavourite is optional strings to send and can be used and req.query.durationExact and req.query.isFavourite at server side.

3.GET Sending arrays {{url}}admin/recordings/sessions/?os["Windows","Linux","Macintosh"]

and you can access those array values at server side like this

let osValues = JSON.parse(req.query.os);
        if(osValues.length > 0)
        {
            for (let i=0; i<osValues.length; i++)
            {
                console.log(osValues[i])
                //do whatever you want to do here
            }
        }

How to write PNG image to string with the PIL?

You can use the BytesIO class to get a wrapper around strings that behaves like a file. The BytesIO object provides the same interface as a file, but saves the contents just in memory:

import io

with io.BytesIO() as output:
    image.save(output, format="GIF")
    contents = output.getvalue()

You have to explicitly specify the output format with the format parameter, otherwise PIL will raise an error when trying to automatically detect it.

If you loaded the image from a file it has a format parameter that contains the original file format, so in this case you can use format=image.format.

In old Python 2 versions before introduction of the io module you would have used the StringIO module instead.

Mapping over values in a python dictionary

While my original answer missed the point (by trying to solve this problem with the solution to Accessing key in factory of defaultdict), I have reworked it to propose an actual solution to the present question.

Here it is:

class walkableDict(dict):
  def walk(self, callback):
    try:
      for key in self:
        self[key] = callback(self[key])
    except TypeError:
      return False
    return True

Usage:

>>> d = walkableDict({ k1: v1, k2: v2 ... })
>>> d.walk(f)

The idea is to subclass the original dict to give it the desired functionality: "mapping" a function over all the values.

The plus point is that this dictionary can be used to store the original data as if it was a dict, while transforming any data on request with a callback.

Of course, feel free to name the class and the function the way you want (the name chosen in this answer is inspired by PHP's array_walk() function).

Note: Neither the try-except block nor the return statements are mandatory for the functionality, they are there to further mimic the behavior of the PHP's array_walk.

How to test code dependent on environment variables using JUnit?

Hope the issue is resolved. I just thought to tell my solution.

Map<String, String> env = System.getenv();
    new MockUp<System>() {
        @Mock           
        public String getenv(String name) 
        {
            if (name.equalsIgnoreCase( "OUR_OWN_VARIABLE" )) {
                return "true";
            }
            return env.get(name);
        }
    };

How do I programmatically set the value of a select box element using JavaScript?

You most likely want this:

$("._statusDDL").val('2');

OR

$('select').prop('selectedIndex', 3); 

Jquery date picker z-index issue

simply in your css use '.ui-datepicker{ z-index: 9999 !important;}' Here 9999 can be replaced to whatever layer value you want your datepicker available. Neither any code is to be commented nor adding 'position:relative;' css on input elements. Because increasing the z-index of input elements will have effect on all input type buttons, which may not be needed for some cases.

What is the default value for Guid?

You can use these methods to get an empty guid. The result will be a guid with all it's digits being 0's - "00000000-0000-0000-0000-000000000000".

new Guid()

default(Guid)

Guid.Empty

How can I create a blank/hardcoded column in a sql query?

SELECT
    hat,
    shoe,
    boat,
    0 as placeholder
FROM
    objects

And '' as placeholder for strings.

Set Culture in an ASP.Net MVC app

What is the best place is your question. The best place is inside the Controller.Initialize method. MSDN writes that it is called after the constructor and before the action method. In contrary of overriding OnActionExecuting, placing your code in the Initialize method allow you to benefit of having all custom data annotation and attribute on your classes and on your properties to be localized.

For example, my localization logic come from an class that is injected to my custom controller. I have access to this object since Initialize is called after the constructor. I can do the Thread's culture assignation and not having every error message displayed correctly.

 public BaseController(IRunningContext runningContext){/*...*/}

 protected override void Initialize(RequestContext requestContext)
 {
     base.Initialize(requestContext);
     var culture = runningContext.GetCulture();
     Thread.CurrentThread.CurrentUICulture = culture;
     Thread.CurrentThread.CurrentCulture = culture;
 }

Even if your logic is not inside a class like the example I provided, you have access to the RequestContext which allow you to have the URL and HttpContext and the RouteData which you can do basically any parsing possible.

How to print the contents of RDD?

The map function is a transformation, which means that Spark will not actually evaluate your RDD until you run an action on it.

To print it, you can use foreach (which is an action):

linesWithSessionId.foreach(println)

To write it to disk you can use one of the saveAs... functions (still actions) from the RDD API