Programs & Examples On #Jhtmlarea

A simple, light weight, extensible WYSIWYG HTML Editor built on top of jQuery. This component allows you to easily display a WYSIWYG HTML Editor in place of any TextArea DOM Elements on the page.

Install / upgrade gradle on Mac OS X

Another alternative is to use sdkman. An advantage of sdkman over brew is that many versions of gradle are supported. (brew only supports the latest version and 2.14.) To install sdkman execute:

curl -s "https://get.sdkman.io" | bash

Then follow the instructions. Go here for more installation information. Once sdkman is installed use the command:

sdk install gradle

Or to install a specific version:

sdk install gradle 2.2

Or use to use a specific installed version:

sdk use gradle 2.2

To see which versions are installed and available:

sdk list gradle

For more information go here.

Add JsonArray to JsonObject

here is simple code

List <String> list = new ArrayList <String>();
list.add("a");
list.add("b");
JSONArray array = new JSONArray();
for (int i = 0; i < list.size(); i++) {
        array.put(list.get(i));
}
JSONObject obj = new JSONObject();
try {
    obj.put("result", array);
} catch (JSONException e) {
 // TODO Auto-generated catch block
e.printStackTrace();
}
pw.write(obj.toString());

Finding the 'type' of an input element

Check the type property. Would that suffice?

How can I convert integer into float in Java?

Here is how you can do it :

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int x = 3;
    int y = 2;
    Float fX = new Float(x);
    float res = fX.floatValue()/y;
    System.out.println("res = "+res);
}

See you !

Difference between `Optional.orElse()` and `Optional.orElseGet()`

The difference is pretty subtle and if you dont pay much attention then you will keep it using in a wrong way.

Best way to understand the difference between orElse() and orElseGet() is that orElse() will always be executed if the Optional<T> is null or not, But orElseGet() will only be executed when Optional<T> is null.

The dictionary meaning of orElse is :- execute the part when something is not present, but here it contradicts, see the below example:

    Optional<String> nonEmptyOptional = Optional.of("Vishwa Ratna");
    String value = nonEmptyOptional.orElse(iAmStillExecuted());

    public static String iAmStillExecuted(){
    System.out.println("nonEmptyOptional is not NULL,still I am being executed");
    return "I got executed";
    }

Output: nonEmptyOptional is not NULL,still I am being executed


    Optional<String> emptyOptional = Optional.ofNullable(null);
    String value = emptyOptional.orElse(iAmStillExecuted());
    public static String iAmStillExecuted(){
    System.out.println("emptyOptional is NULL, I am being executed, it is normal as 
    per dictionary");
    return "I got executed";
    }

Output: emptyOptional is NULL, I am being executed, it is normal as per dictionary

For orElseGet() , The method goes as per dictionary meaning, The orElseGet() part will be executed only when the Optional is null.

Benchmarks:

+--------------------+------+-----+------------+-------------+-------+
| Benchmark          | Mode | Cnt | Score      | Error       | Units |
+--------------------+------+-----+------------+-------------+-------+
| orElseBenchmark    | avgt | 20  | 60934.425  | ± 15115.599 | ns/op |
+--------------------+------+-----+------------+-------------+-------+
| orElseGetBenchmark | avgt | 20  | 3.798      | ± 0.030     | ns/op |
+--------------------+------+-----+------------+-------------+-------+

Remarks: orElseGet() has clearly outperformed orElse() for our particular example.

Hope it clears the doubts of people like me who wants the very basic ground example :)

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

For the Collatz problem, you can get a significant boost in performance by caching the "tails". This is a time/memory trade-off. See: memoization (https://en.wikipedia.org/wiki/Memoization). You could also look into dynamic programming solutions for other time/memory trade-offs.

Example python implementation:

import sys

inner_loop = 0

def collatz_sequence(N, cache):
    global inner_loop

    l = [ ]
    stop = False
    n = N

    tails = [ ]

    while not stop:
        inner_loop += 1
        tmp = n
        l.append(n)
        if n <= 1:
            stop = True  
        elif n in cache:
            stop = True
        elif n % 2:
            n = 3*n + 1
        else:
            n = n // 2
        tails.append((tmp, len(l)))

    for key, offset in tails:
        if not key in cache:
            cache[key] = l[offset:]

    return l

def gen_sequence(l, cache):
    for elem in l:
        yield elem
        if elem in cache:
            yield from gen_sequence(cache[elem], cache)
            raise StopIteration

if __name__ == "__main__":
    le_cache = {}

    for n in range(1, 4711, 5):
        l = collatz_sequence(n, le_cache)
        print("{}: {}".format(n, len(list(gen_sequence(l, le_cache)))))

    print("inner_loop = {}".format(inner_loop))

How to delete multiple files at once in Bash on Linux?

Bash supports all sorts of wildcards and expansions.

Your exact case would be handled by brace expansion, like so:

$ rm -rf abc.log.2012-03-{14,27,28}

The above would expand to a single command with all three arguments, and be equivalent to typing:

$ rm -rf abc.log.2012-03-14 abc.log.2012-03-27 abc.log.2012-03-28

It's important to note that this expansion is done by the shell, before rm is even loaded.

Split value from one field to two

This takes smhg from here and curt's from Last index of a given substring in MySQL and combines them. This is for mysql, all I needed was to get a decent split of name to first_name last_name with the last name a single word, the first name everything before that single word, where the name could be null, 1 word, 2 words, or more than 2 words. Ie: Null; Mary; Mary Smith; Mary A. Smith; Mary Sue Ellen Smith;

So if name is one word or null, last_name is null. If name is > 1 word, last_name is last word, and first_name all words before last word.

Note that I've already trimmed off stuff like Joe Smith Jr. ; Joe Smith Esq. and so on, manually, which was painful, of course, but it was small enough to do that, so you want to make sure to really look at the data in the name field before deciding which method to use.

Note that this also trims the outcome, so you don't end up with spaces in front of or after the names.

I'm just posting this for others who might google their way here looking for what I needed. This works, of course, test it with the select first.

It's a one time thing, so I don't care about efficiency.

SELECT TRIM( 
    IF(
        LOCATE(' ', `name`) > 0,
        LEFT(`name`, LENGTH(`name`) - LOCATE(' ', REVERSE(`name`))),
        `name`
    ) 
) AS first_name,
TRIM( 
    IF(
        LOCATE(' ', `name`) > 0,
        SUBSTRING_INDEX(`name`, ' ', -1) ,
        NULL
    ) 
) AS last_name
FROM `users`;


UPDATE `users` SET
`first_name` = TRIM( 
    IF(
        LOCATE(' ', `name`) > 0,
        LEFT(`name`, LENGTH(`name`) - LOCATE(' ', REVERSE(`name`))),
        `name`
    ) 
),
`last_name` = TRIM( 
    IF(
        LOCATE(' ', `name`) > 0,
        SUBSTRING_INDEX(`name`, ' ', -1) ,
        NULL
    ) 
);

Run a Java Application as a Service on Linux

Linux service init script are stored into /etc/init.d. You can copy and customize /etc/init.d/skeleton file, and then call

service [yourservice] start|stop|restart

see http://www.ralfebert.de/blog/java/debian_daemon/. Its for Debian (so, Ubuntu as well) but fit more distribution.

How to copy a huge table data into another table in SQL Server

If you are copying into a new table, the quickest way is probably what you have in your question, unless your rows are very large.

If your rows are very large, you may want to use the bulk insert functions in SQL Server. I think you can call them from C#.

Or you can first download that data into a text file, then bulk-copy (bcp) it. This has the additional benefit of allowing you to ignore keys, indexes etc.

Also try the Import/Export utility that comes with the SQL Management Studio; not sure whether it will be as fast as a straight bulk-copy, but it should allow you to skip the intermediate step of writing out as a flat file, and just copy directly table-to-table, which might be a bit faster than your SELECT INTO statement.

Graphical user interface Tutorial in C

My favourite UI tutorials all come from zetcode.com:

These are tutorials I'd consider to be "starting tutorials". The example tutorial gets you up and going, but doesn't show you anything too advanced or give much explanation. Still, often, I find the big problem is "how do I start?" and these have always proved useful to me.

Why does the program give "illegal start of type" error?

You have a misplaced closing brace before the return statement.

Installing MySQL-python

yum install mysql-devel

It worked for me.

How to convert URL parameters to a JavaScript object?

For Node JS, you can use the Node JS API querystring:

const querystring = require('querystring');

querystring.parse('abc=foo&def=%5Basf%5D&xyz=5&foo=b%3Dar');
// returns the object

Documentation: https://nodejs.org/api/querystring.html

Error: " 'dict' object has no attribute 'iteritems' "

In Python2, dictionary.iteritems() is more efficient than dictionary.items() so in Python3, the functionality of dictionary.iteritems() has been migrated to dictionary.items() and iteritems() is removed. So you are getting this error.

Use dict.items() in Python3 which is same as dict.iteritems() of Python2.

How to restore the dump into your running mongodb

I have been through a lot of trouble so I came up with my own solution, I created this script, just set the path inside script and db name and run it, it will do the trick

#!/bin/bash

FILES= #absolute or relative path to dump directory
DB=`db` #db name
for file in $FILES
do

    name=$(basename $file)
    collection="${name%.*}"
    echo `mongoimport --db "$DB" --file "$name" --collection "$collection"`

done

Check OS version in Swift?

The easiest and the simplest way to check system version (and a lot of other versions) in Swift 2 and higher is:

if #available(iOS 9.0, *) { // check for iOS 9.0 and later

}

Also, with #available you can check versions of these:

iOS
iOSApplicationExtension
macOS
macOSApplicationExtension
watchOS
watchOSApplicationExtension
tvOS
tvOSApplicationExtension
swift

How to delete zero components in a vector in Matlab?

If you just wish to remove the zeros, leaving the non-zeros behind in a, then the very best solution is

a(a==0) = [];

This deletes the zero elements, using a logical indexing approach in MATLAB. When the index to a vector is a boolean vector of the same length as the vector, then MATLAB can use that boolean result to index it with. So this is equivalent to

a(find(a==0)) = [];

And, when you set some array elements to [] in MATLAB, the convention is to delete them.

If you want to put the zeros into a new result b, while leaving a unchanged, the best way is probably

b = a(a ~= 0);

Again, logical indexing is used here. You could have used the equivalent version (in terms of the result) of

b = a(find(a ~= 0));

but mlint will end up flagging the line as one where the purely logical index was more efficient, and thus more appropriate.

As always, beware EXACT tests for zero or for any number, if you would have accepted elements of a that were within some epsilonic tolerance of zero. Do those tests like this

b = a(abs(a) >= tol);

This retains only those elements of a that are at least as large as your tolerance.

What is "android:allowBackup"?

This is not explicitly mentioned, but based on the following docs, I think it is implied that an app needs to declare and implement a BackupAgent in order for data backup to work, even in the case when allowBackup is set to true (which is the default value).

http://developer.android.com/reference/android/R.attr.html#allowBackup http://developer.android.com/reference/android/app/backup/BackupManager.html http://developer.android.com/guide/topics/data/backup.html

How to change the session timeout in PHP?

Adding comment for anyone using Plesk having issues with any of the above as it was driving me crazy, setting session.gc_maxlifetime from your PHP script wont work as Plesk has it's own garbage collection script run from cron.

I used the solution posted on the link below of moving the cron job from hourly to daily to avoid this issue, then the top answer above should work:

mv /etc/cron.hourly/plesk-php-cleanuper /etc/cron.daily/

https://websavers.ca/plesk-php-sessions-timing-earlier-expected

How to count digits, letters, spaces for a string in Python?

def match_string(words):
    nums = 0
    letter = 0
    other = 0
    for i in words :
        if i.isalpha():
            letter+=1
        elif i.isdigit():
            nums+=1
        else:
            other+=1
    return nums,letter,other

x = match_string("Hello World")
print(x)
>>>
(0, 10, 2)
>>>

object==null or null==object?

