Programs & Examples On #Ecma262

ECMA-262 is a Standard defining the ECMAScript scripting language also known as JavaScript.

What is the difference between JavaScript and ECMAScript?

ECMAScript is the language, whereas JavaScript, JScript, and even ActionScript 3 are called "dialects". Wikipedia sheds some light on this.

first-child and last-child with IE8

If you want to carry on using CSS3 selectors but need to support older browsers I would suggest using a polyfill such as Selectivizr.js

How to use jQuery in AngularJS

You have to do binding in a directive. Look at this:

angular.module('ng', []).
directive('sliderRange', function($parse, $timeout){
    return {
        restrict: 'A',
        replace: true,
        transclude: false,
        compile: function(element, attrs) {            
            var html = '<div class="slider-range"></div>';
            var slider = $(html);
            element.replaceWith(slider);
            var getterLeft = $parse(attrs.ngModelLeft), setterLeft = getterLeft.assign;
            var getterRight = $parse(attrs.ngModelRight), setterRight = getterRight.assign;

            return function (scope, slider, attrs, controller) {
                var vsLeft = getterLeft(scope), vsRight = getterRight(scope), f = vsLeft || 0, t = vsRight || 10;                        

                var processChange = function() {
                    var vs = slider.slider("values"), f = vs[0], t = vs[1];                                        
                    setterLeft(scope, f);
                    setterRight(scope, t);                    
                }                 
                slider.slider({
                    range: true,
                    min: 0,
                    max: 10,
                    step: 1,
                    change: function() { setTimeout(function () { scope.$apply(processChange); }, 1) }
                }).slider("values", [f, t]);                    
            };            
        }
    };
});

This shows you an example of a slider range, done with jQuery UI. Example usage:

<div slider-range ng-model-left="question.properties.range_from" ng-model-right="question.properties.range_to"></div>

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

I have same problem after upgrading to Gradle Wrapper 5.1.rec3. I am back to Gradle 4.6

Splitting applicationContext to multiple files

@eljenso : intrafest-servlet.xml webapplication context xml will be used if the application uses SPRING WEB MVC.

Otherwise the @kosoant configuration is fine.

Simple example if you dont use SPRING WEB MVC, but want to utitlize SPRING IOC :

In web.xml:

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:application-context.xml</param-value>
</context-param>

Then, your application-context.xml will contain: <import resource="foo-services.xml"/> these import statements to load various application context files and put into main application-context.xml.

Thanks and hope this helps.

editing PATH variable on mac

environment.plst file loads first on MAC so put the path on it.

For 1st time use, use the following command

export PATH=$PATH: /path/to/set

System.IO.IOException: file used by another process

The code works as best I can tell. I would fire up Sysinternals process explorer and find out what is holding the file open. It might very well be Visual Studio.

Unexpected end of file error

Change the Platform of your C++ project to "x64" (or whichever platform you are targeting) instead of "Win32". This can be found in Visual Studio under Build -> Configuration Manager. Find your project in the list and change the Platform column. Don't forget to do this for all solution configurations.

How to call a shell script from python code?

import os
import sys

Assuming test.sh is the shell script that you would want to execute

os.system("sh test.sh")

pip install - locale.Error: unsupported locale setting

Ubuntu:

$ sudo vi /etc/default/locale

Add below setting at the end of file.

LC_ALL = en_US.UTF-8

How generate unique Integers based on GUIDs

I had a requirement where multiple instances of a console application needed to get an unique integer ID. It is used to identify the instance and assigned at startup. Because the .exe is started by hands, I settled on a solution using the ticks of the start time.

My reasoning was that it would be nearly impossible for the user to start two .exe in the same millisecond. This behavior is deterministic: if you have a collision, you know that the problem was that two instances were started at the same time. Methods depending on hashcode, GUID or random numbers might fail in unpredictable ways.

I set the date to 0001-01-01, add the current time and divide the ticks by 10000 (because I don't set the microseconds) to get a number that is small enough to fit into an integer.

 var now = DateTime.Now;
 var zeroDate = DateTime.MinValue.AddHours(now.Hour).AddMinutes(now.Minute).AddSeconds(now.Second).AddMilliseconds(now.Millisecond);
 int uniqueId = (int)(zeroDate.Ticks / 10000);

EDIT: There are some caveats. To make collisions unlikely, make sure that:

  • The instances are started manually (more than one millisecond apart)
  • The ID is generated once per instance, at startup
  • The ID must only be unique in regard to other instances that are currently running
  • Only a small number of IDs will ever be needed

How do I resolve "Please make sure that the file is accessible and that it is a valid assembly or COM component"?

In my case I also have unmanaged dll's (C++) in workspace and if you specify:

<files>
    <file src="bin\*.dll" target="lib" />
</files>

nuget would try to load every dll as an assembly, even the C++ libraries! To avoid this behaviour explicitly define your C# assemblies with references tag:

<references>
    <reference file="Managed1.dll" />
    <reference file="Managed2.dll" />
</references>

Remark: parent of references is metadata -> according to documentation https://docs.microsoft.com/en-us/nuget/reference/nuspec#general-form-and-schema

Documentation: https://docs.microsoft.com/en-us/nuget/reference/nuspec

Keyboard shortcuts with jQuery

If you want just simple shortcuts (like 1 letter, for example just g) you could easily do it without a extra plugin:

$(document).keypress(function(e) {
  if(e.charCode == 103) {
    // Your Code
  }
});

Why not inherit from List<T>?

Does allowing people to say

myTeam.subList(3, 5);

make any sense at all? If not then it shouldn't be a List.

Increment value in mysql update query

Who needs to update string and numbers SET @a = 0; UPDATE obj_disposition SET CODE = CONCAT('CD_', @a:=@a+1);

How to write both h1 and h2 in the same line?

<h1 style="text-align: left; float: left;">Text 1</h1>
<h2 style="text-align: right; float: right; display: inline;">Text 2</h2>
<hr style="clear: both;" />

Hope this helps!

Using If else in SQL Select statement

You can use simply if statement under select query as like I have described below

if(some_condition,if_satisfied,not_satisfied)

SELECT IF(IDParent < 1,ID,IDParent)  FROM yourTable ;

JavaScript operator similar to SQL "like"

No.

You want to use: .indexOf("foo") and then check the index. If it's >= 0, it contains that string.

What is the best way to add a value to an array in state

For functional components with hooks

const [searches, setSearches] = useState([]);

// Using .concat(), no wrapper function (not recommended)
setSearches(searches.concat(query));

// Using .concat(), wrapper function (recommended)
setSearches(searches => searches.concat(query));

// Spread operator, no wrapper function (not recommended)
setSearches([...searches, query]);

// Spread operator, wrapper function (recommended)
setSearches(searches => [...searches, query]);

source: https://medium.com/javascript-in-plain-english/how-to-add-to-an-array-in-react-state-3d08ddb2e1dc

jQuery deferreds and promises - .then() vs .done()

.done() terminates the promise chain, making sure nothing else can attach further steps. This means that the jQuery promise implementation can throw any unhandled exception, since no one can possible handle it using .fail().

In practical terms, if you do not plan to attach more steps to a promise, you should use .done(). For more details see why promises need to be done

How to Parse JSON Array with Gson

You can parse the JSONArray directly, don't need to wrap your Post class with PostEntity one more time and don't need new JSONObject().toString() either:

Gson gson = new Gson();
String jsonOutput = "Your JSON String";
Type listType = new TypeToken<List<Post>>(){}.getType();
List<Post> posts = gson.fromJson(jsonOutput, listType);

Hope that helps.

What is "Connect Timeout" in sql server connection string?

How a connection works in a nutshell

A connection between a program and a database server relies on a handshake.

What this means is that when a connection is opened then the thread establishing the connection will send network packets to the database server. This thread will then pause until either network packets about this connection are received from the database server or when the connection timeout expires.

The connection timeout

The connection timeout is measured in seconds from the point the connection is opened.

When the timeout expires then the thread will continue, but it will do so having reported a connection failure.

  • If there is no value specified for connection timeout in the connection string then the default value is 30.

  • A value greater than zero means how many seconds before it gives up e.g. a value of 10 means to wait 10 seconds.

  • A value of 0 means to never give up waiting for the connection

Note: A value of 0 is not advised since it is possible for either the connection request packets or the server response packets to get lost. Will you seriously be prepared to wait even a day for a response that may never come?

What should I set my Connection Timeout value to?

This setting should depend on the speed of your network and how long you are prepared to allow a thread to wait for a response.

As an example, on a task that repeats hourly during the day, I know my network has always responded within one second so I set the connection timeout to a value of 2 just to be safe. I will then try again three times before giving up and either raising a support ticket or escalating a similar existing support ticket.

Test your own network speed and consider what to do when a connection fails as a one off, and also when it fails repeatedly and sporadically.

Windows Bat file optional argument parsing

Once I had written a program that handle the short (-h), long (--help) and non-option arguments in batch file. This techniques includes:

  • non-option arguments followed by a option arguments.

  • shift operator for those options that have no argument like '--help'.

  • two time shift operator for those options that require an argument.

  • loop through a label for processing all command line arguments.

  • Exit script and stop processing for those options that no need to require further action like '--help'.

  • Wrote help functions for user guidiness

Here is my code.

set BOARD=
set WORKSPACE=
set CFLAGS=
set LIB_INSTALL=true
set PREFIX=lib
set PROGRAM=install_boards

:initial
 set result=false
 if "%1" == "-h" set result=true
 if "%1" == "--help" set result=true
 if "%result%" == "true" (
 goto :usage
 )
 if "%1" == "-b" set result=true
 if "%1" == "--board" set result=true
 if "%result%" == "true" (
 goto :board_list
 )
 if "%1" == "-n" set result=true
 if "%1" == "--no-lib" set result=true
 if "%result%" == "true" (
 set LIB_INSTALL=false
 shift & goto :initial
 )
 if "%1" == "-c" set result=true
 if "%1" == "--cflag" set result=true
 if "%result%" == "true" (
 set CFLAGS=%2
 if not defined CFLAGS (
 echo %PROGRAM%: option requires an argument -- 'c'
 goto :try_usage
 )
 shift & shift & goto :initial
 )
 if "%1" == "-p" set result=true
 if "%1" == "--prefix" set result=true
 if "%result%" == "true" (
 set PREFIX=%2
 if not defined PREFIX (
 echo %PROGRAM%: option requires an argument -- 'p'
 goto :try_usage
 )
 shift & shift & goto :initial
 )

:: handle non-option arguments
set BOARD=%1
set WORKSPACE=%2

goto :eof


:: Help section

:usage
echo Usage: %PROGRAM% [OPTIONS]... BOARD... WORKSPACE
echo Install BOARD to WORKSPACE location.
echo WORKSPACE directory doesn't already exist!
echo.
echo Mandatory arguments to long options are mandatory for short options too.
echo   -h, --help                   display this help and exit
echo   -b, --boards                 inquire about available CS3 boards
echo   -c, --cflag=CFLAGS           making the CS3 BOARD libraries for CFLAGS
echo   -p. --prefix=PREFIX          install CS3 BOARD libraries in PREFIX
echo                                [lib]
echo   -n, --no-lib                 don't install CS3 BOARD libraries by default
goto :eof

:try_usage
echo Try '%PROGRAM% --help' for more information
goto :eof

How to make a boolean variable switch between true and false every time a method is invoked?

Assuming your code above is the actual code, you have two problems:

1) your if statements need to be '==', not '='. You want to do comparison, not assignment.

2) The second if should be an 'else if'. Otherwise when it's false, you will set it to true, then the second if will be evaluated, and you'll set it back to false, as you describe

if (a == false) {
  a = true;
} else if (a == true) {
  a = false;
}

Another thing that would make it even simpler is the '!' operator:

a = !a;

will switch the value of a.

Key hash for Android-Facebook app

To get the Android key hash code, follow these steps:

  1. Download OpenSSL for Windows here
  2. Now unzip to the C drive
  3. Open a CMD prompt
  4. Type cd C:\Program Files\Java\jdk1.6.0_26\bin
  5. Then type only keytool -export -alias myAlias -keystore C:\Users\your user name\.android\myKeyStore | C:\openssl-0.9.8k_WIN32\bin\openssl sha1 -binary | C:\openssl-0.9.8k_WIN32\bin\openssl enc -a -e
  6. Done

Create an Array of Arraylists

You can create Array of ArrayList

List<Integer>[] outer = new List[number];
for (int i = 0; i < number; i++) {
    outer[i] = new ArrayList<>();
}

This will be helpful in scenarios like this. You know the size of the outer one. But the size of inner ones varies. Here you can create an array of fixed length which contains size-varying Array lists. Hope this will be helpful for you.

In Java 8 and above you can do it in a much better way.

List<Integer>[] outer = new List[number];
Arrays.setAll(outer, element -> new ArrayList<>());

Even better using method reference

List<Integer>[] outer = new List[10];
Arrays.setAll(outer,  ArrayList :: new);

How to get MAC address of client using PHP?

First you check your user agent OS Linux or windows or another. Then Your OS Windows Then this code use:

public function win_os(){ 
    ob_start();
    system('ipconfig-a');
    $mycom=ob_get_contents(); // Capture the output into a variable
    ob_clean(); // Clean (erase) the output buffer
    $findme = "Physical";
    $pmac = strpos($mycom, $findme); // Find the position of Physical text
    $mac=substr($mycom,($pmac+36),17); // Get Physical Address

    return $mac;
   }

And your OS Linux Ubuntu or Linux then this code use:

public function unix_os(){
    ob_start();
    system('ifconfig -a');
    $mycom = ob_get_contents(); // Capture the output into a variable
    ob_clean(); // Clean (erase) the output buffer
    $findme = "Physical";
    //Find the position of Physical text 
    $pmac = strpos($mycom, $findme); 
    $mac = substr($mycom, ($pmac + 37), 18);

    return $mac;
    }

This code may be work OS X.

Passing dynamic javascript values using Url.action()

The @Url.Action() method is proccess on the server-side, so you cannot pass a client-side value to this function as a parameter. You can concat the client-side variables with the server-side url generated by this method, which is a string on the output. Try something like this:

var firstname = "abc";
var username = "abcd";
location.href = '@Url.Action("Display", "Customer")?uname=' + firstname + '&name=' + username;

The @Url.Action("Display", "Customer") is processed on the server-side and the rest of the string is processed on the client-side, concatenating the result of the server-side method with the client-side.

How do I manually create a file with a . (dot) prefix in Windows? For example, .htaccess

Go to command prompt, cd to the appropriate folder and type:

notepad .htaccess

After confirmation dialog the file will be created and you will be editing it directly. If you just want to create an empty file, try

echo. > .htaccess

The server encountered an internal error or misconfiguration and was unable to complete your request

You should look for the error in the file error_log in the log directory. Maybe there are differences between your local and server configuration (db user/password etc.etc.)

usually the log file is in

/var/log/apache2/error.log

or

/var/log/httpd/error.log

Difference between Divide and Conquer Algo and Dynamic Programming

Divide and Conquer

  • In this problem is solved in following three steps: 1. Divide - Dividing into number of sub-problems 2. Conquer - Conquering by solving sub-problems recursively 3. Combine - Combining sub-problem solutions to get original problem's solution
  • Recursive approach
  • Top Down technique
  • Example: Merge Sort

Dynamic Programming

  • In this the problem is solved in following steps: 1. Defining structure of optimal solution 2. Defines value of optimal solutions repeatedly. 3. Obtaining values of optimal solution in bottom-up fashion 4. Getting final optimal solution from obtained values
  • Non-Recursive
  • Bottom Up Technique
  • Example: Strassen's Matrix Multiplication

C++ IDE for Macs

Code::Blocks is cross-platform, using the wxWidgets library. It's the one I use.

SQL Server 2008 Connection Error "No process is on the other end of the pipe"

This Might help as reference

I had the same issue, after multiple trial of suggested solution on this site and others, I found a solution for my scenario. The account was locked out How to Check if the account is Locked out... Login to the server using higher privileged account (like SA or admin rights) Expand security ==> select the login name ==>open the property window of the login ==> select the status page on the property window

Make sure This 3 Things 1, permission to connect database is GRANTED 2, Login is ENABLED 3, Status SQL server authentication Login is not locked out (Uncheck the box)

Thanks Tsige

SELECT * WHERE NOT EXISTS

SELECT * FROM employees WHERE name NOT IN (SELECT name FROM eotm_dyn)

OR

SELECT * FROM employees WHERE NOT EXISTS (SELECT * FROM eotm_dyn WHERE eotm_dyn.name = employees.name)

OR

SELECT * FROM employees LEFT OUTER JOIN eotm_dyn ON eotm_dyn.name = employees.name WHERE eotm_dyn IS NULL

Removing a Fragment from the back stack

I created a code to jump to the desired back stack index, it worked fine to my purpose.

ie. I have Fragment1, Fragment2 and Fragment3, I want to jump from Fragment3 to Fragment1

I created a method called onBackPressed in Fragment3 that jumps to Fragment1

Fragment3:

public void onBackPressed() {
    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.popBackStack(fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount()-2).getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
}

In the activity, I need to know if my current fragment is the Fragment3, so I call the onBackPressed of my fragment instead calling super

FragmentActivity:

@Override
public void onBackPressed() {
    Fragment f = getSupportFragmentManager().findFragmentById(R.id.my_fragment_container);
    if (f instanceof Fragment3)
    {
        ((Fragment3)f).onBackPressed();
    } else {
        super.onBackPressed();
    }
}

Fire event on enter key press for a textbox

Try this option.

update that coding part in Page_Load event before catching IsPostback

 TextBox1.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('ctl00_ContentPlaceHolder1_Button1').click();return false;}} else {return true}; ");

How to remove symbols from a string with Python?

I often just open the console and look for the solution in the objects methods. Quite often it's already there:

>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello   s'

Short answer: Use string.replace().

Do while loop in SQL Server 2008

If you are not very offended by the GOTO keyword, it can be used to simulate a DO / WHILE in T-SQL. Consider the following rather nonsensical example written in pseudocode:

SET I=1
DO
 PRINT I
 SET I=I+1
WHILE I<=10

Here is the equivalent T-SQL code using goto:

DECLARE @I INT=1;
START:                -- DO
  PRINT @I;
  SET @I+=1;
IF @I<=10 GOTO START; -- WHILE @I<=10

Notice the one to one mapping between the GOTO enabled solution and the original DO / WHILE pseudocode. A similar implementation using a WHILE loop would look like:

DECLARE @I INT=1;
WHILE (1=1)              -- DO
 BEGIN
  PRINT @I;
  SET @I+=1;
  IF NOT (@I<=10) BREAK; -- WHILE @I<=10
 END

Now, you could of course rewrite this particular example as a simple WHILE loop, since this is not such a good candidate for a DO / WHILE construct. The emphasis was on example brevity rather than applicability, since legitimate cases requiring a DO / WHILE are rare.


REPEAT / UNTIL, anyone (does NOT work in T-SQL)?

SET I=1
REPEAT
  PRINT I
  SET I=I+1
UNTIL I>10

... and the GOTO based solution in T-SQL:

DECLARE @I INT=1;
START:                    -- REPEAT
  PRINT @I;
  SET @I+=1;
IF NOT(@I>10) GOTO START; -- UNTIL @I>10

Through creative use of GOTO and logic inversion via the NOT keyword, there is a very close relationship between the original pseudocode and the GOTO based solution. A similar solution using a WHILE loop looks like:

DECLARE @I INT=1;
WHILE (1=1)       -- REPEAT
 BEGIN
  PRINT @I;
  SET @I+=1;
  IF @I>10 BREAK; -- UNTIL @I>10
 END

An argument can be made that for the case of the REPEAT / UNTIL, the WHILE based solution is simpler, because the if condition is not inverted. On the other hand it is also more verbose.

If it wasn't for all of the disdain around the use of GOTO, these might even be idiomatic solutions for those few times when these particular (evil) looping constructs are necessary in T-SQL code for the sake of clarity.

Use these at your own discretion, trying not to suffer the wrath of your fellow developers when they catch you using the much maligned GOTO.

Your configuration specifies to merge with the <branch name> from the remote, but no such ref was fetched.?

Check if your remote branch is available to pull. I had the same issue, finally realized the remote branch was deleted by someone.

Fragment pressing back button

Solution for Pressing or handling back button in Fragment.

The way I solved my issue I am sure it will helps you too:

1.If you don't have any Edit Text-box in your fragment you can use below code

Here MainHomeFragment is main Fragment (When I press back button from second fragment it will take me too MainHomeFragment)

    @Override
    public void onResume() {

    super.onResume();

    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){

                MainHomeFragment mainHomeFragment = new SupplierHomeFragment();
                android.support.v4.app.FragmentTransaction fragmentTransaction =
                        getActivity().getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.fragment_container, mainHomeFragment);
                fragmentTransaction.commit();

                return true;    
            }    
            return false;
        }
    }); }

2.If you have another fragment named as Somefragment and it has Edit text-box then you can do it by this way.

private EditText editText;

Then In,

onCreateView():    
editText = (EditText) view.findViewById(R.id.editText);

Then Override OnResume,

@Override
public void onResume() {
    super.onResume();

    editText.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                editTextOFS.clearFocus();
                getView().requestFocus();
            }
            return false;
        }
    });

    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){

                MainHomeFragment mainHomeFragment = new SupplierHomeFragment();
                android.support.v4.app.FragmentTransaction fragmentTransaction =
                        getActivity().getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.fragment_container, mainHomeFragment);
                fragmentTransaction.commit();

                return true;

            }

            return false;
        }
    });

}

That's all folks (amitamie.com) :-) ;-)

Determine the number of lines within a text file

Reading a file in and by itself takes some time, garbage collecting the result is another problem as you read the whole file just to count the newline character(s),

At some point, someone is going to have to read the characters in the file, regardless if this the framework or if it is your code. This means you have to open the file and read it into memory if the file is large this is going to potentially be a problem as the memory needs to be garbage collected.

Nima Ara made a nice analysis that you might take into consideration

Here is the solution proposed, as it reads 4 characters at a time, counts the line feed character and re-uses the same memory address again for the next character comparison.

private const char CR = '\r';  
private const char LF = '\n';  
private const char NULL = (char)0;

public static long CountLinesMaybe(Stream stream)  
{
    Ensure.NotNull(stream, nameof(stream));

    var lineCount = 0L;

    var byteBuffer = new byte[1024 * 1024];
    const int BytesAtTheTime = 4;
    var detectedEOL = NULL;
    var currentChar = NULL;

    int bytesRead;
    while ((bytesRead = stream.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
    {
        var i = 0;
        for (; i <= bytesRead - BytesAtTheTime; i += BytesAtTheTime)
        {
            currentChar = (char)byteBuffer[i];

            if (detectedEOL != NULL)
            {
                if (currentChar == detectedEOL) { lineCount++; }

                currentChar = (char)byteBuffer[i + 1];
                if (currentChar == detectedEOL) { lineCount++; }

                currentChar = (char)byteBuffer[i + 2];
                if (currentChar == detectedEOL) { lineCount++; }

                currentChar = (char)byteBuffer[i + 3];
                if (currentChar == detectedEOL) { lineCount++; }
            }
            else
            {
                if (currentChar == LF || currentChar == CR)
                {
                    detectedEOL = currentChar;
                    lineCount++;
                }
                i -= BytesAtTheTime - 1;
            }
        }

        for (; i < bytesRead; i++)
        {
            currentChar = (char)byteBuffer[i];

            if (detectedEOL != NULL)
            {
                if (currentChar == detectedEOL) { lineCount++; }
            }
            else
            {
                if (currentChar == LF || currentChar == CR)
                {
                    detectedEOL = currentChar;
                    lineCount++;
                }
            }
        }
    }

    if (currentChar != LF && currentChar != CR && currentChar != NULL)
    {
        lineCount++;
    }
    return lineCount;
}

Above you can see that a line is read one character at a time as well by the underlying framework as you need to read all characters to see the line feed.

If you profile it as done bay Nima you would see that this is a rather fast and efficient way of doing this.

Get first date of current month in java

In order to get a Date (that can be used in JPA later on), I did

Date startOfMonth = Date.from(LocalDate.now().withDayOfMonth(1).atStartOfDay().toInstant(ZoneOffset.UTC));
  • I take current date LocalDate.now()
  • Move it to first day of the month withDayOfMonth(1)
  • Move it to the sart of the day atStartOfDay() to get rid of hours and minutes
  • and deal with the TimeZone issues by changing it into an Instant with the "right" ZoneOffset.

Removing all unused references from a project in Visual Studio projects

In a Visual Basic project there is support to remove "Unused References" (Project-->References-->Unused References). In C# there isn´t such a function.

The only way to do it in a C# project (without other tools) is to remove possible unused assemblies, compile the project and verify if any errors occur during compilation. If none errors occur you have removed a unused assembly. (See my post)

If you want to know which project (assembly) depends on other assemblies you can use NDepend.

ARG or ENV, which one to use in this case?

So if want to set the value of an environment variable to something different for every build then we can pass these values during build time and we don't need to change our docker file every time.

While ENV, once set cannot be overwritten through command line values. So, if we want to have our environment variable to have different values for different builds then we could use ARG and set default values in our docker file. And when we want to overwrite these values then we can do so using --build-args at every build without changing our docker file.

For more details, you can refer this.

Check Whether a User Exists

Why don't you simply use

grep -c '^username:' /etc/passwd

It will return 1 (since a user has max. 1 entry) if the user exists and 0 if it doesn't.

How do I set the rounded corner radius of a color drawable using xml?

Try below code

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners
    android:bottomLeftRadius="30dp"
    android:bottomRightRadius="30dp"
    android:topLeftRadius="30dp"
    android:topRightRadius="30dp" />
<solid android:color="#1271BB" />

<stroke
    android:width="5dp"
    android:color="#1271BB" />

<padding
    android:bottom="1dp"
    android:left="1dp"
    android:right="1dp"
    android:top="1dp" /></shape>

How to fix div on scroll

On jQuery for designers there's a well written post about this, this is the jQuery snippet that does the magic. just replace #comment with the selector of the div that you want to float.

Note: To see the whole article go here: http://jqueryfordesigners.com/fixed-floating-elements/

$(document).ready(function () {
  var $obj = $('#comment');
  var top = $obj.offset().top - parseFloat($obj.css('marginTop').replace(/auto/, 0));

  $(window).scroll(function (event) {
    // what the y position of the scroll is
    var y = $(this).scrollTop();

    // whether that's below the form
    if (y >= top) {
      // if so, ad the fixed class
      $obj.addClass('fixed');
    } else {
      // otherwise remove it
      $obj.removeClass('fixed');
    }
  });
});

how to modify the size of a column

Regardless of what error Oracle SQL Developer may indicate in the syntax highlighting, actually running your alter statement exactly the way you originally had it works perfectly:

ALTER TABLE TEST_PROJECT2 MODIFY proj_name VARCHAR2(300);

You only need to add parenthesis if you need to alter more than one column at once, such as:

ALTER TABLE TEST_PROJECT2 MODIFY (proj_name VARCHAR2(400), proj_desc VARCHAR2(400));

Why am I getting ImportError: No module named pip ' right after installing pip?

If you wrote

pip install --upgrade pip

and you got

Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 20.2.1
    Uninstalling pip-20.2.1:
ERROR: Could not install packages due to an EnvironmentError...

then you have uninstalled pip instead install pip. This could be the reason of your problem.

The Gorodeckij Dimitrij's answer works for me.

python -m ensurepip

Animation fade in and out

According to the documentation AnimationSet

Represents a group of Animations that should be played together. The transformation of each individual animation are composed together into a single transform. If AnimationSet sets any properties that its children also set (for example, duration or fillBefore), the values of AnimationSet override the child values

AnimationSet mAnimationSet = new AnimationSet(false); //false means don't share interpolators

Pass true if all of the animations in this set should use the interpolator associated with this AnimationSet. Pass false if each animation should use its own interpolator.

ImageView imageView= (ImageView)findViewById(R.id.imageView);
Animation fadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in);
Animation fadeOutAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out);
mAnimationSet.addAnimation(fadeInAnimation);
mAnimationSet.addAnimation(fadeOutAnimation);
imageView.startAnimation(mAnimationSet);

