Programs & Examples On #Ieee 754

IEEE 754 is the Institute of Electrical and Electronics Engineers standard for floating-point computation, and is the most common & widely used floating-point standard.

biggest integer that can be stored in a double

The biggest/largest integer that can be stored in a double without losing precision is the same as the largest possible value of a double. That is, DBL_MAX or approximately 1.8 × 10308 (if your double is an IEEE 754 64-bit double). It's an integer. It's represented exactly. What more do you want?

Go on, ask me what the largest integer is, such that it and all smaller integers can be stored in IEEE 64-bit doubles without losing precision. An IEEE 64-bit double has 52 bits of mantissa, so I think it's 253:

  • 253 + 1 cannot be stored, because the 1 at the start and the 1 at the end have too many zeros in between.
  • Anything less than 253 can be stored, with 52 bits explicitly stored in the mantissa, and then the exponent in effect giving you another one.
  • 253 obviously can be stored, since it's a small power of 2.

Or another way of looking at it: once the bias has been taken off the exponent, and ignoring the sign bit as irrelevant to the question, the value stored by a double is a power of 2, plus a 52-bit integer multiplied by 2exponent - 52. So with exponent 52 you can store all values from 252 through to 253 - 1. Then with exponent 53, the next number you can store after 253 is 253 + 1 × 253 - 52. So loss of precision first occurs with 253 + 1.

Float and double datatype in Java

The Wikipedia page on it is a good place to start.

To sum up:

  • float is represented in 32 bits, with 1 sign bit, 8 bits of exponent, and 23 bits of the significand (or what follows from a scientific-notation number: 2.33728*1012; 33728 is the significand).

  • double is represented in 64 bits, with 1 sign bit, 11 bits of exponent, and 52 bits of significand.

By default, Java uses double to represent its floating-point numerals (so a literal 3.14 is typed double). It's also the data type that will give you a much larger number range, so I would strongly encourage its use over float.

There may be certain libraries that actually force your usage of float, but in general - unless you can guarantee that your result will be small enough to fit in float's prescribed range, then it's best to opt with double.

If you require accuracy - for instance, you can't have a decimal value that is inaccurate (like 1/10 + 2/10), or you're doing anything with currency (for example, representing $10.33 in the system), then use a BigDecimal, which can support an arbitrary amount of precision and handle situations like that elegantly.

Formatting doubles for output in C#

The answer to this is simple and can be found on MSDN

Remember that a floating-point number can only approximate a decimal number, and that the precision of a floating-point number determines how accurately that number approximates a decimal number. By default, a Double value contains 15 decimal digits of precision, although a maximum of 17 digits is maintained internally.

In your example, the value of i is 6.89999999999999946709 which has the number 9 for all positions between the 3rd and the 16th digit (remember to count the integer part in the digits). When converting to string, the framework rounds the number to the 15th digit.

i     = 6.89999999999999 946709
digit =           111111 111122
        1 23456789012345 678901

Ranges of floating point datatype in C?

As dasblinkenlight already answered, the numbers come from the way that floating point numbers are represented in IEEE-754, and Andreas has a nice breakdown of the maths.

However - be careful that the precision of floating point numbers isn't exactly 6 or 15 significant decimal digits as the table suggests, since the precision of IEEE-754 numbers depends on the number of significant binary digits.

  • float has 24 significant binary digits - which depending on the number represented translates to 6-8 decimal digits of precision.

  • double has 53 significant binary digits, which is approximately 15 decimal digits.

Another answer of mine has further explanation if you're interested.

Double precision - decimal places

It is because it's being converted from a binary representation. Just because it has printed all those decimal digits doesn't mean it can represent all decimal values to that precision. Take, for example, this in Python:

>>> 0.14285714285714285
0.14285714285714285
>>> 0.14285714285714286
0.14285714285714285

Notice how I changed the last digit, but it printed out the same number anyway.

Superscript in Python plots

If you want to write unit per meter (m^-1), use $m^{-1}$), which means -1 inbetween {}

Example: plt.ylabel("Specific Storage Values ($m^{-1}$)", fontsize = 12 )

IIS: Idle Timeout vs Recycle

Idle Timeout is if no action has been asked from your web app, it the process will drop and release everything from memory

Recycle is a forced action on the application where your processed is closed and started again, for memory leaking purposes and system health