As others have said, it's a habit learned from C to avoid typos - although even in C I'd expect decent compilers at high enough warning levels to give a warning. As Chandru says, comparing against null in Java in this way would only cause problems if you were using a variable of type Boolean (which you're not in the sample code). I'd say that's a pretty rare situation, and not one for which it's worth changing the way you write code everywhere else. (I wouldn't bother reversing the operands even in this case; if I'm thinking clearly enough to consider reversing them, I'm sure I can count the equals signs.)

What hasn't been mentioned is that many people (myself certainly included) find the if (variable == constant) form to be more readable - it's a more natural way of expressing yourself. This is a reason not to blindly copy a convention from C. You should always question practices (as you're doing here :) before assuming that what may be useful in one environment is useful in another.

Determine a string's encoding in C#

My solution is to use built-in stuffs with some fallbacks.

I picked the strategy from an answer to another similar question on stackoverflow but I can't find it now.

It checks the BOM first using the built-in logic in StreamReader, if there's BOM, the encoding will be something other than Encoding.Default, and we should trust that result.

If not, it checks whether the bytes sequence is valid UTF-8 sequence. if it is, it will guess UTF-8 as the encoding, and if not, again, the default ASCII encoding will be the result.

static Encoding getEncoding(string path) {
    var stream = new FileStream(path, FileMode.Open);
    var reader = new StreamReader(stream, Encoding.Default, true);
    reader.Read();

    if (reader.CurrentEncoding != Encoding.Default) {
        reader.Close();
        return reader.CurrentEncoding;
    }

    stream.Position = 0;

    reader = new StreamReader(stream, new UTF8Encoding(false, true));
    try {
        reader.ReadToEnd();
        reader.Close();
        return Encoding.UTF8;
    }
    catch (Exception) {
        reader.Close();
        return Encoding.Default;
    }
}

Get current URL from IFRAME

Some additional information for anyone who might be struggling with this:

You'll be getting null values if you're trying to get URL from iframe before it's loaded. I solved this problem by creating the whole iframe in javascript and getting the values I needed with the onLoad function:

var iframe = document.createElement('iframe');
iframe.onload = function() {

    //some custom settings
    this.width=screen.width;this.height=screen.height; this.passing=0; this.frameBorder="0";

    var href = iframe.contentWindow.location.href;
    var origin = iframe.contentWindow.location.origin;
    var url = iframe.contentWindow.location.url;
    var path = iframe.contentWindow.location.pathname;

    console.log("href: ", href)
    console.log("origin: ", origin)
    console.log("path: ", path)
    console.log("url: ", url)
};

iframe.src = 'http://localhost/folder/index.html';

document.body.appendChild(iframe);

Because of the same-origin policy, I had problems when accessing "cross origin" frames - I solved that by running a webserver locally instead of running all the files directly from my disk. In order for all of this to work, you need to be accessing the iframe with the same protocol, hostname and port as the origin. Not sure which of these was/were missing when running all files from my disk.

Also, more on location objects: https://www.w3schools.com/JSREF/obj_location.asp

How to close TCP and UDP ports via windows command line

Use TCPView: http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx
or CurrPorts: https://www.nirsoft.net/utils/cports.html

Alternatively, if you don't want to use EXTERNAL SOFTWARE (these tools don't require an installation by the way), you can simply FIRST run the netstat command (preferably netstat -b ) & then setup Local Security Policy to block the IP address of the user's machine in question, that's what I have been doing with unwanted or even unknown connections - that allows you doing everything WITHOUT ANY EXTERNAL SOFTWARE (everything comes with Windows)...

MySQL - How to parse a string value to DATETIME format inside an INSERT statement?

Use MySQL's STR_TO_DATE() function to parse the string that you're attempting to insert:

INSERT INTO tblInquiry (fldInquiryReceivedDateTime) VALUES
  (STR_TO_DATE('5/15/2012 8:06:26 AM', '%c/%e/%Y %r'))

PHP __get and __set magic methods

It's because $bar is a public property.

$foo->bar = 'test';

There is no need to call the magic method when running the above.

Deleting public $bar; from your class should correct this.

Using Java to pull data from a webpage?

The simplest solution (without depending on any third-party library or platform) is to create a URL instance pointing to the web page / link you want to download, and read the content using streams.

For example:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;


public class DownloadPage {

    public static void main(String[] args) throws IOException {

        // Make a URL to the web page
        URL url = new URL("http://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage");

        // Get the input stream through URL Connection
        URLConnection con = url.openConnection();
        InputStream is =con.getInputStream();

        // Once you have the Input Stream, it's just plain old Java IO stuff.

        // For this case, since you are interested in getting plain-text web page
        // I'll use a reader and output the text content to System.out.

        // For binary content, it's better to directly read the bytes from stream and write
        // to the target file.


        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        String line = null;

        // read each line and write to System.out
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    }
}

Hope this helps.

jQuery - If element has class do this

First, you're missing some parentheses in your conditional:

if ($("#about").hasClass("opened")) {
  $("#about").animate({right: "-700px"}, 2000);
}

But you can also simplify this to:

$('#about.opened').animate(...);

If #about doesn't have the opened class, it won't animate.

If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)

Remove Fragment Page from ViewPager in Android

Try this solution. I have used databinding for binding view. You can use common "findViewById()" function.

public class ActCPExpense extends BaseActivity implements View.OnClickListener,  {
private static final String TAG = ActCPExpense.class.getSimpleName();
private Context mContext;
private ActCpLossBinding mBinding;

private ViewPagerAdapter adapter;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try {
        setContentView(R.layout.act_cp_loss);
        mBinding = DataBindingUtil.setContentView(this, R.layout.act_cp_loss);
        mContext = ActCPExpense.this;
        initViewsAct();


    } catch (Exception e) {
        LogUtils.LOGE(TAG, e);
    }

}


private void initViewsAct() {

    adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(FragmentCPPayee.newInstance(), "Title");
    mBinding.viewpager.setAdapter(adapter);
    mBinding.tab.setViewPager(mBinding.viewpager);



}



@Override
public boolean onOptionsItemSelected(MenuItem itemActUtility) {
    int i = itemActUtility.getItemId();
    if (i == android.R.id.home) {
        onBackPressed();

    } 

    return super.onOptionsItemSelected(itemActUtility);
}

@Override
public void onClick(View view) {
    super.onClick(view);
    int id = view.getId();
    if (id == R.id.btnAdd) {
        addFragment();

    } else if (id == R.id.btnDelete) {
        removeFragment();

    }


}
    private void addFragment(){
    adapter.addFragment(FragmentCPPayee.newInstance("Title");
    adapter.notifyDataSetChanged();
    mBinding.tab.setViewPager(mBinding.viewpager);
}
private void removeFragment(){
    adapter.removeItem(mBinding.viewpager.getCurrentItem());
    mBinding.tab.setViewPager(mBinding.viewpager);
}


class ViewPagerAdapter extends FragmentStatePagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();


    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public int getItemPosition(@NonNull Object object) {
        return PagerAdapter.POSITION_NONE;
    }


    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }


    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);

    }

    public void removeItem(int pos) {

        destroyItem(null, pos, mFragmentList.get(pos));
        mFragmentList.remove(pos);
        mFragmentTitleList.remove(pos);
        adapter.notifyDataSetChanged();
        mBinding.viewpager.setCurrentItem(pos - 1, false);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return "Title " + String.valueOf(position + 1);
    }
}


}

HttpContext.Current.Request.Url.Host what it returns?

Try this:

string callbackurl = Request.Url.Host != "localhost" 
    ? Request.Url.Host : Request.Url.Authority;

This will work for local as well as production environment. Because the local uses url with port no that is possible using Url.Host.

Force uninstall of Visual Studio

So Soumyaansh's Revo Uninstaller Pro fix worked for me :) ( After 2 days of troubleshooting other options {screams internally 😀} ).

I did run into the an issue with his method though, "Could not find a suitable SDK to target" even though I selected to install Visual Studio with custom settings and selected the SDK I wanted to install. You may need to download the Windows 10 Standalone SDK to resolved this, in order to develop UWP apps if you see this same error after reinstalling Visual Studio.

To do this

  1. Uninstall any Windows 10 SDKs that me on the system (the naming schem for them looks like Windows 10 SDK (WINDOWS_VERSION_NUMBER_HERE) -> Windows 10 SDK (14393) etc . . .). If there are no SDKs on your system go to step 2!
  2. All that's left is to download the SDKs you want by Checking out the SDK Archive for all available SDKs and you should be good to go in developing for the UWP!

mySQL convert varchar to date

select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%Y%m'); 

or

select date_format(str_to_date('12/31/2011', '%m/%d/%Y'), '%Y%m'); 

hard to tell from your example

Why do we use web.xml?

It's the default configuration for a Java web application; it's required.

WicketFilter

is applied to every HTTP request that's sent to this web app.

Is it possible to use jQuery to read meta tags

$("meta")

Should give you back an array of elements whose tag name is META and then you can iterate over the collection to pick out whatever attributes of the elements you are interested in.

How to convert timestamp to datetime in MySQL?

Use the FROM_UNIXTIME() function in MySQL

Remember that if you are using a framework that stores it in milliseconds (for example Java's timestamp) you have to divide by 1000 to obtain the right Unix time in seconds.

Convert YYYYMMDD string date to a datetime value

You should have to use DateTime.TryParseExact.

var newDate = DateTime.ParseExact("20111120", 
                                  "yyyyMMdd", 
                                   CultureInfo.InvariantCulture);

OR

string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;

if (DateTime.TryParseExact(str, 
                           format, 
                           System.Globalization.CultureInfo.InvariantCulture,
                           System.Globalization.DateTimeStyles.None, 
                           out date))
{
     //valid
}

Base64 length calculation?

In windows - I wanted to estimate size of mime64 sized buffer, but all precise calculation formula's did not work for me - finally I've ended up with approximate formula like this:

Mine64 string allocation size (approximate) = (((4 * ((binary buffer size) + 1)) / 3) + 1)

So last +1 - it's used for ascii-zero - last character needs to allocated to store zero ending - but why "binary buffer size" is + 1 - I suspect that there is some mime64 termination character ? Or may be this is some alignment issue.

T-SQL: Deleting all duplicate rows but keeping one

Example query:

DELETE FROM Table
WHERE ID NOT IN
(
SELECT MIN(ID)
FROM Table
GROUP BY Field1, Field2, Field3, ...
)

Here fields are column on which you want to group the duplicate rows.

how to overlap two div in css?

See demo here you need to introduce an additiona calss for second div

.overlap{
    top: -30px;
position: relative;
left: 30px;
}

What's the best way to do a backwards loop in C/C#/C++?

I prefer a while loop. It's more clear to me than decrementing i in the condition of a for loop

int i = arrayLength;
while(i)
{
    i--;
    //do something with array[i]
}

How to decode encrypted wordpress admin password?

just edit wp_user table with your phpmyadmin, and choose MD5 on Function field then input your new password, save it (go button). enter image description here

How do I know which version of Javascript I'm using?

JavaScript 1.2 was introduced with Netscape Navigator 4 in 1997. That version number only ever had significance for Netscape browsers. For example, Microsoft's implementation (as used in Internet Explorer) is called JScript, and has its own version numbering which bears no relation to Netscape's numbering.

How to append in a json file in Python?

json_obj=json.dumps(a_dict, ensure_ascii=False)

want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format

The following code gives expected output. Is that you want?

import java.util.Calendar;
import java.util.Date;

public class DateAndTime {

    public static void main(String[] args) throws Exception {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SS");
        String strDate = sdf.format(cal.getTime());
        System.out.println("Current date in String Format: " + strDate);

        SimpleDateFormat sdf1 = new SimpleDateFormat();
        sdf1.applyPattern("dd/MM/yyyy HH:mm:ss.SS");
        Date date = sdf1.parse(strDate);
        String string=sdf1.format(date);
        System.out.println("Current date in Date Format: " + string);

    }
}

Android Studio : unmappable character for encoding UTF-8

Check all 'C' characters. There are may be some cyrillic 'C's in english-looking word.
Reason for this is that in both english and russian keyboards 'C' occupies same physical button.

Angular JS Uncaught Error: [$injector:modulerr]

In development environments I recommend you to use not minified distributives. And all errors become more informative! Instead of angular.min.js, use angular.js.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.js">     
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-route.js">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-resource.js">

How do I compare two Integers?

if (x.equals(y))

This looks like an expensive operation. Are there any hash codes calculated this way?

It is not an expensive operation and no hash codes are calculated. Java does not magically calculate hash codes, equals(...) is just a method call, not different from any other method call.

The JVM will most likely even optimize the method call away (inlining the comparison that takes place inside the method), so this call is not much more expensive than using == on two primitive int values.

Note: Don't prematurely apply micro-optimizations; your assumptions like "this must be slow" are most likely wrong or don't matter, because the code isn't a performance bottleneck.

Why isn't Python very good for functional programming?

Scheme doesn't have algebraic data types or pattern matching but it's certainly a functional language. Annoying things about Python from a functional programming perspective:

  1. Crippled Lambdas. Since Lambdas can only contain an expression, and you can't do everything as easily in an expression context, this means that the functions you can define "on the fly" are limited.

  2. Ifs are statements, not expressions. This means, among other things, you can't have a lambda with an If inside it. (This is fixed by ternaries in Python 2.5, but it looks ugly.)

  3. Guido threatens to remove map, filter, and reduce every once in a while

On the other hand, python has lexical closures, Lambdas, and list comprehensions (which are really a "functional" concept whether or not Guido admits it). I do plenty of "functional-style" programming in Python, but I'd hardly say it's ideal.

Return Type for jdbcTemplate.queryForList(sql, object, classType)

List<Conversation> conversations = **jdbcTemplate**.**queryForList**(
            **SQL_QUERY**,
            new Object[] {userId, dateFrom, dateTo});  //placeholders values

Suppose the sql query is like

SQL_QUERY = "**select** info,count(*),IF(info is null , 'DATA' , 'NO DATA') **from** table where userId=? , dateFrom=? , dateTo=?";

**HERE userId=? , dateFrom=? , dateTo=?**

the question marks are place holders

**SQL_QUERY**,
            new Object[] {userId, dateFrom, dateTo});

It will go as an object array along with the sql query

Global variables in AngularJS

Example of AngularJS "global variables" using $rootScope:

Controller 1 sets the global variable:

function MyCtrl1($scope, $rootScope) {
    $rootScope.name = 'anonymous'; 
}

Controller 2 reads the global variable:

function MyCtrl2($scope, $rootScope) {
    $scope.name2 = $rootScope.name; 
}

Here is a working jsFiddle: http://jsfiddle.net/natefriedman/3XT3F/1/

Invariant Violation: _registerComponent(...): Target container is not a DOM element

the ready function can be used like this:

$(document).ready(function () {
  React.render(<App />, document.body);
});

If you don't want to use jQuery, you can use the onload function:

<body onload="initReact()">...</body>

Get Line Number of certain phrase in file Python

You can use list comprehension:

content = open("path/to/file.txt").readlines()

lookup = 'the dog barked'

lines = [line_num for line_num, line_content in enumerate(content) if lookup in line_content]

print(lines)

Seeding the random number generator in Javascript

To write your own pseudo random generator is quite simple.

The suggestion of Dave Scotese is useful but, as pointed out by others, it is not quite uniformly distributed.

However, it is not because of the integer arguments of sin. It's simply because of the range of sin, which happens to be a one dimensional projection of a circle. If you would take the angle of the circle instead it would be uniform.

So instead of sin(x) use arg(exp(i * x)) / (2 * PI).

If you don't like the linear order, mix it a bit up with xor. The actual factor doesn't matter that much either.

To generate n pseudo random numbers one could use the code:

function psora(k, n) {
  var r = Math.PI * (k ^ n)
  return r - Math.floor(r)
}
n = 42; for(k = 0; k < n; k++) console.log(psora(k, n))

Please also note that you cannot use pseudo random sequences when real entropy is needed.

Adding an assets folder in Android Studio

right click on app-->select

New-->Select Folder-->then click on Assets Folder

How to: "Separate table rows with a line"

Set colspan to your number of columns, and background color as you wish

<tr style="background: #aaa;">
 <td colspan="2"></td>
</tr>

How to check if string contains Latin characters only?

All these answers are correct, but I had to also check if the string contains other characters and Hebrew letters so I simply used:

if (!str.match(/^[\d]+$/)) {
    //contains other characters as well
}

How to use PrimeFaces p:fileUpload? Listener method is never invoked or UploadedFile is null / throws an error / not usable

With JBoss 7.2(Undertow) and PrimeFaces 6.0 org.primefaces.webapp.filter.FileUploadFilter should be removed from web.xml and context param file uploader should be set to native:

<context-param>
    <param-name>primefaces.UPLOADER</param-name>
    <param-value>native</param-value>
</context-param>

Recursively find files with a specific extension

As an alternative to using -regex option on find, since the question is labeled , you can use the brace expansion mechanism:

eval find . -false "-o -name Robert".{jpg,pdf}

Convert character to Date in R

library(lubridate) if your date format is like this '04/24/2017 05:35:00'then change it like below prods.all$Date2<-gsub("/","-",prods.all$Date2) then change the date format parse_date_time(prods.all$Date2, orders="mdy hms")

Embed an External Page Without an Iframe?

Question is good, but the answer is : it depends on that.

If the other webpage doesn't contain any form or text, for example you can use the CURL method to pickup the exact content and after then showing on your page. YOu can do it without using an iframe.

But, if the page what you want to embed contains for example a form it will not work correctly , because the form handling is on that site.

Change table header color using bootstrap

there's a bootstrap function to change the color of table header called thead-dark for dark background of table header and thead-light for light background of table header. Your code will look like this after using this function.

<table class="table">
    <tr class="thead-danger">
        <!-- here I used dark table headre -->
        <th>
            @Html.DisplayNameFor(model => model.name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.checkBox1)
        </th>
        <th></th>
    </tr>

How can I determine the current CPU utilization from the shell?

Try this command:

cat /proc/stat

This will be something like this:

cpu  55366 271 17283 75381807 22953 13468 94542 0
cpu0 3374 0 2187 9462432 1393 2 665 0
cpu1 2074 12 1314 9459589 841 2 43 0
cpu2 1664 0 1109 9447191 666 1 571 0
cpu3 864 0 716 9429250 387 2 118 0
cpu4 27667 110 5553 9358851 13900 2598 21784 0
cpu5 16625 146 2861 9388654 4556 4026 24979 0
cpu6 1790 0 1836 9436782 480 3307 19623 0
cpu7 1306 0 1702 9399053 726 3529 26756 0
intr 4421041070 559 10 0 4 5 0 0 0 26 0 0 0 111 0 129692 0 0 0 0 0 95 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 369 91027 1580921706 1277926101 570026630 991666971 0 277768 0 0 0 0 0 0 0 0 0 0 0 0 0
ctxt 8097121
btime 1251365089
processes 63692
procs_running 2
procs_blocked 0

