Programs & Examples On #Httpapplication

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

In my case my site on IIS was pointing to a different project than the one I was running on visual studio.

System.Data.SqlClient.SqlException: Login failed for user

I just ran into this error and it took days to resolve. We were thrown for a loop by the red-herring error message mentioned in the initial question, plus the Windows Event Viewer error log indicated something similar:

Login failed for user '(domain\name-PC)$'. Reason: Could not find a login matching the name provided. [CLIENT: <local machine>]

Neither of these was true, the user had all the necessary permissions in SQL Server.

In our case, the solution was to switch the Application Pool Identity in IIS to NetworkService.

"This operation requires IIS integrated pipeline mode."

I resolved this problem by following steps:

  1. Right click on root folder of project.
  2. Goto properties
  3. Click web in left menu
  4. change current port http://localhost:####/
  5. click create virtual directory
  6. Save the changes (ctrl+s)
  7. Run

may be it help you to.

Could not load file or assembly 'System.Web.Http 4.0.0 after update from 2012 to 2013

For me it was only crashing with this error on a production environment, not on local machine; what solved it was to delete the content of /bin folder and then to regenerate it again.

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

We recently upgraded to the NuGet version of SqlClient (Microsoft.Data.SqlClient) which contains a bug. This bug was introduced during the lifetime of the 1.x cycle and has already been fixed. The fix will be available in the 2.0.0 release which is not available at the time of this writing. A preview is available.

You can inspect the details here: https://github.com/dotnet/SqlClient/issues/262

An item with the same key has already been added

I hit this in MVC 5 and Visual Studio Express 2013. I had two properties with an IndexAttribute like below. Commenting out one of them and recompiling resulted in scaffolding the MVC 5 controller with views, using Entity Framework succeeding. Mysteriously, when I uncommented the attribute, recompiled, and tried again, the scaffolder ran just fine.

Perhaps the underlying entity data model or "something" was cached/corrupted, and removing and re-adding the IndexAttribute simply triggered a rebuild of that "something".

[Index(IsUnique = true)]
public string Thing1 { get; set; }

[Index(IsUnique = true)]
public string Thing2 { get; set; }

The remote host closed the connection. The error code is 0x800704CD

I get this one all the time. It means that the user started to download a file, and then it either failed, or they cancelled it.

To reproduce the exception try do this yourself - however I'm unaware of any ways to prevent it (except for handling this specific exception only).

You need to decide what the best way forward is depending on your app.

Server cannot set status after HTTP headers have been sent IIS7.5

We were getting the same error - so this may be useful to some.

For us the cause was super simple. An interface change confused an end user and they were pressing the back button in the browser at a 'bad' time after a form submission (sure we should probably have used a PRG pattern, but we didn't).

We fixed the issue and the user is no longer pressing the back button. Problem solved.

System.Data.SqlClient.SqlException: Invalid object name 'dbo.Projects'

TLDR: Check that you don't connect to the same table/view twice.

FooConfiguration.cs    
builder.ToTable("Profiles", "dbo");
...

BarConfiguration.cs
builder.ToTable("profiles", "dbo");

For me the issue was that I was trying to add an entity that connected to the same table as some other entity that already existed.

I added a new DbSet with entity and config, thinking we don't have it in our solution yet, however after searching for table name through all solution I found another place where we already connected to it.

Switching to use existing DbSet and removing my newly added one solved the issue.

WCF, Service attribute value in the ServiceHost directive could not be found

This error occurs due to mismatch of Service name in .SVC file. Probably you might have changed the name of the service class that is implementing the interface.The Solution is to open .SVC file and exactly match the Service attribute and CodeBehind Attribute. So your .SVC file should be like

<%@ ServiceHost Language="Language you are using" Debug="bool value to enable debugging" Service="Service class name that is implementing your Service interface" Codebehind="~/Appcode/Class implementing interface.cs"%>. for eg.

<%@ ServiceHost Language="C#" Debug="true" Service="Product.Service" CodeBehind="~/AppCode/Product.Service.cs"%>

This example is for .svc file that is using C# language, with debugging enabled, Service class implementing interface and this class is within app folder with name Service.cs and Product is namespace for Service class.

Also Please make respective change in service config file.

<system.serviceModel>
    <services>
        <service name="Product.Service" behaviorConfiguration="ServiceBehavior">
            <endpoint address="" binding="wsHttpBinding" contract="Product.Iservice">
            </endpoint>
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        </service>
    </services>
    <behaviors>
        <behavior name="ServiceBehavior">
            <serviceMetaData httpGetEnabled="true"/>
            <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
    </behaviors>
</system.serviceModel>

How to get file path from OpenFileDialog and FolderBrowserDialog?

Use the Path class from System.IO. It contains useful calls for manipulating file paths, including GetDirectoryName which does what you want, returning the directory portion of the file path.

Usage is simple.

string directoryPath = System.IO.Path.GetDirectoryName(choofdlog.FileName);

MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"?

Increasing number of max-connections will not solve the problem.

We were experiencing the same situation on our servers. This is what happens

User open a page/view, that connect to the database, query the database, still query(queries) were not finished and user leave the page or move to some other page. So the connection that was open, will remains open, and keep increasing number of connections, if there are more users connecting with the db and doing something similar.

You can set interactive_timeout MySQL, bydefault it is 28800 (8hours) to 1 hour

SET interactive_timeout=3600

SQL Server: how to create a stored procedure

CREATE PROCEDURE [dbo].[USP_StudentInformation]
@S_Name VARCHAR(50)
,@S_Address VARCHAR(500)
AS
BEGIN
SET NOCOUNT ON;

DECLARE @Date VARCHAR(50)

SET @Date = GETDATE()


IF EXISTS (
        SELECT *
        FROM TB_StdFunction
        WHERE S_Name = @S_Name
            AND S_Address = @S_Address
        )
BEGIN
    UPDATE TB_StdFunction
    SET S_Name = @S_Name
        ,S_Address = @S_Address
        ,ModifiedDate = @Date
    WHERE S_Name = @S_Name
        AND S_Address = @S_Address

    SELECT *
    FROM TB_StdFunction
END
ELSE
BEGIN
    INSERT INTO TB_StdFunction (
        S_Name
        ,S_Address
        ,CreatedDate
        )
    VALUES (
        @S_Name
        ,@S_Address
        ,@date          
        )

    SELECT *
    FROM TB_StdFunction
END
END

Table Name :   TB_StdFunction


S_No  INT PRIMARY KEY AUTO_INCREMENT
S_Name nvarchar(50)
S_Address nvarchar(500)
CreatedDate nvarchar(50)
ModifiedDate nvarchar(50)

json_encode is returning NULL?

few day ago I have the SAME problem with 1 table.

Firstly try:

echo json_encode($rows);
echo json_last_error();  // returns 5 ?

If last line returns 5, problem is with your data. I know, your tables are in UTF-8, but not entered data. For example the input was in txt file, but created on Win machine with stupid encoding (in my case Win-1250 = CP1250) and this data has been entered into the DB.

Solution? Look for new data (excel, web page), edit source txt file via PSPad (or whatever else), change encoding to UTF-8, delete all rows and now put data from original. Save. Enter into DB.

You can also only change encoding to utf-8 and then change all rows manually (give cols with special chars - desc, ...). Good for slaves...

C# "must declare a body because it is not marked abstract, extern, or partial"

must declare a body because it is not marked abstract, extern, or partialI had the same problem here:

    private static void swapMth(ref int x, ref int y);
    {
        int num = x;
        x = y;
        y = num;
    }


    private void button_Click(object sender, EventArgs e)
    {
        int x = 10;
        int y = 20;
        labelResult.Text = $"Befor      n1 = {x} , n2={y} ";
        swapMth(ref x, ref y);
        labelResult.Text += $"\n After  n1 = {x} , n2={y}";
    }

And it was solved by deleting ";" from the method line:

private static void swapMth(ref int x, ref int y); PROBLEM

to

private static void swapMth(ref int x, ref int y) SOLVED

I know it is basic mistake, hope someone could get help by this note.

    private static void swapMth(ref int x, ref int y)
    {
        int num = x;
        x = y;
        y = num;
    }


    private void button_Click(object sender, EventArgs e)
    {
        int x = 10;
        int y = 20;
        labelResult.Text = $"Befor      n1 = {x} , n2={y} ";
        swapMth(ref x, ref y);
        labelResult.Text += $"\n After  n1 = {x} , n2={y}";
    }

Why do I need to do `--set-upstream` all the time?

You can make this happen with less typing. First, change the way your push works:

git config --global push.default current

This will infer the origin my_branch part, thus you can do:

git push -u

Which will both create the remote branch with the same name and track it.

How to append elements into a dictionary in Swift?

if you want to modify or update NSDictionary then first of all typecast it as NSMutableDictionary

let newdictionary = NSDictionary as NSMutableDictionary

then simply use

 newdictionary.setValue(value: AnyObject?, forKey: String)

How do I translate an ISO 8601 datetime string into a Python datetime object?

I prefer using the dateutil library for timezone handling and generally solid date parsing. If you were to get an ISO 8601 string like: 2010-05-08T23:41:54.000Z you'd have a fun time parsing that with strptime, especially if you didn't know up front whether or not the timezone was included. pyiso8601 has a couple of issues (check their tracker) that I ran into during my usage and it hasn't been updated in a few years. dateutil, by contrast, has been active and worked for me:

import dateutil.parser
yourdate = dateutil.parser.parse(datestring)

Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable

Android Home should be the root folder of SDK.

export ANDROID_HOME="$HOME/android-sdk-linux"

EDIT: Open terminal and type these commands. (yes, on a ternimal , not in bashrc file)

export ANDROID_HOME=~/android-sdk-macosx
PATH=$PATH:$ANDROID_HOME/tools
PATH=$PATH:$ANDROID_HOME/platform-tools    

and then in the same terminal just type android. If configured you would be able to use build commands from this terminal. (it's a temporary solution)

How to compare two JSON have the same properties without order?

This question reminds of how to determine equality for two JavaScript objects. So, I would choose this general function

Compares JS objects:

function objectEquals(x, y) {
    // if both are function
    if (x instanceof Function) {
        if (y instanceof Function) {
            return x.toString() === y.toString();
        }
        return false;
    }
    if (x === null || x === undefined || y === null || y === undefined) { return x === y; }
    if (x === y || x.valueOf() === y.valueOf()) { return true; }

    // if one of them is date, they must had equal valueOf
    if (x instanceof Date) { return false; }
    if (y instanceof Date) { return false; }

    // if they are not function or strictly equal, they both need to be Objects
    if (!(x instanceof Object)) { return false; }
    if (!(y instanceof Object)) { return false; }

    var p = Object.keys(x);
    return Object.keys(y).every(function (i) { return p.indexOf(i) !== -1; }) ?
            p.every(function (i) { return objectEquals(x[i], y[i]); }) : false;
}

$http.get(...).success is not a function

If you are trying to use AngularJs 1.6.6 as of 21/10/2017 the following parameter works as .success and has been depleted. The .then() method takes two arguments: a response and an error callback which will be called with a response object.

 $scope.login = function () {
        $scope.btntext = "Please wait...!";
        $http({
            method: "POST",
            url: '/Home/userlogin', // link UserLogin with HomeController 
            data: $scope.user
         }).then(function (response) {
            console.log("Result value is : " + parseInt(response));
            data = response.data;
            $scope.btntext = 'Login';
            if (data == 1) {
                window.location.href = '/Home/dashboard';
             }
            else {
            alert(data);
        }
        }, function (error) {

        alert("Failed Login");
        });

The above snipit works for a login page.

Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice

I've had a very similar issue using spring-boot-starter-data-redis. To my implementation there was offered a @Bean for RedisTemplate as follows:

@Bean
public RedisTemplate<String, List<RoutePlantCache>> redisTemplate(RedisConnectionFactory connectionFactory) {
    final RedisTemplate<String, List<RoutePlantCache>> template = new RedisTemplate<>();
    template.setConnectionFactory(connectionFactory);
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache.class));

    // Add some specific configuration here. Key serializers, etc.
    return template;
}

The fix was to specify an array of RoutePlantCache as following:

template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache[].class));

Below the exception I had:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `[...].RoutePlantCache` out of START_ARRAY token
 at [Source: (byte[])"[{ ... },{ ... [truncated 1478 bytes]; line: 1, column: 1]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1468) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1242) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1190) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeFromArray(BeanDeserializer.java:604) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:190) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:166) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3572) ~[jackson-databind-2.11.4.jar:2.11.4]

increase legend font size ggplot2

You can also specify the font size relative to the base_size included in themes such as theme_bw() (where base_size is 11) using the rel() function.

For example:

ggplot(mtcars, aes(disp, mpg, col=as.factor(cyl))) +
  geom_point() +
  theme_bw() +
  theme(legend.text=element_text(size=rel(0.5)))

Locating child nodes of WebElements in selenium

According to JavaDocs, you can do this:

WebElement input = divA.findElement(By.xpath(".//input"));

How can I ask in xpath for "the div-tag that contains a span with the text 'hello world'"?

WebElement elem = driver.findElement(By.xpath("//div[span[text()='hello world']]"));

The XPath spec is a suprisingly good read on this.

Write variable to a file in Ansible

Unless you are writing very small files, you should probably use templates.

Example:

- name: copy upstart script
  template: 
    src: myCompany-service.conf.j2 
    dest: "/etc/init/myCompany-service.conf"

How to find value using key in javascript dictionary

Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.

If you make Dict into an object, this will work:

var dict = {};
var addPair = function (myKey, myValue) {
    dict[myKey] = myValue;
};
var giveValue = function (myKey) {
    return dict[myKey];
};

The myKey variable is already a string, so you don't need more quotes.

Open Excel file for reading with VBA without display

Using ADO (AnonJr already explained) and utilizing SQL is possibly the best option for fetching data from a closed workbook without opening that in conventional way. Please watch this VIDEO.

OTHERWISE, possibly GetObject(<filename with path>) is the most CONCISE way. Worksheets remain invisible, however will appear in project explorer window in VBE just like any other workbook opened in conventional ways.

Dim wb As Workbook

Set wb = GetObject("C:\MyData.xlsx")  'Worksheets will remain invisible, no new window appears in the screen
' your codes here
wb.Close SaveChanges:=False

If you want to read a particular sheet, need not even define a Workbook variable

Dim sh As Worksheet
Set sh = GetObject("C:\MyData.xlsx").Worksheets("MySheet")
' your codes here
sh.Parent.Close SaveChanges:=False 'Closes the associated workbook

Check if object is a jQuery object

However, There is one more way to check the object in jQuery.

jQuery.type(a); //this returns type of variable.

I have made example to understand things, jsfiddle link

How to turn off caching on Firefox?

Enter "about:config" into the Firefox address bar and set:

browser.cache.disk.enable = false
browser.cache.memory.enable = false

If developing locally, or using HTML5's new manifest attribute you may have to also set the following in about:config -

browser.cache.offline.enable = false

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

npm install -g increase-memory-limit

increase-memory-limit

OR

  1. Navigate to %appdata% -> npm folder or C:\Users\{user_name}\AppData\Roaming\npm
  2. Open ng.cmd in your favorite editor
  3. Add --max_old_space_size=8192 to the IF and ELSE block

now ng.cmd file looks like this after the change:

@IF EXIST "%~dp0\node.exe" (
  "%~dp0\node.exe" "--max_old_space_size=8192" "%~dp0\node_modules\@angular\cli\bin\ng" %*
) ELSE (
  @SETLOCAL
  @SET PATHEXT=%PATHEXT:;.JS;=;%
  node "--max_old_space_size=8192" "%~dp0\node_modules\@angular\cli\bin\ng" %*
)

TSQL Default Minimum DateTime

Unless you are doing a DB to track historical times more than a century ago, using

Modified datetime DEFAULT ((0)) 

is perfectly safe and sound and allows more elegant queries than '1753-01-01' and more efficient queries than NULL.

However, since first Modified datetime is the time at which the record was inserted, you can use:

Modified datetime NOT NULL DEFAULT (GETUTCDATE())

which avoids the whole issue and makes your inserts easier and safer - as in you don't insert it at all and SQL does the housework :-)

With that in place you can still have elegant and fast queries by using 0 as a practical minimum since it's guranteed to always be lower than any insert-generated GETUTCDATE().

How to remove all files from directory without removing directory in Node.js

To remove all files from a directory, first you need to list all files in the directory using fs.readdir, then you can use fs.unlink to remove each file. Also fs.readdir will give just the file names, you need to concat with the directory name to get the full path.

Here is an example

const fs = require('fs');
const path = require('path');

const directory = 'test';

fs.readdir(directory, (err, files) => {
  if (err) throw err;

  for (const file of files) {
    fs.unlink(path.join(directory, file), err => {
      if (err) throw err;
    });
  }
});

Update node version 14

There is a recursive flag that you can use in rmdir to remove all the files recursively. See nodejs docs for more information.

const fs = require('fs').promises;

const directory = 'test';

fs.rmdir(directory, { recursive: true })
  .then(() => console.log('directory removed!'));

R memory management / cannot allocate vector of size n Mb

If you are running your script at linux environment you can use this command:

bsub -q server_name -R "rusage[mem=requested_memory]" "Rscript script_name.R"

and the server will allocate the requested memory for you (according to the server limits, but with good server - hugefiles can be used)

Alphabet range in Python

In Python 2.7 and 3 you can use this:

import string
string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'

string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

As @Zaz says: string.lowercase is deprecated and no longer works in Python 3 but string.ascii_lowercase works in both

What happens when a duplicate key is put into a HashMap?

You may find your answer in the javadoc of Map#put(K, V) (which actually returns something):

public V put(K key,
             V value)

Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for this key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)