The negative impact of both is usually the use of your Session and Application state is lost if you mess with Recycle to a faster time.(logged in users etc will be logged out, if they where about to "check out" all would have been lost" that's why recycle is at such a large time out value, idle timeout doesn't matter because nobody is logged in anyway and figure 20 minutes an no action they are not still "shopping"

The positive would be get rid of the idle time out as your website will respond faster on its "first" response if its not a highly active site where a user would have to wait for it to load if you have 1 user every 20 minutes lets say. So a website that get his less then 1 time in 20 minutes actually you would want to increase this value as the website has to load up again from scratch for each user. but if you set this to 0 over a long time, any memory leaks in code could over a certain amount of time, entirely take over the server.

Format an Integer using Java String Format

If you are using a third party library called apache commons-lang, the following solution can be useful:

Use StringUtils class of apache commons-lang :

int i = 5;
StringUtils.leftPad(String.valueOf(i), 3, "0"); // --> "005"

As StringUtils.leftPad() is faster than String.format()

How to extract the first two characters of a string in shell scripting?

You've gotten several good answers and I'd go with the Bash builtin myself, but since you asked about sed and awk and (almost) no one else offered solutions based on them, I offer you these:

echo "USCAGoleta9311734.5021-120.1287855805" | awk '{print substr($0,0,2)}'

and

echo "USCAGoleta9311734.5021-120.1287855805" | sed 's/\(^..\).*/\1/'

The awk one ought to be fairly obvious, but here's an explanation of the sed one:

  • substitute "s/"
  • the group "()" of two of any characters ".." starting at the beginning of the line "^" and followed by any character "." repeated zero or more times "*" (the backslashes are needed to escape some of the special characters)
  • by "/" the contents of the first (and only, in this case) group (here the backslash is a special escape referring to a matching sub-expression)
  • done "/"

Check if cookies are enabled

JavaScript

You could create a cookie using JavaScript and check if it exists:

//Set a Cookie`
document.cookie="testcookie"`

//Check if cookie exists`
cookiesEnabled=(document.cookie.indexOf("testcookie")!=-1)? true : false`

Or you could use a jQuery Cookie plugin

//Set a Cookie`
$.cookie("testcookie", "testvalue")

//Check if cookie exists`
cookiesEnabled=( $.cookie("testcookie") ) ? true : false`

Php

setcookie("testcookie", "testvalue");

if( isset( $_COOKIE['testcookie'] ) ) {

}

Not sure if the Php will work as I'm unable to test it.

How can I get sin, cos, and tan to use degrees instead of radians?

You can use a function like this to do the conversion:

function toDegrees (angle) {
  return angle * (180 / Math.PI);
}

Note that functions like sin, cos, and so on do not return angles, they take angles as input. It seems to me that it would be more useful to you to have a function that converts a degree input to radians, like this:

function toRadians (angle) {
  return angle * (Math.PI / 180);
}

which you could use to do something like tan(toRadians(45)).

count number of characters in nvarchar column

text doesn't work with len function.

ntext, text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead. For more information, see Using Large-Value Data Types.

Source

Tooltip on image

You can use the standard HTML title attribute of image for this:

<img src="source of image" alt="alternative text" title="this will be displayed as a tooltip"/>

Is there a better way to compare dictionary values

If your values are hashable (ie. strings), then you can simply compare the ItemsView of the two dicts.

https://docs.python.org/3/library/stdtypes.html#dict-views

set_with_unique_key_value_pairs = dict1.items() ^ dict2.items()
set_with_matching_key_value_pairs = dict1.items() & dict2.items()

Any set operations are available to you.

Since you might not care about keys in this case, you can also just use the ValuesView (again, provided the values are hashable).

set_with_matching_values = dict1.values() & dict2.values()

Creating new table with SELECT INTO in SQL

The syntax for creating a new table is

CREATE TABLE new_table
AS
SELECT *
  FROM old_table

This will create a new table named new_table with whatever columns are in old_table and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.

SELECT INTO is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.

Json.NET serialize object with root name

A very simple approach for me is just to create 2 classes.

public class ClassB
{
    public string id{ get; set; }
    public string name{ get; set; }
    public int status { get; set; }
    public DateTime? updated_at { get; set; }
}

public class ClassAList
{
    public IList<ClassB> root_name{ get; set; } 
}

And when you going to do serialization:

var classAList = new ClassAList();
//...
//assign some value
//...
var jsonString = JsonConvert.SerializeObject(classAList)

Lastly, you will see your desired result as the following:

{
  "root_name": [
    {
      "id": "1001",
      "name": "1000001",
      "status": 1010,
      "updated_at": "2016-09-28 16:10:48"
    },
    {
      "id": "1002",
      "name": "1000002",
      "status": 1050,
      "updated_at": "2016-09-28 16:55:55"
    }
  ]
}

Hope this helps!

No signing certificate "iOS Distribution" found

Double click and install the production certificate in your key chain. This might resolve the issue.

How do I set an un-selectable default description in a select (drop-down) menu in HTML?

<option value="" selected disabled hidden>Default Text</option>

Leaving the disabled flag in prevents them from not selecting an option and the hidden flag will remove it from the list. In my case I was using it with an enum list as well and the concept holds the same

<select asp-for="Property" asp-items="Html.GetEnumSelectList<PropertyEnum>()">
                        <option value="" selected disabled hidden>Select Property Enum</option>
                        <option value=""></option>
                    </select>

StringStream in C#

Since your Print() method presumably deals with Text data, could you rewrite it to accept a TextWriter parameter?

The library provides a StringWriter: TextWriter but not a StringStream. I suppose you could create one by wrapping a MemoryStream, but is it really necessary?


After the Update:

void Main() 
{
  string myString;  // outside using

  using (MemoryStream stream = new MemoryStream ())
  {
     Print(stream);
     myString = Encoding.UTF8.GetString(stream.ToArray());
  }
  ... 

}

You may want to change UTF8 to ASCII, depending on the encoding used by Print().

How do I render a Word document (.doc, .docx) in the browser using JavaScript?

If you wanted to pre-process your DOCX files, rather than waiting until runtime you could convert them into HTML first by using a file conversion API such as Zamzar. You could use the API to programatically convert from DOCX to HMTL, save the output to your server and then serve that HTML up to your end users.

Conversion is pretty easy:

curl https://api.zamzar.com/v1/jobs \
-u API_KEY: \
-X POST \
-F "[email protected]" \
-F "target_format=html5"

This would remove any runtime dependencies on Google & Microsoft's services (for example if they were down, or you were rate limited by them).

It also has the benefit that you could extend to other filetypes if you wanted (PPTX, XLS, DOC etc)

Best way to repeat a character in C#

Without a doubt the accepted answer is the best and fastest way to repeat a single character.

Binoj Anthony's answer is a simple and quite efficient way to repeat a string.

However, if you don't mind a little more code, you can use my array fill technique to efficiently create these strings even faster. In my comparison tests, the code below executed in about 35% of the time of the StringBuilder.Insert code.

public static string Repeat(this string value, int count)
{
    var values = new char[count * value.Length];
    values.Fill(value.ToCharArray());
    return new string(values);
}

public static void Fill<T>(this T[] destinationArray, params T[] value)
{
    if (destinationArray == null)
    {
        throw new ArgumentNullException("destinationArray");
    }

    if (value.Length > destinationArray.Length)
    {
        throw new ArgumentException("Length of value array must not be more than length of destination");
    }

    // set the initial array value
    Array.Copy(value, destinationArray, value.Length);

    int copyLength, nextCopyLength;

    for (copyLength = value.Length; (nextCopyLength = copyLength << 1) < destinationArray.Length; copyLength = nextCopyLength)
    {
        Array.Copy(destinationArray, 0, destinationArray, copyLength, copyLength);
    }

    Array.Copy(destinationArray, 0, destinationArray, copyLength, destinationArray.Length - copyLength);
}

For more about this array fill technique, see Fastest way to fill an array with a single value

Fixing npm path in Windows 8 and 10

When you're on Windows but running VS Code in Windows Subsystem for Linux like this

linux@user: /home$ code .

you actually want to install NodeJs on Linux with

linux@user: /home$ sudo apt install nodejs

Installing NodeJs on Windows, modifying PATH and restarting will get you no results.

App installation failed due to application-identifier entitlement

Steps

  1. With your device connected, and Xcode open, select Window->Devices
  2. Now select the app and download the container using setting icon
  3. Delete the app
  4. Install app again using Xcode
  5. Stop from Xcode
  6. Go to Window->Device and select the app and replace the container that is backup from previous app

jQuery AJAX submit form

I really liked this answer by superluminary and especially the way he wrapped is solution in a jQuery plugin. So thanks to superluminary for a very useful answer. In my case, though, I wanted a plugin that would allow me to define the success and error event handlers by means of options when the plugin is initialized.

So here is what I came up with:

;(function(defaults, $, undefined) {
    var getSubmitHandler = function(onsubmit, success, error) {
        return function(event) {
            if (typeof onsubmit === 'function') {
                onsubmit.call(this, event);
            }
            var form = $(this);
            $.ajax({
                type: form.attr('method'),
                url: form.attr('action'),
                data: form.serialize()
            }).done(function() {
                if (typeof success === 'function') {
                    success.apply(this, arguments);
                }
            }).fail(function() {
                if (typeof error === 'function') {
                    error.apply(this, arguments);
                }
            });
            event.preventDefault();
        };
    };
    $.fn.extend({
        // Usage:
        // jQuery(selector).ajaxForm({ 
        //                              onsubmit:function() {},
        //                              success:function() {}, 
        //                              error: function() {} 
        //                           });
        ajaxForm : function(options) {
            options = $.extend({}, defaults, options);
            return $(this).each(function() {
                $(this).submit(getSubmitHandler(options['onsubmit'], options['success'], options['error']));
            });
        }
    });
})({}, jQuery);

This plugin allows me to very easily "ajaxify" html forms on the page and provide onsubmit, success and error event handlers for implementing feedback to the user of the status of the form submit. This allowed the plugin to be used as follows:

 $('form').ajaxForm({
      onsubmit: function(event) {
          // User submitted the form
      },
      success: function(data, textStatus, jqXHR) {
          // The form was successfully submitted
      },
      error: function(jqXHR, textStatus, errorThrown) {
          // The submit action failed
      }
 });

Note that the success and error event handlers receive the same arguments that you would receive from the corresponding events of the jQuery ajax method.

Filter Pyspark dataframe column with None value

There are multiple ways you can remove/filter the null values from a column in DataFrame.

Lets create a simple DataFrame with below code:

date = ['2016-03-27','2016-03-28','2016-03-29', None, '2016-03-30','2016-03-31']
df = spark.createDataFrame(date, StringType())

Now you can try one of the below approach to filter out the null values.

# Approach - 1
df.filter("value is not null").show()

# Approach - 2
df.filter(col("value").isNotNull()).show()

# Approach - 3
df.filter(df["value"].isNotNull()).show()

# Approach - 4
df.filter(df.value.isNotNull()).show()

# Approach - 5
df.na.drop(subset=["value"]).show()

# Approach - 6
df.dropna(subset=["value"]).show()

# Note: You can also use where function instead of a filter.

You can also check the section "Working with NULL Values" on my blog for more information.

I hope it helps.

Set the selected index of a Dropdown using jQuery

This will work:

<head>
    <script type="text/javascript">
        function Init () {
            var counter = document.getElementById ("counter");
            for (var i = 1; i < 1000; i++) {
                var option = new Option (i, i);
                counter.options.add (option);
            }
            counter.focus ();
        }
        
        function OnKeyPressCounter (event, counter) {
            var chCode = ('charCode' in event) ? event.charCode : event.keyCode;
        
            if (chCode == 68 /* + */) {
                if (counter.selectedIndex < counter.options.length - 1) {
                    counter.selectedIndex++;
                }
            }
            if (chCode == 45 /* - */) {
                if (counter.selectedIndex > 0) {
                    counter.selectedIndex--;
                }
            }
        }
    </script>
</head>
<body onload="Init ()">
    Use the + and - keys to increase/decrease the counter.
    <select id="counter" onkeypress="OnKeyPressCounter(event, this)" style="width:80px"></select>
</body>

Cygwin Make bash command not found

I had the same problem and it was due to several installations of cygwin.

Check the link (the icon) that you click on to start the terminal. In case it does not point to the directory of your updated cygwin installation, you have the wrong installation of cygwin. When updating, double check the location of cygwin, and start exactly this instance of cygwin.

How do I convert a double into a string in C++?

The boost (tm) way:

std::string str = boost::lexical_cast<std::string>(dbl);

The Standard C++ way:

std::ostringstream strs;
strs << dbl;
std::string str = strs.str();

Note: Don't forget #include <sstream>

Remove scroll bar track from ScrollView in Android

Solved my problem by adding this to my ListView:

android:scrollbars="none"

How to send multiple data fields via Ajax?

I am a beginner at ajax but I think to use this "data: {status: status, name: name}" method datatype must be set to JSON i.e

$.ajax({
type: "POST",
dataType: "json",
url: "ajax/activity_save.php",
data: {status: status, name: name},

Moment Js UTC to Local Time

let utcTime = "2017-02-02 08:00:13.567";
var offset = moment().utcOffset();
var localText = moment.utc(utcTime).utcOffset(offset).format("L LT");

Try this JsFiddle

Why does javascript map function return undefined?

You can implement like a below logic. Suppose you want an array of values.

let test = [ {name:'test',lastname:'kumar',age:30},
             {name:'test',lastname:'kumar',age:30},
             {name:'test3',lastname:'kumar',age:47},
             {name:'test',lastname:'kumar',age:28},
             {name:'test4',lastname:'kumar',age:30},
             {name:'test',lastname:'kumar',age:29}]

let result1 = test.map(element => 
              { 
                 if (element.age === 30) 
                 {
                    return element.lastname;
                 }
              }).filter(notUndefined => notUndefined !== undefined);

output : ['kumar','kumar','kumar']

How to send only one UDP packet with netcat?

Netcat sends one packet per newline. So you're fine. If you do anything more complex then you might need something else.

I was fooling around with Wireshark when I realized this. Don't know if it helps.

What does Include() do in LINQ?

Let's say for instance you want to get a list of all your customers:

var customers = context.Customers.ToList();

And let's assume that each Customer object has a reference to its set of Orders, and that each Order has references to LineItems which may also reference a Product.

As you can see, selecting a top-level object with many related entities could result in a query that needs to pull in data from many sources. As a performance measure, Include() allows you to indicate which related entities should be read from the database as part of the same query.

Using the same example, this might bring in all of the related order headers, but none of the other records:

var customersWithOrderDetail = context.Customers.Include("Orders").ToList();

As a final point since you asked for SQL, the first statement without Include() could generate a simple statement:

SELECT * FROM Customers;

The final statement which calls Include("Orders") may look like this:

SELECT *
FROM Customers JOIN Orders ON Customers.Id = Orders.CustomerId;

%Like% Query in spring JpaRepository

Try this.

@Query("Select c from Registration c where c.place like '%'||:place||'%'")

How to compile C programming in Windows 7?

Get gcc for Windows . However, you will have to install MinGW as well.

You can use Visual Studio 2010 express edition as well. Link here

2 "style" inline css img tags?

Do not use more than one style attribute. Just seperate styles in the style attribute with ; It is a block of inline CSS, so think of this as you would do CSS in a separate stylesheet.

So in this case its: style="height:100px;width:100px;"

You can use this for any CSS style, so if you wanted to change the colour of the text to white: style="height:100px;width:100px;color:#ffffff" and so on.

However, it is worth using inline CSS sparingly, as it can make code less manageable in future. Using an external stylesheet may be a better option for this. It depends really on your requirements. Inline CSS does make for quicker coding.

Checking if a list is empty with LINQ

This was critical to get this to work with Entity Framework:

var genericCollection = list as ICollection<T>;

if (genericCollection != null)
{
   //your code 
}

How to get first two characters of a string in oracle query?

Try select substr(orderno, 1,2) from shipment;

convert nan value to zero

nan is never equal to nan

if z!=z:z=0

so for a 2D array

for entry in nparr:
    if entry!=entry:entry=0

Unable to specify the compiler with CMake

Never try to set the compiler in the CMakeLists.txt file.

See the CMake FAQ about how to use a different compiler:

https://gitlab.kitware.com/cmake/community/wikis/FAQ#how-do-i-use-a-different-compiler

(Note that you are attempting method #3 and the FAQ says "(avoid)"...)

We recommend avoiding the "in the CMakeLists" technique because there are problems with it when a different compiler was used for a first configure, and then the CMakeLists file changes to try setting a different compiler... And because the intent of a CMakeLists file should be to work with multiple compilers, according to the preference of the developer running CMake.

The best method is to set the environment variables CC and CXX before calling CMake for the very first time in a build tree.

After CMake detects what compilers to use, it saves them in the CMakeCache.txt file so that it can still generate proper build systems even if those variables disappear from the environment...

If you ever need to change compilers, you need to start with a fresh build tree.

How to get absolute value from double - c-language

It's worth noting that Java can overload a method such as abs so that it works with an integer or a double. In C, overloading doesn't exist, so you need different functions for integer versus double.

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

A subtle problem causing even print to fail is having your environment variables set wrong, eg. here LC_ALL set to "C". In Debian they discourage setting it: Debian wiki on Locale

$ echo $LANG
en_US.utf8
$ echo $LC_ALL 
C
$ python -c "print (u'voil\u00e0')"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe0' in position 4: ordinal not in range(128)
$ export LC_ALL='en_US.utf8'
$ python -c "print (u'voil\u00e0')"
voilà
$ unset LC_ALL
$ python -c "print (u'voil\u00e0')"
voilà

You don't have permission to access / on this server

If you set SELinux in permissive mode (command setenforce 0) and it works (worked for me) then you can run restorecon (sudo restorecon -Rv /var/www/html/) which set the correct context to the files in Apache directory permanently because setenforce is temporal. The context for Apache is httpd_sys_content_t and you can verify it running the command ls -Z /var/www/html/ that outputs something like:

-rwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 index.html

In case the file does not have the right context, appear something like this:

drwxr-xr-x. root root unconfined_u:object_r:user_home_t:s0 tests

Hope it can help you.

PD: excuse me my English

How to get response as String using retrofit without using GSON or any other library in android

** Update ** A scalars converter has been added to retrofit that allows for a String response with less ceremony than my original answer below.

Example interface --

public interface GitHubService {
    @GET("/users/{user}")
    Call<String> listRepos(@Path("user") String user);
}

Add the ScalarsConverterFactory to your retrofit builder. Note: If using ScalarsConverterFactory and another factory, add the scalars factory first.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(ScalarsConverterFactory.create())
    // add other factories here, if needed.
    .build();

You will also need to include the scalars converter in your gradle file --

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

--- Original Answer (still works, just more code) ---

I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -

First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --

public interface GitHubService {
    @GET("/users/{user}")
    Call<ResponseBody> listRepos(@Path("user") String user);
}

then you can create and execute your call --

GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Throwable t) {
        e.printStackTrace();
    }
});

Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.

C# HttpWebRequest of type "application/x-www-form-urlencoded" - how to send '&' character in content body?

Since your content-type is application/x-www-form-urlencoded you'll need to encode the POST body, especially if it contains characters like & which have special meaning in a form.

Try passing your string through HttpUtility.UrlEncode before writing it to the request stream.

Here are a couple links for reference.

Ineligible Devices section appeared in Xcode 6.x.x

Ran into the same issue, using Unity3D

=> Xcode 6.3 requires Unity 4.6.4

If you're using an older Unity version (e.g. 4.6.3) you'll always get your devices in the Ineligible Devices section

Fastest way to get the first object from a queryset in django?

You can use array slicing:

Entry.objects.all()[:1].get()

Which can be used with .filter():

Entry.objects.filter()[:1].get()

You wouldn't want to first turn it into a list because that would force a full database call of all the records. Just do the above and it will only pull the first. You could even use .order_by() to ensure you get the first you want.

Be sure to add the .get() or else you will get a QuerySet back and not an object.

Why Response.Redirect causes System.Threading.ThreadAbortException?

There is no simple and elegant solution to the Redirect problem in ASP.Net WebForms. You can choose between the Dirty solution and the Tedious solution

Dirty: Response.Redirect(url) sends a redirect to the browser, and then throws a ThreadAbortedException to terminate the current thread. So no code is executed past the Redirect()-call. Downsides: It is bad practice and have performance implications to kill threads like this. Also, ThreadAbortedExceptions will show up in exception logging.

Tedious: The recommended way is to call Response.Redirect(url, false) and then Context.ApplicationInstance.CompleteRequest() However, code execution will continue and the rest of the event handlers in the page lifecycle will still be executed. (E.g. if you perform the redirect in Page_Load, not only will the rest of the handler be executed, Page_PreRender and so on will also still be called - the rendered page will just not be sent to the browser. You can avoid the extra processing by e.g. setting a flag on the page, and then let subsequent event handlers check this flag before before doing any processing.

(The documentation to CompleteRequest states that it "Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution". This can easily be misunderstood. It does bypass further HTTP filters and modules, but it doesn't bypass further events in the current page lifecycle.)

The deeper problem is that WebForms lacks a level of abstraction. When you are in a event handler, you are already in the process of building a page to output. Redirecting in an event handler is ugly because you are terminating a partially generated page in order to generate a different page. MVC does not have this problem since the control flow is separate from rendering views, so you can do a clean redirect by simply returning a RedirectAction in the controller, without generating a view.

pip not working in Python Installation in Windows 10

I faced a problem upgrading pip from version 9.0.1 to 9.0.3 The upgrade failed middle way(after uninstalling version 9.0.1 and without installing version 9.0.3). This usually creates a broken pip file. Broken pip can be solved by the command-->

easy_install pip

Which usually installs the latest version of pip, and solves the issue. In order to confirm, type

pip --version

Hope this was helpfull...

Eclipse comment/uncomment shortcut?

Source -> Remove Block Comment

link

enter image description here

How to install Boost on Ubuntu

Installing Boost on Ubuntu with an example of using boost::array:

Install libboost-all-dev and aptitude:

sudo apt install libboost-all-dev

sudo apt install aptitude

aptitude search boost

Then paste this into a C++ file called main.cpp:

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

using namespace std;
int main(){
  boost::array<int, 4> arr = {{1,2,3,4}};
  cout << "hi" << arr[0];
  return 0;
}

Compile like this:

g++ -o s main.cpp

Run it like this:

./s

Program prints:

hi1

Is there a way to 'pretty' print MongoDB shell output to a file?

Since you are doing this on a terminal and just want to inspect a record in a sane way, you can use a trick like this:

mongo | tee somefile

Use the session as normal - db.collection.find().pretty() or whatever you need to do, ignore the long output, and exit. A transcript of your session will be in the file tee wrote to.

Be mindful that the output might contain escape sequences and other garbage due to the mongo shell expecting an interactive session. less handles these gracefully.

How do I add 24 hours to a unix timestamp in php?

A Unix timestamp is simply the number of seconds since January the first 1970, so to add 24 hours to a Unix timestamp we just add the number of seconds in 24 hours. (24 * 60 *60)

time() + 24*60*60;

How to close form

You can also close the application:

Application.Exit();

It will end the processes.

Which characters need to be escaped in HTML?

The exact answer depends on the context. In general, these characters must not be present (HTML 5.2 §3.2.4.2.5):

Text nodes and attribute values must consist of Unicode characters, must not contain U+0000 characters, must not contain permanently undefined Unicode characters (noncharacters), and must not contain control characters other than space characters. This specification includes extra constraints on the exact value of Text nodes and attribute values depending on their precise context.

For elements in HTML, the constraints of the Text content model also depends on the kind of element. For instance, an "<" inside a textarea element does not need to be escaped in HTML because textarea is an escapable raw text element.

These restrictions are scattered across the specification. E.g., attribute values (§8.1.2.3) must not contain an ambiguous ampersand and be either (i) empty, (ii) within single quotes (and thus must not contain U+0027 APOSTROPHE character '), (iii) within double quotes (must not contain U+0022 QUOTATION MARK character "), or (iv) unquoted — with the following restrictions:

... must not contain any literal space characters, any U+0022 QUOTATION MARK characters ("), U+0027 APOSTROPHE characters ('), U+003D EQUALS SIGN characters (=), U+003C LESS-THAN SIGN characters (<), U+003E GREATER-THAN SIGN characters (>), or U+0060 GRAVE ACCENT characters (`), and must not be the empty string.

Windows- Pyinstaller Error "failed to execute script " When App Clicked