More details:

http://www.mail-archive.com/[email protected]/msg01690.html http://www.linuxhowtos.org/System/procstat.htm

What is the simplest and most robust way to get the user's current location on Android?

public static Location getBestLocation(Context ctxt) {
    Location gpslocation = getLocationByProvider(
        LocationManager.GPS_PROVIDER, ctxt);
    Location networkLocation = getLocationByProvider(
        LocationManager.NETWORK_PROVIDER, ctxt);
    Location fetchedlocation = null;
    // if we have only one location available, the choice is easy
    if (gpslocation != null) {
        Log.i("New Location Receiver", "GPS Location available.");
        fetchedlocation = gpslocation;
    } else {
        Log.i("New Location Receiver",
            "No GPS Location available. Fetching Network location lat="
                + networkLocation.getLatitude() + " lon ="
                + networkLocation.getLongitude());
        fetchedlocation = networkLocation;
    }
    return fetchedlocation;
}

/**
 * get the last known location from a specific provider (network/gps)
 */
private static Location getLocationByProvider(String provider, Context ctxt) {
    Location location = null;
    // if (!isProviderSupported(provider)) {
    // return null;
    // }
    LocationManager locationManager = (LocationManager) ctxt
            .getSystemService(Context.LOCATION_SERVICE);
    try {
        if (locationManager.isProviderEnabled(provider)) {
            location = locationManager.getLastKnownLocation(provider);
        }
    } catch (IllegalArgumentException e) {
        Log.i("New Location Receiver", "Cannot access Provider " + provider);
    }
    return location;
}

Formatting a number with exactly two decimals in JavaScript

Here's a TypeScript implementation of https://stackoverflow.com/a/21323330/916734. It also dries things up with functions, and allows for a optional digit offset.

export function round(rawValue: number | string, precision = 0, fractionDigitOffset = 0): number | string {
  const value = Number(rawValue);
  if (isNaN(value)) return rawValue;

  precision = Number(precision);
  if (precision % 1 !== 0) return NaN;

  let [ stringValue, exponent ] = scientificNotationToParts(value);

  let shiftExponent = exponentForPrecision(exponent, precision, Shift.Right);
  const enlargedValue = toScientificNotation(stringValue, shiftExponent);
  const roundedValue = Math.round(enlargedValue);

  [ stringValue, exponent ] = scientificNotationToParts(roundedValue);
  const precisionWithOffset = precision + fractionDigitOffset;
  shiftExponent = exponentForPrecision(exponent, precisionWithOffset, Shift.Left);

  return toScientificNotation(stringValue, shiftExponent);
}

enum Shift {
  Left = -1,
  Right = 1,
}

function scientificNotationToParts(value: number): Array<string> {
  const [ stringValue, exponent ] = value.toString().split('e');
  return [ stringValue, exponent ];
}

function exponentForPrecision(exponent: string, precision: number, shift: Shift): number {
  precision = shift * precision;
  return exponent ? (Number(exponent) + precision) : precision;
}

function toScientificNotation(value: string, exponent: number): number {
  return Number(`${value}e${exponent}`);
}

Android Studio gradle takes too long to build

Recommended Reading: How I save 5h/week on Gradle builds!

According to this excellent post you should try to optimized the following:

  • Gradle Daemon
  • Parallel Project Execution
  • Configure projects on demand
  • Modules are expensive...

Mysql password expired. Can't connect

All of these answers are using Linux consoles to access MySQL.

If you are on Windows and are using WAMP, you can start by opening the MySQL console (click WAMP icon->MySQL->MySQL console).

Then it will request you to enter your current password, enter it.

And then type SET PASSWORD = PASSWORD('some_pass');

batch file to copy files to another location?

@echo off cls echo press any key to continue backup ! pause xcopy c:\users\file*.* e:\backup*.* /s /e echo backup complete pause


file = name of file your wanting to copy

backup = where u want the file to be moved to

Hope this helps

Navigation bar show/hide

Here is a very quick and simple solution:

self.navigationController.hidesBarsOnTap = YES;

This will work on single tap instead of double tap. Also it will change the behavior for the navigation controller even after pushing or popping the current view controller.

You can always modify this behavior in your controller within the viewWillAppear: and viewWillDisappear: actions if you would like to set the behavior only for a single view controller.

Here is the documentation:

Javascript: Fetch DELETE and PUT requests

Here are examples for Delete and Put for React & redux & ReduxThunk with Firebase:

Update (PUT):

export const updateProduct = (id, title, description, imageUrl) => {
    await fetch(`https://FirebaseProjectName.firebaseio.com/products/${id}.json`, {
  method: "PATCH",
  header: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    title,
    description,
    imageUrl,
  }),
});

dispatch({
  type: "UPDATE_PRODUCT",
  pid: id,
  productData: {
    title,
    description,
    imageUrl,
  },
});
};
};

Delete:

export const deleteProduct = (ProductId) => {
  return async (dispatch) => {
await fetch(
  `https://FirebaseProjectName.firebaseio.com/products/${ProductId}.json`,
  {
    method: "DELETE",
  }
);
dispatch({
  type: "DELETE_PRODUCT",
  pid: ProductId,
});
  };
};

How to disable the parent form when a child form is active?

Have you tried using Form.ShowDialog() instead of Form.Show()?

ShowDialog shows your window as modal, which means you cannot interact with the parent form until it closes.

Which is the fastest algorithm to find prime numbers?

If it has to be really fast you can include a list of primes:
http://www.bigprimes.net/archive/prime/

If you just have to know if a certain number is a prime number, there are various prime tests listed on wikipedia. They are probably the fastest method to determine if large numbers are primes, especially because they can tell you if a number is not a prime.

wamp server mysql user id and password

WAMP Server – MySQL – Resetting the Root Password (Windows)

  1. Log on to your system as Administrator.

  2. Click on the Wamp server icon > MySQL > MySQL Console

  3. Enter password: LEAVE BLANK AND HIT ENTER

  4. mysql> UPDATE mysql.user SET Password=PASSWORD(‘MyNewPass’) WHERE User=’root’; ENTER Query OK

  5. mysql>FLUSH PRIVILEGES; ENTER mysql>quit ENTER mysql>bye

  6. Edit phpmyadmin file called “config.inc.php” enter ‘MyNewPass’ ($cfg['Servers'][$i]['password'] = ‘MyNewPass‘;)

  7. Restart all services

  8. Clear all cookies – I got the No password error and it was because of the cookies. (ERROR 1045: Access denied for user: ‘root@localhost’ (Using password: NO))

replace NULL with Blank value or Zero in sql server

Replace Null Values as Empty: ISNULL('Value','')

Replace Null Values as 0: ISNULL('Value',0)

Swift - Split string over multiple lines

Sample

var yourString = "first line \n second line \n third line"

In case, you don't find the + operator suitable

Postgres password authentication fails

pg_hba.conf entry define login methods by IP addresses. You need to show the relevant portion of pg_hba.conf in order to get proper help.

Change this line:

host    all             all             <my-ip-address>/32        md5

To reflect your local network settings. So, if your IP is 192.168.16.78 (class C) with a mask of 255.255.255.0, then put this:

host    all             all             192.168.16.0/24        md5

Make sure your WINDOWS MACHINE is in that network 192.168.16.0 and try again.

Is it valid to define functions in JSON results?

Let's quote one of the spec's - http://tools.ietf.org/html/rfc7159#section-12

The The JavaScript Object Notation (JSON) Data Interchange Format Specification states:

JSON is a subset of JavaScript but excludes assignment and invocation.

Since JSON's syntax is borrowed from JavaScript, it is possible to use that language's "eval()" function to parse JSON texts. This generally constitutes an unacceptable security risk, since the text
could contain executable code along with data declarations
. The same consideration applies to the use of eval()-like functions in any other programming language in which JSON texts conform to that
language's syntax.

So all answers which state, that functions are not part of the JSON standard are correct.

The official answer is: No, it is not valid to define functions in JSON results!


The answer could be yes, because "code is data" and "data is code". Even if JSON is used as a language independent data serialization format, a tunneling of "code" through other types will work.

A JSON string might be used to pass a JS function to the client-side browser for execution.

[{"data":[["1","2"],["3","4"]],"aFunction":"function(){return \"foo bar\";}"}]

This leads to question's like: How to "Execute JavaScript code stored as a string".

Be prepared, to raise your "eval() is evil" flag and stick your "do not tunnel functions through JSON" flag next to it.

Removing spaces from string

When I am reading numbers from contact book, then it doesn't worked I used

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

It worked and for url you may use

url=url.replaceAll(" ", "%20");

Read and write a text file in typescript

import { readFileSync } from 'fs';

const file = readFileSync('./filename.txt', 'utf-8');

This worked for me. You may need to wrap the second command in any function or you may need to declare inside a class without keyword const.

How to remove an element from the flow?

Another option is to set height: 0; overflow: visible; to an element, though it won't be really outside the flow and therefore may break margin collapsing.

Android read text raw resource file

@borislemke you can do this by similar way like

TextView  tv ;
findViewById(R.id.idOfTextView);
tv.setText(readNewTxt());
private String readNewTxt(){
InputStream inputStream = getResources().openRawResource(R.raw.yourNewTextFile);
 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

 int i;
 try {
 i = inputStream.read();
while (i != -1)
  {
   byteArrayOutputStream.write(i);
   i = inputStream.read();
   }
    inputStream.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
 e.printStackTrace();
 }

 return byteArrayOutputStream.toString();
 }

How does JavaScript .prototype work?

This is a very simple prototype based object model that would be considered as a sample during the explanation, with no comment yet:

function Person(name){
    this.name = name;
}
Person.prototype.getName = function(){
    console.log(this.name);
}
var person = new Person("George");

There are some crucial points that we have to consider before going through the prototype concept.

1- How JavaScript functions actually work:

To take the first step we have to figure out, how JavaScript functions actually work , as a class like function using this keyword in it or just as a regular function with its arguments, what it does and what it returns.

Let's say we want to create a Person object model. but in this step I'm gonna be trying to do the same exact thing without using prototype and new keyword.

So in this step functions, objects and this keyword, are all we have.

The first question would be how this keyword could be useful without using new keyword.

So to answer that let's say we have an empty object, and two functions like:

var person = {};
function Person(name){  this.name = name;  }

function getName(){
    console.log(this.name);
}

and now without using new keyword how we could use these functions. So JavaScript has 3 different ways to do that:

a. first way is just to call the function as a regular function:

Person("George");
getName();//would print the "George" in the console

in this case, this would be the current context object, which is usually is the global window object in the browser or GLOBAL in Node.js. It means we would have, window.name in browser or GLOBAL.name in Node.js, with "George" as its value.

b. We can attach them to an object, as its properties

-The easiest way to do this is modifying the empty person object, like:

person.Person = Person;
person.getName = getName;

this way we can call them like:

person.Person("George");
person.getName();// -->"George"

and now the person object is like:

Object {Person: function, getName: function, name: "George"}

-The other way to attach a property to an object is using the prototype of that object that can be find in any JavaScript object with the name of __proto__, and I have tried to explain it a bit on the summary part. So we could get the similar result by doing:

person.__proto__.Person = Person;
person.__proto__.getName = getName;

But this way what we actually are doing is modifying the Object.prototype, because whenever we create a JavaScript object using literals ({ ... }), it gets created based on Object.prototype, which means it gets attached to the newly created object as an attribute named __proto__ , so if we change it, as we have done on our previous code snippet, all the JavaScript objects would get changed, not a good practice. So what could be the better practice now:

person.__proto__ = {
    Person: Person,
    getName: getName
};

and now other objects are in peace, but it still doesn't seem to be a good practice. So we have still one more solutions, but to use this solution we should get back to that line of code where person object got created (var person = {};) then change it like:

var propertiesObject = {
    Person: Person,
    getName: getName
};
var person = Object.create(propertiesObject);

what it does is creating a new JavaScript Object and attach the propertiesObject to the __proto__ attribute. So to make sure you can do:

console.log(person.__proto__===propertiesObject); //true

But the tricky point here is you have access to all the properties defined in __proto__ on the first level of the person object(read the summary part for more detail).


as you see using any of these two way this would exactly point to the person object.

c. JavaScript has another way to provide the function with this, which is using call or apply to invoke the function.

The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).

and

The call() method calls a function with a given this value and arguments provided individually.

this way which is my favorite, we can easily call our functions like:

Person.call(person, "George");

or

//apply is more useful when params count is not fixed
Person.apply(person, ["George"]);

getName.call(person);   
getName.apply(person);

these 3 methods are the important initial steps to figure out the .prototype functionality.


2- How does the new keyword work?

this is the second step to understand the .prototype functionality.this is what I use to simulate the process:

function Person(name){  this.name = name;  }
my_person_prototype = { getName: function(){ console.log(this.name); } };

in this part I'm gonna be trying to take all the steps which JavaScript takes, without using the new keyword and prototype, when you use new keyword. so when we do new Person("George"), Person function serves as a constructor, These are what JavaScript does, one by one:

a. first of all it makes an empty object, basically an empty hash like:

var newObject = {};

b. the next step that JavaScript takes is to attach the all prototype objects to the newly created object

we have my_person_prototype here similar to the prototype object.

for(var key in my_person_prototype){
    newObject[key] = my_person_prototype[key];
}

It is not the way that JavaScript actually attaches the properties that are defined in the prototype. The actual way is related to the prototype chain concept.


a. & b. Instead of these two steps you can have the exact same result by doing:

var newObject = Object.create(my_person_prototype);
//here you can check out the __proto__ attribute
console.log(newObject.__proto__ === my_person_prototype); //true
//and also check if you have access to your desired properties
console.log(typeof newObject.getName);//"function"

now we can call the getName function in our my_person_prototype:

newObject.getName();

c. then it gives that object to the constructor,

we can do this with our sample like:

Person.call(newObject, "George");

or

Person.apply(newObject, ["George"]);

then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created.

now the end result before simulating the other steps: Object {name: "George"}


Summary:

Basically, when you use the new keyword on a function, you are calling on that and that function serves as a constructor, so when you say:

new FunctionName()

JavaScript internally makes an object, an empty hash and then it gives that object to the constructor, then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created and then it gives you that object of course if you haven't used the return statement in your function or if you've put a return undefined; at the end of your function body.

So when JavaScript goes to look up a property on an object, the first thing it does, is it looks it up on that object. And then there is a secret property [[prototype]] which we usually have it like __proto__ and that property is what JavaScript looks at next. And when it looks through the __proto__, as far as it is again another JavaScript object, it has its own __proto__ attribute, it goes up and up until it gets to the point where the next __proto__ is null. The point is the only object in JavaScript that its __proto__ attribute is null is Object.prototype object:

console.log(Object.prototype.__proto__===null);//true

and that's how inheritance works in JavaScript.

The prototype chain

In other words, when you have a prototype property on a function and you call a new on that, after JavaScript finishes looking at that newly created object for properties, it will go look at the function's .prototype and also it is possible that this object has its own internal prototype. and so on.

How to delete migration files in Rails 3

Sometimes I found myself deleting the migration file and then deleting the corresponding entry on the table schema_migrations from the database. Not pretty but it works.

Increasing heap space in Eclipse: (java.lang.OutOfMemoryError)