Parameters:
key - key with which the specified value is to be associated.
value - value to be associated with the specified key.

Returns:
previous value associated with specified key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with the specified key, if the implementation supports null values.)

So if you don't assign the returned value when calling mymap.put("1", "a string"), it just becomes unreferenced and thus eligible for garbage collection.

How to split string using delimiter char using T-SQL?

For your specific data, you can use

Select col1, col2, LTRIM(RTRIM(SUBSTRING(
    STUFF(col3, CHARINDEX('|', col3,
    PATINDEX('%|Client Name =%', col3) + 14), 1000, ''),
    PATINDEX('%|Client Name =%', col3) + 14, 1000))) col3
from Table01

EDIT - charindex vs patindex

Test

select col3='Clent ID = 4356hy|Client Name = B B BOB|Client Phone = 667-444-2626|Client Fax = 666-666-0151|Info = INF8888877 -MAC333330554/444400800'
into t1m
from master..spt_values a
cross join master..spt_values b
where a.number < 100
-- (711704 row(s) affected)

set statistics time on

dbcc dropcleanbuffers
dbcc freeproccache
select a=CHARINDEX('|Client Name =', col3) into #tmp1 from t1m
drop table #tmp1

dbcc dropcleanbuffers
dbcc freeproccache
select a=PATINDEX('%|Client Name =%', col3) into #tmp2 from t1m
drop table #tmp2

set statistics time off

Timings

CHARINDEX:

 SQL Server Execution Times (1):
   CPU time = 5656 ms,  elapsed time = 6418 ms.
 SQL Server Execution Times (2):
   CPU time = 5813 ms,  elapsed time = 6114 ms.
 SQL Server Execution Times (3):
   CPU time = 5672 ms,  elapsed time = 6108 ms.

PATINDEX:

 SQL Server Execution Times (1):
   CPU time = 5906 ms,  elapsed time = 6296 ms.
 SQL Server Execution Times (2):
   CPU time = 5860 ms,  elapsed time = 6404 ms.
 SQL Server Execution Times (3):
   CPU time = 6109 ms,  elapsed time = 6301 ms.

Conclusion

The timings for CharIndex and PatIndex for 700k calls are within 3.5% of each other, so I don't think it would matter whichever is used. I use them interchangeably when both can work.

AWK to print field $2 first, then field $1

Use a dot or a pipe as the field separator:

awk -v FS='[.|]' '{
    printf "%s%s %s.%s\n", toupper(substr($4,1,1)), substr($4,2), $1, $2
}' << END
[email protected]|com.emailclient.account
[email protected]|com.socialsite.auth.account
END

gives:

Emailclient [email protected]
Socialsite [email protected]

Convert textbox text to integer

If your SQL database allows Null values for that field try using int? value like that :

if (this.txtboxname.Text == "" || this.txtboxname.text == null)
     value = null;
else
     value = Convert.ToInt32(this.txtboxname.Text);

Take care that Convert.ToInt32 of a null value returns 0 !

Convert.ToInt32(null) returns 0

What is a vertical tab?

I just found the VT char in a .pptx document at several places within a table element. But no clue about how it was inserted.

android: how to align image in the horizontal center of an imageview?

Try:

android:layout_height="wrap_content"
android:scaleType="fitStart"

on the image in the RelativeLayout

android EditText - finished typing event

Okay this will work 100% for sure.

First you will need to setup listener if keyboard is show or hide. If keyboard is showing then probably user is typing, otherwise done typing.

final View activityRootView = findViewById(android.R.id.content);
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                    Rect r = new Rect();
                    //r will be populated with the coordinates of your view that area still visible.
                    activityRootView.getWindowVisibleDisplayFrame(r);

                    int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
                    if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard...

                        isTyping = true;
                    } else {
//to make sure this will call only once when keyboard is hide.
                        if(isTyping){
                            isTyping = false;
                        }
                    }
            }
        });

How do I discard unstaged changes in Git?

If it's almost impossible to rule out modifications of the files, have you considered ignoring them? If this statement is right and you wouldn't touch those files during your development, this command may be useful:

git update-index --assume-unchanged file_to_ignore

How do I find out which settings.xml file maven is using

Use the Maven debug option, ie mvn -X :

Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...

In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml.

Can the :not() pseudo-class have multiple arguments?

Starting from CSS Selectors 4 using multiple arguments in the :not selector becomes possible (see here).

In CSS3, the :not selector only allows 1 selector as an argument. In level 4 selectors, it can take a selector list as an argument.

Example:

/* In this example, all p elements will be red, except for 
   the first child and the ones with the class special. */

p:not(:first-child, .special) {
  color: red;
}

Unfortunately, browser support is limited. For now, it only works in Safari.

Hibernate: "Field 'id' doesn't have a default value"

This issue is because sometimes you need to again update/create the database or sometimes if you have added the field in db table but not not entity class then it can not insert any null value or zero so this error came. So check both side.Db and Entity class.

int value under 10 convert to string two digit number

You can also do it this way

private static string GetPaddingSequence(int padding)
{
      StringBuilder SB = new StringBuilder();
      for (int i = 0; i < padding; i++)
      {
           SB.Append("0");
      }

      return SB.ToString();
  }

public static string FormatNumber(int number, int padding)
{
    return number.ToString(GetPaddingSequence(padding));
}

Finally call the function FormatNumber

string x = FormatNumber(1,2);

Output will be 01 which is based on your padding parameter. Increasing it will increase the number of 0s

ViewDidAppear is not called when opening app from background

As per Apple's documentation:

(void)beginAppearanceTransition:(BOOL)isAppearing animated:(BOOL)animated;

Description:
Tells a child controller its appearance is about to change. If you are implementing a custom container controller, use this method to tell the child that its views are about to appear or disappear. Do not invoke viewWillAppear:, viewWillDisappear:, viewDidAppear:, or viewDidDisappear: directly.

(void)endAppearanceTransition;

Description:

Tells a child controller its appearance has changed. If you are implementing a custom container controller, use this method to tell the child that the view transition is complete.

Sample code:

(void)applicationDidEnterBackground:(UIApplication *)application
{

    [self.window.rootViewController beginAppearanceTransition: NO animated: NO];  // I commented this line

    [self.window.rootViewController endAppearanceTransition]; // I commented this line

}

Question: How I fixed?

Ans: I found this piece of lines in application. This lines made my app not recieving any ViewWillAppear notification's. When I commented these lines it's working fine.

Simulator or Emulator? What is the difference?

In more or less normal parlance: If your software can do everything the mimicked system can do, it's an emulator. If it only approximates the results of a system (IT or otherwise), it's a simulator.

How do I get git to default to ssh and not https for new repositories

  • GitHub

    git config --global url.ssh://[email protected]/.insteadOf https://github.com/
    
  • BitBucket

    git config --global url.ssh://[email protected]/.insteadOf https://bitbucket.org/
    

That tells git to always use SSH instead of HTTPS when connecting to GitHub/BitBucket, so you'll authenticate by certificate by default, instead of being prompted for a password.

How to printf "unsigned long" in C?

The format is %lu.

Please check about the various other datatypes and their usage in printf here

JavaScript check if value is only undefined, null or false

Boolean(val) === false. This worked for me to check if value was falsely.

How to load URL in UIWebView in Swift?

Easy,Tested and working 100%

Import webkit :

import WebKit

Assign IBOutlet to webview:

var webView : WKWebView!

set delegate:

class ViewController: UIViewController , WKNavigationDelegate{

Write code on viewDidLoad():

// loading URL :
let myBlog = "https://stackoverflow.com/users/4600136/mr-javed-multani?tab=profile"
let url = NSURL(string: myBlog)
    let request = NSURLRequest(url: url! as URL)

    // init and load request in webview.
    webView = WKWebView(frame: self.view.frame)
    webView.navigationDelegate = self
    webView.load(request as URLRequest)
    self.view.addSubview(webView)
    self.view.sendSubview(toBack: webView)

Write delegate methods:

//MARK:- WKNavigationDelegate

func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
print(error.localizedDescription)
}


 func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
print("Strat to load")
    }

 func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
print("finish to load")
}

look like: enter image description here

Check if process returns 0 with batch file

How to write a compound statement with if?

You can write a compound statement in an if block using parenthesis. The first parenthesis must come on the line with the if and the second on a line by itself.

if %ERRORLEVEL% == 0 (
    echo ErrorLevel is zero
    echo A second statement
) else if %ERRORLEVEL% == 1 (
    echo ErrorLevel is one
    echo A second statement
) else (
   echo ErrorLevel is > 1
   echo A second statement
)

HTML: Is it possible to have a FORM tag in each TABLE ROW in a XHTML valid way?

Im late to the party, but this worked great for me and the code should explain itself;

<script type="text/javascript">
    function formAJAX(btn){
        var $form = $(btn).closest('[action]');
        var str = $form.find('[name]').serialize();
        $.post($form.attr('action'), str, function(data){
            //do stuff
        });
    }
<script>

HTML:

<tr action="scriptURL.php">
    <td>
        Field 1:<input type="text" name="field1"/>
    </td>
    <td>
        Field 2:<input type="text" name="field2" />
    </td>
    <td><button type="button" onclick="formAJAX(this)">Update</button></td>
</tr>

jquery onclick change css background image

I think this should be:

$('.home').click(function() {
     $(this).css('background', 'url(images/tabs3.png)');
 });

and remove this:

<div class="home" onclick="function()">
     //-----------^^^^^^^^^^^^^^^^^^^^---------no need for this

You have to make sure you have a correct path to your image.

How to normalize a NumPy array to within a certain range?

audio /= np.max(np.abs(audio),axis=0)
image *= (255.0/image.max())

Using /= and *= allows you to eliminate an intermediate temporary array, thus saving some memory. Multiplication is less expensive than division, so

image *= 255.0/image.max()    # Uses 1 division and image.size multiplications

is marginally faster than

image /= image.max()/255.0    # Uses 1+image.size divisions

Since we are using basic numpy methods here, I think this is about as efficient a solution in numpy as can be.


In-place operations do not change the dtype of the container array. Since the desired normalized values are floats, the audio and image arrays need to have floating-point point dtype before the in-place operations are performed. If they are not already of floating-point dtype, you'll need to convert them using astype. For example,

image = image.astype('float64')

Remove trailing zeros

Very simple answer is to use TrimEnd(). Here is the result,

double value = 1.00;
string output = value.ToString().TrimEnd('0');

Output is 1 If my value is 1.01 then my output will be 1.01

How can I do width = 100% - 100px in CSS?

Modern browsers now support the:

width: calc(100% - 100px);

To see the list of supported browser versions checkout: Can I use calc() as CSS unit value?

There is a jQuery fallback: css width: calc(100% -100px); alternative using jquery

In Excel, how do I extract last four letters of a ten letter string?

No need to use a macro. Supposing your first string is in A1.

=RIGHT(A1, 4)

Drag this down and you will get your four last characters.

Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()

=RIGHT(TRIMSPACES(A1), 4)

Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:

=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))

Python: Assign Value if None Exists

This is a very different style of programming, but I always try to rewrite things that looked like

bar = None
if foo():
    bar = "Baz"

if bar is None:
    bar = "Quux"

into just:

if foo():
    bar = "Baz"
else:
    bar = "Quux"

That is to say, I try hard to avoid a situation where some code paths define variables but others don't. In my code, there is never a path which causes an ambiguity of the set of defined variables (In fact, I usually take it a step further and make sure that the types are the same regardless of code path). It may just be a matter of personal taste, but I find this pattern, though a little less obvious when I'm writing it, much easier to understand when I'm later reading it.

Getting the parent div of element

var parentDiv = pDoc.parentElement

edit: this is sometimes parentNode in some cases.

https://developer.mozilla.org/en-US/docs/Web/API/Node/parentElement

Android view layout_width - how to change programmatically?

I believe your question is to change only width of view dynamically, whereas above methods will change layout properties completely to new one, so I suggest to getLayoutParams() from view first, then set width on layoutParams, and finally set layoutParams to the view, so following below steps to do the same.

View view = findViewById(R.id.nutrition_bar_filled);
LayoutParams layoutParams = view.getLayoutParams();
layoutParams.width = newWidth;
view.setLayoutParams(layoutParams);

What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim?

remap is an option that makes mappings work recursively. By default it is on and I'd recommend you leave it that way. The rest are mapping commands, described below:

:map and :noremap are recursive and non-recursive versions of the various mapping commands. For example, if we run:

:map j gg           (moves cursor to first line)
:map Q j            (moves cursor to first line)
:noremap W j        (moves cursor down one line)

Then:

  • j will be mapped to gg.
  • Q will also be mapped to gg, because j will be expanded for the recursive mapping.
  • W will be mapped to j (and not to gg) because j will not be expanded for the non-recursive mapping.

Now remember that Vim is a modal editor. It has a normal mode, visual mode and other modes.

For each of these sets of mappings, there is a mapping that works in normal, visual, select and operator modes (:map and :noremap), one that works in normal mode (:nmap and :nnoremap), one in visual mode (:vmap and :vnoremap) and so on.

For more guidance on this, see:

:help :map
:help :noremap
:help recursive_mapping
:help :map-modes

How can I find out if I have Xcode commandline tools installed?

Thanks to the folks on Freenode's #macdev, here is some information:

In the old days before Xcode was on the app-store, it included commandline tools.

Now you get it from the store, and with this new mechanism it can't install extra things outside of the Xcode.app, so you have to manually do it yourself, by:

xcode-select --install

On Xcode 4.x you can check to see if they are installed from within the Xcode UI:

enter image description here

On Xcode 5.x it is now here:

enter image description here

My problem of finding gcc/gdb is that they have been superseded by clang/lldb: GDB missing in OS X v10.9 (Mavericks)