That error is due to missing of modules in pyinstaller. You can find the missing modules by running script in executable command line, i.e., by removing '-w' from the command. Once you created the command line executable file then in command line it will show the missing modules. By finding those missing modules you can add this to your command : " --hidden-import = missingmodule "

I solved my problem through this.

(XML) The markup in the document following the root element must be well-formed. Start location: 6:2

After insuring that the string "strOutput" has a correct XML structure, you can do this:

Matcher junkMatcher = (Pattern.compile("^([\\W]+)<")).matcher(strOutput);
strOutput = junkMatcher.replaceFirst("<");

PHP display current server path

If you call getcwd it should give you the path:

<?php
  echo getcwd();
?>

How to convert numbers between hexadecimal and decimal

If you want maximum performance when doing conversion from hex to decimal number, you can use the approach with pre-populated table of hex-to-decimal values.

Here is the code that illustrates that idea. My performance tests showed that it can be 20%-40% faster than Convert.ToInt32(...):

class TableConvert
  {
      static sbyte[] unhex_table =
      { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
       ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
       ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
       , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1
       ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
       ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
       ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
       ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
      };

      public static int Convert(string hexNumber)
      {
          int decValue = unhex_table[(byte)hexNumber[0]];
          for (int i = 1; i < hexNumber.Length; i++)
          {
              decValue *= 16;
              decValue += unhex_table[(byte)hexNumber[i]];
          }
          return decValue;
      }
  }

how to delete all cookies of my website in php

<?php
      parse_str(http_build_query($_COOKIE),$arr);
      foreach ($arr as $k=>$v) {
        setCookie("$k","",1000,"/");
      }

SQL: How to perform string does not equal

select * from table
where tester NOT LIKE '%username%';

Column/Vertical selection with Keyboard in SublimeText 3

This should do it:

  1. Ctrl+A - select all.
  2. Ctrl+Shift+L - split selection into lines.
  3. Then move all cursors with left/right, select with Shift+left/right. Move all cursors to start of line with Home.

Select Top and Last rows in a table (SQL server)

To get the bottom 1000 you will want to order it by a column in descending order, and still take the top 1000.

SELECT TOP 1000 *
FROM [SomeTable]
ORDER BY MySortColumn DESC

If you care for it to be in the same order as before you can use a common table expression for that:

;WITH CTE AS (
    SELECT TOP 1000 *
    FROM [SomeTable]
    ORDER BY MySortColumn DESC
)

SELECT * 
FROM CTE
ORDER BY MySortColumn

Questions every good Java/Java EE Developer should be able to answer?

One sure is comparison of string. Difference between

String helloWorld = "Hello World";
helloWorld == "Hello World";
"Hello World".equals(helloWorld);

Spaces cause split in path with PowerShell

There's a hack I've used since the Invoke-Expression works fine for me.

You could set the current location to the path with spaces, invoke the expression, get back to your previous location and continue:

$currLocation = Get-Location
Set-Location = "C:\Windows Services\"
Invoke-Expression ".\MyService.exe"
Set-Location $currLocation

This will only work if the exe doesn't have any spaces in its name.

Hope this helps

How does one check if a table exists in an Android SQLite database?

Important condition is IF NOT EXISTS to check table is already exist or not in database

like...

String query = "CREATE TABLE IF NOT EXISTS " + TABLE_PLAYER_PHOTO + "("
            + KEY_PLAYER_ID + " TEXT,"
            + KEY_PLAYER_IMAGE + " TEXT)";
db.execSQL(query);

How does the "this" keyword work?

Whould this help? (Most confusion of 'this' in javascript is coming from the fact that it generally is not linked to your object, but to the current executing scope -- that might not be exactly how it works but is always feels like that to me -- see the article for a complete explanation)

How to select all records from one table that do not exist in another table?

I don't have enough rep points to vote up froadie's answer. But I have to disagree with the comments on Kris's answer. The following answer:

SELECT name
FROM table2
WHERE name NOT IN
    (SELECT name 
     FROM table1)

Is FAR more efficient in practice. I don't know why, but I'm running it against 800k+ records and the difference is tremendous with the advantage given to the 2nd answer posted above. Just my $0.02.

Enabling WiFi on Android Emulator

(Repeating here my answer elsewhere.)

In theory, linux (the kernel underlying android) has mac80211_hwsim driver, which simulates WiFi. It can be used to set up several WiFi devices (an acces point, and another WiFi device, and so on), which would make up a WiFi network.

It's useful for testing WiFi programs under linux. Possibly, even under user-mode linux or other isolated virtual "boxes" with linux.

In theory, this driver could be used for tests in the android systems where you don't have a real WiFi device (or don't want to use it), and also in some kind of android emulators. Perhaps, one can manage to use this driver in android-x86, or--for testing--in android-x86 run in VirtualBox.

JQuery html() vs. innerHTML

If you're wondering about functionality, then jQuery's .html() performs the same intended functionality as .innerHTML, but it also performs checks for cross-browser compatibility.

For this reason, you can always use jQuery's .html() instead of .innerHTML where possible.

How to add items to a spinner in Android?

This code basically reads a JSON array object and convert each row into an option in the spinner that is passed as a parameter:

public ArrayAdapter<String> getArrayAdapterFromArrayListForSpinner(ArrayList<JSONObject> aArrayList, String aField)
{
    ArrayAdapter<String> aArrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item);
    aArrayAdapter.setDropDownViewResource(R.layout.multiline_spinner_dropdown_item); //android.R.layout.simple_spinner_dropdown_item
    try {
        for (int i = 0; i < aArrayList.size(); i++)
        {
            aArrayAdapter.add(aArrayList.get(i).getString(aField)); 
        }
    } catch (JSONException e) {
        e.printStackTrace();
        ShowMessage("Error while reading the JSON list");
    }
    return aArrayAdapter;       
}

How to while loop until the end of a file in Python without checking for empty line?

for line in f

reads all file to a memory, and that can be a problem.

My offer is to change the original source by replacing stripping and checking for empty line. Because if it is not last line - You will receive at least newline character in it ('\n'). And '.strip()' removes it. But in last line of a file You will receive truely empty line, without any characters. So the following loop will not give You false EOF, and You do not waste a memory:

with open("blablabla.txt", "r") as fl_in:
   while True:
      line = fl_in.readline()

        if not line:
            break

      line = line.strip()
      # do what You want

Simplest way to restart service on a remote computer

If it doesn't require human interaction which means there will be no UI that invokes this operation and I assume it would restart at some set interval? If you have access to machine, you could just set a scheduled task to execute a batch file using good old NET STOP and NET START

net stop "DNS Client"
net start "DNS client"

or if you want to get a little more sophisticated, you could try Powershell

How to format JSON in notepad++

I was unable to find JSTool. Please see below url to see how I installed Notepad++

How to view Plugin Manager in Notepad++

I created JSMinNPP folder in C:\Program Files (x86)\Notepad++\plugins and copied JSMinNPP to it.

enter image description here

enter image description here

Get the new record primary key ID from MySQL insert query?

Here what you are looking for !!!

select LAST_INSERT_ID()

This is the best alternative of SCOPE_IDENTITY() function being used in SQL Server.

You also need to keep in mind that this will only work if Last_INSERT_ID() is fired following by your Insert query. That is the query returns the id inserted in the schema. You can not get specific table's last inserted id.

For more details please go through the link The equivalent of SQLServer function SCOPE_IDENTITY() in mySQL?

Failed to load resource under Chrome

I was getting this error, only in Chrome (last version 24.0.1312.57 m), and only if the image was larger than the html img. I was using a php script to output the image like this:

header('Content-Length: '.strlen($data));
header("Content-type: image/{$ext}");
echo base64_decode($data);

I resolved it adding 1 to the lenght of the image:

header('Content-Length: '.strlen($data) + 1);
header("Content-type: image/{$ext}");
echo base64_decode($data);

Appears that Chrome dont expect the correct number of bytes.

Tested with sucess in Chrome and IE 9. Hope this help.

Efficient way to Handle ResultSet in Java

A couple of things to enhance the other answers. First, you should never return a HashMap, which is a specific implementation. Return instead a plain old java.util.Map. But that's actually not right for this example, anyway. Your code only returns the last row of the ResultSet as a (Hash)Map. You instead want to return a List<Map<String,Object>>. Think about how you should modify your code to do that. (Or you could take Dave Newton's suggestion).

Shuffling a list of objects

'print func(foo)' will print the return value of 'func' when called with 'foo'. 'shuffle' however has None as its return type, as the list will be modified in place, hence it prints nothing. Workaround:

# shuffle the list in place 
random.shuffle(b)

# print it
print(b)

If you're more into functional programming style you might want to make the following wrapper function:

def myshuffle(ls):
    random.shuffle(ls)
    return ls

CSS getting text in one line rather than two

Add white-space: nowrap;:

.garage-title {
    clear: both;
    display: inline-block;
    overflow: hidden;
    white-space: nowrap;
}

jsFiddle

Bootstrap 3 with remote Modal

For Bootstrap 3

The workflow I had to deal with was loading content with a url context that could change. So by default setup your modal with javascript or the href for the default context you want to show :

$('#myModal').modal({
        show: false,
        remote: 'some/context'
});

Destroying the modal wouldn't work for me because I wasn't loading from the same remote, thus I had to :

$(".some-action-class").on('click', function () {
        $('#myModal').removeData('bs.modal');
        $('#myModal').modal({remote: 'some/new/context?p=' + $(this).attr('buttonAttr') });
        $('#myModal').modal('show');
});

This of course was easily refactored into a js library and gives you a lot of flexibility with loading modals

I hope this saves someone 15 minutes of tinkering.

When or Why to use a "SET DEFINE OFF" in Oracle Database

Here is the example:

SQL> set define off;
SQL> select * from dual where dummy='&var';

no rows selected

SQL> set define on
SQL> /
Enter value for var: X
old   1: select * from dual where dummy='&var'
new   1: select * from dual where dummy='X'

D
-
X

With set define off, it took a row with &var value, prompted a user to enter a value for it and replaced &var with the entered value (in this case, X).

How to stop default link click behavior with jQuery

This code strip all event listeners

var old_element=document.getElementsByClassName(".update-cart");    
var new_element = old_element.cloneNode(true);
old_element.parentNode.replaceChild(new_element, old_element);  

How can I get list of values from dict?

Follow the below example --

songs = [
{"title": "happy birthday", "playcount": 4},
{"title": "AC/DC", "playcount": 2},
{"title": "Billie Jean", "playcount": 6},
{"title": "Human Touch", "playcount": 3}
]

print("====================")
print(f'Songs --> {songs} \n')
title = list(map(lambda x : x['title'], songs))
print(f'Print Title --> {title}')

playcount = list(map(lambda x : x['playcount'], songs))
print(f'Print Playcount --> {playcount}')
print (f'Print Sorted playcount --> {sorted(playcount)}')

# Aliter -
print(sorted(list(map(lambda x: x['playcount'],songs))))

How do I combine 2 select statements into one?

select t1.* from 
(select * from TABLE Where CCC='D' AND DDD='X') as t1,
(select * from TABLE Where CCC<>'D' AND DDD='X') as t2

Another way to do this!

Difference between Groovy Binary and Source release?

Binary releases contain computer readable version of the application, meaning it is compiled. Source releases contain human readable version of the application, meaning it has to be compiled before it can be used.

How do I make an input field accept only letters in javaScript?

dep and clg alphabets validation is not working

_x000D_
_x000D_
var selectedRow = null;

function validateform() {

  var table = document.getElementById("mytable");
  var rowCount = table.rows.length;
  console.log(rowCount);

  var x = document.forms["myform"]["usrname"].value;
  if (x == "") {
    alert("name must be filled out");
    return false;
  }

  var y = document.forms["myform"]["usremail"].value;
  if (y == "") {
    alert("email must be filled out");
    return false;
  }
  var mail = /[^@]+@[a-zA-Z]+\.[a-zA-Z]{2,6}/
  if (mail.test(y)) {
    //alert("email must be a valid format");
    //return false ;
  } else {
    alert("not a mail id")
    return false;
  }

  var z = document.forms["myform"]["usrage"].value;
  if (z == "") {
    alert("age must be filled out");
    return false;
  }

  if (isNaN(z) || z < 1 || z > 100) {
    alert("The age must be a number between 1 and 100");
    return false;
  }

  var a = document.forms["myform"]["usrdpt"].value;
  if (a == "") {
    alert("Dept must be filled out");
    return false;
  }

  var dept = "`@#$%^&*()+=-[]\\\';,./{}|\":<>?~_";
  if (dept.match(a)) {
    alert("special charachers found");
    return false;
  }

  var b = document.forms["myform"]["usrclg"].value;
  if (b == "") {
    alert("College must be filled out");
    return false;
  }
  console.log(table);
  var row = table.insertRow(rowCount);
  row.setAttribute('id', rowCount);
  var cell0 = row.insertCell(0);
  var cell1 = row.insertCell(1);
  var cell2 = row.insertCell(2);
  var cell3 = row.insertCell(3);
  var cell4 = row.insertCell(4);
  var cell5 = row.insertCell(5);
  var cell6 = row.insertCell(6);
  var cell7 = row.insertCell(7);


  cell0.innerHTML = rowCount;
  cell1.innerHTML = x;
  cell2.innerHTML = y;
  cell3.innerHTML = z;
  cell4.innerHTML = a;
  cell5.innerHTML = b;
  cell6.innerHTML = '<Button type="button" onclick=onEdit("' + x + '","' + y + '","' + z + '","' + a + '","' + b + '","' + rowCount + '")>Edit</BUTTON>';
  cell7.innerHTML = '<Button type="button" onclick=deletefunction(' + rowCount + ')>Delete</BUTTON>';

}

function emptyfunction() {
  document.getElementById("usrname").value = "";
  document.getElementById("usremail").value = "";
  document.getElementById("usrage").value = "";
  document.getElementById("usrdpt").value = "";
  document.getElementById("usrclg").value = "";
}

function onEdit(x, y, z, a, b, rowCount) {
  selectedRow = rowCount;
  console.log(selectedRow);
  document.forms["myform"]["usrname"].value = x;
  document.forms["myform"]["usremail"].value = y;
  document.forms["myform"]["usrage"].value = z;
  document.forms["myform"]["usrdpt"].value = a;
  document.forms["myform"]["usrclg"].value = b;
  document.getElementById('Add').style.display = 'none';
  document.getElementById('update').style.display = 'block';
}

function deletefunction(rowCount) {
  document.getElementById("mytable").deleteRow(rowCount);
}

