Programs & Examples On #Apr

The Apache Portable Runtime (APR) library provides a variety of services masking the differences between different operating systems with a uniform, platform-neutral interface.

What does "The APR based Apache Tomcat Native library was not found" mean?

I had the same problem when tom?at could not find the class. Try to view other log files. Sometimes No class def found error appears in different log files:

  • tomcat8-stdout
  • tomcat8-stderr
  • localhost

How to combine results of two queries into a single dataset

Old question, but where others use JOIN to combine unrelated queries to rows in one table, this is my solution to combine unrelated queries to one row, e.g:

select 
  (select count(*) c from v$session where program = 'w3wp.exe') w3wp,
  (select count(*) c from v$session) total,
  sysdate
from dual;

which gives the following one-row output:

W3WP   TOTAL  SYSDATE
-----  -----  -------------------
   14    290  2020/02/18 10:45:07

(which tells me that our web server currently uses 14 Oracle sessions out of the total of 290 sessions; I log this output without headers in an sqlplus script that runs every so many minutes)

Remove trailing zeros

The following code could be used to not use the string type:

int decimalResult = 789.500
while (decimalResult>0 && decimalResult % 10 == 0)
{
    decimalResult = decimalResult / 10;
}
return decimalResult;

Returns 789.5

How can I see normal print output created during pytest run?

The other answers don't work. The only way to see the captured output is using the following flag:

pytest --show-capture all

What represents a double in sql server?

A Float represents double in SQL server. You can find a proof from the coding in C# in visual studio. Here I have declared Overtime as a Float in SQL server and in C#. Thus I am able to convert

int diff=4;
attendance.OverTime = Convert.ToDouble(diff);

Here OverTime is declared float type

Removing elements from array Ruby

Not very simple but:

a = [1,1,1,2,2,3]
b = a.group_by {|n| n}.each {|k,v| v.pop [1,3].count(k)}.values.flatten
=> [1, 1, 2, 2]

Also handles the case for multiples in the 'subtrahend':

a = [1,1,1,2,2,3]
b = a.group_by {|n| n}.each {|k,v| v.pop [1,1,3].count(k)}.values.flatten
=> [1, 2, 2]

EDIT: this is more an enhancement combining Norm212 and my answer to make a "functional" solution.

b = [1,1,3].each.with_object( a ) { |del| a.delete_at( a.index( del ) ) }

Put it in a lambda if needed:

subtract = lambda do |minuend, subtrahend|
  subtrahend.each.with_object( minuend ) { |del| minuend.delete_at( minuend.index( del ) ) }
end

then:

subtract.call a, [1,1,3]

Solutions for INSERT OR UPDATE on SQL Server

In SQL Server 2008 you can use the MERGE statement

Invoking a PHP script from a MySQL trigger

Run away from store procedures as much as possible. They are pretty hard to maintain and are VERY OLD STUFF ;)

How can I get the UUID of my Android phone in an application?

<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>

How to copy text to the client's clipboard using jQuery?

Copying to the clipboard is a tricky task to do in Javascript in terms of browser compatibility. The best way to do it is using a small flash. It will work on every browser. You can check it in this article.

Here's how to do it for Internet Explorer:

function copy (str)
{
    //for IE ONLY!
    window.clipboardData.setData('Text',str);
}

Why is the <center> tag deprecated in HTML?

HTML is intended for structuring data, not controlling layout. CSS is intended to control layout. You'll also find that many designers frown on using <table> for layouts for this very same reason.

How to move or copy files listed by 'find' command in unix?

If you're using GNU find,

find . -mtime 1 -exec cp -t ~/test/ {} +

This works as well as piping the output into xargs while avoiding the pitfalls of doing so (it handles embedded spaces and newlines without having to use find ... -print0 | xargs -0 ...).

What is the difference between resource and endpoint?

Possibly mine isn't a great answer but here goes.

Since working more with truly RESTful web services over HTTP, I've tried to steer people away from using the term endpoint since it has no clear definition, and instead use the language of REST which is resources and resource locations.

To my mind, endpoint is a TCP term. It's conflated with HTTP because part of the URL identifies a listening server.

So resource isn't a newer term, I don't think, I think endpoint was always misappropriated and we're realising that as we're getting our heads around REST as a style of API.

Edit

I blogged about this.

https://medium.com/@lukepuplett/stop-saying-endpoints-92c19e33e819

What is the difference between "::" "." and "->" in c++

In C++ you can access fields or methods, using different operators, depending on it's type:

  • ClassName::FieldName : class public static field and methods
  • ClassInstance.FieldName : accessing a public field (or method) through class reference
  • ClassPointer->FieldName : accessing a public field (or method) dereferencing a class pointer

Note that :: should be used with a class name rather than a class instance, since static fields or methods are common to all instances of a class.

class AClass{
public:
static int static_field;
int instance_field;

static void static_method();
void method();
};

then you access this way:

AClass instance;
AClass *pointer = new AClass();

instance.instance_field; //access instance_field through a reference to AClass
instance.method();

pointer->instance_field; //access instance_field through a pointer to AClass
pointer->method();

AClass::static_field;  
AClass::static_method();

Difference between JOIN and INNER JOIN

INNER JOIN = JOIN

INNER JOIN is the default if you don't specify the type when you use the word JOIN.

You can also use LEFT OUTER JOIN or RIGHT OUTER JOIN, in which case the word OUTER is optional, or you can specify CROSS JOIN.

OR

For an inner join, the syntax is:

SELECT ...
FROM TableA
[INNER] JOIN TableB

(in other words, the "INNER" keyword is optional - results are the same with or without it)

SQL exclude a column using SELECT * [except columnA] FROM tableA?

Yes it's possible (but not recommended).

CREATE TABLE contact (contactid int, name varchar(100), dob datetime)
INSERT INTO contact SELECT 1, 'Joe', '1974-01-01'

DECLARE @columns varchar(8000)

SELECT @columns = ISNULL(@columns + ', ','') + QUOTENAME(column_name)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'contact' AND COLUMN_NAME <> 'dob'
ORDER BY ORDINAL_POSITION

EXEC ('SELECT ' + @columns + ' FROM contact')

Explanation of the code:

  1. Declare a variable to store a comma separated list of column names. This defaults to NULL.
  2. Use a system view to determine the names of the columns in our table.
  3. Use SELECT @variable = @variable + ... FROM to concatenate the column names. This type of SELECT does not not return a result set. This is perhaps undocumented behaviour but works in every version of SQL Server. As an alternative you could use SET @variable = (SELECT ... FOR XML PATH('')) to concatenate strings.
  4. Use the ISNULL function to prepend a comma only if this is not the first column name. Use the QUOTENAME function to support spaces and punctuation in column names.
  5. Use the WHERE clause to hide columns we don't want to see.
  6. Use EXEC (@variable), also known as dynamic SQL, to resolve the column names at runtime. This is needed because we don't know the column names at compile time.

How to change default text file encoding in Eclipse?

I was having the same problem when I received a html to put inside my project and rename it to .jsp. To solve the problem, I needed to what people above already said, that is, to change text encoding in Eclipse Preferences. However, before renaming the files to .jsp, it was necessary to include the following line in the beginning of each .html file:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

I believe this forced Eclipse to understand that it was necessary to change file encoding when I tried to rename .html to .jsp.

How to convert a currency string to a double with jQuery or Javascript?

I know you've found a solution to your question, I just wanted to recommend that maybe you look at the following more extensive jQuery plugin for International Number Formats:

International Number Formatter

Rotate a div using javascript

Can be pretty easily done assuming you're using jQuery and css3:

http://jsfiddle.net/S7JDU/8/

HTML:

<div id="clicker">Click Here</div>
<div id="rotating"></div>

CSS:

#clicker { 
    width: 100px; 
    height: 100px; 
    background-color: Green; 
}

#rotating { 
    width: 100px; 
    height: 100px; 
    background-color: Red; 
    margin-top: 50px; 
    -webkit-transition: all 0.3s ease-in-out;
    -moz-transition: all 0.3s ease-in-out;
    -o-transition: all 0.3s ease-in-out;
    transition: all 0.3s ease-in-out;
}

.rotated { 
    transform:rotate(25deg); 
    -webkit-transform:rotate(25deg); 
    -moz-transform:rotate(25deg); 
    -o-transform:rotate(25deg); 
}

JS:

$(document).ready(function() {
    $('#clicker').click(function() {
        $('#rotating').toggleClass('rotated');
    });
});

How to let an ASMX file output JSON

A quick gotcha that I learned the hard way (basically spending 4 hours on Google), you can use PageMethods in your ASPX file to return JSON (with the [ScriptMethod()] marker) for a static method, however if you decide to move your static methods to an asmx file, it cannot be a static method.

Also, you need to tell the web service Content-Type: application/json in order to get JSON back from the call (I'm using jQuery and the 3 Mistakes To Avoid When Using jQuery article was very enlightening - its from the same website mentioned in another answer here).

How to have a default option in Angular.js select box

Depending on how many options you have, you could put your values in an array and auto-populate your options like this

<select ng-model="somethingHere.values" ng-options="values for values in [5,4,3,2,1]">
   <option value="">Pick a Number</option>
</select>

Favicon dimensions?

16x16 pixels, *.ico format.

Calculating how many minutes there are between two times

If the difference between endTime and startTime is greater than or equal to 60 Minutes , the statement:endTime.Subtract(startTime).Minutes; will always return (minutesDifference % 60). Obviously which is not desired when we are only talking about minutes (not hours here).
Here are some of the ways if you want to get total number of minutes(in different typecasts):

// Default value that is returned is of type *double* 
double double_minutes = endTime.Subtract(startTime).TotalMinutes; 
int integer_minutes = (int)endTime.Subtract(startTime).TotalMinutes; 
long long_minutes = (long)endTime.Subtract(startTime).TotalMinutes; 
string string_minutes = (string)endTime.Subtract(startTime).TotalMinutes; 

Use of REPLACE in SQL Query for newline/ carriage return characters

There are probably embedded tabs (CHAR(9)) etc. as well. You can find out what other characters you need to replace (we have no idea what your goal is) with something like this:

DECLARE @var NVARCHAR(255), @i INT;

SET @i = 1;

SELECT @var = AccountType FROM dbo.Account
  WHERE AccountNumber = 200
  AND AccountType LIKE '%Daily%';

CREATE TABLE #x(i INT PRIMARY KEY, c NCHAR(1), a NCHAR(1));

WHILE @i <= LEN(@var)
BEGIN
  INSERT #x 
    SELECT SUBSTRING(@var, @i, 1), ASCII(SUBSTRING(@var, @i, 1));

  SET @i = @i + 1;
END

SELECT i,c,a FROM #x ORDER BY i;

You might also consider doing better cleansing of this data before it gets into your database. Cleaning it every time you need to search or display is not the best approach.

Installing Apple's Network Link Conditioner Tool

It's in an additional download. Use this menu item:

Xcode > Open Developer Tool > More Developer Tools...

and get "Hardware IO Tools for Xcode".

For Xcode 8+, get "Additional Tools for Xcode [version]".

Double-click on a .prefPane file to install. If you already have an older .prefPane installed, you'll need to remove it from /Library/PreferencePanes.

C# 4.0 optional out/ref arguments

As already mentioned, this is simply not allowed and I think it makes a very good sense. However, to add some more details, here is a quote from the C# 4.0 Specification, section 21.1:

Formal parameters of constructors, methods, indexers and delegate types can be declared optional:

fixed-parameter:
    attributesopt parameter-modifieropt type identifier default-argumentopt
default-argument:
    = expression

  • A fixed-parameter with a default-argument is an optional parameter, whereas a fixed-parameter without a default-argument is a required parameter.
  • A required parameter cannot appear after an optional parameter in a formal-parameter-list.
  • A ref or out parameter cannot have a default-argument.

'list' object has no attribute 'shape'

import numpy
X = numpy.array(the_big_nested_list_you_had)

It's still not going to do what you want; you have more bugs, like trying to unpack a 3-dimensional shape into two target variables in test.

Links in <select> dropdown options

This is an old question, I know but for 2019 peeps:

Like above if you just want to change the URL you can do this:

<select onChange="window.location.href=this.value">
    <option value="www.google.com">A</option>
    <option value="www.aol.com">B</option>
</select>

But if you want it to act like an a tag and so you can do "./page", "#bottom" or "?a=567" use window.location.replace()

<select onChange="window.location.redirect(this.value)">
    <option value="..">back</option>
    <option value="./list">list</option>
    <option value="#bottom">bottom</option>
</select>

Error message: (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)

Check that the server name you're logging into with SQL Management Studio matches your connection string.

I was getting this error today. It turned out that I hadn't realised the machine with SQL Server installed had multiples servers running. I had in fact put my database in a totally different server to the one I thought I was using. (So my connection string was pointing to a server with no database)

Hence, When .net tried to access the database it couldn't find anything and gave only a misleading error message about pipes.

I opened the correct server in SQL Management Studio, added my database to and then all worked fine. (If the correct server isn't available in the dropdown, try browsing for it.)

Image showing the connection string matching the correct server name

How to disable Compatibility View in IE

This should be enough to force an IE user to drop compatibility mode in any IE version:

<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />

However, there are a couple of caveats one should be aware of:

  • The meta tag above should be included as the very first tag under <head>. Only the <title> tag may be placed above it.

If you don't do that, you'll get an error on IE9 Dev Tools: X-UA-Compatible META tag ignored because document mode is already finalized.

  • If you want this markup to validate, make sure you remember to close the meta tag with a /> instead of just >.

  • Starting with IE11, edge mode is the preferred document mode. To support/enable that, use the HTML5 document type declaration <!doctype html>.

  • If you need to support webfonts on IE7, make sure you use <!DOCTYPE html>. I've tested it and found that rendering webfonts on IE7 got pretty unreliable when using <!doctype html>.

The use of Google Chrome Frame is popular, but unfortunately it's going to be dropped sometime this month, Jan. 2014.

<meta http-equiv="X-UA-Compatible" content="IE=EDGE,chrome=1">

Extensive related info here. The tip on using it as the first meta tag is on a previously mentioned source here, which has been updated.

How do I change the IntelliJ IDEA default JDK?

I am using IntelliJ 2020.3.1 and the File > Other Settings... menu option has disappeared. I went to Settings in the usual way and searched for "jdk". Under Build, Execution, Deployment > Build Tools > Maven > Importing I found the the setting that will solve my specific issue:

JDK for importer.

IntelliJ 2020.3 Settings dialog

Android + Pair devices via bluetooth programmatically

The Best way is do not use any pairing code. Instead of onClick go to other function or other class where You create the socket using UUID.
Android automatically pops up for pairing if already not paired.

or see this link for better understanding

Below is code for the same:

private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
    public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
        // Cancel discovery because it's costly and we're about to connect
        mBtAdapter.cancelDiscovery();

        // Get the device MAC address, which is the last 17 chars in the View
        String info = ((TextView) v).getText().toString();
        String address = info.substring(info.length() - 17);

        // Create the result Intent and include the MAC address
        Intent intent = new Intent();
        intent.putExtra(EXTRA_DEVICE_ADDRESS, address);

        // Set result and finish this Activity
        setResult(Activity.RESULT_OK, intent);

      // **add this 2 line code** 
       Intent myIntent = new Intent(view.getContext(), Connect.class);
        startActivityForResult(myIntent, 0);

        finish();
    }
};