Also note that Xcode contains compiler and debugger, so one of the things installing commandline tools will do is symlink or modify $PATH. It also downloads certain things like git.

How to a convert a date to a number and back again in MATLAB

Use DATESTR

>> datestr(40189)
ans =
12-Jan-0110

Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM

>> datenum(2010,1,11)
ans =
      734149
>> datenum(2010,1,11)-40189
ans =
      693960
>> datestr(40189+693960)
ans =
11-Jan-2010

In other words, to convert any serial Excel date, call

datestr(excelSerialDate + 693960)

EDIT

To get the date in mm/dd/yyyy format, call datestr with the specified format

excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010

Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things

excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010

Get file from project folder java

These lines worked in my case,

ClassLoader classLoader = getClass().getClassLoader();
File fi = new File(classLoader.getResource("test.txt").getFile());

provided test.txt file inside src

Get the content of a sharepoint folder with Excel VBA

IMHO the coolest way is to go via WebDAV (without Network Folder, as this is often not permitted). This can be accomplished via ActiveX Data Objects as layed out in this excellent article excellent article (code can be used directly in Excel, used the concept recently).

Hope this helps!

http://blog.itwarlocks.com/2009/04/28/accessing-webdav-in-microsoft-word-visual-basic/

the original link is dead, but at least the textual content is still available on archive.org: http://web.archive.org/web/20091008034423/http://blog.itwarlocks.com/2009/04/28/accessing-webdav-in-microsoft-word-visual-basic

Include of non-modular header inside framework module

I had the same problem and solve it by just making header file public. [problem]

If you are working on multiple modules in your project. Then your header file needs to be public to be used in other parts of projects. What you need is to select that header file, and in project Utilities view. Change the file from Project/Private to Public. See image below:

Changing header file scope

Maven 3 warnings about build.plugins.plugin.version

Run like:

  $ mvn help:describe -DartifactId=maven-war-plugin -DgroupId=org.apache.maven.plugins

for plug-in that have no version. You get output:

Name: Maven WAR Plugin
Description: Builds a Web Application Archive (WAR) file from the project
  output and its dependencies.
Group Id: org.apache.maven.plugins
Artifact Id: maven-war-plugin
Version: 2.2
Goal Prefix: war

Use version that shown in output.

UPDATE If you want to select among list of versions, use http://search.maven.org/ or http://mvnrepository.com/ Note that your favorite Java IDE must have Maven package search dialog. Just check docs.

SUPER UPDATE I also use:

$ mvn dependency:tree
$ mvn dependency:list
$ mvn dependency:resolve
$ mvn dependency:resolve-plugins  # <-- THIS

Recently I discover how to get latest version for plug-in (or library) so no longer needs for googling or visiting Maven Central:

$ mvn versions:display-dependency-updates
$ mvn versions:display-plugin-updates     # <-- THIS

Getting the length of two-dimensional array

int secondDimensionSize = nir[0].length;

Each element of the first dimension is actually another array with the length of the second dimension.

Pass by Reference / Value in C++

My understanding of the words "If the function modifies that value, the modifications appear also within the scope of the calling function for both passing by value and by reference" is that they are an error.

Modifications made in a called function are not in scope of the calling function when passing by value.

Either you have mistyped the quoted words or they have been extracted out of whatever context made what appears to be wrong, right.

Could you please ensure you have correctly quoted your source and if there are no errors there give more of the text surrounding that statement in the source material.

Entity Framework Join 3 Tables

This is untested, but I believe the syntax should work for a lambda query. As you join more tables with this syntax you have to drill further down into the new objects to reach the values you want to manipulate.

var fullEntries = dbContext.tbl_EntryPoint
    .Join(
        dbContext.tbl_Entry,
        entryPoint => entryPoint.EID,
        entry => entry.EID,
        (entryPoint, entry) => new { entryPoint, entry }
    )
    .Join(
        dbContext.tbl_Title,
        combinedEntry => combinedEntry.entry.TID,
        title => title.TID,
        (combinedEntry, title) => new 
        {
            UID = combinedEntry.entry.OwnerUID,
            TID = combinedEntry.entry.TID,
            EID = combinedEntry.entryPoint.EID,
            Title = title.Title
        }
    )
    .Where(fullEntry => fullEntry.UID == user.UID)
    .Take(10);

spacing between form fields

  <form>     
            <div class="form-group">
                <label for="nameLabel">Name</label>
                <input id="name" name="name" class="form-control" type="text" /> 
            </div>
            <div class="form-group">
                <label for="PhoneLabel">Phone</label>
                <input id="phone" name="phone" class="form-control" type="text" /> 
            </div>
            <div class="form-group">
                <label for="yearLabel">Year</label>
                <input id="year" name="year" class="form-control" type="text" />
            </div>
        </form>

How can I change the remote/target repository URL on Windows?

Take a look in .git/config and make the changes you need.

Alternatively you could use

git remote rm [name of the url you sets on adding]

and

git remote add [name] [URL]

Or just

git remote set-url [URL]

Before you do anything wrong, double check with

git help remote

How to parse dates in multiple formats using SimpleDateFormat

Here is the complete example (with main method) which can be added as a utility class in your project. All the format mentioned in SimpleDateFormate API is supported in the below method.

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

import org.apache.commons.lang.time.DateUtils;

public class DateUtility {

    public static Date parseDate(String inputDate) {

        Date outputDate = null;
        String[] possibleDateFormats =
              {
                    "yyyy.MM.dd G 'at' HH:mm:ss z",
                    "EEE, MMM d, ''yy",
                    "h:mm a",
                    "hh 'o''clock' a, zzzz",
                    "K:mm a, z",
                    "yyyyy.MMMMM.dd GGG hh:mm aaa",
                    "EEE, d MMM yyyy HH:mm:ss Z",
                    "yyMMddHHmmssZ",
                    "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
                    "yyyy-MM-dd'T'HH:mm:ss.SSSXXX",
                    "YYYY-'W'ww-u",
                    "EEE, dd MMM yyyy HH:mm:ss z", 
                    "EEE, dd MMM yyyy HH:mm zzzz",
                    "yyyy-MM-dd'T'HH:mm:ssZ",
                    "yyyy-MM-dd'T'HH:mm:ss.SSSzzzz", 
                    "yyyy-MM-dd'T'HH:mm:sszzzz",
                    "yyyy-MM-dd'T'HH:mm:ss z",
                    "yyyy-MM-dd'T'HH:mm:ssz", 
                    "yyyy-MM-dd'T'HH:mm:ss",
                    "yyyy-MM-dd'T'HHmmss.SSSz",
                    "yyyy-MM-dd",
                    "yyyyMMdd",
                    "dd/MM/yy",
                    "dd/MM/yyyy"
              };

        try {

            outputDate = DateUtils.parseDate(inputDate, possibleDateFormats);
            System.out.println("inputDate ==> " + inputDate + ", outputDate ==> " + outputDate);

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return outputDate;

    }

    public static String formatDate(Date date, String requiredDateFormat) {
        SimpleDateFormat df = new SimpleDateFormat(requiredDateFormat);
        String outputDateFormatted = df.format(date);
        return outputDateFormatted;
    }

    public static void main(String[] args) {

        DateUtility.parseDate("20181118");
        DateUtility.parseDate("2018-11-18");
        DateUtility.parseDate("18/11/18");
        DateUtility.parseDate("18/11/2018");
        DateUtility.parseDate("2018.11.18 AD at 12:08:56 PDT");
        System.out.println("");
        DateUtility.parseDate("Wed, Nov 18, '18");
        DateUtility.parseDate("12:08 PM");
        DateUtility.parseDate("12 o'clock PM, Pacific Daylight Time");
        DateUtility.parseDate("0:08 PM, PDT");
        DateUtility.parseDate("02018.Nov.18 AD 12:08 PM");
        System.out.println("");
        DateUtility.parseDate("Wed, 18 Nov 2018 12:08:56 -0700");
        DateUtility.parseDate("181118120856-0700");
        DateUtility.parseDate("2018-11-18T12:08:56.235-0700");
        DateUtility.parseDate("2018-11-18T12:08:56.235-07:00");
        DateUtility.parseDate("2018-W27-3");
    }

}

Overloading and overriding

Another point to add.

Overloading More than one method with Same name. Same or different return type. Different no of parameters or Different type of parameters. In Same Class or Derived class.

int Add(int num1, int num2) int Add(int num1, int num2, int num3) double Add(int num1, int num2) double Add(double num1, double num2)

Can be possible in same class or derived class. Generally prefers in same class. E.g. Console.WriteLine() has 19 overloaded methods.

Can overload class constructors, methods.

Can consider as Compile Time (static / Early Binding) polymorphism.

=====================================================================================================

Overriding cannot be possible in same class. Can Override class methods, properties, indexers, events.

Has some limitations like The overridden base method must be virtual, abstract, or override. You cannot use the new, static, or virtual modifiers to modify an override method.

Can Consider as Run Time (Dynamic / Late Binding) polymorphism.

Helps in versioning http://msdn.microsoft.com/en-us/library/6fawty39.aspx

=====================================================================================================

Helpful Links

http://msdn.microsoft.com/en-us/library/ms173152.aspx Compile time polymorphism vs. run time polymorphism

Change hash without reload in jQuery

This works for me

$('ul.questions li a').click(function(event) {
    event.preventDefault();
    $('.tab').hide();
    window.location.hash = this.hash;
    $($(this).attr('href')).fadeIn('slow');
});

Check here http://jsbin.com/edicu for a demo with almost identical code

PHP $_POST not working?

Instead of using $_POST, use $_REQUEST:

HTML:

<form action="" method="post">
  <input type="text" name="firstname">
  <input type="submit" name="submit" value="Submit">
</form>

PHP:

if(isset($_REQUEST['submit'])){
  $test = $_REQUEST['firstname'];
  echo $test;
}

How to parse XML using shellscript?

There's also xmlstarlet (which is available for Windows as well).

http://xmlstar.sourceforge.net/doc/xmlstarlet.txt

Google maps API V3 method fitBounds()

This happens because LatLngBounds() does not take two arbitrary points as parameters, but SW and NE points

use the .extend() method on an empty bounds object

var bounds = new google.maps.LatLngBounds();
bounds.extend(myPlace);
bounds.extend(Item_1);
map.fitBounds(bounds);

Demo at http://jsfiddle.net/gaby/22qte/

Easy way to turn JavaScript array into comma-separated list?

As of Chrome 72, it's possible to use Intl.ListFormat:

_x000D_
_x000D_
const vehicles = ['Motorcycle', 'Bus', 'Car'];_x000D_
_x000D_
const formatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });_x000D_
console.log(formatter.format(vehicles));_x000D_
// expected output: "Motorcycle, Bus, and Car"_x000D_
_x000D_
const formatter2 = new Intl.ListFormat('de', { style: 'short', type: 'disjunction' });_x000D_
console.log(formatter2.format(vehicles));_x000D_
// expected output: "Motorcycle, Bus oder Car"_x000D_
_x000D_
const formatter3 = new Intl.ListFormat('en', { style: 'narrow', type: 'unit' });_x000D_
console.log(formatter3.format(vehicles));_x000D_
// expected output: "Motorcycle Bus Car"
_x000D_
_x000D_
_x000D_

Please note that this way is in its very earlier stage, so as of the date of posting this answer, expect incompatibility with older versions of Chrome and other browsers.

Why did a network-related or instance-specific error occur while establishing a connection to SQL Server?

If you are connecting from Windows Machine A to Windows Machine B (server with SQL Server installed) and are getting this error, you need to do the following:

On Machine B:

  1. Turn on the Windows service called "SQL Server Browser" and start the service Windows Services
  2. In Windows Firewall:
    • enable incoming port UDP 1434 (in case SQL Server Management Studio on machine A is connecting or a program on machine A is connecting)
    • enable incoming port TCP 1433 (in case there is a telnet connection) Windows firewall
  3. In SQL Server Configuration Manager:
    • enable TCP/IP protocol for port 1433 Sql Server Configuration Manager

Replace a string in shell script using a variable

If you want to interpret $replace, you should not use single quotes since they prevent variable substitution.

Try:

echo $LINE | sed -e "s/12345678/${replace}/g"

Transcript:

pax> export replace=987654321
pax> echo X123456789X | sed "s/123456789/${replace}/"
X987654321X
pax> _

Just be careful to ensure that ${replace} doesn't have any characters of significance to sed (like / for instance) since it will cause confusion unless escaped. But if, as you say, you're replacing one number with another, that shouldn't be a problem.

Storing Python dictionaries

Also see the speeded-up package ujson:

import ujson

with open('data.json', 'wb') as fp:
    ujson.dump(data, fp)

How to show two figures using matplotlib?

You should call plt.show() only at the end after creating all the plots.

Batch File: ( was unexpected at this time

You are getting that error because when the param1 if statements are evaluated, param is always null due to being scoped variables without delayed expansion.

When parentheses are used, all the commands and variables within those parentheses are expanded. And at that time, param1 has no value making the if statements invalid. When using delayed expansion, the variables are only expanded when the command is actually called.

Also I recommend using if not defined command to determine if a variable is set.

@echo off
setlocal EnableExtensions EnableDelayedExpansion
cls
title ~USB Wizard~
echo What do you want to do?
echo 1.Enable/Disable USB Storage Devices.
echo 2.Enable/Disable Writing Data onto USB Storage.
echo 3.~Yet to come~.

set "a=%globalparam1%"
goto :aCheck
:aPrompt
set /p "a=Enter Choice: "
:aCheck
if not defined a goto :aPrompt
echo %a%

IF "%a%"=="2" (
    title USB WRITE LOCK
    echo What do you want to do?
    echo 1.Apply USB Write Protection
    echo 2.Remove USB Write Protection

    ::param1
    set "param1=%globalparam2%"
    goto :param1Check
    :param1Prompt
    set /p "param1=Enter Choice: "
    :param1Check
    if not defined param1 goto :param1Prompt
    echo !param1!

    if "!param1!"=="1" (
        REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000001 
        echo USB Write is Locked!
    )
    if "!param1!"=="2" (
        REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000000
        echo USB Write is Unlocked! 
    )
)
pause
endlocal

mongo - couldn't connect to server 127.0.0.1:27017

if u install by brew (on osx) first run sudo mkdir /data/db start mondoDB Daemon by typing mongod (leave it open) and then run mongo by typing mongo in new terminal tab

Apply style to cells of first row

Use tr:first-child to take the first tr:

.category_table tr:first-child td {
    vertical-align: top;
}

If you have nested tables, and you don't want to apply styles to the inner rows, add some child selectors so only the top-level tds in the first top-level tr get the styles:

.category_table > tbody > tr:first-child > td {
    vertical-align: top;
}

Trim whitespace from a String

I think that substr() throws an exception if str only contains the whitespace.

I would modify it to the following code:

string trim(string& str)
{
    size_t first = str.find_first_not_of(' ');
    if (first == std::string::npos)
        return "";
    size_t last = str.find_last_not_of(' ');
    return str.substr(first, (last-first+1));
}

How to write a multiline Jinja statement

According to the documentation: https://jinja.palletsprojects.com/en/2.10.x/templates/#line-statements you may use multi-line statements as long as the code has parens/brackets around it. Example:

{% if ( (foo == 'foo' or bar == 'bar') and 
        (fooo == 'fooo' or baar == 'baar') ) %}
    <li>some text</li>
{% endif %}

Edit: Using line_statement_prefix = '#'* the code would look like this:

# if ( (foo == 'foo' or bar == 'bar') and 
       (fooo == 'fooo' or baar == 'baar') )
    <li>some text</li>
# endif

*Here's an example of how you'd specify the line_statement_prefix in the Environment:

from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
    loader=PackageLoader('yourapplication', 'templates'),
    autoescape=select_autoescape(['html', 'xml']),
    line_statement_prefix='#'
)

Or using Flask:

from flask import Flask
app = Flask(__name__, instance_relative_config=True, static_folder='static')
app.jinja_env.filters['zip'] = zip
app.jinja_env.line_statement_prefix = '#'

Get file content from URL?

$url = "https://chart.googleapis....";
$json = file_get_contents($url);

Now you can either echo the $json variable, if you just want to display the output, or you can decode it, and do something with it, like so:

$data = json_decode($json);
var_dump($data);

Configure WAMP server to send email

Sendmail wasn't working for me so I used msmtp 1.6.2 w32 and most just followed the instructions at DeveloperSide. Here is a quick rundown of the setup for posterity:

Enabled IMAP access under your Gmail account (the one msmtp is sending emails from)

Enable access for less secure apps. Log into your google account and go here

Edit php.ini, find and change each setting below to reflect the following:

; These are commented out by prefixing a semicolon
;SMTP = localhost
;smtp_port = 25

; Set these paths to where you put your msmtp files.
; I used backslashes in php.ini and it works fine.
; The example in the devside guide uses forwardslashes. 
sendmail_path = "C:\wamp64\msmtp\msmtp.exe -d -C C:\wamp64\msmtp\msmtprc.ini -t --read-envelope-from"

mail.log = "C:\wamp64\msmtp\maillog.txt"

Create and edit the file msmtprc.ini in the same directory as your msmtp.exe file as follows, replacing it with your own email and password:

# Default values for all accounts
defaults
tls_certcheck off
# I used forward slashes here and it works.
logfile C:/wamp64/msmtp/msmtplog.txt

account Gmail
host smtp.gmail.com
port 587
auth on
tls on
from [email protected]
user [email protected]
password ReplaceWithYourPassword
account default : gmail

How to deploy a war file in JBoss AS 7?

open up console and navigate to bin folder and run

JBOSS_HOME/bin > stanalone.sh

Once it is up and running just copy past your war file in

standalone/deployments folder

Thats probably it for jboss 7.1

npm - EPERM: operation not permitted on Windows

Restarting VsCode solved it for me!

How do I iterate through lines in an external file with shell?

This might work for you:

cat <<\! >names.txt
> alison
> barb
> charlie
> david
> !
OIFS=$IFS; IFS=$'\n'; NAMES=($(<names.txt)); IFS=$OIFS
echo "${NAMES[@]}"
alison barb charlie david
echo "${NAMES[0]}"
alison
for NAME in "${NAMES[@]}";do echo $NAME;done
alison
barb
charlie
david

How to do "If Clicked Else .."

 var flag = 0;

 $('#target').click(function() {
    flag = 1;
 });

 if (flag == 1)
 {
  alert("Clicked");
 }
 else
 {
   alert("Not clicked");
 }

How to open a WPF Popup when another control is clicked, using XAML markup only?

I had some issues with the MouseDown part of this, but here is some code that might get your started.

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <Control VerticalAlignment="Top">
            <Control.Template>
                <ControlTemplate>
                    <StackPanel>
                    <TextBox x:Name="MyText"></TextBox>
                    <Popup x:Name="Popup" PopupAnimation="Fade" VerticalAlignment="Top">
                        <Border Background="Red">
                            <TextBlock>Test Popup Content</TextBlock>
                        </Border>
                    </Popup>
                    </StackPanel>
                    <ControlTemplate.Triggers>
                        <EventTrigger RoutedEvent="UIElement.MouseEnter" SourceName="MyText">
                            <BeginStoryboard>
                                <Storyboard>
                                    <BooleanAnimationUsingKeyFrames Storyboard.TargetName="Popup" Storyboard.TargetProperty="(Popup.IsOpen)">
                                        <DiscreteBooleanKeyFrame KeyTime="00:00:00" Value="True"/>
                                    </BooleanAnimationUsingKeyFrames>
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger>
                        <EventTrigger RoutedEvent="UIElement.MouseLeave" SourceName="MyText">
                            <BeginStoryboard>
                                <Storyboard>
                                    <BooleanAnimationUsingKeyFrames Storyboard.TargetName="Popup" Storyboard.TargetProperty="(Popup.IsOpen)">
                                        <DiscreteBooleanKeyFrame KeyTime="00:00:00" Value="False"/>
                                    </BooleanAnimationUsingKeyFrames>
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Control.Template>
        </Control>
    </Grid>
</Window>

Converting a String to a List of Words?

This way you eliminate every special char outside of the alphabet:

def wordsToList(strn):
    L = strn.split()
    cleanL = []
    abc = 'abcdefghijklmnopqrstuvwxyz'
    ABC = abc.upper()
    letters = abc + ABC
    for e in L:
        word = ''
        for c in e:
            if c in letters:
                word += c
        if word != '':
            cleanL.append(word)
    return cleanL

s = 'She loves you, yea yea yea! '
L = wordsToList(s)
print(L)  # ['She', 'loves', 'you', 'yea', 'yea', 'yea']

I'm not sure if this is fast or optimal or even the right way to program.

Can I change the name of `nohup.out`?

nohup some_command &> nohup2.out &

and voila.


Older syntax for Bash version < 4:

nohup some_command > nohup2.out 2>&1 &

Where are SQL Server connection attempts logged?

If you'd like to track only failed logins, you can use the SQL Server Audit feature (available in SQL Server 2008 and above). You will need to add the SQL server instance you want to audit, and check the failed login operation to audit.

Note: tracking failed logins via SQL Server Audit has its disadvantages. For example - it doesn't provide the names of client applications used.

If you want to audit a client application name along with each failed login, you can use an Extended Events session.

To get you started, I recommend reading this article: http://www.sqlshack.com/using-extended-events-review-sql-server-failed-logins/

Laravel whereIn OR whereIn

$query = DB::table('dms_stakeholder_permissions');
$query->select(DB::raw('group_concat(dms_stakeholder_permissions.fid) as fid'),'dms_stakeholder_permissions.rights');
$query->where('dms_stakeholder_permissions.stakeholder_id','4');
$query->orWhere(function($subquery)  use ($stakeholderId){
            $subquery->where('dms_stakeholder_permissions.stakeholder_id',$stakeholderId);
            $subquery->whereIn('dms_stakeholder_permissions.rights',array('1','2','3'));
    });

 $result = $query->get();

return $result;

// OUTPUT @input $stakeholderId = 1

//select group_concat(dms_stakeholder_permissions.fid) as fid, dms_stakeholder_permissionss.rights from dms_stakeholder_permissions where dms_stakeholder_permissions.stakeholder_id = 4 or (dms_stakeholder_permissions.stakeholder_id = 1 and dms_stakeholder_permissions.rights in (1, 2, 3))

Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

create a libs folder in the inside WEB-INF directory and add jstl, standard jars as below.enter image description here

How do I list all cron jobs for all users?

I ended up writing a script (I'm trying to teach myself the finer points of bash scripting, so that's why you don't see something like Perl here). It's not exactly a simple affair, but it does most of what I need. It uses Kyle's suggestion for looking up individual users' crontabs, but also deals with /etc/crontab (including the scripts launched by run-parts in /etc/cron.hourly, /etc/cron.daily, etc.) and the jobs in the /etc/cron.d directory. It takes all of those and merges them into a display something like the following:

mi     h    d  m  w  user      command
09,39  *    *  *  *  root      [ -d /var/lib/php5 ] && find /var/lib/php5/ -type f -cmin +$(/usr/lib/php5/maxlifetime) -print0 | xargs -r -0 rm
47     */8  *  *  *  root      rsync -axE --delete --ignore-errors / /mirror/ >/dev/null
17     1    *  *  *  root      /etc/cron.daily/apt
17     1    *  *  *  root      /etc/cron.daily/aptitude
17     1    *  *  *  root      /etc/cron.daily/find
17     1    *  *  *  root      /etc/cron.daily/logrotate
17     1    *  *  *  root      /etc/cron.daily/man-db
17     1    *  *  *  root      /etc/cron.daily/ntp
17     1    *  *  *  root      /etc/cron.daily/standard
17     1    *  *  *  root      /etc/cron.daily/sysklogd
27     2    *  *  7  root      /etc/cron.weekly/man-db
27     2    *  *  7  root      /etc/cron.weekly/sysklogd
13     3    *  *  *  archiver  /usr/local/bin/offsite-backup 2>&1
32     3    1  *  *  root      /etc/cron.monthly/standard
36     4    *  *  *  yukon     /home/yukon/bin/do-daily-stuff
5      5    *  *  *  archiver  /usr/local/bin/update-logs >/dev/null

Note that it shows the user, and more-or-less sorts by hour and minute so that I can see the daily schedule.

So far, I've tested it on Ubuntu, Debian, and Red Hat AS.

#!/bin/bash

# System-wide crontab file and cron job directory. Change these for your system.
CRONTAB='/etc/crontab'
CRONDIR='/etc/cron.d'

# Single tab character. Annoyingly necessary.
tab=$(echo -en "\t")

# Given a stream of crontab lines, exclude non-cron job lines, replace
# whitespace characters with a single space, and remove any spaces from the
# beginning of each line.
function clean_cron_lines() {
    while read line ; do
        echo "${line}" |
            egrep --invert-match '^($|\s*#|\s*[[:alnum:]_]+=)' |
            sed --regexp-extended "s/\s+/ /g" |
            sed --regexp-extended "s/^ //"
    done;
}

# Given a stream of cleaned crontab lines, echo any that don't include the
# run-parts command, and for those that do, show each job file in the run-parts
# directory as if it were scheduled explicitly.
function lookup_run_parts() {
    while read line ; do
        match=$(echo "${line}" | egrep -o 'run-parts (-{1,2}\S+ )*\S+')

        if [[ -z "${match}" ]] ; then
            echo "${line}"
        else
            cron_fields=$(echo "${line}" | cut -f1-6 -d' ')
            cron_job_dir=$(echo  "${match}" | awk '{print $NF}')

            if [[ -d "${cron_job_dir}" ]] ; then
                for cron_job_file in "${cron_job_dir}"/* ; do  # */ <not a comment>
                    [[ -f "${cron_job_file}" ]] && echo "${cron_fields} ${cron_job_file}"
                done
            fi
        fi
    done;
}

# Temporary file for crontab lines.
temp=$(mktemp) || exit 1

# Add all of the jobs from the system-wide crontab file.
cat "${CRONTAB}" | clean_cron_lines | lookup_run_parts >"${temp}" 

# Add all of the jobs from the system-wide cron directory.
cat "${CRONDIR}"/* | clean_cron_lines >>"${temp}"  # */ <not a comment>

# Add each user's crontab (if it exists). Insert the user's name between the
# five time fields and the command.
while read user ; do
    crontab -l -u "${user}" 2>/dev/null |
        clean_cron_lines |
        sed --regexp-extended "s/^((\S+ +){5})(.+)$/\1${user} \3/" >>"${temp}"
done < <(cut --fields=1 --delimiter=: /etc/passwd)

# Output the collected crontab lines. Replace the single spaces between the
# fields with tab characters, sort the lines by hour and minute, insert the
# header line, and format the results as a table.
cat "${temp}" |
    sed --regexp-extended "s/^(\S+) +(\S+) +(\S+) +(\S+) +(\S+) +(\S+) +(.*)$/\1\t\2\t\3\t\4\t\5\t\6\t\7/" |
    sort --numeric-sort --field-separator="${tab}" --key=2,1 |
    sed "1i\mi\th\td\tm\tw\tuser\tcommand" |
    column -s"${tab}" -t

rm --force "${temp}"

css rotate a pseudo :after or :before content:""

Inline elements can't be transformed, and pseudo elements are inline by default, so you must apply display: block or display: inline-block to transform them:

_x000D_
_x000D_
#whatever:after {
  content: "\24B6";
  display: inline-block;
  transform: rotate(30deg);
}
_x000D_
<div id="whatever">Some text </div>
_x000D_
_x000D_
_x000D_

How do I filter date range in DataTables?

Following one is working fine with moments js 2.10 and above

$.fn.dataTableExt.afnFiltering.push(
        function( settings, data, dataIndex ) {
            var min  = $('#min-date').val()
            var max  = $('#max-date').val()
            var createdAt = data[0] || 0; // Our date column in the table
            //createdAt=createdAt.split(" ");
            var startDate   = moment(min, "DD/MM/YYYY");
            var endDate     = moment(max, "DD/MM/YYYY");
            var diffDate = moment(createdAt, "DD/MM/YYYY");
            //console.log(startDate);
            if (
              (min == "" || max == "") ||
              (diffDate.isBetween(startDate, endDate))


            ) {  return true;  }
            return false;

        }
    );

How to retrieve Jenkins build parameters using the Groovy API?

To get the parameterized build params from the current build from your GroovyScript (using Pipeline), all you need to do is: Say you had a variable called VARNAME.

def myVariable = env.VARNAME

Docker error cannot delete docker container, conflict: unable to remove repository reference

Remove docker images >

List all containers

docker container ls

List all images

docker image ls

Stop container by container id

docker container stop <container_id>

Remove container by container id

docker container rm <container_id>

If don't want stop and remove, can force remove

docker container rm -f <container_id>

Remove image

docker image rm <image_id>

Done!

How to convert String object to Boolean Object?

Use the Apache Commons library BooleanUtils class:

String[] values= new String[]{"y","Y","n","N","Yes","YES","yes","no","No","NO","true","false","True","False","TRUE","FALSE",null};
for(String booleanStr : values){
    System.out.println("Str ="+ booleanStr +": boolean =" +BooleanUtils.toBoolean(booleanStr));
}

Result:

Str =N: boolean =false
Str =Yes: boolean =true
Str =YES: boolean =true
Str =yes: boolean =true
Str =no: boolean =false
Str =No: boolean =false
Str =NO: boolean =false
Str =true: boolean =true
Str =false: boolean =false
Str =True: boolean =true
Str =False: boolean =false
Str =TRUE: boolean =true
Str =FALSE: boolean =false
Str =null: boolean =false

MVC pattern on Android

Android's MVC pattern is (kind-of) implemented with their Adapter classes. They replace a controller with an "adapter." The description for the adapter states:

An Adapter object acts as a bridge between an AdapterView and the underlying data for that view.

I'm just looking into this for an Android application that reads from a database, so I don't know how well it works yet. However, it seems a little like Qt's Model-View-Delegate architecture, which they claim is a step up from a traditional MVC pattern. At least on the PC, Qt's pattern works fairly well.

C#: calling a button event handler method without actually clicking the button

All above methods are not good because you might change event function name. The easiest is:

btnTest.PerfromClick();

How to beautifully update a JPA entity in Spring Data?

This is more an object initialzation question more than a jpa question, both methods work and you can have both of them at the same time , usually if the data member value is ready before the instantiation you use the constructor parameters, if this value could be updated after the instantiation you should have a setter.

jQuery function to get all unique elements from an array?

You can use array.filter to return the first item of each distinct value-

_x000D_
_x000D_
var a = [ 1, 5, 1, 6, 4, 5, 2, 5, 4, 3, 1, 2, 6, 6, 3, 3, 2, 4 ];_x000D_
_x000D_
var unique = a.filter(function(itm, i, a) {_x000D_
    return i == a.indexOf(itm);_x000D_
});_x000D_
_x000D_
console.log(unique);
_x000D_
_x000D_
_x000D_

If supporting IE8 and below is primary, don't use the unsupported filter method.

Otherwise,

if (!Array.prototype.filter) {
    Array.prototype.filter = function(fun, scope) {
        var T = this, A = [], i = 0, itm, L = T.length;
        if (typeof fun == 'function') {
            while(i < L) {
                if (i in T) {
                    itm = T[i];
                    if (fun.call(scope, itm, i, T)) A[A.length] = itm;
                }
                ++i;
            }
        }
        return A;
    }
}