What to do if i have to processed even more that 500000 records ?

There are a few ways, to increase the java heap size for your app where a few have suggested already. Your app need to remove the elements from your adddressMap as your app add new element into it and so you won't encounter oom if there are more records coming in. Look for producer-consumer if you are interested.

Failed to instantiate module [$injector:unpr] Unknown provider: $routeProvider

In my case it was because the file was minified with wrong scope. Use Array!

app.controller('StoreController', ['$http', function($http) {
    ...
}]);

Coffee syntax:

app.controller 'StoreController', Array '$http', ($http) ->
  ...

Java: Difference between the setPreferredSize() and setSize() methods in components

Usage depends on whether the component's parent has a layout manager or not.

  • setSize() -- use when a parent layout manager does not exist;
  • setPreferredSize() (also its related setMinimumSize and setMaximumSize) -- use when a parent layout manager exists.

The setSize() method probably won't do anything if the component's parent is using a layout manager; the places this will typically have an effect would be on top-level components (JFrames and JWindows) and things that are inside of scrolled panes. You also must call setSize() if you've got components inside a parent without a layout manager.

Generally, setPreferredSize() will lay out the components as expected if a layout manager is present; most layout managers work by getting the preferred (as well as minimum and maximum) sizes of their components, then using setSize() and setLocation() to position those components according to the layout's rules.

For example, a BorderLayout tries to make the bounds of its "north" region equal to the preferred size of its north component---they may end up larger or smaller than that, depending on the size of the JFrame, the size of the other components in the layout, and so on.

select dept names who have more than 2 employees whose salary is greater than 1000

SELECT DEPTNAME
FROM(SELECT D.DEPTNAME,COUNT(EMPID) AS TOTEMP
     FROM DEPT AS D,EMPLOYEE AS E
     WHERE D.DEPTID=E.DEPTID AND SALARY>1000
     GROUP BY D.DEPTID
     )
WHERE TOTEMP>2;

Changing the maximum length of a varchar column?

In Oracle SQL Developer

ALTER TABLE car_details MODIFY torque VARCHAR(100);

DataGridView AutoFit and Fill

Try this :

  DGV.AutoResizeColumns();
  DGV.AutoSizeColumnsMode=DataGridViewAutoSizeColumnsMode.AllCells;

How to compare Boolean?

Try this:

if (Boolean.TRUE.equals(yourValue)) { ... }

As additional benefit this is null-safe.

What is the use of System.in.read()?

Two and a half years late is better than never, right?

int System.in.read() reads the next byte of data from the input stream. But I am sure you already knew that, because it is trivial to look up. So, what you are probably asking is:

  • Why is it declared to return an int when the documentation says that it reads a byte?

  • and why does it appear to return garbage? (I type '9', but it returns 57.)

It returns an int because besides all the possible values of a byte, it also needs to be able to return an extra value to indicate end-of-stream. So, it has to return a type which can express more values than a byte can.

Note: They could have made it a short, but they opted for int instead, possibly as a tip of the hat of historical significance to C, whose getc() function also returns an int, but more importantly because short is a bit cumbersome to work with, (the language offers no means of specifying a short literal, so you have to specify an int literal and cast it to short,) plus on certain architectures int has better performance than short.

It appears to return garbage because when you view a character as an integer, what you are looking at is the ASCII(*) value of that character. So, a '9' appears as a 57. But if you cast it to a character, you get '9', so all is well.

Think of it this way: if you typed the character '9' it is nonsensical to expect System.in.read() to return the number 9, because then what number would you expect it to return if you had typed an 'a'? Obviously, characters must be mapped to numbers. ASCII(*) is a system of mapping characters to numbers. And in this system, character '9' maps to number 57, not number 9.

(*) Not necessarily ASCII; it may be some other encoding, like UTF-16; but in the vast majority of encodings, and certainly in all popular encodings, the first 127 values are the same as ASCII. And this includes all english alphanumeric characters and popular symbols.

React component initialize state from props

set the state data inside constructor like this

constructor(props) {
    super(props);
    this.state = {
      productdatail: this.props.productdetailProps
    };
}

it will not going to work if u set in side componentDidMount() method through props.

How to handle windows file upload using Selenium WebDriver?

First add the file to your project resource directory

then

public YourPage uploadFileBtnSendKeys() {
    final ClassLoader classLoader = getClass().getClassLoader();
    final File file = new File(classLoader.getResource("yourFile.whatever").getPath());
    uploadFileBtn.sendKeys(file.getPath());
    return this;
}

Walla, you will see your choosen selected file, and have skipped the file explorer window

How to store an output of shell script to a variable in Unix?

Suppose you want to store the result of an echo command

echo hello   
x=$(echo hello)  
echo "$x",world!  

output:

hello  
hello,world!

How to convert string to string[]?

Casting can also help converting string to string[]. In this case, casting the string with ToArray() is demonstrated:

String myString = "My String";
String[] myString.Cast<char>().Cast<string>().ToArray();

make UITableViewCell selectable only while editing

Have you tried setting the selection properties of your tableView like this:

tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES; 

If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath in your UITableView delegate. The documentation states:

Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected. 

You can have this method return nil in cases where you don't want the selection to happen.

Design DFA accepting binary strings divisible by a number 'n'

Below, I have written an answer for n equals to 5, but you can apply same approach to draw DFAs for any value of n and 'any positional number system' e.g binary, ternary...

First lean the term 'Complete DFA', A DFA defined on complete domain in d:Q × S?Q is called 'Complete DFA'. In other words we can say; in transition diagram of complete DFA there is no missing edge (e.g. from each state in Q there is one outgoing edge present for every language symbol in S). Note: Sometime we define partial DFA as d ? Q × S?Q (Read: How does “d:Q × S?Q” read in the definition of a DFA).

Design DFA accepting Binary numbers divisible by number 'n':

Step-1: When you divide a number ? by n then reminder can be either 0, 1, ..., (n - 2) or (n - 1). If remainder is 0 that means ? is divisible by n otherwise not. So, in my DFA there will be a state qr that would be corresponding to a remainder value r, where 0 <= r <= (n - 1), and total number of states in DFA is n.
After processing a number string ? over S, the end state is qr implies that ? % n => r (% reminder operator).

In any automata, the purpose of a state is like memory element. A state in an atomata stores some information like fan's switch that can tell whether the fan is in 'off' or in 'on' state. For n = 5, five states in DFA corresponding to five reminder information as follows:

  1. State q0 reached if reminder is 0. State q0 is the final state(accepting state). It is also an initial state.
  2. State q1 reaches if reminder is 1, a non-final state.
  3. State q2 if reminder is 2, a non-final state.
  4. State q3 if reminder is 3, a non-final state.
  5. State q4 if reminder is 4, a non-final state.

Using above information, we can start drawing transition diagram TD of five states as follows:

fig-1
Figure-1

So, 5 states for 5 remainder values. After processing a string ? if end-state becomes q0 that means decimal equivalent of input string is divisible by 5. In above figure q0 is marked final state as two concentric circle.
Additionally, I have defined a transition rule d:(q0, 0)?q0 as a self loop for symbol '0' at state q0, this is because decimal equivalent of any string consist of only '0' is 0 and 0 is a divisible by n.

Step-2: TD above is incomplete; and can only process strings of '0's. Now add some more edges so that it can process subsequent number's strings. Check table below, shows new transition rules those can be added next step:

+-------------------------------------+
¦Number¦Binary¦Remainder(%5)¦End-state¦
+------+------+-------------+---------¦
¦One   ¦1     ¦1            ¦q1       ¦
+------+------+-------------+---------¦
¦Two   ¦10    ¦2            ¦q2       ¦
+------+------+-------------+---------¦
¦Three ¦11    ¦3            ¦q3       ¦
+------+------+-------------+---------¦
¦Four  ¦100   ¦4            ¦q4       ¦
+-------------------------------------+
  1. To process binary string '1' there should be a transition rule d:(q0, 1)?q1
  2. Two:- binary representation is '10', end-state should be q2, and to process '10', we just need to add one more transition rule d:(q1, 0)?q2
    Path: ?(q0)-1?(q1)-0?(q2)
  3. Three:- in binary it is '11', end-state is q3, and we need to add a transition rule d:(q1, 1)?q3
    Path: ?(q0)-1?(q1)-1?(q3)
  4. Four:- in binary '100', end-state is q4. TD already processes prefix string '10' and we just need to add a new transition rule d:(q2, 0)?q4
    Path: ?(q0)-1?(q1)-0?(q2)-0?(q4)

fig-2 Figure-2

Step-3: Five = 101
Above transition diagram in figure-2 is still incomplete and there are many missing edges, for an example no transition is defined for d:(q2, 1)-?. And the rule should be present to process strings like '101'.
Because '101' = 5 is divisible by 5, and to accept '101' I will add d:(q2, 1)?q0 in above figure-2.
Path: ?(q0)-1?(q1)-0?(q2)-1?(q0)
with this new rule, transition diagram becomes as follows:

fig-3 Figure-3

Below in each step I pick next subsequent binary number to add a missing edge until I get TD as a 'complete DFA'.

Step-4: Six = 110.

We can process '11' in present TD in figure-3 as: ?(q0)-11?(q3) -0?(?). Because 6 % 5 = 1 this means to add one rule d:(q3, 0)?q1.

fig-4 Figure-4

Step-5: Seven = 111

+--------------------------------------------------------------+
¦Number¦Binary¦Remainder(%5)¦End-state¦ Path       ¦ Add       ¦
+------+------+-------------+---------+------------+-----------¦
¦Seven ¦111   ¦7 % 5 = 2    ¦q2       ¦ q0-11?q3   ¦ q3-1?q2    ¦
+--------------------------------------------------------------+

fig-5 Figure-5

Step-6: Eight = 1000

+----------------------------------------------------------+
¦Number¦Binary¦Remainder(%5)¦End-state¦ Path     ¦ Add     ¦
+------+------+-------------+---------+----------+---------¦
¦Eight ¦1000  ¦8 % 5 = 3    ¦q3       ¦q0-100?q4 ¦ q4-0?q3  ¦
+----------------------------------------------------------+

fig-6 Figure-6

Step-7: Nine = 1001

+----------------------------------------------------------+
¦Number¦Binary¦Remainder(%5)¦End-state¦ Path     ¦ Add     ¦
+------+------+-------------+---------+----------+---------¦
¦Nine  ¦1001  ¦9 % 5 = 4    ¦q4       ¦q0-100?q4 ¦ q4-1?q4  ¦
+----------------------------------------------------------+

fig-7 Figure-7

In TD-7, total number of edges are 10 == Q × S = 5 × 2. And it is a complete DFA that can accept all possible binary strings those decimal equivalent is divisible by 5.

Design DFA accepting Ternary numbers divisible by number n:

Step-1 Exactly same as for binary, use figure-1.

Step-2 Add Zero, One, Two

+------------------------------------------------------+
¦Decimal¦Ternary¦Remainder(%5)¦End-state¦   Add        ¦
+-------+-------+-------------+---------+--------------¦
¦Zero   ¦0      ¦0            ¦q0       ¦ d:(q0,0)?q0  ¦
+-------+-------+-------------+---------+--------------¦
¦One    ¦1      ¦1            ¦q1       ¦ d:(q0,1)?q1  ¦
+-------+-------+-------------+---------+--------------¦
¦Two    ¦2      ¦2            ¦q2       ¦ d:(q0,2)?q3  ¦
+------------------------------------------------------+

fig-8
Figure-8

Step-3 Add Three, Four, Five

+-----------------------------------------------------+
¦Decimal¦Ternary¦Remainder(%5)¦End-state¦  Add        ¦
+-------+-------+-------------+---------+-------------¦
¦Three  ¦10     ¦3            ¦q3       ¦ d:(q1,0)?q3 ¦
+-------+-------+-------------+---------+-------------¦
¦Four   ¦11     ¦4            ¦q4       ¦ d:(q1,1)?q4 ¦
+-------+-------+-------------+---------+-------------¦
¦Five   ¦12     ¦0            ¦q0       ¦ d:(q1,2)?q0 ¦
+-----------------------------------------------------+

fig-9
Figure-9

Step-4 Add Six, Seven, Eight

+-----------------------------------------------------+
¦Decimal¦Ternary¦Remainder(%5)¦End-state¦  Add        ¦
+-------+-------+-------------+---------+-------------¦
¦Six    ¦20     ¦1            ¦q1       ¦ d:(q2,0)?q1 ¦
+-------+-------+-------------+---------+-------------¦
¦Seven  ¦21     ¦2            ¦q2       ¦ d:(q2,1)?q2 ¦
+-------+-------+-------------+---------+-------------¦
¦Eight  ¦22     ¦3            ¦q3       ¦ d:(q2,2)?q3 ¦
+-----------------------------------------------------+

fig-10
Figure-10

Step-5 Add Nine, Ten, Eleven

+-----------------------------------------------------+
¦Decimal¦Ternary¦Remainder(%5)¦End-state¦  Add        ¦
+-------+-------+-------------+---------+-------------¦
¦Nine   ¦100    ¦4            ¦q4       ¦ d:(q3,0)?q4 ¦
+-------+-------+-------------+---------+-------------¦
¦Ten    ¦101    ¦0            ¦q0       ¦ d:(q3,1)?q0 ¦
+-------+-------+-------------+---------+-------------¦
¦Eleven ¦102    ¦1            ¦q1       ¦ d:(q3,2)?q1 ¦
+-----------------------------------------------------+

fig-11
Figure-11

Step-6 Add Twelve, Thirteen, Fourteen

+------------------------------------------------------+
¦Decimal ¦Ternary¦Remainder(%5)¦End-state¦  Add        ¦
+--------+-------+-------------+---------+-------------¦
¦Twelve  ¦110    ¦2            ¦q2       ¦ d:(q4,0)?q2 ¦
+--------+-------+-------------+---------+-------------¦
¦Thirteen¦111    ¦3            ¦q3       ¦ d:(q4,1)?q3 ¦
+--------+-------+-------------+---------+-------------¦
¦Fourteen¦112    ¦4            ¦q4       ¦ d:(q4,2)?q4 ¦
+------------------------------------------------------+

fig-12
Figure-12

Total number of edges in transition diagram figure-12 are 15 = Q × S = 5 * 3 (a complete DFA). And this DFA can accept all strings consist over {0, 1, 2} those decimal equivalent is divisible by 5.
If you notice at each step, in table there are three entries because at each step I add all possible outgoing edge from a state to make a complete DFA (and I add an edge so that qr state gets for remainder is r)!

To add further, remember union of two regular languages are also a regular. If you need to design a DFA that accepts binary strings those decimal equivalent is either divisible by 3 or 5, then draw two separate DFAs for divisible by 3 and 5 then union both DFAs to construct target DFA (for 1 <= n <= 10 your have to union 10 DFAs).

If you are asked to draw DFA that accepts binary strings such that decimal equivalent is divisible by 5 and 3 both then you are looking for DFA of divisible by 15 ( but what about 6 and 8?).

Note: DFAs drawn with this technique will be minimized DFA only when there is no common factor between number n and base e.g. there is no between 5 and 2 in first example, or between 5 and 3 in second example, hence both DFAs constructed above are minimized DFAs. If you are interested to read further about possible mini states for number n and base b read paper: Divisibility and State Complexity.