function onUpdatefunction() {
  var row = document.getElementById(selectedRow);
  console.log(row);

  var x = document.forms["myform"]["usrname"].value;
  if (x == "") {
    alert("name must be filled out");
    document.myForm.x.focus();
    return false;
  }

  var y = document.forms["myform"]["usremail"].value;
  if (y == "") {
    alert("email must be filled out");
    document.myForm.y.focus();
    return false;
  }

  var mail = /[^@]+@[a-zA-Z]+\.[a-zA-Z]{2,6}/
  if (mail.test(y)) {
    //alert("email must be a valid format");
    //return false ;
  } else {
    alert("not a mail id");

    return false;
  }

  var z = document.forms["myform"]["usrage"].value;
  if (z == "") {
    alert("age must be filled out");
    document.myForm.z.focus();
    return false;
  }
  if (isNaN(z) || z < 1 || z > 100) {
    alert("The age must be a number between 1 and 100");
    return false;
  }

  var a = document.forms["myform"]["usrdpt"].value;
  if (a == "") {
    alert("Dept must be filled out");
    return false;
  }
  var letters = /^[A-Za-z]+$/;
  if (a.test(letters)) {
    //Your logice will be here.
  } else {
    alert("Please enter only alphabets");
    return false;
  }

  var b = document.forms["myform"]["usrclg"].value;
  if (b == "") {
    alert("College must be filled out");
    return false;
  }
  var letters = /^[A-Za-z]+$/;
  if (b.test(letters)) {
    //Your logice will be here.
  } else {
    alert("Please enter only alphabets");
    return false;
  }

  row.cells[1].innerHTML = x;
  row.cells[2].innerHTML = y;
  row.cells[3].innerHTML = z;
  row.cells[4].innerHTML = a;
  row.cells[5].innerHTML = b;
}
_x000D_
<html>

<head>
</head>

<body>
  <form name="myform">
    <h1>
      <center> Admission form </center>
    </h1>
    <center>
      <tr>
        <td>Name :</td>
        <td><input type="text" name="usrname" PlaceHolder="Enter Your First Name" required></td>
      </tr>

      <tr>
        <td> Email ID :</td>
        <td><input type="text" name="usremail" PlaceHolder="Enter Your email address" pattern="[^@]+@[a-zA-Z]+\.[a-zA-Z]{2,6}" required></td>
      </tr>

      <tr>
        <td>Age :</td>
        <td><input type="number" name="usrage" PlaceHolder="Enter Your Age" required></td>
      </tr>

      <tr>
        <td>Dept :</td>
        <td><input type="text" name="usrdpt" PlaceHolder="Enter Dept"></td>
      </tr>

      <tr>
        <td>College :</td>
        <td><input type="text" name="usrclg" PlaceHolder="Enter college"></td>
      </tr>
    </center>

    <center>
      <br>
      <br>
      <tr>
        <td>
          <Button type="button" onclick="validateform()" id="Add">Add</button>
        </td>
        <td>
          <Button type="button" onclick="onUpdatefunction()" style="display:none;" id="update">update</button>
        </td>
        <td><button type="reset">Reset</button></td>
      </tr>
    </center>
    <br><br>
    <center>
      <table id="mytable" border="1">
        <tr>
          <th>SNO</th>
          <th>Name</th>
          <th>Email ID</th>
          <th>Age</th>
          <th>Dept</th>
          <th>College</th>
        </tr>
    </center>
    </table>
  </form>
</body>

</html>
_x000D_
_x000D_
_x000D_

Responsive font size in CSS

Try including this on your style sheet:

html {
  font-size: min(max(16px, 4vw), 22px);
}

More info at https://css-tricks.com/simplified-fluid-typography/

C#: List All Classes in Assembly

I'd just like to add to Jon's example. To get a reference to your own assembly, you can use:

Assembly myAssembly = Assembly.GetExecutingAssembly();

System.Reflection namespace.

If you want to examine an assembly that you have no reference to, you can use either of these:

Assembly assembly = Assembly.ReflectionOnlyLoad(fullAssemblyName);
Assembly assembly = Assembly.ReflectionOnlyLoadFrom(fileName);

If you intend to instantiate your type once you've found it:

Assembly assembly = Assembly.Load(fullAssemblyName);
Assembly assembly = Assembly.LoadFrom(fileName);

See the Assembly class documentation for more information.

Once you have the reference to the Assembly object, you can use assembly.GetTypes() like Jon already demonstrated.

Convert command line arguments into an array in Bash

Side-by-side view of how the array and $@ are practically the same.

Code:

#!/bin/bash

echo "Dollar-1 : $1"
echo "Dollar-2 : $2"
echo "Dollar-3 : $3"
echo "Dollar-AT: $@"
echo ""

myArray=( "$@" )

echo "A Val 0: ${myArray[0]}"
echo "A Val 1: ${myArray[1]}"
echo "A Val 2: ${myArray[2]}"
echo "A All Values: ${myArray[@]}"

Input:

./bash-array-practice.sh 1 2 3 4

Output:

Dollar-1 : 1
Dollar-2 : 2
Dollar-3 : 3
Dollar-AT: 1 2 3 4

A Val 0: 1
A Val 1: 2
A Val 2: 3
A All Values: 1 2 3 4

Send multipart/form-data files with angular using $http

Here's an updated answer for Angular 4 & 5. TransformRequest and angular.identity were dropped. I've also included the ability to combine files with JSON data in one request.

Angular 5 Solution:

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

uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
  // Note that setting a content-type header
  // for mutlipart forms breaks some built in
  // request parsers like multer in express.
  const options = {} as any; // Set any options you like
  const formData = new FormData();

  // Append files to the virtual form.
  for (const file of files) {
    formData.append(file.name, file)
  }

  // Optional, append other kev:val rest data to the form.
  Object.keys(restObj).forEach(key => {
    formData.append(key, restObj[key]);
  });

  // Send it.
  return this.httpClient.post(uploadUrl, formData, options)
    .toPromise()
    .catch((e) => {
      // handle me
    });
}

Angular 4 Solution:

// Note that these imports below are deprecated in Angular 5
import {Http, RequestOptions} from '@angular/http';

uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
  // Note that setting a content-type header
  // for mutlipart forms breaks some built in
  // request parsers like multer in express.
  const options = new RequestOptions();
  const formData = new FormData();

  // Append files to the virtual form.
  for (const file of files) {
    formData.append(file.name, file)
  }

  // Optional, append other kev:val rest data to the form.
  Object.keys(restObj).forEach(key => {
    formData.append(key, restObj[key]);
  });

  // Send it.
  return this.http.post(uploadUrl, formData, options)
    .toPromise()
    .catch((e) => {
      // handle me
    });
}

How do I create delegates in Objective-C?

Disclaimer: this is the Swift version of how to create a delegate.

So, what are delegates? …in software development, there are general reusable solution architectures that help to solve commonly occurring problems within a given context, these “templates”, so to speak, are best known as design patterns. Delegates are a design pattern that allows one object to send messages to another object when a specific event happens. Imagine an object A calls an object B to perform an action. Once the action is complete, object A should know that B has completed the task and take necessary action, this can be achieved with the help of delegates!

For a better explanation, I am going to show you how to create a custom delegate that passes data between classes, with Swift in a simple application,start by downloading or cloning this starter project and run it!

You can see an app with two classes, ViewController A and ViewController B. B has two views that on tap changes the background color of the ViewController, nothing too complicated right? well now let’s think in an easy way to also change the background color of class A when the views on class B are tapped.

The problem is that this views are part of class B and have no idea about class A, so we need to find a way to communicate between this two classes, and that’s where delegation shines. I divided the implementation into 6 steps so you can use this as a cheat sheet when you need it.

step 1: Look for the pragma mark step 1 in ClassBVC file and add this

//MARK: step 1 Add Protocol here.
protocol ClassBVCDelegate: class {
func changeBackgroundColor(_ color: UIColor?)
}

The first step is to create a protocol, in this case, we will create the protocol in class B, inside the protocol you can create as many functions that you want based on the requirements of your implementation. In this case, we just have one simple function that accepts an optional UIColor as an argument. Is a good practice to name your protocols adding the word delegate at the end of the class name, in this case, ClassBVCDelegate.

step 2: Look for the pragma mark step 2 in ClassVBC and add this

//MARK: step 2 Create a delegate property here.
weak var delegate: ClassBVCDelegate?

Here we just create a delegate property for the class, this property must adopt the protocol type, and it should be optional. Also, you should add the weak keyword before the property to avoid retain cycles and potential memory leaks, if you don’t know what that means don’t worry for now, just remember to add this keyword.

step 3: Look for the pragma mark step 3 inside the handleTap method in ClassBVC and add this

//MARK: step 3 Add the delegate method call here.
delegate?.changeBackgroundColor(tapGesture.view?.backgroundColor)

One thing that you should know, run the app and tap on any view, you won’t see any new behavior and that’s correct but the thing that I want to point out is that the app it’s not crashing when the delegate is called, and it’s because we create it as an optional value and that’s why it won’t crash even the delegated doesn’t exist yet. Let’s now go to ClassAVC file and make it, the delegated.

step 4: Look for the pragma mark step 4 inside the handleTap method in ClassAVC and add this next to your class type like this.

//MARK: step 4 conform the protocol here.
class ClassAVC: UIViewController, ClassBVCDelegate {
}

Now ClassAVC adopted the ClassBVCDelegate protocol, you can see that your compiler is giving you an error that says “Type ‘ClassAVC does not conform to protocol ‘ClassBVCDelegate’ and this only means that you didn’t use the methods of the protocol yet, imagine that when class A adopts the protocol is like signing a contract with class B and this contract says “Any class adopting me MUST use my functions!”

Quick note: If you come from an Objective-C background you are probably thinking that you can also shut up that error making that method optional, but for my surprise, and probably yours, Swift language does not support optional protocols, if you want to do it you can create an extension for your protocol or use the @objc keyword in your protocol implementation.

Personally, If I have to create a protocol with different optional methods I would prefer to break it into different protocols, that way I will follow the concept of giving one single responsibility to my objects, but it can vary based on the specific implementation.

here is a good article about optional methods.

step 5: Look for the pragma mark step 5 inside the prepare for segue method and add this

//MARK: step 5 create a reference of Class B and bind them through the `prepareforsegue` method.
if let nav = segue.destination as? UINavigationController, let classBVC = nav.topViewController as? ClassBVC {
classBVC.delegate = self
}

Here we are just creating an instance of ClassBVC and assign its delegate to self, but what is self here? well, self is the ClassAVC which has been delegated!

step 6: Finally, look for the pragma step 6 in ClassAVC and let’s use the functions of the protocol, start typing func changeBackgroundColor and you will see that it’s auto-completing it for you. You can add any implementation inside it, in this example, we will just change the background color, add this.

//MARK: step 6 finally use the method of the contract
func changeBackgroundColor(_ color: UIColor?) {
view.backgroundColor = color
}

Now run the app!

Delegates are everywhere and you probably use them without even notice, if you create a tableview in the past you used delegation, many classes of UIKIT works around them and many other frameworks too, they solve these main problems.

  • Avoid tight coupling of objects.
  • Modify behavior and appearance without the need to subclass objects.
  • Allow tasks to be handled off to any arbitrary object.

Congratulations, you just implement a custom delegate, I know that you are probably thinking, so much trouble just for this? well, delegation is a very important design pattern to understand if you want to become an iOS developer, and always keep in mind that they have one to one relationship between objects.

You can see the original tutorial here

Access denied for user 'root'@'localhost' while attempting to grant privileges. How do I grant privileges?

One simple solution which always works for me when faced with mysql "access denied" errors: use sudo.

sudo mysql -u root

Then the necessary permissions exist for GRANT commands.

app.config for a class library

There is no automatic addition of app.config file when you add a class library project to your solution.

To my knowledge, there is no counter indication about doing so manualy. I think this is a common usage.

About log4Net config, you don't have to put the config into app.config, you can have a dedicated conf file in your project as well as an app.config file at the same time.

this link http://logging.apache.org/log4net/release/manual/configuration.html will give you examples about both ways (section in app.config and standalone log4net conf file)

Cross Domain Form POSTing

It is possible to build an arbitrary GET or POST request and send it to any server accessible to a victims browser. This includes devices on your local network, such as Printers and Routers.

There are many ways of building a CSRF exploit. A simple POST based CSRF attack can be sent using .submit() method. More complex attacks, such as cross-site file upload CSRF attacks will exploit CORS use of the xhr.withCredentals behavior.

CSRF does not violate the Same-Origin Policy For JavaScript because the SOP is concerned with JavaScript reading the server's response to a clients request. CSRF attacks don't care about the response, they care about a side-effect, or state change produced by the request, such as adding an administrative user or executing arbitrary code on the server.

Make sure your requests are protected using one of the methods described in the OWASP CSRF Prevention Cheat Sheet. For more information about CSRF consult the OWASP page on CSRF.

header('HTTP/1.0 404 Not Found'); not doing anything

No, it probably is actually working. It's just not readily visible. Instead of just using the header call, try doing that, then including 404.php, and then calling die.

You can test the fact that the HTTP/1.0 404 Not Found works by creating a PHP file named, say, test.php with this content:

<?php

header("HTTP/1.0 404 Not Found");
echo "PHP continues.\n";
die();
echo "Not after a die, however.\n";

Then viewing the result with curl -D /dev/stdout reveals:

HTTP/1.0 404 Not Found
Date: Mon, 04 Apr 2011 03:39:06 GMT
Server: Apache
X-Powered-By: PHP/5.3.2
Content-Length: 14
Connection: close
Content-Type: text/html

PHP continues.

Calling filter returns <filter object at ... >

It looks like you're using python 3.x. In python3, filter, map, zip, etc return an object which is iterable, but not a list. In other words,

filter(func,data) #python 2.x

is equivalent to:

list(filter(func,data)) #python 3.x

I think it was changed because you (often) want to do the filtering in a lazy sense -- You don't need to consume all of the memory to create a list up front, as long as the iterator returns the same thing a list would during iteration.

If you're familiar with list comprehensions and generator expressions, the above filter is now (almost) equivalent to the following in python3.x:

( x for x in data if func(x) ) 

As opposed to:

[ x for x in data if func(x) ]

in python 2.x

How to do SQL Like % in Linq?

I do always this:

from h in OH
where h.Hierarchy.Contains("/12/")
select h

I know I don't use the like statement but it's work fine in the background is this translated into a query with a like statement.

Preventing form resubmission

There are 2 approaches people used to take here:

Method 1: Use AJAX + Redirect