Questions every good PHP Developer should be able to answer

Is php cross-browser?

(i know, this will make laught many people, but is the more-asked question on php forums!)

How to select data where a field has a min value in MySQL?

In fact, depends what you want to get: - Just the min value:

SELECT MIN(price) FROM pieces
  • A table (multiples rows) whith the min value: Is as John Woo said above.

  • But, if can be different rows with same min value, the best is ORDER them from another column, because after or later you will need to do it (starting from John Woo answere):

    SELECT * FROM pieces WHERE price = ( SELECT MIN(price) FROM pieces) ORDER BY stock ASC

Get path from open file in Python

You can get it like this also.

filepath = os.path.abspath(f.name)

Append an object to a list in R in amortized constant time, O(1)?

I have made a small comparison of methods mentioned here.

n = 1e+4
library(microbenchmark)
### Using environment as a container
lPtrAppend <- function(lstptr, lab, obj) {lstptr[[deparse(substitute(lab))]] <- obj}
### Store list inside new environment
envAppendList <- function(lstptr, obj) {lstptr$list[[length(lstptr$list)+1]] <- obj} 

microbenchmark(times = 5,  
        env_with_list_ = {
            listptr <- new.env(parent=globalenv())
            listptr$list <- NULL
            for(i in 1:n) {envAppendList(listptr, i)}
            listptr$list
        },
        c_ = {
            a <- list(0)
            for(i in 1:n) {a = c(a, list(i))}
        },
        list_ = {
            a <- list(0)
            for(i in 1:n) {a <- list(a, list(i))}
        },
        by_index = {
            a <- list(0)
            for(i in 1:n) {a[length(a) + 1] <- i}
            a
        },
        append_ = { 
            a <- list(0)    
            for(i in 1:n) {a <- append(a, i)} 
            a
        },
        env_as_container_ = {
            listptr <- new.env(parent=globalenv())
            for(i in 1:n) {lPtrAppend(listptr, i, i)} 
            listptr
        }   
)

Results:

Unit: milliseconds
              expr       min        lq       mean    median        uq       max neval cld
    env_with_list_  188.9023  198.7560  224.57632  223.2520  229.3854  282.5859     5  a 
                c_ 1275.3424 1869.1064 2022.20984 2191.7745 2283.1199 2491.7060     5   b
             list_   17.4916   18.1142   22.56752   19.8546   20.8191   36.5581     5  a 
          by_index  445.2970  479.9670  540.20398  576.9037  591.2366  607.6156     5  a 
           append_ 1140.8975 1316.3031 1794.10472 1620.1212 1855.3602 3037.8416     5   b
 env_as_container_  355.9655  360.1738  399.69186  376.8588  391.7945  513.6667     5  a 

Return a "NULL" object if search result not found

You can try this:

return &Type();

How to select rows in a DataFrame between two values, in Python Pandas?

Instead of this

df = df[(99 <= df['closing_price'] <= 101)]

You should use this

df = df[(df['closing_price']>=99 ) & (df['closing_price']<=101)]

We have to use NumPy's bitwise Logic operators |, &, ~, ^ for compounding queries. Also, the parentheses are important for operator precedence.

For more info, you can visit the link :Comparisons, Masks, and Boolean Logic

Easy pretty printing of floats in python?

List comps are your friend.

print ", ".join("%.2f" % f for f in list_o_numbers)

Try it:

>>> nums = [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999]
>>> print ", ".join("%.2f" % f for f in nums)
9.00, 0.05, 0.03, 0.01

How do I convert strings between uppercase and lowercase in Java?

Coverting the first letter of word capital

input:

hello world

String A = hello;
String B = world;
System.out.println(A.toUpperCase().charAt(0)+A.substring(1) + " " + B.toUpperCase().charAt(0)+B.substring(1));

Output:

Hello World

How to get rid of "Unnamed: 0" column in a pandas DataFrame?

It's the index column, pass pd.to_csv(..., index=False) to not write out an unnamed index column in the first place, see the to_csv() docs.

Example:

In [37]:
df = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))
pd.read_csv(io.StringIO(df.to_csv()))

Out[37]:
   Unnamed: 0         a         b         c
0           0  0.109066 -1.112704 -0.545209
1           1  0.447114  1.525341  0.317252
2           2  0.507495  0.137863  0.886283
3           3  1.452867  1.888363  1.168101
4           4  0.901371 -0.704805  0.088335

compare with:

In [38]:
pd.read_csv(io.StringIO(df.to_csv(index=False)))

Out[38]:
          a         b         c
0  0.109066 -1.112704 -0.545209
1  0.447114  1.525341  0.317252
2  0.507495  0.137863  0.886283
3  1.452867  1.888363  1.168101
4  0.901371 -0.704805  0.088335

You could also optionally tell read_csv that the first column is the index column by passing index_col=0:

In [40]:
pd.read_csv(io.StringIO(df.to_csv()), index_col=0)

Out[40]:
          a         b         c
0  0.109066 -1.112704 -0.545209
1  0.447114  1.525341  0.317252
2  0.507495  0.137863  0.886283
3  1.452867  1.888363  1.168101
4  0.901371 -0.704805  0.088335

Function passed as template argument

Came here with the additional requirement, that also parameter/return types should vary. Following Ben Supnik this would be for some type T

typedef T(*binary_T_op)(T, T);

instead of

typedef int(*binary_int_op)(int, int);

The solution here is to put the function type definition and the function template into a surrounding struct template.

template <typename T> struct BinOp
{
    typedef T(*binary_T_op )(T, T); // signature for all valid template params
    template<binary_T_op op>
    T do_op(T a, T b)
    {
       return op(a,b);
    }
};


double mulDouble(double a, double b)
{
    return a * b;
}


BinOp<double> doubleBinOp;

double res = doubleBinOp.do_op<&mulDouble>(4, 5);

Alternatively BinOp could be a class with static method template do_op(...), then called as

double res = BinOp<double>::do_op<&mulDouble>(4, 5);

How to cache Google map tiles for offline usage?

You can use Open Street Map : you will find dozens of different layers and map types, and this is absolutely free. You can download all the map tiles you want. And of course, as anyone can enhance the map, it displays more information than Google's maps. If you need help, you can ask the community which is also very active.

Changing an element's ID with jQuery

I'm not sure what your goal is, but might it be better to use addClass instead? I mean an objects ID in my opinion should be static and specific to that object. If you are just trying to change it from showing on the page or something like that I would put those details in a class and then add it to the object rather then trying to change it's ID. Again, I'm saying that without understand your underlining goal.

Remove all whitespaces from NSString

Easy task using stringByReplacingOccurrencesOfString

NSString *search = [searchbar.text stringByReplacingOccurrencesOfString:@" " withString:@""];

Setting PATH environment variable in OSX permanently