Connect.java file is :

public class Connect extends Activity {
private static final String TAG = "zeoconnect";
private ByteBuffer localByteBuffer;
 private InputStream in;
 byte[] arrayOfByte = new byte[4096];
 int bytes;


  public BluetoothDevice mDevice;



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.connect);



              try {
                setup();
            } catch (ZeoMessageException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ZeoMessageParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            }

 private void setup() throws ZeoMessageException, ZeoMessageParseException  {
    // TODO Auto-generated method stub

        getApplicationContext().registerReceiver(receiver,
                    new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
        getApplicationContext().registerReceiver(receiver,
                    new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));

            BluetoothDevice zee = BluetoothAdapter.getDefaultAdapter().
                    getRemoteDevice("**:**:**:**:**:**");// add device mac adress

            try {
                sock = zee.createRfcommSocketToServiceRecord(
                         UUID.fromString("*******************")); // use unique UUID
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            Log.d(TAG, "++++ Connecting");
            try {
                sock.connect();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            Log.d(TAG, "++++ Connected");


            try {
                in = sock.getInputStream();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

              Log.d(TAG, "++++ Listening...");

              while (true) {

                  try {
                      bytes = in.read(arrayOfByte);
                      Log.d(TAG, "++++ Read "+ bytes +" bytes");  
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                }
                        Log.d(TAG, "++++ Done: test()"); 

                        }} 




 private static final LogBroadcastReceiver receiver = new LogBroadcastReceiver();
    public static class LogBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context paramAnonymousContext, Intent paramAnonymousIntent) {
            Log.d("ZeoReceiver", paramAnonymousIntent.toString());
            Bundle extras = paramAnonymousIntent.getExtras();
            for (String k : extras.keySet()) {
                Log.d("ZeoReceiver", "    Extra: "+ extras.get(k).toString());
            }
        }


    };

    private BluetoothSocket sock;
    @Override
    public void onDestroy() {
        getApplicationContext().unregisterReceiver(receiver);
        if (sock != null) {
            try {
                sock.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        super.onDestroy();
    }
 }

What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?

__func__ is an implicitly declared identifier that expands to a character array variable containing the function name when it is used inside of a function. It was added to C in C99. From C99 §6.4.2.2/1:

The identifier __func__ is implicitly declared by the translator as if, immediately following the opening brace of each function definition, the declaration

static const char __func__[] = "function-name";

appeared, where function-name is the name of the lexically-enclosing function. This name is the unadorned name of the function.

Note that it is not a macro and it has no special meaning during preprocessing.

__func__ was added to C++ in C++11, where it is specified as containing "an implementation-de?ned string" (C++11 §8.4.1[dcl.fct.def.general]/8), which is not quite as useful as the specification in C. (The original proposal to add __func__ to C++ was N1642).

__FUNCTION__ is a pre-standard extension that some C compilers support (including gcc and Visual C++); in general, you should use __func__ where it is supported and only use __FUNCTION__ if you are using a compiler that does not support it (for example, Visual C++, which does not support C99 and does not yet support all of C++0x, does not provide __func__).

__PRETTY_FUNCTION__ is a gcc extension that is mostly the same as __FUNCTION__, except that for C++ functions it contains the "pretty" name of the function including the signature of the function. Visual C++ has a similar (but not quite identical) extension, __FUNCSIG__.

For the nonstandard macros, you will want to consult your compiler's documentation. The Visual C++ extensions are included in the MSDN documentation of the C++ compiler's "Predefined Macros". The gcc documentation extensions are described in the gcc documentation page "Function Names as Strings."

Delete last char of string

Removes any trailing commas:

while (strgroupids.EndsWith(","))
    strgroupids = strgroupids.Substring(0, strgroupids.Length - 1);

This is backwards though, you wrote the code that adds the comma in the first place. You should use string.Join(",",g) instead, assuming g is a string[]. Give it a better name than g too !

google map API zoom range

Available Zoom Levels

Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.

Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.

As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:

  • Road maps - seem to go up to zoom level 22 everywhere
  • Hybrid and satellite maps - the max available zoom levels depend on location. Here are some examples:
  • Remote regions of Antarctica: 13
  • Gobi Desert: 17
  • Much of the U.S. and Europe: 21
  • "Deep zoom" locations: 22-23 (see bkaid's link)

Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.

Map Scale at Various Zoom Levels

Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:

meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)

Formula is from Chris Broadfoot's comment.


Google Maps basics

Zoom Level - zoom

0 - 19

0 lowest zoom (whole world)

19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()


What you're looking for are the scales for each zoom level. Use these:

20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9  : 2311162.307000
8  : 4622324.614000
7  : 9244649.227000
6  : 18489298.450000
5  : 36978596.910000
4  : 73957193.820000
3  : 147914387.600000
2  : 295828775.300000
1  : 591657550.500000

How to use Python to login to a webpage and retrieve cookies for later usage?

import urllib, urllib2, cookielib

username = 'myuser'
password = 'mypassword'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()

resp.read() is the straight html of the page you want to open, and you can use opener to view any page using your session cookie.

How to change the text of a button in jQuery?

$("#btnAddProfile").text("Save");

What are the new features in C++17?

Language features:

Templates and Generic Code

Lambda

Attributes

Syntax cleanup

Cleaner multi-return and flow control

  • Structured bindings

    • Basically, first-class std::tie with auto
    • Example:
      • const auto [it, inserted] = map.insert( {"foo", bar} );
      • Creates variables it and inserted with deduced type from the pair that map::insert returns.
    • Works with tuple/pair-likes & std::arrays and relatively flat structs
    • Actually named structured bindings in standard
  • if (init; condition) and switch (init; condition)

    • if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
    • Extends the if(decl) to cases where decl isn't convertible-to-bool sensibly.
  • Generalizing range-based for loops

    • Appears to be mostly support for sentinels, or end iterators that are not the same type as begin iterators, which helps with null-terminated loops and the like.
  • if constexpr

    • Much requested feature to simplify almost-generic code.

Misc

Library additions:

Data types

Invoke stuff

File System TS v1

New algorithms

  • for_each_n

  • reduce

  • transform_reduce

  • exclusive_scan

  • inclusive_scan

  • transform_exclusive_scan

  • transform_inclusive_scan

  • Added for threading purposes, exposed even if you aren't using them threaded

Threading

(parts of) Library Fundamentals TS v1 not covered above or below

Container Improvements

Smart pointer changes

Other std datatype improvements:

Misc

Traits

Deprecated

Isocpp.org has has an independent list of changes since C++14; it has been partly pillaged.

Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.

Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.

Additional entries pillaged from SD-6 feature-test list.

clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.

these slides had some features missing elsewhere.

While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:

Removed:

There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:

Papers not yet integrated into above:

  • P0505R0 (constexpr chrono)

  • P0418R2 (atomic tweaks)

  • P0512R0 (template argument deduction tweaks)

  • P0490R0 (structured binding tweaks)

  • P0513R0 (changes to std::hash)

  • P0502R0 (parallel exceptions)

  • P0509R1 (updating restrictions on exception handling)

  • P0012R1 (make exception specifications be part of the type system)

  • P0510R0 (restrictions on variants)

  • P0504R0 (tags for optional/variant/any)

  • P0497R0 (shared ptr tweaks)

  • P0508R0 (structured bindings node handles)

  • P0521R0 (shared pointer use count and unique changes?)

Spec changes:

Further reference:

git pull displays "fatal: Couldn't find remote ref refs/heads/xxxx" and hangs up

In my case, it happenned for the master branch. Later found that my access to the project was accidentally revoked by the project manager. To cross-check, I visited the review site and couldn't see any commits of the said branch and others for that project.

case in sql stored procedure on SQL Server

CASE isn't used for flow control... for this, you would need to use IF...

But, there's a set-based solution to this problem instead of the procedural approach:

UPDATE tblEmployee
SET 
  InOffice = CASE WHEN @NewStatus = 'InOffice' THEN -1 ELSE InOffice END,
  OutOffice = CASE WHEN @NewStatus = 'OutOffice' THEN -1 ELSE OutOffice END,
  Home = CASE WHEN @NewStatus = 'Home' THEN -1 ELSE Home END
WHERE EmpID = @EmpID

Note that the ELSE will preserves the original value if the @NewStatus condition isn't met.

How do I remove javascript validation from my eclipse project?

Window -> Preferences -> JavaScript -> Validator (also per project settings possible)

or

Window -> Preferences -> Validation (disable validations and configure their settings)

java.sql.SQLException: Exhausted Resultset

This occurs typically when the stmt is reused butexpecting a different ResultSet, try creting a new stmt and executeQuery. It fixed it for me!

What does the C++ standard state the size of int, long type to be?

From Alex B The C++ standard does not specify the size of integral types in bytes, but it specifies minimum ranges they must be able to hold. You can infer minimum size in bits from the required range. You can infer minimum size in bytes from that and the value of the CHAR_BIT macro that defines the number of bits in a byte (in all but the most obscure platforms it's 8, and it can't be less than 8).

One additional constraint for char is that its size is always 1 byte, or CHAR_BIT bits (hence the name).

Minimum ranges required by the standard (page 22) are:

and Data Type Ranges on MSDN:

signed char: -127 to 127 (note, not -128 to 127; this accommodates 1's-complement platforms) unsigned char: 0 to 255 "plain" char: -127 to 127 or 0 to 255 (depends on default char signedness) signed short: -32767 to 32767 unsigned short: 0 to 65535 signed int: -32767 to 32767 unsigned int: 0 to 65535 signed long: -2147483647 to 2147483647 unsigned long: 0 to 4294967295 signed long long: -9223372036854775807 to 9223372036854775807 unsigned long long: 0 to 18446744073709551615 A C++ (or C) implementation can define the size of a type in bytes sizeof(type) to any value, as long as

the expression sizeof(type) * CHAR_BIT evaluates to the number of bits enough to contain required ranges, and the ordering of type is still valid (e.g. sizeof(int) <= sizeof(long)). The actual implementation-specific ranges can be found in header in C, or in C++ (or even better, templated std::numeric_limits in header).

For example, this is how you will find maximum range for int:

C:

#include <limits.h>
const int min_int = INT_MIN;
const int max_int = INT_MAX;

C++:

#include <limits>
const int min_int = std::numeric_limits<int>::min();
const int max_int = std::numeric_limits<int>::max();

This is correct, however, you were also right in saying that: char : 1 byte short : 2 bytes int : 4 bytes long : 4 bytes float : 4 bytes double : 8 bytes

Because 32 bit architectures are still the default and most used, and they have kept these standard sizes since the pre-32 bit days when memory was less available, and for backwards compatibility and standardization it remained the same. Even 64 bit systems tend to use these and have extentions/modifications. Please reference this for more information:

http://en.cppreference.com/w/cpp/language/types

Finding blocking/locking queries in MS SQL (mssql)

I found this query which helped me find my locked table and query causing the issue.

SELECT  L.request_session_id AS SPID, 
        DB_NAME(L.resource_database_id) AS DatabaseName,
        O.Name AS LockedObjectName, 
        P.object_id AS LockedObjectId, 
        L.resource_type AS LockedResource, 
        L.request_mode AS LockType,
        ST.text AS SqlStatementText,        
        ES.login_name AS LoginName,
        ES.host_name AS HostName,
        TST.is_user_transaction as IsUserTransaction,
        AT.name as TransactionName,
        CN.auth_scheme as AuthenticationMethod
FROM    sys.dm_tran_locks L
        JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
        JOIN sys.objects O ON O.object_id = P.object_id
        JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
        JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
        JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
        JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
        CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE   resource_database_id = db_id()
ORDER BY L.request_session_id

How to get char from string by index?

Previous answers cover about ASCII character at a certain index.

It is a little bit troublesome to get a Unicode character at a certain index in Python 2.

E.g., with s = '????????' which is <type 'str'>,

__getitem__, e.g., s[i] , does not lead you to where you desire. It will spit out semething like ?. (Many Unicode characters are more than 1 byte but __getitem__ in Python 2 is incremented by 1 byte.)

In this Python 2 case, you can solve the problem by decoding:

s = '????????'
s = s.decode('utf-8')
for i in range(len(s)):
    print s[i]

SQL UPDATE with sub-query that references the same table in MySQL

UPDATE user_account student

SET (student.student_education_facility_id) = (

   SELECT teacher.education_facility_id

   FROM user_account teacher

   WHERE teacher.user_account_id = student.teacher_id AND teacher.user_type = 'ROLE_TEACHER'

)

WHERE student.user_type = 'ROLE_STUDENT';

How to escape single quotes within single quoted strings

Simple example of escaping quotes in shell:

$ echo 'abc'\''abc'
abc'abc
$ echo "abc"\""abc"
abc"abc

It's done by finishing already opened one ('), placing escaped one (\'), then opening another one ('). This syntax works for all commands. It's very similar approach to the 1st answer.

Java method to swap primitives

Apparently I don't have enough reputation points to comment on Dansalmo's answer, but it is a good one, though mis-named. His answer is actually a K-combinator.

int K( int a, int b ) {
    return a;
}

The JLS is specific about argument evaluation when passing to methods/ctors/etc. (Was this not so in older specs?)

Granted, this is a functional idiom, but it is clear enough to those who recognize it. (If you don't understand code you find, don't mess with it!)

y = K(x, x=y);  // swap x and y

The K-combinator is specifically designed for this kind of thing. AFAIK there's no reason it shouldn't pass a code review.

My $0.02.

How to remove close button on the jQuery UI dialog?

The best way to hide the button is to filter it with it's data-icon attribute:

$('#dialog-id [data-icon="delete"]').hide();

How do I disable directory browsing?

Add this in your .htaccess file:

Options -Indexes

If it is not work for any reason, try this within your .htaccess file:

IndexIgnore *

How do you grep a file and get the next 5 lines

Here is a sed solution:

sed '/19:55/{
N
N
N
N
N
s/\n/ /g
}' file.txt

C# How to determine if a number is a multiple of another?

followings programs will execute,"one number is multiple of another" in

#include<stdio.h>
int main
{
int a,b;
printf("enter any two number\n");
scanf("%d%d",&a,&b);
if (a%b==0)
printf("this is  multiple number");
else if (b%a==0);
printf("this is multiple number");
else
printf("this is not multiple number");
return 0;
}

html select scroll bar

Horizontal scrollbars in a HTML Select are not natively supported. However, here's a way to create the appearance of a horizontal scrollbar:

1. First create a css class

<style type="text/css">
 .scrollable{
   overflow: auto;
   width: 70px; /* adjust this width depending to amount of text to display */
   height: 80px; /* adjust height depending on number of options to display */
   border: 1px silver solid;
 }
 .scrollable select{
   border: none;
 }
</style>

2. Wrap the SELECT inside a DIV - also, explicitly set the size to the number of options.

<div class="scrollable">
<select size="6" multiple="multiple">
    <option value="1" selected>option 1 The Long Option</option>
    <option value="2">option 2</option>
    <option value="3">option 3</option>
    <option value="4">option 4</option>
    <option value="5">option 5 Another Longer than the Long Option ;)</option>
    <option value="6">option 6</option>