I hope this will help you.

How do I return the response from an asynchronous call?

Have a look at this example:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope,$http) {

    var getJoke = function(){
        return $http.get('http://api.icndb.com/jokes/random').then(function(res){
            return res.data.value;  
        });
    }

    getJoke().then(function(res) {
        console.log(res.joke);
    });
});

As you can see getJoke is returning a resolved promise (it is resolved when returning res.data.value). So you wait until the $http.get request is completed and then console.log(res.joke) is executed (as a normal asynchronous flow).

This is the plnkr:

http://embed.plnkr.co/XlNR7HpCaIhJxskMJfSg/

ES6 way (async - await)

(function(){
  async function getJoke(){
    let response = await fetch('http://api.icndb.com/jokes/random');
    let data = await response.json();
    return data.value;
  }

  getJoke().then((joke) => {
    console.log(joke);
  });
})();

How to move text up using CSS when nothing is working

you can try

position: relative;
bottom: 20px;

but I don't see a problem on my browser (Google Chrome)

Array of an unknown length in C#

You might also want to look into Dictionarys if your data is unique, This will give you two columns to work with.

User name , Total bill

it gives you a lot of built in tools to search and update just the value.

How do you pass view parameters when navigating from an action in JSF2?

You can do it using Primefaces like this :

<p:button 
      outcome="/page2.xhtml?faces-redirect=true&amp;id=#{myBean.id}">
</p:button>

How to capture UIView to UIImage without loss of quality on retina display

All Swift 3 answers did not worked for me so I have translated the most accepted answer:

extension UIImage {
    class func imageWithView(view: UIView) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0.0)
        view.layer.render(in: UIGraphicsGetCurrentContext()!)
        let img: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img!
    }
}

Download single files from GitHub

Go to DownGit - Enter Your URL - Simply Download

No need to install anything or follow complex instructions; specially suited for large source files.

Disclaimer: I am the author of this tool.


Download with DownGit


You can download individual files and directories as zip. You can also create download link, and even give name to the zip file. Detailed usage- here.

Place API key in Headers or URL

I would not put the key in the url, as it does violate this loose 'standard' that is REST. However, if you did, I would place it in the 'user' portion of the url.

eg: http://[email protected]/myresource/myid

This way it can also be passed as headers with basic-auth.

Looping Over Result Sets in MySQL

Use cursors.

A cursor can be thought of like a buffered reader, when reading through a document. If you think of each row as a line in a document, then you would read the next line, perform your operations, and then advance the cursor.

How can I use nohup to run process as a background process in linux?

In general, I use nohup CMD & to run a nohup background process. However, when the command is in a form that nohup won't accept then I run it through bash -c "...".

For example:

nohup bash -c "(time ./script arg1 arg2 > script.out) &> time_n_err.out" &

stdout from the script gets written to script.out, while stderr and the output of time goes into time_n_err.out.

So, in your case:

nohup bash -c "(time bash executeScript 1 input fileOutput > scrOutput) &> timeUse.txt" &

Java multiline string

This is something that you should never use without thinking about what it's doing. But for one-off scripts I've used this with great success:

Example:

    System.out.println(S(/*
This is a CRAZY " ' ' " multiline string with all sorts of strange 
   characters!
*/));

Code:

// From: http://blog.efftinge.de/2008/10/multi-line-string-literals-in-java.html
// Takes a comment (/**/) and turns everything inside the comment to a string that is returned from S()
public static String S() {
    StackTraceElement element = new RuntimeException().getStackTrace()[1];
    String name = element.getClassName().replace('.', '/') + ".java";
    StringBuilder sb = new StringBuilder();
    String line = null;
    InputStream in = classLoader.getResourceAsStream(name);
    String s = convertStreamToString(in, element.getLineNumber());
    return s.substring(s.indexOf("/*")+2, s.indexOf("*/"));
}

// From http://www.kodejava.org/examples/266.html
private static String convertStreamToString(InputStream is, int lineNum) {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null; int i = 1;
    try {
        while ((line = reader.readLine()) != null) {
            if (i++ >= lineNum) {
                sb.append(line + "\n");
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return sb.toString();
}

Getting JavaScript object key list

If you decide to use Underscore.js you better do

var obj = {
    key1: 'value1',
    key2: 'value2',
    key3: 'value3',
    key4: 'value4'
}

var keys = [];
_.each( obj, function( val, key ) {
    keys.push(key);
});
console.log(keys.lenth, keys);

What is the iOS 6 user agent string?

Some more:

Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25

Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B350 Safari/8536.25

Two div blocks on same line

You can use a HTML table:

<table>
<tr>
<td>
<div id="bloc1">your content</div>
</td>
<td>
<div id="bloc2">your content</div>
</td>
</tr>
</table>   

Vue.js toggle class on click

I've got a solution that allows you to check for different values of a prop and thus different <th> elements will become active/inactive. Using vue 2 syntax.

<th 
class="initial " 
@click.stop.prevent="myFilter('M')"
:class="[(activeDay == 'M' ? 'active' : '')]">
<span class="wkday">M</span>
</th>
...
<th 
class="initial " 
@click.stop.prevent="myFilter('T')"
:class="[(activeDay == 'T' ? 'active' : '')]">
<span class="wkday">T</span>
</th>



new Vue({
  el: '#my-container',

  data: {
      activeDay: 'M'
  },

  methods: {
    myFilter: function(day){
        this.activeDay = day;
      // some code to filter users
    }
  }
})

How do you redirect HTTPS to HTTP?

Keep in mind that the Rewrite engine only kicks in once the HTTP request has been received - which means you would still need a certificate, in order for the client to set up the connection to send the request over!

However if the backup machine will appear to have the same hostname (as far as the client is concerned), then there should be no reason you can't use the same certificate as the main production machine.

WAMP 403 Forbidden message on Windows 7

I have found that if you are using ammps that for some reason its always forbidden when its in your root folder so i put it in the directory above my root folder and made a alias in the httpd.conf using this

Alias /phpmyadmin "C:/Program Files (x86)/Ampps/phpMyAdmin"

please note i am using ammps and i dont know for sure if it will work for others but its worth a try ;)

Read/Parse text file line by line in VBA

I find the FileSystemObject with a TxtStream the easiest way to read files

Dim fso As FileSystemObject: Set fso = New FileSystemObject
Set txtStream = fso.OpenTextFile(filePath, ForReading, False)

Then with this txtStream object you have all sorts of tools which intellisense picks up (unlike using the FreeFile() method) so there is less guesswork. Plus you don' have to assign a FreeFile and hope it is actually still free since when you assigned it.

You can read a file like:

Do While Not txtStream.AtEndOfStream
    txtStream.ReadLine
Loop
txtStream.Close

NOTE: This requires a reference to Microsoft Scripting Runtime.

Neither BindingResult nor plain target object for bean name available as request attr

I worked on this same issue and I am sure I have found out the exact reason for it.

Neither BindingResult nor plain target object for bean name 'command' available as request attribute

If your successView property value (name of jsp page) is the same as your input page name, then second value of ModelAndView constructor must be match with the commandName of the input page.

E.g.

index.jsp

<html>
<body>
    <table>
        <tr><td><a href="Login.html">Login</a></td></tr>
    </table>
</body>
</html>

dispatcher-servlet.xml

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">

    <property name="prefix">
        <value>/WEB-INF/jsp/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>
<bean id="urlMapping"
    class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="urlMap">
        <map>              
            <entry key="/Login.html">
                <ref bean="userController"/>
            </entry>
        </map>          
    </property>             
</bean>     
 <bean id="userController" class="controller.AddCountryFormController">     
       <property name="commandName"><value>country</value></property>
       <property name="commandClass"><value>controller.Country</value></property>        
       <property name="formView"><value>countryForm</value></property>
       <property name="successView"><value>countryForm</value></property>
   </bean>      

AddCountryFormController.java

package controller;

import javax.servlet.http.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.mvc.SimpleFormController;


public class AddCountryFormController extends SimpleFormController
{

    public AddCountryFormController(){
        setCommandName("Country.class");
    }

    protected ModelAndView onSubmit(HttpServletRequest request,HttpServletResponse response,Object command,BindException errors){

            Country country=(Country)command;

            System.out.println("calling onsubmit method !!!!!");

        return new ModelAndView(getSuccessView(),"country",country);

    }

}

Country.java

package controller;

public class Country
{
    private String countryName;

    public void setCountryName(String value){
        countryName=value;
    }

    public String getCountryName(){
        return countryName;
    }

}

countryForm.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<body>
    <form:form commandName="country" method="POST" >
            <table>
                    <tr><td><form:input path="countryName"/></td></tr>
                    <tr><td><input type="submit" value="Save"/></td></tr>
            </table>
    </form:form>
</body>
<html>

Input page commandName="country" ModelAndView Constructor as return new ModelAndView(getSuccessView(),"country",country); Means inputpage commandName==ModeAndView(,"commandName",)

Conversion from 12 hours time to 24 hours time in java

Try this:

import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
   public static void main(String [] args) throws Exception {
       SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
       SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a");
       Date date = parseFormat.parse("10:30 PM");
       System.out.println(parseFormat.format(date) + " = " + displayFormat.format(date));
   }
}

which produces:

10:30 PM = 22:30

See: http://download.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html

Laravel assets url

Besides put all your assets in the public folder, you can use the HTML::image() Method, and only needs an argument which is the path to the image, relative on the public folder, as well:

{{ HTML::image('imgs/picture.jpg') }}

Which generates the follow HTML code:

<img src="http://localhost:8000/imgs/picture.jpg">

The link to other elements of HTML::image() Method: http://laravel-recipes.com/recipes/185/generating-an-html-image-element

How much overhead does SSL impose?

I second @erickson: The pure data-transfer speed penalty is negligible. Modern CPUs reach a crypto/AES throughput of several hundred MBit/s. So unless you are on resource constrained system (mobile phone) TLS/SSL is fast enough for slinging data around.

But keep in mind that encryption makes caching and load balancing much harder. This might result in a huge performance penalty.

But connection setup is really a show stopper for many application. On low bandwidth, high packet loss, high latency connections (mobile device in the countryside) the additional roundtrips required by TLS might render something slow into something unusable.

For example we had to drop the encryption requirement for access to some of our internal web apps - they where next to unusable if used from china.

strdup() - what does it do in C?

No point repeating the other answers, but please note that strdup() can do anything it wants from a C perspective, since it is not part of any C standard. It is however defined by POSIX.1-2001.

Merging a lot of data.frames

Put them into a list and use merge with Reduce

Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
#    id v1 v2 v3
# 1   1  1 NA NA
# 2  10  4 NA NA
# 3   2  3  4 NA
# 4  43  5 NA NA
# 5  73  2 NA NA
# 6  23 NA  2  1
# 7  57 NA  3 NA
# 8  62 NA  5  2
# 9   7 NA  1 NA
# 10 96 NA  6 NA

You can also use this more concise version:

Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))

Is the ternary operator faster than an "if" condition in Java

Ternary operators are just shorthand. They compile into the equivalent if-else statement, meaning they will be exactly the same.

What are the differences between Deferred, Promise and Future in JavaScript?

A Promise represents a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers to an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of the final value, the asynchronous method returns a promise of having a value at some point in the future.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

The deferred.promise() method allows an asynchronous function to prevent other code from interfering with the progress or status of its internal request. The Promise exposes only the Deferred methods needed to attach additional handlers or determine the state (then, done, fail, always, pipe, progress, state and promise), but not ones that change the state (resolve, reject, notify, resolveWith, rejectWith, and notifyWith).

If target is provided, deferred.promise() will attach the methods onto it and then return this object rather than create a new one. This can be useful to attach the Promise behavior to an object that already exists.

If you are creating a Deferred, keep a reference to the Deferred so that it can be resolved or rejected at some point. Return only the Promise object via deferred.promise() so other code can register callbacks or inspect the current state.

Simply we can say that a Promise represents a value that is not yet known where as a Deferred represents work that is not yet finished.


enter image description here

Eclipse shows errors but I can't find them

Take a look at

Window ? Show View ? Problems

or

Window ? Show View ? Error Log

What is the meaning of @_ in Perl?

The question was what @_ means in Perl. The answer to that question is that, insofar as $_ means it in Perl, @_ similarly means they.

No one seems to have mentioned this critical aspect of its meaning — as well as theirs.

They’re consequently both used as pronouns, or sometimes as topicalizers.

They typically have nominal antecedents, although not always.

Delete specified file from document directory

FreeGor version converted to Swift 3.0

 func removeOldFileIfExist() {
    let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
    if paths.count > 0 {
        let dirPath = paths[0]
        let fileName = "filename.jpg"
        let filePath = NSString(format:"%@/%@", dirPath, fileName) as String
        if FileManager.default.fileExists(atPath: filePath) {
            do {
                try FileManager.default.removeItem(atPath: filePath)
                print("User photo has been removed")
            } catch {
                print("an error during a removing")
            }
        }
    }
}

How to solve java.lang.OutOfMemoryError trouble in Android