If you are using zsh do the following.

  1. Open .zshrc file nano $HOME/.zshrc

  2. You will see the commented $PATH variable here

    # If you come from bash you might have to change your $PATH.
    # export PATH=$HOME/bin:/usr/local/...

  3. Remove the comment symbol(#) and append your new path using a separator(:) like this.

export PATH=$HOME/bin:/usr/local/bin:/Users/ebin/Documents/Softwares/mongoDB/bin:$PATH

  1. Activate the change source $HOME/.zshrc

You're done !!!

Assign multiple values to array in C

typedef struct{
  char array[4];
}my_array;

my_array array = { .array = {1,1,1,1} }; // initialisation

void assign(my_array a)
{
  array.array[0] = a.array[0];
  array.array[1] = a.array[1];
  array.array[2] = a.array[2];
  array.array[3] = a.array[3]; 
}

char num = 5;
char ber = 6;

int main(void)
{
  printf("%d\n", array.array[0]);
// ...

  // this works even after initialisation
  assign((my_array){ .array = {num,ber,num,ber} });

  printf("%d\n", array.array[0]);
// ....
  return 0;
}

Error in finding last used cell in Excel with VBA

Note: this answer was motivated by this comment. The purpose of UsedRange is different from what is mentioned in the answer above.

As to the correct way of finding the last used cell, one has first to decide what is considered used, and then select a suitable method. I conceive at least three meanings:

  1. Used = non-blank, i.e., having data.

  2. Used = "... in use, meaning the section that contains data or formatting." As per official documentation, this is the criterion used by Excel at the time of saving. See also this official documentation. If one is not aware of this, the criterion may produce unexpected results, but it may also be intentionally exploited (less often, surely), e.g., to highlight or print specific regions, which may eventually have no data. And, of course, it is desirable as a criterion for the range to use when saving a workbook, lest losing part of one's work.

  3. Used = "... in use, meaning the section that contains data or formatting" or conditional formatting. Same as 2., but also including cells that are the target for any Conditional Formatting rule.

How to find the last used cell depends on what you want (your criterion).

For criterion 1, I suggest reading this answer. Note that UsedRange is cited as unreliable. I think that is misleading (i.e., "unfair" to UsedRange), as UsedRange is simply not meant to report the last cell containing data. So it should not be used in this case, as indicated in that answer. See also this comment.

For criterion 2, UsedRange is the most reliable option, as compared to other options also designed for this use. It even makes it unnecessary to save a workbook to make sure that the last cell is updated. Ctrl+End will go to a wrong cell prior to saving (“The last cell is not reset until you save the worksheet”, from http://msdn.microsoft.com/en-us/library/aa139976%28v=office.10%29.aspx. It is an old reference, but in this respect valid).

For criterion 3, I do not know any built-in method. Criterion 2 does not account for Conditional Formatting. One may have formatted cells, based on formulas, which are not detected by UsedRange or Ctrl+End. In the figure, the last cell is B3, since formatting was applied explicitly to it. Cells B6:D7 have a format derived from a Conditional Formatting rule, and this is not detected even by UsedRange. Accounting for this would require some VBA programming.

enter image description here


As to your specific question: What's the reason behind this?

Your code uses the first cell in your range E4:E48 as a trampoline, for jumping down with End(xlDown).

The "erroneous" output will obtain if there are no non-blank cells in your range other than perhaps the first. Then, you are leaping in the dark, i.e., down the worksheet (you should note the difference between blank and empty string!).

Note that:

  1. If your range contains non-contiguous non-blank cells, then it will also give a wrong result.

  2. If there is only one non-blank cell, but it is not the first one, your code will still give you the correct result.

Subset dataframe by multiple logical conditions of rows to remove

This answer is more meant to explain why, not how. The '==' operator in R is vectorized in a same way as the '+' operator. It matches the elements of whatever is on the left side to the elements of whatever is on the right side, per element. For example:

> 1:3 == 1:3
[1] TRUE TRUE TRUE

Here the first test is 1==1 which is TRUE, the second 2==2 and the third 3==3. Notice that this returns a FALSE in the first and second element because the order is wrong:

> 3:1 == 1:3
[1] FALSE  TRUE FALSE

Now if one object is smaller then the other object then the smaller object is repeated as much as it takes to match the larger object. If the size of the larger object is not a multiplication of the size of the smaller object you get a warning that not all elements are repeated. For example:

>  1:2 == 1:3
[1]  TRUE  TRUE FALSE
Warning message:
In 1:2 == 1:3 :
  longer object length is not a multiple of shorter object length

Here the first match is 1==1, then 2==2, and finally 1==3 (FALSE) because the left side is smaller. If one of the sides is only one element then that is repeated:

> 1:3 == 1
[1]  TRUE FALSE FALSE

The correct operator to test if an element is in a vector is indeed '%in%' which is vectorized only to the left element (for each element in the left vector it is tested if it is part of any object in the right element).

Alternatively, you can use '&' to combine two logical statements. '&' takes two elements and checks elementwise if both are TRUE:

> 1:3 == 1 & 1:3 != 2
[1]  TRUE FALSE FALSE

Left join only selected columns in R with the merge() function

You can do this by subsetting the data you pass into your merge:

merge(x = DF1, y = DF2[ , c("Client", "LO")], by = "Client", all.x=TRUE)

Or you can simply delete the column after your current merge :)

How to avoid annoying error "declared and not used"

One angle not so far mentioned is tool sets used for editing the code.

Using Visual Studio Code along with the Extension from lukehoban called Go will do some auto-magic for you. The Go extension automatically runs gofmt, golint etc, and removes and adds import entries. So at least that part is now automatic.

I will admit its not 100% of the solution to the question, but however useful enough.

PHP mkdir: Permission denied problem

Don't set permissions to 777 when using mkdir in PHP

Link only answers are not considered good practice on StackOverflow, but the advice that is given here should generally NOT be followed up.

I would like to revert to this great answer on a similar question. I quote:

Please stop suggesting to use 777. You're making your file writeable by everyone, which pretty much means you lose all security that the permission system was designed for. If you suggest this, think about the consequences it may have on a poorly configured webserver: it would become incredibly easy to "hack" the website, by overwriting the files. So, don't.

Generate random numbers with a given (numerical) distribution

Since Python 3.6, there's a solution for this in Python's standard library, namely random.choices.

Example usage: let's set up a population and weights matching those in the OP's question:

>>> from random import choices
>>> population = [1, 2, 3, 4, 5, 6]
>>> weights = [0.1, 0.05, 0.05, 0.2, 0.4, 0.2]

Now choices(population, weights) generates a single sample:

>>> choices(population, weights)
4

The optional keyword-only argument k allows one to request more than one sample at once. This is valuable because there's some preparatory work that random.choices has to do every time it's called, prior to generating any samples; by generating many samples at once, we only have to do that preparatory work once. Here we generate a million samples, and use collections.Counter to check that the distribution we get roughly matches the weights we gave.

>>> million_samples = choices(population, weights, k=10**6)
>>> from collections import Counter
>>> Counter(million_samples)
Counter({5: 399616, 6: 200387, 4: 200117, 1: 99636, 3: 50219, 2: 50025})

How to validate numeric values which may contain dots or commas?

\d{1,2}[,.]\d{1,2}

\d means a digit, the {1,2} part means 1 or 2 of the previous character (\d in this case) and the [,.] part means either a comma or dot.

How to Use Content-disposition for force a file to download to the hard drive?

With recent browsers you can use the HTML5 download attribute as well:

<a download="quot.pdf" href="../doc/quot.pdf">Click here to Download quotation</a>

It is supported by most of the recent browsers except MSIE11. You can use a polyfill, something like this (note that this is for data uri only, but it is a good start):

(function (){

    addEvent(window, "load", function (){
        if (isInternetExplorer())
            polyfillDataUriDownload();
    });

    function polyfillDataUriDownload(){
        var links = document.querySelectorAll('a[download], area[download]');
        for (var index = 0, length = links.length; index<length; ++index) {
            (function (link){
                var dataUri = link.getAttribute("href");
                var fileName = link.getAttribute("download");
                if (dataUri.slice(0,5) != "data:")
                    throw new Error("The XHR part is not implemented here.");
                addEvent(link, "click", function (event){
                    cancelEvent(event);
                    try {
                        var dataBlob = dataUriToBlob(dataUri);
                        forceBlobDownload(dataBlob, fileName);
                    } catch (e) {
                        alert(e)
                    }
                });
            })(links[index]);
        }
    }

    function forceBlobDownload(dataBlob, fileName){
        window.navigator.msSaveBlob(dataBlob, fileName);
    }

    function dataUriToBlob(dataUri) {
        if  (!(/base64/).test(dataUri))
            throw new Error("Supports only base64 encoding.");
        var parts = dataUri.split(/[:;,]/),
            type = parts[1],
            binData = atob(parts.pop()),
            mx = binData.length,
            uiArr = new Uint8Array(mx);
        for(var i = 0; i<mx; ++i)
            uiArr[i] = binData.charCodeAt(i);
        return new Blob([uiArr], {type: type});
    }

    function addEvent(subject, type, listener){
        if (window.addEventListener)
            subject.addEventListener(type, listener, false);
        else if (window.attachEvent)
            subject.attachEvent("on" + type, listener);
    }

    function cancelEvent(event){
        if (event.preventDefault)
            event.preventDefault();
        else
            event.returnValue = false;
    }

    function isInternetExplorer(){
        return /*@cc_on!@*/false || !!document.documentMode;
    }
    
})();

Valid characters in a Java class name

Every programming language has its own set of rules and conventions for the kinds of names that you're allowed to use, and the Java programming language is no different. The rules and conventions for naming your variables can be summarized as follows:

  • Variable names are case-sensitive. A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "_". The convention, however, is to always begin your variable names with a letter, not "$" or "_". Additionally, the dollar sign character, by convention, is never used at all. You may find some situations where auto-generated names will contain the dollar sign, but your variable names should always avoid using it. A similar convention exists for the underscore character; while it's technically legal to begin your variable's name with "_", this practice is discouraged. White space is not permitted.

  • Subsequent characters may be letters, digits, dollar signs, or underscore characters. Conventions (and common sense) apply to this rule as well. When choosing a name for your variables, use full words instead of cryptic abbreviations. Doing so will make your code easier to read and understand. In many cases it will also make your code self-documenting; fields named cadence, speed, and gear, for example, are much more intuitive than abbreviated versions, such as s, c, and g. Also keep in mind that the name you choose must not be a keyword or reserved word.

  • If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. The names gearRatio and currentGear are prime examples of this convention. If your variable stores a constant value, such as static final int NUM_GEARS = 6, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.

From the official Java Tutorial.

Why am I getting Unknown error in line 1 of pom.xml?

Got this error on eclipse IDE version 4.10, Spring boot 2.2.0.M4, changed the Spring boot version to 2.2.0.M2 (after many other solutions recommended and it solved the error). Maybe something missing or broken in the latest version of Spring boot starter project module maven POM.

Html attributes for EditorFor() in ASP.NET MVC

Why not just use

@Html.DisplayFor(model => model.Control.PeriodType)

CSS - Overflow: Scroll; - Always show vertical scroll bar?

Try the following code to display scroll bar always on your page,

::-webkit-scrollbar {
  -webkit-appearance: none;
  width: 10px;
}

::-webkit-scrollbar-thumb {
  border-radius: 5px;
  background-color: rgba(0,0,0,.5);
  -webkit-box-shadow: 0 0 1px rgba(255,255,255,.5);
}

this will always show the vertical and horizontal scroll bar on your page. If you need only a vertical scroll bar then put overflow-x: hidden

jQuery: Check if button is clicked

$('input[type="button"]').click(function (e) {
    if (e.target) {
        alert(e.target.id + ' clicked');
    }
});

you should tweak this a little (eg. use a name in stead of an id to alert), but this way you have more generic function.

Using group by and having clause

The semantics of Having

To better understand having, you need to see it from a theoretical point of view.

A group by is a query that takes a table and summarizes it into another table. You summarize the original table by grouping the original table into subsets (based upon the attributes that you specify in the group by). Each of these groups will yield one tuple.

The Having is simply equivalent to a WHERE clause after the group by has executed and before the select part of the query is computed.

Lets say your query is:

select a, b, count(*) 
from Table 
where c > 100 
group by a, b 
having count(*) > 10;

The evaluation of this query can be seen as the following steps:

  1. Perform the WHERE, eliminating rows that do not satisfy it.
  2. Group the table into subsets based upon the values of a and b (each tuple in each subset has the same values of a and b).
  3. Eliminate subsets that do not satisfy the HAVING condition
  4. Process each subset outputting the values as indicated in the SELECT part of the query. This creates one output tuple per subset left after step 3.

You can extend this to any complex query there Table can be any complex query that return a table (a cross product, a join, a UNION, etc).

In fact, having is syntactic sugar and does not extend the power of SQL. Any given query:

SELECT list 
FROM table
GROUP BY attrList
HAVING condition;

can be rewritten as:

SELECT list from (
   SELECT listatt 
   FROM table 
   GROUP BY attrList) as Name
WHERE condition;

The listatt is a list that includes the GROUP BY attributes and the expressions used in list and condition. It might be necessary to name some expressions in this list (with AS). For instance, the example query above can be rewritten as:

select a, b, count 
from (select a, b, count(*) as count
      from Table 
      where c > 100
      group by a, b) as someName
where count > 10;

The solution you need

Your solution seems to be correct:

SELECT s.sid, s.name
FROM Supplier s, Supplies su, Project pr
WHERE s.sid = su.sid AND su.jid = pr.jid
GROUP BY s.sid, s.name
HAVING COUNT (DISTINCT pr.jid) >= 2 

You join the three tables, then using sid as a grouping attribute (sname is functionally dependent on it, so it does not have an impact on the number of groups, but you must include it, otherwise it cannot be part of the select part of the statement). Then you are removing those that do not satisfy your condition: the satisfy pr.jid is >= 2, which is that you wanted originally.

Best solution to your problem

I personally prefer a simpler cleaner solution:

  1. You need to only group by Supplies (sid, pid, jid**, quantity) to find the sid of those that supply at least to two projects.
  2. Then join it to the Suppliers table to get the supplier same.

 SELECT sid, sname from
    (SELECT sid from supplies 
    GROUP BY sid, pid 
    HAVING count(DISTINCT jid) >= 2
    ) AS T1
NATURAL JOIN 
Supliers;

It will also be faster to execute, because the join is only done when needed, not all the times.

--dmg

How to check if a directory containing a file exist?

EDIT: as of Java8 you'd better use Files class:

Path resultingPath = Files.createDirectories('A/B');

I don't know if this ultimately fixes your problem but class File has method mkdirs() which fully creates the path specified by the file.

File f = new File("/A/B/");
f.mkdirs();

Not able to access adb in OS X through Terminal, "command not found"

If you are using zsh on an OS X, you have to edit the zshrc file.

Use vim or your favorite text editor to open zshrc file:

vim ~/.zshrc

Paste the path to adb in this file:

export PATH="/Users/{$USER}/Library/Android/sdk/platform-tools":$PATH

How to create range in Swift?

I want to do this:

print("Hello"[1...3])
// out: Error

But unfortunately, I can't write a subscript of my own because the loathed one takes up the name space.

We can do this however:

print("Hello"[range: 1...3])
// out: ell 

Just add this to your project:

extension String {
    subscript(range: ClosedRange<Int>) -> String {
        get {
            let start = String.Index(utf16Offset: range.lowerBound, in: self)
            let end = String.Index(utf16Offset: range.upperBound, in: self)
            return String(self[start...end])
        }
    }
}

AngularJS - Find Element with attribute

You haven't stated where you're looking for the element. If it's within the scope of a controller, it is possible, despite the chorus you'll hear about it not being the 'Angular Way'. The chorus is right, but sometimes, in the real world, it's unavoidable. (If you disagree, get in touch—I have a challenge for you.)

If you pass $element into a controller, like you would $scope, you can use its find() function. Note that, in the jQueryLite included in Angular, find() will only locate tags by name, not attribute. However, if you include the full-blown jQuery in your project, all the functionality of find() can be used, including finding by attribute.

So, for this HTML:

<div ng-controller='MyCtrl'>
    <div>
        <div name='foo' class='myElementClass'>this one</div>
    </div>
</div>

This AngularJS code should work:

angular.module('MyClient').controller('MyCtrl', [
    '$scope',
    '$element',
    '$log',
    function ($scope, $element, $log) {

        // Find the element by its class attribute, within your controller's scope
        var myElements = $element.find('.myElementClass');

        // myElements is now an array of jQuery DOM elements

        if (myElements.length == 0) {
            // Not found. Are you sure you've included the full jQuery?
        } else {
            // There should only be one, and it will be element 0
            $log.debug(myElements[0].name); // "foo"
        }

    }
]);

Align printf output in Java

You can try the below example. Do use '-' before the width to ensure left indentation. By default they will be right indented; which may not suit your purpose.

System.out.printf("%2d. %-20s $%.2f%n",  i + 1, BOOK_TYPE[i], COST[i]);

Format String Syntax: http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax

Formatting Numeric Print Output: https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

PS: This could go as a comment to DwB's answer, but i still don't have permissions to comment and so answering it.

Why is it bad practice to call System.gc()?

It has already been explained that calling system.gc() may do nothing, and that any code that "needs" the garbage collector to run is broken.

However, the pragmatic reason that it is bad practice to call System.gc() is that it is inefficient. And in the worst case, it is horribly inefficient! Let me explain.

A typical GC algorithm identifies garbage by traversing all non-garbage objects in the heap, and inferring that any object not visited must be garbage. From this, we can model the total work of a garbage collection consists of one part that is proportional to the amount of live data, and another part that is proportional to the amount of garbage; i.e. work = (live * W1 + garbage * W2).

Now suppose that you do the following in a single-threaded application.

System.gc(); System.gc();

The first call will (we predict) do (live * W1 + garbage * W2) work, and get rid of the outstanding garbage.

The second call will do (live* W1 + 0 * W2) work and reclaim nothing. In other words we have done (live * W1) work and achieved absolutely nothing.

We can model the efficiency of the collector as the amount of work needed to collect a unit of garbage; i.e. efficiency = (live * W1 + garbage * W2) / garbage. So to make the GC as efficient as possible, we need to maximize the value of garbage when we run the GC; i.e. wait until the heap is full. (And also, make the heap as big as possible. But that is a separate topic.)

If the application does not interfere (by calling System.gc()), the GC will wait until the heap is full before running, resulting in efficient collection of garbage1. But if the application forces the GC to run, the chances are that the heap won't be full, and the result will be that garbage is collected inefficiently. And the more often the application forces GC, the more inefficient the GC becomes.

Note: the above explanation glosses over the fact that a typical modern GC partitions the heap into "spaces", the GC may dynamically expand the heap, the application's working set of non-garbage objects may vary and so on. Even so, the same basic principal applies across the board to all true garbage collectors2. It is inefficient to force the GC to run.


1 - This is how the "throughput" collector works. Concurrent collectors such as CMS and G1 use different criteria to decide when to start the garbage collector.

2 - I'm also excluding memory managers that use reference counting exclusively, but no current Java implementation uses that approach ... for good reason.

URL to load resources from the classpath in Java

URL url = getClass().getClassLoader().getResource("someresource.xxx");

That should do it.

How to Add a Dotted Underline Beneath HTML Text

HTML5 element can give dotted underline so the beneath text will have dotted line rather than regular underline. And the title attribute creates a tool tip for the user when they hover their cursor over the element:

NOTE: The dotted border/underline is shown by default in Firefox and Opera, but IE8, Safari, and Chrome need a line of CSS:

<abbr title="Hyper Text Markup Language">HTML</abbr>

Background image jumps when address bar hides iOS/Android/Mobile Chrome

I set my width element, with javascript. After I set the de vh.

html

<div id="gifimage"><img src="back_phone_back.png" style="width: 100%"></div>

css

#gifimage {
    position: absolute;
    height: 70vh;
}

javascript

imageHeight = document.getElementById('gifimage').clientHeight;

// if (isMobile)       
document.getElementById('gifimage').setAttribute("style","height:" + imageHeight + "px");

This works for me. I don't use jquery ect. because I want it to load as soon as posible.

How can I store JavaScript variable output into a PHP variable?

in your view:

  <?php $value = '<p id="course_id"></p>';?>

javascript code:

  var course = document.getElementById("courses").value;
  
 document.getElementById("course_id").innerHTML = course;

How much memory can a 32 bit process access on a 64 bit operating system?

The limit is not 2g or 3gb its 4gb for 32bit.

The reason people think its 3gb is that the OS shows 3gb free when they really have 4gb of system ram.

Its total RAM of 4gb. So if you have a 1 gb video card that counts as part of the total ram viewed by the 32bit OS.

4Gig not 3 not 2 got it?

center aligning a fixed position div

This works if you want the element to span across the page like another navigation bar.

width: calc (width: 100% - width whatever else is off centering it)

For example if your side navigation bar is 200px:

width: calc(100% - 200px);

JavaScript error: "is not a function"

Your LMSInitialize function is declared inside Scorm_API_12 function. So it can be seen only in Scorm_API_12 function's scope.

If you want to use this function like API.LMSInitialize(""), declare Scorm_API_12 function like this:

function Scorm_API_12() {
var Initialized = false;

this.LMSInitialize = function(param) {
    errorCode = "0";
    if (param == "") {
        if (!Initialized) {
            Initialized = true;
            errorCode = "0";
            return "true";
        } else {
            errorCode = "101";
        }
    } else {
        errorCode = "201";
    }
    return "false";
}

// some more functions, omitted.
}

var API = new Scorm_API_12();

How does strtok() split the string into tokens in C?

strtok doesn't change the parameter itself (str). It stores that pointer (in a local static variable). It can then change what that parameter points to in subsequent calls without having the parameter passed back. (And it can advance that pointer it has kept however it needs to perform its operations.)

From the POSIX strtok page:

This function uses static storage to keep track of the current string position between calls.

There is a thread-safe variant (strtok_r) that doesn't do this type of magic.

What are forward declarations in C++?

int add(int x, int y); // forward declaration using function prototype

Can you explain "forward declaration" more further? What is the problem if we use it in the main() function?

It's same as #include"add.h". If you know,preprocessor expands the file which you mention in #include, in the .cpp file where you write the #include directive. That means, if you write #include"add.h", you get the same thing, it is as if you doing "forward declaration".

I'm assuming that add.h has this line:

int add(int x, int y); 

Using custom fonts using CSS?

Generically, you can use a custom font using @font-face in your CSS. Here's a very basic example:

@font-face {
    font-family: 'YourFontName'; /*a name to be used later*/
    src: url('http://domain.com/fonts/font.ttf'); /*URL to font*/
}

Then, trivially, to use the font on a specific element:

.classname {
    font-family: 'YourFontName';
}

(.classname is your selector).

Note that certain font-formats don't work on all browsers; you can use fontsquirrel.com's generator to avoid too much effort converting.