</select>
</div>

Format specifier %02x

%02x means print at least 2 digits, prepend it with 0's if there's less. In your case it's 7 digits, so you get no extra 0 in front.

Also, %x is for int, but you have a long. Try %08lx instead.

How to create an Oracle sequence starting with max value from a table?

Based on Ivan Laharnar with less code and simplier:

declare
    lastSeq number;
begin
    SELECT MAX(ID) + 1 INTO lastSeq FROM <TABLE_NAME>;
    if lastSeq IS NULL then lastSeq := 1; end if;
    execute immediate 'CREATE SEQUENCE <SEQUENCE_NAME> INCREMENT BY 1 START WITH ' || lastSeq || ' MAXVALUE 999999999 MINVALUE 1 NOCACHE';
end;

How to programmatically set the ForeColor of a label to its default?

labelname.ForeColor = Color.Colorname;   ­­­­

How do I create a datetime in Python from milliseconds?

Converting millis to datetime (UTC):

import datetime
time_in_millis = 1596542285000
dt = datetime.datetime.fromtimestamp(time_in_millis / 1000.0, tz=datetime.timezone.utc)

Converting datetime to string following the RFC3339 standard (used by Open API specification):

from rfc3339 import rfc3339
converted_to_str = rfc3339(dt, utc=True, use_system_timezone=False)
# 2020-08-04T11:58:05Z

Open local folder from link

you can use

<a href="\\computername\folder">Open folder</a>

in Internet Explorer

Disable scrolling in webview?

Just use android:focusableInTouchMode="false" on your webView.

onclick go full screen

var elem = document.getElementById("myvideo");
function openFullscreen() {
  if (elem.requestFullscreen) {
      elem.requestFullscreen();
  } else if (elem.mozRequestFullScreen) { /* Firefox */
      elem.mozRequestFullScreen();
  } else if (elem.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
      elem.webkitRequestFullscreen();
  } else if (elem.msRequestFullscreen) { /* IE/Edge */
      elem.msRequestFullscreen();
  }
}
//Internet Explorer 10 and earlier does not support the msRequestFullscreen() method.

How large should my recv buffer be when calling recv in the socket library

16kb is about right; if you're using gigabit ethernet, each packet could be 9kb in size.

Can we instantiate an abstract class directly?

You can't directly instantiate an abstract class, but you can create an anonymous class when there is no concrete class:

public class AbstractTest {
    public static void main(final String... args) {
        final Printer p = new Printer() {
            void printSomethingOther() {
                System.out.println("other");
            }
            @Override
            public void print() {
                super.print();
                System.out.println("world");
                printSomethingOther(); // works fine
            }
        };
        p.print();
        //p.printSomethingOther(); // does not work
    }
}

abstract class Printer {
    public void print() {
        System.out.println("hello");
    }
}

This works with interfaces, too.

Using Selenium Web Driver to retrieve value of a HTML input

You can do like this :

webelement time=driver.findElement(By.id("input_name")).getAttribute("value");

this will give you the time displaying on the webpage.

Python - Dimension of Data Frame

df.shape, where df is your DataFrame.

Understanding the Linux oom-killer's logs

Memory management in Linux is a bit tricky to understand, and I can't say I fully understand it yet, but I'll try to share a little bit of my experience and knowledge.

Short answer to your question: Yes there are other stuff included than whats in the list.

What's being shown in your list is applications run in userspace. The kernel uses memory for itself and modules, on top of that it also has a lower limit of free memory that you can't go under. When you've reached that level it will try to free up resources, and when it can't do that anymore, you end up with an OOM problem.

From the last line of your list you can read that the kernel reports a total-vm usage of: 1498536kB (1,5GB), where the total-vm includes both your physical RAM and swap space. You stated you don't have any swap but the kernel seems to think otherwise since your swap space is reported to be full (Total swap = 524284kB, Free swap = 0kB) and it reports a total vmem size of 1,5GB.

Another thing that can complicate things further is memory fragmentation. You can hit the OOM killer when the kernel tries to allocate lets say 4096kB of continous memory, but there are no free ones availible.

Now that alone probably won't help you solve the actual problem. I don't know if it's normal for your program to require that amount of memory, but I would recommend to try a static code analyzer like cppcheck to check for memory leaks or file descriptor leaks. You could also try to run it through Valgrind to get a bit more information out about memory usage.

@Autowired and static method

Use AppContext. Make sure you create a bean in your context file.

private final static Foo foo = AppContext.getApplicationContext().getBean(Foo.class);

public static void randomMethod() {
     foo.doStuff();
}

What is ":-!!" in C code?

It's creating a size 0 bitfield if the condition is false, but a size -1 (-!!1) bitfield if the condition is true/non-zero. In the former case, there is no error and the struct is initialized with an int member. In the latter case, there is a compile error (and no such thing as a size -1 bitfield is created, of course).

Connect HTML page with SQL server using javascript

JavaScript is a client-side language and your MySQL database is going to be running on a server.

So you have to rename your file to index.php for example (.php is important) so you can use php code for that. It is not very difficult, but not directly possible with html.

(Somehow you can tell your server to let the html files behave like php files, but this is not the best solution.)

So after you renamed your file, go to the very top, before <html> or <!DOCTYPE html> and type:

<?php
    if($_SERVER['REQUEST_METHOD'] == 'POST') {
        /*Creating variables*/
        $name = $_POST["name"];
        $address = $_POST["address"];
        $age = $_POST["age"];


        $dbhost = "localhost"; /*most of the time it's localhost*/
        $username = "yourusername";
        $password = "yourpassword";
        $dbname = "mydatabase";

        $mysql = mysqli_connect($dbhost, $username, $password, $dbname); //It connects
        $query = "INSERT INTO yourtable (name,address,age) VALUES $name, $address, $age";
        mysqli_query($mysql, $query);
    }
?>
<!DOCTYPE html>
<html>
<head>.......
....
    <form method="post">
        <input name="name" type="text"/>
        <input name="address" type="text"/>
        <input name="age" type="text"/>
    </form>
....

How to commit to remote git repository

You just need to make sure you have the rights to push to the remote repository and do

git push origin master

or simply

git push

Crystal Reports - Adding a parameter to a 'Command' query

When you are in the Command, click Create to create a new parameter; call it project_name. Once you've created it, double click its name to add it to the command's text. You query should resemble:

SELECT Projecttname, ReleaseDate, TaskName
FROM DB_Table
WHERE Project_Name LIKE {?project_name} + '*'
AND ReleaseDate >= getdate() --assumes sql server

If desired, link the main report to the subreport on this ({?project_name}) field. If you don't establish a link between the main and subreport, CR will prompt you for the subreport's parameter.

In versions prior to 2008, a command's parameter was only allowed to be a scalar value.

Saving an Object (Data persistence)

Quick example using company1 from your question, with python3.

import pickle

# Save the file
pickle.dump(company1, file = open("company1.pickle", "wb"))

# Reload the file
company1_reloaded = pickle.load(open("company1.pickle", "rb"))

However, as this answer noted, pickle often fails. So you should really use dill.

import dill

# Save the file
dill.dump(company1, file = open("company1.pickle", "wb"))

# Reload the file
company1_reloaded = dill.load(open("company1.pickle", "rb"))

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

Use:

 System.out.println("Current date in Date Format: " + sdf.format(date));

HTTP Range header

As Wrikken suggested, it's a valid request. It's also quite common when the client is requesting media or resuming a download.

A client will often test to see if the server handles ranged requests other than just looking for an Accept-Ranges response. Chrome always sends a Range: bytes=0- with its first GET request for a video, so it's something you can't dismiss.

Whenever a client includes Range: in its request, even if it's malformed, it's expecting a partial content (206) response. When you seek forward during HTML5 video playback, the browser only requests the starting point. For example:

Range: bytes=3744-

So, in order for the client to play video properly, your server must be able to handle these incomplete range requests.

You can handle the type of 'range' you specified in your question in two ways:

First, You could reply with the requested starting point given in the response, then the total length of the file minus one (the requested byte range is zero-indexed). For example:

Request:

GET /BigBuckBunny_320x180.mp4 
Range: bytes=100-

Response:

206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/64656927

Second, you could reply with the starting point given in the request and an open-ended file length (size). This is for webcasts or other media where the total length is unknown. For example:

Request:

GET /BigBuckBunny_320x180.mp4
Range: bytes=100-

Response:

206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/*

Tips:

You must always respond with the content length included with the range. If the range is complete, with start to end, then the content length is simply the difference:

Request: Range: bytes=500-1000

Response: Content-Range: bytes 500-1000/123456

Remember that the range is zero-indexed, so Range: bytes=0-999 is actually requesting 1000 bytes, not 999, so respond with something like:

Content-Length: 1000
Content-Range: bytes 0-999/123456

Or:

Content-Length: 1000
Content-Range: bytes 0-999/*

But, avoid the latter method if possible because some media players try to figure out the duration from the file size. If your request is for media content, which is my hunch, then you should include its duration in the response. This is done with the following format:

X-Content-Duration: 63.23 

This must be a floating point. Unlike Content-Length, this value doesn't have to be accurate. It's used to help the player seek around the video. If you are streaming a webcast and only have a general idea of how long it will be, it's better to include your estimated duration rather than ignore it altogether. So, for a two-hour webcast, you could include something like:

X-Content-Duration: 7200.00 

With some media types, such as webm, you must also include the content-type, such as:

Content-Type: video/webm 

All of these are necessary for the media to play properly, especially in HTML5. If you don't give a duration, the player may try to figure out the duration (to allow for seeking) from its file size, but this won't be accurate. This is fine, and necessary for webcasts or live streaming, but not ideal for playback of video files. You can extract the duration using software like FFMPEG and save it in a database or even the filename.

X-Content-Duration is being phased out in favor of Content-Duration, so I'd include that too. A basic, response to a "0-" request would include at least the following:

HTTP/1.1 206 Partial Content
Date: Sun, 08 May 2013 06:37:54 GMT
Server: Apache/2.0.52 (Red Hat)
Accept-Ranges: bytes
Content-Length: 3980
Content-Range: bytes 0-3979/3980
Content-Type: video/webm
X-Content-Duration: 2054.53
Content-Duration: 2054.53

One more point: Chrome always starts its first video request with the following:

Range: bytes=0-

Some servers will send a regular 200 response as a reply, which it accepts (but with limited playback options), but try to send a 206 instead to show than your server handles ranges. RFC 2616 says it's acceptable to ignore range headers.

Send form data with jquery ajax json

The accepted answer here indeed makes a json from a form, but the json contents is really a string with url-encoded contents.

To make a more realistic json POST, use some solution from Serialize form data to JSON to make formToJson function and add contentType: 'application/json;charset=UTF-8' to the jQuery ajax call parameters.

$.ajax({
    url: 'test.php',
    type: "POST",
    dataType: 'json',
    data: formToJson($("form")),
    contentType: 'application/json;charset=UTF-8',
    ...
})

SSRS Query execution failed for dataset

Like many others here, I had the same error. In my case it was because the execute permission was denied on a stored procedure it used. It was resolved when the user associated with the data source was given that permission.

Android custom dropdown/popup menu

First, create a folder named “menu” in the “res” folder.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/search"
        android:icon="@android:drawable/ic_menu_search"
        android:title="Search"/>
    <item
        android:id="@+id/add"
        android:icon="@android:drawable/ic_menu_add"
        android:title="Add"/>
    <item
        android:id="@+id/edit"
        android:icon="@android:drawable/ic_menu_edit"
        android:title="Edit">
        <menu>
            <item
                android:id="@+id/share"
                android:icon="@android:drawable/ic_menu_share"
                android:title="Share"/>
        </menu>
    </item>

</menu>

Then, create your Activity Class:

public class PopupMenu1 extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.popup_menu_1);
    }

    public void onPopupButtonClick(View button) {
        PopupMenu popup = new PopupMenu(this, button);
        popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu());

        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {
                Toast.makeText(PopupMenu1.this,
                        "Clicked popup menu item " + item.getTitle(),
                        Toast.LENGTH_SHORT).show();
                return true;
            }
        });

        popup.show();
    }
}

Python NameError: name is not defined

Define the class before you use it:

class Something:
    def out(self):
        print("it works")

s = Something()
s.out()

You need to pass self as the first argument to all instance methods.

How can I create a Windows .exe (standalone executable) using Java/Eclipse?

Java doesn't natively allow building of an exe, that would defeat its purpose of being cross-platform.

AFAIK, these are your options:

  1. Make a runnable JAR. If the system supports it and is configured appropriately, in a GUI, double clicking the JAR will launch the app. Another option would be to write a launcher shell script/batch file which will start your JAR with the appropriate parameters

  2. There also executable wrappers - see How can I convert my Java program to an .exe file?

See also: Convert Java to EXE: Why, When, When Not and How

Deploying just HTML, CSS webpage to Tomcat

There is no real need to create a war to run it from Tomcat. You can follow these steps

  1. Create a folder in webapps folder e.g. MyApp

  2. Put your html and css in that folder and name the html file, which you want to be the starting page for your application, index.html

  3. Start tomcat and point your browser to url "http://localhost:8080/MyApp". Your index.html page will pop up in the browser

How to check if a database exists in SQL Server?

TRY THIS

IF EXISTS 
   (
     SELECT name FROM master.dbo.sysdatabases 
    WHERE name = N'New_Database'
    )
BEGIN
    SELECT 'Database Name already Exist' AS Message
END
ELSE
BEGIN
    CREATE DATABASE [New_Database]
    SELECT 'New Database is Created'
END

Google Maps: Set Center, Set Center Point and Set more points

Try using this code for v3:

gMap = new google.maps.Map(document.getElementById('map')); 
gMap.setZoom(13);      // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);

How to get javax.comm API?

Another Simple way i found in Netbeans right click on your project>libraris click add jar/folder add your comm.jar and you done.

if you dont have comm.jar download it from >>> http://llk.media.mit.edu/projects/picdev/software/javaxcomm.zip

receiver type *** for instance message is a forward declaration

There are two related error messages that may tell you something is wrong with declarations and/or imports.

The first is the one you are referring to, which can be generated by NOT putting an #import in your .m (or .pch file) while declaring an @class in your .h.

The second you might see, if you had a method in your States class like:

- (void)logout:(NSTimer *)timer

after adding the #import is this:

No visible @interface for "States" declares the selector 'logout:'

If you see this, you need to check and see if you declared your "logout" method (in this instance) in the .h file of the class you're importing or forwarding.

So in your case, you would need a:

- (void)logout:(NSTimer *)timer;

in your States class's .h to make one or both of these related errors disappear.

How to disable editing of elements in combobox for c#?

This is another method I use because changing DropDownSyle to DropDownList makes it look 3D and sometimes its just plain ugly.

You can prevent user input by handling the KeyPress event of the ComboBox like this.

private void ComboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
      e.Handled = true;
}

vuetify center items into v-flex

v-flex does not have a display flex! Inspect v-flex in your browser and you will find out it is just a simple block div.

So, you should override it with display: flex in your HTML or CSS to make it work with justify-content.

Loop through a Map with JSTL

You can loop through a hash map like this

<%
ArrayList list = new ArrayList();
TreeMap itemList=new TreeMap();
itemList.put("test", "test");
list.add(itemList);
pageContext.setAttribute("itemList", list);                            
%>

  <c:forEach items="${itemList}" var="itemrow">
   <input  type="text"  value="<c:out value='${itemrow.test}'/>"/>
  </c:forEach>               

For more JSTL functionality look here

How to select date without time in SQL

you can use like this

SELECT Convert(varchar(10), GETDATE(),120) 

CSS - Expand float child DIV height to parent's height

<div class="parent" style="height:500px;">
<div class="child-left floatLeft" style="height:100%">
</div>

<div class="child-right floatLeft" style="height:100%">
</div>
</div>

I used inline style just to give idea.

SOAP PHP fault parsing WSDL: failed to load external entity?

If you use docker there is a chance you get error because of OpenSSL default security level.

You need lower seclevel in /etc/ssl/openssl.cnf from DEFAULT@SECLEVEL=2 to DEFAULT@SECLEVEL=1

Or just add into Dockerfile

RUN sed -i "s|DEFAULT@SECLEVEL=2|DEFAULT@SECLEVEL=1|g" /etc/ssl/openssl.cnf

Source: https://github.com/dotnet/runtime/issues/30667#issuecomment-566482876

After that change I can run SoapClient without any additional options


You can verify it by run on container

curl -A 'cURL User Agent' -4 https://ewus.nfz.gov.pl/ws-broker-server-ewus/services/Auth?wsdl

How to calculate date difference in JavaScript?

var d1=new Date(2011,0,1); // jan,1 2011
var d2=new Date(); // now

var diff=d2-d1,sign=diff<0?-1:1,milliseconds,seconds,minutes,hours,days;
diff/=sign; // or diff=Math.abs(diff);
diff=(diff-(milliseconds=diff%1000))/1000;
diff=(diff-(seconds=diff%60))/60;
diff=(diff-(minutes=diff%60))/60;
days=(diff-(hours=diff%24))/24;

console.info(sign===1?"Elapsed: ":"Remains: ",
             days+" days, ",
             hours+" hours, ",
             minutes+" minutes, ",
             seconds+" seconds, ",
             milliseconds+" milliseconds.");

jquery: how to get the value of id attribute?

$('.select_continent').click(function () {
    alert($(this).attr('value'));
});

Open two instances of a file in a single Visual Studio session

to work on a two section of a one long file simply use shortcut ( Ctrl + \ ) or click on split editor window while you are on selected Tab. the icon is on top-right of the VS Code. enter image description here

ImportError: No module named xlsxwriter

Here are some easy way to get you up and running with the XlsxWriter module.The first step is to install the XlsxWriter module.The pip installer is the preferred method for installing Python modules from PyPI, the Python Package Index:

sudo pip install xlsxwriter

Note

Windows users can omit sudo at the start of the command.

Converting from Integer, to BigInteger

The method you want is BigInteger#valueOf(long val).

E.g.,

BigInteger bi = BigInteger.valueOf(myInteger.intValue());

Making a String first is unnecessary and undesired.

How to perform a for-each loop over all the files under a specified path?

Here is a better way to loop over files as it handles spaces and newlines in file names:

#!/bin/bash

find . -type f -iname "*.txt" -print0 | while IFS= read -r -d $'\0' line; do
    echo "$line"
    ls -l "$line"    
done

How do I get my solution in Visual Studio back online in TFS?

I am using Visual Studio 2017 15.4.0 version. Especially when i started use lightweight solution option, this offline thing happened to me. I tried to above solutions which are:

  1. Tried to regedit option but can not see appropriate menu options. Didn't work.
  2. Right click on solution, there is go online option and when i choose it that gives this error message: "The solution is offline because its associated Team Foundation Server is offline. Unable to determine the workspace for this solution."

Then from File -> Source Control -> Advanced -> Change Source Control. I saw my files. I select them and then chose bind option. That worked for me.

SQL Server : SUM() of multiple rows including where clauses

sounds like you want something like:

select PropertyID, SUM(Amount)
from MyTable
Where EndDate is null
Group by PropertyID

LINQ Contains Case Insensitive

You can use string.Compare

    lst.Where(x => string.Compare(x,"valueToCompare",StringComparison.InvariantCultureIgnoreCase)==0);

if you just want to check contains then use "Any"

  lst.Any(x => string.Compare(x,"valueToCompare",StringComparison.InvariantCultureIgnoreCase)==0)

REST response code for invalid data

I would recommend 422. It's not part of the main HTTP spec, but it is defined by a public standard (WebDAV) and it should be treated by browsers the same as any other 4xx status code.

From RFC 4918:

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

Get Row Index on Asp.net Rowcommand event

Or, you can use a control class instead of their types:

GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);

int RowIndex = row.RowIndex; 

How to add an element to Array and shift indexes?

I smell homework, so probably an ArrayList won't be allowed (?)

Instead of looking for a way to "shift indexes", maybe just build a new array:

int[] b = new int[a.length +1];

Then

  1. copy indexes form array a counting from zero up to insert position
  2. ...
  3. ...

//edit: copy values of course, not indexes

What is the best way to parse html in C#?

Try this script.

http://www.biterscripting.com/SS_URLs.html

When I use it with this url,

script SS_URLs.txt URL("http://stackoverflow.com/questions/56107/what-is-the-best-way-to-parse-html-in-c")

It shows me all the links on the page for this thread.

http://sstatic.net/so/all.css
http://sstatic.net/so/favicon.ico
http://sstatic.net/so/apple-touch-icon.png
.
.
.

You can modify that script to check for images, variables, whatever.

How do I configure the proxy settings so that Eclipse can download new plugins?

I installed HandyCache, in them install link on my general proxy.

In IE set proxy 127.0.0.1.

In Eclipse, Window > Preferences > General > Network Connections, set Active Provider = Native.

IPhone/IPad: How to get screen width programmatically?

This can be done in in 3 lines of code:

// grab the window frame and adjust it for orientation
UIView *rootView = [[[UIApplication sharedApplication] keyWindow] 
                                   rootViewController].view;
CGRect originalFrame = [[UIScreen mainScreen] bounds];
CGRect adjustedFrame = [rootView convertRect:originalFrame fromView:nil];

How to convert a negative number to positive?

simply multiplying by -1 works in both ways ...

>>> -10 * -1
10
>>> 10 * -1
-10

Check if element is visible in DOM

Just for the reference it should be noted that getBoundingClientRect() can work in certain cases.

For example, a simple check that the element is hidden using display: none could look somewhat like this:

var box = element.getBoundingClientRect();
var visible = box.width && box.height;

This is also handy because it also covers zero-width, zero-height and position: fixed cases. However, it shall not report elements hidden with opacity: 0 or visibility: hidden (but neither would offsetParent).

How to create radio buttons and checkbox in swift (iOS)?

Checkbox

You can create your own CheckBox control extending UIButton with Swift:

import UIKit

class CheckBox: UIButton {
    // Images
    let checkedImage = UIImage(named: "ic_check_box")! as UIImage
    let uncheckedImage = UIImage(named: "ic_check_box_outline_blank")! as UIImage
    
    // Bool property
    var isChecked: Bool = false {
        didSet {
            if isChecked == true {
                self.setImage(checkedImage, for: UIControl.State.normal)
            } else {
                self.setImage(uncheckedImage, for: UIControl.State.normal)
            }
        }
    }
        
    override func awakeFromNib() {
        self.addTarget(self, action:#selector(buttonClicked(sender:)), for: UIControl.Event.touchUpInside)
        self.isChecked = false
    }
        
    @objc func buttonClicked(sender: UIButton) {
        if sender == self {
            isChecked = !isChecked
        }
    }
}

And then add it to your views with Interface Builder:

enter image description here

Radio Buttons

Radio Buttons can be solved in a similar way.

For example, the classic gender selection Woman - Man:

enter image description here

import UIKit

class RadioButton: UIButton {
    var alternateButton:Array<RadioButton>?
    
    override func awakeFromNib() {
        self.layer.cornerRadius = 5
        self.layer.borderWidth = 2.0
        self.layer.masksToBounds = true
    }
    
    func unselectAlternateButtons() {
        if alternateButton != nil {
            self.isSelected = true
            
            for aButton:RadioButton in alternateButton! {
                aButton.isSelected = false
            }
        } else {
            toggleButton()
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        unselectAlternateButtons()
        super.touchesBegan(touches, with: event)
    }
    
    func toggleButton() {
        self.isSelected = !isSelected
    }
    
    override var isSelected: Bool {
        didSet {
            if isSelected {
                self.layer.borderColor = Color.turquoise.cgColor
            } else {
                self.layer.borderColor = Color.grey_99.cgColor
            }
        }
    }
}

You can init your radio buttons like this:

    override func awakeFromNib() {
        self.view.layoutIfNeeded()
        
        womanRadioButton.selected = true
        manRadioButton.selected = false
    }
    
    override func viewDidLoad() {
        womanRadioButton?.alternateButton = [manRadioButton!]
        manRadioButton?.alternateButton = [womanRadioButton!]
    }

Hope it helps.

CURL to access a page that requires a login from a different page

The web site likely uses cookies to store your session information. When you run

curl --user user:pass https://xyz.com/a  #works ok
curl https://xyz.com/b #doesn't work

curl is run twice, in two separate sessions. Thus when the second command runs, the cookies set by the 1st command are not available; it's just as if you logged in to page a in one browser session, and tried to access page b in a different one.

What you need to do is save the cookies created by the first command:

curl --user user:pass --cookie-jar ./somefile https://xyz.com/a

and then read them back in when running the second:

curl --cookie ./somefile https://xyz.com/b

Alternatively you can try downloading both files in the same command, which I think will use the same cookies.

How do I find which transaction is causing a "Waiting for table metadata lock" state?

I had a similar issue with Datagrip and none of these solutions worked.

Once I restarted the Datagrip Client it was no longer an issue and I could drop tables again.

Is it possible to use Visual Studio on macOS?

While Parallels is technically a VM it is capable of running games in high resolution at a high frame rate. If you run Parallels in Coherence mode it completely integrates Windows 7 into OS X and .Net framework is fully supported. So yes you can install Visual Studio on your Mac however the Apps you created would only run of windows computers unless they were web based.

How to convert .crt to .pem

I found the OpenSSL answer given above didn't work for me, but the following did, working with a CRT file sourced from windows.

openssl x509 -inform DER -in yourdownloaded.crt -out outcert.pem -text

How to restart a single container with docker-compose

It is very simple: Use the command:

docker-compose restart worker

You can set the time to wait for stop before killing the container (in seconds)

docker-compose restart -t 30 worker

Note that this will restart the container but without rebuilding it. If you want to apply your changes and then restart, take a look at the other answers.

How do I save a stream to a file in C#?

private void SaveFileStream(String path, Stream stream)
{
    var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write);
    stream.CopyTo(fileStream);
    fileStream.Dispose();
}

Finding the average of a list

as a beginner, I just coded this:

L = [15, 18, 2, 36, 12, 78, 5, 6, 9]

total = 0

def average(numbers):
    total = sum(numbers)
    total = float(total)
    return total / len(numbers)

print average(L)

java.net.SocketException: Connection reset by peer: socket write error When serving a file

I face this problem but resolution is very simple. I am writing the 1 MB file in 1024 Byte Buffer causing this issue. To Understand refer code before and After Fix.

Code with Excepion

DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }
    

After Fixes:

DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[102400];
        
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }

    

How to POST a FORM from HTML to ASPX page

In the html form, you need to supply additional viewstate variable and disable ViewState in a server page. This requires some control on both sides , though.

Form HTML:

<html><body> <form id='postForm' action='WebForm.aspx' method='POST'>
        <input type='text' name='postData' value='base-64-encoded-value' />
        <input type='hidden' name='__VIEWSTATE' value='' />  <!-- still need __VIEWSTATE, even empty one -->
    </form>

</body></html>

Note empty __VIEWSTATE.

WebForm.aspx:

<%@ Page Language="C#" AutoEventWireup="true" 
CodeBehind="WebForm.aspx.cs" Inherits="WebForm"
 EnableEventValidation="False" EnableViewState="false" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="postForm" runat="server">
        <asp:TextBox ID="postData" runat="server"></asp:TextBox>
    <div>

    </div>
    </form>
</body>
</html>

Note EnableEventValidation="False", EnableViewState="false" to prevent validation error for empty view state. Code Behind/Inherits values are not precise.

WebForm.cs:

public partial class WebForm : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string value = Encoding.Unicode.GetString(Convert.FromBase64String(this.postData.Text));
    }
}

JSP tricks to make templating easier?

Based on the same basic idea as in @Will Hartung's answer, here is my magic one-tag extensible template engine. It even includes documentation and an example :-)

WEB-INF/tags/block.tag:

<%--
    The block tag implements a basic but useful extensible template system.

    A base template consists of a block tag without a 'template' attribute.
    The template body is specified in a standard jsp:body tag, which can
    contain EL, JSTL tags, nested block tags and other custom tags, but
    cannot contain scriptlets (scriptlets are allowed in the template file,
    but only outside of the body and attribute tags). Templates can be
    full-page templates, or smaller blocks of markup included within a page.

    The template is customizable by referencing named attributes within
    the body (via EL). Attribute values can then be set either as attributes
    of the block tag element itself (convenient for short values), or by
    using nested jsp:attribute elements (better for entire blocks of markup).

    Rendering a template block or extending it in a child template is then
    just a matter of invoking the block tag with the 'template' attribute set
    to the desired template name, and overriding template-specific attributes
    as necessary to customize it.

    Attribute values set when rendering a tag override those set in the template
    definition, which override those set in its parent template definition, etc.
    The attributes that are set in the base template are thus effectively used
    as defaults. Attributes that are not set anywhere are treated as empty.

    Internally, attributes are passed from child to parent via request-scope
    attributes, which are removed when rendering is complete.

    Here's a contrived example:

    ====== WEB-INF/tags/block.tag (the template engine tag)

    <the file you're looking at right now>

    ====== WEB-INF/templates/base.jsp (base template)

    <%@ page trimDirectiveWhitespaces="true" %>
    <%@ taglib prefix="t" tagdir="/WEB-INF/tags" %>
    <t:block>
        <jsp:attribute name="title">Template Page</jsp:attribute>
        <jsp:attribute name="style">
            .footer { font-size: smaller; color: #aaa; }
            .content { margin: 2em; color: #009; }
            ${moreStyle}
        </jsp:attribute>
        <jsp:attribute name="footer">
            <div class="footer">
                Powered by the block tag
            </div>
        </jsp:attribute>
        <jsp:body>
            <html>
                <head>
                    <title>${title}</title>
                    <style>
                        ${style}
                    </style>
                </head>
                <body>
                    <h1>${title}</h1>
                    <div class="content">
                        ${content}
                    </div>
                    ${footer}
                </body>
            </html>
        </jsp:body>
    </t:block>

    ====== WEB-INF/templates/history.jsp (child template)

    <%@ page trimDirectiveWhitespaces="true" %>
    <%@ taglib prefix="t" tagdir="/WEB-INF/tags" %>
    <t:block template="base" title="History Lesson">
        <jsp:attribute name="content" trim="false">
            <p>${shooter} shot first!</p>
        </jsp:attribute>
    </t:block>

    ====== history-1977.jsp (a page using child template)

    <%@ page trimDirectiveWhitespaces="true" %>
    <%@ taglib prefix="t" tagdir="/WEB-INF/tags" %>
    <t:block template="history" shooter="Han" />

    ====== history-1997.jsp (a page using child template)

    <%@ page trimDirectiveWhitespaces="true" %>
    <%@ taglib prefix="t" tagdir="/WEB-INF/tags" %>
    <t:block template="history" title="Revised History Lesson">
        <jsp:attribute name="moreStyle">.revised { font-style: italic; }</jsp:attribute>
        <jsp:attribute name="shooter"><span class="revised">Greedo</span></jsp:attribute>
    </t:block>

--%>

<%@ tag trimDirectiveWhitespaces="true" %>
<%@ tag import="java.util.HashSet, java.util.Map, java.util.Map.Entry" %>
<%@ tag dynamic-attributes="dynattributes" %>
<%@ attribute name="template" %>
<%
    // get template name (adding default .jsp extension if it does not contain
    // any '.', and /WEB-INF/templates/ prefix if it does not start with a '/')
    String template = (String)jspContext.getAttribute("template");
    if (template != null) {
        if (!template.contains("."))
            template += ".jsp";
        if (!template.startsWith("/"))
            template = "/WEB-INF/templates/" + template;
    }
    // copy dynamic attributes into request scope so they can be accessed from included template page
    // (child is processed before parent template, so only set previously undefined attributes)
    Map<String, String> dynattributes = (Map<String, String>)jspContext.getAttribute("dynattributes");
    HashSet<String> addedAttributes = new HashSet<String>();
    for (Map.Entry<String, String> e : dynattributes.entrySet()) {
        if (jspContext.getAttribute(e.getKey(), PageContext.REQUEST_SCOPE) == null) {
            jspContext.setAttribute(e.getKey(), e.getValue(), PageContext.REQUEST_SCOPE);
            addedAttributes.add(e.getKey());
        }
    }
%>

<% if (template == null) { // this is the base template itself, so render it %>
    <jsp:doBody/>
<% } else { // this is a page using the template, so include the template instead %>
    <jsp:include page="<%= template %>" />
<% } %>

<%
    // clean up the added attributes to prevent side effect outside the current tag
    for (String key : addedAttributes) {
        jspContext.removeAttribute(key, PageContext.REQUEST_SCOPE);
    }
%>

How do I draw a set of vertical lines in gnuplot?

From the Gnuplot documentation. To draw a vertical line from the bottom to the top of the graph at x=3, use:

set arrow from 3, graph 0 to 3, graph 1 nohead

VB.NET - If string contains "value1" or "value2"

If strMyString.Contains("Something") or strMyString.Contains("Something2") Then

End if

The error indicates that the compiler thinks you want to do a bitwise OR on a Boolean and a string. Which of course won't work.

How to kill a child process after a given timeout in Bash?

# Spawn a child process:
(dosmth) & pid=$!
# in the background, sleep for 10 secs then kill that process
(sleep 10 && kill -9 $pid) &

or to get the exit codes as well:

# Spawn a child process:
(dosmth) & pid=$!
# in the background, sleep for 10 secs then kill that process
(sleep 10 && kill -9 $pid) & waiter=$!
# wait on our worker process and return the exitcode
exitcode=$(wait $pid && echo $?)
# kill the waiter subshell, if it still runs
kill -9 $waiter 2>/dev/null
# 0 if we killed the waiter, cause that means the process finished before the waiter
finished_gracefully=$?

modal View controllers - how to display and dismiss

Example in Swift, picturing the foundry's explanation above and the Apple's documentation:

  1. Basing on the Apple's documentation and the foundry's explanation above (correcting some errors), presentViewController version using delegate design pattern:

ViewController.swift

import UIKit

protocol ViewControllerProtocol {
    func dismissViewController1AndPresentViewController2()
}

class ViewController: UIViewController, ViewControllerProtocol {

    @IBAction func goToViewController1BtnPressed(sender: UIButton) {
        let vc1: ViewController1 = self.storyboard?.instantiateViewControllerWithIdentifier("VC1") as ViewController1
        vc1.delegate = self
        vc1.modalTransitionStyle = UIModalTransitionStyle.FlipHorizontal
        self.presentViewController(vc1, animated: true, completion: nil)
    }

    func dismissViewController1AndPresentViewController2() {
        self.dismissViewControllerAnimated(false, completion: { () -> Void in
            let vc2: ViewController2 = self.storyboard?.instantiateViewControllerWithIdentifier("VC2") as ViewController2
            self.presentViewController(vc2, animated: true, completion: nil)
        })
    }

}

ViewController1.swift

import UIKit

class ViewController1: UIViewController {

    var delegate: protocol<ViewControllerProtocol>!

    @IBAction func goToViewController2(sender: UIButton) {
        self.delegate.dismissViewController1AndPresentViewController2()
    }

}

ViewController2.swift

import UIKit

class ViewController2: UIViewController {

}
  1. Basing on the foundry's explanation above (correcting some errors), pushViewController version using delegate design pattern:

ViewController.swift

import UIKit

protocol ViewControllerProtocol {
    func popViewController1AndPushViewController2()
}

class ViewController: UIViewController, ViewControllerProtocol {

    @IBAction func goToViewController1BtnPressed(sender: UIButton) {
        let vc1: ViewController1 = self.storyboard?.instantiateViewControllerWithIdentifier("VC1") as ViewController1
        vc1.delegate = self
        self.navigationController?.pushViewController(vc1, animated: true)
    }

    func popViewController1AndPushViewController2() {
        self.navigationController?.popViewControllerAnimated(false)
        let vc2: ViewController2 = self.storyboard?.instantiateViewControllerWithIdentifier("VC2") as ViewController2
        self.navigationController?.pushViewController(vc2, animated: true)
    }

}

ViewController1.swift

import UIKit

class ViewController1: UIViewController {

    var delegate: protocol<ViewControllerProtocol>!

    @IBAction func goToViewController2(sender: UIButton) {
        self.delegate.popViewController1AndPushViewController2()
    }

}

ViewController2.swift

import UIKit

class ViewController2: UIViewController {

}

Twitter API - Display all tweets with a certain hashtag?

UPDATE for v1.1:

Rather than giving q="search_string" give it q="hashtag" in URL encoded form to return results with HASHTAG ONLY. So your query would become:

    GET https://api.twitter.com/1.1/search/tweets.json?q=%23freebandnames

%23 is URL encoded form of #. Try the link out in your browser and it should work.

You can optimize the query by adding since_id and max_id parameters detailed here. Hope this helps !

Note: Search API is now a OAUTH authenticated call, so please include your access_tokens to the above call

Updated

Twitter Search doc link: https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets.html

How to select id with max date group by category in PostgreSQL?

Another approach is to use the first_value window function: http://sqlfiddle.com/#!12/7a145/14

SELECT DISTINCT
  first_value("id") OVER (PARTITION BY "category" ORDER BY "date" DESC) 
FROM Table1
ORDER BY 1;

... though I suspect hims056's suggestion will typically perform better where appropriate indexes are present.

A third solution is:

SELECT
  id
FROM (
  SELECT
    id,
    row_number() OVER (PARTITION BY "category" ORDER BY "date" DESC) AS rownum
  FROM Table1
) x
WHERE rownum = 1;

Redirect to an external URL from controller action in Spring MVC

Looking into the actual implementation of UrlBasedViewResolver and RedirectView the redirect will always be contextRelative if your redirect target starts with /. So also sending a //yahoo.com/path/to/resource wouldn't help to get a protocol relative redirect.

So to achieve what you are trying you could do something like:

@RequestMapping(method = RequestMethod.POST)
public String processForm(HttpServletRequest request, LoginForm loginForm, 
                          BindingResult result, ModelMap model) 
{
    String redirectUrl = request.getScheme() + "://www.yahoo.com";
    return "redirect:" + redirectUrl;
}

How do I restart my C# WinForm Application?

I might be late to the party but here is my simple solution and it works like a charm with every application I have:

        try
        {
            //run the program again and close this one
            Process.Start(Application.StartupPath + "\\blabla.exe"); 
            //or you can use Application.ExecutablePath

            //close this one
            Process.GetCurrentProcess().Kill();
        }
        catch
        { }

failed to load ad : 3

This is a simple WORKAROUND (no solution):

You can install a mediation such as InMobi: https://developers.google.com/admob/android/mediation/inmobi

In this way, if for whatever reason admob is not showing you ads, you can still show them from other ad networks.

What is the difference between max-device-width and max-width for mobile web?

max-width is the width of the target display area, e.g. the browser; max-device-width is the width of the device's entire rendering area, i.e. the actual device screen.

• If you are using the max-device-width, when you change the size of the browser window on your desktop, the CSS style won't change to different media query setting;

• If you are using the max-width, when you change the size of the browser on your desktop, the CSS will change to different media query setting and you might be shown with the styling for mobiles, such as touch-friendly menus.

How can I create a dynamically sized array of structs?

If you want to grow the array dynamically, you should use malloc() to dynamically allocate some fixed amount of memory, and then use realloc() whenever you run out. A common technique is to use an exponential growth function such that you allocate some small fixed amount and then make the array grow by duplicating the allocated amount.

Some example code would be:

size = 64; i = 0;
x = malloc(sizeof(words)*size); /* enough space for 64 words */
while (read_words()) {
    if (++i > size) {
        size *= 2;
        x = realloc(sizeof(words) * size);
    }
}
/* done with x */
free(x);