Few hints to handle such error/exception for Android Apps:

  1. Activities & Application have methods like:

    • onLowMemory
    • onTrimMemory Handle these methods to watch on memory usage.
  2. tag in Manifest can have attribute 'largeHeap' set to TRUE, which requests more heap for App sandbox.

  3. Managing in-memory caching & disk caching:

    • Images and other data could have been cached in-memory while app running, (locally in activities/fragment and globally); should be managed or removed.
  4. Use of WeakReference, SoftReference of Java instance creation , specifically to files.

  5. If so many images, use proper library/data structure which can manage memory, use samling of images loaded, handle disk-caching.

  6. Handle OutOfMemory exception

  7. Follow best practices for coding

    • Leaking of memory (Don't hold everything with strong reference)
  8. Minimize activity stack e.g. number of activities in stack (Don't hold everything on context/activty)

    • Context makes sense, those data/instances not required out of scope (activity and fragments), hold them into appropriate context instead global reference-holding.
  9. Minimize the use of statics, many more singletons.

  10. Take care of OS basic memory fundametals

    • Memory fragmentation issues
  11. Involk GC.Collect() manually sometimes when you are sure that in-memory caching no more needed.

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

Execute SQL script to create tables and rows

If you have password for your dB then

mysql -u <username> -p <DBName> < yourfile.sql

How do you split a list into evenly sized chunks?

This question reminds me of the Raku (formerly Perl 6) .comb(n) method. It breaks up strings into n-sized chunks. (There's more to it than that, but I'll leave out the details.)

It's easy enough to implement a similar function in Python3 as a lambda expression:

comb = lambda s,n: (s[i:i+n] for i in range(0,len(s),n))

Then you can call it like this:

some_list = list(range(0, 20))  # creates a list of 20 elements
generator = comb(some_list, 4)  # creates a generator that will generate lists of 4 elements
for sublist in generator:
    print(sublist)  # prints a sublist of four elements, as it's generated

Of course, you don't have to assign the generator to a variable; you can just loop over it directly like this:

for sublist in comb(some_list, 4):
    print(sublist)  # prints a sublist of four elements, as it's generated

As a bonus, this comb() function also operates on strings:

list( comb('catdogant', 3) )  # returns ['cat', 'dog', 'ant']

How to overplot a line on a scatter plot in python?

I'm partial to scikits.statsmodels. Here an example:

import statsmodels.api as sm
import numpy as np
import matplotlib.pyplot as plt

X = np.random.rand(100)
Y = X + np.random.rand(100)*0.1

results = sm.OLS(Y,sm.add_constant(X)).fit()

print results.summary()

plt.scatter(X,Y)

X_plot = np.linspace(0,1,100)
plt.plot(X_plot, X_plot*results.params[0] + results.params[1])

plt.show()

The only tricky part is sm.add_constant(X) which adds a columns of ones to X in order to get an intercept term.

     Summary of Regression Results
=======================================
| Dependent Variable:            ['y']|
| Model:                           OLS|
| Method:                Least Squares|
| Date:               Sat, 28 Sep 2013|
| Time:                       09:22:59|
| # obs:                         100.0|
| Df residuals:                   98.0|
| Df model:                        1.0|
==============================================================================
|                   coefficient     std. error    t-statistic          prob. |
------------------------------------------------------------------------------
| x1                      1.007       0.008466       118.9032         0.0000 |
| const                 0.05165       0.005138        10.0515         0.0000 |
==============================================================================
|                          Models stats                      Residual stats  |
------------------------------------------------------------------------------
| R-squared:                     0.9931   Durbin-Watson:              1.484  |
| Adjusted R-squared:            0.9930   Omnibus:                    12.16  |
| F-statistic:                1.414e+04   Prob(Omnibus):           0.002294  |
| Prob (F-statistic):        9.137e-108   JB:                        0.6818  |
| Log likelihood:                 223.8   Prob(JB):                  0.7111  |
| AIC criterion:                 -443.7   Skew:                     -0.2064  |
| BIC criterion:                 -438.5   Kurtosis:                   2.048  |
------------------------------------------------------------------------------

example plot

What is the cause for "angular is not defined"

I had the same problem as deke. I forgot to include the most important script: angular.js :)

<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>

How to cin to a vector

One-liner to read a fixed amount of numbers into a vector (C++11):

#include <algorithm>
#include <iterator>
#include <iostream>
#include <vector>
#include <cstddef>

int main()
{
    const std::size_t LIMIT{5};
    std::vector<int> collection;

    std::generate_n(std::back_inserter(collection), LIMIT,
        []()
        {
            return *(std::istream_iterator<int>(std::cin));
        }
    );

    return 0;
}

java.net.ConnectException: Connection refused

I had the same problem, but running the Server before running the Client fixed it.

Pass entire form as data in jQuery Ajax function

There's a function that does exactly this:

http://api.jquery.com/serialize/

var data = $('form').serialize();
$.post('url', data);

Get Absolute Position of element within the window in wpf

I think what BrandonS wants is not the position of the mouse relative to the root element, but rather the position of some descendant element.

For that, there is the TransformToAncestor method:

Point relativePoint = myVisual.TransformToAncestor(rootVisual)
                              .Transform(new Point(0, 0));

Where myVisual is the element that was just double-clicked, and rootVisual is Application.Current.MainWindow or whatever you want the position relative to.

How to read a configuration file in Java

Create a configuration file and put your entries there.

SERVER_PORT=10000     
THREAD_POOL_COUNT=3     
ROOT_DIR=/home/   

You can load this file using Properties.load(fileName) and retrieved values you get(key);

How to use a different version of python during NPM install?

set python to python2.7 before running npm install

Linux:

export PYTHON=python2.7

Windows:

set PYTHON=python2.7

Hiding elements in responsive layout?

Bootstrap 4.x answer

hidden-* classes are removed from Bootstrap 4 beta onward.

If you want to show on medium and up use the d-* classes, e.g.:

<div class="d-none d-md-block">This will show in medium and up</div>

If you want to show only in small and below use this:

<div class="d-block d-md-none"> This will show only in below medium form factors</div>

Screen size and class chart

| Screen Size        | Class                          |
|--------------------|--------------------------------|
| Hidden on all      | .d-none                        |
| Hidden only on xs  | .d-none .d-sm-block            |
| Hidden only on sm  | .d-sm-none .d-md-block         |
| Hidden only on md  | .d-md-none .d-lg-block         |
| Hidden only on lg  | .d-lg-none .d-xl-block         |
| Hidden only on xl  | .d-xl-none                     |
| Visible on all     | .d-block                       |
| Visible only on xs | .d-block .d-sm-none            |
| Visible only on sm | .d-none .d-sm-block .d-md-none |
| Visible only on md | .d-none .d-md-block .d-lg-none |
| Visible only on lg | .d-none .d-lg-block .d-xl-none |
| Visible only on xl | .d-none .d-xl-block            |

Rather than using explicit .visible-* classes, you make an element visible by simply not hiding it at that screen size. You can combine one .d-*-none class with one .d-*-block class to show an element only on a given interval of screen sizes (e.g. .d-none.d-md-block.d-xl-none shows the element only on medium and large devices).

Documentation

Replace Multiple String Elements in C#

Quicker - no. More effective - yes, if you will use the StringBuilder class. With your implementation each operation generates a copy of a string which under circumstances may impair performance. Strings are immutable objects so each operation just returns a modified copy.

If you expect this method to be actively called on multiple Strings of significant length, it might be better to "migrate" its implementation onto the StringBuilder class. With it any modification is performed directly on that instance, so you spare unnecessary copy operations.

public static class StringExtention
{
    public static string clean(this string s)
    {
        StringBuilder sb = new StringBuilder (s);

        sb.Replace("&", "and");
        sb.Replace(",", "");
        sb.Replace("  ", " ");
        sb.Replace(" ", "-");
        sb.Replace("'", "");
        sb.Replace(".", "");
        sb.Replace("eacute;", "é");

        return sb.ToString().ToLower();
    }
}

How to use an environment variable inside a quoted string in Bash

You are doing it right, so I guess something else is at fault (not export-ing COLUMNS ?).

A trick to debug these cases is to make a specialized command (a closure for programming language guys). Create a shell script named diff-columns doing:

exec /usr/bin/diff -x -y -w -p -W "$COLUMNS" "$@"

and just use

svn diff "$@" --diff-cmd  diff-columns

This way your code is cleaner to read and more modular (top-down approach), and you can test the diff-columns code thouroughly separately (bottom-up approach).

Should I learn C before learning C++?

In the process of learning C++ you will learn most of C as well. But keep in mind a lot of C++ code is not valid C. C++ was designed to be compatible with C code, so i'd say learn C++ first. Brian wrote a great answer regarding this.

AngularJS - difference between pristine/dirty and touched/untouched

$pristine/$dirty tells you whether the user actually changed anything, while $touched/$untouched tells you whether the user has merely been there/visited.

This is really useful for validation. The reason for $dirty was always to avoid showing validation responses until the user has actually visited a certain control. But, by using only the $dirty property, the user wouldn't get validation feedback unless they actually altered the value. So, an $invalid field still wouldn't show the user a prompt if the user didn't change/interact with the value. If the user entirely ignored a required field, everything looked OK.

With Angular 1.3 and ng-touched, you can now set a particular style on a control as soon as the user has blurred, regardless of whether they actually edited the value or not.

Here's a CodePen that shows the difference in behavior.

What does \0 stand for?

In C \0 is a character literal constant store into an int data type that represent the character with value of 0.

Since Objective-C is a strict superset of C this constant is retained.

Converting Swagger specification JSON to HTML documentation

I was not satisfied with swagger-codegen when I was looking for a tool to do this, so I wrote my own. Have a look at bootprint-swagger

The main goal compared to swagger-codegen is to provide an easy setup (though you'll need nodejs). And it should be easy to adapt styling and templates to your own needs, which is a core functionality of the bootprint-project

How to insert date values into table

insert into run(id,name,dob)values(&id,'&name',[what should I write here?]);

insert into run(id,name,dob)values(&id,'&name',TO_DATE('&dob','YYYY-MM-DD'));

How do I create the small icon next to the website tab for my site?

It is called favicon.ico and you can generate it from this site.

http://www.favicon.cc/

Display Back Arrow on Toolbar

Add this to activity's xml in layout folder:

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">
    <android.support.v7.widget.Toolbar
        android:id="@+id/prod_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>

Make toolbar clickable, add these to onCreate method:

Toolbar toolbar = (Toolbar) findViewById(R.id.prod_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        finish();
    }
});

showing that a date is greater than current date

In sql server, you can do

SELECT *
FROM table t
WHERE t.date > DATEADD(dd,90,now())

How to set background color of an Activity to white programmatically?

Add this single line in your activity, after setContentView() call

getWindow().getDecorView().setBackgroundColor(Color.WHITE);

How to get position of a certain element in strings vector, to use it as an index in ints vector?

To get a position of an element in a vector knowing an iterator pointing to the element, simply subtract v.begin() from the iterator:

ptrdiff_t pos = find(Names.begin(), Names.end(), old_name_) - Names.begin();

Now you need to check pos against Names.size() to see if it is out of bounds or not:

if(pos >= Names.size()) {
    //old_name_ not found
}

vector iterators behave in ways similar to array pointers; most of what you know about pointer arithmetic can be applied to vector iterators as well.

Starting with C++11 you can use std::distance in place of subtraction for both iterators and pointers:

ptrdiff_t pos = distance(Names.begin(), find(Names.begin(), Names.end(), old_name_));

What is an NP-complete in computer science?

NP-complete problems are a set of problems to each of which any other NP-problem can be reduced in polynomial time, and whose solution may still be verified in polynomial time. That is, any NP problem can be transformed into any of the NP-complete problems. – Informally, an NP-complete problem is an NP problem that is at least as "tough" as any other problem in NP.

Controlling Spacing Between Table Cells

Use the border-spacing property on the table element to set the spacing between cells.

Make sure border-collapse is set to separate (or there will be a single border between each cell instead of a separate border around each one that can have spacing between them).

correct way to use super (argument passing)

If you're going to have a lot of inheritence (that's the case here) I suggest you to pass all parameters using **kwargs, and then pop them right after you use them (unless you need them in upper classes).

class First(object):
    def __init__(self, *args, **kwargs):
        self.first_arg = kwargs.pop('first_arg')
        super(First, self).__init__(*args, **kwargs)

class Second(First):
    def __init__(self, *args, **kwargs):
        self.second_arg = kwargs.pop('second_arg')
        super(Second, self).__init__(*args, **kwargs)

class Third(Second):
    def __init__(self, *args, **kwargs):
        self.third_arg = kwargs.pop('third_arg')
        super(Third, self).__init__(*args, **kwargs)

This is the simplest way to solve those kind of problems.

third = Third(first_arg=1, second_arg=2, third_arg=3)

Check if int is between two numbers

One problem is that a ternary relational construct would introduce serious parser problems:

<expr> ::= <expr> <rel-op> <expr> |
           ... |
           <expr> <rel-op> <expr> <rel-op> <expr>

When you try to express a grammar with those productions using a typical PGS, you'll find that there is a shift-reduce conflict at the point of the first <rel-op>. The parse needs to lookahead an arbitrary number of symbols to see if there is a second <rel-op> before it can decide whether the binary or ternary form has been used. In this case, you could not simply ignore the conflict because that would result in incorrect parses.

I'm not saying that this grammar is fatally ambiguous. But I think you'd need a backtracking parser to deal with it correctly. And that is a serious problem for a programming language where fast compilation is a major selling point.

Custom CSS Scrollbar for Firefox

Since Firefox 64, is possible to use new specs for a simple Scrollbar styling (not as complete as in Chrome with vendor prefixes).

In this example is possible to see a solution that combine different rules to address both Firefox and Chrome with a similar (not equal) final result (example use your original Chrome rules):

The key rules are:

For Firefox

.scroller {
  overflow-y: scroll;
  scrollbar-color: #0A4C95 #C2D2E4;
}

For Chrome

.scroller::-webkit-scrollbar {
    width: 15px;
    height: 15px;
}

.scroller::-webkit-scrollbar-track-piece  {
    background-color: #C2D2E4;
}

.scroller::-webkit-scrollbar-thumb:vertical {
    height: 30px;
    background-color: #0A4C95;
}

Please note that respect to your solution, is possible to use also simpler Chrome rules as the following:

.scroller::-webkit-scrollbar-track  {
    background-color: #C2D2E4;
}

.scroller::-webkit-scrollbar-thumb {
    height: 30px;
    background-color: #0A4C95;
}

Finally, in order to hide arrows in scrollbars also in Firefox, currently is necessary to set it as "thin" with the following rule scrollbar-width: thin;

How can I make a Python script standalone executable to run without ANY dependency?

You may like py2exe. You'll also find information in there for doing it on Linux.

How to capture multiple repeated groups?

I think you need something like this....

b="HELLO,THERE,WORLD"
re.findall('[\w]+',b)

Which in Python3 will return

['HELLO', 'THERE', 'WORLD']

JVM heap parameters