below I have added a Python script, I written it for fun while learning Python library pygraphviz. I am adding it I hope it can be helpful for someone in someway.

Design DFA for base 'b' number strings divisible by number 'n':

So we can apply above trick to draw DFA to recognize number strings in any base 'b' those are divisible a given number 'n'. In that DFA total number of states will be n (for n remainders) and number of edges should be equal to 'b' * 'n' — that is complete DFA: 'b' = number of symbols in language of DFA and 'n' = number of states.

Using above trick, below I have written a Python Script to Draw DFA for input base and number. In script, function divided_by_N populates DFA's transition rules in base * number steps. In each step-num, I convert num into number string num_s using function baseN(). To avoid processing each number string, I have used a temporary data-structure lookup_table. In each step, end-state for number string num_s is evaluated and stored in lookup_table to use in next step.

For transition graph of DFA, I have written a function draw_transition_graph using Pygraphviz library (very easy to use). To use this script you need to install graphviz. To add colorful edges in transition diagram, I randomly generates color codes for each symbol get_color_dict function.

#!/usr/bin/env python
import pygraphviz as pgv
from pprint import pprint
from random import choice as rchoice

def baseN(n, b, syms="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
    """ converts a number `n` into base `b` string """
    return ((n == 0) and syms[0]) or (
        baseN(n//b, b, syms).lstrip(syms[0]) + syms[n % b])

def divided_by_N(number, base):
    """
    constructs DFA that accepts given `base` number strings
    those are divisible by a given `number`
    """
    ACCEPTING_STATE = START_STATE = '0'
    SYMBOL_0 = '0'
    dfa = {
        str(from_state): {
            str(symbol): 'to_state' for symbol in range(base)
        }
        for from_state in range(number)
    }
    dfa[START_STATE][SYMBOL_0] = ACCEPTING_STATE
    # `lookup_table` keeps track: 'number string' -->[dfa]--> 'end_state'
    lookup_table = { SYMBOL_0: ACCEPTING_STATE }.setdefault
    for num in range(number * base):
        end_state = str(num % number)
        num_s = baseN(num, base)
        before_end_state = lookup_table(num_s[:-1], START_STATE)
        dfa[before_end_state][num_s[-1]] = end_state
        lookup_table(num_s, end_state)
    return dfa

def symcolrhexcodes(symbols):
    """
    returns dict of color codes mapped with alphabets symbol in symbols
    """
    return {
        symbol: '#'+''.join([
            rchoice("8A6C2B590D1F4E37") for _ in "FFFFFF"
        ])
        for symbol in symbols
    }

def draw_transition_graph(dfa, filename="filename"):
    ACCEPTING_STATE = START_STATE = '0'
    colors = symcolrhexcodes(dfa[START_STATE].keys())
    # draw transition graph
    tg = pgv.AGraph(strict=False, directed=True, decorate=True)
    for from_state in dfa:
        for symbol, to_state in dfa[from_state].iteritems():
            tg.add_edge("Q%s"%from_state, "Q%s"%to_state,
                        label=symbol, color=colors[symbol],
                        fontcolor=colors[symbol])

    # add intial edge from an invisible node!
    tg.add_node('null', shape='plaintext', label='start')
    tg.add_edge('null', "Q%s"%START_STATE,)

    # make end acception state as 'doublecircle'
    tg.get_node("Q%s"%ACCEPTING_STATE).attr['shape'] = 'doublecircle'
    tg.draw(filename, prog='circo')
    tg.close()

def print_transition_table(dfa):
    print("DFA accepting number string in base '%(base)s' "
            "those are divisible by '%(number)s':" % {
                'base': len(dfa['0']),
                'number': len(dfa),})
    pprint(dfa)

if __name__ == "__main__":
    number = input ("Enter NUMBER: ")
    base = input ("Enter BASE of number system: ")
    dfa = divided_by_N(number, base)

    print_transition_table(dfa)
    draw_transition_graph(dfa)

Execute it:

~/study/divide-5/script$ python script.py 
Enter NUMBER: 5
Enter BASE of number system: 4
DFA accepting number string in base '4' those are divisible by '5':
{'0': {'0': '0', '1': '1', '2': '2', '3': '3'},
 '1': {'0': '4', '1': '0', '2': '1', '3': '2'},
 '2': {'0': '3', '1': '4', '2': '0', '3': '1'},
 '3': {'0': '2', '1': '3', '2': '4', '3': '0'},
 '4': {'0': '1', '1': '2', '2': '3', '3': '4'}}
~/study/divide-5/script$ ls
script.py filename.png
~/study/divide-5/script$ display filename

Output:

base_4_divided_5_best
DFA accepting number strings in base 4 those are divisible by 5

Similarly, enter base = 4 and number = 7 to generate - dfa accepting number string in base '4' those are divisible by '7'
Btw, try changing filename to .png or .jpeg.

References those I use to write this script:
➊ Function baseN from "convert integer to a string in a given numeric base in python"
➋ To install "pygraphviz": "Python does not see pygraphviz"
➌ To learn use of Pygraphviz: "Python-FSM"
➍ To generate random hex color codes for each language symbol: "How would I make a random hexdigit code generator using .join and for loops?"

$.browser is undefined error

The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.

How do I convert Long to byte[] and back in java

If you are already using an OutputStream to write to the socket, then DataOutputStream might be a good fit. Here is an example:

// Assumes you are currently working with a SocketOutputStream.

SocketOutputStream outputStream = ...
long longValue = ...

DataOutputStream dataOutputStream = new DataOutputStream(outputStream);

dataOutputStream.writeLong(longValue);
dataOutputStream.flush();

There are similar methods for short, int, float, etc. You can then use DataInputStream on the receiving side.

PHP-FPM doesn't write to error log

I had a similar issue and had to do the following to the pool.d/www.conf file

php_admin_value[error_log] = /var/log/fpm-php.www.log
php_admin_flag[log_errors] = on

It still wasn't writing the log file so I actually had to create it by touch /var/log/fpm-php.www.log then setting the correct owner sudo chown www-data:www-data /var/log/fpm-php.www.log.

Once this was done, and php5-fpm restarted, logging was resumed.

Letsencrypt add domain to existing certificate

this worked for me

 sudo letsencrypt certonly -a webroot --webroot-path=/var/www/html -d
 domain.com -d www.domain.com

PHP Pass by reference in foreach

Because if you create a reference to a variable, all names for that variable (including the original) BECOME REFERENCES.

Switch statement with returns -- code correctness

I'd normally write the code without them. IMO, dead code tends to indicate sloppiness and/or lack of understanding.

Of course, I'd also consider something like:

char const *rets[] = {"blah", "foo", "bar"};

return rets[something];

Edit: even with the edited post, this general idea can work fine:

char const *rets[] = { "blah", "foo", "bar", "bar", "foo"};

if ((unsigned)something < 5)
    return rets[something]
return "foobar";

At some point, especially if the input values are sparse (e.g., 1, 100, 1000 and 10000), you want a sparse array instead. You can implement that as either a tree or a map reasonably well (though, of course, a switch still works in this case as well).

Are static methods inherited in Java?

Static members are universal members. They can be accessed from anywhere.

TypeError: module.__init__() takes at most 2 arguments (3 given)

from Object import Object

or

From Class_Name import Class_name

If Object is a .py file.

Oracle DB : java.sql.SQLException: Closed Connection

You have to validate the connection.

If you use Oracle it is likely that you use Oracle´s Universal Connection Pool. The following assumes that you do so.

The easiest way to validate the connection is to tell Oracle that the connection must be validated while borrowing it. This can be done with

pool.setValidateConnectionOnBorrow(true);

But it works only if you hold the connection for a short period. If you borrow the connection for a longer time, it is likely that the connection gets broken while you hold it. In that case you have to validate the connection explicitly with

if (connection == null || !((ValidConnection) connection).isValid())

See the Oracle documentation for further details.

Why do people write #!/usr/bin/env python on the first line of a Python script?

Perhaps your question is in this sense:

If you want to use: $python myscript.py

You don't need that line at all. The system will call python and then python interpreter will run your script.

But if you intend to use: $./myscript.py

Calling it directly like a normal program or bash script, you need write that line to specify to the system which program use to run it, (and also make it executable with chmod 755)

How to read from stdin line by line in Node

if you want to ask the user number of lines first:

_x000D_
_x000D_
    //array to save line by line 
    let xInputs = [];

    const getInput = async (resolve)=>{
            const readline = require('readline').createInterface({
                input: process.stdin,
                output: process.stdout,
            });
            readline.on('line',(line)=>{
            readline.close();
            xInputs.push(line);
            resolve(line);
            })
    }

    const getMultiInput = (numberOfInputLines,callback)=>{
        let i = 0;
        let p = Promise.resolve(); 
        for (; i < numberOfInputLines; i++) {
            p = p.then(_ => new Promise(resolve => getInput(resolve)));
        }
        p.then(()=>{
            callback();
        });
    }

    //get number of lines 
    const readline = require('readline').createInterface({
        input: process.stdin,
        output: process.stdout,
        terminal: false
    });
    readline.on('line',(line)=>{
        getMultiInput(line,()=>{
           //get here the inputs from xinputs array 
        });
        readline.close();
    })
_x000D_
_x000D_
_x000D_

Border Radius of Table is not working

border-collapse: separate !important; worked.

Thanks.

HTML

<table class="bordered">
    <thead>
        <tr>
            <th><label>Labels</label></th>
            <th><label>Labels</label></th>
            <th><label>Labels</label></th>
            <th><label>Labels</label></th>
            <th><label>Labels</label></th>
        </tr>
    </thead>

    <tbody>
        <tr>
            <td><label>Value</label></td>
            <td><label>Value</label></td>
            <td><label>Value</label></td>
            <td><label>Value</label></td>
            <td><label>Value</label></td>                            
        </tr>
    </tbody>                    
</table>

CSS

table {
    border-collapse: separate !important;
    border-spacing: 0;
    width: 600px;
    margin: 30px;
}
.bordered {
    border: solid #ccc 1px;
    -moz-border-radius: 6px;
    -webkit-border-radius: 6px;
    border-radius: 6px;
    -webkit-box-shadow: 0 1px 1px #ccc;
    -moz-box-shadow: 0 1px 1px #ccc;
    box-shadow: 0 1px 1px #ccc;
}
.bordered tr:hover {
    background: #ECECEC;    
    -webkit-transition: all 0.1s ease-in-out;
    -moz-transition: all 0.1s ease-in-out;
    transition: all 0.1s ease-in-out;
}
.bordered td, .bordered th {
    border-left: 1px solid #ccc;
    border-top: 1px solid #ccc;
    padding: 10px;
    text-align: left;
}
.bordered th {
    background-color: #ECECEC;
    background-image: -webkit-gradient(linear, left top, left bottom, from(#F8F8F8), to(#ECECEC));
    background-image: -webkit-linear-gradient(top, #F8F8F8, #ECECEC);
    background-image: -moz-linear-gradient(top, #F8F8F8, #ECECEC);    
    background-image: linear-gradient(top, #F8F8F8, #ECECEC);
    -webkit-box-shadow: 0 1px 0 rgba(255,255,255,.8) inset;
    -moz-box-shadow:0 1px 0 rgba(255,255,255,.8) inset;
    box-shadow: 0 1px 0 rgba(255,255,255,.8) inset;
    border-top: none;
    text-shadow: 0 1px 0 rgba(255,255,255,.5);
}
.bordered td:first-child, .bordered th:first-child {
    border-left: none;
}
.bordered th:first-child {
    -moz-border-radius: 6px 0 0 0;
    -webkit-border-radius: 6px 0 0 0;
    border-radius: 6px 0 0 0;
}
.bordered th:last-child {
    -moz-border-radius: 0 6px 0 0;
    -webkit-border-radius: 0 6px 0 0;
    border-radius: 0 6px 0 0;
}
.bordered th:only-child{
    -moz-border-radius: 6px 6px 0 0;
    -webkit-border-radius: 6px 6px 0 0;
    border-radius: 6px 6px 0 0;
}
.bordered tr:last-child td:first-child {
    -moz-border-radius: 0 0 0 6px;
    -webkit-border-radius: 0 0 0 6px;
    border-radius: 0 0 0 6px;
}
.bordered tr:last-child td:last-child {
    -moz-border-radius: 0 0 6px 0;
    -webkit-border-radius: 0 0 6px 0;
    border-radius: 0 0 6px 0;
} 

jsFiddle

Changing the Git remote 'push to' default

You can easily change default remote for branches all at once simple using this command

git push -u <remote_name> --all

How to append elements at the end of ArrayList in Java?

I ran into a similar problem and just passed the end of the array to the ArrayList.add() index param like so:

public class Stack {

    private ArrayList<String> stringList = new ArrayList<String>();

    RandomStringGenerator rsg = new RandomStringGenerator();

    private void push(){
        String random = rsg.randomStringGenerator();
        stringList.add(stringList.size(), random);
    }

}

Is it possible to write data to file using only JavaScript?

If you are talking about browser javascript, you can not write data directly to local file for security reason. HTML 5 new API can only allow you to read files.

But if you want to write data, and enable user to download as a file to local. the following code works:

    function download(strData, strFileName, strMimeType) {
    var D = document,
        A = arguments,
        a = D.createElement("a"),
        d = A[0],
        n = A[1],
        t = A[2] || "text/plain";

    //build download link:
    a.href = "data:" + strMimeType + "charset=utf-8," + escape(strData);


    if (window.MSBlobBuilder) { // IE10
        var bb = new MSBlobBuilder();
        bb.append(strData);
        return navigator.msSaveBlob(bb, strFileName);
    } /* end if(window.MSBlobBuilder) */



    if ('download' in a) { //FF20, CH19
        a.setAttribute("download", n);
        a.innerHTML = "downloading...";
        D.body.appendChild(a);
        setTimeout(function() {
            var e = D.createEvent("MouseEvents");
            e.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            a.dispatchEvent(e);
            D.body.removeChild(a);
        }, 66);
        return true;
    }; /* end if('download' in a) */



    //do iframe dataURL download: (older W3)
    var f = D.createElement("iframe");
    D.body.appendChild(f);
    f.src = "data:" + (A[2] ? A[2] : "application/octet-stream") + (window.btoa ? ";base64" : "") + "," + (window.btoa ? window.btoa : escape)(strData);
    setTimeout(function() {
        D.body.removeChild(f);
    }, 333);
    return true;
}

to use it:

download('the content of the file', 'filename.txt', 'text/plain');

How to generate Class Diagram (UML) on Android Studio (IntelliJ Idea)

For those who want to use simpleUML in Android Studio and having issues in running SimpleUML.

First download simpleUML jar from here https://plugins.jetbrains.com/plugin/4946-simpleumlce

Now follow the below steps.

Step 1:

Click on File and go to Settings (File ? Settings)

Step 2

Select Plugins from Left Panel and click Install plugin from disk


1]

Step 3:

Locate the SimpleUML jar file and select it.

2]

Step 4:

Now Restart Android Studio (File ? Invalidate Caches/Restart ? Just Restart)

Step 5:

After you restart Right Click the Package name and Select New Diagram or Add to simpleUML Diagram ? New Diagram.

3

Step 6:

Set a file name and create UML file. I created with name NewDiagram

enter image description here Step 7:

Now Right Click the Package name and Select the file you created. In my case it was NewDiagram

enter image description here

Step 8:

All files are stacked on top of one another. You can just drag and drop them and set a hierarchy.

enter image description here

Like this below, you can drag these classes

enter image description here

PHP Warning: Division by zero

A lot of the answers here do not work for (string)"0.00".

Try this:

if (isset($_POST['num1']) && (float)$_POST['num1'] != 0) {
  ...
}

Or even more strict:

if (isset($_POST['num1']) && is_numeric($_POST['num1']) && (float)$_POST['num1'] != 0) {
  ...
}

Delayed function calls

Building upon the answer from David O'Donoghue here is an optimized version of the Delayed Delegate:

using System.Windows.Forms;
using System.Collections.Generic;
using System;

namespace MyTool
{
    public class DelayedDelegate
    {
       static private DelayedDelegate _instance = null;

        private Timer _runDelegates = null;

        private Dictionary<MethodInvoker, DateTime> _delayedDelegates = new Dictionary<MethodInvoker, DateTime>();

        public DelayedDelegate()
        {
        }

        static private DelayedDelegate Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new DelayedDelegate();
                }

                return _instance;
            }
        }

        public static void Add(MethodInvoker pMethod, int pDelay)
        {
            Instance.AddNewDelegate(pMethod, pDelay * 1000);
        }

        public static void AddMilliseconds(MethodInvoker pMethod, int pDelay)
        {
            Instance.AddNewDelegate(pMethod, pDelay);
        }

        private void AddNewDelegate(MethodInvoker pMethod, int pDelay)
        {
            if (_runDelegates == null)
            {
                _runDelegates = new Timer();
                _runDelegates.Tick += RunDelegates;
            }
            else
            {
                _runDelegates.Stop();
            }

            _delayedDelegates.Add(pMethod, DateTime.Now + TimeSpan.FromMilliseconds(pDelay));

            StartTimer();
        }

        private void StartTimer()
        {
            if (_delayedDelegates.Count > 0)
            {
                int delay = FindSoonestDelay();
                if (delay == 0)
                {
                    RunDelegates();
                }
                else
                {
                    _runDelegates.Interval = delay;
                    _runDelegates.Start();
                }
            }
        }

        private int FindSoonestDelay()
        {
            int soonest = int.MaxValue;
            TimeSpan remaining;

            foreach (MethodInvoker invoker in _delayedDelegates.Keys)
            {
                remaining = _delayedDelegates[invoker] - DateTime.Now;
                soonest = Math.Max(0, Math.Min(soonest, (int)remaining.TotalMilliseconds));
            }

            return soonest;
        }

        private void RunDelegates(object pSender = null, EventArgs pE = null)
        {
            try
            {
                _runDelegates.Stop();

                List<MethodInvoker> removeDelegates = new List<MethodInvoker>();

                foreach (MethodInvoker method in _delayedDelegates.Keys)
                {
                    if (DateTime.Now >= _delayedDelegates[method])
                    {
                        method();

                        removeDelegates.Add(method);
                    }
                }

                foreach (MethodInvoker method in removeDelegates)
                {
                    _delayedDelegates.Remove(method);
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                StartTimer();
            }
        }
    }
}

The class could be slightly more improved by using a unique key for the delegates. Because if you add the same delegate a second time before the first one fired, you might get a problem with the dictionary.

What is <=> (the 'Spaceship' Operator) in PHP 7?

According to the RFC that introduced the operator, $a <=> $b evaluates to:

  • 0 if $a == $b
  • -1 if $a < $b
  • 1 if $a > $b

which seems to be the case in practice in every scenario I've tried, although strictly the official docs only offer the slightly weaker guarantee that $a <=> $b will return

an integer less than, equal to, or greater than zero when $a is respectively less than, equal to, or greater than $b

Regardless, why would you want such an operator? Again, the RFC addresses this - it's pretty much entirely to make it more convenient to write comparison functions for usort (and the similar uasort and uksort).

usort takes an array to sort as its first argument, and a user-defined comparison function as its second argument. It uses that comparison function to determine which of a pair of elements from the array is greater. The comparison function needs to return:

an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

The spaceship operator makes this succinct and convenient:

$things = [
    [
        'foo' => 5.5,
        'bar' => 'abc'
    ],
    [
        'foo' => 7.7,
        'bar' => 'xyz'
    ],
    [
        'foo' => 2.2,
        'bar' => 'efg'
    ]
];

// Sort $things by 'foo' property, ascending
usort($things, function ($a, $b) {
    return $a['foo'] <=> $b['foo'];
});

// Sort $things by 'bar' property, descending
usort($things, function ($a, $b) {
    return $b['bar'] <=> $a['bar'];
});

More examples of comparison functions written using the spaceship operator can be found in the Usefulness section of the RFC.

What Content-Type value should I send for my XML sitemap?

both are fine.

text/xxx means that in case the program does not understand xxx it makes sense to show the file to the user as plain text. application/xxx means that it is pointless to show it.

Please note that those content-types were originally defined for E-Mail attachment before they got later used in Web world.

Push to GitHub without a password using ssh-key

As usual, create an SSH key and paste the public key to GitHub. Add the private key to ssh-agent. (I assume this is what you have done.)

To check everything is correct, use ssh -T [email protected]

Next, don't forget to modify the remote point as follows:

git remote set-url origin [email protected]:username/your-repository.git

perform an action on checkbox checked or unchecked event on html form

The problem is how you've attached the listener:

<input type="checkbox" ...  onchange="doalert(this.id)">

Inline listeners are effectively wrapped in a function which is called with the element as this. That function then calls the doalert function, but doesn't set its this so it will default to the global object (window in a browser).

Since the window object doesn't have a checked property, this.checked always resolves to false.

If you want this within doalert to be the element, attach the listener using addEventListener:

window.onload = function() {
  var input = document.querySelector('#g01-01');
  if (input) {   
    input.addEventListener('change', doalert, false);
  }
}

Or if you wish to use an inline listener:

<input type="checkbox" ...  onchange="doalert.call(this, this.id)">

Is div inside list allowed?

If you look at xhtml1-strict.dtd, you'll see

<!ELEMENT li %Flow;>
<!ENTITY % Flow "(#PCDATA | %block; | form | %inline; | %misc;)*">
<!ENTITY % block
     "p | %heading; | div | %lists; | %blocktext; | fieldset | table">

Thus div, p etc. can be inside li (according to XHTML 1.0 Strict DTD from w3.org).

How to remove element from an array in JavaScript?

Typescript solution that does not mutate original array

function removeElementAtIndex<T>(input: T[], index: number) {
  return input.slice(0, index).concat(input.slice(index + 1));
}

Relative imports in Python 3

I had a similar problem and solved it by creating a symbolic link to the package in the working directory:

ln -s ../../../my_package my_package

and then import it as usual:

import my_package

I know this is more like a "Linux" solution rather than a "Python" solution. but it's a valid approach nonetheless.

How to automatically crop and center an image

Try this:

#yourElementId
{
    background: url(yourImageLocation.jpg) no-repeat center center;
    width: 100px;
    height: 100px;
}

Keep in mind that width and height will only work if your DOM element has layout (a block displayed element, like a div or an img). If it is not (a span, for example), add display: block; to the CSS rules. If you do not have access to the CSS files, drop the styles inline in the element.

sys.argv[1] meaning in script

Just adding to Frederic's answer, for example if you call your script as follows:

./myscript.py foo bar

sys.argv[0] would be "./myscript.py" sys.argv[1] would be "foo" and sys.argv[2] would be "bar" ... and so forth.

In your example code, if you call the script as follows ./myscript.py foo , the script's output will be "Hello there foo".

define a List like List<int,string>?

List<Tuple<string, DateTime, string>> mylist = new List<Tuple<string, DateTime,string>>();
mylist.Add(new Tuple<string, DateTime, string>(Datei_Info.Dateiname, Datei_Info.Datum, Datei_Info.Größe));
for (int i = 0; i < mylist.Count; i++)
{
     Console.WriteLine(mylist[i]);
}

Convert date from 'Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)' to 'YYYY-MM-DD' in javascript

The easiest way for me to convert a date was to stringify it then slice it.

var event = new Date("Fri Apr 05 2019 16:59:00 GMT-0700 (Pacific Daylight Time)");

let date = JSON.stringify(event)
date = date.slice(1,11)

// console.log(date) = '2019-04-05'

How to run different python versions in cmd

I also met the case to use both python2 and python3 on my Windows machine. Here's how i resolved it:

  1. download python2x and python3x, installed them.
  2. add C:\Python35;C:\Python35\Scripts;C:\Python27;C:\Python27\Scripts to environment variable PATH.
  3. Go to C:\Python35 to rename python.exe to python3.exe, also to C:\Python27, rename python.exe to python2.exe.
  4. restart your command window.
  5. type python2 scriptname.py, or python3 scriptname.py in command line to switch the version you like.

Export table from database to csv file

You can also use following Node.js module to do it with ease:

https://www.npmjs.com/package/mssql-to-csv

var mssqlExport = require('mssql-to-csv')

    // All config options supported by https://www.npmjs.com/package/mssql 
    var dbconfig = {
        user: 'username',
        password: 'pass',
        server: 'servername',
        database: 'dbname',
        requestTimeout: 320000,
        pool: {
            max: 20,
            min: 12,
            idleTimeoutMillis: 30000
        }
    };

    var options = {
        ignoreList: ["sysdiagrams"], // tables to ignore 
        tables: [],                  // empty to export all the tables 
        outputDirectory: 'somedir',
        log: true
    };

    mssqlExport(dbconfig, options).then(function(){
        console.log("All done successfully!");
        process.exit(0);
    }).catch(function(err){
        console.log(err.toString());
        process.exit(-1);
   });

How do I know if jQuery has an Ajax request pending?

The $.ajax() function returns a XMLHttpRequest object. Store that in a variable that's accessible from the Submit button's "OnClick" event. When a submit click is processed check to see if the XMLHttpRequest variable is:

1) null, meaning that no request has been sent yet

2) that the readyState value is 4 (Loaded). This means that the request has been sent and returned successfully.

In either of those cases, return true and allow the submit to continue. Otherwise return false to block the submit and give the user some indication of why their submit didn't work. :)

Failed to start mongod.service: Unit mongod.service not found

Please follow the below steps, it should work.

1 - Uninstall current installation completely

Source - official instructions

sudo service mongod stop

Remove Packages

sudo apt-get purge mongodb-org*

Remove the folders

sudo rm -r /var/log/mongodb
sudo rm -r /var/lib/mongodb

2 - Reinstall as described on official site, I will just write down the all steps. enter link description here

Import the public key

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5

Create a list file for Ubuntu 16.04

echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list

update the list

sudo apt-get update

Install the latest package

sudo apt-get install -y mongodb-org

3 - Now it should work, please try below command

sudo service mongod start

and check the status

mongo

it should appear the mongo shell

SOAP vs REST (differences)

REST vs SOAP is not the right question to ask.

REST, unlike SOAP is not a protocol.

REST is an architectural style and a design for network-based software architectures.

REST concepts are referred to as resources. A representation of a resource must be stateless. It is represented via some media type. Some examples of media types include XML, JSON, and RDF. Resources are manipulated by components. Components request and manipulate resources via a standard uniform interface. In the case of HTTP, this interface consists of standard HTTP ops e.g. GET, PUT, POST, DELETE.

@Abdulaziz's question does illuminate the fact that REST and HTTP are often used in tandem. This is primarily due to the simplicity of HTTP and its very natural mapping to RESTful principles.

Fundamental REST Principles

Client-Server Communication

Client-server architectures have a very distinct separation of concerns. All applications built in the RESTful style must also be client-server in principle.

Stateless

Each client request to the server requires that its state be fully represented. The server must be able to completely understand the client request without using any server context or server session state. It follows that all state must be kept on the client.

Cacheable

Cache constraints may be used, thus enabling response data to be marked as cacheable or not-cacheable. Any data marked as cacheable may be reused as the response to the same subsequent request.

Uniform Interface

All components must interact through a single uniform interface. Because all component interaction occurs via this interface, interaction with different services is very simple. The interface is the same! This also means that implementation changes can be made in isolation. Such changes, will not affect fundamental component interaction because the uniform interface is always unchanged. One disadvantage is that you are stuck with the interface. If an optimization could be provided to a specific service by changing the interface, you are out of luck as REST prohibits this. On the bright side, however, REST is optimized for the web, hence incredible popularity of REST over HTTP!

The above concepts represent defining characteristics of REST and differentiate the REST architecture from other architectures like web services. It is useful to note that a REST service is a web service, but a web service is not necessarily a REST service.

See this blog post on REST Design Principles for more details on REST and the above stated bullets.

EDIT: update content based on comments

How to exclude records with certain values in sql select

SELECT SC.StoreId 
FROM StoreClients SC
WHERE SC.StoreId NOT IN (SELECT StoreId FROM StoreClients WHERE ClientId = 5)

In this way neither JOIN nor GROUP BY is necessary.

ListView item background via custom selector

I'm not sure how to achieve your desired effect through the selector itself -- after all, by definition, there is one selector for the whole list.

However, you can get control on selection changes and draw whatever you want. In this sample project, I make the selector transparent and draw a bar on the selected item.

Scatter plot with error bars

#some example data
set.seed(42)
df <- data.frame(x = rep(1:10,each=5), y = rnorm(50))

#calculate mean, min and max for each x-value
library(plyr)
df2 <- ddply(df,.(x),function(df) c(mean=mean(df$y),min=min(df$y),max=max(df$y)))

#plot error bars
library(Hmisc)
with(df2,errbar(x,mean,max,min))
grid(nx=NA,ny=NULL)

Error occurred during initialization of VM (java/lang/NoClassDefFoundError: java/lang/Object)

I had the same error in my case was when I needed to update jdk 7 to jdk 8, and my bad was just I installed jdk8 and I never installed jre8, only that, the error was solved immediately when I installed jre8.

Using :before and :after CSS selector to insert Html

content doesn't support HTML, only text. You should probably use javascript, jQuery or something like that.

Another problem with your code is " inside a " block. You should mix ' and " (class='headingDetail').

If content did support HTML you could end up in an infinite loop where content is added inside content.

PHP Foreach Arrays and objects

Use

//$arr should be array as you mentioned as below
foreach($arr as $key=>$value){
  echo $value->sm_id;
}

OR

//$arr should be array as you mentioned as below
foreach($arr as $value){
  echo $value->sm_id;
}

How to convert integer to string in C?

Use sprintf():

int someInt = 368;
char str[12];
sprintf(str, "%d", someInt);

All numbers that are representable by int will fit in a 12-char-array without overflow, unless your compiler is somehow using more than 32-bits for int. When using numbers with greater bitsize, e.g. long with most 64-bit compilers, you need to increase the array size—at least 21 characters for 64-bit types.

How do I get the path and name of the file that is currently executing?

Simplest way is:

in script_1.py:

import subprocess
subprocess.call(['python3',<path_to_script_2.py>])

in script_2.py:

sys.argv[0]

P.S.: I've tried execfile, but since it reads script_2.py as a string, sys.argv[0] returned <string>.

How to fix the error "Windows SDK version 8.1" was not found?

I encountered this issue while trying to build an npm project. It was failing to install a node-sass package and this was the error it was printing. I solved it by setting my npm proxy correctly so that i

Returning Month Name in SQL Server Query

basically this ...

declare @currentdate datetime = getdate()
select left(datename(month,DATEADD(MONTH, -1, GETDATE())),3)
union all
select left(datename(month,(DATEADD(MONTH, -2, GETDATE()))),3)
union all
select left(datename(month,(DATEADD(MONTH, -3, GETDATE()))),3)

Colon (:) in Python list index

a[len(a):] - This gets you the length of a to the end. It selects a range. If you reverse a[:len(a)] it will get you the beginning to whatever is len(a).

How do I force a DIV block to extend to the bottom of a page even if it has no content?

Try playing around with the following css rule:

#content {
    min-height: 600px;
    height: auto !important;
    height: 600px;
}

Change the height to suit your page. height is mentioned twice for cross browser compatibility.

How to pass a value to razor variable from javascript variable?

You can't. and the reason is that they do not "live" in the same time. The Razor variables are "Server side variables" and they don't exist anymore after the page was sent to the "Client side".

When the server get a request for a view, it creates the view with only HTML, CSS and Javascript code. No C# code is left, it's all get "translated" to the client side languages.

The Javascript code DOES exist when the view is still on the server, but it's meaningless and will be executed by the browser only (Client side again).

This is why you can use Razor variables to change the HTML and Javascript but not vice versa. Try to look at your page source code (CTRL+U in most browsers), there will be no sign of C# code there.

In short:

  1. The server gets a request.

  2. The server creates or "takes" the view, then computes and translates all the C# code that was embedded in the view to CSS, Javascript, and HTML.

  3. The server returns the client side version of the view to the browser as a response to the request. (there is no C# at this point anymore)

  4. the browser renders the page and executes all the Javascript

Go / golang time.Now().UnixNano() convert to milliseconds?

I think it's better to round the time to milliseconds before the division.

func makeTimestamp() int64 {
    return time.Now().Round(time.Millisecond).UnixNano() / (int64(time.Millisecond)/int64(time.Nanosecond))
}

Here is an example program:

package main

import (
        "fmt"
        "time"
)

func main() {
        fmt.Println(unixMilli(time.Unix(0, 123400000)))
        fmt.Println(unixMilli(time.Unix(0, 123500000)))
        m := makeTimestampMilli()
        fmt.Println(m)
        fmt.Println(time.Unix(m/1e3, (m%1e3)*int64(time.Millisecond)/int64(time.Nanosecond)))
}

func unixMilli(t time.Time) int64 {
        return t.Round(time.Millisecond).UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond))
}