This way you post your form in the background using JQuery or something similar to Page2, while the user still sees page1 displayed. Upon successful posting, you redirect the browser to Page2.

Method 2: Post + Redirect to self

This is a common technique on forums. Form on Page1 posts the data to Page2, Page2 processes the data and does what needs to be done, and then it does a HTTP redirect on itself. This way the last "action" the browser remembers is a simple GET on page2, so the form is not being resubmitted upon F5.

How to bind 'touchstart' and 'click' events but not respond to both?

I had to do something similar. Here is a simplified version of what worked for me. If a touch event is detected, remove the click binding.

$thing.on('touchstart click', function(event){
  if (event.type == "touchstart")
    $(this).off('click');

  //your code here
});

In my case the click event was bound to an <a> element so I had to remove the click binding and rebind a click event which prevented the default action for the <a> element.

$thing.on('touchstart click', function(event){
  if (event.type == "touchstart")
    $(this).off('click').on('click', function(e){ e.preventDefault(); });

  //your code here
});

Does JavaScript pass by reference?

Function arguments are passed either by-value or by-sharing, but never ever by reference in JavaScript!

Call-by-Value

Primitive types are passed by-value:

_x000D_
_x000D_
var num = 123, str = "foo";

function f(num, str) {
  num += 1;
  str += "bar";
  console.log("inside of f:", num, str);
}

f(num, str);
console.log("outside of f:", num, str);
_x000D_
_x000D_
_x000D_

Reassignments inside a function scope are not visible in the surrounding scope.

This also applies to Strings, which are a composite data type and yet immutable:

_x000D_
_x000D_
var str = "foo";

function f(str) {
  str[0] = "b"; // doesn't work, because strings are immutable
  console.log("inside of f:", str);
}

f(str);
console.log("outside of f:", str);
_x000D_
_x000D_
_x000D_

Call-by-Sharing

Objects, that is to say all types that are not primitives, are passed by-sharing. A variable that holds a reference to an object actually holds merely a copy of this reference. If JavaScript would pursue a call-by-reference evaluation strategy, the variable would hold the original reference. This is the crucial difference between by-sharing and by-reference.

What are the practical consequences of this distinction?

_x000D_
_x000D_
var o = {x: "foo"}, p = {y: 123};

function f(o, p) {
  o.x = "bar"; // Mutation
  p = {x: 456}; // Reassignment
  console.log("o inside of f:", o);
  console.log("p inside of f:", p);
}

f(o, p);

console.log("o outside of f:", o);
console.log("p outside of f:", p);
_x000D_
_x000D_
_x000D_

Mutating means to modify certain properties of an existing Object. The reference copy that a variable is bound to and that refers to this object remains the same. Mutations are thus visible in the caller's scope.

Reassigning means to replace the reference copy bound to a variable. Since it is only a copy, other variables holding a copy of the same reference remain unaffected. Reassignments are thus not visible in the caller's scope like they would be with a call-by-reference evaluation strategy.

Further information on evaluation strategies in ECMAScript.

400 BAD request HTTP error code meaning?

A 400 means that the request was malformed. In other words, the data stream sent by the client to the server didn't follow the rules.

In the case of a REST API with a JSON payload, 400's are typically, and correctly I would say, used to indicate that the JSON is invalid in some way according to the API specification for the service.

By that logic, both the scenarios you provided should be 400s.

Imagine instead this were XML rather than JSON. In both cases, the XML would never pass schema validation--either because of an undefined element or an improper element value. That would be a bad request. Same deal here.

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0

Try this one

cd android && ./gradlew clean && ./gradlew :app:bundleRelease

What causes this error? "Runtime error 380: Invalid property value"

Just to throw my two cents in: another common cause of this error in my experience is code in the Form_Resize event that uses math to resize controls on a form. Control dimensions (Height and Width) can't be set to negative values, so code like the following in your Form_Resize event can cause this error:

Private Sub Form_Resize()
    'Resize text box to fit the form, with a margin of 1000 twips on the right.'
    'This will error out if the width of the Form drops below 1000 twips.'
    txtFirstName.Width = Me.Width - 1000
End Sub

The above code will raise an an "Invalid property value" error if the form is resized to less than 1000 twips wide. If this is the problem, the easiest solution is to add On Error Resume Next as the first line, so that these kinds of errors are ignored. This is one of those rare situations in VB6 where On Error Resume Next is your friend.

R Not in subset

The expression df1$id %in% idNums1 produces a logical vector. To negate it, you need to negate the whole vector:

!(df1$id %in% idNums1)

"Application tried to present modally an active controller"?

Instead of using:

self.present(viewControllerToPresent: UIViewController, animated: Bool, completion: (() -> Void)?)

you can use:

self.navigationController?.pushViewController(viewController: UIViewController, animated: Bool)

SQL ORDER BY date problem

this should work for your date format

order by convert(date, your_column, 104) desc

Change marker size in Google maps V3

This answer expounds on John Black's helpful answer, so I will repeat some of his answer content in my answer.

The easiest way to resize a marker seems to be leaving argument 2, 3, and 4 null and scaling the size in argument 5.

var pinIcon = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FFFF00",
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(42, 68)
);  

As an aside, this answer to a similar question asserts that defining marker size in the 2nd argument is better than scaling in the 5th argument. I don't know if this is true.

Leaving arguments 2-4 null works great for the default google pin image, but you must set an anchor explicitly for the default google pin shadow image, or it will look like this:

what happens when you leave anchor null on an enlarged shadow

The bottom center of the pin image happens to be collocated with the tip of the pin when you view the graphic on the map. This is important, because the marker's position property (marker's LatLng position on the map) will automatically be collocated with the visual tip of the pin when you leave the anchor (4th argument) null. In other words, leaving the anchor null ensures the tip points where it is supposed to point.

However, the tip of the shadow is not located at the bottom center. So you need to set the 4th argument explicitly to offset the tip of the pin shadow so the shadow's tip will be colocated with the pin image's tip.

By experimenting I found the tip of the shadow should be set like this: x is 1/3 of size and y is 100% of size.

var pinShadow = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
    null,
    null,
    /* Offset x axis 33% of overall size, Offset y axis 100% of overall size */
    new google.maps.Point(40, 110), 
    new google.maps.Size(120, 110)); 

to give this:

offset the enlarged shadow anchor explicitly

jQuery, get ID of each element in a class using .each?

Try this, replacing .myClassName with the actual name of the class (but keep the period at the beginning).

$('.myClassName').each(function() {
    alert( this.id );
});

So if the class is "test", you'd do $('.test').each(func....

This is the specific form of .each() that iterates over a jQuery object.

The form you were using iterates over any type of collection. So you were essentially iterating over an array of characters t,e,s,t.

Using that form of $.each(), you would need to do it like this:

$.each($('.myClassName'), function() {
    alert( this.id );
});

...which will have the same result as the example above.

Insert new column into table in sqlite?

ALTER TABLE {tableName} ADD COLUMN COLNew {type};
UPDATE {tableName} SET COLNew = {base on {type} pass value here};

This update is required to handle the null value, inputting a default value as you require. As in your case, you need to call the SELECT query and you will get the order of columns, as paxdiablo already said:

SELECT name, colnew, qty, rate FROM{tablename}

and in my opinion, your column name to get the value from the cursor:

private static final String ColNew="ColNew";
String val=cursor.getString(cursor.getColumnIndex(ColNew));

so if the index changes your application will not face any problems.

This is the safe way in the sense that otherwise, if you are using CREATE temptable or RENAME table or CREATE, there would be a high chance of data loss if not handled carefully, for example in the case where your transactions occur while the battery is running out.

How to activate "Share" button in android app?

Create a button with an id share and add the following code snippet.

share.setOnClickListener(new View.OnClickListener() {             
    @Override
    public void onClick(View v) {

        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        String shareBody = "Your body here";
        String shareSub = "Your subject here";
        sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, shareSub);
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
        startActivity(Intent.createChooser(sharingIntent, "Share using"));
    }
});

The above code snippet will open the share chooser on share button click action. However, note...The share code snippet might not output very good results using emulator. For actual results, run the code snippet on android device to get the real results.

How to add a ListView to a Column in Flutter?

Actually, when you read docs the ListView should be inside Expanded Widget so it can work.

  Widget build(BuildContext context) {
return Scaffold(
    body: Column(
  children: <Widget>[
    Align(
      child: PayableWidget(),
    ),
    Expanded(
      child: _myListView(context),
    )
  ],
));

}

How to convert a Django QuerySet to a list

Why not just call list() on the Queryset?

answers_list = list(answers)

This will also evaluate the QuerySet/run the query. You can then remove/add from that list.

Is there a command line command for verifying what version of .NET is installed

you can check installed c# compilers and the printed version of the .net:

@echo off

for /r "%SystemRoot%\Microsoft.NET\Framework\" %%# in ("*csc.exe") do (
    set "l="
    for /f "skip=1 tokens=2 delims=k" %%$ in ('"%%# #"') do (
        if not defined l (
            echo Installed: %%$
            set l=%%$
        )
    )
)

echo latest installed .NET %l%

the csc.exe does not have a -version switch but it prints the .net version in its logo. You can also try with msbuild.exe but .net framework 1.* does not have msbuild.

Given a URL to a text file, what is the simplest way to read the contents of the text file?

The requests library has a simpler interface and works with both Python 2 and 3.

import requests

response = requests.get(target_url)
data = response.text

How can I restart a Java application?

Of course it is possible to restart a Java application.

The following method shows a way to restart a Java application:

public void restartApplication()
{
  final String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
  final File currentJar = new File(MyClassInTheJar.class.getProtectionDomain().getCodeSource().getLocation().toURI());

  /* is it a jar file? */
  if(!currentJar.getName().endsWith(".jar"))
    return;

  /* Build command: java -jar application.jar */
  final ArrayList<String> command = new ArrayList<String>();
  command.add(javaBin);
  command.add("-jar");
  command.add(currentJar.getPath());

  final ProcessBuilder builder = new ProcessBuilder(command);
  builder.start();
  System.exit(0);
}

Basically it does the following:

  1. Find the java executable (I used the java binary here, but that depends on your requirements)
  2. Find the application (a jar in my case, using the MyClassInTheJar class to find the jar location itself)
  3. Build a command to restart the jar (using the java binary in this case)
  4. Execute it! (and thus terminating the current application and starting it again)

Chrome Uncaught Syntax Error: Unexpected Token ILLEGAL

I get the same error in Chrome after pasting code copied from jsfiddle.

If you select all the code from a panel in jsfiddle and paste it into the free text editor Notepad++, you should be able to see the problem character as a question mark "?" at the very end of your code. Delete this question mark, then copy and paste the code from Notepad++ and the problem will be gone.

How to get memory available or used in C#

You might want to check the GC.GetTotalMemory method.

It retrieves the number of bytes currently thought to be allocated by the garbage collector.

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

C++03 3.10/1 says: "Every expression is either an lvalue or an rvalue." It's important to remember that lvalueness versus rvalueness is a property of expressions, not of objects.

Lvalues name objects that persist beyond a single expression. For example, obj , *ptr , ptr[index] , and ++x are all lvalues.

Rvalues are temporaries that evaporate at the end of the full-expression in which they live ("at the semicolon"). For example, 1729 , x + y , std::string("meow") , and x++ are all rvalues.

The address-of operator requires that its "operand shall be an lvalue". if we could take the address of one expression, the expression is an lvalue, otherwise it's an rvalue.

 &obj; //  valid
 &12;  //invalid

Should C# or C++ be chosen for learning Games Programming (consoles)?

Ok here is my two cents.

If you are planning to seriously get into the game industry I recommend you learn both languages. Starting off with C++ then moving into a managed language like C#. C++ has it's advantages over C#, but C# also has advantages over C++.

Personally I prefer C# over C++ any day. This is because many reasons:, just a few:

  1. C# makes programming fun again ;).
  2. It's managed code helps me complete complex tasks easily and not forget safety.
  3. C#s' is pure OOP, forcing rules in your code that helps keep your code more readable, 'maintainable' and execution is more stable. Productivity rate surpasses C++ by at least 10%, the best C++ programmer could be an even better C# programmer.
  4. This isn't really a reason, more like something 'I' like about C#: LINQ.

Now...there are many things that I miss about C++. I miss being able to (completely) manage my own memory. I can't tell you how many times I caught myself trying to 'delete' an instance/reference. Another thing I dislike about C# is the inability to use multiple-inheritance, but then again it has forced me to think more about how to structure my code.

There has been more discussions on this topic than there are stars in the known universe and they all close at a dead end. Neither language is better than the other and refusing either one for the other will just hurt you in the long run. Times change and so do the standards for computer programming.

Whatever language you choose to keep at the top of your list, always keep your options open and don't set your mind to any one single language. You say you already know C++, why not learn C#, it can't hurt and I 'promise' you, it will make you a better C++ programmer.

LINQ Join with Multiple Conditions in On Clause

This works fine for 2 tables. I have 3 tables and on clause has to link 2 conditions from 3 tables. My code:

from p in _dbContext.Products join pv in _dbContext.ProductVariants on p.ProduktId equals pv.ProduktId join jpr in leftJoinQuery on new { VariantId = pv.Vid, ProductId = p.ProduktId } equals new { VariantId = jpr.Prices.VariantID, ProductId = jpr.Prices.ProduktID } into lj

But its showing error at this point: join pv in _dbContext.ProductVariants on p.ProduktId equals pv.ProduktId

Error: The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'GroupJoin'.

How can I make a menubar fixed on the top while scrolling

The postition:absolute; tag positions the element relative to it's immediate parent. I noticed that even in the examples, there isn't room for scrolling, and when i tried it out, it didn't work. Therefore, to pull off the facebook floating menu, the position:fixed; tag should be used instead. It displaces/keeps the element at the given/specified location, and the rest of the page can scroll smoothly - even with the responsive ones.

Please see CSS postion attribute documentation when you can :)

Programmatically change input type of the EditText from PASSWORD to NORMAL & vice versa

This is the full onClick handler for the Image/Button to show/hide the password.

    new OnClickListener() {
        @Override
        public void onClick(View v) {
            // current ursor position
            int cursorPosition = edtPassword.getSelectionStart();

            // toggles the control variable
            isPassworsVisible = !isPassworsVisible;

            // sets the image toggler inside edit text
            passwordVisible.setImageDrawable(getResources().getDrawable(isPassworsVisible ? R.drawable.ic_eye_checked : R.drawable.ic_eye_unchecked));

            // apply input type
            edtPassword.setInputType(isPassworsVisible ? InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD : InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);

            // returns cursor to position
            edtPassword.setSelection(cursorPosition);
        }
    };