The JVM will start with memory useage at the initial heap level. If the maxheap is higher, it will grow to the maxheap size as memory requirements exceed it's current memory.

So,

  • -Xms512m -Xmx512m

JVM starts with 512 M, never resizes.

  • -Xms64m -Xmx512m

JVM starts with 64M, grows (up to max ceiling of 512) if mem. requirements exceed 64.

How to implement a queue using two stacks?

A solution in c#

public class Queue<T> where T : class
{
    private Stack<T> input = new Stack<T>();
    private Stack<T> output = new Stack<T>();
    public void Enqueue(T t)
    {
        input.Push(t);
    }

    public T Dequeue()
    {
        if (output.Count == 0)
        {
            while (input.Count != 0)
            {
                output.Push(input.Pop());
            }
        }

        return output.Pop();
    }
}

Correct mime type for .mp4

According to RFC 4337 § 2, video/mp4 is indeed the correct Content-Type for MPEG-4 video.

Generally, you can find official MIME definitions by searching for the file extension and "IETF" or "RFC". The RFC (Request for Comments) articles published by the IETF (Internet Engineering Taskforce) define many Internet standards, including MIME types.

Get the Id of current table row with Jquery

Create a class in css name it .buttoncontact, add the class attribute to your buttons

function ClickedRow() {
    $(document).on('click', '.buttoncontact', function () {
        var row = $(this).parents('tr').attr('id');
        var rowtext = $(this).closest('tr').text();
        alert(row);      
    });
}

Read and overwrite a file in Python

The fileinput module has an inplace mode for writing changes to the file you are processing without using temporary files etc. The module nicely encapsulates the common operation of looping over the lines in a list of files, via an object which transparently keeps track of the file name, line number etc if you should want to inspect them inside the loop.

from fileinput import FileInput
for line in FileInput("file", inplace=1):
    line = line.replace("foobar", "bar")
    print(line)

How do you uninstall a python package that was installed using distutils?

Yes, it is safe to simply delete anything that distutils installed. That goes for installed folders or .egg files. Naturally anything that depends on that code will no longer work.

If you want to make it work again, simply re-install.

By the way, if you are using distutils also consider using the multi-version feature. It allows you to have multiple versions of any single package installed. That means you do not need to delete an old version of a package if you simply want to install a newer version.

C++ queue - simple example

Simply declare it as below if you want to us the STL queue container.

std::queue<myclass*> my_queue;

CSS-Only Scrollable Table with fixed headers

Only with CSS :

CSS:

tr {
  width: 100%;
  display: inline-table;
  table-layout: fixed;
}

table{
 height:300px;              // <-- Select the height of the table
 display: -moz-groupbox;    // Firefox Bad Effect
}
tbody{
  overflow-y: scroll;      
  height: 200px;            //  <-- Select the height of the body
  width: 100%;
  position: absolute;
}

Bootply : http://www.bootply.com/AgI8LpDugl

How to update core-js to core-js@3 dependency?

With this

npm install --save core-js@^3

you now get the error

"core-js@<3 is no longer maintained and not recommended for usage due to the number of
issues. Please, upgrade your dependencies to the actual version of core-js@3"

so you might want to instead try

npm install --save core-js@3

if you're reading this post June 9 2020.

How to get Rails.logger printing to the console/stdout when running rspec?

For Rails 4, see this answer.

For Rails 3.x, configure a logger in config/environments/test.rb:

config.logger = Logger.new(STDOUT)
config.logger.level = Logger::ERROR

This will interleave any errors that are logged during testing to STDOUT. You may wish to route the output to STDERR or use a different log level instead.

Sending these messages to both the console and a log file requires something more robust than Ruby's built-in Logger class. The logging gem will do what you want. Add it to your Gemfile, then set up two appenders in config/environments/test.rb:

logger = Logging.logger['test']
logger.add_appenders(
    Logging.appenders.stdout,
    Logging.appenders.file('example.log')
)
logger.level = :info
config.logger = logger

How to check if a string in Python is in ASCII?

New in Python 3.7 (bpo32677)

No more tiresome/inefficient ascii checks on strings, new built-in str/bytes/bytearray method - .isascii() will check if the strings is ascii.

print("is this ascii?".isascii())
# True

Get index of element as child relative to parent

Yet another way

$("#wizard li").click(function () 
{
    $($(this),'#wizard"').index();
});

Demo https://jsfiddle.net/m9xge3f5/

jQuery changing style of HTML element

$('#navigation ul li').css({'display' : 'inline-block'});

It seems a typo there ...syntax mistake :))

How to generate a random string of a fixed length in Go?

Use package uniuri, which generates cryptographically secure uniform (unbiased) strings.

Disclaimer: I'm the author of the package

ORA-28000: the account is locked error getting frequently

One of the reasons of your problem could be the password policy you are using.

And if there is no such policy of yours then check your settings for the password properties in the DEFAULT profile with the following query:

SELECT resource_name, limit
FROM dba_profiles 
WHERE profile = 'DEFAULT'
AND resource_type = 'PASSWORD';

And If required, you just need to change the PASSWORD_LIFE_TIME to unlimited with the following query:

ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;

And this Link might be helpful for your problem.

How to create a notification with NotificationCompat.Builder?

Use this code

            Intent intent = new Intent(getApplicationContext(), SomeActvity.class);
            PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(),
                    (int) System.currentTimeMillis(), intent, 0);

            NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(getApplicationContext())
                            .setSmallIcon(R.drawable.your_notification_icon)
                            .setContentTitle("Notification title")
                            .setContentText("Notification message!")
                            .setContentIntent(pIntent);

            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(0, mBuilder.build());

How do I change the ID of a HTML element with JavaScript?

It does work in Firefox (including 2.0.0.20). See http://jsbin.com/akili (add /edit to the url to edit):

<p id="one">One</p>
<a href="#" onclick="document.getElementById('one').id = 'two'; return false">Link2</a>

The first click changes the id to "two", the second click errors because the element with id="one" now can't be found!

Perhaps you have another element already with id="two" (FYI you can't have more than one element with the same id).

Converting characters to integers in Java

public class IntergerParser {

public static void main(String[] args){
String number = "+123123";
System.out.println(parseInt(number));
}

private static int parseInt(String number){
    char[] numChar = number.toCharArray();
    int intValue = 0;
    int decimal = 1;
    for(int index = numChar.length ; index > 0 ; index --){
        if(index == 1 ){
            if(numChar[index - 1] == '-'){
                return intValue * -1;
            } else if(numChar[index - 1] == '+'){
                return intValue;
            }
        }
        intValue = intValue + (((int)numChar[index-1] - 48) * (decimal));
        System.out.println((int)numChar[index-1] - 48+ " " + (decimal));
        decimal = decimal * 10;
    }
    return intValue;
}

Cannot load properties file from resources directory

Using ClassLoader.getSystemClassLoader()

Sample code :

Properties prop = new Properties();
InputStream input = null;
try {
    input = ClassLoader.getSystemClassLoader().getResourceAsStream("conf.properties");
    prop.load(input);

} catch (IOException io) {
    io.printStackTrace();
}

Angular: Cannot find a differ supporting object '[object Object]'

I received this error in my code because I'd not run JSON.parse(result).

So my result was a string instead of an array of objects.

i.e. I got:

"[{},{}]" 

instead of:

[{},{}]

import { Storage } from '@ionic/storage';
...
private static readonly SERVER = 'server';
...
getStorage(): Promise {
  return this.storage.get(LoginService.SERVER);
}
...
this.getStorage()
  .then((value) => {
     let servers: Server[] = JSON.parse(value) as Server[];
                   }
  );

How to get a tab character?

I use <span style="display: inline-block; width: 2ch;">&#9;</span> for a two characters wide tab.

How to unpack and pack pkg file?

@shrx I've succeeded to unpack the BSD.pkg (part of the Yosemite installer) by using "pbzx" command.

pbzx <pkg> | cpio -idmu

The "pbzx" command can be downloaded from the following link:

Set value of input instead of sendKeys() - Selenium WebDriver nodejs

Thanks to Andrey-Egorov and this answer, I've managed to do it in C#

IWebDriver driver = new ChromeDriver();
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
string value = (string)js.ExecuteScript("document.getElementById('elementID').setAttribute('value', 'new value for element')");

Direct download from Google Drive using Google Drive API

#Case 1: download file with small size.

#Case 2: download file with large size.

  • You stuck a wall of a virus scan alert page returned. By parsing html dom element, I tried to get link with confirm code under button "Download anyway" but it didn't work. Its may required cookie or session info. enter image description here

SOLUTION:

  • Finally I found solution for two above cases. Just need to put httpConnection.setDoOutput(true) in connection step to get a Json.

    )]}' { "disposition":"SCAN_CLEAN", "downloadUrl":"http:www...", "fileName":"exam_list_json.txt", "scanResult":"OK", "sizeBytes":2392}

Then, you can use any Json parser to read downloadUrl, fileName and sizeBytes.

  • You can refer follow snippet, hope it help.

    private InputStream gConnect(String remoteFile) throws IOException{
        URL  url = new URL(remoteFile);
        URLConnection connection = url.openConnection();
        if(connection instanceof HttpURLConnection){
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            connection.setAllowUserInteraction(false);
            httpConnection.setInstanceFollowRedirects(true);
            httpConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)");
            httpConnection.setDoOutput(true);          
            httpConnection.setRequestMethod("GET");
            httpConnection.connect();
    
            int reqCode = httpConnection.getResponseCode();
    
    
            if(reqCode == HttpURLConnection.HTTP_OK){
                InputStream is = httpConnection.getInputStream();
                Map<String, List<String>> map = httpConnection.getHeaderFields();
                List<String> values = map.get("content-type");
                if(values != null && !values.isEmpty()){
                    String type = values.get(0);
    
                    if(type.contains("text/html")){
                        String cookie = httpConnection.getHeaderField("Set-Cookie");
                        String temp = Constants.getPath(mContext, Constants.PATH_TEMP) + "/temp.html";
                        if(saveGHtmlFile(is, temp)){
                            String href = getRealUrl(temp);
                            if(href != null){
                                return parseUrl(href, cookie);
                            }
                        }
    
    
                    } else if(type.contains("application/json")){
                        String temp = Constants.getPath(mContext, Constants.PATH_TEMP) + "/temp.txt";
                        if(saveGJsonFile(is, temp)){
                            FileDataSet data = JsonReaderHelper.readFileDataset(new File(temp));
                            if(data.getPath() != null){
                                return parseUrl(data.getPath());
                            }
                        }
                    }
                }
                return is;
            }
        }
        return null;
    }
    

And

   public static FileDataSet readFileDataset(File file) throws IOException{
        FileInputStream is = new FileInputStream(file);
        JsonReader reader = new JsonReader(new InputStreamReader(is, "UTF-8"));

        reader.beginObject();
        FileDataSet rs = new FileDataSet();
        while(reader.hasNext()){
            String name = reader.nextName();
            if(name.equals("downloadUrl")){
                rs.setPath(reader.nextString());
            } else if(name.equals("fileName")){
                rs.setName(reader.nextString());
            } else if(name.equals("sizeBytes")){
                rs.setSize(reader.nextLong());
            } else {
                reader.skipValue();
            }
        }
        reader.endObject();
        return rs;

    }

Check whether an array is empty

However, empty($error) still returns true, even though nothing is set.

That's not how empty() works. According to the manual, it will return true on an empty array only. Anything else wouldn't make sense.

Set a DateTime database field to "Now"

Use GETDATE()

Returns the current database system timestamp as a datetime value without the database time zone offset. This value is derived from the operating system of the computer on which the instance of SQL Server is running.

UPDATE table SET date = GETDATE()

MySQL order by before group by

Just to recap, the standard solution uses an uncorrelated subquery and looks like this:

SELECT x.*
  FROM my_table x
  JOIN (SELECT grouping_criteria,MAX(ranking_criterion) max_n FROM my_table GROUP BY grouping_criteria) y
    ON y.grouping_criteria = x.grouping_criteria
   AND y.max_n = x.ranking_criterion;

If you're using an ancient version of MySQL, or a fairly small data set, then you can use the following method:

SELECT x.*
  FROM my_table x
  LEFT
  JOIN my_table y
    ON y.joining_criteria = x.joining_criteria
   AND y.ranking_criteria < x.ranking_criteria
 WHERE y.some_non_null_column IS NULL;  

jQuery - Follow the cursor with a DIV

You don't need jQuery for this. Here's a simple working example:

<!DOCTYPE html>
<html>
    <head>
        <title>box-shadow-experiment</title>
        <style type="text/css">
            #box-shadow-div{
                position: fixed;
                width: 1px;
                height: 1px;
                border-radius: 100%;
                background-color:black;
                box-shadow: 0 0 10px 10px black;
                top: 49%;
                left: 48.85%;
            }
        </style>
        <script type="text/javascript">
            window.onload = function(){
                var bsDiv = document.getElementById("box-shadow-div");
                var x, y;
    // On mousemove use event.clientX and event.clientY to set the location of the div to the location of the cursor:
                window.addEventListener('mousemove', function(event){
                    x = event.clientX;
                    y = event.clientY;                    
                    if ( typeof x !== 'undefined' ){
                        bsDiv.style.left = x + "px";
                        bsDiv.style.top = y + "px";
                    }
                }, false);
            }
        </script>
    </head>
    <body>
        <div id="box-shadow-div"></div>
    </body>
</html>

I chose position: fixed; so scrolling wouldn't be an issue.

how to stop a for loop

Others ways to do the same is:

el = L[0][0]
m=len(L)

print L == [[el]*m]*m

Or:

first_el = L[0][0]
print all(el == first_el for inner_list in L for el in inner_list)

String.equals() with multiple conditions (and one action on result)

Keep the acceptable values in a HashSet and check if your string exists using the contains method:

Set<String> accept = new HashSet<String>(Arrays.asList(new String[] {"john", "mary", "peter"}));
if (accept.contains(some_string)) {
    //...
}

Unable to allocate array with shape and data type

I came across this problem on Windows too. The solution for me was to switch from a 32-bit to a 64-bit version of Python. Indeed, a 32-bit software, like a 32-bit CPU, can adress a maximum of 4 GB of RAM (2^32). So if you have more than 4 GB of RAM, a 32-bit version cannot take advantage of it.