func makeTimestampMilli() int64 {
        return unixMilli(time.Now())
}

The above program printed the result below on my machine:

123
124
1472313624305
2016-08-28 01:00:24.305 +0900 JST

T-SQL: Looping through an array of known values

use a static cursor variable and a split function:

declare @comma_delimited_list varchar(4000)
set @comma_delimited_list = '4,7,12,22,19'

declare @cursor cursor
set @cursor = cursor static for 
  select convert(int, Value) as Id from dbo.Split(@comma_delimited_list) a

declare @id int
open @cursor
while 1=1 begin
  fetch next from @cursor into @id
  if @@fetch_status <> 0 break
  ....do something....
end
-- not strictly necessary w/ cursor variables since they will go out of scope like a normal var
close @cursor
deallocate @cursor

Cursors have a bad rep since the default options when declared against user tables can generate a lot of overhead.

But in this case the overhead is quite minimal, less than any other methods here. STATIC tells SQL Server to materialize the results in tempdb and then iterate over that. For small lists like this, it's the optimal solution.

Using XPATH to search text containing &nbsp;

Bear in mind that a standards-compliant XML processor will have replaced any entity references other than XML's five standard ones (&amp;, &gt;, &lt;, &apos;, &quot;) with the corresponding character in the target encoding by the time XPath expressions are evaluated. Given that behavior, PhiLho's and jsulak's suggestions are the way to go if you want to work with XML tools. When you enter &#160; in the XPath expression, it should be converted to the corresponding byte sequence before the XPath expression is applied.