Add row to query result using select

You use it like this:

SELECT  age, name
FROM    users
UNION
SELECT  25 AS age, 'Betty' AS name

Use UNION ALL to allow duplicates: if there is a 25-years old Betty among your users, the second query will not select her again with mere UNION.

How do I do base64 encoding on iOS?

iOS includes built in support for base64 encoding and decoding. If you look at resolv.h you should see the two functions b64_ntop and b64_pton . The Square SocketRocket library provides a reasonable example of how to use these functions from objective-c.

These functions are pretty well tested and reliable - unlike many of the implementations you may find in random internet postings. Don't forget to link against libresolv.dylib.

enum - getting value of enum on string conversion

I implemented access using the following

class D(Enum):
    x = 1
    y = 2

    def __str__(self):
        return '%s' % self.value

now I can just do

print(D.x) to get 1 as result.

You can also use self.name in case you wanted to print x instead of 1.

Appending items to a list of lists in python

import csv
cols = [' V1', ' I1'] # define your columns here, check the spaces!
data = [[] for col in cols] # this creates a list of **different** lists, not a list of pointers to the same list like you did in [[]]*len(positions) 
with open('data.csv', 'r') as f:
    for rec in csv.DictReader(f):
        for l, col in zip(data, cols):
            l.append(float(rec[col]))