With a 64-bit version of Python (the one labeled x86-64 in the download page), the issue disappeared.

You can check which version you have by entering the interpreter. I, with a 64-bit version, now have: Python 3.7.5rc1 (tags/v3.7.5rc1:4082f600a5, Oct 1 2019, 20:28:14) [MSC v.1916 64 bit (AMD64)], where [MSC v.1916 64 bit (AMD64)] means "64-bit Python".

Note : as of the time of this writing (May 2020), matplotlib is not available on python39, so I recommand installing python37, 64 bits.

Sources :

Break a previous commit into multiple commits

Here is how to split one commit in IntelliJ IDEA, PyCharm, PhpStorm etc

  1. In Version Control log window, select the commit you would like to split, right click and select the Interactively Rebase from Here

  2. mark the one you want to split as edit, click Start Rebasing

  3. You should see a yellow tag is placed meaning that the HEAD is set to that commit. Right click on that commit, select Undo Commit

  4. Now those commits are back to staging area, you can then commit them separately. After all change has been committed, the old commit becomes inactive.

PowerShell : retrieve JSON object by field value

This is my json data:

[
   {
      "name":"Test",
      "value":"TestValue"
   },
   {
      "name":"Test",
      "value":"TestValue"
   }
]

Powershell script:

$data = Get-Content "Path to json file" | Out-String | ConvertFrom-Json

foreach ($line in $data) {
     $line.name
}

How do I redirect a user when a button is clicked?

You can easily wrap your button tag with tag.Using Url.Action() HTML Helper this will get to navigate to one page to another.

<a href='@Url.Action("YourAction", "YourController")'>
    <input type='button' value='Dummy Button' />
</a>

If you want to navigate with javascript onclick() function then use

<input type='button' value='Dummy Button' onclick='window.location = "@Url.Action("YourAction", "YourController")";' />

How To Set Text In An EditText

If you check the docs for EditText, you'll find a setText() method. It takes in a String and a TextView.BufferType. For example:

EditText editText = (EditText)findViewById(R.id.edit_text);
editText.setText("This sets the text.", TextView.BufferType.EDITABLE);

It also inherits TextView's setText(CharSequence) and setText(int) methods, so you can set it just like a regular TextView:

editText.setText("Hello world!");
editText.setText(R.string.hello_world);

Send an Array with an HTTP Get

That depends on what the target server accepts. There is no definitive standard for this. See also a.o. Wikipedia: Query string:

While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field (e.g. field1=value1&field1=value2&field2=value3).[4][5]

Generally, when the target server uses a strong typed programming language like Java (Servlet), then you can just send them as multiple parameters with the same name. The API usually offers a dedicated method to obtain multiple parameter values as an array.

foo=value1&foo=value2&foo=value3
String[] foo = request.getParameterValues("foo"); // [value1, value2, value3]

The request.getParameter("foo") will also work on it, but it'll return only the first value.

String foo = request.getParameter("foo"); // value1

And, when the target server uses a weak typed language like PHP or RoR, then you need to suffix the parameter name with braces [] in order to trigger the language to return an array of values instead of a single value.

foo[]=value1&foo[]=value2&foo[]=value3
$foo = $_GET["foo"]; // [value1, value2, value3]
echo is_array($foo); // true

In case you still use foo=value1&foo=value2&foo=value3, then it'll return only the first value.

$foo = $_GET["foo"]; // value1
echo is_array($foo); // false

Do note that when you send foo[]=value1&foo[]=value2&foo[]=value3 to a Java Servlet, then you can still obtain them, but you'd need to use the exact parameter name including the braces.

String[] foo = request.getParameterValues("foo[]"); // [value1, value2, value3]

Is there a C# case insensitive equals operator?

System.Collections.CaseInsensitiveComparer

or

System.StringComparer.OrdinalIgnoreCase

How to find difference between two columns data?

select previous, Present, previous-Present as Difference from tablename

or

select previous, Present, previous-Present as Difference from #TEMP1

How to catch SQLServer timeout exceptions

When a client sends ABORT, no transactions are rolled back. To avoid this behavior we have to use SET_XACT_ABORT ON https://docs.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql?view=sql-server-ver15

How to get the width and height of an android.widget.ImageView?

my friend by this u are not getting height of image stored in db.but you are getting view height.for getting height of image u have to create bitmap from db,s image.and than u can fetch height and width of imageview

C# : "A first chance exception of type 'System.InvalidOperationException'"

Consider using System.Windows.Forms.Timer instead of System.Threading.Timer for a GUI application, for timers that are based on the Windows message queue instead of on dedicated threads or the thread pool.

In your scenario, for the purpose of periodic updates of UI, it seems particularly appropriate since you don't really have a background work or long calculation to perform. You just want to do periodic small tasks that have to happen on the UI thread anyway.

Why should I use a pointer rather than the object itself?

This is has been discussed at length, but in Java everything is a pointer. It makes no distinction between stack and heap allocations (all objects are allocated on the heap), so you don't realize you're using pointers. In C++, you can mix the two, depending on your memory requirements. Performance and memory usage is more deterministic in C++ (duh).

Checking whether a String contains a number value in Java

Why don't you try to write a function based on Integer.parseInt(String obj) ? The function could accept as parameter your String object, and then tokenize the String and use Integer.parseInt(String obj) to extract the number from the "lucky" substring...

Javadoc of Integer.parseInt(String obj)

ORACLE convert number to string

This should solve your problem:

select replace(to_char(a, '90D90'),'.00','')
from
(
select 50 a from dual
union
select 50.57 from dual
union
select 5.57 from dual
union
select 0.35 from dual
union
select 0.4 from dual
);

Give a look also as this SQL Fiddle for test.

Pure Javascript listen to input value change

If you would like to monitor the changes each time there is a keystroke on the keyboard.

const textarea = document.querySelector(`#string`)
textarea.addEventListener("keydown", (e) =>{
   console.log('test') 
})

pythonic way to do something N times without an index variable?

I found the various answers really elegant (especially Alex Martelli's) but I wanted to quantify performance first hand, so I cooked up the following script:

from itertools import repeat
N = 10000000

def payload(a):
    pass

def standard(N):
    for x in range(N):
        payload(None)

def underscore(N):
    for _ in range(N):
        payload(None)

def loopiter(N):
    for _ in repeat(None, N):
        payload(None)

def loopiter2(N):
    for _ in map(payload, repeat(None, N)):
        pass

if __name__ == '__main__':
    import timeit
    print("standard: ",timeit.timeit("standard({})".format(N),
        setup="from __main__ import standard", number=1))
    print("underscore: ",timeit.timeit("underscore({})".format(N),
        setup="from __main__ import underscore", number=1))
    print("loopiter: ",timeit.timeit("loopiter({})".format(N),
        setup="from __main__ import loopiter", number=1))
    print("loopiter2: ",timeit.timeit("loopiter2({})".format(N),
        setup="from __main__ import loopiter2", number=1))

I also came up with an alternative solution that builds on Martelli's one and uses map() to call the payload function. OK, I cheated a bit in that I took the freedom of making the payload accept a parameter that gets discarded: I don't know if there is a way around this. Nevertheless, here are the results:

standard:  0.8398549720004667
underscore:  0.8413165839992871
loopiter:  0.7110594899968419
loopiter2:  0.5891903560004721

so using map yields an improvement of approximately 30% over the standard for loop and an extra 19% over Martelli's.

React won't load local images

Here is what worked for me. First, let us understand the problem. You cannot use a variable as argument to require. Webpack needs to know what files to bundle at compile time.

When I got the error, I thought it may be related to path issue as in absolute vs relative. So I passed a hard-coded value to require like below: <img src={require("../assets/images/photosnap.svg")} alt="" />. It was working fine. But in my case the value is a variable coming from props. I tried to pass a string literal variable as some suggested. It did not work. Also I tried to define a local method using switch case for all 10 values (I knew it was not best solution, but I just wanted it to work somehow). That too did not work. Then I came to know that we can NOT pass variable to the require.

As a workaround I have modified the data in the data.json file to confine it to just the name of my image. This image name which is coming from the props as a String literal. I concatenated it to the hard coded value, like so:

import React from "react";

function JobCard(props) {  

  const { logo } = props;
  
  return (
      <div className="jobCards">
          <img src={require(`../assets/images/${logo}`)} alt="" /> 
      </div>
    )
} 
  

The actual value contained in the logo would be coming from data.json file and would refer to some image name like photosnap.svg.

'cout' was not declared in this scope

Put the following code before int main():

using namespace std;

And you will be able to use cout.

For example:

#include<iostream>
using namespace std;
int main(){
    char t = 'f';
    char *t1;
    char **t2;
    cout<<t;        
    return 0;
}

Now take a moment and read up on what cout is and what is going on here: http://www.cplusplus.com/reference/iostream/cout/


Further, while its quick to do and it works, this is not exactly a good advice to simply add using namespace std; at the top of your code. For detailed correct approach, please read the answers to this related SO question.

How to create a dump with Oracle PL/SQL Developer?

Just to keep this up to date:

The current version of SQLDeveloper has an export tool (Tools > Database Export) that will allow you to dump a schema to a file, with filters for object types, object names, table data etc.

It's a fair amount easier to set-up and use than exp and imp if you're used to working in a GUI environment, but not as versatile if you need to use it for scripting anything.

Find the paths between two given nodes?

The original code is a bit cumbersome and you might want to use the collections.deque instead if you want to use BFS to find if a path exists between 2 points on the graph. Here is a quick solution I hacked up:

Note: this method might continue infinitely if there exists no path between the two nodes. I haven't tested all cases, YMMV.

from collections import deque

# a sample graph
  graph = {'A': ['B', 'C','E'],
           'B': ['A','C', 'D'],
           'C': ['D'],
           'D': ['C'],
           'E': ['F','D'],
           'F': ['C']}

   def BFS(start, end):
    """ Method to determine if a pair of vertices are connected using BFS

    Args:
      start, end: vertices for the traversal.

    Returns:
      [start, v1, v2, ... end]
    """
    path = []
    q = deque()
    q.append(start)
    while len(q):
      tmp_vertex = q.popleft()
      if tmp_vertex not in path:
        path.append(tmp_vertex)

      if tmp_vertex == end:
        return path

      for vertex in graph[tmp_vertex]:
        if vertex not in path:
          q.append(vertex)

"Object doesn't support this property or method" error in IE11

Add the code snippet in JS file used in master page or used globally.

<script language="javascript">
if (typeof browseris !== 'undefined') {
    browseris.ie = false;
}
</script>

For more information refer blog: http://blogs2share.blogspot.in/2016/11/object-doesnt-support-property-or.html

Shell Script: Execute a python program from within a shell script

I use this and it works fine

#/bin/bash
/usr/bin/python python python_script.py

Select from multiple tables without a join?

You could try this notattion:

SELECT * from table1,table2 

More complicated one :

SELECT table1.field1,table1.field2, table2.field3,table2.field8 from table1,table2 where table1.field2 = something and table2.field3 = somethingelse

When should I use Async Controllers in ASP.NET MVC?

You may find my MSDN article on the subject helpful; I took a lot of space in that article describing when you should use async on ASP.NET, not just how to use async on ASP.NET.

I have some concerns using async actions in ASP.NET MVC. When it improves performance of my apps, and when - not.

First, understand that async/await is all about freeing up threads. On GUI applications, it's mainly about freeing up the GUI thread so the user experience is better. On server applications (including ASP.NET MVC), it's mainly about freeing up the request thread so the server can scale.

In particular, it won't:

  • Make your individual requests complete faster. In fact, they will complete (just a teensy bit) slower.
  • Return to the caller/browser when you hit an await. await only "yields" to the ASP.NET thread pool, not to the browser.

First question is - is it good to use async action everywhere in ASP.NET MVC?

I'd say it's good to use it everywhere you're doing I/O. It may not necessarily be beneficial, though (see below).

However, it's bad to use it for CPU-bound methods. Sometimes devs think they can get the benefits of async by just calling Task.Run in their controllers, and this is a horrible idea. Because that code ends up freeing up the request thread by taking up another thread, so there's no benefit at all (and in fact, they're taking the penalty of extra thread switches)!

Shall I use async/await keywords when I want to query database (via EF/NHibernate/other ORM)?

You could use whatever awaitable methods you have available. Right now most of the major players support async, but there are a few that don't. If your ORM doesn't support async, then don't try to wrap it in Task.Run or anything like that (see above).

Note that I said "you could use". If you're talking about ASP.NET MVC with a single database backend, then you're (almost certainly) not going to get any scalability benefit from async. This is because IIS can handle far more concurrent requests than a single instance of SQL server (or other classic RDBMS). However, if your backend is more modern - a SQL server cluster, Azure SQL, NoSQL, etc - and your backend can scale, and your scalability bottleneck is IIS, then you can get a scalability benefit from async.

Third question - How many times I can use await keywords to query database asynchronously in ONE single action method?

As many as you like. However, note that many ORMs have a one-operation-per-connection rule. In particular, EF only allows a single operation per DbContext; this is true whether the operation is synchronous or asynchronous.

Also, keep in mind the scalability of your backend again. If you're hitting a single instance of SQL Server, and your IIS is already capable of keeping SQLServer at full capacity, then doubling or tripling the pressure on SQLServer is not going to help you at all.

On delete cascade with doctrine2

Here is simple example. A contact has one to many associated phone numbers. When a contact is deleted, I want all its associated phone numbers to also be deleted, so I use ON DELETE CASCADE. The one-to-many/many-to-one relationship is implemented with by the foreign key in the phone_numbers.

CREATE TABLE contacts
 (contact_id BIGINT AUTO_INCREMENT NOT NULL,
 name VARCHAR(75) NOT NULL,
 PRIMARY KEY(contact_id)) ENGINE = InnoDB;

CREATE TABLE phone_numbers
 (phone_id BIGINT AUTO_INCREMENT NOT NULL,
  phone_number CHAR(10) NOT NULL,
 contact_id BIGINT NOT NULL,
 PRIMARY KEY(phone_id),
 UNIQUE(phone_number)) ENGINE = InnoDB;

ALTER TABLE phone_numbers ADD FOREIGN KEY (contact_id) REFERENCES \
contacts(contact_id) ) ON DELETE CASCADE;

By adding "ON DELETE CASCADE" to the foreign key constraint, phone_numbers will automatically be deleted when their associated contact is deleted.

INSERT INTO table contacts(name) VALUES('Robert Smith');
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8963333333', 1);
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8964444444', 1);

Now when a row in the contacts table is deleted, all its associated phone_numbers rows will automatically be deleted.

DELETE TABLE contacts as c WHERE c.id=1; /* delete cascades to phone_numbers */

To achieve the same thing in Doctrine, to get the same DB-level "ON DELETE CASCADE" behavoir, you configure the @JoinColumn with the onDelete="CASCADE" option.

<?php
namespace Entities;

use Doctrine\Common\Collections\ArrayCollection;

/**
 * @Entity
 * @Table(name="contacts")
 */
class Contact 
{

    /**
     *  @Id
     *  @Column(type="integer", name="contact_id") 
     *  @GeneratedValue
     */
    protected $id;  

    /** 
     * @Column(type="string", length="75", unique="true") 
     */ 
    protected $name; 

    /** 
     * @OneToMany(targetEntity="Phonenumber", mappedBy="contact")
     */ 
    protected $phonenumbers; 

    public function __construct($name=null)
    {
        $this->phonenumbers = new ArrayCollection();

        if (!is_null($name)) {

            $this->name = $name;
        }
    }

    public function getId()
    {
        return $this->id;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function addPhonenumber(Phonenumber $p)
    {
        if (!$this->phonenumbers->contains($p)) {

            $this->phonenumbers[] = $p;
            $p->setContact($this);
        }
    }

    public function removePhonenumber(Phonenumber $p)
    {
        $this->phonenumbers->remove($p);
    }
}

<?php
namespace Entities;

/**
 * @Entity
 * @Table(name="phonenumbers")
 */
class Phonenumber 
{

    /**
    * @Id
    * @Column(type="integer", name="phone_id") 
    * @GeneratedValue
    */
    protected $id; 

    /**
     * @Column(type="string", length="10", unique="true") 
     */  
    protected $number;

    /** 
     * @ManyToOne(targetEntity="Contact", inversedBy="phonenumbers")
     * @JoinColumn(name="contact_id", referencedColumnName="contact_id", onDelete="CASCADE")
     */ 
    protected $contact; 

    public function __construct($number=null)
    {
        if (!is_null($number)) {

            $this->number = $number;
        }
    }

    public function setPhonenumber($number)
    {
        $this->number = $number;
    }

    public function setContact(Contact $c)
    {
        $this->contact = $c;
    }
} 
?>

<?php

$em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);

$contact = new Contact("John Doe"); 

$phone1 = new Phonenumber("8173333333");
$phone2 = new Phonenumber("8174444444");
$em->persist($phone1);
$em->persist($phone2);
$contact->addPhonenumber($phone1); 
$contact->addPhonenumber($phone2); 

$em->persist($contact);
try {

    $em->flush();
} catch(Exception $e) {

    $m = $e->getMessage();
    echo $m . "<br />\n";
}

If you now do

# doctrine orm:schema-tool:create --dump-sql

you will see that the same SQL will be generated as in the first, raw-SQL example

How do I extract the contents of an rpm?

In OpenSuse at least, the unrpm command comes with the build package.

In a suitable directory (because this is an archive bomb):

unrpm file.rpm

Python return statement error " 'return' outside function"

As per the documentation on the return statement, return may only occur syntactically nested in a function definition. The same is true for yield.

How to listen state changes in react.js?

In 2020 you can listen state changes with useEffect hook like this

export function MyComponent(props) {
    const [myState, setMystate] = useState('initialState')

    useEffect(() => {
        console.log(myState, '- Has changed')
    },[myState]) // <-- here put the parameter to listen
}

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

I coded up an equivalent C program to experiment, and I can confirm this strange behaviour. What's more, gcc believes the 64-bit integer (which should probably be a size_t anyway...) to be better, as using uint_fast32_t causes gcc to use a 64-bit uint.

I did a bit of mucking around with the assembly:
Simply take the 32-bit version, replace all 32-bit instructions/registers with the 64-bit version in the inner popcount-loop of the program. Observation: the code is just as fast as the 32-bit version!

This is obviously a hack, as the size of the variable isn't really 64 bit, as other parts of the program still use the 32-bit version, but as long as the inner popcount-loop dominates performance, this is a good start.

I then copied the inner loop code from the 32-bit version of the program, hacked it up to be 64 bit, fiddled with the registers to make it a replacement for the inner loop of the 64-bit version. This code also runs as fast as the 32-bit version.

My conclusion is that this is bad instruction scheduling by the compiler, not actual speed/latency advantage of 32-bit instructions.

(Caveat: I hacked up assembly, could have broken something without noticing. I don't think so.)

Force file download with php using header()

I’m pretty sure you don’t add the mime type as a JPEG on file downloads:

header('Content-Type: image/png');

These headers have never failed me:

$quoted = sprintf('"%s"', addcslashes(basename($file), '"\\'));
$size   = filesize($file);

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $quoted); 
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $size);