Move column by name to front of table in pandas

Maybe I'm missing something, but a lot of these answers seem overly complicated. You should be able to just set the columns within a single list:

Column to the front:

df = df[ ['Mid'] + [ col for col in df.columns if col != 'Mid' ] ]

Or if instead, you want to move it to the back:

df = df[ [ col for col in df.columns if col != 'Mid' ] + ['Mid'] ]

Or if you wanted to move more than one column:

cols_to_move = ['Mid', 'Zsore']
df           = df[ cols_to_move + [ col for col in df.columns if col not in cols_to_move ] ]

How to change href attribute using JavaScript after opening the link in a new window?

Is there any downside of leveraging mousedown listener to modify the href attribute with a new URL location and then let the browser figures out where it should redirect to?

It's working fine so far for me. Would like to know what the limitations are with this approach?

// Simple code snippet to demonstrate the said approach
const a = document.createElement('a');
a.textContent = 'test link';
a.href = '/haha';
a.target = '_blank';
a.rel = 'noopener';

a.onmousedown = () => {
  a.href = '/lol';
};

document.body.appendChild(a);
}

How do I concatenate a boolean to a string in Python?

answer = “True”

myvars = “the answer is” + answer

print(myvars)

That should give you the answer is True easily as you have stored answer as a string by using the quotation marks

Connection refused to MongoDB errno 111

Thanks for the help everyone!

Turns out that it was an iptable conflict. Two rules listing the port open (which resulted in a closed port).

However, one of the comments by aka and another by manu2013 were problems that I would have run into, if not for the conflict.

So! Always remember to edit the /etc/mongod.conf file and set your bind_ip = 0.0.0.0 in order to make connections externally.

Also, make sure that you don't have conflicting rules in your iptable for the port mongo wants (see link on mongodb's site to set up your iptables properly).

How to split a single column values to multiple column values?

SELECT
   SUBSTRING_INDEX(SUBSTRING_INDEX(rent, ' ', 1), ' ', -1) AS currency,
   SUBSTRING_INDEX(SUBSTRING_INDEX(rent, ' ', 3), ' ', -1) AS rent
FROM tolets

How to install maven on redhat linux

Installing maven in Amazon Linux / redhat

--> sudo wget http://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo

--> sudo sed -i s/\$releasever/6/g /etc/yum.repos.d/epel-apache-maven.repo

-->sudo yum install -y apache-maven

--> mvn --version

Output looks like


Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T07:58:13Z) Maven home: /usr/share/apache-maven Java version: 1.8.0_171, vendor: Oracle Corporation Java home: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.171-8.b10.amzn2.x86_64/jre Default locale: en_US, platform encoding: UTF-8 OS name: "linux", version: "4.14.47-64.38.amzn2.x86_64", arch: "amd64", family: "unix"

*If its thrown error related to java please follow the below step to update java 8 *

Installing java 8 in amazon linux/redhat

--> yum search java | grep openjdk

--> yum install java-1.8.0-openjdk-headless.x86_64

--> yum install java-1.8.0-openjdk-devel.x86_64

--> update-alternatives --config java #pick java 1.8 and press 1

--> update-alternatives --config javac #pick java 1.8 and press 2

Thank You

What are these ^M's that keep showing up in my files in emacs?

They have to do with the difference between DOS style line endings and Unix style. Check out the Wikipedia article. You may be able to find a dos2unix tool to help, or simply write a small script to fix them yourself.

Edit: I found the following Python sample code here:

string.replace( str, '\r', '' )

C++ code file extension? .cc vs .cpp

The other option is .cxx where the x is supposed to be a plus rotated 45°.

Windows, Mac and Linux all support .c++ so we should just use that.

How to compare two List<String> to each other?

    private static bool CompareDictionaries(IDictionary<string, IEnumerable<string>> dict1, IDictionary<string, IEnumerable<string>> dict2)
    {
        if (dict1.Count != dict2.Count)
        {
            return false;
        }

        var keyDiff = dict1.Keys.Except(dict2.Keys);
        if (keyDiff.Any())
        {
            return false;
        }

        return (from key in dict1.Keys 
                let value1 = dict1[key] 
                let value2 = dict2[key] 
                select value1.Except(value2)).All(diffInValues => !diffInValues.Any());
    }

How do I use the nohup command without getting nohup.out?

The nohup command only writes to nohup.out if the output would otherwise go to the terminal. If you have redirected the output of the command somewhere else - including /dev/null - that's where it goes instead.

 nohup command >/dev/null 2>&1   # doesn't create nohup.out

If you're using nohup, that probably means you want to run the command in the background by putting another & on the end of the whole thing:

 nohup command >/dev/null 2>&1 & # runs in background, still doesn't create nohup.out

On Linux, running a job with nohup automatically closes its input as well. On other systems, notably BSD and macOS, that is not the case, so when running in the background, you might want to close input manually. While closing input has no effect on the creation or not of nohup.out, it avoids another problem: if a background process tries to read anything from standard input, it will pause, waiting for you to bring it back to the foreground and type something. So the extra-safe version looks like this:

nohup command </dev/null >/dev/null 2>&1 & # completely detached from terminal 

Note, however, that this does not prevent the command from accessing the terminal directly, nor does it remove it from your shell's process group. If you want to do the latter, and you are running bash, ksh, or zsh, you can do so by running disown with no argument as the next command. That will mean the background process is no longer associated with a shell "job" and will not have any signals forwarded to it from the shell. (Note the distinction: a disowned process gets no signals forwarded to it automatically by its parent shell - but without nohup, it will still receive a HUP signal sent via other means, such as a manual kill command. A nohup'ed process ignores any and all HUP signals, no matter how they are sent.)

Explanation:

In Unixy systems, every source of input or target of output has a number associated with it called a "file descriptor", or "fd" for short. Every running program ("process") has its own set of these, and when a new process starts up it has three of them already open: "standard input", which is fd 0, is open for the process to read from, while "standard output" (fd 1) and "standard error" (fd 2) are open for it to write to. If you just run a command in a terminal window, then by default, anything you type goes to its standard input, while both its standard output and standard error get sent to that window.

But you can ask the shell to change where any or all of those file descriptors point before launching the command; that's what the redirection (<, <<, >, >>) and pipe (|) operators do.

The pipe is the simplest of these... command1 | command2 arranges for the standard output of command1 to feed directly into the standard input of command2. This is a very handy arrangement that has led to a particular design pattern in UNIX tools (and explains the existence of standard error, which allows a program to send messages to the user even though its output is going into the next program in the pipeline). But you can only pipe standard output to standard input; you can't send any other file descriptors to a pipe without some juggling.

The redirection operators are friendlier in that they let you specify which file descriptor to redirect. So 0<infile reads standard input from the file named infile, while 2>>logfile appends standard error to the end of the file named logfile. If you don't specify a number, then input redirection defaults to fd 0 (< is the same as 0<), while output redirection defaults to fd 1 (> is the same as 1>).

Also, you can combine file descriptors together: 2>&1 means "send standard error wherever standard output is going". That means that you get a single stream of output that includes both standard out and standard error intermixed with no way to separate them anymore, but it also means that you can include standard error in a pipe.

So the sequence >/dev/null 2>&1 means "send standard output to /dev/null" (which is a special device that just throws away whatever you write to it) "and then send standard error to wherever standard output is going" (which we just made sure was /dev/null). Basically, "throw away whatever this command writes to either file descriptor".

When nohup detects that neither its standard error nor output is attached to a terminal, it doesn't bother to create nohup.out, but assumes that the output is already redirected where the user wants it to go.

The /dev/null device works for input, too; if you run a command with </dev/null, then any attempt by that command to read from standard input will instantly encounter end-of-file. Note that the merge syntax won't have the same effect here; it only works to point a file descriptor to another one that's open in the same direction (input or output). The shell will let you do >/dev/null <&1, but that winds up creating a process with an input file descriptor open on an output stream, so instead of just hitting end-of-file, any read attempt will trigger a fatal "invalid file descriptor" error.

How to use Macro argument as string literal?

Use the preprocessor # operator:

#define CALL_DO_SOMETHING(VAR) do_something(#VAR, VAR);

JUnit 4 compare Sets

If you want to check whether a List or Set contains a set of specific values (instead of comparing it with an already existing collection), often the toString method of collections is handy:

String[] actualResult = calltestedmethod();
assertEquals("[foo, bar]", Arrays.asList(actualResult).toString());

List otherResult = callothertestedmethod();
assertEquals("[42, mice]", otherResult.toString());

This is a bit shorter than first constructing the expected collection and comparing it with the actual collection, and easier to write and correct.

(Admittedly, this is not a particularily clean method, and can't distinguish an element "foo, bar" from two elements "foo" and "bar". But in practice I think it's most important that it's easy and fast to write tests, otherwise many developers just won't without being pressed.)

How to get a substring of text?

If you have your text in your_text variable, you can use:

your_text[0..29]

Git Push Error: insufficient permission for adding an object to repository database

I'll add my two cents just as a way to discover files with a specific ownership inside a directory.

The issue was caused by running some git command as root. The received message was:

$ git commit -a -m "fix xxx"
error: insufficient permission for adding an object to repository database .git/objects
error: setup.sh: failed to insert into database

I first looked at git config -l, then I resolved with:

find .git/ -exec stat --format="%G %n" {} + |grep root

chown -R $(id -un):$(id -gn) .git/objects/

git commit -a -m "fixed git objects ownership"

Is it possible to use Visual Studio on macOS?

Yes, you can! There's a Visual Studio for macs and there's Visual Studio Code if you only need a text editor like Sublime Text.

.attr("disabled", "disabled") issue

To add disabled attribute

$('#id').attr("disabled", "true");

To remove Disabled Attribute

$('#id').removeAttr('disabled');

StringUtils.isBlank() vs String.isEmpty()

The bottom line is :

isEmpty take " " as a character but isBlank not. Rest both are same.

How can I set the focus (and display the keyboard) on my EditText programmatically

I tried a lot ways and it's not working tho, not sure is it because i'm using shared transition from fragment to activity containing the edit text.

Btw my edittext is also wrapped in LinearLayout.

I added a slight delay to request focus and below code worked for me: (Kotlin)

 et_search.postDelayed({
     editText.requestFocus()

     showKeyboard()
 },400) //only 400 is working fine, even 300 / 350, the cursor is not showing

showKeyboard()

 val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
 imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)

What is the effect of encoding an image in base64?

Encoding an image to base64 will make it about 30% bigger.

See the details in the wikipedia article about the Data URI scheme, where it states:

Base64-encoded data URIs are 1/3 larger in size than their binary equivalent. (However, this overhead is reduced to 2-3% if the HTTP server compresses the response using gzip)

Is there a way to "limit" the result with ELOQUENT ORM of Laravel?

We can use LIMIT like bellow:

Model::take(20)->get();

What is a monad?

Explaining monads seems to be like explaining control-flow statements. Imagine that a non-programmer asks you to explain them?

You can give them an explanation involving the theory - Boolean Logic, register values, pointers, stacks, and frames. But that would be crazy.

You could explain them in terms of the syntax. Basically all control-flow statements in C have curly brackets, and you can distinguish the condition and the conditional code by where they are relative to the brackets. That may be even crazier.

Or you could also explain loops, if statements, routines, subroutines, and possibly co-routines.

Monads can replace a fairly large number of programming techniques. There's a specific syntax in languages that support them, and some theories about them.

They are also a way for functional programmers to use imperative code without actually admitting it, but that's not their only use.

Call japplet from jframe

First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.

Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.

Instead, I would move all of the "application" content to a separate component, like a JPanel for example and simply move this between the applet or frame as required...

ps- You can use f.setLocationRelativeTo(null) to center the window on the screen ;)

Updated

You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...

Within the constructor of GalzyTable2 you are doing...

JApplet app = new JApplet(); add(app); app.init(); app.start(); 

...Why are you adding another applet to an applet??

Case in point...

Within the main method, you are trying to add the instance of JFrame to itself...

f.getContentPane().add(f, button2); 

Instead, create yourself a class that extends from something like JPanel, add your UI logical to this, using compound components if required.

Then, add this panel to whatever top level container you need.

Take the time to read through Creating a GUI with Swing