whitespaces in the path of windows filepath

Try putting double quotes in your filepath variable

"\"E:/ABC/SEM 2/testfiles/all.txt\""

Check the permissions of the file or in any case consider renaming the folder to remove the space

Executing JavaScript without a browser?

Well there is JavaScript as OSA, an extension that provides JavaScript as an alternative to appleScript. I've been using that about 10 years ago, don't know if it's still working with current OS versions

Vue.js - How to properly watch for nested data

Tracking individual changed items in a list

If you want to watch all items in a list and know which item in the list changed, you can set up custom watchers on every item separately, like so:

var vm = new Vue({
  data: {
    list: [
      {name: 'obj1 to watch'},
      {name: 'obj2 to watch'},
    ],
  },
  methods: {
    handleChange (newVal, oldVal) {
      // Handle changes here!
      // NOTE: For mutated objects, newVal and oldVal will be identical.
      console.log(newVal);
    },
  },
  created () {
    this.list.forEach((val) => {
      this.$watch(() => val, this.handleChange, {deep: true});
    });
  },
});

If your list isn't populated straight away (like in the original question), you can move the logic out of created to wherever needed, e.g. inside the .then() block.

Watching a changing list

If your list itself updates to have new or removed items, I've developed a useful pattern that "shallow" watches the list itself, and dynamically watches/unwatches items as the list changes:

// NOTE: This example uses Lodash (_.differenceBy and _.pull) to compare lists
//       and remove list items. The same result could be achieved with lots of
//       list.indexOf(...) if you need to avoid external libraries.

var vm = new Vue({
  data: {
    list: [
      {name: 'obj1 to watch'},
      {name: 'obj2 to watch'},
    ],
    watchTracker: [],
  },
  methods: {
    handleChange (newVal, oldVal) {
      // Handle changes here!
      console.log(newVal);
    },
    updateWatchers () {
      // Helper function for comparing list items to the "watchTracker".
      const getItem = (val) => val.item || val;

      // Items that aren't already watched: watch and add to watched list.
      _.differenceBy(this.list, this.watchTracker, getItem).forEach((item) => {
        const unwatch = this.$watch(() => item, this.handleChange, {deep: true});
        this.watchTracker.push({ item: item, unwatch: unwatch });
        // Uncomment below if adding a new item to the list should count as a "change".
        // this.handleChange(item);
      });

      // Items that no longer exist: unwatch and remove from the watched list.
      _.differenceBy(this.watchTracker, this.list, getItem).forEach((watchObj) => {
        watchObj.unwatch();
        _.pull(this.watchTracker, watchObj);
        // Optionally add any further cleanup in here for when items are removed.
      });
    },
  },
  watch: {
    list () {
      return this.updateWatchers();
    },
  },
  created () {
    return this.updateWatchers();
  },
});

How can you undo the last git add?

So the real answer to

Can this programmer now unstage his last changes with some magical git command?

is actually: No, you cannot unstage just the last git add.

That is if we interpret the question as in the following situation:

Initial file:

void foo() {

}

main() {
    foo();
}

First change followed by git add:

void foo(int bar) {
    print("$bar");
}

main() {
    foo(1337);
}

Second change followed by git add:

void foo(int bar, String baz) {
    print("$bar $baz");
}

main() {
    foo(1337, "h4x0r");
}

In this case, git reset -p will not help, since its smallest granularity is lines. git doesn't know that about the intermediate state of:

void foo(int bar) {
    print("$bar");
}

main() {
    foo(1337);
}

any more.

How to create multiple class objects with a loop in python?

Using a dictionary for unique names without a name list:

class MyClass:
    def __init__(self, name):
        self.name = name
        self.pretty_print_name()

    def pretty_print_name(self):
    print("This object's name is {}.".format(self.name))

my_objects = {}
for i in range(1,11):
    name = 'obj_{}'.format(i)
    my_objects[name] = my_objects.get(name, MyClass(name = name))

Output:

"This object's name is obj_1."
"This object's name is obj_2."
"This object's name is obj_3."
"This object's name is obj_4."
"This object's name is obj_5."
"This object's name is obj_6."
"This object's name is obj_7."
"This object's name is obj_8."
"This object's name is obj_9."
"This object's name is obj_10."

How does Google reCAPTCHA v2 work behind the scenes?

This is speculation, but based on Google's reference to the "risk analysis engine" they use (http://googleonlinesecurity.blogspot.com/2014/12/are-you-robot-introducing-no-captcha.html)

I would assume it looks at how you behaved prior to clicking, how your cursor moved on its way to the check (organic path/acceleration), which part of the checkbox was clicked (random places, or dead on center every time), browser fingerprint, Google cookies & contents, click location history tied to your fingerprint or account if it detects one etc.

It's fairly difficult to fake "organic" behavior in such a way that it would fool a continuously learning pattern detection engine. In the cases where it's not sure, it still prompts you to match an actual CAPTCHA string.

Uploading an Excel sheet and importing the data into SQL Server database

 protected void btnUpload_Click(object sender, EventArgs e)
    {
          if (Page.IsValid)
            {
                bool logval = true;
                if (logval == true)
                {
                    String img_1 = fuUploadExcelName.PostedFile.FileName;
                    String img_2 = System.IO.Path.GetFileName(img_1);
                    string extn = System.IO.Path.GetExtension(img_1);

                    string frstfilenamepart = "";
                    frstfilenamepart = "Emp" + DateTime.Now.ToString("ddMMyyyyhhmmss"); ;
                    UploadExcelName.Value = frstfilenamepart + extn;
                    fuUploadExcelName.SaveAs(Server.MapPath("~/Emp/EmpExcel/") + "/" + UploadExcelName.Value);
                    string PathName = Server.MapPath("~/Emp/EmpExcel/") + "\\" + UploadExcelName.Value;
                    GetExcelSheetForEmp(PathName, UploadExcelName.Value);

                }
            }


    }

    private void GetExcelSheetForEmp(string PathName, string UploadExcelName)
    {
        string excelFile = "EmpExcel/" + PathName;
        OleDbConnection objConn = null;
        System.Data.DataTable dt = null;
        try
        {

            DataSet dss = new DataSet();
            String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + PathName;
            objConn = new OleDbConnection(connString);
            objConn.Open();
            dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            if (dt == null)
            {
                return;
            }
            String[] excelSheets = new String[dt.Rows.Count];
            int i = 0;
            foreach (DataRow row in dt.Rows)
            {
                if (i == 0)
                {
                    excelSheets[i] = row["TABLE_NAME"].ToString();
                    OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + excelSheets[i] + "]", objConn);
                    OleDbDataAdapter oleda = new OleDbDataAdapter();
                    oleda.SelectCommand = cmd;
                    oleda.Fill(dss, "TABLE");

                }
                i++;
            }
            grdByExcel.DataSource = dss.Tables[0].DefaultView;
            grdByExcel.DataBind();


        }

        catch (Exception ex)
        {
            ViewState["Fuletypeidlist"] = "0";
            grdByExcel.DataSource = null;
            grdByExcel.DataBind();
        }
        finally
        {
            if (objConn != null)
            {
                objConn.Close();
                objConn.Dispose();
            }
            if (dt != null)
            {
                dt.Dispose();
            }
        }

    }

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

ResourceDictionary in a separate assembly

An example, just to make this a 15 seconds answer -

Say you have "styles.xaml" in a WPF library named "common" and you want to use it from your main application project:

  1. Add a reference from the main project to "common" project
  2. Your app.xaml should contain:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="pack://application:,,,/Common;component/styles.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

Return rows in random order

Here's an example (source):

SET @randomId = Cast(((@maxValue + 1) - @minValue) * Rand() + @minValue AS tinyint);

Add button to a layout programmatically

If you just have included a layout file at the beginning of onCreate() inside setContentView and want to get this layout to add new elements programmatically try this:

ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);

then you can create a new Button for example and just add it:

Button bt = new Button(this);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 
                                    LayoutParams.WRAP_CONTENT));
linerLayout.addView(bt);

Can't use WAMP , port 80 is used by IIS 7.5

I had lot of problems with this error (Thanks to Microsoft -- Grrr!!)

Finally found the solution ..... I am sharing this solution

There are couple of ways to stop IIS 7.5

  • Best one is:

    Open a CMD prompt (as Admin) and type this:

    iisreset /stop Here is a snapshot:

    Image

  • Next option if you still cannot stop the IIS 7.5

    Try this video link.

  • Final option is to change the port number as the last option httpd.conf

PS: Don't forget to restart the WAMP once fixing the errors


You can also

Just disable and stop the World Wide Web Publishing Service (This shuts down IIS forever) - - -(You need to use Run from the starting point in windows):

sc config w3svc start= disabled
net stop w3svc

If you don't want it disabled, but manual instead, replace disabled by demand (don't remove space).

How to display a gif fullscreen for a webpage background?

You can set up a background with your GIF file and set the body this way:

body{
background-image:url('http://www.example.com/yourfile.gif');
background-position: center;
background-size: cover;
}

Change background image URL with your GIF. With background-position: center you can put the image to the center and with background-size: cover you set the picture to fit all the screen. You can also set background-size: contain if you want to fit the picture at 100% of the screen but without leaving any part of the picture without showing.

Here's more info about the property:

http://www.w3schools.com/cssref/css3_pr_background-size.asp

Hope it helps :)

Does bootstrap 4 have a built in horizontal divider?

For Bootstrap v4;

for a thin line;

<div class="divider"></div>

for a medium thick line;

<div class="divider py-1 bg-dark"></div>

for a thick line;

<div class="divider py-1 bg-dark"><hr></div>

How to get row count using ResultSet in Java?

Following two options worked for me:

1) A function that returns the number of rows in your ResultSet.

private int resultSetCount(ResultSet resultSet) throws SQLException{
    try{
        int i = 0;
        while (resultSet.next()) {
            i++;
        }
        return i;
    } catch (Exception e){
       System.out.println("Error getting row count");
       e.printStackTrace();
    }
    return 0;
}

2) Create a second SQL statement with the COUNT option.

Truncating long strings with CSS: feasible yet?

OK, Firefox 7 implemented text-overflow: ellipsis as well as text-overflow: "string". Final release is planned for 2011-09-27.

How can I split a text into sentences?

You can also use sentence tokenization function in NLTK:

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

sent_tokenize(sentence)

How to find the location of the Scheduled Tasks folder

Tasks are saved in filesystem AND registry

Tasks are stored in 3 locations: 1 file system location and 2 registry locations.

File system:

C:\Windows\System32\Tasks

Registry:

HKLM\Software\Microsoft\Windows NT\CurrentVersion\Schedule\Taskcache\Tasks
HKLM\Software\Microsoft\Windows NT\CurrentVersion\Schedule\Taskcache\Tree

So, you need to delete a corrupted task in these 3 locations.

What are the differences between stateless and stateful systems, and how do they impact parallelism?

A stateful server keeps state between connections. A stateless server does not.

So, when you send a request to a stateful server, it may create some kind of connection object that tracks what information you request. When you send another request, that request operates on the state from the previous request. So you can send a request to "open" something. And then you can send a request to "close" it later. In-between the two requests, that thing is "open" on the server.

When you send a request to a stateless server, it does not create any objects that track information regarding your requests. If you "open" something on the server, the server retains no information at all that you have something open. A "close" operation would make no sense, since there would be nothing to close.

HTTP and NFS are stateless protocols. Each request stands on its own.

Sometimes cookies are used to add some state to a stateless protocol. In HTTP (web pages), the server sends you a cookie and then the browser holds the state, only to send it back to the server on a subsequent request.