Find what 2 numbers add to something and multiply to something

That's basically a set of 2 simultaneous equations:

x*y = a
X+y = b

(using the mathematical convention of x and y for the variables to solve and a and b for arbitrary constants).

But the solution involves a quadratic equation (because of the x*y), so depending on the actual values of a and b, there may not be a solution, or there may be multiple solutions.

ERROR 1396 (HY000): Operation CREATE USER failed for 'jack'@'localhost'

I had the same error. But command "FLUSH PRIVILEGES;" didn't help. I did like that:

CREATE USER 'jimmy'@'localhost' IDENTIFIED BY 'test123';
UPDATE mysql.user SET USER='jack' WHERE USER='jimmy';

Excel VBA - Delete empty rows

How about

sub foo()
  dim r As Range, rows As Long, i As Long
  Set r = ActiveSheet.Range("A1:Z50")
  rows = r.rows.Count
  For i = rows To 1 Step (-1)
    If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
  Next
End Sub

Try this

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Range("A" & i & ":" & "Z" & i)
            Else
                Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

IF you want to delete the entire row then use this code

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Rows(i)
            Else
                Set DelRange = Union(DelRange, Rows(i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

WCF service startup error "This collection already contains an address with scheme http"

I had this problem, and the cause was rather silly. I was trying out Microsoft's demo regarding running a ServiceHost from w/in a Command Line executable. I followed the instructions, including where it says to add the appropriate Service (and interface). But I got the above error.

Turns out when I added the service class, VS automatically added the configuration to the app.config. And the demo was trying to add that info too. Since it was already in the config, I removed the demo part, and it worked.

Installing Apple's Network Link Conditioner Tool

For Xcode 8 you gotta download a package named Additional Tools for Xcode 8

For other versions (8.1, 8.2) get the package here

Double click and open the dmg and go to Hardware directory. Double click on Network Link Conditioner.prefPane.

enter image description here

Click on install

enter image description here

Now Network Link Conditioner will be available in System Preferences.

For versions older than Xcode 8, the package to be downloaded is called Hardware IO Tools for Xcode. Get it from this page

Add jars to a Spark Job - spark-submit

There is restriction on using --jars: if you want to specify a directory for location of jar/xml file, it doesn't allow directory expansions. This means if you need to specify absolute path for each jar.

If you specify --driver-class-path and you are executing in yarn cluster mode, then driver class doesn't get updated. We can verify if class path is updated or not under spark ui or spark history server under tab environment.

Option which worked for me to pass jars which contain directory expansions and which worked in yarn cluster mode was --conf option. It's better to pass driver and executor class paths as --conf, which adds them to spark session object itself and those paths are reflected on Spark Configuration. But Please make sure to put jars on the same path across the cluster.

spark-submit \
  --master yarn \
  --queue spark_queue \
  --deploy-mode cluster    \
  --num-executors 12 \
  --executor-memory 4g \
  --driver-memory 8g \
  --executor-cores 4 \
  --conf spark.ui.enabled=False \
  --conf spark.driver.extraClassPath=/usr/hdp/current/hbase-master/lib/hbase-server.jar:/usr/hdp/current/hbase-master/lib/hbase-common.jar:/usr/hdp/current/hbase-master/lib/hbase-client.jar:/usr/hdp/current/hbase-master/lib/zookeeper.jar:/usr/hdp/current/hbase-master/lib/hbase-protocol.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/scopt_2.11-3.3.0.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/spark-examples_2.10-1.1.0.jar:/etc/hbase/conf \
  --conf spark.hadoop.mapred.output.dir=/tmp \
  --conf spark.executor.extraClassPath=/usr/hdp/current/hbase-master/lib/hbase-server.jar:/usr/hdp/current/hbase-master/lib/hbase-common.jar:/usr/hdp/current/hbase-master/lib/hbase-client.jar:/usr/hdp/current/hbase-master/lib/zookeeper.jar:/usr/hdp/current/hbase-master/lib/hbase-protocol.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/scopt_2.11-3.3.0.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/spark-examples_2.10-1.1.0.jar:/etc/hbase/conf \
  --conf spark.hadoop.mapreduce.output.fileoutputformat.outputdir=/tmp

Object of class mysqli_result could not be converted to string in

Before using the $result variable, you should use $row = mysqli_fetch_array($result) or mysqli_fetch_assoc() functions.

Like this:

$row = mysqli_fetch_array($result);

and use the $row array as you need.

Laravel: Get base url

Check this -

<a href="{{url('/abc/xyz')}}">Go</a>

This is working for me and I hope it will work for you.

What is duck typing?

Duck typing means that an operation does not formally specify the requirements that its operands have to meet, but just tries it out with what is given.

Unlike what others have said, this does not necessarily relate to dynamic languages or inheritance issues.

Example task: Call some method Quack on an object.

Without using duck-typing, a function f doing this task has to specify in advance that its argument has to support some method Quack. A common way is the use of interfaces

interface IQuack { 
    void Quack();
}

void f(IQuack x) { 
    x.Quack(); 
}

Calling f(42) fails, but f(donald) works as long as donald is an instance of a IQuack-subtype.

Another approach is structural typing - but again, the method Quack() is formally specified any anything that cannot prove it quacks in advance will cause a compiler failure.

def f(x : { def Quack() : Unit }) = x.Quack() 

We could even write

f :: Quackable a => a -> IO ()
f = quack

in Haskell, where the Quackable typeclass ensures the existence of our method.


So how does duck typing change this?

Well, as I said, a duck typing system does not specify requirements but just tries if anything works.

Thus, a dynamic type system as Python's always uses duck typing:

def f(x):
    x.Quack()

If f gets an x supporting a Quack(), everything is fine, if not, it will crash at runtime.

But duck typing doesn't imply dynamic typing at all - in fact, there is a very popular but completely static duck typing approach that doesn't give any requirements too:

template <typename T>
void f(T x) { x.Quack(); } 

The function doesn't tell in any way that it wants some x that can Quack, so instead it just tries at compile time and if everything works, it's fine.

How to check if an element is in an array

As of Swift 2.1 NSArrays have containsObjectthat can be used like so:

if myArray.containsObject(objectImCheckingFor){
    //myArray has the objectImCheckingFor
}

Excel: VLOOKUP that returns true or false?

ISNA is the best function to use. I just did. I wanted all cells whose value was NOT in an array to conditionally format to a certain color.

=ISNA(VLOOKUP($A2,Sheet1!$A:$D,2,FALSE))

How do I import a .dmp file into Oracle?

imp system/system-password@SID file=directory-you-selected\FILE.dmp log=log-dir\oracle_load.log fromuser=infodba touser=infodba commit=Y

Right click to select a row in a Datagridview and show a menu to delete it

private void dataGridView1_CellContextMenuStripNeeded(object sender, 
DataGridViewCellContextMenuStripNeededEventArgs e)
{            
    if (e.RowIndex != -1)
    {
        dataGridView1.ClearSelection();
        this.dataGridView1.Rows[e.RowIndex].Selected = true;
        e.ContextMenuStrip = contextMenuStrip1;
    }
}

Check if input is integer type in C

I've been searching for a simpler solution using only loops and if statements, and this is what I came up with. The program also works with negative integers and correctly rejects any mixed inputs that may contain both integers and other characters.


#include <stdio.h>
#include <stdlib.h> // Used for atoi() function
#include <string.h> // Used for strlen() function

#define TRUE 1
#define FALSE 0

int main(void)
{
    char n[10]; // Limits characters to the equivalent of the 32 bits integers limit (10 digits)
    int intTest;
    printf("Give me an int: ");

    do
    {        
        scanf(" %s", n);

        intTest = TRUE; // Sets the default for the integer test variable to TRUE

        int i = 0, l = strlen(n);
        if (n[0] == '-') // Tests for the negative sign to correctly handle negative integer values
            i++;
        while (i < l)
        {            
            if (n[i] < '0' || n[i] > '9') // Tests the string characters for non-integer values
            {              
                intTest = FALSE; // Changes intTest variable from TRUE to FALSE and breaks the loop early
                break;
            }
            i++;
        }
        if (intTest == TRUE)
            printf("%i\n", atoi(n)); // Converts the string to an integer and prints the integer value
        else
            printf("Retry: "); // Prints "Retry:" if tested FALSE
    }
    while (intTest == FALSE); // Continues to ask the user to input a valid integer value
    return 0;
}

LINQ to Entities does not recognize the method

I got the same error in this code:

 var articulos_en_almacen = xx.IV00102.Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();

this was the exactly error:

System.NotSupportedException: 'LINQ to Entities does not recognize the method 'Boolean Exists(System.Predicate`1[conector_gp.Models.almacenes_por_sucursal])' method, and this method cannot be translated into a store expression.'

I solved this way:

var articulos_en_almacen = xx.IV00102.ToList().Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();

I added a .ToList() before my table, this decouple the Entity and linq code, and avoid my next linq expression be translated

NOTE: this solution isn't optimal, because avoid entity filtering, and simply loads all table into memory

Make ABC Ordered List Items Have Bold Style

You could do something like this also:

<ol type="A" style="font-weight: bold;">

<li style="padding-bottom: 8px;">****</li>

It is simple code for the beginners.

This code is been tested in "Mozilla, chrome and edge..

Unzipping files

I wrote an unzipper in Javascript. It works.

It relies on Andy G.P. Na's binary file reader and some RFC1951 inflate logic from notmasteryet. I added the ZipFile class.

working example:
http://cheeso.members.winisp.net/Unzip-Example.htm (dead link)

The source:
http://cheeso.members.winisp.net/srcview.aspx?dir=js-unzip (dead link)

NB: the links are dead; I'll find a new host soon.

Included in the source is a ZipFile.htm demonstration page, and 3 distinct scripts, one for the zipfile class, one for the inflate class, and one for a binary file reader class. The demo also depends on jQuery and jQuery UI. If you just download the js-zip.zip file, all of the necessary source is there.


Here's what the application code looks like in Javascript:

// In my demo, this gets attached to a click event.
// it instantiates a ZipFile, and provides a callback that is
// invoked when the zip is read.  This can take a few seconds on a
// large zip file, so it's asynchronous. 
var readFile = function(){
    $("#status").html("<br/>");
    var url= $("#urlToLoad").val();
    var doneReading = function(zip){
        extractEntries(zip);
    };

    var zipFile = new ZipFile(url, doneReading);
};


// this function extracts the entries from an instantiated zip
function extractEntries(zip){
    $('#report').accordion('destroy');

    // clear
    $("#report").html('');

    var extractCb = function(id) {
        // this callback is invoked with the entry name, and entry text
        // in my demo, the text is just injected into an accordion panel.
        return (function(entryName, entryText){
            var content = entryText.replace(new RegExp( "\\n", "g" ), "<br/>");
            $("#"+id).html(content);
            $("#status").append("extract cb, entry(" + entryName + ")  id(" + id + ")<br/>");
            $('#report').accordion('destroy');
            $('#report').accordion({collapsible:true, active:false});
        });
    }

    // for each entry in the zip, extract it. 
    for (var i=0; i<zip.entries.length;  i++) {
        var entry = zip.entries[i];

        var entryInfo = "<h4><a>" + entry.name + "</a></h4>\n<div>";

        // contrive an id for the entry, make it unique
        var randomId = "id-"+ Math.floor((Math.random() * 1000000000));

        entryInfo += "<span class='inputDiv'><h4>Content:</h4><span id='" + randomId +
            "'></span></span></div>\n";

        // insert the info for one entry as the last child within the report div
        $("#report").append(entryInfo);

        // extract asynchronously
        entry.extract(extractCb(randomId));
    }
}

The demo works in a couple of steps: The readFile fn is triggered by a click, and instantiates a ZipFile object, which reads the zip file. There's an asynchronous callback for when the read completes (usually happens in less than a second for reasonably sized zips) - in this demo the callback is held in the doneReading local variable, which simply calls extractEntries, which just blindly unzips all the content of the provided zip file. In a real app you would probably choose some of the entries to extract (allow the user to select, or choose one or more entries programmatically, etc).

The extractEntries fn iterates over all entries, and calls extract() on each one, passing a callback. Decompression of an entry takes time, maybe 1s or more for each entry in the zipfile, which means asynchrony is appropriate. The extract callback simply adds the extracted content to an jQuery accordion on the page. If the content is binary, then it gets formatted as such (not shown).


It works, but I think that the utility is somewhat limited.

For one thing: It's very slow. Takes ~4 seconds to unzip the 140k AppNote.txt file from PKWare. The same uncompress can be done in less than .5s in a .NET program. EDIT: The Javascript ZipFile unpacks considerably faster than this now, in IE9 and in Chrome. It is still slower than a compiled program, but it is plenty fast for normal browser usage.

For another: it does not do streaming. It basically slurps in the entire contents of the zipfile into memory. In a "real" programming environment you could read in only the metadata of a zip file (say, 64 bytes per entry) and then read and decompress the other data as desired. There's no way to do IO like that in javascript, as far as I know, therefore the only option is to read the entire zip into memory and do random access in it. This means it will place unreasonable demands on system memory for large zip files. Not so much a problem for a smaller zip file.

Also: It doesn't handle the "general case" zip file - there are lots of zip options that I didn't bother to implement in the unzipper - like ZIP encryption, WinZip encryption, zip64, UTF-8 encoded filenames, and so on. (EDIT - it handles UTF-8 encoded filenames now). The ZipFile class handles the basics, though. Some of these things would not be hard to implement. I have an AES encryption class in Javascript; that could be integrated to support encryption. Supporting Zip64 would probably useless for most users of Javascript, as it is intended to support >4gb zipfiles - don't need to extract those in a browser.

I also did not test the case for unzipping binary content. Right now it unzips text. If you have a zipped binary file, you'd need to edit the ZipFile class to handle it properly. I didn't figure out how to do that cleanly. It does binary files now, too.


EDIT - I updated the JS unzip library and demo. It now does binary files, in addition to text. I've made it more resilient and more general - you can now specify the encoding to use when reading text files. Also the demo is expanded - it shows unzipping an XLSX file in the browser, among other things.

So, while I think it is of limited utility and interest, it works. I guess it would work in Node.js.

How to remove spaces from a string using JavaScript?

This?

str = str.replace(/\s/g, '');

Example

_x000D_
_x000D_
var str = '/var/www/site/Brand new document.docx';_x000D_
_x000D_
document.write( str.replace(/\s/g, '') );
_x000D_
_x000D_
_x000D_


Update: Based on this question, this:

str = str.replace(/\s+/g, '');

is a better solution. It produces the same result, but it does it faster.

The Regex

\s is the regex for "whitespace", and g is the "global" flag, meaning match ALL \s (whitespaces).

A great explanation for + can be found here.

As a side note, you could replace the content between the single quotes to anything you want, so you can replace whitespace with any other string.

How can I have linebreaks in my long LaTeX equations?

If it is inline equation, then use \allowbreak. Use it like:

$x_1,x_2,x_3,\allowbreak x_4,x_5$.

Latex will break equation in this place only if necessary.

How do I view the full content of a text or varchar(MAX) column in SQL Server 2008 Management Studio?

SSMS only allows unlimited data for XML data. This is not the default and needs to be set in the options.

enter image description here

One trick which might work in quite limited circumstances is simply naming the column in a special manner as below so it gets treated as XML data.

DECLARE @S varchar(max) = 'A'

SET @S =  REPLICATE(@S,100000) + 'B' 

SELECT @S as [XML_F52E2B61-18A1-11d1-B105-00805F49916B]

In SSMS (at least versions 2012 to current of 18.3) this displays the results as below

enter image description here

Clicking on it opens the full results in the XML viewer. Scrolling to the right shows the last character of B is preserved,

However this does have some significant problems. Adding extra columns to the query breaks the effect and extra rows all become concatenated with the first one. Finally if the string contains characters such as < opening the XML viewer fails with a parsing error.

A more robust way of doing this that avoids issues of SQL Server converting < to &lt; etc or failing due to these characters is below (credit Adam Machanic here).

DECLARE @S varchar(max)

SELECT @S = ''

SELECT @S = @S + '
' + OBJECT_DEFINITION(OBJECT_ID) FROM SYS.PROCEDURES

SELECT @S AS [processing-instruction(x)] FOR XML PATH('')

Show div #id on click with jQuery

The problem you're having is that the event-handlers are being bound before the elements are present in the DOM, if you wrap the jQuery inside of a $(document).ready() then it should work perfectly well:

$(document).ready(
    function(){
        $("#music").click(function () {
            $("#musicinfo").show("slow");
        });

    });

An alternative is to place the <script></script> at the foot of the page, so it's encountered after the DOM has been loaded and ready.

To make the div hide again, once the #music element is clicked, simply use toggle():

$(document).ready(
    function(){
        $("#music").click(function () {
            $("#musicinfo").toggle();
        });
    });

JS Fiddle demo.

And for fading:

$(document).ready(
    function(){
        $("#music").click(function () {
            $("#musicinfo").fadeToggle();
        });
    });

JS Fiddle demo.

How to install a package inside virtualenv?

Well i don't have an appropriate reason regarding why this behavior occurs but then i just found a small work around

Inside the VirtualEnvironment

pip install -Iv package_name==version_number

now this will install the version in your virtual environment

Additionally you can check inside the virtual environment with this

pip install yolk
yolk -l

This shall give you the details of all the installed packages in both the locations(system and virtualenv)

While some might say its not appropriate to use --system-site-packages (it may be true), but what if you have already done a lot of stuffs inside your virtualenv? Now you dont want to redo everything from the scratch.

You may use this as a hack and be careful from the next time :)

Xcode variables

Here's a list of the environment variables. I think you might want CURRENT_VARIANT. See also BUILD_VARIANTS.

Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag

You should put your component between an enclosing tag, Which means:

// WRONG!

return (  
    <Comp1 />
    <Comp2 />
)

Instead:

// Correct

return (
    <div>
       <Comp1 />
       <Comp2 />
    </div>
)

Edit: Per Joe Clay's comment about the Fragments API

// More Correct

return (
    <React.Fragment>
       <Comp1 />
       <Comp2 />
    </React.Fragment>
)

// Short syntax

return (
    <>
       <Comp1 />
       <Comp2 />
    </>
)

Store an array in HashMap

If you want to store multiple values for a key (if I understand you correctly), you could try a MultiHashMap (available in various libraries, not only commons-collections).

How to set up Android emulator proxy settings

Depending on which environment you are using to run the emulator, check the logs to see how the emulator is started. Mine is started as:

C:\Users\johan\AppData\Local\Android\Sdk\tools\emulator.exe -netdelay none -netspeed full -avd Nexus_5X_API_23

Then you add the -http-proxy option, in my case:

C:\Users\johan\AppData\Local\Android\Sdk\tools\emulator.exe -netdelay none -netspeed full -avd Nexus_5X_API_23 -http-proxy 192.168.0.22:8888

Calling C/C++ from Python?

pybind11 minimal runnable example

pybind11 was previously mentioned at https://stackoverflow.com/a/38542539/895245 but I would like to give here a concrete usage example and some further discussion about implementation.

All and all, I highly recommend pybind11 because it is really easy to use: you just include a header and then pybind11 uses template magic to inspect the C++ class you want to expose to Python and does that transparently.

The downside of this template magic is that it slows down compilation immediately adding a few seconds to any file that uses pybind11, see for example the investigation done on this issue. PyTorch agrees. A proposal to remediate this problem has been made at: https://github.com/pybind/pybind11/pull/2445

Here is a minimal runnable example to give you a feel of how awesome pybind11 is:

class_test.cpp

#include <string>

#include <pybind11/pybind11.h>

struct ClassTest {
    ClassTest(const std::string &name) : name(name) { }
    void setName(const std::string &name_) { name = name_; }
    const std::string &getName() const { return name; }
    std::string name;
};

namespace py = pybind11;

PYBIND11_PLUGIN(class_test) {
    py::module m("my_module", "pybind11 example plugin");
    py::class_<ClassTest>(m, "ClassTest")
        .def(py::init<const std::string &>())
        .def("setName", &ClassTest::setName)
        .def("getName", &ClassTest::getName)
        .def_readwrite("name", &ClassTest::name);
    return m.ptr();
}

class_test_main.py

#!/usr/bin/env python3

import class_test

my_class_test = class_test.ClassTest("abc");
print(my_class_test.getName())
my_class_test.setName("012")
print(my_class_test.getName())
assert(my_class_test.getName() == my_class_test.name)

Compile and run:

#!/usr/bin/env bash
set -eux
g++ `python3-config --cflags` -shared -std=c++11 -fPIC class_test.cpp \
  -o class_test`python3-config --extension-suffix` `python3-config --libs`
./class_test_main.py

This example shows how pybind11 allows you to effortlessly expose the ClassTest C++ class to Python! Compilation produces a file named class_test.cpython-36m-x86_64-linux-gnu.so which class_test_main.py automatically picks up as the definition point for the class_test natively defined module.

Perhaps the realization of how awesome this is only sinks in if you try to do the same thing by hand with the native Python API, see for example this example of doing that, which has about 10x more code: https://github.com/cirosantilli/python-cheat/blob/4f676f62e87810582ad53b2fb426b74eae52aad5/py_from_c/pure.c On that example you can see how the C code has to painfully and explicitly define the Python class bit by bit with all the information it contains (members, methods, further metadata...). See also:

pybind11 claims to be similar to Boost.Python which was mentioned at https://stackoverflow.com/a/145436/895245 but more minimal because it is freed from the bloat of being inside the Boost project:

pybind11 is a lightweight header-only library that exposes C++ types in Python and vice versa, mainly to create Python bindings of existing C++ code. Its goals and syntax are similar to the excellent Boost.Python library by David Abrahams: to minimize boilerplate code in traditional extension modules by inferring type information using compile-time introspection.

The main issue with Boost.Python—and the reason for creating such a similar project—is Boost. Boost is an enormously large and complex suite of utility libraries that works with almost every C++ compiler in existence. This compatibility has its cost: arcane template tricks and workarounds are necessary to support the oldest and buggiest of compiler specimens. Now that C++11-compatible compilers are widely available, this heavy machinery has become an excessively large and unnecessary dependency.

Think of this library as a tiny self-contained version of Boost.Python with everything stripped away that isn't relevant for binding generation. Without comments, the core header files only require ~4K lines of code and depend on Python (2.7 or 3.x, or PyPy2.7 >= 5.7) and the C++ standard library. This compact implementation was possible thanks to some of the new C++11 language features (specifically: tuples, lambda functions and variadic templates). Since its creation, this library has grown beyond Boost.Python in many ways, leading to dramatically simpler binding code in many common situations.

pybind11 is also the only non-native alternative hightlighted by the current Microsoft Python C binding documentation at: https://docs.microsoft.com/en-us/visualstudio/python/working-with-c-cpp-python-in-visual-studio?view=vs-2019 (archive).

Tested on Ubuntu 18.04, pybind11 2.0.1, Python 3.6.8, GCC 7.4.0.