print data

# [[3.0, 3.0], [0.01, 0.01]]

Force page scroll position to top at page refresh in HTML

This is one of the best way to do so:

_x000D_
_x000D_
<script>
$(window).on('beforeunload', function() {
  $('body').hide();
  $(window).scrollTop(0);
});
</script>
_x000D_
_x000D_
_x000D_

SSL "Peer Not Authenticated" error with HttpClient 4.1

This is thrown when

... the peer was not able to identify itself (for example; no certificate, the particular cipher suite being used does not support authentication, or no peer authentication was established during SSL handshaking) this exception is thrown.

Probably the cause of this exception (where is the stacktrace) will show you why this exception is thrown. Most likely the default keystore shipped with Java does not contain (and trust) the root certificate of the TTP that is being used.

The answer is to retrieve the root certificate (e.g. from your browsers SSL connection), import it into the cacerts file and trust it using keytool which is shipped by the Java JDK. Otherwise you will have to assign another trust store programmatically.

YouTube: How to present embed video with sound muted

For me works using &autoplay=1&mute=1

How do I flush the PRINT buffer in TSQL?

Use the RAISERROR function:

RAISERROR( 'This message will show up right away...',0,1) WITH NOWAIT

You shouldn't completely replace all your prints with raiserror. If you have a loop or large cursor somewhere just do it once or twice per iteration or even just every several iterations.

Also: I first learned about RAISERROR at this link, which I now consider the definitive source on SQL Server Error handling and definitely worth a read:
http://www.sommarskog.se/error-handling-I.html

In what cases do I use malloc and/or new?

Always use new in C++. If you need a block of untyped memory, you can use operator new directly:

void *p = operator new(size);
   ...
operator delete(p);

How can I pass a parameter to a Java Thread?

For Anonymous classes:

In response to question edits here is how it works for Anonymous classes

   final X parameter = ...; // the final is important
   Thread t = new Thread(new Runnable() {
       p = parameter;
       public void run() { 
         ...
       };
   t.start();

Named classes:

You have a class that extends Thread (or implements Runnable) and a constructor with the parameters you'd like to pass. Then, when you create the new thread, you have to pass in the arguments, and then start the thread, something like this:

Thread t = new MyThread(args...);
t.start();

Runnable is a much better solution than Thread BTW. So I'd prefer:

   public class MyRunnable implements Runnable {
      private X parameter;
      public MyRunnable(X parameter) {
         this.parameter = parameter;
      }

      public void run() {
      }
   }
   Thread t = new Thread(new MyRunnable(parameter));
   t.start();

This answer is basically the same as this similar question: How to pass parameters to a Thread object

How do I add a margin between bootstrap columns without wrapping

You should work with padding on the inner container rather than with margin. Try this!

HTML

<div class="row info-panel">
    <div class="col-md-4" id="server_1">
       <div class="server-action-menu">
           Server 1
       </div>
   </div>
</div>

CSS

.server-action-menu {
    background-color: transparent;
    background-image: linear-gradient(to bottom, rgba(30, 87, 153, 0.2) 0%, rgba(125, 185, 232, 0) 100%);
    background-repeat: repeat;
    border-radius:10px;
    padding: 5px;
}

Cannot issue data manipulation statements with executeQuery()

executeQuery() returns a ResultSet. I'm not as familiar with Java/MySQL, but to create indexes you probably want a executeUpdate().

groovy: safely find a key in a map and return its value

The whole point of using Maps is direct access. If you know for sure that the value in a map will never be Groovy-false, then you can do this:

def mymap = [name:"Gromit", likes:"cheese", id:1234]
def key = "likes"

if(mymap[key]) {
    println mymap[key]
}

However, if the value could potentially be Groovy-false, you should use:

if(mymap.containsKey(key)) {
    println mymap[key]
}

The easiest solution, though, if you know the value isn't going to be Groovy-false (or you can ignore that), and want a default value, is like this:

def value = mymap[key] ?: "default"

All three of these solutions are significantly faster than your examples, because they don't scan the entire map for keys. They take advantage of the HashMap (or LinkedHashMap) design that makes direct key access nearly instantaneous.

/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

In my case LD_LIBRARY_PATH had /usr/lib64 first before /usr/local/lib64. (I was builing llvm 3.9).
The new gcc compiler that I installed to compile llvm 3.9 had libraries using newer GLIBCXX libraries under /usr/local/lib64 So I fixed LD_LIBRARY_PATH for the linker to see /usr/local/lib64 first.
That solved this problem.

Using Mockito with multiple calls to the same method with the same arguments

doReturn( value1, value2, value3 ).when( method-call )

How can I send an inner <div> to the bottom of its parent <div>?

<div style="width: 200px; height: 150px; border: 1px solid black;position:relative">
    <div style="width: 100%; height: 50px; border: 1px solid red;position:absolute;bottom:0">
    </div>
</div>

Angular ng-if="" with multiple arguments

For people looking to do if statements with multiple 'or' values.

<div ng-if="::(a || b || c || d || e || f)"><div>

How to include a sub-view in Blade templates?

When you use laravel modules, you may add the name's module:

@include('cimple::shared.posts_list')

Submit form with Enter key without submit button?

Jay Gilford's answer will work, but I think really the easiest way is to just slap a display: none; on a submit button in the form.

How do you validate a URL with a regular expression in Python?

Here's the complete regexp to parse a URL.

(?:http://(?:(?:(?:(?:(?:[a-zA-Z\d](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?)\.
)*(?:[a-zA-Z](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?))|(?:(?:\d+)(?:\.(?:\d+)
){3}))(?::(?:\d+))?)(?:/(?:(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F
\d]{2}))|[;:@&=])*)(?:/(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{
2}))|[;:@&=])*))*)(?:\?(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{
2}))|[;:@&=])*))?)?)|(?:ftp://(?:(?:(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?
:%[a-fA-F\d]{2}))|[;?&=])*)(?::(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-
fA-F\d]{2}))|[;?&=])*))?@)?(?:(?:(?:(?:(?:[a-zA-Z\d](?:(?:[a-zA-Z\d]|-
)*[a-zA-Z\d])?)\.)*(?:[a-zA-Z](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?))|(?:(?
:\d+)(?:\.(?:\d+)){3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z\d])?))|(?:(?:\d+)(?:
\.(?:\d+)){3}))(?::(?:\d+))?)(?:(?:/(?:(?:(?:(?:(?:[a-zA-Z\d\$\-_.!~*'
(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*)(?:/(?:(?:(?:[a-zA-Z\d\$\-_.!~*'(),
])|(?:%[a-fA-F\d]{2})|[:@&=+])*))*)?)))?)|(?:/(?:(?:(?:(?:(?:[a-zA-Z\d
\$\-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*)(?:/(?:(?:(?:[a-zA-Z\d\$\
-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*))*)?))|(?:(?:(?:(?:(?:[a-zA-
Z\d\$\-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*)(?:/(?:(?:(?:[a-zA-Z\d
\$\-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*))*)?)))

Given its complexibility, I think you should go the urlparse way.

For completeness, here's the pseudo-BNF of the above regex (as a documentation):

; The generic form of a URL is:

genericurl     = scheme ":" schemepart

; Specific predefined schemes are defined here; new schemes
; may be registered with IANA

url            = httpurl | ftpurl | newsurl |
                 nntpurl | telneturl | gopherurl |
                 waisurl | mailtourl | fileurl |
                 prosperourl | otherurl

; new schemes follow the general syntax
otherurl       = genericurl

; the scheme is in lower case; interpreters should use case-ignore
scheme         = 1*[ lowalpha | digit | "+" | "-" | "." ]
schemepart     = *xchar | ip-schemepart


; URL schemeparts for ip based protocols:

ip-schemepart  = "//" login [ "/" urlpath ]

login          = [ user [ ":" password ] "@" ] hostport
hostport       = host [ ":" port ]
host           = hostname | hostnumber
hostname       = *[ domainlabel "." ] toplabel
domainlabel    = alphadigit | alphadigit *[ alphadigit | "-" ] alphadigit
toplabel       = alpha | alpha *[ alphadigit | "-" ] alphadigit
alphadigit     = alpha | digit
hostnumber     = digits "." digits "." digits "." digits
port           = digits
user           = *[ uchar | ";" | "?" | "&" | "=" ]
password       = *[ uchar | ";" | "?" | "&" | "=" ]
urlpath        = *xchar    ; depends on protocol see section 3.1

; The predefined schemes:

; FTP (see also RFC959)

ftpurl         = "ftp://" login [ "/" fpath [ ";type=" ftptype ]]
fpath          = fsegment *[ "/" fsegment ]
fsegment       = *[ uchar | "?" | ":" | "@" | "&" | "=" ]
ftptype        = "A" | "I" | "D" | "a" | "i" | "d"

; FILE

fileurl        = "file://" [ host | "localhost" ] "/" fpath

; HTTP

httpurl        = "http://" hostport [ "/" hpath [ "?" search ]]
hpath          = hsegment *[ "/" hsegment ]
hsegment       = *[ uchar | ";" | ":" | "@" | "&" | "=" ]
search         = *[ uchar | ";" | ":" | "@" | "&" | "=" ]

; GOPHER (see also RFC1436)

gopherurl      = "gopher://" hostport [ / [ gtype [ selector
                 [ "%09" search [ "%09" gopher+_string ] ] ] ] ]
gtype          = xchar
selector       = *xchar
gopher+_string = *xchar

; MAILTO (see also RFC822)

mailtourl      = "mailto:" encoded822addr
encoded822addr = 1*xchar               ; further defined in RFC822

; NEWS (see also RFC1036)

newsurl        = "news:" grouppart
grouppart      = "*" | group | article
group          = alpha *[ alpha | digit | "-" | "." | "+" | "_" ]
article        = 1*[ uchar | ";" | "/" | "?" | ":" | "&" | "=" ] "@" host

; NNTP (see also RFC977)

nntpurl        = "nntp://" hostport "/" group [ "/" digits ]

; TELNET

telneturl      = "telnet://" login [ "/" ]

; WAIS (see also RFC1625)

waisurl        = waisdatabase | waisindex | waisdoc
waisdatabase   = "wais://" hostport "/" database
waisindex      = "wais://" hostport "/" database "?" search
waisdoc        = "wais://" hostport "/" database "/" wtype "/" wpath
database       = *uchar
wtype          = *uchar
wpath          = *uchar

; PROSPERO

prosperourl    = "prospero://" hostport "/" ppath *[ fieldspec ]
ppath          = psegment *[ "/" psegment ]
psegment       = *[ uchar | "?" | ":" | "@" | "&" | "=" ]
fieldspec      = ";" fieldname "=" fieldvalue
fieldname      = *[ uchar | "?" | ":" | "@" | "&" ]
fieldvalue     = *[ uchar | "?" | ":" | "@" | "&" ]

; Miscellaneous definitions

lowalpha       = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" |
                 "i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" |
                 "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" |
                 "y" | "z"
hialpha        = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" |
                 "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" |
                 "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z"
alpha          = lowalpha | hialpha
digit          = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" |
                 "8" | "9"
safe           = "$" | "-" | "_" | "." | "+"
extra          = "!" | "*" | "'" | "(" | ")" | ","
national       = "{" | "}" | "|" | "\" | "^" | "~" | "[" | "]" | "`"
punctuation    = "" | "#" | "%" | 


reserved       = ";" | "/" | "?" | ":" | "@" | "&" | "="
hex            = digit | "A" | "B" | "C" | "D" | "E" | "F" |
                 "a" | "b" | "c" | "d" | "e" | "f"
escape         = "%" hex hex

unreserved     = alpha | digit | safe | extra
uchar          = unreserved | escape
xchar          = unreserved | reserved | escape
digits         = 1*digit

How do you count the number of occurrences of a certain substring in a SQL varchar?

Perhaps you should not store data that way. It is a bad practice to ever store a comma delimited list in a field. IT is very inefficient for querying. This should be a related table.

Remove all the elements that occur in one list from another

Alternate Solution :

reduce(lambda x,y : filter(lambda z: z!=y,x) ,[2,3,5,8],[1,2,6,8])

How do I test which class an object is in Objective-C?

You also can use

NSString *className = [[myObject class] description]; 

on any NSObject

Batch file to move files to another directory

Try:

move "C:\files\*.txt" "C:\txt"

Rename file with Git

You can rename a file using git's mv command:

$ git mv file_from file_to

Example:

$ git mv helo.txt hello.txt

$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   renamed:    helo.txt -> hello.txt
#

$ git commit -m "renamed helo.txt to hello.txt"
[master 14c8c4f] renamed helo.txt to hello.txt
 1 files changed, 0 insertions(+), 0 deletions(-)
 rename helo.txt => hello.txt (100%)

What is the difference between sscanf or atoi to convert a string to an integer?

You have 3 choices:

  1. atoi

This is probably the fastest if you're using it in performance-critical code, but it does no error reporting. If the string does not begin with an integer, it will return 0. If the string contains junk after the integer, it will convert the initial part and ignore the rest. If the number is too big to fit in int, the behaviour is unspecified.

  1. sscanf

Some error reporting, and you have a lot of flexibility for what type to store (signed/unsigned versions of char/short/int/long/long long/size_t/ptrdiff_t/intmax_t).

The return value is the number of conversions that succeed, so scanning for "%d" will return 0 if the string does not begin with an integer. You can use "%d%n" to store the index of the first character after the integer that's read in another variable, and thereby check to see if the entire string was converted or if there's junk afterwards. However, like atoi, behaviour on integer overflow is unspecified.

  1. strtol and family

Robust error reporting, provided you set errno to 0 before making the call. Return values are specified on overflow and errno will be set. You can choose any number base from 2 to 36, or specify 0 as the base to auto-interpret leading 0x and 0 as hex and octal, respectively. Choices of type to convert to are signed/unsigned versions of long/long long/intmax_t.

If you need a smaller type you can always store the result in a temporary long or unsigned long variable and check for overflow yourself.

Since these functions take a pointer to pointer argument, you also get a pointer to the first character following the converted integer, for free, so you can tell if the entire string was an integer or parse subsequent data in the string if needed.


Personally, I would recommend the strtol family for most purposes. If you're doing something quick-and-dirty, atoi might meet your needs.

As an aside, sometimes I find I need to parse numbers where leading whitespace, sign, etc. are not supposed to be accepted. In this case it's pretty damn easy to roll your own for loop, eg.,

for (x=0; (unsigned)*s-'0'<10; s++) 
    x=10*x+(*s-'0');

Or you can use (for robustness):

if (isdigit(*s))
    x=strtol(s, &s, 10);
else /* error */ 

Invoke JSF managed bean action on page load

@PostConstruct is run ONCE in first when Bean Created. the solution is create a Unused property and Do your Action in Getter method of this property and add this property to your .xhtml file like this :

<h:inputHidden  value="#{loginBean.loginStatus}"/>

and in your bean code:

public void setLoginStatus(String loginStatus) {
    this.loginStatus = loginStatus;
}

public String getLoginStatus()  {
    // Do your stuff here.
    return loginStatus;
}

Boto3 to download all files from a S3 Bucket

I'm currently achieving the task, by using the following

#!/usr/bin/python
import boto3
s3=boto3.client('s3')
list=s3.list_objects(Bucket='bucket')['Contents']
for s3_key in list:
    s3_object = s3_key['Key']
    if not s3_object.endswith("/"):
        s3.download_file('bucket', s3_object, s3_object)
    else:
        import os
        if not os.path.exists(s3_object):
            os.makedirs(s3_object)

Although, it does the job, I'm not sure its good to do this way. I'm leaving it here to help other users and further answers, with better manner of achieving this

How to write a test which expects an Error to be thrown in Jasmine?

In my case the function throwing error was async so I followed here:

await expectAsync(asyncFunction()).toBeRejected();
await expectAsync(asyncFunction()).toBeRejectedWithError(...);

How do you check if a variable is an array in JavaScript?

In Crockford's JavaScript The Good Parts, there is a function to check if the given argument is an array:

var is_array = function (value) {
    return value &&
        typeof value === 'object' &&
        typeof value.length === 'number' &&
        typeof value.splice === 'function' &&
        !(value.propertyIsEnumerable('length'));
};

He explains:

First, we ask if the value is truthy. We do this to reject null and other falsy values. Second, we ask if the typeof value is 'object'. This will be true for objects, arrays, and (weirdly) null. Third, we ask if the value has a length property that is a number. This will always be true for arrays, but usually not for objects. Fourth, we ask if the value contains a splice method. This again will be true for all arrays. Finally, we ask if the length property is enumerable (will length be produced by a for in loop?). That will be false for all arrays. This is the most reliable test for arrayness that I have found. It is unfortunate that it is so complicated.

How to pass the password to su/sudo/ssh without overriding the TTY?

I've got:

ssh user@host bash -c "echo mypass | sudo -S mycommand"

Works for me.

How to get a complete list of object's methods and attributes?

For the complete list of attributes, the short answer is: no. The problem is that the attributes are actually defined as the arguments accepted by the getattr built-in function. As the user can reimplement __getattr__, suddenly allowing any kind of attribute, there is no possible generic way to generate that list. The dir function returns the keys in the __dict__ attribute, i.e. all the attributes accessible if the __getattr__ method is not reimplemented.

For the second question, it does not really make sense. Actually, methods are callable attributes, nothing more. You could though filter callable attributes, and, using the inspect module determine the class methods, methods or functions.

Getting list of parameter names inside python function

Well we don't actually need inspect here.

>>> func = lambda x, y: (x, y)
>>> 
>>> func.__code__.co_argcount
2
>>> func.__code__.co_varnames
('x', 'y')
>>>
>>> def func2(x,y=3):
...  print(func2.__code__.co_varnames)
...  pass # Other things
... 
>>> func2(3,3)
('x', 'y')
>>> 
>>> func2.__defaults__
(3,)

For Python 2.5 and older, use func_code instead of __code__, and func_defaults instead of __defaults__.

How to get Enum Value from index in Java?

I recently had the same problem and used the solution provided by Harry Joy. That solution only works with with zero-based enumaration though. I also wouldn't consider it save as it doesn't deal with indexes that are out of range.

The solution I ended up using might not be as simple but it's completely save and won't hurt the performance of your code even with big enums:

public enum Example {

    UNKNOWN(0, "unknown"), ENUM1(1, "enum1"), ENUM2(2, "enum2"), ENUM3(3, "enum3");

    private static HashMap<Integer, Example> enumById = new HashMap<>();
    static {
        Arrays.stream(values()).forEach(e -> enumById.put(e.getId(), e));
    }

    public static Example getById(int id) {
        return enumById.getOrDefault(id, UNKNOWN);
    }

    private int id;
    private String description;

    private Example(int id, String description) {
        this.id = id;
        this.description= description;
    }

    public String getDescription() {
        return description;
    }

    public int getId() {
        return id;
    }
}

If you are sure that you will never be out of range with your index and you don't want to use UNKNOWN like I did above you can of course also do:

public static Example getById(int id) {
        return enumById.get(id);
}

How can I change the Bootstrap default font family using font from Google?

I am using React Bootstrap, which is based on Bootstrap 4. The approach is to use Sass, simliar to Nelson Rothermel's answer above.

The idea is to override Bootstraps Sass variable for font family in your custom Sass file. If you are using Google Fonts, then make sure you import it at the top of your custom Sass file.

For example, my custom Sass file is called custom.sass with the following content:

@import url('https://fonts.googleapis.com/css2?family=Dancing+Script&display=swap');
   
$font-family-sans-serif: "Dancing Script", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji" !default;

I simply added the font I want to the front of the default values, which can be found in ..\node_modules\boostrap\dist\scss\_variables.scss.

How the custom.scss file is used is shown here, which is obtained from here, which is obtained from here...

Because the React app is created by the Create-React-App utility, there's no need to go through all the crufts like Gulp; I just saved the files and React will compile the Sass for me automagically behind the scene.

Mongodb: failed to connect to server on first connect

Adding one more answer as the solution is from different contexts:

MongoDb Atlas problem solution

I connected to MongoDB Atlas and whitelisted my machine's IP by following the below steps:

  • Go to the security tab

the security tab

  • Go to the network access tab under the security tab

network access tab under security tab

  • Go to the IP whitelist tab

IP whitelist tab


Spring @Autowired and @Qualifier

The @Qualifier annotation is used to resolve the autowiring conflict, when there are multiple beans of same type.

The @Qualifier annotation can be used on any class annotated with @Component or on methods annotated with @Bean. This annotation can also be applied on constructor arguments or method parameters.

Ex:-

public interface Vehicle {
     public void start();
     public void stop();
}

There are two beans, Car and Bike implements Vehicle interface

@Component(value="car")
public class Car implements Vehicle {

     @Override
     public void start() {
           System.out.println("Car started");
     }

     @Override
     public void stop() {
           System.out.println("Car stopped");
     }
 }

@Component(value="bike")
public class Bike implements Vehicle {

     @Override
     public void start() {
          System.out.println("Bike started");
     }

     @Override
     public void stop() {
          System.out.println("Bike stopped");
     }
}

Injecting Bike bean in VehicleService using @Autowired with @Qualifier annotation. If you didn't use @Qualifier, it will throw NoUniqueBeanDefinitionException.

@Component
public class VehicleService {

    @Autowired
    @Qualifier("bike")
    private Vehicle vehicle;

    public void service() {
         vehicle.start();
         vehicle.stop();
    }
}

Reference:- @Qualifier annotation example

How to use tick / checkmark symbol (?) instead of bullets in unordered list?

<ul>
  <li>this is my text</li>
  <li>this is my text</li>
  <li>this is my text</li>
  <li>this is my text</li>
  <li>this is my text</li>
</ul>

you can use this simple css style

ul {
     list-style-type: '\2713';
   }

How to call javascript function from asp.net button click event

If you don't need to initiate a post back when you press this button, then making the overhead of a server control isn't necesary.

<input id="addButton" type="button" value="Add" />

<script type="text/javascript" language="javascript">
     $(document).ready(function()
     {
         $('#addButton').click(function() 
         { 
             showDialog('#addPerson'); 
         });
     });
</script>

If you still need to be able to do a post back, you can conditionally stop the rest of the button actions with a little different code:

<asp:Button ID="buttonAdd" runat="server" Text="Add" />

<script type="text/javascript" language="javascript">
     $(document).ready(function()
     {
         $('#<%= buttonAdd.ClientID %>').click(function(e) 
         { 
             showDialog('#addPerson');

             if(/*Some Condition Is Not Met*/) 
                return false;
         });
     });
</script>

How much overhead does SSL impose?

Order of magnitude: zero.

In other words, you won't see your throughput cut in half, or anything like it, when you add TLS. Answers to the "duplicate" question focus heavily on application performance, and how that compares to SSL overhead. This question specifically excludes application processing, and seeks to compare non-SSL to SSL only. While it makes sense to take a global view of performance when optimizing, that is not what this question is asking.

The main overhead of SSL is the handshake. That's where the expensive asymmetric cryptography happens. After negotiation, relatively efficient symmetric ciphers are used. That's why it can be very helpful to enable SSL sessions for your HTTPS service, where many connections are made. For a long-lived connection, this "end-effect" isn't as significant, and sessions aren't as useful.


Here's an interesting anecdote. When Google switched Gmail to use HTTPS, no additional resources were required; no network hardware, no new hosts. It only increased CPU load by about 1%.

Get Hours and Minutes (HH:MM) from date

Here is syntax for showing hours and minutes for a field coming out of a SELECT statement. In this example, the SQL field is named "UpdatedOnAt" and is a DateTime. Tested with MS SQL 2014.

SELECT Format(UpdatedOnAt ,'hh:mm') as UpdatedOnAt from MyTable

I like the format that shows the day of the week as a 3-letter abbreviation, and includes the seconds:

SELECT Format(UpdatedOnAt ,'ddd hh:mm:ss') as UpdatedOnAt from MyTable

The "as UpdatedOnAt" suffix is optional. It gives you a column heading equal tot he field you were selecting to begin with.

DISABLE the Horizontal Scroll

Try adding this to your CSS

html, body {
    max-width: 100%;
    overflow-x: hidden;
}

How to open a new form from another form

I would use a value that gets set when more button get pushed closed the first dialog and then have the original form test the value and then display the the there dialog.

For the Ex

  1. Create three windows froms
  2. Form1 Form2 Form3
  3. Add One button to Form1
  4. Add Two buttons to form2

Form 1 Code

 public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private bool DrawText = false;

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 f2 = new Form2();
        f2.ShowDialog();
        if (f2.ShowMoreActions)
        {
            Form3 f3 = new Form3();
            f3.ShowDialog();
        }

    }

Form2 code

 public partial class Form2 : Form
 {
        public Form2()
        {
            InitializeComponent();
        }

        public bool ShowMoreActions = false;
        private void button1_Click(object sender, EventArgs e)
        {
            ShowMoreActions = true;
            this.Close();
        }


        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }

Leave form3 as is

Python: print a generator expression?

Or you can always map over an iterator, without the need to build an intermediate list:

>>> _ = map(sys.stdout.write, (x for x in string.letters if x in (y for y in "BigMan on campus")))
acgimnopsuBM

Pass form data to another page with php

The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

index.php

<html>
<body>

<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>

</body>
</html> 

site2.php

 <html>
 <body>

 Hello <?php echo $_POST["name"]; ?>!<br>
 Your mail is <?php echo $_POST["mail"]; ?>.

 </body>
 </html> 

output

Hello "name" !

Your email is "[email protected]" .

How do I make the return type of a method generic?

You need to make it a generic method, like this:

public static T ConfigSetting<T>(string settingName)
{  
    return /* code to convert the setting to T... */
}

But the caller will have to specify the type they expect. You could then potentially use Convert.ChangeType, assuming that all the relevant types are supported:

public static T ConfigSetting<T>(string settingName)
{  
    object value = ConfigurationManager.AppSettings[settingName];
    return (T) Convert.ChangeType(value, typeof(T));
}

I'm not entirely convinced that all this is a good idea, mind you...

How to cache data in a MVC application

Reference the System.Web dll in your model and use System.Web.Caching.Cache

    public string[] GetNames()
    {
      string[] names = Cache["names"] as string[];
      if(names == null) //not in cache
      {
        names = DB.GetNames();
        Cache["names"] = names;
      }
      return names;
    }

A bit simplified but I guess that would work. This is not MVC specific and I have always used this method for caching data.

Rounded Corners Image in Flutter

This is the code that I have used.

Container(
      width: 200.0,
      height: 200.0,
      decoration: BoxDecoration(
        image: DecorationImage(
         image: NetworkImage('Network_Image_Link')),
        color: Colors.blue,
   borderRadius: BorderRadius.all(Radius.circular(25.0)),
      ),
    ),

Thank you!!!

Sublime text 3. How to edit multiple lines?

Use CTRL+D at each line and it will find the matching words and select them then you can use multiple cursors.

You can also use find to find all the occurrences and then it would be multiple cursors too.

Disabling tab focus on form elements

A simple way is to put tabindex="-1" in the field(s) you don't want to be tabbed to. Eg

<input type="text" tabindex="-1" name="f1">

How do you convert between 12 hour time and 24 hour time in PHP?

// 24-hour time to 12-hour time 
$time_in_12_hour_format  = date("g:i a", strtotime("13:30"));

// 12-hour time to 24-hour time 
$time_in_24_hour_format  = date("H:i", strtotime("1:30 PM"));

Sum across multiple columns with dplyr

dplyr >= 1.0.0

In newer versions of dplyr you can use rowwise() along with c_across to perform row-wise aggregation for functions that do not have specific row-wise variants, but if the row-wise variant exists it should be faster.

Since rowwise() is just a special form of grouping and changes the way verbs work you'll likely want to pipe it to ungroup() after doing your row-wise operation.

To select a range of rows:

df %>%
  dplyr::rowwise() %>% 
  dplyr::mutate(sumrange = sum(dplyr::c_across(x1:x5), na.rm = T))
# %>% dplyr::ungroup() # you'll likely want to ungroup after using rowwise()

To select rows by type:

df %>%
  dplyr::rowwise() %>% 
  dplyr::mutate(sumnumeric = sum(c_across(where(is.numeric)), na.rm = T))
# %>% dplyr::ungroup() # you'll likely want to ungroup after using rowwise()

In your specific case a row-wise variant exists so you can do the following (note the use of across instead):

df %>%
  dplyr::mutate(sumrow = rowSums(dplyr::across(x1:x5), na.rm = T))

For more information see the page on rowwise.

Java Try Catch Finally blocks without Catch

The finally block is always run after the try block ends, whether try ends normally or abnormally due to an exception, er, throwable.

If an exception is thrown by any of the code within the try block, then the current method simply re-throws (or continues to throw) the same exception (after running the finally block).

If the finally block throws an exception / error / throwable, and there is already a pending throwable, it gets ugly. Quite frankly, I forget exactly what happens (so much for my certification years ago). I think both throwables get linked together, but there is some special voodoo you have to do (i.e. - a method call I would have to look up) to get the original problem before the "finally" barfed, er, threw up.

Incidentally, try/finally is a pretty common thing to do for resource management, since java has no destructors.

E.g. -

r = new LeakyThing();
try { useResource( r); }
finally { r.release(); }  // close, destroy, etc

"Finally", one more tip: if you do bother to put in a catch, either catch specific (expected) throwable subclasses, or just catch "Throwable", not "Exception", for a general catch-all error trap. Too many problems, such as reflection goofs, throw "Errors", rather than "Exceptions", and those will slip right by any "catch all" coded as:

catch ( Exception e) ...  // doesn't really catch *all*, eh?

do this instead:

catch ( Throwable t) ...

How to send a simple string between two programs using pipes?

A regular pipe can only connect two related processes. It is created by a process and will vanish when the last process closes it.

A named pipe, also called a FIFO for its behavior, can be used to connect two unrelated processes and exists independently of the processes; meaning it can exist even if no one is using it. A FIFO is created using the mkfifo() library function.

Example

writer.c

#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
    int fd;
    char * myfifo = "/tmp/myfifo";

    /* create the FIFO (named pipe) */
    mkfifo(myfifo, 0666);

    /* write "Hi" to the FIFO */
    fd = open(myfifo, O_WRONLY);
    write(fd, "Hi", sizeof("Hi"));
    close(fd);

    /* remove the FIFO */
    unlink(myfifo);

    return 0;
}

reader.c

#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>

#define MAX_BUF 1024

int main()
{
    int fd;
    char * myfifo = "/tmp/myfifo";
    char buf[MAX_BUF];

    /* open, read, and display the message from the FIFO */
    fd = open(myfifo, O_RDONLY);
    read(fd, buf, MAX_BUF);
    printf("Received: %s\n", buf);
    close(fd);

    return 0;
}

Note: Error checking was omitted from the above code for simplicity.

How to convert C++ Code to C

Maybe good ol' cfront will do?

Creating a new user and password with Ansible

This is how it worked for me

- hosts: main
  vars:
  # created with:
  #  python -c "from passlib.hash import sha512_crypt; print sha512_crypt.encrypt('<password>')"
  # above command requires the PassLib library: sudo pip install passlib
  - password: '$6$rounds=100000$H/83rErWaObIruDw$DEX.DgAuZuuF.wOyCjGHnVqIetVt3qRDnTUvLJHBFKdYr29uVYbfXJeHg.IacaEQ08WaHo9xCsJQgfgZjqGZI0'

tasks:

- user: name=spree password={{password}} groups=sudo,www-data shell=/bin/bash append=yes
  sudo: yes

Visual Studio Code includePath

I tried this and now working Configuration for c_cpp_properties.json

{
"configurations": [
    {
        "name": "Win32",
        "compilerPath": "C:/MinGW/bin/g++.exe",
        "includePath": [
            "C:/MinGW/lib/gcc/mingw32/9.2.0/include/c++"
        ],
        "defines": [
            "_DEBUG",
            "UNICODE",
            "_UNICODE"
        ],
        "cStandard": "c17",
        "cppStandard": "c++17",
        "intelliSenseMode": "windows-gcc-x64"
    }
],
"version": 4
  }

task.json configuration File

{
"version": "2.0.0",
"tasks": [
    {
        "type": "cppbuild",
        "label": "C/C++: g++.exe build active file",
        "command": "C:\\MinGW\\bin\\g++.exe",
        "args": [
            "-g",
            "${file}",
            "-o",
            "${fileDirname}\\${fileBasenameNoExtension}.exe"
        ],
        "options": {
            "cwd": "C:\\MinGW\\bin"
        },
        "problemMatcher": [
            "$gcc"
        ],
        "group": {
            "kind": "build",
            "isDefault": true
        },
        "detail": "compiler: C:\\MinGW\\bin\\g++.exe"
    }
]}

How to get a matplotlib Axes instance to plot to?

You can either

fig, ax = plt.subplots()  #create figure and axes
candlestick(ax, quotes, ...)

or

candlestick(plt.gca(), quotes) #get the axis when calling the function

The first gives you more flexibility. The second is much easier if candlestick is the only thing you want to plot

How to specify a multi-line shell variable?

I would like to give one additional answer, while the other ones will suffice in most cases.

I wanted to write a string over multiple lines, but its contents needed to be single-line.

sql="                       \
SELECT c1, c2               \
from Table1, ${TABLE2}      \
where ...                   \
"

I am sorry if this if a bit off-topic (I did not need this for SQL). However, this post comes up among the first results when searching for multi-line shell variables and an additional answer seemed appropriate.

iPhone keyboard, Done button and resignFirstResponder

In Xcode 5.1

Enable Done Button

  • In Attributes Inspector for the UITextField in Storyboard find the field "Return Key" and select "Done"

Hide Keyboard when Done is pressed

  • In Storyboard make your ViewController the delegate for the UITextField
  • Add this method to your ViewController

    -(BOOL)textFieldShouldReturn:(UITextField *)textField
    {
        [textField resignFirstResponder];
        return YES;
    }
    

Android Studio: Gradle - build fails -- Execution failed for task ':dexDebug'

Cleaning the Project using Build in Menu Bar work for many error scenarios in Android Studio and so it does in this case.

insert data from one table to another in mysql

INSERT INTO destination_table ( 
      Field_1, 
      Field_2, 
      Field_3) 
SELECT Field_1, 
      Field_2, 
      Field_3 
      FROM source_table;

BUT this is a BAD MYSQL

Do this instead:

  1. drop the destination table: DROP DESTINATION_TABLE;
  2. CREATE TABLE DESTINATION_TABLE AS (SELECT * FROM SOURCE_TABLE);

Select query to get data from SQL Server

you have to add parameter also @zip

 SqlConnection conn = new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Password=");
      conn.Open();
      SqlCommand command = new SqlCommand("Select id from [table1] where name=@zip", conn);
      //
    // Add new SqlParameter to the command.
    //
      command.Parameters.AddWithValue("@zip","india");
      int result = (Int32) (command.ExecuteScalar());
      using (SqlDataReader reader = command.ExecuteReader())
      {
          // iterate your results here
       Console.WriteLine(String.Format("{0}",reader["id"]));

      }
      conn.Close();

android TextView: setting the background color dynamically doesn't work

If you would like to support all versions: Try this:

myTextView.setBackgroundColor(ContextCompat.getColor(this,R.color.mycolor)); 

Ubuntu, how do you remove all Python 3 but not 2

Removing Python 3 was the worst thing I did since I recently moved to the world of Linux. It removed Firefox, my launcher and, as I read while trying to fix my problem, it may also remove your desktop and terminal! Finally fixed after a long daytime nightmare. Just don't remove Python 3. Keep it there!

If that happens to you, here is the fix:

https://askubuntu.com/q/384033/402539

https://askubuntu.com/q/810854/402539

How do I work with dynamic multi-dimensional arrays in C?

Here is working code that defines a subroutine make_3d_array to allocate a multidimensional 3D array with N1, N2 and N3 elements in each dimension, and then populates it with random numbers. You can use the notation A[i][j][k] to access its elements.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>


// Method to allocate a 2D array of floats
float*** make_3d_array(int nx, int ny, int nz) {
    float*** arr;
    int i,j;

    arr = (float ***) malloc(nx*sizeof(float**));

    for (i = 0; i < nx; i++) {
        arr[i] = (float **) malloc(ny*sizeof(float*));

        for(j = 0; j < ny; j++) {
            arr[i][j] = (float *) malloc(nz * sizeof(float));
        }
    }

    return arr;
} 



int main(int argc, char *argv[])
{
    int i, j, k;
    size_t N1=10,N2=20,N3=5;

    // allocates 3D array
    float ***ran = make_3d_array(N1, N2, N3);

    // initialize pseudo-random number generator
    srand(time(NULL)); 

    // populates the array with random numbers
    for (i = 0; i < N1; i++){
        for (j=0; j<N2; j++) {
            for (k=0; k<N3; k++) {
                ran[i][j][k] = ((float)rand()/(float)(RAND_MAX));
            }
        }
   }

    // prints values
    for (i=0; i<N1; i++) {
        for (j=0; j<N2; j++) {
            for (k=0; k<N3; k++) {
                printf("A[%d][%d][%d] = %f \n", i,j,k,ran[i][j][k]);
            }
        }
    }

    free(ran);
}