SMB is a stateful protocol. A client can open a file on the server, and the server may deny other clients access to that file until the client closes it.

Using the GET parameter of a URL in JavaScript

I made this variation of gnarf's solution, so the call and the result is similar to PHP:

function S_GET(id){
    var a = new RegExp(id+"=([^&#=]*)");
    return decodeURIComponent(a.exec(window.location.search)[1]);
}

But as being called in a function slows the process, its better to use as global:

window['var_name'] = decodeURIComponent( /var_in_get=([^&#=]*)/.exec(window.location.search)[1] );

UPDATE

As I'm still learning JS, I created a better answer in a more JS behaviour:

Url = {
    get get(){
        var vars= {};
        if(window.location.search.length!==0)
            window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value){
                key=decodeURIComponent(key);
                if(typeof vars[key]==="undefined") {vars[key]= decodeURIComponent(value);}
                else {vars[key]= [].concat(vars[key], decodeURIComponent(value));}
            });
        return vars;
    }
};

This allows to be called just using Url.get.

Example The url ?param1=param1Value&param2=param2Value can be called like:

Url.get.param1 //"param1Value"
Url.get.param2 //"param2Value"

here is a snipet:

_x000D_
_x000D_
// URL GET params_x000D_
url = "?a=2&a=3&b=2&a=4";_x000D_
_x000D_
Url = {_x000D_
    get get(){_x000D_
        var vars= {};_x000D_
        if(url.length!==0)_x000D_
            url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value){_x000D_
                key=decodeURIComponent(key);_x000D_
                if(typeof vars[key]==="undefined") {vars[key]= decodeURIComponent(value);}_x000D_
                else {vars[key]= [].concat(vars[key], decodeURIComponent(value));}_x000D_
            });_x000D_
        return vars;_x000D_
    }_x000D_
};_x000D_
_x000D_
document.querySelector('log').innerHTML = JSON.stringify(Url.get);
_x000D_
<log></log>
_x000D_
_x000D_
_x000D_

Difference between a theta join, equijoin and natural join

Natural is a subset of Equi which is a subset of Theta.

If I use the = sign on a theta join is it exactly the same as just using a natural join???

Not necessarily, but it would be an Equi. Natural means you are matching on all similarly named columns, Equi just means you are using '=' exclusively (and not 'less than', like, etc)

This is pure academia though, you could work with relational databases for years and never hear anyone use these terms.

How do you find the row count for all your tables in Postgres

I made a small variation to include all tables, also for non-public tables.

CREATE TYPE table_count AS (table_schema TEXT,table_name TEXT, num_rows INTEGER); 

CREATE OR REPLACE FUNCTION count_em_all () RETURNS SETOF table_count  AS '
DECLARE 
    the_count RECORD; 
    t_name RECORD; 
    r table_count%ROWTYPE; 

BEGIN
    FOR t_name IN 
        SELECT table_schema,table_name
        FROM information_schema.tables
        where table_schema !=''pg_catalog''
          and table_schema !=''information_schema''
        ORDER BY 1,2
        LOOP
            FOR the_count IN EXECUTE ''SELECT COUNT(*) AS "count" FROM '' || t_name.table_schema||''.''||t_name.table_name
            LOOP 
            END LOOP; 

            r.table_schema := t_name.table_schema;
            r.table_name := t_name.table_name; 
            r.num_rows := the_count.count; 
            RETURN NEXT r; 
        END LOOP; 
        RETURN; 
END;
' LANGUAGE plpgsql; 

use select count_em_all(); to call it.

Hope you find this usefull. Paul

add image to uitableview cell

Try this code:--

UIImageView *imv = [[UIImageView alloc]initWithFrame:CGRectMake(3,2, 20, 25)];
imv.image=[UIImage imageNamed:@"arrow2.png"];
[cell addSubview:imv];
[imv release];

Different names of JSON property during serialization and deserialization

You can write a serialize class to do that:

public class Symbol

{
     private String symbol;

     private String name;

     public String getSymbol() {
        return symbol;
    }
    public void setSymbol(String symbol) {
        this.symbol = symbol;
    }    
    public String getName() {
        return name;
    }    
    public void setName(String name) {
        this.name = name;
    }
}
public class SymbolJsonSerializer extends JsonSerializer<Symbol> {

    @Override
    public void serialize(Symbol symbol, JsonGenerator jgen, SerializerProvider serializers) throws IOException, JsonProcessingException {
        jgen.writeStartObject();

        jgen.writeStringField("symbol", symbol.getSymbol());
         //Changed name to full_name as the field name of Json string
        jgen.writeStringField("full_name", symbol.getName());
        jgen.writeEndObject(); 
    }
}

            ObjectMapper mapper = new ObjectMapper();

            SimpleModule module = new SimpleModule();
            module.addSerializer(Symbol.class, new SymbolJsonSerializer());
            mapper.registerModule(module); 

            //only convert non-null field, option...
            mapper.setSerializationInclusion(Include.NON_NULL); 

            String jsonString = mapper.writeValueAsString(symbolList);

close fxml window by code, javafx

  1. give your close button an fx:id, if you haven't yet: <Button fx:id="closeButton" onAction="#closeButtonAction">
  2. In your controller class:

    @FXML private javafx.scene.control.Button closeButton;
    
    @FXML
    private void closeButtonAction(){
        // get a handle to the stage
        Stage stage = (Stage) closeButton.getScene().getWindow();
        // do what you have to do
        stage.close();
    }
    

Return array from function

neater:

function BlockID() {
  return {
    "s":"Images/Block_01.png",
    "g":"Images/Block_02.png",
    "C":"Images/Block_03.png",
    "d":"Images/Block_04.png"
   }
}

or just

var images = {
  "s":"Images/Block_01.png",
  "g":"Images/Block_02.png",
  "C":"Images/Block_03.png",
  "d":"Images/Block_04.png"
}

Asynchronous file upload (AJAX file upload) using jsp and javascript

I don't believe AJAX can handle file uploads but this can be achieved with libraries that leverage flash. Another advantage of the flash implementation is the ability to do multiple files at once (like gmail).

SWFUpload is a good start : http://www.swfupload.org/documentation

jQuery and some of the other libraries have plugins that leverage SWFUpload. On my last project we used SWFUpload and Java without a problem.

Also helpful and worth looking into is Apache's FileUpload : http://commons.apache.org/fileupload/index.html

How to remove all subviews of a view in Swift?

EDIT: (thanks Jeremiah / Rollo)

By far the best way to do this in Swift for iOS is:

view.subviews.forEach({ $0.removeFromSuperview() }) // this gets things done
view.subviews.map({ $0.removeFromSuperview() }) // this returns modified array

^^ These features are fun!

let funTimes = ["Awesome","Crazy","WTF"]
extension String { 
    func readIt() {
        print(self)
    }
}

funTimes.forEach({ $0.readIt() })

//// END EDIT

Just do this:

for view in self.view.subviews {
    view.removeFromSuperview()
}

Or if you are looking for a specific class

for view:CustomViewClass! in self.view.subviews {
        if view.isKindOfClass(CustomViewClass) {
            view.doClassThing()
        }
    }

Alter and Assign Object Without Side Effects

You will have the same object two times in your array, because object values are passed by reference. You have to create a new object like this

myElement.id = 244;
myElement.value = 3556;
myArray[0] = $.extend({}, myElement); //for shallow copy or
myArray[0] = $.extend(true, {}, myElement); // for deep copy

or

myArray.push({ id: 24, value: 246 });

C# using streams

To expand a little on other answers here, and help explain a lot of the example code you'll see dotted about, most of the time you don't read and write to a stream directly. Streams are a low-level means to transfer data.

You'll notice that the functions for reading and writing are all byte orientated, e.g. WriteByte(). There are no functions for dealing with integers, strings etc. This makes the stream very general-purpose, but less simple to work with if, say, you just want to transfer text.

However, .NET provides classes that convert between native types and the low-level stream interface, and transfers the data to or from the stream for you. Some notable such classes are:

StreamWriter // Badly named. Should be TextWriter.
StreamReader // Badly named. Should be TextReader.
BinaryWriter
BinaryReader

To use these, first you acquire your stream, then you create one of the above classes and associate it with the stream. E.g.

MemoryStream memoryStream = new MemoryStream();
StreamWriter myStreamWriter = new StreamWriter(memoryStream);

StreamReader and StreamWriter convert between native types and their string representations then transfer the strings to and from the stream as bytes. So

myStreamWriter.Write(123);

will write "123" (three characters '1', '2' then '3') to the stream. If you're dealing with text files (e.g. html), StreamReader and StreamWriter are the classes you would use.

Whereas

myBinaryWriter.Write(123);

will write four bytes representing the 32-bit integer value 123 (0x7B, 0x00, 0x00, 0x00). If you're dealing with binary files or network protocols BinaryReader and BinaryWriter are what you might use. (If you're exchanging data with networks or other systems, you need to be mindful of endianness, but that's another post.)

How can I open Windows Explorer to a certain directory from within a WPF app?

Process.Start("explorer.exe" , @"C:\Users");

I had to use this, the other way of just specifying the tgt dir would shut the explorer window when my application terminated.

How do you overcome the svn 'out of date' error?

I did this and it worked for me:
1. Take a back-up of your file. You can simply copy your code to a text file.
2. Right Click the file you want to commit >> Team >> Show History. 3. In "Show History" Panel you will see all the revisions of that file. Right click on latest revision of the file >> Get Revision: It will override your local changes.
4. Now, merge your code with the latest file with the back-up file (step#1).
5. Synchronise and Commit the newly merged file.

How to set enum to null

Color? color = null;

or you can use

Color? color = new Color?();

example where assigning null wont work

color = x == 5 ? Color.Red : x == 9 ? Color.Black : null ; 

so you can use :

 color = x == 5 ? Color.Red : x == 9 ? Color.Black : new Color?(); 

Creating Unicode character from its number

Just cast your int to a char. You can convert that to a String using Character.toString():

String s = Character.toString((char)c);

EDIT:

Just remember that the escape sequences in Java source code (the \u bits) are in HEX, so if you're trying to reproduce an escape sequence, you'll need something like int c = 0x2202.

Count number of files within a directory in Linux?

this is one:

ls -l . | egrep -c '^-'

Note:

ls -1 | wc -l

Which means: ls: list files in dir

-1: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too

|: pipe output onto...

wc: "wordcount"

-l: count lines.

Case insensitive string as HashMap key

Two choices come to my mind:

  1. You could use directly the s.toUpperCase().hashCode(); as the key of the Map.
  2. You could use a TreeMap<String> with a custom Comparator that ignore the case.

Otherwise, if you prefer your solution, instead of defining a new kind of String, I would rather implement a new Map with the required case insensibility functionality.

Error including image in Latex

I had the same problem, caused by a clash between the graphicx package and an inclusion of the epsfig package that survived the ages...

Please check that there is no inclusion of epsfig, it is deprecated.

How to check if activity is in foreground or in visible background?

If you are using EventBus, it as a method called hasSubscriberForEvent which can be used to check if an Activity is focused.

How to convert an enum type variable to a string?

A clean solution to this problem would be:

#define RETURN_STR(val, e) {if (val == e) {return #e;}}

std::string conv_dxgi_format_to_string(int value) {
    RETURN_STR(value, DXGI_FORMAT_UNKNOWN);
    RETURN_STR(value, DXGI_FORMAT_R32G32B32A32_TYPELESS);
    RETURN_STR(value, DXGI_FORMAT_R32G32B32A32_FLOAT);
    RETURN_STR(value, DXGI_FORMAT_R32G32B32A32_UINT);
    RETURN_STR(value, DXGI_FORMAT_R32G32B32A32_SINT);
    RETURN_STR(value, DXGI_FORMAT_R32G32B32_TYPELESS);
    RETURN_STR(value, DXGI_FORMAT_R32G32B32_FLOAT);

    /* ... */

    return "<UNKNOWN>";
}

The good thing about this solution is that it is simple and also constructing the function can be done easily via copy and replace. Note that if you are going to do a lot of conversions and your enum has too many possible values, this solution might become CPU intensive.

How to use the gecko executable with Selenium

This can be due to system cannot find firefox installed location on path.

Try following code, which should work.

System.setProperty("webdriver.firefox.bin","C:\\Program Files\\Mozilla Firefox\\firefox.exe"); 
System.setProperty("webdriver.gecko.driver","<location of geckodriver>\\geckodriver.exe");

Merge two array of objects based on a key

Well... assuming both arrays are of the same length, I would probably do something like this:

var newArr = []
for (var i = 0; i < array1.length; i++ {
    if (array1[i].id === array2[i].id) {
      newArr.push({id: array1[i].id, date: array1[i].date, name: array2[i].name});
  }
}

How to inspect FormData?

Try this function:

function formDataToObject(formData) {
  return Array.from(formData.entries()).reduce((old, pair) => ({
    ...old,
    [pair[0]]: pair[1],
  }), {});
}

Split files using tar, gz, zip, or bzip2

use tar to split into multiple archives

there are plenty of programs that will work with tar files on windows, including cygwin.

INNER JOIN ON vs WHERE clause

I'll also point out that using the older syntax is more subject to error. If you use inner joins without an ON clause, you will get a syntax error. If you use the older syntax and forget one of the join conditions in the where clause, you will get a cross join. The developers often fix this by adding the distinct keyword (rather than fixing the join because they still don't realize the join itself is broken) which may appear to cure the problem but will slow down the query considerably.

Additionally for maintenance if you have a cross join in the old syntax, how will the maintainer know if you meant to have one (there are situations where cross joins are needed) or if it was an accident that should be fixed?

Let me point you to this question to see why the implicit syntax is bad if you use left joins. Sybase *= to Ansi Standard with 2 different outer tables for same inner table

Plus (personal rant here), the standard using the explicit joins is over 20 years old, which means implicit join syntax has been outdated for those 20 years. Would you write application code using a syntax that has been outdated for 20 years? Why do you want to write database code that is?

static files with express.js

If you have a complicated folder structure, such as

- Your application
     - assets
         - images
             - profile.jpg
     - web
     - server
        - index.js

If you want to serve assets/images from index.js

app.use('/images', express.static(path.join(__dirname, '..', 'assets', 'images')))

To view from your browser

http://localhost:4000/images/profile.jpg

If you need more clarification comment, I'll elaborate.

IndentationError: unexpected unindent WHY?

It's because you have:

def readTTable(fname):
    try:

without a matching except block after the try: block. Every try must have at least one matching except.

See the Errors and Exceptions section of the Python tutorial.

Index of element in NumPy array

I'm torn between these two ways of implementing an index of a NumPy array:

idx = list(classes).index(var)
idx = np.where(classes == var)

Both take the same number of characters, but the first method returns an int instead of a numpy.ndarray.

Why do you need to put #!/bin/bash at the beginning of a script file?

To be more precise the shebang #!, when it is the first two bytes of an executable (x mode) file, is interpreted by the execve(2) system call (which execute programs). But POSIX specification for execve don't mention the shebang.

It must be followed by a file path of an interpreter executable (which BTW could even be relative, but most often is absolute).

A nice trick (or perhaps not so nice one) to find an interpreter (e.g. python) in the user's $PATH is to use the env program (always at /usr/bin/env on all Linux) like e.g.

 #!/usr/bin/env python

Any ELF executable can be an interpreter. You could even use #!/bin/cat or #!/bin/true if you wanted to! (but that would be often useless)