Updated with example

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException;  public class GalaxyTable2 extends JPanel {      private static final int PREF_W = 700;     private static final int PREF_H = 600;      String[] columnNames                     = {"Phone Name", "Brief Description", "Picture", "price",                         "Buy"};  // Create image icons     ImageIcon Image1 = new ImageIcon(                     getClass().getResource("s1.png"));     ImageIcon Image2 = new ImageIcon(                     getClass().getResource("s2.png"));     ImageIcon Image3 = new ImageIcon(                     getClass().getResource("s3.png"));     ImageIcon Image4 = new ImageIcon(                     getClass().getResource("s4.png"));     ImageIcon Image5 = new ImageIcon(                     getClass().getResource("note.png"));     ImageIcon Image6 = new ImageIcon(                     getClass().getResource("note2.png"));     ImageIcon Image7 = new ImageIcon(                     getClass().getResource("note3.png"));      Object[][] rowData = {         {"Galaxy S", "3G Support,CPU 1GHz",             Image1, 120, false},         {"Galaxy S II", "3G Support,CPU 1.2GHz",             Image2, 170, false},         {"Galaxy S III", "3G Support,CPU 1.4GHz",             Image3, 205, false},         {"Galaxy S4", "4G Support,CPU 1.6GHz",             Image4, 230, false},         {"Galaxy Note", "4G Support,CPU 1.4GHz",             Image5, 190, false},         {"Galaxy Note2 II", "4G Support,CPU 1.6GHz",             Image6, 190, false},         {"Galaxy Note 3", "4G Support,CPU 2.3GHz",             Image7, 260, false},};      MyTable ss = new MyTable(                     rowData, columnNames);      // Create a table     JTable jTable1 = new JTable(ss);      public GalaxyTable2() {         jTable1.setRowHeight(70);          add(new JScrollPane(jTable1),                         BorderLayout.CENTER);          JPanel buttons = new JPanel();          JButton button = new JButton("Home");         buttons.add(button);         JButton button2 = new JButton("Confirm");         buttons.add(button2);          add(buttons, BorderLayout.SOUTH);     }      @Override      public Dimension getPreferredSize() {         return new Dimension(PREF_W, PREF_H);     }      public void actionPerformed(ActionEvent e) {         new AMainFrame7().setVisible(true);     }      public static void main(String[] args) {          EventQueue.invokeLater(new Runnable() {             @Override             public void run() {                 try {                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());                 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {                     ex.printStackTrace();                 }                  JFrame frame = new JFrame("Testing");                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                 frame.add(new GalaxyTable2());                 frame.pack();                 frame.setLocationRelativeTo(null);                 frame.setVisible(true);             }         });     } } 

You also seem to have a lack of understanding about how to use layout managers.

Take the time to read through Creating a GUI with Swing and Laying components out in a container

How to remove \xa0 from string in Python?

Python recognize it like a space character, so you can split it without args and join by a normal whitespace:

line = ' '.join(line.split())

Resolve Git merge conflicts in favor of their changes during a pull

If you're already in conflicted state, and you want to just accept all of theirs:

git checkout --theirs .
git add .

If you want to do the opposite:

git checkout --ours .
git add .

This is pretty drastic, so make sure you really want to wipe everything out like this before doing it.

How to declare global variables in Android?

On activity result is called before on resume. So move you login check to on resume and your second login can be blocked once the secomd activity has returned a positive result. On resume is called every time so there is not worries of it not being called the first time.

Angular get object from array by Id

// Used In TypeScript For Angular 4+        
const viewArray = [
          {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
          {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
          {id: 3, question: "Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
          {id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
          {id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
          {id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
          {id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
          {id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
          {id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
          {id: 10, question: "Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
          {id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
          {id: 12, question: "Do you feel a sense of peace and contentment  in your home? ", category: "Home Environment", subs: []},
          {id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
          {id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
          {id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
    ];

         const arrayObj = any;
         const objectData = any;

          for (let index = 0; index < this.viewArray.length; index++) {
              this.arrayObj = this.viewArray[index];
              this.arrayObj.filter((x) => {
                if (x.id === id) {
                  this.objectData = x;
                }
              });
              console.log('Json Object Data by ID ==> ', this.objectData);
            }
          };

Parsing a JSON string in Ruby

This looks like JavaScript Object Notation (JSON). You can parse JSON that resides in some variable, e.g. json_string, like so:

require 'json'
JSON.parse(json_string)

If you’re using an older Ruby, you may need to install the json gem.


There are also other implementations of JSON for Ruby that may fit some use-cases better:

Rails Object to hash

Old question, but heavily referenced ... I think most people use other methods, but there is infact a to_hash method, it has to be setup right. Generally, pluck is a better answer after rails 4 ... answering this mainly because I had to search a bunch to find this thread or anything useful & assuming others are hitting the same problem...

Note: not recommending this for everyone, but edge cases!


From the ruby on rails api ... http://api.rubyonrails.org/classes/ActiveRecord/Result.html ...

This class encapsulates a result returned from calling #exec_query on any database connection adapter. For example:

result = ActiveRecord::Base.connection.exec_query('SELECT id, title, body FROM posts')
result # => #<ActiveRecord::Result:0xdeadbeef>

...

# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
      {"id" => 2, "title" => "title_2", "body" => "body_2"},
      ...
     ] ...

addEventListener not working in IE8

IE doesn't support addEventListener until version 9, so you have to use attachEvent, here's an example:

if (!someElement.addEventListener) {
    _checkbox.attachEvent("onclick", setCheckedValues);
}
else {
    _checkbox.addEventListener("click", setCheckedValues, false);
}

How to read HDF5 files in Python

Reading the file

import h5py

f = h5py.File(file_name, mode)

Studying the structure of the file by printing what HDF5 groups are present

for key in f.keys():
    print(key) #Names of the groups in HDF5 file.

Extracting the data

#Get the HDF5 group
group = f[key]

#Checkout what keys are inside that group.
for key in group.keys():
    print(key)

data = group[some_key_inside_the_group].value
#Do whatever you want with data

#After you are done
f.close()

How to pass a datetime parameter?

I feel your pain ... yet another date time format... just what you needed!

Using Web Api 2 you can use route attributes to specify parameters.

so with attributes on your class and your method you can code up a REST URL using this utc format you are having trouble with (apparently its ISO8601, presumably arrived at using startDate.toISOString())

[Route(@"daterange/{startDate:regex(^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$)}/{endDate:regex(^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$)}")]
    [HttpGet]
    public IEnumerable<MyRecordType> GetByDateRange(DateTime startDate, DateTime endDate)

.... BUT, although this works with one date (startDate), for some reason it doesnt work when the endDate is in this format ... debugged for hours, only clue is exception says it doesnt like colon ":" (even though web.config is set with :

<system.web>
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" requestPathInvalidCharacters="" />
</system.web>

So, lets make another date format (taken from the polyfill for the ISO date format) and add it to the Javascript date (for brevity, only convert up to minutes):

if (!Date.prototype.toUTCDateTimeDigits) {
    (function () {

        function pad(number) {
            if (number < 10) {
                return '0' + number;
            }
            return number;
        }

        Date.prototype.toUTCDateTimeDigits = function () {
            return this.getUTCFullYear() +
              pad(this.getUTCMonth() + 1) +
              pad(this.getUTCDate()) +
              'T' +
              pad(this.getUTCHours()) +
              pad(this.getUTCMinutes()) +
              'Z';
        };

    }());
}

Then when you send the dates to the Web API 2 method, you can convert them from string to date:

[RoutePrefix("api/myrecordtype")]
public class MyRecordTypeController : ApiController
{


    [Route(@"daterange/{startDateString}/{endDateString}")]
    [HttpGet]
    public IEnumerable<MyRecordType> GetByDateRange([FromUri]string startDateString, [FromUri]string endDateString)
    {
        var startDate = BuildDateTimeFromYAFormat(startDateString);
        var endDate = BuildDateTimeFromYAFormat(endDateString);
    ...
    }

    /// <summary>
    /// Convert a UTC Date String of format yyyyMMddThhmmZ into a Local Date
    /// </summary>
    /// <param name="dateString"></param>
    /// <returns></returns>
    private DateTime BuildDateTimeFromYAFormat(string dateString)
    {
        Regex r = new Regex(@"^\d{4}\d{2}\d{2}T\d{2}\d{2}Z$");
        if (!r.IsMatch(dateString))
        {
            throw new FormatException(
                string.Format("{0} is not the correct format. Should be yyyyMMddThhmmZ", dateString)); 
        }

        DateTime dt = DateTime.ParseExact(dateString, "yyyyMMddThhmmZ", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);

        return dt;
    }

so the url would be

http://domain/api/myrecordtype/daterange/20140302T0003Z/20140302T1603Z

Hanselman gives some related info here:

http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx

Why an interface can not implement another interface?

Hope this will help you a little what I have learned in oops (core java) during my college.

Implements denotes defining an implementation for the methods of an interface. However interfaces have no implementation so that's not possible. An interface can however extend another interface, which means it can add more methods and inherit its type.

Here is an example below, this is my understanding and what I have learnt in oops.

interface ParentInterface{  
        void myMethod();  
}  

interface SubInterface extends ParentInterface{  
        void anotherMethod();  
}  

and keep one thing in a mind one interface can only extend another interface and if you want to define it's function on some class then only a interface in implemented eg below

public interface Dog
{
    public boolean Barks();

    public boolean isGoldenRetriever();
}

Now, if a class were to implement this interface, this is what it would look like:

public class SomeClass implements Dog
{
    public boolean Barks{
    // method definition here

    }

    public boolean isGoldenRetriever{
    // method definition here
    }
}

and if a abstract class has some abstract function define and declare and you want to define those function or you can say implement those function then you suppose to extends that class because abstract class can only be extended. here is example below.

public abstract class MyAbstractClass {

    public abstract void abstractMethod();
}

Here is an example subclass of MyAbstractClass:

public class MySubClass extends MyAbstractClass {

    public void abstractMethod() {
        System.out.println("My method implementation");
    }
}

Looping Over Result Sets in MySQL

Something like this should do the trick (However, read after the snippet for more info)

CREATE PROCEDURE GetFilteredData()
BEGIN
  DECLARE bDone INT;

  DECLARE var1 CHAR(16);    -- or approriate type
  DECLARE Var2 INT;
  DECLARE Var3 VARCHAR(50);

  DECLARE curs CURSOR FOR  SELECT something FROM somewhere WHERE some stuff;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;

  DROP TEMPORARY TABLE IF EXISTS tblResults;
  CREATE TEMPORARY TABLE IF NOT EXISTS tblResults  (
    --Fld1 type,
    --Fld2 type,
    --...
  );

  OPEN curs;

  SET bDone = 0;
  REPEAT
    FETCH curs INTO var1,, b;

    IF whatever_filtering_desired
       -- here for whatever_transformation_may_be_desired
       INSERT INTO tblResults VALUES (var1, var2, var3 ...);
    END IF;
  UNTIL bDone END REPEAT;

  CLOSE curs;
  SELECT * FROM tblResults;
END

A few things to consider...

Concerning the snippet above:

  • may want to pass part of the query to the Stored Procedure, maybe particularly the search criteria, to make it more generic.
  • If this method is to be called by multiple sessions etc. may want to pass a Session ID of sort to create a unique temporary table name (actually unnecessary concern since different sessions do not share the same temporary file namespace; see comment by Gruber, below)
  • A few parts such as the variable declarations, the SELECT query etc. need to be properly specified

More generally: trying to avoid needing a cursor.

I purposely named the cursor variable curs[e], because cursors are a mixed blessing. They can help us implement complicated business rules that may be difficult to express in the declarative form of SQL, but it then brings us to use the procedural (imperative) form of SQL, which is a general feature of SQL which is neither very friendly/expressive, programming-wise, and often less efficient performance-wise.

Maybe you can look into expressing the transformation and filtering desired in the context of a "plain" (declarative) SQL query.

angular2 submit form by pressing enter without submit button

Hopefully this can help somebody: for some reason I couldn't track because of lack of time, if you have a form like:

<form (ngSubmit)="doSubmit($event)">
  <button (click)="clearForm()">Clear</button>
  <button type="submit">Submit</button>
</form>

when you hit the Enter button, the clearForm function is called, even though the expected behaviour was to call the doSubmit function. Changing the Clear button to a <a> tag solved the issue for me. I would still like to know if that's expected or not. Seems confusing to me

How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite?

In case anyone gets the same error I did: “Requirements installation failed with status: 1.” here's what to do:

Install Homebrew (for some reason might not work automatically) with this command:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Then proceed to install rvm again using

curl -sSL https://get.rvm.io | bash -s stable --ruby

Quit and reopen Terminal and then:

rvm install 2.2
rvm use 2.2 --default

Open Excel file for reading with VBA without display

The problem with both iDevlop's and Ashok's answers is that the fundamental problem is an Excel design flaw (apparently) in which the Open method fails to respect the Application.ScreenUpdating setting of False. Consequently, setting it to False is of no benefit to this problem.

If Patrick McDonald's solution is too burdensome due to the overhead of starting a second instance of Excel, then the best solution I've found is to minimize the time that the opened workbook is visible by re-activating the original window as quickly as possible:

Dim TempWkBk As Workbook
Dim CurrentWin As Window

Set CurrentWin = ActiveWindow
Set TempWkBk = Workbooks.Open(SomeFilePath)
CurrentWin.Activate      'Allows only a VERY brief flash of the opened workbook
TempWkBk.Windows(1).Visible = False 'Only necessary if you also need to prevent
                                    'the user from manually accessing the opened
                                    'workbook before it is closed.

'Operate on the new workbook, which is not visible to the user, then close it...

iPhone UITextField - Change placeholder text color

Another option that doesn't require subclassing - leave placeholder blank, and put a label on top of edit button. Manage the label just like you would manage the placeholder (clearing once user inputs anything..)

Format output string, right alignment

To do it by using f-string and with control of the number of trailing digits:

print(f'A number -> {my_number:>20.5f}')

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

The only thing that worked for me was creating a new application in the IIS, mapping it to exactly the same physical path, and changing only the authentication to be Anonymous.

Fixing a systemd service 203/EXEC failure (no such file or directory)

I ran across a Main process exited, code=exited, status=203/EXEC today as well and my bug was that I forgot to add the executable bit to the file.

What is the meaning of "int(a[::-1])" in Python?

The notation that is used in

a[::-1]

means that for a given string/list/tuple, you can slice the said object using the format

<object_name>[<start_index>, <stop_index>, <step>]

This means that the object is going to slice every "step" index from the given start index, till the stop index (excluding the stop index) and return it to you.

In case the start index or stop index is missing, it takes up the default value as the start index and stop index of the given string/list/tuple. If the step is left blank, then it takes the default value of 1 i.e it goes through each index.

So,

a = '1234'
print a[::2]

would print

13

Now the indexing here and also the step count, support negative numbers. So, if you give a -1 index, it translates to len(a)-1 index. And if you give -x as the step count, then it would step every x'th value from the start index, till the stop index in the reverse direction. For example

a = '1234'
print a[3:0:-1]

This would return

432

Note, that it doesn't return 4321 because, the stop index is not included.

Now in your case,

str(int(a[::-1]))

would just reverse a given integer, that is stored in a string, and then convert it back to a string

i.e "1234" -> "4321" -> 4321 -> "4321"

If what you are trying to do is just reverse the given string, then simply a[::-1] would work .

`require': no such file to load -- mkmf (LoadError)

The problem is still is recursive on Ubuntu 13/04/13.10/14.04

and

sudo apt-get install ruby1.9.1-dev

worked out for me okay. So If you are using Ubuntu 13.04/13.10/14.04 then using this will really come in handy.

This works even if ruby version is 1.9.3. This is because there is no ruby1.9.3-dev available in the Repository...

Overriding the java equals() method - not working?

Slightly off-topic to your question, but it's probably worth mentioning anyway:

Commons Lang has got some excellent methods you can use in overriding equals and hashcode. Check out EqualsBuilder.reflectionEquals(...) and HashCodeBuilder.reflectionHashCode(...). Saved me plenty of headache in the past - although of course if you just want to do "equals" on ID it may not fit your circumstances.

I also agree that you should use the @Override annotation whenever you're overriding equals (or any other method).

Move entire line up and down in Vim

:m.+1 or :m.-2 would do if you're moving a single line. Here's my script to move multiple lines. In visual mode, Alt-up/Alt-down will move the lines containing the visual selection up/down by one line. In insert mode or normal mode, Alt-up/Alt-down will move the current line if no count prefix is given. If there's a count prefix, Alt-up/Alt-down will move that many lines beginning from the current line up/down by one line.

function! MoveLines(offset) range
    let l:col = virtcol('.')
    let l:offset = str2nr(a:offset)
    exe 'silent! :' . a:firstline . ',' . a:lastline . 'm'
        \ . (l:offset > 0 ? a:lastline + l:offset : a:firstline + l:offset)
    exe 'normal ' . l:col . '|'
endf

imap <silent> <M-up> <C-O>:call MoveLines('-2')<CR>
imap <silent> <M-down> <C-O>:call MoveLines('+1')<CR>
nmap <silent> <M-up> :call MoveLines('-2')<CR>
nmap <silent> <M-down> :call MoveLines('+1')<CR>
vmap <silent> <M-up> :call MoveLines('-2')<CR>gv
vmap <silent> <M-down> :call MoveLines('+1')<CR>gv

No server in Eclipse; trying to install Tomcat

You can install Tomcat server form Eclipse market place.

Help -> Eclipse Market Place search for 'Tomcat' -> Install Eclipse Tomcat plugin.

enter image description here

After installation restart eclipse.

Pass table as parameter into sql server UDF

you can do something like this

/* CREATE USER DEFINED TABLE TYPE */

CREATE TYPE StateMaster AS TABLE
(
 StateCode VARCHAR(2),
 StateDescp VARCHAR(250)
)
GO

/*CREATE FUNCTION WHICH TAKES TABLE AS A PARAMETER */

CREATE FUNCTION TableValuedParameterExample(@TmpTable StateMaster READONLY)
RETURNS  VARCHAR(250)
AS
BEGIN
 DECLARE @StateDescp VARCHAR(250)
 SELECT @StateDescp = StateDescp FROM @TmpTable
 RETURN @StateDescp
END
GO

/*CREATE STORED PROCEDURE WHICH TAKES TABLE AS A PARAMETER */

CREATE PROCEDURE TableValuedParameterExample_SP
(
@TmpTable StateMaster READONLY
)
AS
BEGIN
 INSERT INTO StateMst 
  SELECT * FROM @TmpTable
END
GO


BEGIN
/* DECLARE VARIABLE OF TABLE USER DEFINED TYPE */
DECLARE @MyTable StateMaster

/* INSERT DATA INTO TABLE TYPE */
INSERT INTO @MyTable VALUES('11','AndhraPradesh')
INSERT INTO @MyTable VALUES('12','Assam')

/* EXECUTE STORED PROCEDURE */
EXEC TableValuedParameterExample_SP @MyTable
GO

For more details check this link: http://sailajareddy-technical.blogspot.in/2012/09/passing-table-valued-parameter-to.html

select from one table, insert into another table oracle sql query

From the oracle documentation, the below query explains it better

INSERT INTO tbl_temp2 (fld_id)
SELECT tbl_temp1.fld_order_id
FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;

You can read this link

Your query would be as follows

//just the concept    
    INSERT INTO quotedb
    (COLUMN_NAMES) //seperated by comma
    SELECT COLUMN_NAMES FROM tickerdb,quotedb WHERE quotedb.ticker = tickerdb.ticker

Note: Make sure the columns in insert and select are in right position as per your requirement

Hope this helps!

How to get JQuery.trigger('click'); to initiate a mouse click

You can't simulate a click event with javascript. jQuery .trigger() function only fires an event named "click" on the element, which you can capture with .on() jQuery method.

<DIV> inside link (<a href="">) tag

I would just format two different a-tags with a { display: block; height: 15px; width: 40px; } . This way you don't even need the div-tags...

React eslint error missing in props validation

You need to define propTypes as a static getter if you want it inside the class declaration:

static get propTypes() { 
    return { 
        children: PropTypes.any, 
        onClickOut: PropTypes.func 
    }; 
}

If you want to define it as an object, you need to define it outside the class, like this:

IxClickOut.propTypes = {
    children: PropTypes.any,
    onClickOut: PropTypes.func,
};

Also it's better if you import prop types from prop-types, not react, otherwise you'll see warnings in console (as preparation for React 16):

import PropTypes from 'prop-types';

Undefined symbols for architecture i386: _OBJC_CLASS_$_SKPSMTPMessage", referenced from: error

I had this issue when I opened the same project twice, only one project was the original and the other was cloned from a git url.

'Product' > 'Clean' solved the problem.

MySQL and PHP - insert NULL rather than empty string

To pass a NULL to MySQL, you do just that.

INSERT INTO table (field,field2) VALUES (NULL,3)

So, in your code, check if $intLat, $intLng are empty, if they are, use NULL instead of '$intLat' or '$intLng'.

$intLat = !empty($intLat) ? "'$intLat'" : "NULL";
$intLng = !empty($intLng) ? "'$intLng'" : "NULL";

$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
          VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$long', 
                  $intLat, $intLng)";

How can I upgrade NumPy?

When you already have an older version of NumPy, use this:

pip install numpy --upgrade

If it still doesn't work, try:

pip install numpy --upgrade --ignore-installed

proper hibernate annotation for byte[]

I'm using the Hibernate 4.2.7.SP1 with Postgres 9.3 and following works for me:

@Entity
public class ConfigAttribute {
  @Lob
  public byte[] getValueBuffer() {
    return m_valueBuffer;
  }
}

as Oracle has no trouble with that, and for Postgres I'm using custom dialect:

public class PostgreSQLDialectCustom extends PostgreSQL82Dialect {

    @Override
    public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) {
    if (sqlTypeDescriptor.getSqlType() == java.sql.Types.BLOB) {
      return BinaryTypeDescriptor.INSTANCE;
    }
    return super.remapSqlTypeDescriptor(sqlTypeDescriptor);
  }
}

the advantage of this solution I consider, that I can keep hibernate jars untouched.

For more Postgres/Oracle compatibility issues with Hibernate, see my blog post.

Android EditText Max Length

For me this solution works:

edittext.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);

Access to file download dialog in Firefox

Dont know, but you could perhaps check the source of one of the Firefox download addons.

Here is the source for one that I use Download Statusbar.

Validate phone number using javascript

JavaScript to validate the phone number:

_x000D_
_x000D_
function phonenumber(inputtxt) {_x000D_
  var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;_x000D_
  if(inputtxt.value.match(phoneno)) {_x000D_
    return true;_x000D_
  }_x000D_
  else {_x000D_
    alert("message");_x000D_
    return false;_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

The above script matches:

XXX-XXX-XXXX
XXX.XXX.XXXX
XXX XXX XXXX

If you want to use a + sign before the number in the following way
+XX-XXXX-XXXX
+XX.XXXX.XXXX
+XX XXXX XXXX
use the following code:

function phonenumber(inputtxt) {
  var phoneno = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
  if(inputtxt.value.match(phoneno)) {
    return true;
  }  
  else {  
    alert("message");
    return false;
  }
}

Refresh Fragment at reload

// Reload current fragment
Fragment frag = new Order();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment_home, frag).commit();

Scala check if element is present in a list

Just use contains

myFunction(strings.contains(myString))

javascript regex for special characters

There are some issue with above written Regex.

This works perfectly.

^[a-zA-Z\d\-_.,\s]+$

Only allowed special characters are included here and can be extended after comma.

Freeze the top row for an html table only (Fixed Table Header Scrolling)

you can use two divs one for the headings and the other for the table. then use

#headings {
  position: fixed;
  top: 0px;
  width: 960px;
}

as @ptriek said this will only work for fixed width columns.

Passing a method as a parameter in Ruby

You can pass a method as parameter with method(:function) way. Below is a very simple example:

def double(a)
  return a * 2 
end
=> nil

def method_with_function_as_param( callback, number) 
  callback.call(number) 
end 
=> nil

method_with_function_as_param( method(:double) , 10 ) 
=> 20

What is the python "with" statement designed for?

Again for completeness I'll add my most useful use-case for with statements.

I do a lot of scientific computing and for some activities I need the Decimal library for arbitrary precision calculations. Some part of my code I need high precision and for most other parts I need less precision.

I set my default precision to a low number and then use with to get a more precise answer for some sections:

from decimal import localcontext

with localcontext() as ctx:
    ctx.prec = 42   # Perform a high precision calculation
    s = calculate_something()
s = +s  # Round the final result back to the default precision

I use this a lot with the Hypergeometric Test which requires the division of large numbers resulting form factorials. When you do genomic scale calculations you have to be careful of round-off and overflow errors.

How to extend / inherit components?

Alternative Solution:

This answer of Thierry Templier is an alternative way to get around the problem.

After some questions with Thierry Templier, I came to the following working example that meets my expectations as an alternative to inheritance limitation mentioned in this question:

1 - Create custom decorator:

export function CustomComponent(annotation: any) {
  return function (target: Function) {
    var parentTarget = Object.getPrototypeOf(target.prototype).constructor;
    var parentAnnotations = Reflect.getMetadata('annotations', parentTarget);

    var parentAnnotation = parentAnnotations[0];
    Object.keys(parentAnnotation).forEach(key => {
      if (isPresent(parentAnnotation[key])) {
        // verify is annotation typeof function
        if(typeof annotation[key] === 'function'){
          annotation[key] = annotation[key].call(this, parentAnnotation[key]);
        }else if(
        // force override in annotation base
        !isPresent(annotation[key])
        ){
          annotation[key] = parentAnnotation[key];
        }
      }
    });

    var metadata = new Component(annotation);

    Reflect.defineMetadata('annotations', [ metadata ], target);
  }
}

2 - Base Component with @Component decorator:

@Component({
  // create seletor base for test override property
  selector: 'master',
  template: `
    <div>Test</div>
  `
})
export class AbstractComponent {

}

3 - Sub component with @CustomComponent decorator:

@CustomComponent({
  // override property annotation
  //selector: 'sub',
  selector: (parentSelector) => { return parentSelector + 'sub'}
})
export class SubComponent extends AbstractComponent {
  constructor() {
  }
}

Plunkr with complete example.

How to change text color of simple list item

In simple word "you can't do it through simple setListAdapter" . you must used custom listview for freely changes in text color or in any other views

for Custom Listview you can go with this link

GROUP_CONCAT ORDER BY

You can use SEPARATOR and ORDER BY inside the GROUP_CONCAT function in this way:

SELECT li.client_id, group_concat(li.percentage ORDER BY li.views ASC SEPARATOR ',') 
AS views, group_concat(li.percentage ORDER BY li.percentage ASC SEPARATOR ',') FROM li
GROUP BY client_id;

VSCode: How to Split Editor Vertically

Simply in windows

ctrl + @ (the button 2 in the upper horizontal row of numbers in keyboard)

Is there a native jQuery function to switch elements?

Many of these answers are simply wrong for the general case, others are unnecessarily complicated if they in fact even work. The jQuery .before and .after methods do most of what you want to do, but you need a 3rd element the way many swap algorithms work. It's pretty simple - make a temporary DOM element as a placeholder while you move things around. There is no need to look at parents or siblings, and certainly no need to clone...

$.fn.swapWith = function(that) {
  var $this = this;
  var $that = $(that);

  // create temporary placeholder
  var $temp = $("<div>");

  // 3-step swap
  $this.before($temp);
  $that.before($this);
  $temp.after($that).remove();

  return $this;
}

1) put the temporary div temp before this

2) move this before that

3) move that after temp

3b) remove temp

Then simply

$(selectorA).swapWith(selectorB);

DEMO: http://codepen.io/anon/pen/akYajE

How do I write dispatch_after GCD in Swift 3, 4, and 5?

In Swift 4.1 and Xcode 9.4.1

Simple answer is...

//To call function after 5 seconds time
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
//Here call your function
}

.gitignore for Visual Studio Projects and Solutions

Here's an extract from a .gitignore on a recent project I was working on. I've extracted the ones that I believe are related to Visual Studio, including the compilation outputs; it's a cross platform project, so there are various other ignore rules for files produced by other build systems, and I can't guarantee that I separated them out exactly.

*.dll
*.exe
*.exp
*.ilk
*.lib
*.ncb
*.log
*.pdb
*.vcproj.*.user
[Dd]ebug
[Rr]elease

Perhaps this question should be Community Wiki, so we can all edit together one master list with comments about which files should be ignored for which types of project?

How to read existing text files without defining path

You need to decide which directory you want the file to be relative to. Once you have done that, you construct the full path like this:

string fullPathToFile = Path.Combine(dir, fileName);

If you don't supply the base directory dir then you will be at the total mercy of whatever happens to the working directory of your process. That is something that can be out of your control. For example, shortcuts to your application may specify it. Using file dialogs can change it.

For a console application it is reasonable to use relative files directly because console applications are designed so that the working directory is a critical input and is a well-defined part of the execution environment. However, for a GUI app that is not the case which is why I recommend you explicitly convert your relative file name to a full absolute path using some well-defined base directory.

Now, since you have a console application, it is reasonable for you to use a relative path, provided that the expectation is that the files in question will be located in the working directory. But it would be very common for that not to be the case. Normally the working directory is used to specify where the user's input and output files are to be stored. It does not typically point to the location where the program's files are.

One final option is that you don't attempt to deploy these program files as external text files. Perhaps a better option is to link them to the executable as resources. That way they are bound up with the executable and you can completely side-step this issue.

Replace given value in vector

The ifelse function would be a quick and easy way to do this.

How can I remove 3 characters at the end of a string in php?

<?php echo substr($string, 0, strlen($string) - 3); ?>

How to access the local Django webserver from outside world

If you are using Docker you need to make sure ports are exposed as well

Sorting data based on second column of a file

You can use the sort command:

sort -k2 -n yourfile

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

For example:

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

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

How to specify the JDK version in android studio?

This is old question but still my answer may help someone

For checking Java version in android studio version , simply open Terminal of Android Studio and type

java -version 

This will display java version installed in android studio

How to pass a single object[] to a params object[]

One option is you can wrap it into another array:

Foo(new object[]{ new object[]{ (object)"1", (object)"2" } });

Kind of ugly, but since each item is an array, you can't just cast it to make the problem go away... such as if it were Foo(params object items), then you could just do:

Foo((object) new object[]{ (object)"1", (object)"2" });

Alternatively, you could try defining another overloaded instance of Foo which takes just a single array:

void Foo(object[] item)
{
    // Somehow don't duplicate Foo(object[]) and
    // Foo(params object[]) without making an infinite
    // recursive call... maybe something like
    // FooImpl(params object[] items) and then this
    // could invoke it via:
    // FooImpl(new object[] { item });
}

Read each line of txt file to new array element

If you don't need any special processing, this should do what you're looking for

$lines = file($filename, FILE_IGNORE_NEW_LINES);