You can find a nice set of free web-fonts provided by Google Fonts (also has auto-generated CSS @font-face rules, so you don't have to write your own).

while also preventing people from having free access to download the font, if possible

Nope, it isn't possible to style your text with a custom font embedded via CSS, while preventing people from downloading it. You need to use images, Flash, or the HTML5 Canvas, all of which aren't very practical.

I hope that helped!

How to expand/collapse a diff sections in Vimdiff?

Aside from the ones you mention, I only use frequently when diffing the following:

  • :diffupdate :diffu -> recalculate the diff, useful when after making several changes vim's isn't showing minimal changes anymore. Note that it only works if the files have been modified inside vimdiff. Otherwise, use:
    • :e to reload the files if they have been modified outside of vimdiff.
  • :set noscrollbind -> temporarily disable simultaneous scrolling on both buffers, reenable by :set scrollbind and scrolling.

Most of what you asked for is folding: vim user manual's chapter on folding. Outside of diffs I sometime use:

  • zo -> open fold.
  • zc -> close fold.

But you'll probably be better served by:

  • zr -> reducing folding level.
  • zm -> one more folding level, please.

or even:

  • zR -> Reduce completely the folding, I said!.
  • zM -> fold Most!.

The other thing you asked for, use n lines of folding, can be found at the vim reference manual section on options, via the section on diff:

  • set diffopt=<TAB>, then update or add context:n.

You should also take a look at the user manual section on diff.

How to override and extend basic Django admin templates?

if you need to overwrite the admin/index.html, you can set the index_template parameter of the AdminSite.

e.g.

# urls.py
...
from django.contrib import admin

admin.site.index_template = 'admin/my_custom_index.html'
admin.autodiscover()

and place your template in <appname>/templates/admin/my_custom_index.html

In Angular, how to pass JSON object/array into directive?

If you want to follow all the "best practices," there's a few things I'd recommend, some of which are touched on in other answers and comments to this question.


First, while it doesn't have too much of an affect on the specific question you asked, you did mention efficiency, and the best way to handle shared data in your application is to factor it out into a service.

I would personally recommend embracing AngularJS's promise system, which will make your asynchronous services more composable compared to raw callbacks. Luckily, Angular's $http service already uses them under the hood. Here's a service that will return a promise that resolves to the data from the JSON file; calling the service more than once will not cause a second HTTP request.

app.factory('locations', function($http) {
  var promise = null;

  return function() {
    if (promise) {
      // If we've already asked for this data once,
      // return the promise that already exists.
      return promise;
    } else {
      promise = $http.get('locations/locations.json');
      return promise;
    }
  };
});

As far as getting the data into your directive, it's important to remember that directives are designed to abstract generic DOM manipulation; you should not inject them with application-specific services. In this case, it would be tempting to simply inject the locations service into the directive, but this couples the directive to that service.

A brief aside on code modularity: a directive’s functions should almost never be responsible for getting or formatting their own data. There’s nothing to stop you from using the $http service from within a directive, but this is almost always the wrong thing to do. Writing a controller to use $http is the right way to do it. A directive already touches a DOM element, which is a very complex object and is difficult to stub out for testing. Adding network I/O to the mix makes your code that much more difficult to understand and that much more difficult to test. In addition, network I/O locks in the way that your directive will get its data – maybe in some other place you’ll want to have this directive receive data from a socket or take in preloaded data. Your directive should either take data in as an attribute through scope.$eval and/or have a controller to handle acquiring and storing the data.

- The 80/20 Guide to Writing AngularJS Directives

In this specific case, you should place the appropriate data on your controller's scope and share it with the directive via an attribute.

app.controller('SomeController', function($scope, locations) {
  locations().success(function(data) {
    $scope.locations = data;
  });
});
<ul class="list">
   <li ng-repeat="location in locations">
      <a href="#">{{location.id}}. {{location.name}}</a>
   </li>
</ul>
<map locations='locations'></map>
app.directive('map', function() {
  return {
    restrict: 'E',
    replace: true,
    template: '<div></div>',
    scope: {
      // creates a scope variable in your directive
      // called `locations` bound to whatever was passed
      // in via the `locations` attribute in the DOM
      locations: '=locations'
    },
    link: function(scope, element, attrs) {
      scope.$watch('locations', function(locations) {
        angular.forEach(locations, function(location, key) {
          // do something
        });
      });
    }
  };
});

In this way, the map directive can be used with any set of location data--the directive is not hard-coded to use a specific set of data, and simply linking the directive by including it in the DOM will not fire off random HTTP requests.

Can I use jQuery with Node.js?

As of jsdom v10, .env() function is deprecated. I did it like below after trying a lot of things to require jquery:

_x000D_
_x000D_
var jsdom = require('jsdom');_x000D_
const { JSDOM } = jsdom;_x000D_
const { window } = new JSDOM();_x000D_
const { document } = (new JSDOM('')).window;_x000D_
global.document = document;_x000D_
_x000D_
var $ = jQuery = require('jquery')(window);
_x000D_
_x000D_
_x000D_

Hope this helps you or anyone who has been facing these types of issues.

Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2

Updated Answer: For Android Studio 3.1 & above

For Android Studio 3.1 & above, the distributionUrl has been updated to version 4.6 from version 4.4. Your gradle-wrapper.properties should look like this:

#DATE
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip

Updated Answer:

For Android Studio 3.0 & above, the distributionUrl has been updated to version 4.1 from version 3.3. Your gradle-wrapper.properties should look like this:

#DATE
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip

Original Answer:

#DATE
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip

How to know Laravel version and where is it defined?

In your Laravel deployment it would be

/vendor/laravel/framework/src/Illuminate/Foundation/Application.php

to see who changed your Laravel version look at what's defined in composer.json. If you have "laravel/framework": "5.4.*", then it will update to the latest after composer update is run. Composer.lock is the file that results from running a composer update, so really see who last one to modify the composer.json file was (hopefully you have that in version control). You can read more about it here https://getcomposer.org/doc/01-basic-usage.md

Find all packages installed with easy_install/pip?

The below is a little slow, but it gives a nicely formatted list of packages that pip is aware of. That is to say, not all of them were installed "by" pip, but all of them should be able to be upgraded by pip.

$ pip search . | egrep -B1 'INSTALLED|LATEST'

The reason it is slow is that it lists the contents of the entire pypi repo. I filed a ticket suggesting pip list provide similar functionality but more efficiently.

Sample output: (restricted the search to a subset instead of '.' for all.)

$ pip search selenium | egrep -B1 'INSTALLED|LATEST'

selenium                  - Python bindings for Selenium
  INSTALLED: 2.24.0
  LATEST:    2.25.0
--
robotframework-selenium2library - Web testing library for Robot Framework
  INSTALLED: 1.0.1 (latest)
$

Http 415 Unsupported Media type error with JSON

The reason can be not adding "annotation-driven" in your dispatcher servlet xml file. and also it may be due to not adding as application/json in the headers

How can I pair socks from a pile efficiently?

This is how I actually do it, for p pairs of socks (n = 2p individual socks):

  • Grab a sock at random from the pile.
  • For the first sock, or if all previously-chosen socks have been paired, simply place the sock into the first "slot" of an "array" of unpaired socks in front of you.
  • If you have one or more selected unpaired socks, check your current sock against all the unpaired socks in the array.
    • It is possible to separate socks into general classes or types (white/black, ankle/crew, athletic/dress) when building your array, and "drill-down" to only compare like-for-like.
    • If you find an acceptable match, put both socks together and remove them from the array.
    • If you do not, put the current sock into the first open slot in the array.
  • Repeat with every sock.

The worst-case scenario of this scheme is that every pair of socks is different enough that it must be matched exactly, and that the first n/2 socks you pick are all different. This is your O(n2) scenario, and it's extremely unlikely. If the number of unique types of sock t is less than the number of pairs p = n/2, and the socks in each type are alike enough (usually in wear-related terms) that any sock of that type can be paired with any other, then as I inferred above, the maximum number of socks you will ever have to compare to is t, after which the next one you pull will match one of the unpaired socks. This scenario is much more likely in the average sock drawer than the worst-case, and reduces the worst-case complexity to O(n*t) where usually t << n.

Windows Batch Files: if else

Surround your %1 with something.

Eg:

if not "%1" == ""

Another one I've seen fairly often:

if not {%1} == {}

And so on...

The problem, as you can likely guess, is that the %1 is literally replaced with emptiness. It is not 'an empty string' it is actually a blank spot in your source file at that point.

Then after the replacement, the interpreter tries to parse the if statement and gets confused.

Java/Groovy - simple date reformatting

oldDate is not in the format of the SimpleDateFormat you are using to parse it.

Try this format: dd-MMM-yyyy - It matches what you're trying to parse.

Understanding unique keys for array children in React.js

Just add the unique key to the your Components

data.map((marker)=>{
    return(
        <YourComponents 
            key={data.id}     // <----- unique key
        />
    );
})

NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference

The exception occurs due to this statement,

called_from.equalsIgnoreCase("add")

It seem that the previous statement

String called_from = getIntent().getStringExtra("called");

returned a null reference.

You can check whether the intent to start this activity contains such a key "called".

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

'It' requires a dll file called cvextern.dll . 'It' can be either your own cs file or some other third party dll which you are using in your project.

To call native dlls to your own cs file, copy the dll into your project's root\lib directory and add it as an existing item. (Add -Existing item) and use Dllimport with correct location.

For third party , copy the native library to the folder where the third party library resides and add it as an existing item.

After building make sure that the required dlls are appearing in Build folder. In some cases it may not appear or get replaced in Build folder. Delete the Build folder manually and build again.

How to remove files that are listed in the .gitignore but still on the repository?

I can't say it's an appropriate solution but you can try this.

Steps

  • I am hoping that you have already cloned your repo.
  • Now copy the file somewhere outside of your project.
  • Add that filename with a location in gitigonre file.
  • Remove that file from your local project.
  • Push your code to remote origin.
  • And now add that copied file into your project it'll be ignored.

This is just a hack solution if you want to maintain the history and don't to create mass in it.

If you don't want to use this solution please kindly ignore and try to avoid devote it. Because I am really trying to increase my score on this side

How to group pandas DataFrame entries by date in a non-unique column

This might be easier to explain with a sample dataset.

Create Sample Data

Let's assume we have a single column of Timestamps, date and another column we would like to perform an aggregation on, a.

df = pd.DataFrame({'date':pd.DatetimeIndex(['2012-1-1', '2012-6-1', '2015-1-1', '2015-2-1', '2015-3-1']),
                   'a':[9,5,1,2,3]}, columns=['date', 'a'])

df

        date  a
0 2012-01-01  9
1 2012-06-01  5
2 2015-01-01  1
3 2015-02-01  2
4 2015-03-01  3

There are several ways to group by year

  • Use the dt accessor with year property
  • Put date in index and use anonymous function to access year
  • Use resample method
  • Convert to pandas Period

.dt accessor with year property

When you have a column (and not an index) of pandas Timestamps, you can access many more extra properties and methods with the dt accessor. For instance:

df['date'].dt.year

0    2012
1    2012
2    2015
3    2015
4    2015
Name: date, dtype: int64

We can use this to form our groups and calculate some aggregations on a particular column:

df.groupby(df['date'].dt.year)['a'].agg(['sum', 'mean', 'max'])

      sum  mean  max
date                
2012   14     7    9
2015    6     2    3

put date in index and use anonymous function to access year

If you set the date column as the index, it becomes a DateTimeIndex with the same properties and methods as the dt accessor gives normal columns

df1 = df.set_index('date')
df1.index.year

Int64Index([2012, 2012, 2015, 2015, 2015], dtype='int64', name='date')

Interestingly, when using the groupby method, you can pass it a function. This function will be implicitly passed the DataFrame's index. So, we can get the same result from above with the following:

df1.groupby(lambda x: x.year)['a'].agg(['sum', 'mean', 'max'])

      sum  mean  max
2012   14     7    9
2015    6     2    3

Use the resample method

If your date column is not in the index, you must specify the column with the on parameter. You also need to specify the offset alias as a string.

df.resample('AS', on='date')['a'].agg(['sum', 'mean', 'max'])

             sum  mean  max
date                       
2012-01-01  14.0   7.0  9.0
2013-01-01   NaN   NaN  NaN
2014-01-01   NaN   NaN  NaN
2015-01-01   6.0   2.0  3.0

Convert to pandas Period

You can also convert the date column to a pandas Period object. We must pass in the offset alias as a string to determine the length of the Period.

df['date'].dt.to_period('A')

0   2012
1   2012
2   2015
3   2015
4   2015
Name: date, dtype: object

We can then use this as a group

df.groupby(df['date'].dt.to_period('Y'))['a'].agg(['sum', 'mean', 'max'])


      sum  mean  max
2012   14     7    9
2015    6     2    3

Getting "conflicting types for function" in C, why?

When you don't give a prototype for the function before using it, C assumes that it takes any number of parameters and returns an int. So when you first try to use do_something, that's the type of function the compiler is looking for. Doing this should produce a warning about an "implicit function declaration".

So in your case, when you actually do declare the function later on, C doesn't allow function overloading, so it gets pissy because to it you've declared two functions with different prototypes but with the same name.

Short answer: declare the function before trying to use it.

jquery equivalent for JSON.stringify

There is no such functionality in jQuery. Use JSON.stringify or alternatively any jQuery plugin with similar functionality (e.g jquery-json).

Detect if HTML5 Video element is playing

jQuery(document).on('click', 'video', function(){
        if (this.paused) {
            this.play();
        } else {
            this.pause();
        }
});

Using G++ to compile multiple .cpp and .h files

As rebenvp said I used:

g++ *.cpp -o output

And then do this for output:

./output

But a better solution is to use make file. Read here to know more about make files.

Also make sure that you have added the required .h files in the .cpp files.

Center a column using Twitter Bootstrap 3

You can use the very flexible solution flexbox to your Bootstrap.

justify-content: center;

can center your column.

Check out flex.

jQuery get the image src

When dealing with the HTML DOM (ie. this), the array selector [0] must be used to retrieve the jQuery element from the Javascript array.

$(this)[0].getAttribute('src');

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

I enabled zlib.output_compression in php.ini and it seemed to fix the issue for me.

PHP Regex to check date is in YYYY-MM-DD format

This method can be useful to validate date in PHP. Current method is for mm/dd/yyyy format. You have to update parameter sequence in checkdate as per your format and delimiter in explode .

    function isValidDate($dt)
    {
        $dtArr = explode('/', $dt);
        if (!empty($dtArr[0]) && !empty($dtArr[1]) && !empty($dtArr[2])) {
            return checkdate((int) $dtArr[0], (int) $dtArr[1], (int) $dtArr[2]);
        } else {
            return false;
        }
    }

How can I search (case-insensitive) in a column using LIKE wildcard?

You must set up proper encoding and collation for your tables.

Table encoding must reflect the actual data encoding. What is your data encoding?

To see table encoding, you can run a query SHOW CREATE TABLE tablename

How to get the file name from a full path using JavaScript?

var filename = fullPath.replace(/^.*[\\\/]/, '')

This will handle both \ OR / in paths

How to round a number to significant figures in Python

I can't think of anything that would be able to handle this out of the box. But it's fairly well handled for floating point numbers.

>>> round(1.2322, 2)
1.23

Integers are trickier. They're not stored as base 10 in memory, so significant places isn't a natural thing to do. It's fairly trivial to implement once they're a string though.

Or for integers:

>>> def intround(n, sigfigs):
...   n = str(n)
...   return n[:sigfigs] + ('0' * (len(n)-(sigfigs)))

>>> intround(1234, 1)
'1000'
>>> intround(1234, 2)

If you would like to create a function that handles any number, my preference would be to convert them both to strings and look for a decimal place to decide what to do:

>>> def roundall1(n, sigfigs):
...   n = str(n)
...   try:
...     sigfigs = n.index('.')
...   except ValueError:
...     pass
...   return intround(n, sigfigs)

Another option is to check for type. This will be far less flexible, and will probably not play nicely with other numbers such as Decimal objects:

>>> def roundall2(n, sigfigs):
...   if type(n) is int: return intround(n, sigfigs)
...   else: return round(n, sigfigs)

How to compile a Perl script to a Windows executable with Strawberry Perl?

  :: short answer :
  :: perl -MCPAN -e "install PAR::Packer" 
  pp -o <<DesiredExeName>>.exe <<MyFancyPerlScript>> 

  :: long answer - create the following cmd , adjust vars to your taste ...
  :: next_line_is_templatized
  :: file:compile-morphus.1.2.3.dev.ysg.cmd v1.0.0
  :: disable the echo
  @echo off

  :: this is part of the name of the file - not used
  set _Action=run

  :: the name of the Product next_line_is_templatized
  set _ProductName=morphus

  :: the version of the current Product next_line_is_templatized
  set _ProductVersion=1.2.3

  :: could be dev , test , dev , prod next_line_is_templatized
  set _ProductType=dev

  :: who owns this Product / environment next_line_is_templatized
  set _ProductOwner=ysg

  :: identifies an instance of the tool ( new instance for this version could be created by simply changing the owner )   
  set _EnvironmentName=%_ProductName%.%_ProductVersion%.%_ProductType%.%_ProductOwner%

  :: go the run dir
  cd %~dp0

  :: do 4 times going up
  for /L %%i in (1,1,5) do pushd ..

  :: The BaseDir is 4 dirs up than the run dir
  set _ProductBaseDir=%CD%
  :: debug echo BEFORE _ProductBaseDir is %_ProductBaseDir%
  :: remove the trailing \

  IF %_ProductBaseDir:~-1%==\ SET _ProductBaseDir=%_ProductBaseDir:~0,-1%
  :: debug echo AFTER _ProductBaseDir is %_ProductBaseDir%
  :: debug pause


  :: The version directory of the Product 
  set _ProductVersionDir=%_ProductBaseDir%\%_ProductName%\%_EnvironmentName%

  :: the dir under which all the perl scripts are placed
  set _ProductVersionPerlDir=%_ProductVersionDir%\sfw\perl

  :: The Perl script performing all the tasks
  set _PerlScript=%_ProductVersionPerlDir%\%_Action%_%_ProductName%.pl

  :: where the log events are stored 
  set _RunLog=%_ProductVersionDir%\data\log\compile-%_ProductName%.cmd.log

  :: define a favorite editor 
  set _MyEditor=textpad

  ECHO Check the variables 
  set _
  :: debug PAUSE
  :: truncate the run log
  echo date is %date% time is %time% > %_RunLog%


  :: uncomment this to debug all the vars 
  :: debug set  >> %_RunLog%

  :: for each perl pm and or pl file to check syntax and with output to logs
  for /f %%i in ('dir %_ProductVersionPerlDir%\*.pl /s /b /a-d' ) do echo %%i >> %_RunLog%&perl -wc %%i | tee -a  %_RunLog% 2>&1


  :: for each perl pm and or pl file to check syntax and with output to logs
  for /f %%i in ('dir %_ProductVersionPerlDir%\*.pm /s /b /a-d' ) do echo %%i >> %_RunLog%&perl -wc %%i | tee -a  %_RunLog% 2>&1

  :: now open the run log
  cmd /c start /max %_MyEditor% %_RunLog%


  :: this is the call without debugging
  :: old 
  echo CFPoint1  OK The run cmd script %0 is executed >> %_RunLog%
  echo CFPoint2  OK  compile the exe file  STDOUT and STDERR  to a single _RunLog file >> %_RunLog%
  cd %_ProductVersionPerlDir%

  pp -o %_Action%_%_ProductName%.exe %_PerlScript% | tee -a %_RunLog% 2>&1 

  :: open the run log
  cmd /c start /max %_MyEditor% %_RunLog%

  :: uncomment this line to wait for 5 seconds
  :: ping localhost -n 5

  :: uncomment this line to see what is happening 
  :: PAUSE

  ::
  :::::::
  :: Purpose: 
  :: To compile every *.pl file into *.exe file under a folder 
  :::::::
  :: Requirements : 
  :: perl , pp , win gnu utils tee 
  :: perl -MCPAN -e "install PAR::Packer" 
  :: text editor supporting <<textEditor>> <<FileNameToOpen>> cmd call syntax
  :::::::
  :: VersionHistory
  :: 1.0.0 --- 2012-06-23 12:05:45 --- ysg --- Initial creation from run_morphus.cmd
  :::::::
  :: eof file:compile-morphus.1.2.3.dev.ysg.cmd v1.0.0

VB.NET 'If' statement with 'Or' conditional has both sides evaluated?

It's your "fault" in that that's how Or is defined, so it's the behaviour you should expect:

In a Boolean comparison, the Or operator always evaluates both expressions, which could include making procedure calls. The OrElse Operator (Visual Basic) performs short-circuiting, which means that if expression1 is True, then expression2 is not evaluated.

But you don't have to endure it. You can use OrElse to get short-circuiting behaviour.

So you probably want:

If (example Is Nothing OrElse Not example.Item = compare.Item) Then
    'Proceed
End If

I can't say it reads terribly nicely, but it should work...

Insert Update trigger how to determine if insert or update

CREATE TRIGGER dbo.TableName_IUD
ON dbo.TableName
AFTER INSERT, UPDATE, DELETE
AS 
BEGIN
    SET NOCOUNT ON;

    --
    -- Check if this is an INSERT, UPDATE or DELETE Action.
    -- 
    DECLARE @action as char(1);

    SET @action = 'I'; -- Set Action to Insert by default.
    IF EXISTS(SELECT * FROM DELETED)
    BEGIN
        SET @action = 
            CASE
                WHEN EXISTS(SELECT * FROM INSERTED) THEN 'U' -- Set Action to Updated.
                ELSE 'D' -- Set Action to Deleted.       
            END
    END
    ELSE 
        IF NOT EXISTS(SELECT * FROM INSERTED) RETURN; -- Nothing updated or inserted.

    ...

    END

Task not serializable: java.io.NotSerializableException when calling function outside closure only on classes not objects

RDDs extend the Serialisable interface, so this is not what's causing your task to fail. Now this doesn't mean that you can serialise an RDD with Spark and avoid NotSerializableException

Spark is a distributed computing engine and its main abstraction is a resilient distributed dataset (RDD), which can be viewed as a distributed collection. Basically, RDD's elements are partitioned across the nodes of the cluster, but Spark abstracts this away from the user, letting the user interact with the RDD (collection) as if it were a local one.

Not to get into too many details, but when you run different transformations on a RDD (map, flatMap, filter and others), your transformation code (closure) is:

  1. serialized on the driver node,
  2. shipped to the appropriate nodes in the cluster,
  3. deserialized,
  4. and finally executed on the nodes

You can of course run this locally (as in your example), but all those phases (apart from shipping over network) still occur. [This lets you catch any bugs even before deploying to production]

What happens in your second case is that you are calling a method, defined in class testing from inside the map function. Spark sees that and since methods cannot be serialized on their own, Spark tries to serialize the whole testing class, so that the code will still work when executed in another JVM. You have two possibilities:

Either you make class testing serializable, so the whole class can be serialized by Spark:

import org.apache.spark.{SparkContext,SparkConf}

object Spark {
  val ctx = new SparkContext(new SparkConf().setAppName("test").setMaster("local[*]"))
}

object NOTworking extends App {
  new Test().doIT
}

class Test extends java.io.Serializable {
  val rddList = Spark.ctx.parallelize(List(1,2,3))

  def doIT() =  {
    val after = rddList.map(someFunc)
    after.collect().foreach(println)
  }

  def someFunc(a: Int) = a + 1
}

or you make someFunc function instead of a method (functions are objects in Scala), so that Spark will be able to serialize it:

import org.apache.spark.{SparkContext,SparkConf}

object Spark {
  val ctx = new SparkContext(new SparkConf().setAppName("test").setMaster("local[*]"))
}

object NOTworking extends App {
  new Test().doIT
}

class Test {
  val rddList = Spark.ctx.parallelize(List(1,2,3))

  def doIT() =  {
    val after = rddList.map(someFunc)
    after.collect().foreach(println)
  }

  val someFunc = (a: Int) => a + 1
}

Similar, but not the same problem with class serialization can be of interest to you and you can read on it in this Spark Summit 2013 presentation.

As a side note, you can rewrite rddList.map(someFunc(_)) to rddList.map(someFunc), they are exactly the same. Usually, the second is preferred as it's less verbose and cleaner to read.

EDIT (2015-03-15): SPARK-5307 introduced SerializationDebugger and Spark 1.3.0 is the first version to use it. It adds serialization path to a NotSerializableException. When a NotSerializableException is encountered, the debugger visits the object graph to find the path towards the object that cannot be serialized, and constructs information to help user to find the object.

In OP's case, this is what gets printed to stdout:

Serialization stack:
    - object not serializable (class: testing, value: testing@2dfe2f00)
    - field (class: testing$$anonfun$1, name: $outer, type: class testing)
    - object (class testing$$anonfun$1, <function1>)

UIViewController viewDidLoad vs. viewWillAppear: What is the proper division of labor?

viewDidLoad is things you have to do once. viewWillAppear gets called every time the view appears. You should do things that you only have to do once in viewDidLoad - like setting your UILabel texts. However, you may want to modify a specific part of the view every time the user gets to view it, e.g. the iPod application scrolls the lyrics back to the top every time you go to the "Now Playing" view.

However, when you are loading things from a server, you also have to think about latency. If you pack all of your network communication into viewDidLoad or viewWillAppear, they will be executed before the user gets to see the view - possibly resulting a short freeze of your app. It may be good idea to first show the user an unpopulated view with an activity indicator of some sort. When you are done with your networking, which may take a second or two (or may even fail - who knows?), you can populate the view with your data. Good examples on how this could be done can be seen in various twitter clients. For example, when you view the author detail page in Twitterrific, the view only says "Loading..." until the network queries have completed.

How do I make a LinearLayout scrollable?

<?xml version="1.0" encoding="utf-8"?>
<ScrollView ...>

    <LinearLayout ...>

        ...
        ...

    </LinearLayout>

</ScrollView>

Android: how to parse URL String with spaces to URI object?

You should in fact URI-encode the "invalid" characters. Since the string actually contains the complete URL, it's hard to properly URI-encode it. You don't know which slashes / should be taken into account and which not. You cannot predict that on a raw String beforehand. The problem really needs to be solved at a higher level. Where does that String come from? Is it hardcoded? Then just change it yourself accordingly. Does it come in as user input? Validate it and show error, let the user solve itself.

At any way, if you can ensure that it are only the spaces in URLs which makes it invalid, then you can also just do a string-by-string replace with %20:

URI uri = new URI(string.replace(" ", "%20"));

Or if you can ensure that it's only the part after the last slash which needs to be URI-encoded, then you can also just do so with help of android.net.Uri utility class:

int pos = string.lastIndexOf('/') + 1;
URI uri = new URI(string.substring(0, pos) + Uri.encode(string.substring(pos)));

Do note that URLEncoder is insuitable for the task as it's designed to encode query string parameter names/values as per application/x-www-form-urlencoded rules (as used in HTML forms). See also Java URL encoding of query string parameters.

SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?

Here is a simple example for others visiting this old post, but is confused by the example in the question and the other answer:

Delivery -> Package (One -> Many)

CREATE TABLE Delivery(
    Id INT IDENTITY PRIMARY KEY,
    NoteNumber NVARCHAR(255) NOT NULL
)

CREATE TABLE Package(
    Id INT IDENTITY PRIMARY KEY,
    Status INT NOT NULL DEFAULT 0,
    Delivery_Id INT NOT NULL,
    CONSTRAINT FK_Package_Delivery_Id FOREIGN KEY (Delivery_Id) REFERENCES Delivery (Id) ON DELETE CASCADE
)

The entry with the foreign key Delivery_Id (Package) is deleted with the referenced entity in the FK relationship (Delivery).

So when a Delivery is deleted the Packages referencing it will also be deleted. If a Package is deleted nothing happens to any deliveries.

Python equivalent for HashMap

You need a dict:

my_dict = {'cheese': 'cake'}

Example code (from the docs):

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

You can read more about dictionaries here.

how to find my angular version in my project?

  1. Browser > Inspect > Element >

    <.app-root _nghost-hey-c0="" ng-version="8.2.11">

  2. In terminal

    :> ng version
    :> ng --version
    :> ng -v

Sniff HTTP packets for GET and POST requests from an application

Put http.request.method == "POST" in the display filter of wireshark to only show POST requests. Click on the packet, then expand the Hypertext Transfer Protocol field. The POST data will be right there on top.

How to check if array element is null to avoid NullPointerException in Java

The example code does not throw an NPE. (there also should not be a ';' behind the i++)

How to Identify port number of SQL server

Visually you can open "SQL Server Configuration Manager" and check properties of "Network Configuration":

SQL Server Configuration

Compare if BigDecimal is greater than zero

it is safer to use the method compareTo()

    BigDecimal a = new BigDecimal(10);
    BigDecimal b = BigDecimal.ZERO;

    System.out.println(" result ==> " + a.compareTo(b));

console print

    result ==> 1

compareTo() returns

  • 1 if a is greater than b
  • -1 if b is less than b
  • 0 if a is equal to b

now for your problem you can use

if (value.compareTo(BigDecimal.ZERO) > 0)

or

if (value.compareTo(new BigDecimal(0)) > 0)

I hope it helped you.

setTimeout / clearTimeout problems

The problem is that the timer variable is local, and its value is lost after each function call.

You need to persist it, you can put it outside the function, or if you don't want to expose the variable as global, you can store it in a closure, e.g.:

var endAndStartTimer = (function () {
  var timer; // variable persisted here
  return function () {
    window.clearTimeout(timer);
    //var millisecBeforeRedirect = 10000; 
    timer = window.setTimeout(function(){alert('Hello!');},10000); 
  };
})();

How to clear the logs properly for a Docker container?

You can set up logrotate to clear the logs periodically.

Example file in /etc/logrotate.d/docker-logs

/var/lib/docker/containers/*/*.log {
 rotate 7
 daily
 compress
 size=50M
 missingok
 delaycompress
 copytruncate
}

equivalent of rm and mv in windows .cmd

move in windows is equivalent of mv command in Linux

del in windows is equivalent of rm command in Linux

How to place the "table" at the middle of the webpage?

The shortest and easiest answer is: you shouldn't vertically center things in webpages. HTML and CSS simply are not created with that in mind. They are text formatting languages, not user interface design languages.

That said, this is the best way I can think of. However, this will NOT WORK in Internet Explorer 7 and below!

<style>
  html, body {
    height: 100%;
  }
  #tableContainer-1 {
    height: 100%;
    width: 100%;
    display: table;
  }
  #tableContainer-2 {
    vertical-align: middle;
    display: table-cell;
    height: 100%;
  }
  #myTable {
    margin: 0 auto;
  }
</style>
<div id="tableContainer-1">
  <div id="tableContainer-2">
    <table id="myTable" border>
      <tr><td>Name</td><td>J W BUSH</td></tr>
      <tr><td>Proficiency</td><td>PHP</td></tr>
      <tr><td>Company</td><td>BLAH BLAH</td></tr>
    </table>
  </div>
</div>

AngularJS: ng-model not binding to ng-checked for checkboxes

What you could do is use ng-repeat passing in the value of whatever you're iterating on to the ng-checked and from there utilising ng-class to apply your styles depending on the result.

I did something similar recently and it worked for me.

How to Kill A Session or Session ID (ASP.NET/C#)

Session.Abandon()

This marks the session as Abandoned, but the session won't actually be Abandoned at that moment, the request has to complete first.

*ngIf and *ngFor on same element causing error

I didn't want to wrap my *ngFor into another div with *ngIf or use [ngClass], so I created a pipe named show:

show.pipe.ts

export class ShowPipe implements PipeTransform {    
  transform(values: any[], show: boolean): any[] {
    if (!show) {
      return[];
    }
    return values;
  }
}

any.page.html

<table>
  <tr *ngFor="let arr of anyArray | show : ngIfCondition">
    <td>{{arr.label}}</td>
  </tr>
</table>

Java Compare Two Lists

You can try intersection() and subtract() methods from CollectionUtils.

intersection() method gives you a collection containing common elements and the subtract() method gives you all the uncommon ones.

They should also take care of similar elements

What does it mean when the size of a VARCHAR2 in Oracle is declared as 1 byte?

it means ONLY one byte will be allocated per character - so if you're using multi-byte charsets, your 1 character won't fit

if you know you have to have at least room enough for 1 character, don't use the BYTE syntax unless you know exactly how much room you'll need to store that byte

when in doubt, use VARCHAR2(1 CHAR)

same thing answered here Difference between BYTE and CHAR in column datatypes

Also, in 12c the max for varchar2 is now 32k, not 4000. If you need more than that, use CLOB

in Oracle, don't use VARCHAR