Programs & Examples On #Ometa

OMeta is an object oriented language for pattern matching, which tries to provide convenient way for programmers to create parsers and compilers.

Access And/Or exclusions

Seeing that it appears you are running using the SQL syntax, try with the correct wild card.

SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4; 

Class has no initializers Swift

This is from Apple doc

Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state.

You get the error message Class "HomeCell" has no initializers because your variables is in an indeterminate state. Either you create initializers or you make them optional types, using ! or ?

how to fix groovy.lang.MissingMethodException: No signature of method:

This may also be because you might have given classname with all letters in lowercase something which groovy (know of version 2.5.0) does not support.

class name - User is accepted but user is not.

How can I bold the fonts of a specific row or cell in an Excel worksheet with C#?

Your question is a little unclear...as the part that you indicate you want to bold in Excel is a DataGridView in the import from word method. Do you maybe want to bold the first row in the excel document?

using xl = Microsoft.Office.Interop.Excel;

xl.Range rng = (xl.Range)xlWorkSheet.Rows[0];
rng.Font.Bold = true;

Simple as that!

HTH, Z

In Postgresql, force unique on combination of two columns

CREATE TABLE someTable (
    id serial PRIMARY KEY,
    col1 int NOT NULL,
    col2 int NOT NULL,
    UNIQUE (col1, col2)
)

autoincrement is not postgresql. You want a serial.

If col1 and col2 make a unique and can't be null then they make a good primary key:

CREATE TABLE someTable (
    col1 int NOT NULL,
    col2 int NOT NULL,
    PRIMARY KEY (col1, col2)
)

JPA Query.getResultList() - use in a generic way

If you need a more convenient way to access the results, it's possible to transform the result of an arbitrarily complex SQL query to a Java class with minimal hassle:

Query query = em.createNativeQuery("select 42 as age, 'Bob' as name from dual", 
        MyTest.class);
MyTest myTest = (MyTest) query.getResultList().get(0);
assertEquals("Bob", myTest.name);

The class needs to be declared an @Entity, which means you must ensure it has an unique @Id.

@Entity
class MyTest {
    @Id String name;
    int age;
}

How does Django's Meta class work?

Django's Model class specifically handles having an attribute named Meta which is a class. It's not a general Python thing.

Python metaclasses are completely different.

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

You must sort your data according your needs (es. in reverse order) and use select top query

SELECT * FROM X WHERE id IN (...) with Dapper ORM

Directly from the GitHub project homepage:

Dapper allow you to pass in IEnumerable and will automatically parameterize your query.

connection.Query<int>(
    @"select * 
      from (select 1 as Id union all select 2 union all select 3) as X 
      where Id in @Ids", 
    new { Ids = new int[] { 1, 2, 3 });

Will be translated to:

select * 
from (select 1 as Id union all select 2 union all select 3) as X 
where Id in (@Ids1, @Ids2, @Ids3)

// @Ids1 = 1 , @Ids2 = 2 , @Ids2 = 3

SQL Server - boolean literal?

SQL Server does not have literal true or false values. You'll need to use the 1=1 method (or similar) in the rare cases this is needed.

One option is to create your own named variables for true and false

DECLARE @TRUE bit
DECLARE @FALSE bit
SET @TRUE = 1
SET @FALSE = 0

select * from SomeTable where @TRUE = @TRUE

But these will only exist within the scope of the batch (you'll have to redeclare them in every batch in which you want to use them)

Open Google Chrome from VBA/Excel

Worked here too:

Sub test544()

  Dim chromePath As String

  chromePath = """C:\Program Files\Google\Chrome\Application\chrome.exe"""

  Shell (chromePath & " -url http:google.ca")

End Sub

Select 2 columns in one and combine them

Your syntax should work, maybe add a space between the colums like

SELECT something + ' ' + somethingElse as onlyOneColumn FROM someTable

How to Select a substring in Oracle SQL up to a specific character?

Using a combination of SUBSTR, INSTR, and NVL (for strings without an underscore) will return what you want:

SELECT NVL(SUBSTR('ABC_blah', 0, INSTR('ABC_blah', '_')-1), 'ABC_blah') AS output
  FROM DUAL

Result:

output
------
ABC

Use:

SELECT NVL(SUBSTR(t.column, 0, INSTR(t.column, '_')-1), t.column) AS output
  FROM YOUR_TABLE t

Reference:

Addendum

If using Oracle10g+, you can use regex via REGEXP_SUBSTR.

Truncate a SQLite table if it exists?

Just do delete. This is from the SQLite documentation:

The Truncate Optimization

"When the WHERE is omitted from a DELETE statement and the table being deleted has no triggers, SQLite uses an optimization to erase the entire table content without having to visit each row of the table individually. This "truncate" optimization makes the delete run much faster. Prior to SQLite version 3.6.5, the truncate optimization also meant that the sqlite3_changes() and sqlite3_total_changes() interfaces and the count_changes pragma will not actually return the number of deleted rows. That problem has been fixed as of version 3.6.5."

Faster alternative in Oracle to SELECT COUNT(*) FROM sometable

Think about it: the database really has to go to every row to do that. In a multi-user environment my COUNT(*) could be different from your COUNT(*). It would be impractical to have a different counter for each and every session so you have literally to count the rows. Most of the time anyway you would have a WHERE clause or a JOIN in your query so your hypothetical counter would be of litte practical value.

There are ways to speed up things however: if you have an INDEX on a NOT NULL column Oracle will count the rows of the index instead of the table. In a proper relational model all tables have a primary key so the COUNT(*) will use the index of the primary key.

Bitmap index have entries for NULL rows so a COUNT(*) will use a bitmap index if there is one available.

How to drop SQL default constraint without knowing its name?

Drop all default contstraints in a database - safe for nvarchar(max) threshold.

/* WARNING: THE SAMPLE BELOW; DROPS ALL THE DEFAULT CONSTRAINTS IN A DATABASE */ 
/* MAY 03, 2013 - BY WISEROOT  */
declare @table_name nvarchar(128)
declare @column_name nvarchar(128)
declare @df_name nvarchar(128)
declare @cmd nvarchar(128) 

declare table_names cursor for 
 SELECT t.name TableName, c.name ColumnName
 FROM sys.columns c INNER JOIN
     sys.tables t ON c.object_id = t.object_id INNER JOIN
     sys.schemas s ON t.schema_id = s.schema_id
     ORDER BY T.name, c.name

     open table_names
fetch next from table_names into @table_name , @column_name
while @@fetch_status = 0
BEGIN

if exists (SELECT top(1) d.name from sys.tables t join sys.default_constraints d on d.parent_object_id = t.object_id join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id where t.name = @table_name and c.name = @column_name)
BEGIN
    SET @df_name = (SELECT top(1) d.name from sys.tables t join sys.default_constraints d on d.parent_object_id = t.object_id join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id where t.name = @table_name and c.name = @column_name)
    select @cmd = 'ALTER TABLE [' + @table_name +  '] DROP CONSTRAINT [' +  @df_name + ']'
    print @cmd
    EXEC sp_executeSQL @cmd;
END

  fetch next from table_names into @table_name , @column_name
END

close table_names 
deallocate table_names

SQL Bulk Insert with FIRSTROW parameter skips the following line

To let SQL handle quote escape and everything else do this

BULK INSERT Test_CSV
FROM  'C:\MyCSV.csv' 
WITH (
 FORMAT='CSV'
 --FIRSTROW = 2,  --uncomment this if your CSV contains header, so start parsing at line 2
);

In regards to other answers, here is valuable info as well:

I keep seeing this in all answers: ROWTERMINATOR = '\n'
The \n means LF and it is Linux style EOL

In Windows the EOL is made of 2 chars CRLF so you need ROWTERMINATOR = '\r\n'

enter image description here

enter image description here

How to best display in Terminal a MySQL SELECT returning too many fields?

I believe putty has a maximum number of columns you can specify for the window.

For Windows I personally use Windows PowerShell and set the screen buffer width reasonably high. The column width remains fixed and you can use a horizontal scroll bar to see the data. I had the same problem you're having now.

edit: For remote hosts that you have to SSH into you would use something like plink + Windows PowerShell

Passing a varchar full of comma delimited values to a SQL Server IN function

The simplest way i found was to use FIND_IN_SET

FIND_IN_SET(column_name, values)

values=(1,2,3)

SELECT name WHERE FIND_IN_SET(id, values)

How do I limit the number of rows returned by an Oracle query after ordering?

If you are not on Oracle 12C, you can use TOP N query like below.

SELECT *
 FROM
   ( SELECT rownum rnum
          , a.*
       FROM sometable a 
   ORDER BY name
   )
WHERE rnum BETWEEN 10 AND 20;

You can even move this from clause in with clause as follows

WITH b AS
( SELECT rownum rnum
      , a.* 
   FROM sometable a ORDER BY name
) 
SELECT * FROM b 
WHERE rnum BETWEEN 10 AND 20;

Here actually we are creating a inline view and renaming rownum as rnum. You can use rnum in main query as filter criteria.

How to export data as CSV format from SQL Server using sqlcmd?

You can do it in a hackish way. Careful using the sqlcmd hack. If the data has double quotes or commas you will run into trouble.

You can use a simple script to do it properly:

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Data Exporter                                                 '
'                                                               '
' Description: Allows the output of data to CSV file from a SQL '
'       statement to either Oracle, SQL Server, or MySQL        '
' Author: C. Peter Chen, http://dev-notes.com                   '
' Version Tracker:                                              '
'       1.0   20080414 Original version                         '
'   1.1   20080807 Added email functionality                '
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
option explicit
dim dbType, dbHost, dbName, dbUser, dbPass, outputFile, email, subj, body, smtp, smtpPort, sqlstr

'''''''''''''''''
' Configuration '
'''''''''''''''''
dbType = "oracle"                 ' Valid values: "oracle", "sqlserver", "mysql"
dbHost = "dbhost"                 ' Hostname of the database server
dbName = "dbname"                 ' Name of the database/SID
dbUser = "username"               ' Name of the user
dbPass = "password"               ' Password of the above-named user
outputFile = "c:\output.csv"      ' Path and file name of the output CSV file
email = "[email protected]"           ' Enter email here should you wish to email the CSV file (as attachment); if no email, leave it as empty string ""
  subj = "Email Subject"          ' The subject of your email; required only if you send the CSV over email
  body = "Put a message here!"    ' The body of your email; required only if you send the CSV over email
  smtp = "mail.server.com"        ' Name of your SMTP server; required only if you send the CSV over email
  smtpPort = 25                   ' SMTP port used by your server, usually 25; required only if you send the CSV over email
sqlStr = "select user from dual"  ' SQL statement you wish to execute
'''''''''''''''''''''
' End Configuration '
'''''''''''''''''''''



dim fso, conn

'Create filesystem object 
set fso = CreateObject("Scripting.FileSystemObject")

'Database connection info
set Conn = CreateObject("ADODB.connection")
Conn.ConnectionTimeout = 30
Conn.CommandTimeout = 30
if dbType = "oracle" then
    conn.open("Provider=MSDAORA.1;User ID=" & dbUser & ";Password=" & dbPass & ";Data Source=" & dbName & ";Persist Security Info=False")
elseif dbType = "sqlserver" then
    conn.open("Driver={SQL Server};Server=" & dbHost & ";Database=" & dbName & ";Uid=" & dbUser & ";Pwd=" & dbPass & ";")
elseif dbType = "mysql" then
    conn.open("DRIVER={MySQL ODBC 3.51 Driver}; SERVER=" & dbHost & ";PORT=3306;DATABASE=" & dbName & "; UID=" & dbUser & "; PASSWORD=" & dbPass & "; OPTION=3")
end if

' Subprocedure to generate data.  Two parameters:
'   1. fPath=where to create the file
'   2. sqlstr=the database query
sub MakeDataFile(fPath, sqlstr)
    dim a, showList, intcount
    set a = fso.createtextfile(fPath)

    set showList = conn.execute(sqlstr)
    for intcount = 0 to showList.fields.count -1
        if intcount <> showList.fields.count-1 then
            a.write """" & showList.fields(intcount).name & ""","
        else
            a.write """" & showList.fields(intcount).name & """"
        end if
    next
    a.writeline ""

    do while not showList.eof
        for intcount = 0 to showList.fields.count - 1
            if intcount <> showList.fields.count - 1 then
                a.write """" & showList.fields(intcount).value & ""","
            else
                a.write """" & showList.fields(intcount).value & """"
            end if
        next
        a.writeline ""
        showList.movenext
    loop
    showList.close
    set showList = nothing

    set a = nothing
end sub

' Call the subprocedure
call MakeDataFile(outputFile,sqlstr)

' Close
set fso = nothing
conn.close
set conn = nothing

if email <> "" then
    dim objMessage
    Set objMessage = CreateObject("CDO.Message")
    objMessage.Subject = "Test Email from vbs"
    objMessage.From = email
    objMessage.To = email
    objMessage.TextBody = "Please see attached file."
    objMessage.AddAttachment outputFile

    objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
    objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = smtp
    objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = smtpPort

objMessage.Configuration.Fields.Update

    objMessage.Send
end if

'You're all done!!  Enjoy the file created.
msgbox("Data Writer Done!")

Source: Writing SQL output to CSV with VBScript.

SQL Server "AFTER INSERT" trigger doesn't see the just-inserted row

Is it possible the INSERT is valid, but that a separate UPDATE is done afterwards that is invalid but wouldn't fire the trigger?

Get the generated SQL statement from a SqlCommand object?

This is what I use to output parameter lists for a stored procedure into the debug console:

string query = (from SqlParameter p in sqlCmd.Parameters where p != null where p.Value != null select string.Format("Param: {0} = {1},  ", p.ParameterName, p.Value.ToString())).Aggregate(sqlCmd.CommandText, (current, parameter) => current + parameter);
Debug.WriteLine(query);

This will generate a console outputt simlar to this:

Customer.prGetCustomerDetails: @Offset = 1,  Param: @Fetch = 10,  Param: @CategoryLevel1ID = 3,  Param: @VehicleLineID = 9,  Param: @SalesCode1 = bce,  

I place this code directly below any procedure I wish to debug and is similar to a sql profiler session but in C#.

Dynamic SELECT TOP @var In SQL Server

The syntax "select top (@var) ..." only works in SQL SERVER 2005+. For SQL 2000, you can do:

set rowcount @top

select * from sometable

set rowcount 0 

Hope this helps

Oisin.

(edited to replace @@rowcount with rowcount - thanks augustlights)

How to do a SQL NOT NULL with a DateTime?

SELECT * FROM Table where codtable not in (Select codtable from Table where fecha is null)

Possible to perform cross-database queries with PostgreSQL?

I have run into this before an came to the same conclusion about cross database queries as you. What I ended up doing was using schemas to divide the table space that way I could keep the tables grouped but still query them all.

Use of var keyword in C#

var is the way to deal with anonymous types, whether from LINQ statements or not. Any other use is heavily dependent on who will read your code and what guidelines are in place.

If you are the only audience or your audience is comfortable with using var or is very familiar with your code then I guess it doesn't matter. If you use it like: var s = new SqlConnection() then it largely doesnt matter and probably improves code readability. If people aren't too picky and its okay for them to do a little work to know the type when its not apparent (which is not needed in most cases, how you use it in the following statements would usually explain everything) then its alright.

But if you have picky, close-minded teammates who love to whine or if your company's design guidelines specifically forbid using var when the type is not obvious then you will most likely meet heavy opposition.

If using var makes your code insanely difficult to read, you will probably get shot by using var even if its probably your app design that is to blame.

If var introduces ambiguity (sort of like your IEnumerable/IEnumerable example), just don't use it and be explicit. But var does have its conveniences and in some cases, IMHO, even improves readabilty by reducing clutter.

Type or namespace name does not exist

And if all else fails, such as ensuring that the target frameworks are the same, and you are dealing with a WPF class library in VS2010, simply restart Visual Studio. That did it for me.

Forcing anti-aliasing using css: Is this a myth?

I think you got it a bit wrong. Someone in the thread you pasted says that you can stop anti-aliasing by using px instead of pt, not that you can force it by using the latter. I'm a bit sceptical to both of the claims though...

jquery datatables default sort

This worked for me:

       jQuery('#tblPaging').dataTable({
            "sort": true,
            "pageLength": 20
        });

SQL Server: Difference between PARTITION BY and GROUP BY

They're used in different places. group by modifies the entire query, like:

select customerId, count(*) as orderCount
from Orders
group by customerId

But partition by just works on a window function, like row_number:

select row_number() over (partition by customerId order by orderId)
    as OrderNumberForThisCustomer
from Orders

A group by normally reduces the number of rows returned by rolling them up and calculating averages or sums for each row. partition by does not affect the number of rows returned, but it changes how a window function's result is calculated.

Force IE10 to run in IE10 Compatibility View?

I had the exact same problem, this - "meta http-equiv="X-UA-Compatible" content="IE=7">" works great in IE8 and IE9, but not in IE10. There is a bug in the server browser definition files that shipped with .NET 2.0 and .NET 4, namely that they contain definitions for a certain range of browser versions. But the versions for some browsers (like IE 10) aren't within those ranges any more. Therefore, ASP.NET sees them as unknown browsers and defaults to a down-level definition, which has certain inconveniences, like that it does not support features like JavaScript.

My thanks to Scott Hanselman for this fix.

Here is the link -

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

This MS KP fix just adds missing files to the asp.net on your server. I installed it and rebooted my server and it now works perfectly. I would have thought that MS would have given this fix a wider distribution.

Rick

Computational complexity of Fibonacci Sequence

It is bounded on the lower end by 2^(n/2) and on the upper end by 2^n (as noted in other comments). And an interesting fact of that recursive implementation is that it has a tight asymptotic bound of Fib(n) itself. These facts can be summarized:

T(n) = O(2^(n/2))  (lower bound)
T(n) = O(2^n)   (upper bound)
T(n) = T(Fib(n)) (tight bound)

The tight bound can be reduced further using its closed form if you like.

Multiple select statements in Single query

I know this is an old stack but i will post this Multi-SQL select case

    SELECT bp.bizid, bp.usrid, bp.website, 
ROUND((SELECT SUM(rating) FROM ratings WHERE bizid=bp.bizid)/(SELECT COUNT(*) FROM ratings WHERE bizid=bp.bizid), 1) AS 'ratings', 
(SELECT COUNT(*) FROM bzreviews WHERE bizid=bp.bizid) AS 'ttlreviews', 
bp.phoneno, als.bizname, 
(SELECT COUNT(*) FROM endorsment WHERE bizid=bp.bizid) AS 'endorses'
, als.imgname, bp.`location`, bp.`ownership`, 
(SELECT COUNT(*) FROM follows WHERE bizid=bp.bizid) AS 'followers', 
bp.categories, bp.openhours, bp.bizdecri FROM bizprofile AS bp 
INNER JOIN alluser AS als ON bp.usrid=als.userid 
WHERE als.usertype='Business'

How do I restrict an input to only accept numbers?

Using ng-pattern on the text field:

<input type="text"  ng-model="myText" name="inputName" ng-pattern="onlyNumbers">

Then include this on your controller

$scope.onlyNumbers = /^\d+$/;

Run an OLS regression with Pandas Data Frame

Statsmodels kan build an OLS model with column references directly to a pandas dataframe.

Short and sweet:

model = sm.OLS(df[y], df[x]).fit()


Code details and regression summary:

# imports
import pandas as pd
import statsmodels.api as sm
import numpy as np

# data
np.random.seed(123)
df = pd.DataFrame(np.random.randint(0,100,size=(100, 3)), columns=list('ABC'))

# assign dependent and independent / explanatory variables
variables = list(df.columns)
y = 'A'
x = [var for var in variables if var not in y ]

# Ordinary least squares regression
model_Simple = sm.OLS(df[y], df[x]).fit()

# Add a constant term like so:
model = sm.OLS(df[y], sm.add_constant(df[x])).fit()

model.summary()

Output:

                            OLS Regression Results                            
==============================================================================
Dep. Variable:                      A   R-squared:                       0.019
Model:                            OLS   Adj. R-squared:                 -0.001
Method:                 Least Squares   F-statistic:                    0.9409
Date:                Thu, 14 Feb 2019   Prob (F-statistic):              0.394
Time:                        08:35:04   Log-Likelihood:                -484.49
No. Observations:                 100   AIC:                             975.0
Df Residuals:                      97   BIC:                             982.8
Df Model:                           2                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const         43.4801      8.809      4.936      0.000      25.996      60.964
B              0.1241      0.105      1.188      0.238      -0.083       0.332
C             -0.0752      0.110     -0.681      0.497      -0.294       0.144
==============================================================================
Omnibus:                       50.990   Durbin-Watson:                   2.013
Prob(Omnibus):                  0.000   Jarque-Bera (JB):                6.905
Skew:                           0.032   Prob(JB):                       0.0317
Kurtosis:                       1.714   Cond. No.                         231.
==============================================================================

How to directly get R-squared, Coefficients and p-value:

# commands:
model.params
model.pvalues
model.rsquared

# demo:
In[1]: 
model.params
Out[1]:
const    43.480106
B         0.124130
C        -0.075156
dtype: float64

In[2]: 
model.pvalues
Out[2]: 
const    0.000003
B        0.237924
C        0.497400
dtype: float64

Out[3]:
model.rsquared
Out[2]:
0.0190

org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class

i recently experienced this issue when i was trying to build and suddenly the laptop battery ran out of charge. I just removed all the servers from eclipse and then restore it. after doing that, i re-built the war file and it worked.

Android check null or empty string in Android

All you can do is to call equals() method on empty String literal and pass the object you are testing as shown below :

 String nullString = null;
 String empty = new String();
 boolean test = "".equals(empty); // true 
 System.out.println(test); 
 boolean check = "".equals(nullString); // false 
 System.out.println(check);

XCOPY: Overwrite all without prompt in BATCH

The solution is the /Y switch:

xcopy "C:\Users\ADMIN\Desktop\*.*" "D:\Backup\" /K /D /H /Y

How can I prevent the textarea from stretching beyond his parent DIV element? (google-chrome issue only)

I'm hoping you are having the same problem that I had... my issue was simple: Make a fixed textarea with locked percentages inside the container (I'm new to CSS/JS/HTML, so bear with me, if I don't get the lingo correct) so that no matter the device it's displaying on, the box filling the container (the table cell) takes up the correct amount of space. Here's how I solved it:

<table width=100%>
    <tr class="idbbs">
        B.S.:
    </tr></br>
    <tr>
        <textarea id="bsinpt"></textarea>
    </tr>
</table>

Then CSS Looks like this...

#bsinpt
{
    color: gainsboro;
    float: none;
    background: black;
    text-align: left;
    font-family: "Helvetica", "Tahoma", "Verdana", "Arial Black", sans-serif;
    font-size: 100%;
  position: absolute;
  min-height: 60%;
  min-width: 88%;
  max-height: 60%;
  max-width: 88%;
  resize: none;
    border-top-color: lightsteelblue;
    border-top-width: 1px;
    border-left-color: lightsteelblue;
    border-left-width: 1px;
    border-right-color: lightsteelblue;
    border-right-width: 1px;
    border-bottom-color: lightsteelblue;
    border-bottom-width: 1px;
}

Sorry for the sloppy code block here, but I had to show you what's important and I don't know how to insert quoted CSS code on this website. In any case, to ensure you see what I'm talking about, the important CSS is less indented here...

What I then did (as shown here) is very specifically tweak the percentages until I found the ones that worked perfectly to fit display, no matter what device screen is used.

Granted, I think the "resize: none;" is overkill, but better safe than sorry and now the consumers will not have anyway to resize the box, nor will it matter what device they are viewing it from.

It works great.

Quickly reading very large tables as dataframes

Instead of the conventional read.table I feel fread is a faster function. Specifying additional attributes like select only the required columns, specifying colclasses and string as factors will reduce the time take to import the file.

data_frame <- fread("filename.csv",sep=",",header=FALSE,stringsAsFactors=FALSE,select=c(1,4,5,6,7),colClasses=c("as.numeric","as.character","as.numeric","as.Date","as.Factor"))

How do you fade in/out a background color using jquery?

javascript fade to white without jQuery or other library:

<div id="x" style="background-color:rgb(255,255,105)">hello world</div>
<script type="text/javascript">
var gEvent=setInterval("toWhite();", 100);
function toWhite(){
    var obj=document.getElementById("x");
    var unBlue=10+parseInt(obj.style.backgroundColor.split(",")[2].replace(/\D/g,""));
    if(unBlue>245) unBlue=255;
    if(unBlue<256) obj.style.backgroundColor="rgb(255,255,"+unBlue+")";
    else clearInterval(gEvent)
}
</script>

In printing, yellow is minus blue, so starting with the 3rd rgb element (blue) at less than 255 starts out with a yellow highlight. Then the 10+ in setting the var unBlue value increments the minus blue until it reaches 255.

React-Router open Link in new tab

this works fine for me

<Link to={`link`} target="_blank">View</Link>

How do I create test and train samples from one dataframe with pandas?

If your wish is to have one dataframe in and two dataframes out (not numpy arrays), this should do the trick:

def split_data(df, train_perc = 0.8):

   df['train'] = np.random.rand(len(df)) < train_perc

   train = df[df.train == 1]

   test = df[df.train == 0]

   split_data ={'train': train, 'test': test}

   return split_data

Difference between socket and websocket?

You'd have to use WebSockets (or some similar protocol module e.g. as supported by the Flash plugin) because a normal browser application simply can't open a pure TCP socket.

The Socket.IO module available for node.js can help a lot, but note that it is not a pure WebSocket module in its own right.

It's actually a more generic communications module that can run on top of various other network protocols, including WebSockets, and Flash sockets.

Hence if you want to use Socket.IO on the server end you must also use their client code and objects. You can't easily make raw WebSocket connections to a socket.io server as you'd have to emulate their message protocol.

How to make promises work in IE11

If you want this type of code to run in IE11 (which does not support much of ES6 at all), then you need to get a 3rd party promise library (like Bluebird), include that library and change your coding to use ES5 coding structures (no arrow functions, no let, etc...) so you can live within the limits of what older browsers support.

Or, you can use a transpiler (like Babel) to convert your ES6 code to ES5 code that will work in older browsers.

Here's a version of your code written in ES5 syntax with the Bluebird promise library:

<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script>

<script>

'use strict';

var promise = new Promise(function(resolve) {
    setTimeout(function() {
        resolve("result");
    }, 1000);
});

promise.then(function(result) {
    alert("Fulfilled: " + result);
}, function(error) {
    alert("Rejected: " + error);
});

</script>

Get index of clicked element in collection with jQuery

Siblings

$(this).index() can be used to get the index of the clicked element if the elements are siblings.

<div id="container">
    <a href="#" class="link">1</a>
    <a href="#" class="link">2</a>
    <a href="#" class="link">3</a>
    <a href="#" class="link">4</a>
</div>

_x000D_
_x000D_
$('#container').on('click', 'a', function() {
  console.log($(this).index());
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="container">
  <a href="#" class="link">1</a>
  <a href="#" class="link">2</a>
  <a href="#" class="link">3</a>
  <a href="#" class="link">4</a>
</div>
_x000D_
_x000D_
_x000D_


Not siblings

If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.

Pass the selector to the index(selector).

$(this).index(selector);

Example:

Find the index of the <a> element that is clicked.

<tr>
    <td><a href="#" class="adwa">0001</a></td>
</tr>
<tr>
    <td><a href="#" class="adwa">0002</a></td>
</tr>
<tr>
    <td><a href="#" class="adwa">0003</a></td>
</tr>
<tr>
    <td><a href="#" class="adwa">0004</a></td>
</tr>

Fiddle

_x000D_
_x000D_
$('#table').on('click', '.adwa', function() {
    console.log($(this).index(".adwa"));
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table id="table">
    <thead>
        <tr>
            <th>vendor id</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><a href="#" class="adwa">0001</a></td>
        </tr>
        <tr>
            <td><a href="#" class="adwa">0002</a></td>
        </tr>
        <tr>
            <td><a href="#" class="adwa">0003</a></td>
        </tr>
        <tr>
            <td><a href="#" class="adwa">0004</a></td>
        </tr>
    </tbody>
</table>
_x000D_
_x000D_
_x000D_

Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

In my case, this was caused by custom manifest entries added by the maven-jar-plugin.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.6</version>
    <configuration>
        <archive>
            <index>true</index>
            <manifest>
                <addClasspath>true</addClasspath>
            </manifest>
            <manifestEntries>
                <git>${buildNumber}</git>
                <build-time>${timestamp}</build-time>
            </manifestEntries>
        </archive>
    </configuration>
</plugin>

Removing the following entries fixed the problem

<index>true</index>
<manifest>
    <addClasspath>true</addClasspath>
</manifest>

Use of the MANIFEST.MF file in Java

Manifest.MF contains information about the files contained in the JAR file.

Whenever a JAR file is created a default manifest.mf file is created inside META-INF folder and it contains the default entries like this:

Manifest-Version: 1.0
Created-By: 1.7.0_06 (Oracle Corporation)

These are entries as “header:value” pairs. The first one specifies the manifest version and second one specifies the JDK version with which the JAR file is created.

Main-Class header: When a JAR file is used to bundle an application in a package, we need to specify the class serving an entry point of the application. We provide this information using ‘Main-Class’ header of the manifest file,

Main-Class: {fully qualified classname}

The ‘Main-Class’ value here is the class having main method. After specifying this entry we can execute the JAR file to run the application.

Class-Path header: Most of the times we need to access the other JAR files from the classes packaged inside application’s JAR file. This can be done by providing their fully qualified paths in the manifest file using ‘Class-Path’ header,

Class-Path: {jar1-name jar2-name directory-name/jar3-name}

This header can be used to specify the external JAR files on the same local network and not inside the current JAR.

Package version related headers: When the JAR file is used for package versioning the following headers are used as specified by the Java language specification:

Headers in a manifest
Header                  | Definition
-------------------------------------------------------------------
Name                    | The name of the specification.
Specification-Title     | The title of the specification.
Specification-Version   | The version of the specification.
Specification-Vendor    | The vendor of the specification.
Implementation-Title    | The title of the implementation.
Implementation-Version  | The build number of the implementation.
Implementation-Vendor   | The vendor of the implementation.

Package sealing related headers:

We can also specify if any particular packages inside a JAR file should be sealed meaning all the classes defined in that package must be archived in the same JAR file. This can be specified with the help of ‘Sealed’ header,

Name: {package/some-package/} Sealed:true

Here, the package name must end with ‘/’.

Enhancing security with manifest files:

We can use manifest files entries to ensure the security of the web application or applet it packages with the different attributes as ‘Permissions’, ‘Codebae’, ‘Application-Name’, ‘Trusted-Only’ and many more.

META-INF folder:

This folder is where the manifest file resides. Also, it can contain more files containing meta data about the application. For example, in an EJB module JAR file, this folder contains the EJB deployment descriptor for the EJB module along with the manifest file for the JAR. Also, it contains the xml file containing mapping of an abstract EJB references to concrete container resources of the application server on which it will be run.

Reference:
https://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html

Hook up Raspberry Pi via Ethernet to laptop without router?

Yes, you can connect the raspberry direct to your PC without router. For this is necessary that the raspberry and your computer are on the same subnet, and they both have a static ip configured (And an Ethernet cable connected between the two devices).

An ideal configuration would be the following:

Raspberry on eth0: IP: 192.168.1.10 SubNet: 255.255.255.0

Your PC: IP: 192.168.1.11 SubNet 255.255.255.0

To set a manual IP on raspberry you can follow this guide

In your PC you can set a manual IP in the network adapter settings,and the procedure depends on your operating system.

When you have configured the two static IP, you can connect to the raspberry via SSH using the IP set (192.168.1.10).

Another simpler method is to attach on GPIO a button to turn off the raspberry! Take a look here!

java.io.StreamCorruptedException: invalid stream header: 54657374

Clearly you aren't sending the data with ObjectOutputStream: you are just writing the bytes.

  • If you read with readObject() you must write with writeObject().
  • If you read with readUTF() you must write with writeUTF().
  • If you read with readXXX() you must write with writeXXX(), for most values of XXX.

Get current url in Angular

With pure JavaScript:

console.log(window.location.href)

Using Angular:

this.router.url

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
    template: 'The href is: {{href}}'
    /*
    Other component settings
    */
})
export class Component {
    public href: string = "";

    constructor(private router: Router) {}

    ngOnInit() {
        this.href = this.router.url;
        console.log(this.router.url);
    }
}

The plunkr is here: https://plnkr.co/edit/0x3pCOKwFjAGRxC4hZMy?p=preview

Java - Best way to print 2D array?

With Java 8 using Streams and ForEach:

    Arrays.stream(array).forEach((i) -> {
        Arrays.stream(i).forEach((j) -> System.out.print(j + " "));
        System.out.println();
    });

The first forEach acts as outer loop while the next as inner loop

Getting DOM element value using pure JavaScript

The second function should have:

var value = document.getElementById(id).value;

Then they are basically the same function.

FPDF error: Some data has already been output, can't send PDF

For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:

<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

While this will not (note the leading space before the opening <? tag)

 <?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

Also, this will not work either (the echo will break it):

<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.


add ob_start (); at the top and at the end add ob_end_flush();

<?php
    ob_start();
    require('fpdf.php');
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(40,10,'Hello World!');
    $pdf->Output();
    ob_end_flush(); 
?>

give me an error as below:
FPDF error: Some data has already been output, can't send PDF

to over come this error: go to fpdf.php in that,goto line number 996

function Output($name='', $dest='')

after that make changes like this:

function Output($name='', $dest='') {   
    ob_clean();     //Output PDF to so

Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.

<?

while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);

?>

cheers :-)


In my case i had set:

ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);

When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off the display_errors option, the report was generated successfully.

How to delete a workspace in Eclipse?

Click on the menu Window > Preferences and go to Workspaces like below :

| General
    | Startup and Shutdown
        | Workspaces

Select the workspace to delete and click on the Remove button.

Vertically align text to top within a UILabel

I wanted to have a label which was able to have multi-lines, a minimum font size, and centred both horizontally and vertically in it's parent view. I added my label programmatically to my view:

- (void) customInit {
    // Setup label
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    self.label.numberOfLines = 0;
    self.label.lineBreakMode = UILineBreakModeWordWrap;
    self.label.textAlignment = UITextAlignmentCenter;

    // Add the label as a subview
    self.autoresizesSubviews = YES;
    [self addSubview:self.label];
}

And then when I wanted to change the text of my label...

- (void) updateDisplay:(NSString *)text {
    if (![text isEqualToString:self.label.text]) {
        // Calculate the font size to use (save to label's font)
        CGSize textConstrainedSize = CGSizeMake(self.frame.size.width, INT_MAX);
        self.label.font = [UIFont systemFontOfSize:TICKER_FONT_SIZE];
        CGSize textSize = [text sizeWithFont:self.label.font constrainedToSize:textConstrainedSize];
        while (textSize.height > self.frame.size.height && self.label.font.pointSize > TICKER_MINIMUM_FONT_SIZE) {
            self.label.font = [UIFont systemFontOfSize:self.label.font.pointSize-1];
            textSize = [ticker.blurb sizeWithFont:self.label.font constrainedToSize:textConstrainedSize];
        }
        // In cases where the frame is still too large (when we're exceeding minimum font size),
        // use the views size
        if (textSize.height > self.frame.size.height) {
            textSize = [text sizeWithFont:self.label.font constrainedToSize:self.frame.size];
        }

        // Draw 
        self.label.frame = CGRectMake(0, self.frame.size.height/2 - textSize.height/2, self.frame.size.width, textSize.height);
        self.label.text = text;
    }
    [self setNeedsDisplay];
}

Hope that helps someone!

How to list installed packages from a given repo using yum

Try

yum list installed | grep reponame

On one of my servers:

yum list installed | grep remi
ImageMagick2.x86_64                       6.6.5.10-1.el5.remi          installed
memcache.x86_64                          1.4.5-2.el5.remi             installed
mysql.x86_64                              5.1.54-1.el5.remi            installed
mysql-devel.x86_64                        5.1.54-1.el5.remi            installed
mysql-libs.x86_64                         5.1.54-1.el5.remi            installed
mysql-server.x86_64                       5.1.54-1.el5.remi            installed
mysqlclient15.x86_64                      5.0.67-1.el5.remi            installed
php.x86_64                                5.3.5-1.el5.remi             installed
php-cli.x86_64                            5.3.5-1.el5.remi             installed
php-common.x86_64                         5.3.5-1.el5.remi             installed
php-domxml-php4-php5.noarch               1.21.2-1.el5.remi            installed
php-fpm.x86_64                            5.3.5-1.el5.remi             installed
php-gd.x86_64                             5.3.5-1.el5.remi             installed
php-mbstring.x86_64                       5.3.5-1.el5.remi             installed
php-mcrypt.x86_64                         5.3.5-1.el5.remi             installed
php-mysql.x86_64                          5.3.5-1.el5.remi             installed
php-pdo.x86_64                            5.3.5-1.el5.remi             installed
php-pear.noarch                           1:1.9.1-6.el5.remi           installed
php-pecl-apc.x86_64                       3.1.6-1.el5.remi             installed
php-pecl-imagick.x86_64                   3.0.1-1.el5.remi.1           installed
php-pecl-memcache.x86_64                  3.0.5-1.el5.remi             installed
php-pecl-xdebug.x86_64                    2.1.0-1.el5.remi             installed
php-soap.x86_64                           5.3.5-1.el5.remi             installed
php-xml.x86_64                            5.3.5-1.el5.remi             installed
remi-release.noarch                       5-8.el5.remi                 installed

It works.

Sending intent to BroadcastReceiver from adb

I had the same problem and found out that you have to escape spaces in the extra:

adb shell am broadcast -a com.whereismywifeserver.intent.TEST --es sms_body "test\ from\ adb"

So instead of "test from adb" it should be "test\ from\ adb"

Passing arguments to angularjs filters

You can pass multiple arguments to angular filter !

Defining my angular app and and an app level variable -

var app = angular.module('filterApp',[]);
app.value('test_obj', {'TEST' : 'test be check se'});

Your Filter will be like :-

app.filter('testFilter', [ 'test_obj', function(test_obj) {
    function test_filter_function(key, dynamic_data) {
      if(dynamic_data){
        var temp = test_obj[key]; 
        for(var property in dynamic_data){
            temp = temp.replace(property, dynamic_data[property]);
        }
        return temp;
      }
      else{
        return test_obj[key] || key;
      }

    }
    test_filter_function.$stateful = true;
    return test_filter_function;
  }]);

And from HTML you will send data like :-

<span ng-bind="'TEST' | testFilter: { 'be': val, 'se': value2 }"></span>

Here I am sending a JSON object to the filter. You can also send any kind of data like string or number.

also you can pass dynamic number of arguments to filter , in that case you have to use arguments to get those arguments.

For a working demo go here - passing multiple arguments to angular filter

Running script upon login mac

  1. Create your shell script as login.sh in your $HOME folder.

  2. Paste the following one-line script into Script Editor:

    do shell script "$HOME/login.sh"

  3. Then save it as an application.

  4. Finally add the application to your login items.

If you want to make the script output visual, you can swap step 2 for this:

tell application "Terminal"
  activate
  do script "$HOME/login.sh"
end tell

If multiple commands are needed something like this can be used:

tell application "Terminal"
  activate
  do script "cd $HOME"
  do script "./login.sh" in window 1
end tell

How do I create a file at a specific path?

The besty practice is to use '/' and a so called 'raw string' to define file path in Python.

path = r"C:/Test.py"

However, a normal program may not have the permission to write in the C: drive root directory. You may need to allow your program to do so, or choose something more reasonable since you probably not need to do so.

How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?

This suggestion is based on pixel manipulation in canvas 2d context.

From MDN:

You can directly manipulate pixel data in canvases at the byte level

To manipulate pixels we'll use two functions here - getImageData and putImageData.

getImageData usage:

var myImageData = context.getImageData(left, top, width, height);

The putImageData syntax:

context.putImageData(myImageData, x, y); 

Where context is your canvas 2d context, and x and y are the position on the canvas.

So to get red green blue and alpha values, we'll do the following:

var r = imageData.data[((x*(imageData.width*4)) + (y*4))];
var g = imageData.data[((x*(imageData.width*4)) + (y*4)) + 1];
var b = imageData.data[((x*(imageData.width*4)) + (y*4)) + 2];
var a = imageData.data[((x*(imageData.width*4)) + (y*4)) + 3];

Where x is the horizontal offset, y is the vertical offset.

The code making image half-transparent:

var canvas = document.getElementById('myCanvas');
var c = canvas.getContext('2d');
var img = new Image();
img.onload  = function() {
   c.drawImage(img, 0, 0);
   var ImageData = c.getImageData(0,0,img.width,img.height);
   for(var i=0;i<img.height;i++)
      for(var j=0;j<img.width;j++)
         ImageData.data[((i*(img.width*4)) + (j*4) + 3)] = 127;//opacity = 0.5 [0-255]
   c.putImageData(ImageData,0,0);//put image data back
}
img.src = 'image.jpg';

You can make you own "shaders" - see full MDN article here

Bootstrap change carousel height

like Answers above, if you do bootstrap 4 just add few line of css to .carousel , carousel-inner ,carousel-item and img as follows

.carousel .carousel-inner{
height:500px
}
.carousel-inner .carousel-item img{
min-height:200px;
//prevent it from stretch in screen size < than 768px
object-fit:cover
}

@media(max-width:768px){
.carousel .carousel-inner{
//prevent it from adding a white space between carousel and container elements
height:auto
 }
}

Syntax error on print with Python 3

Because in Python 3, print statement has been replaced with a print() function, with keyword arguments to replace most of the special syntax of the old print statement. So you have to write it as

print("Hello World")

But if you write this in a program and someone using Python 2.x tries to run it, they will get an error. To avoid this, it is a good practice to import print function:

from __future__ import print_function

Now your code works on both 2.x & 3.x.

Check out below examples also to get familiar with print() function.

Old: print "The answer is", 2*2
New: print("The answer is", 2*2)

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

Old: print              # Prints a newline
New: print()            # You must call the function!

Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

Old: print (x, y)       # prints repr((x, y))
New: print((x, y))      # Not the same as print(x, y)!

Source: What’s New In Python 3.0?

Error C1083: Cannot open include file: 'stdafx.h'

Add #include "afxwin.h" in your source file. It will solve your issue.

Trying to git pull with error: cannot open .git/FETCH_HEAD: Permission denied

for MacOS user (if High Sierra or higher version) use this:

sudo chown -R $(whoami) $(brew --prefix)/*

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

enter image description here

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2)

enter image description here

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) + 
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

enter image description here

add/remove active class for ul list with jquery?

this will point to the <ul> selected by .nav-list. You can use delegation instead!

$('.nav-list').on('click', 'li', function() {
    $('.nav-list li.active').removeClass('active');
    $(this).addClass('active');
});

java calling a method from another class

You have to initialise the object (create the object itself) in order to be able to call its methods otherwise you would get a NullPointerException.

WordList words = new WordList();

How to temporarily exit Vim and go back

Just put in fg and go back to your most recently suspended program.

Change the image source on rollover using jQuery

I was hoping for an über one liner like:

$("img.screenshot").attr("src", $(this).replace("foo", "bar"));

Capturing console output from a .NET application (C#)

This can be quite easily achieved using the ProcessStartInfo.RedirectStandardOutput property. A full sample is contained in the linked MSDN documentation; the only caveat is that you may have to redirect the standard error stream as well to see all output of your application.

Process compiler = new Process();
compiler.StartInfo.FileName = "csc.exe";
compiler.StartInfo.Arguments = "/r:System.dll /out:sample.exe stdstr.cs";
compiler.StartInfo.UseShellExecute = false;
compiler.StartInfo.RedirectStandardOutput = true;
compiler.Start();    

Console.WriteLine(compiler.StandardOutput.ReadToEnd());

compiler.WaitForExit();

Creating the checkbox dynamically using JavaScript?

You're trying to put a text node inside an input element.

Input elements are empty and can't have children.

...
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
checkbox.id = "id";

var label = document.createElement('label')
label.htmlFor = "id";
label.appendChild(document.createTextNode('text for label after checkbox'));

container.appendChild(checkbox);
container.appendChild(label);

JavaScript for...in vs for

I have seen problems with the "for each" using objects and prototype and arrays

my understanding is that the for each is for properties of objects and NOT arrays

How to get package name from anywhere?

Use: BuildConfig.APPLICATION_ID to get PACKAGE NAME anywhere( ie; services, receiver, activity, fragment, etc )

Example: String PackageName = BuildConfig.APPLICATION_ID;

Correct set of dependencies for using Jackson mapper

No, you can simply use com.fasterxml.jackson.databind.ObjectMapper. Most likely you forgot to fix your import-statements, delete all references to codehaus and you're golden.

How to concatenate strings of a string field in a PostgreSQL 'group by' query?

I'm using Jetbrains Rider and it was a hassle copying the results from above examples to re-execute because it seemed to wrap it all in JSON. This joins them into a single statement that was easier to run

select string_agg('drop table if exists "' || tablename || '" cascade', ';') 
from pg_tables where schemaname != $$pg_catalog$$ and tableName like $$rm_%$$

Use string value from a cell to access worksheet of same name

Guess @user3010492 tested it but I used this with fixed cell A5 --> $A$5 and fixed element of G7 --> $G7

=INDIRECT("'"&$A$5&"'!$G7")

Also works nested nicely in other formula if you enclose it in brackets.

Does Python's time.time() return the local or UTC timestamp?

The time.time() function returns the number of seconds since the epoch, as seconds. Note that the "epoch" is defined as the start of January 1st, 1970 in UTC. So the epoch is defined in terms of UTC and establishes a global moment in time. No matter where you are "seconds past epoch" (time.time()) returns the same value at the same moment.

Here is some sample output I ran on my computer, converting it to a string as well.

Python 2.7.3 (default, Apr 24 2012, 00:00:54) 
[GCC 4.7.0 20120414 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> ts = time.time()
>>> print ts
1355563265.81
>>> import datetime
>>> st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
>>> print st
2012-12-15 01:21:05
>>>

The ts variable is the time returned in seconds. I then converted it to a string using the datetime library making it a string that is human readable.

Reset git proxy to default configuration

For me, I had to add:

git config --global --unset http.proxy

Basically, you can run:

git config --global -l 

to get the list of all proxy defined, and then use "--unset" to disable them

Adding multiple class using ng-class

Below active and activemenu are classes and itemCount and ShowCart is expression/boolean values.

ng-class="{'active' : itemCount, 'activemenu' : showCart}"

What is the largest possible heap size with a 64-bit JVM?

The answer clearly depends on the JVM implementation. Azul claim that their JVM

can scale ... to more than a 1/2 Terabyte of memory

By "can scale" they appear to mean "runs wells", as opposed to "runs at all".

frequent issues arising in android view, Error parsing XML: unbound prefix

As you mention, you need to specify the right namespace. You also see this error with an incorrect namespace.

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns="http://schemas.android.com/apk/res/android"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"
         android:padding="10dip">

will not work.

Change:

xmlns="http://schemas.android.com/apk/res/android"

to

xmlns:android="http://schemas.android.com/apk/res/android"

The error message is referring to everything that starts "android:" as the XML does not know what the "android:" namespace is.

xmlns:android defines it.

How to prevent buttons from submitting forms

The following sample code show you how to prevent button click from submitting form.

You may try my sample code:

 <form autocomplete="off" method="post" action="">
   <p>Title:
     <input type="text" />
   </p>
   <input type="button" onclick="addItem()" value="Add Item">
   <input type="button" onclick="removeItem()" value="Remove Last Item">
   <table>
     <th>Name</th>

     <tr>
       <td>
         <input type="text" id="input1" name="input1" />
       </td>
       <td>
         <input type="hidden" id="input2" name="input2" />
       </td>
     </tr>
   </table>
   <input id="submit" type="submit" name="submit" value="Submit">
 </form>
<script language="javascript">
function addItem() {
return false;
}

function removeItem() {
return false;
}
</script>

TypeError: $(...).on is not a function

If you are using old version of jQuery(< 1.7) then you can use "bind" instead of "on". This will only work in case you are using old version, since as of jQuery 3.0, "bind" has been deprecated.

How to show another window from mainwindow in QT

  1. Implement a slot in your QMainWindow where you will open your new Window,
  2. Place a widget on your QMainWindow,
  3. Connect a signal from this widget to a slot from the QMainWindow (for example: if the widget is a QPushButton connect the signal click() to the QMainWindow custom slot you have created).

Code example:

MainWindow.h

// ...
include "newwindow.h"
// ...
public slots:
   void openNewWindow();
// ...
private:
   NewWindow *mMyNewWindow;
// ...
}

MainWindow.cpp

// ...
   MainWindow::MainWindow()
   {
      // ...
      connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
      // ...
   }
// ...
void MainWindow::openNewWindow()
{
   mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
   mMyNewWindow->show();
   // ...
}

This is an example on how display a custom new window. There are a lot of ways to do this.

jQuery change input text value

Best practice is using the identify directly:

$('#id').val('xxx');

Given a starting and ending indices, how can I copy part of a string in C?

Have you checked strncpy?

char * strncpy ( char * destination, const char * source, size_t num );

You must realize that begin and end actually defines a num of bytes to be copied from one place to another.

Convert String to Uri

If you are using Kotlin and Kotlin android extensions, then there is a beautiful way of doing this.

val uri = myUriString.toUri()

To add Kotlin extensions (KTX) to your project add the following to your app module's build.gradle

  repositories {
    google()
}

dependencies {
    implementation 'androidx.core:core-ktx:1.0.0-rc01'
}

How to read/process command line arguments?

My solution is entrypoint2. Example:

from entrypoint2 import entrypoint
@entrypoint
def add(file, quiet=True): 
    ''' This function writes report.

    :param file: write report to FILE
    :param quiet: don't print status messages to stdout
    '''
    print file,quiet

help text:

usage: report.py [-h] [-q] [--debug] file

This function writes report.

positional arguments:
  file         write report to FILE

optional arguments:
  -h, --help   show this help message and exit
  -q, --quiet  don't print status messages to stdout
  --debug      set logging level to DEBUG

SQL Server equivalent of MySQL's NOW()?

SYSDATETIME() and SYSUTCDATETIME()

are the DateTime2 equivalents of

GetDate() and GetUTCDate()

which return a DateTime.

DateTime2 is now the preferred method for storing the date and time in SQL Server 2008+. See the following StackOverflow Post.

if arguments is equal to this string, define a variable like this string

You can use either "=" or "==" operators for string comparison in bash. The important factor is the spacing within the brackets. The proper method is for brackets to contain spacing within, and operators to contain spacing around. In some instances different combinations work; however, the following is intended to be a universal example.

if [ "$1" == "something" ]; then     ## GOOD

if [ "$1" = "something" ]; then      ## GOOD

if [ "$1"="something" ]; then        ## BAD (operator spacing)

if ["$1" == "something"]; then       ## BAD (bracket spacing)

Also, note double brackets are handled slightly differently compared to single brackets ...

if [[ $a == z* ]]; then   # True if $a starts with a "z" (pattern matching).
if [[ $a == "z*" ]]; then # True if $a is equal to z* (literal matching).

if [ $a == z* ]; then     # File globbing and word splitting take place.
if [ "$a" == "z*" ]; then # True if $a is equal to z* (literal matching).

I hope that helps!

There is no argument given that corresponds to the required formal parameter - .NET Error

I received this same error in the following Linq statement regarding DailyReport. The problem was that DailyReport had no default constructor. Apparently, it instantiates the object before populating the properties.

var sums = reports
    .GroupBy(r => r.CountryRegion)
    .Select(cr => new DailyReport
    {
        CountryRegion = cr.Key,
        ProvinceState = "All",
        RecordDate = cr.First().RecordDate,
        Confirmed = cr.Sum(c => c.Confirmed),
        Recovered = cr.Sum(c => c.Recovered),
        Deaths = cr.Sum(c => c.Deaths)
    });

Why plt.imshow() doesn't display the image?

The solution was as simple as adding plt.show() at the end of the code snippet:

import numpy as np
np.random.seed(123)
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras.datasets import mnist
(X_train,y_train),(X_test,y_test) = mnist.load_data()
print X_train.shape
from matplotlib import pyplot as plt
plt.imshow(X_train[0])
plt.show()

Create an array of integers property in Objective-C

You can put this in your .h file for your class and define it as property, in XCode 7:

@property int  (*stuffILike) [10];

Dependency Walker reports IESHIMS.DLL and WER.DLL missing?

I had this issue recently and I resolved it by simply rolling IE8 back to IE7.

My guess is that IE7 had these files as a wrapper for working on Windows XP, but IE8 was likely made to work with Vista/7 so it removed the files because the later editions just don't use the shim.

SQL Server: How to check if CLR is enabled?

SELECT * FROM sys.configurations
WHERE name = 'clr enabled'

Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0

open app/build.gradle from your app-module and rewrite below line after dependencies block. This allows the plugin to determine what version of Play services you are using

apply plugin: 'com.google.gms.google-services'

I got this idea from here. In this tutorial second point is saying that above plugin line be at the bottom of your app/build.gradle file so that no dependency collisions are introduced. Hope it will help you out.

How to synchronize a static variable among threads running different instances of a class in Java?

If you're simply sharing a counter, consider using an AtomicInteger or another suitable class from the java.util.concurrent.atomic package:

public class Test {

    private final static AtomicInteger count = new AtomicInteger(0); 

    public void foo() {  
        count.incrementAndGet();
    }  
}

How do I get information about an index and table owner in Oracle?

Below are two simple query using which you can check index created on a table in Oracle.

select index_name
  from dba_indexes
 where table_name='&TABLE_NAME'
   and owner='&TABLE_OWNER';
select index_name 
  from user_indexes 
 where table_name='&TABLE_NAME';

Please check for more details and index size below. Index on a table and its size in Oracle

How to set Spring profile from system variable?

You can set the spring profile by supplying -Dspring.profiles.active=<env>

For java files in source(src) directory, you can use by System.getProperty("spring.profiles.active")

For java files in test directory you can supply

  • SPRING_PROFILES_ACTIVE to <env>

OR

Since, "environment", "jvmArgs" and "systemProperties" are ignored for the "test" task. In root build.gradle add a task to set jvm property and environment variable.

test {
    def profile = System.properties["spring.profiles.active"]
    systemProperty "spring.profiles.active",profile
    environment "SPRING.PROFILES_ACTIVE", profile
    println "Running ${project} tests with profile: ${profile}"
}

Compare two files line by line and generate the difference in another file

If you need to solve this with coreutils the accepted answer is good:

comm -23 <(sort file1) <(sort file2) > file3

You can also use sd (stream diff), which doesn't require sorting nor process substitution and supports infinite streams, like so:

cat file1 | sd 'cat file2' > file3

Probably not that much of a benefit on this example, but still consider it; in some cases you won't be able to use comm nor grep -F nor diff.

Here's a blogpost I wrote about diffing streams on the terminal, which introduces sd.

Difference between static and shared libraries?

The most significant advantage of shared libraries is that there is only one copy of code loaded in memory, no matter how many processes are using the library. For static libraries each process gets its own copy of the code. This can lead to significant memory wastage.

OTOH, a advantage of static libraries is that everything is bundled into your application. So you don't have to worry that the client will have the right library (and version) available on their system.

How to return rows from left table not found in right table?

I also like to use NOT EXISTS. When it comes to performance if index correctly it should perform the same as a LEFT JOIN or better. Plus its easier to read.

SELECT Column1
FROM TableA a
WHERE NOT EXISTS ( SELECT Column1
                   FROM Tableb b
                   WHERE a.Column1 = b.Column1
                 )

Add borders to cells in POI generated Excel File

Setting up borders in the style used in the cells will accomplish this. Example:

style.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);

how to make a new line in a jupyter markdown cell

The double space generally works well. However, sometimes the lacking newline in the PDF still occurs to me when using four pound sign sub titles #### in Jupyter Notebook, as the next paragraph is put into the subtitle as a single paragraph. No amount of double spaces and returns fixed this, until I created a notebook copy 'v. PDF' and started using a single backslash '\' which also indents the next paragraph nicely:

#### 1.1 My Subtitle  \

1.1 My Subtitle
    Next paragraph text.

An alternative to this, is to upgrade the level of your four # titles to three # titles, etc. up the title chain, which will remove the next paragraph indent and format the indent of the title itself (#### My Subtitle ---> ### My Subtitle).

### My Subtitle


1.1 My Subtitle

Next paragraph text.

Proper way to declare custom exceptions in modern Python?

Maybe I missed the question, but why not:

class MyException(Exception):
    pass

Edit: to override something (or pass extra args), do this:

class ValidationError(Exception):
    def __init__(self, message, errors):

        # Call the base class constructor with the parameters it needs
        super(ValidationError, self).__init__(message)

        # Now for your custom code...
        self.errors = errors

That way you could pass dict of error messages to the second param, and get to it later with e.errors


Python 3 Update: In Python 3+, you can use this slightly more compact use of super():

class ValidationError(Exception):
    def __init__(self, message, errors):

        # Call the base class constructor with the parameters it needs
        super().__init__(message)

        # Now for your custom code...
        self.errors = errors

how do I get a new line, after using float:left?

You need to "clear" the float after every 6 images. So with your current code, change the styles for containerdivNewLine to:

.containerdivNewLine { clear: both; float: left; display: block; position: relative; } 

Importing modules from parent folder

In a Linux system, you can create a soft link from the "life" folder to the nib.py file. Then, you can simply import it like:

import nib

How to filter array in subdocument with MongoDB

Use $filter aggregation

Selects a subset of the array to return based on the specified condition. Returns an array with only those elements that match the condition. The returned elements are in the original order.

db.test.aggregate([
    {$match: {"list.a": {$gt:3}}}, // <-- match only the document which have a matching element
    {$project: {
        list: {$filter: {
            input: "$list",
            as: "list",
            cond: {$gt: ["$$list.a", 3]} //<-- filter sub-array based on condition
        }}
    }}
]);

Is there any difference between "!=" and "<>" in Oracle Sql?

At university we were taught 'best practice' was to use != when working for employers, though all the operators above have the same functionality.

Xcode project not showing list of simulators

Install iOS Simulator if you're missing one.

Click here to see how.

Docker how to change repository name or rename image?

docker image tag server:latest myname/server:latest

or

docker image tag d583c3ac45fd myname/server:latest

Tags are just human-readable aliases for the full image name (d583c3ac45fd...).

So you can have as many of them associated with the same image as you like. If you don't like the old name you can remove it after you've retagged it:

docker rmi server

That will just remove the alias/tag. Since d583c3ac45fd has other names, the actual image won't be deleted.

Accessing variables from other functions without using global variables

You can completely control the execution of javascript functions (and pass variables between them) using custom jQuery events....I was told that this wasn't possible all over these forums, but I got something working that does exactly that (even using an ajax call).

Here's the answer (IMPORTANT: it's not the checked answer but rather the answer by me "Emile"):

How to get a variable returned across multiple functions - Javascript/jQuery

Is there a vr (vertical rule) in html?

You can use css for simulate a vertical line, and use the class on the div

.vhLine {
  border-left: thick solid #000000;
}

Create empty data frame with column names by assigning a string vector?

How about:

df <- data.frame(matrix(ncol = 3, nrow = 0))
x <- c("name", "age", "gender")
colnames(df) <- x

To do all these operations in one-liner:

setNames(data.frame(matrix(ncol = 3, nrow = 0)), c("name", "age", "gender"))

#[1] name   age    gender
#<0 rows> (or 0-length row.names)

Or

data.frame(matrix(ncol=3,nrow=0, dimnames=list(NULL, c("name", "age", "gender"))))

How to import module when module name has a '-' dash or hyphen in it?

If you can't rename the module to match Python naming conventions, create a new module to act as an intermediary:

 ---- foo_proxy.py ----
 tmp = __import__('foo-bar')
 globals().update(vars(tmp))

 ---- main.py ----
 from foo_proxy import * 

CSS background image alt attribute

You can achieve this by putting the alt tag in the div were your image will appear.

Example:

<div id="yourImage" alt="nameOfImage"></div>

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

Python: "TypeError: __str__ returned non-string" but still prints to output?

I Had the same problem, in my case, was because i was returned a digit:

def __str__(self):
    return self.code

str is waiting for a str, not another.

now work good with:

def __str__(self):
    return self.name

where name is a STRING.

How to fix "Root element is missing." when doing a Visual Studio (VS) Build?

My project did not load and gave me a Root Element Missingerror. I just deleted ****.csproj.user file and reloaded it again. The problem was solved this way

CSS Animation onClick

Add a

-webkit-animation-play-state: paused;

to your CSS file, then you can control whether the animation is running or not by using this JS line:

document.getElementById("myDIV").style.WebkitAnimationPlayState = "running";

if you want the animation to run once, every time you click. Remember to set

-webkit-animation-iteration-count: 1;

Check if a variable is a string in JavaScript

A simple solution would be:

var x = "hello"

if(x === x.toString()){
// it's a string 
}else{
// it isn't
}

Way to get all alphabetic chars in an array in PHP?

To get both upper and lower case merge the two ranges:

$alphas = array_merge(range('A', 'Z'), range('a', 'z'));

Set background colour of cell to RGB value of data in cell

You can use VBA - something like

Range("A1:A6").Interior.Color = RGB(127,187,199)

Just pass in the cell value.

Storing and displaying unicode string (??????) using PHP and MySQL

For those who are looking for PHP ( >5.3.5 ) PDO statement, we can set charset as per below:

$dbh = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');

How can I solve the error 'TS2532: Object is possibly 'undefined'?

With the release of TypeScript 3.7, optional chaining (the ? operator) is now officially available.

As such, you can simplify your expression to the following:

const data = change?.after?.data();

You may read more about it from that version's release notes, which cover other interesting features released on that version.

Run the following to install the latest stable release of TypeScript.

npm install typescript

That being said, Optional Chaining can be used alongside Nullish Coalescing to provide a fallback value when dealing with null or undefined values

const data = change?.after?.data() ?? someOtherData();

Numeric for loop in Django templates

If the number is coming from a model, I found this to be a nice patch to the model:

def iterableQuantity(self):
    return range(self.quantity)

Shell command to sum integers, one per line?

perl -lne '$x += $_; END { print $x; }' < infile.txt

Get drop down value

<select onchange = "selectChanged(this.value)">
  <item value = "1">one</item>
  <item value = "2">two</item>
</select>

and then the javascript...

function selectChanged(newvalue) {
  alert("you chose: " + newvalue);
}

Bootstrap modal: close current, open new

I use this method:

$(function() {
  return $(".modal").on("show.bs.modal", function() {
    var curModal;
    curModal = this;
    $(".modal").each(function() {
      if (this !== curModal) {
        $(this).modal("hide");
      }
    });
  });
});

adding line break

This worked for me:

foreach (var item in FirmNameList){
    if (FirmNames != "")
    {
        FirmNames += ",\r\n"
    }

    FirmNames += item;
}

Access Enum value using EL with JSTL

Here are two more possibilities:

JSP EL 3.0 Constants

As long as you are using at least version 3.0 of EL, then you can import constants into your page as follows:

<%@ page import="org.example.Status" %>
<c:when test="${dp.status eq Status.VALID}">

However, some IDEs don't understand this yet (e.g. IntelliJ) so you won't get any warnings if you make a typo, until runtime.

This would be my preferred method once it gets proper IDE support.

Helper Methods

You could just add getters to your enum.

public enum Status { 
  VALID("valid"), OLD("old");

  private final String val;

  Status(String val) {
    this.val = val;
  }

  public String getStatus() {
    return val;
  }

  public boolean isValid() {
    return this == VALID;
  }

  public boolean isOld() {
    return this == OLD;
  }
}

Then in your JSP:

<c:when test="${dp.status.valid}">

This is supported in all IDEs and will also work if you can't use EL 3.0 yet. This is what I do at the moment because it keeps all the logic wrapped up into my enum.

Also be careful if it is possible for the variable storing the enum to be null. You would need to check for that first if your code doesn't guarantee that it is not null:

<c:when test="${not empty db.status and dp.status.valid}">

I think this method is superior to those where you set an intermediary value in the JSP because you have to do that on each page where you need to use the enum. However, with this solution you only need to declare the getter once.

Converting file size in bytes to human-readable string

This is size improvement of mpen answer

function humanFileSize(bytes, si=false) {
  let u, b=bytes, t= si ? 1000 : 1024;     
  ['', si?'k':'K', ...'MGTPEZY'].find(x=> (u=x, b/=t, b**2<1));
  return `${u ? (t*b).toFixed(1) : bytes} ${u}${!si && u ? 'i':''}B`;    
}

_x000D_
_x000D_
function humanFileSize(bytes, si=false) {_x000D_
  let u, b=bytes, t= si ? 1000 : 1024;     _x000D_
  ['', si?'k':'K', ...'MGTPEZY'].find(x=> (u=x, b/=t, b**2<1));_x000D_
  return `${u ? (t*b).toFixed(1) : bytes} ${u}${!si && u ? 'i':''}B`;    _x000D_
}_x000D_
_x000D_
_x000D_
// TEST_x000D_
console.log(humanFileSize(5000));      // 4.9 KiB_x000D_
console.log(humanFileSize(5000,true)); // 5.0 kB
_x000D_
_x000D_
_x000D_

Combine two columns of text in pandas dataframe

Use of a lamba function this time with string.format().

import pandas as pd
df = pd.DataFrame({'Year': ['2014', '2015'], 'Quarter': ['q1', 'q2']})
print df
df['YearQuarter'] = df[['Year','Quarter']].apply(lambda x : '{}{}'.format(x[0],x[1]), axis=1)
print df

  Quarter  Year
0      q1  2014
1      q2  2015
  Quarter  Year YearQuarter
0      q1  2014      2014q1
1      q2  2015      2015q2

This allows you to work with non-strings and reformat values as needed.

import pandas as pd
df = pd.DataFrame({'Year': ['2014', '2015'], 'Quarter': [1, 2]})
print df.dtypes
print df

df['YearQuarter'] = df[['Year','Quarter']].apply(lambda x : '{}q{}'.format(x[0],x[1]), axis=1)
print df

Quarter     int64
Year       object
dtype: object
   Quarter  Year
0        1  2014
1        2  2015
   Quarter  Year YearQuarter
0        1  2014      2014q1
1        2  2015      2015q2

java.lang.ClassNotFoundException:com.mysql.jdbc.Driver

I had

runtime('mysql:mysql-connector-java')

Changed to

compile('mysql:mysql-connector-java')

Fixed my problem

How to install maven on redhat linux

Sometimes you may get "Exception in thread "main" java.lang.NoClassDefFoundError: org/codehaus/classworlds/Launcher" even after setting M2_HOME and PATH parameters correctly.

This exception is because your JDK/Java version need to be updated/installed.

How to download Visual Studio 2017 Community Edition for offline installation?

The command above worked for me

C:\Users\marcelo\Downloads\vs_community.exe --lang en-en --layout C:\VisualStudio2017 --all

Debugging "Element is not clickable at point" error

I was facing a similar problem whre i have to check two check boxes one after the other.But i was getting the same above error.hence i added wait in between my steps for checking the checkboxes....its working fine and great.here are the steps:-

  When I visit /administrator/user_profiles
  And I press xpath link "//*[@id='1']"
  Then I should see "Please wait for a moment..."
  When I wait for 5 seconds
  And I press xpath link "//*[@id='2']"
  Then I should see "Please wait for a moment..."
  When I visit /administrator/user_profiles_updates

Convert DataTable to CSV stream

BFree's answer worked for me. I needed to post the stream right to the browser. Which I'd imagine is a common alternative. I added the following to BFree's Main() code to do this:

//StreamReader reader = new StreamReader(stream);
//Console.WriteLine(reader.ReadToEnd());

string fileName = "fileName.csv";
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", fileName));
stream.Position = 0;
stream.WriteTo(HttpContext.Current.Response.OutputStream);

How to set time zone of a java.util.Date?

If you must work with only standard JDK classes you can use this:

/**
 * Converts the given <code>date</code> from the <code>fromTimeZone</code> to the
 * <code>toTimeZone</code>.  Since java.util.Date has does not really store time zome
 * information, this actually converts the date to the date that it would be in the
 * other time zone.
 * @param date
 * @param fromTimeZone
 * @param toTimeZone
 * @return
 */
public static Date convertTimeZone(Date date, TimeZone fromTimeZone, TimeZone toTimeZone)
{
    long fromTimeZoneOffset = getTimeZoneUTCAndDSTOffset(date, fromTimeZone);
    long toTimeZoneOffset = getTimeZoneUTCAndDSTOffset(date, toTimeZone);

    return new Date(date.getTime() + (toTimeZoneOffset - fromTimeZoneOffset));
}

/**
 * Calculates the offset of the <code>timeZone</code> from UTC, factoring in any
 * additional offset due to the time zone being in daylight savings time as of
 * the given <code>date</code>.
 * @param date
 * @param timeZone
 * @return
 */
private static long getTimeZoneUTCAndDSTOffset(Date date, TimeZone timeZone)
{
    long timeZoneDSTOffset = 0;
    if(timeZone.inDaylightTime(date))
    {
        timeZoneDSTOffset = timeZone.getDSTSavings();
    }

    return timeZone.getRawOffset() + timeZoneDSTOffset;
}

Credit goes to this post.

setting JAVA_HOME & CLASSPATH in CentOS 6

Do the following steps:

  1. sudo -s
  2. yum install java-1.8.0-openjdk-devel
  3. vi .bash_profile , and add below line into .bash_profile file and save the file.

export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.171-8.b10.el7_5.x86_64/

Note - I am using CentOS7 as OS.

jQuery: read text file from file system

Something like this is what I use all the time. No need for any base64 decoding.

<html>
<head>
<script>
      window.onload = function(event) {
        document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
      }

      function handleFileSelect(event) {
        var fileReader = new FileReader();
        fileReader.onload = function(event) {
          $('#accessKeyField').val(event.target.result);
        }
        var file = event.target.files[0];
        fileReader.readAsText(file);
        document.getElementById('fileInput').value = null;
      }
</script>
</head>
<body>
<input type="file" id="fileInput" style="height: 20px; width: 100px;">
</body>
</html>

IE prompts to open or save json result from server

Have you tried to send your ajax request using POST method ? You could also try to set content type to 'text/x-json' while returning result from the server.

tr:hover not working

tr:hover doesn't work in old browsers.

You can use jQuery for this:

.tr-hover
{  
  background-color:#fefefe;
}
$('.list1 tr').hover(function()
{
    $(this).addClass('tr-hover');
},function()
{
    $(this).removeClass('tr-hover');
});

How can I add a line to a file in a shell script?

This doesn't use sed, but using >> will append to a file. For example:

echo 'one, two, three' >> testfile.csv

Edit: To prepend to a file, try something like this:

echo "text"|cat - yourfile > /tmp/out && mv /tmp/out yourfile

I found this through a quick Google search.

C++ compile error: has initializer but incomplete type

` Please include either of these:

`#include<sstream>`

using std::istringstream; 

npm install error from the terminal

You're likely not in the node directory. Try switching to the directory that you unpacked node to and try running the command there.

Adding POST parameters before submit

you can do this without jQuery:

    var form=document.getElementById('form-id');//retrieve the form as a DOM element

    var input = document.createElement('input');//prepare a new input DOM element
    input.setAttribute('name', inputName);//set the param name
    input.setAttribute('value', inputValue);//set the value
    input.setAttribute('type', inputType)//set the type, like "hidden" or other

    form.appendChild(input);//append the input to the form

    form.submit();//send with added input

How can I get Android Wifi Scan Results into a list?

Try this code

public class WiFiDemo extends Activity implements OnClickListener
 {      
    WifiManager wifi;       
    ListView lv;
    TextView textStatus;
    Button buttonScan;
    int size = 0;
    List<ScanResult> results;

    String ITEM_KEY = "key";
    ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
    SimpleAdapter adapter;

    /* Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        textStatus = (TextView) findViewById(R.id.textStatus);
        buttonScan = (Button) findViewById(R.id.buttonScan);
        buttonScan.setOnClickListener(this);
        lv = (ListView)findViewById(R.id.list);

        wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifi.isWifiEnabled() == false)
        {
            Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
            wifi.setWifiEnabled(true);
        }   
        this.adapter = new SimpleAdapter(WiFiDemo.this, arraylist, R.layout.row, new String[] { ITEM_KEY }, new int[] { R.id.list_value });
        lv.setAdapter(this.adapter);

        registerReceiver(new BroadcastReceiver()
        {
            @Override
            public void onReceive(Context c, Intent intent) 
            {
               results = wifi.getScanResults();
               size = results.size();
            }
        }, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));                    
    }

    public void onClick(View view) 
    {
        arraylist.clear();          
        wifi.startScan();

        Toast.makeText(this, "Scanning...." + size, Toast.LENGTH_SHORT).show();
        try 
        {
            size = size - 1;
            while (size >= 0) 
            {   
                HashMap<String, String> item = new HashMap<String, String>();                       
                item.put(ITEM_KEY, results.get(size).SSID + "  " + results.get(size).capabilities);

                arraylist.add(item);
                size--;
                adapter.notifyDataSetChanged();                 
            } 
        }
        catch (Exception e)
        { }         
    }    
}

WiFiDemo.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textStatus"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Status" />

        <Button
            android:id="@+id/buttonScan"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:text="Scan" />
    </LinearLayout>

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="20dp"></ListView>
</LinearLayout>

For ListView- row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="8dp">

    <TextView
        android:id="@+id/list_value"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="14dp" />
</LinearLayout>

Add these permission in AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Converting binary to decimal integer output

I started working on this problem a long time ago, trying to write my own binary to decimal converter function. I don't actually know how to convert decimal to binary though! I just revisited it today and figured it out and this is what I came up with. I'm not sure if this is what you need, but here it is:

def __degree(number):
    power = 1

    while number % (10**power) != number:
        power += 1

    return power

def __getDigits(number):
    digits = []
    degree = __degree(number)

    for x in range(0, degree):
        digits.append(int(((number % (10**(degree-x))) - (number % (10**(degree-x-1)))) / (10**(degree-x-1))))
    return digits

def binaryToDecimal(number):
    list = __getDigits(number)
    decimalValue = 0
    for x in range(0, len(list)):
        if (list[x] is 1):
            decimalValue += 2**(len(list) - x - 1)
    return decimalValue

Again, I'm still learning Python just on my own, hopefully this helps. The first function determines how many digits there are, the second function actually figures out they are and returns them in a list, and the third function is the only one you actually need to call, and it calculates the decimal value. If your teacher actually wanted you to write your own converter, this works, I haven't tested it with every number, but it seems to work perfectly! I'm sure you'll all find the bugs for me! So anyway, I just called it like:

binaryNum = int(input("Enter a binary number: "))

print(binaryToDecimal(binaryNum))

This prints out the correct result. Cheers!

How to solve Permission denied (publickey) error when using Git?

I had to copy my ssh keys to the root folder. Google Cloud Compute Engine running Ubuntu 18.04

sudo cp ~/.ssh/* /root/.ssh/

Undefined reference to main - collect2: ld returned 1 exit status

It means that es3.c does not define a main function, and you are attempting to create an executable out of it. An executable needs to have an entry point, thereby the linker complains.

To compile only to an object file, use the -c option:

gcc es3.c -c
gcc es3.o main.c -o es3

The above compiles es3.c to an object file, then compiles a file main.c that would contain the main function, and the linker merges es3.o and main.o into an executable called es3.

Create Setup/MSI installer in Visual Studio 2017

You need to install this extension to Visual Studio 2017/2019 in order to get access to the Installer Projects.

According to the page:

This extension provides the same functionality that currently exists in Visual Studio 2015 for Visual Studio Installer projects. To use this extension, you can either open the Extensions and Updates dialog, select the online node, and search for "Visual Studio Installer Projects Extension," or you can download directly from this page.

Once you have finished installing the extension and restarted Visual Studio, you will be able to open existing Visual Studio Installer projects, or create new ones.

How do you use variables in a simple PostgreSQL script?

Here's an example of using a variable in plpgsql:

create table test (id int);
insert into test values (1);
insert into test values (2);
insert into test values (3);

create function test_fn() returns int as $$
    declare val int := 2;
    begin
        return (SELECT id FROM test WHERE id = val);
    end;
$$ LANGUAGE plpgsql;

SELECT * FROM test_fn();
 test_fn 
---------
       2

Have a look at the plpgsql docs for more information.

What's wrong with using == to compare floats in Java?

Two different calculations which produce equal real numbers do not necessarily produce equal floating point numbers. People who use == to compare the results of calculations usually end up being surprised by this, so the warning helps flag what might otherwise be a subtle and difficult to reproduce bug.

SCRIPT5: Access is denied in IE9 on xmlhttprequest

  $.ajax({
        url: '//freegeoip.net/json/',
        type: 'POST',
        dataType: 'jsonp',
        success: function(location) {
            alert(location.ip);
        }
    });

This code will work https sites too

Android Get Application's 'Home' Data Directory

To get the path of file in application package;

ContextWrapper c = new ContextWrapper(this);
Toast.makeText(this, c.getFilesDir().getPath(), Toast.LENGTH_LONG).show();

How to resolve "gpg: command not found" error during RVM installation?

GnuPG (with binary name gpg) is an application used for public key encryption using the OpenPGP protocol, but also verification of signatures (cryptographic signatures, that also can validate the publisher if used correctly). To some extend, you could say it's for OpenPGP what OpenSSL is for X.509 and TLS.

Unlike most Linux distributions (which make heavy use of GnuPG for ensuring untampered software within their package repositories), Mac OS X does not bring GnuPG with the operating system, so you have to install it on your own.

Possible sources are:

  • Package manager Homebrew: brew install gnupg gnupg2
  • Package manager MacPorts: sudo port install gnupg gnupg2
  • Install from GPGTools, which also brings GUI applications and integration in Apple Mail

Capture key press without placing an input element on the page?

jQuery also has an excellent implementation that's incredibly easy to use. Here's how you could implement this functionality across browsers:

$(document).keypress(function(e){
    var checkWebkitandIE=(e.which==26 ? 1 : 0);
    var checkMoz=(e.which==122 && e.ctrlKey ? 1 : 0);

    if (checkWebkitandIE || checkMoz) $("body").append("<p>ctrl+z detected!</p>");
});

Tested in IE7,Firefox 3.6.3 & Chrome 4.1.249.1064

Another way of doing this is to use the keydown event and track the event.keyCode. However, since jQuery normalizes keyCode and charCode using event.which, their spec recommends using event.which in a variety of situations:

$(document).keydown(function(e){
if (e.keyCode==90 && e.ctrlKey)
    $("body").append("<p>ctrl+z detected!</p>");
});

How to get absolute path to file in /resources folder of your project

The proper way that actually works:

URL resource = YourClass.class.getResource("abc");
Paths.get(resource.toURI()).toFile();

It doesn't matter now where the file in the classpath physically is, it will be found as long as the resource is actually a file and not a JAR entry.

(The seemingly obvious new File(resource.getPath()) doesn't work for all paths! The path is still URL-encoded!)

Access elements of parent window from iframe

Have the below js inside the iframe and use ajax to submit the form.

$(function(){

   $("form").submit(e){
        e.preventDefault();

       //Use ajax to submit the form
       $.ajax({
          url: this.action,
          data: $(this).serialize(),
          success: function(){
             window.parent.$("#target").load("urlOfThePageToLoad");
          });
       });

   });

});

Pandas groupby month and year

You can use either resample or Grouper (which resamples under the hood).

First make sure that the datetime column is actually of datetimes (hit it with pd.to_datetime). It's easier if it's a DatetimeIndex:

In [11]: df1
Out[11]:
            abc  xyz
Date
2013-06-01  100  200
2013-06-03  -20   50
2013-08-15   40   -5
2014-01-20   25   15
2014-02-21   60   80

In [12]: g = df1.groupby(pd.Grouper(freq="M"))  # DataFrameGroupBy (grouped by Month)

In [13]: g.sum()
Out[13]:
            abc  xyz
Date
2013-06-30   80  250
2013-07-31  NaN  NaN
2013-08-31   40   -5
2013-09-30  NaN  NaN
2013-10-31  NaN  NaN
2013-11-30  NaN  NaN
2013-12-31  NaN  NaN
2014-01-31   25   15
2014-02-28   60   80

In [14]: df1.resample("M", how='sum')  # the same
Out[14]:
            abc  xyz
Date
2013-06-30   40  125
2013-07-31  NaN  NaN
2013-08-31   40   -5
2013-09-30  NaN  NaN
2013-10-31  NaN  NaN
2013-11-30  NaN  NaN
2013-12-31  NaN  NaN
2014-01-31   25   15
2014-02-28   60   80

Note: Previously pd.Grouper(freq="M") was written as pd.TimeGrouper("M"). The latter is now deprecated since 0.21.


I had thought the following would work, but it doesn't (due to as_index not being respected? I'm not sure.). I'm including this for interest's sake.

If it's a column (it has to be a datetime64 column! as I say, hit it with to_datetime), you can use the PeriodIndex:

In [21]: df
Out[21]:
        Date  abc  xyz
0 2013-06-01  100  200
1 2013-06-03  -20   50
2 2013-08-15   40   -5
3 2014-01-20   25   15
4 2014-02-21   60   80

In [22]: pd.DatetimeIndex(df.Date).to_period("M")  # old way
Out[22]:
<class 'pandas.tseries.period.PeriodIndex'>
[2013-06, ..., 2014-02]
Length: 5, Freq: M

In [23]: per = df.Date.dt.to_period("M")  # new way to get the same

In [24]: g = df.groupby(per)

In [25]: g.sum()  # dang not quite what we want (doesn't fill in the gaps)
Out[25]:
         abc  xyz
2013-06   80  250
2013-08   40   -5
2014-01   25   15
2014-02   60   80

To get the desired result we have to reindex...

Are all Spring Framework Java Configuration injection examples buggy?

In your test, you are comparing the two TestParent beans, not the single TestedChild bean.

Also, Spring proxies your @Configuration class so that when you call one of the @Bean annotated methods, it caches the result and always returns the same object on future calls.

See here:

check if variable is dataframe

Use isinstance, nothing else:

if isinstance(x, pd.DataFrame):
    ... # do something

PEP8 says explicitly that isinstance is the preferred way to check types

No:  type(x) is pd.DataFrame
No:  type(x) == pd.DataFrame
Yes: isinstance(x, pd.DataFrame)

And don't even think about

if obj.__class__.__name__ = 'DataFrame':
    expect_problems_some_day()

isinstance handles inheritance (see What are the differences between type() and isinstance()?). For example, it will tell you if a variable is a string (either str or unicode), because they derive from basestring)

if isinstance(obj, basestring):
    i_am_string(obj)

Specifically for pandas DataFrame objects:

import pandas as pd
isinstance(var, pd.DataFrame)

Convert python long/int to fixed size byte array

One-liner:

bytearray.fromhex('{:0192x}'.format(big_int))

The 192 is 768 / 4, because OP wanted 768-bit numbers and there are 4 bits in a hex digit. If you need a bigger bytearray use a format string with a higher number. Example:

>>> big_int = 911085911092802609795174074963333909087482261102921406113936886764014693975052768158290106460018649707059449553895568111944093294751504971131180816868149233377773327312327573120920667381269572962606994373889233844814776702037586419
>>> bytearray.fromhex('{:0192x}'.format(big_int))
bytearray(b'\x96;h^\xdbJ\x8f3obL\x9c\xc2\xb0-\x9e\xa4Sj-\xf6i\xc1\x9e\x97\x94\x85M\x1d\x93\x10\\\x81\xc2\x89\xcd\xe0a\xc0D\x81v\xdf\xed\xa9\xc1\x83p\xdbU\xf1\xd0\xfeR)\xce\x07\xdepM\x88\xcc\x7fv\\\x1c\x8di\x87N\x00\x8d\xa8\xbd[<\xdf\xaf\x13z:H\xed\xc2)\xa4\x1e\x0f\xa7\x92\xa7\xc6\x16\x86\xf1\xf3')
>>> lepi_int = 0x963b685edb4a8f336f624c9cc2b02d9ea4536a2df669c19e9794854d1d93105c81c289cde061c0448176dfeda9c18370db55f1d0fe5229ce07de704d88cc7f765c1c8d69874e008da8bd5b3cdfaf137a3a48edc229a41e0fa792a7c61686f1f
>>> bytearray.fromhex('{:0192x}'.format(lepi_int))
bytearray(b'\tc\xb6\x85\xed\xb4\xa8\xf36\xf6$\xc9\xcc+\x02\xd9\xeaE6\xa2\xdff\x9c\x19\xe9yHT\xd1\xd91\x05\xc8\x1c(\x9c\xde\x06\x1c\x04H\x17m\xfe\xda\x9c\x187\r\xb5_\x1d\x0f\xe5"\x9c\xe0}\xe7\x04\xd8\x8c\xc7\xf7e\xc1\xc8\xd6\x98t\xe0\x08\xda\x8b\xd5\xb3\xcd\xfa\xf17\xa3\xa4\x8e\xdc"\x9aA\xe0\xfay*|aho\x1f')

[My answer had used hex() before. I corrected it with format() in order to handle ints with odd-sized byte expressions. This fixes previous complaints about ValueError.]

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '...' is therefore not allowed access

Solved with below entry in httpd.conf

#CORS Issue
Header set X-Content-Type-Options "nosniff"
Header always set Access-Control-Max-Age 1728000
Header always set Access-Control-Allow-Origin: "*"
Header always set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT,PATCH"
Header always set Access-Control-Allow-Headers: "DNT,X-CustomHeader,Keep-Alive,Content-Type,Origin,Authentication,Authorization,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control"
Header always set Access-Control-Allow-Credentials true

#CORS REWRITE
RewriteEngine On                  
RewriteCond %{REQUEST_METHOD} OPTIONS 
#RewriteRule ^(.*)$ $1 [R=200,L]
RewriteRule ^(.*)$ $1 [R=200,L,E=HTTP_ORIGIN:%{HTTP:ORIGIN}]]

How to solve privileges issues when restore PostgreSQL Database

For people using Google Cloud Platform, any error will stop the import process. Personally I encountered two different errors depending on the pg_dump command I issued :

1- The input is a PostgreSQL custom-format dump. Use the pg_restore command-line client to restore this dump to a database.

Occurs when you've tried to dump your DB in a non plain text format. I.e when the command lacks the -Fp or --format=plain parameter. However, if you add it to your command, you may then encounter the following error :

2- SET SET SET SET SET SET CREATE EXTENSION ERROR: must be owner of extension plpgsql

This is a permission issue I have been unable to fix using the command provided in the GCP docs, the tips from this current thread, or following advice from Google Postgres team here. Which recommended to issue the following command :

pg_dump -Fp --no-acl --no-owner -U myusername myDBName > mydump.sql

The only thing that did the trick in my case was manually editing the dump file and commenting out all commands relating to plpgsql.

I hope this helps GCP-reliant souls.

Update :

It's easier to dump the file commenting out extensions, especially since some dumps can be huge : pg_dump ... | grep -v -E '(CREATE\ EXTENSION|COMMENT\ ON)' > mydump.sql

Which can be narrowed down to plpgsql : pg_dump ... | grep -v -E '(CREATE\ EXTENSION\ IF\ NOT\ EXISTS\ plpgsql|COMMENT\ ON\ EXTENSION\ plpgsql)' > mydump.sql

How to position the div popup dialog to the center of browser screen?

I write a code in jquery. It isnt seen an easy way. But i hope it is useful for you.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<style type="text/css">

.popup{
    border: 4px solid #6b6a63;
    width: 800px;
    border-radius :7px;
    margin : auto;
    padding : 20px;
    position:fixed;
}

</style>

<div id="popup" class="popup">
some lengthy text<br>
some lengthy text<br>
some lengthy text<br>
some lengthy text<br>
some lengthy text<br>
some lengthy text<br>
some lengthy text<br>
some lengthy text<br>
</div>

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$(document).ready(function(){
    var popup_height = document.getElementById('popup').offsetHeight;
    var popup_width = document.getElementById('popup').offsetWidth;
    $(".popup").css('top',(($(window).height()-popup_height)/2));
    $(".popup").css('left',(($(window).width()-popup_width)/2));
});
</script>

How can I configure my makefile for debug and release builds?

You can use Target-specific Variable Values. Example:

CXXFLAGS = -g3 -gdwarf2
CCFLAGS = -g3 -gdwarf2

all: executable

debug: CXXFLAGS += -DDEBUG -g
debug: CCFLAGS += -DDEBUG -g
debug: executable

executable: CommandParser.tab.o CommandParser.yy.o Command.o
    $(CXX) -o output CommandParser.yy.o CommandParser.tab.o Command.o -lfl

CommandParser.yy.o: CommandParser.l 
    flex -o CommandParser.yy.c CommandParser.l
    $(CC) -c CommandParser.yy.c

Remember to use $(CXX) or $(CC) in all your compile commands.

Then, 'make debug' will have extra flags like -DDEBUG and -g where as 'make' will not.

On a side note, you can make your Makefile a lot more concise like other posts had suggested.

Excel 2013 horizontal secondary axis

You should follow the guidelines on Add a secondary horizontal axis:

Add a secondary horizontal axis

To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.

  1. Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.

  2. On the Layout tab, in the Axes group, click Axes.

    enter image description here

  3. Click Secondary Horizontal Axis, and then click the display option that you want.

enter image description here


Add a secondary vertical axis

You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.

  1. In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:

    • Click the chart.

      This displays the Chart Tools, adding the Design, Layout, and Format tabs.

    • On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.

      enter image description here

  2. On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.

    Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.

  3. On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.

    A secondary vertical axis is displayed in the chart.

  4. To change the display of the secondary vertical axis, do the following:

    • On the Layout tab, in the Axes group, click Axes.

    • Click Secondary Vertical Axis, and then click the display option that you want.

  5. To change the axis options of the secondary vertical axis, do the following:

    • Right-click the secondary vertical axis, and then click Format Axis.

    • Under Axis Options, select the options that you want to use.

MySQL update CASE WHEN/THEN/ELSE

If id is sequential starting at 1, the simplest (and quickest) would be:

UPDATE `table` 
SET uid = ELT(id, 2952, 4925, 1592) 
WHERE id IN (1,2,3)

As ELT() returns the Nth element of the list of strings: str1 if N = 1, str2 if N = 2, and so on. Returns NULL if N is less than 1 or greater than the number of arguments.

Clearly, the above code only works if id is 1, 2, or 3. If id was 10, 20, or 30, either of the following would work:

UPDATE `table` 
SET uid = CASE id 
WHEN 10 THEN 2952 
WHEN 20 THEN 4925 
WHEN 30 THEN 1592 END CASE 
WHERE id IN (10, 20, 30)

or the simpler:

UPDATE `table` 
SET uid = ELT(FIELD(id, 10, 20, 30), 2952, 4925, 1592) 
WHERE id IN (10, 20, 30)

As FIELD() returns the index (position) of str in the str1, str2, str3, ... list. Returns 0 if str is not found.

How do I put a border around an Android textview?

Create a border view with the background color as the color of the border and size of your text view. set border view padding as the width of the border. Set text view background color as the color you want for the text view. Now add your text view inside the border view.

excel plot against a date time x series

You will need to specify TimeSeries in Excel to be plotted. Have a look at this

Plotting Time Series

What is the meaning of "this" in Java?

A quick google search brought this result: http://xahlee.org/java-a-day/this.html

Pretty much the "this" keyword is a reference to the current object (itself).

How to test for $null array in PowerShell

How do you want things to behave?

If you want arrays with no elements to be treated the same as unassigned arrays, use:

[array]$foo = @() #example where we'd want TRUE to be returned
@($foo).Count -eq 0

If you want a blank array to be seen as having a value (albeit an empty one), use:

[array]$foo = @() #example where we'd want FALSE to be returned
$foo.PSObject -eq $null

If you want an array which is populated with only null values to be treated as null:

[array]$foo = $null,$null
@($foo | ?{$_.PSObject}).Count -eq 0 

NB: In the above I use $_.PSObject over $_ to avoid [bool]$false, [int]0, [string]'', etc from being filtered out; since here we're focussed solely on nulls.

Python: What OS am I running on?

If you are running macOS X and run platform.system() you get darwin because macOS X is built on Apple's Darwin OS. Darwin is the kernel of macOS X and is essentially macOS X without the GUI.

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

In order to run the python script, we need to tell the shell three things:

  1. That the file is a script
  2. Which interpreter we want to execute the script
  3. The path of said interpreter

The shebang #! accomplishes (1.). The shebang begins with a # because the # character is a comment marker in many scripting languages. The contents of the shebang line are therefore automatically ignored by the interpreter.

The env command accomplishes (2.) and (3.). To quote "grawity,"

A common use of the env command is to launch interpreters, by making use of the fact that env will search $PATH for the command it is told to launch. Since the shebang line requires an absolute path to be specified, and since the location of various interpreters (perl, bash, python) may vary a lot, it is common to use:

#!/usr/bin/env perl  instead of trying to guess whether it is /bin/perl, /usr/bin/perl, /usr/local/bin/perl, /usr/local/pkg/perl, /fileserver/usr/bin/perl, or /home/MrDaniel/usr/bin/perl on the user's system...

On the other hand, env is almost always in /usr/bin/env. (Except in cases when it isn't; some systems might use /bin/env, but that's a fairly rare occassion and only happens on non-Linux systems.)

How to use AND in IF Statement

I think you should append .value in IF statement:

If Cells(i, "A").Value <> "Miami" And Cells(i, "D").Value <> "Florida" Then
    Cells(i, "C").Value = "BA"
End IF

How to get PID of process by specifying process name and store it in a variable to use further?

use grep [n]ame to remove that grep -v name this is first... Sec using xargs in the way how it is up there is wrong to rnu whatever it is piped you have to use -i ( interactive mode) otherwise you may have issues with the command.

ps axf | grep | grep -v grep | awk '{print "kill -9 " $1}' ? ps aux |grep [n]ame | awk '{print "kill -9 " $2}' ? isnt that better ?

RadioGroup: How to check programmatically

You may need to declare the radio buttons in the onCreate method of your code and use them.

RadioButton rb1 = (RadioButton) findViewById(R.id.option1);
rb1.setChecked(true);

Always show vertical scrollbar in <select>

I guess you cant, this maybe a limitation or not included in the IE browser. I have tried your jsfiddle with IE6-8 and all of it doesn't show the scrollbar and not sure with IE9. While in FF and chrome the scrollbar is shown. I also want to see how to do it in IE if possible.

If you really want to show the scrollbar, you can add a fake scrollbar. If you are familiar with some of the js library which use in RIA. Like in jquery/dojo some of the select is editable, because it is a combination of textbox + select or it can also be a textbox + div.

As an example, see it here a JavaScript that make select like editable.

Working with UTF-8 encoding in Python source

Do not forget to verify if your text editor encodes properly your code in UTF-8.

Otherwise, you may have invisible characters that are not interpreted as UTF-8.

How to sort with a lambda?

Got it.

sort(mMyClassVector.begin(), mMyClassVector.end(), 
    [](const MyClass & a, const MyClass & b) -> bool
{ 
    return a.mProperty > b.mProperty; 
});

I assumed it'd figure out that the > operator returned a bool (per documentation). But apparently it is not so.

Display Python datetime without time

For me, I needed to KEEP a timetime object because I was using UTC and it's a bit of a pain. So, this is what I ended up doing:

date = datetime.datetime.utcnow()

start_of_day = date - datetime.timedelta(
    hours=date.hour, 
    minutes=date.minute, 
    seconds=date.second, 
    microseconds=date.microsecond
)

end_of_day = start_of_day + datetime.timedelta(
    hours=23, 
    minutes=59, 
    seconds=59
)

Example output:

>>> date
datetime.datetime(2016, 10, 14, 17, 21, 5, 511600)
>>> start_of_day
datetime.datetime(2016, 10, 14, 0, 0)
>>> end_of_day
datetime.datetime(2016, 10, 14, 23, 59, 59)

How to align iframe always in the center

I think if you add margin: auto; to the div below it should work.

div#iframe-wrapper iframe {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    margin: auto;
    right: 100px;
    height: 100%;
    width: 100%;
}

Getting the application's directory from a WPF application

I tried this:

    label1.Content = Directory.GetCurrentDirectory();

and get also the directory.

Background service with location listener in android

Very easy no need create class extends LocationListener 1- Variable

private LocationManager mLocationManager;
private LocationListener mLocationListener;
private static double currentLat =0;
private static double currentLon =0;

2- onStartService()

@Override public void onStartService() {
    addListenerLocation();
}

3- Method addListenerLocation()

 private void addListenerLocation() {
    mLocationManager = (LocationManager)
            getSystemService(Context.LOCATION_SERVICE);
    mLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            currentLat = location.getLatitude();
            currentLon = location.getLongitude();

            Toast.makeText(getBaseContext(),currentLat+"-"+currentLon, Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
            Location lastKnownLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if(lastKnownLocation!=null){
                currentLat = lastKnownLocation.getLatitude();
                currentLon = lastKnownLocation.getLongitude();
            }

        }

        @Override
        public void onProviderDisabled(String provider) {
        }
    };
    mLocationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 500, 10, mLocationListener);
}

4- onDestroy()

@Override
public void onDestroy() {
    super.onDestroy();
    mLocationManager.removeUpdates(mLocationListener);
}

php, mysql - Too many connections to database error

There are a bunch of different reasons for the "Too Many Connections" error.

Check out this FAQ page on MySQL.com: http://dev.mysql.com/doc/refman/5.5/en/too-many-connections.html

Check your my.cnf file for "max_connections". If none exist try:

[mysqld]
set-variable=max_connections=250

However the default is 151, so you should be okay.

If you are on a shared host, it might be that other users are taking up too many connections.

Other problems to look out for is the use of persistent connections and running out of diskspace.

Firebase TIMESTAMP to date and Time

Iterating through this is the precise code that worked for me.

querySnapshot.docs.forEach((e) => {
   var readableDate = e.data().date.toDate();
   console.log(readableDate);
}

How to get your Netbeans project into Eclipse

You should be using Maven, as the structure is standardized. To do that (Once you have created your Maven project in Netbeans, just

  1. Go to File -> Import
  2. Open Maven tree node
  3. Select Existing Maven Project
  4. Browse to find your project from NetBeans
  5. Check Add project to Working Set
  6. Click finish.

As long as the project has no errors, I usually get none transferring to eclipse. This works for Maven web projects and regular projects.

The total number of locks exceeds the lock table size

This answer below does not directly answer the OP's question. However, I'm adding this answer here because this page is the first result when you Google "The total number of locks exceeds the lock table size".


If the query you are running is parsing an entire table that spans millions of rows, you can try a while loop instead of changing limits in the configuration.

The while look will break it into pieces. Below is an example looping over an indexed column that is DATETIME.

# Drop
DROP TABLE IF EXISTS
new_table;

# Create (we will add keys later)
CREATE TABLE
new_table
(
    num INT(11),
    row_id VARCHAR(255),
    row_value VARCHAR(255),
    row_date DATETIME
);

# Change the delimimter
DELIMITER //

# Create procedure
CREATE PROCEDURE do_repeat(IN current_loop_date DATETIME)
BEGIN

    # Loops WEEK by WEEK until NOW(). Change WEEK to something shorter like DAY if you still get the lock errors like.
    WHILE current_loop_date <= NOW() DO

        # Do something
        INSERT INTO
            user_behavior_search_tagged_keyword_statistics_with_type
            (
                num,
                row_id,
                row_value,
                row_date
            )
        SELECT
            # Do something interesting here
            num,
            row_id,
            row_value,
            row_date
        FROM
            old_table
        WHERE
            row_date >= current_loop_date AND
            row_date < current_loop_date + INTERVAL 1 WEEK;

        # Increment
        SET current_loop_date = current_loop_date + INTERVAL 1 WEEK;

    END WHILE;

END//

# Run
CALL do_repeat('2017-01-01');

# Cleanup
DROP PROCEDURE IF EXISTS do_repeat//

# Change the delimimter back
DELIMITER ;

# Add keys
ALTER TABLE
    new_table
MODIFY COLUMN
    num int(11) NOT NULL,
ADD PRIMARY KEY
    (num),
ADD KEY
    row_id (row_id) USING BTREE,
ADD KEY
    row_date (row_date) USING BTREE;

You can also adapt it to loop over the "num" column if your table doesn't use a date.

Hope this helps someone!

PHP class: Global variable as property in class

If you want to access a property from inside a class you should:

private $classNumber = 8;

Using LIMIT within GROUP BY to get N results per group?

You could use GROUP_CONCAT aggregated function to get all years into a single column, grouped by id and ordered by rate:

SELECT   id, GROUP_CONCAT(year ORDER BY rate DESC) grouped_year
FROM     yourtable
GROUP BY id

Result:

-----------------------------------------------------------
|  ID | GROUPED_YEAR                                      |
-----------------------------------------------------------
| p01 | 2006,2003,2008,2001,2007,2009,2002,2004,2005,2000 |
| p02 | 2001,2004,2002,2003,2000,2006,2007                |
-----------------------------------------------------------

And then you could use FIND_IN_SET, that returns the position of the first argument inside the second one, eg.

SELECT FIND_IN_SET('2006', '2006,2003,2008,2001,2007,2009,2002,2004,2005,2000');
1

SELECT FIND_IN_SET('2009', '2006,2003,2008,2001,2007,2009,2002,2004,2005,2000');
6

Using a combination of GROUP_CONCAT and FIND_IN_SET, and filtering by the position returned by find_in_set, you could then use this query that returns only the first 5 years for every id:

SELECT
  yourtable.*
FROM
  yourtable INNER JOIN (
    SELECT
      id,
      GROUP_CONCAT(year ORDER BY rate DESC) grouped_year
    FROM
      yourtable
    GROUP BY id) group_max
  ON yourtable.id = group_max.id
     AND FIND_IN_SET(year, grouped_year) BETWEEN 1 AND 5
ORDER BY
  yourtable.id, yourtable.year DESC;

Please see fiddle here.

Please note that if more than one row can have the same rate, you should consider using GROUP_CONCAT(DISTINCT rate ORDER BY rate) on the rate column instead of the year column.

The maximum length of the string returned by GROUP_CONCAT is limited, so this works well if you need to select a few records for every group.

JavaScript, Node.js: is Array.forEach asynchronous?

It is possible to code even the solution like this for example :

 var loop = function(i, data, callback) {
    if (i < data.length) {
        //TODO("SELECT * FROM stackoverflowUsers;", function(res) {
            //data[i].meta = res;
            console.log(i, data[i].title);
            return loop(i+1, data, errors, callback);
        //});
    } else {
       return callback(data);
    }
};

loop(0, [{"title": "hello"}, {"title": "world"}], function(data) {
    console.log("DONE\n"+data);
});

On the other hand, it is much slower than a "for".

Otherwise, the excellent Async library can do this: https://caolan.github.io/async/docs.html#each

path.join vs path.resolve with __dirname

const absolutePath = path.join(__dirname, some, dir);

vs.

const absolutePath = path.resolve(__dirname, some, dir);

path.join will concatenate __dirname which is the directory name of the current file concatenated with values of some and dir with platform-specific separator.

Whereas

path.resolve will process __dirname, some and dir i.e. from right to left prepending it by processing it.

If any of the values of some or dir corresponds to a root path then the previous path will be omitted and process rest by considering it as root

In order to better understand the concept let me explain both a little bit more detail as follows:-

The path.join and path.resolve are two different methods or functions of the path module provided by nodejs.

Where both accept a list of paths but the difference comes in the result i.e. how they process these paths.

path.join concatenates all given path segments together using the platform-specific separator as a delimiter, then normalizes the resulting path. While the path.resolve() process the sequence of paths from right to left, with each subsequent path prepended until an absolute path is constructed.

When no arguments supplied

The following example will help you to clearly understand both concepts:-

My filename is index.js and the current working directory is E:\MyFolder\Pjtz\node

const path = require('path');

console.log("path.join() : ", path.join());
// outputs .
console.log("path.resolve() : ", path.resolve());
// outputs current directory or equivalent to __dirname

Result

? node index.js
path.join() :  .
path.resolve() :  E:\MyFolder\Pjtz\node

path.resolve() method will output the absolute path whereas the path.join() returns . representing the current working directory if nothing is provided

When some root path is passed as arguments

const path=require('path');

console.log("path.join() : " ,path.join('abc','/bcd'));
console.log("path.resolve() : ",path.resolve('abc','/bcd'));

Result i

? node index.js
path.join() :  abc\bcd
path.resolve() :  E:\bcd

path.join() only concatenates the input list with platform-specific separator while the path.resolve() process the sequence of paths from right to left, with each subsequent path prepended until an absolute path is constructed.

What’s the difference between "Array()" and "[]" while declaring a JavaScript array?

I've incurred in a weird behaviour using [].

We have Model "classes" with fields initialised to some value. E.g.:

require([
  "dojo/_base/declare",
  "dijit/_WidgetBase",
], function(declare, parser, ready, _WidgetBase){

   declare("MyWidget", [_WidgetBase], {
     field1: [],
     field2: "",
     function1: function(),
     function2: function()
   });    
});

I found that when the fields are initialised with [] then it would be shared by all Model objects. Making changes to one affects all others.

This doesn't happen initialising them with new Array(). Same for the initialisation of Objects ({} vs new Object())

TBH I am not sure if its a problem with the framework we were using (Dojo)

LINQ Joining in C# with multiple conditions

Your and should be a && in the where clause.

where epl.DepartAirportAfter >  sd.UTCDepartureTime 
and epl.ArriveAirportBy > sd.UTCArrivalTime

should be

where epl.DepartAirportAfter >  sd.UTCDepartureTime 
&& epl.ArriveAirportBy > sd.UTCArrivalTime

Is null check needed before calling instanceof?

No. Java literal null is not an instance of any class. Therefore it can not be an instanceof any class. instanceof will return either false or true therefore the <referenceVariable> instanceof <SomeClass> returns false when referenceVariable value is null.

Get the name of an object's type

The closest you can get is typeof, but it only returns "object" for any sort of custom type. For those, see Jason Bunting.

Edit, Jason's deleted his post for some reason, so just use Object's constructor property.

Constant pointer vs Pointer to constant

const int* ptr;

is a pointer to constant (content). You are allowed to modify the pointer. e.g. ptr = NULL, ptr++, but modification of the content is not possible.

int * const ptr;

Is a constant pointer. The opposite is possible. You are not allowed to modify the pointer, but you are allowed to modify what it points to e.g. *ptr += 5.

Why does pycharm propose to change method to static

PyCharm "thinks" that you might have wanted to have a static method, but you forgot to declare it to be static (using the @staticmethod decorator).

PyCharm proposes this because the method does not use self in its body and hence does not actually change the class instance. Hence the method could be static, i.e. callable without passing a class instance or without even having created a class instance.

How do I connect to a Websphere Datasource with a given JNDI name?

To get a connection from a data source, the following code should work:

import java.sql.Connection;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

Context ctx = new InitialContext();
DataSource dataSource = ctx.lookup("java:comp/env/jdbc/xxxx");
Connection conn = dataSource.getConnection();

// use the connection

conn.close();

While you can look up a data source as defined in the Websphere Data Sources config (i.e. through the websphere console) directly, the lookup from java:comp/env/jdbc/xxxx means that there needs to be an entry in web.xml:

<resource-ref>
    <res-ref-name>jdbc/xxxx</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>

This means that data sources can be mapped on a per application bases and you don't need to change the name of the data source if you want to point your app to a different data source. This is useful when deploying the application to different servers (e.g. test, preprod, prod) which need to point to different databases.

Datatable vs Dataset

One feature of the DataSet is that if you can call multiple select statements in your stored procedures, the DataSet will have one DataTable for each.

Convert row names into first column

A one line option is :

df$names <- rownames(df)

How to add some non-standard font to a website?

If you use ASP.NET, it's really easy to generate image based fonts without actually having to install (as in adding to the installed font base) fonts on the server by using:

PrivateFontCollection pfont = new PrivateFontCollection();
pfont.AddFontFile(filename);
FontFamily ff = pfont.Families[0];

and then drawing with that font onto a Graphics.

Javascript document.getElementById("id").value returning null instead of empty string when the element is an empty text box

I think the textbox you are trying to access is not yet loaded onto the page at the time your javascript is being executed.

ie., For the Javascript to be able to read the textbox from the DOM of the page, the textbox must be available as an element. If the javascript is getting called before the textbox is written onto the page, the textbox will not be visible and so NULL is returned.

How to draw border around a UILabel?

You can set label's border via its underlying CALayer property:

#import <QuartzCore/QuartzCore.h>

myLabel.layer.borderColor = [UIColor greenColor].CGColor
myLabel.layer.borderWidth = 3.0

Swift 5:

myLabel.layer.borderColor = UIColor.darkGray.cgColor
myLabel.layer.borderWidth = 3.0

.prop('checked',false) or .removeAttr('checked')?

Another alternative to do the same thing is to filter on type=checkbox attribute:

$('input[type="checkbox"]').removeAttr('checked');

or

$('input[type="checkbox"]').prop('checked' , false);

Remeber that The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

Know more...

Disable nginx cache for JavaScript files

I have the following nginx virtual host (static content) for local development work to disable all browser caching:

server {
    listen 8080;
    server_name localhost;

    location / {
        root /your/site/public;
        index index.html;

        # kill cache
        add_header Last-Modified $date_gmt;
        add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        if_modified_since off;
        expires off;
        etag off;
    }
}

No cache headers sent:

$ curl -I http://localhost:8080
HTTP/1.1 200 OK
Server: nginx/1.12.1
Date: Mon, 24 Jul 2017 16:19:30 GMT
Content-Type: text/html
Content-Length: 2076
Connection: keep-alive
Last-Modified: Monday, 24-Jul-2017 16:19:30 GMT
Cache-Control: no-store
Accept-Ranges: bytes

Last-Modified is always current time.

javascript close current window

You cannot close a window with javascript that you did not open. It will not work in chrome or firefox.

See https://stackoverflow.com/a/19768082/2623781 for more information.

How do I restore a dump file from mysqldump?

As a specific example of a previous answer:

I needed to restore a backup so I could import/migrate it into SQL Server. I installed MySql only, but did not register it as a service or add it to my path as I don't have the need to keep it running.

I used windows explorer to put my dump file in C:\code\dump.sql. Then opened MySql from the start menu item. Created the DB, then ran the source command with the full path like so:

mysql> create database temp
mysql> use temp
mysql> source c:\code\dump.sql

Storing JSON in database vs. having a new column for each key

short answer you have to mix between them , use json for data that you are not going to make relations with them like contact data , address , products variabls

Download history stock prices automatically from yahoo finance in python

You can check out the yahoo_fin package. It was initially created after Yahoo Finance changed their API (documentation is here: http://theautomatic.net/yahoo_fin-documentation).

from yahoo_fin import stock_info as si

aapl_data = si.get_data("aapl")

nflx_data = si.get_data("nflx")

aapl_data.head()

nflx_data.head()

aapl.to_csv("aapl_data.csv")

nflx_data.to_csv("nflx_data.csv")

Simple excel find and replace for formulas

If the formulas are identical you can use Find and Replace with Match entire cell contents checked and Look in: Formulas. Select the range, go into Find and Replace, make your entries and `Replace All.

enter image description here

Or do you mean that there are several formulas with this same form, but different cell references? If so, then one way to go is a regular expression match and replace. Regular expressions are not built into Excel (or VBA), but can be accessed via Microsoft's VBScript Regular Expressions library.

The following function provides the necessary match and replace capability. It can be used in a subroutine that would identify cells with formulas in the specified range and use the formulas as inputs to the function. For formulas strings that match the pattern you are looking for, the function will produce the replacement formula, which could then be written back to the worksheet.

Function RegexFormulaReplace(formula As String)
    Dim regex As New RegExp
    regex.Pattern = "=\(\(([A-Z]+\d+)-([A-Z]+\d+)\)/([A-Z]+\d+)\)"
'   Test if a match is found
    If regex.Test(formula) = True Then
        RegexFormulaReplace = regex.Replace(formula, "=(EXP((LN($1/$2)/14.32))-1")
    Else
        RegexFormulaReplace = CVErr(xlErrValue)
    End If
    Set regex = Nothing
End Function

In order for the function to work, you would need to add a reference to the Microsoft VBScript Regular Expressions 5.5 library. From the Developer tab of the main ribbon, select VBA and then References from the main toolbar. Scroll down to find the reference to the library and check the box next to it.

Delete specific line number(s) from a text file using sed?

If you want to delete lines 5 through 10 and 12:

sed -e '5,10d;12d' file

This will print the results to the screen. If you want to save the results to the same file:

sed -i.bak -e '5,10d;12d' file

This will back the file up to file.bak, and delete the given lines.

Note: Line numbers start at 1. The first line of the file is 1, not 0.

Illegal Character when trying to compile java code

The BOM is generated by, say, File.WriteAllText() or StreamWriter when you don't specify an Encoding. The default is to use the UTF8 encoding and generate a BOM. You can tell the java compiler about this with its -encoding command line option.

The path of least resistance is to avoid generating the BOM. Do so by specifying System.Text.Encoding.Default, that will write the file with the characters in the default code page of your operating system and doesn't write a BOM. Use the File.WriteAllText(String, String, Encoding) overload or the StreamWriter(String, Boolean, Encoding) constructor.

Just make sure that the file you create doesn't get compiled by a machine in another corner of the world. It will produce mojibake.

What is the difference between buffer and cache memory in Linux?

"Buffers" represent how much portion of RAM is dedicated to cache disk blocks. "Cached" is similar like "Buffers", only this time it caches pages from file reading.

quote from:

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

This error can also be received when the origin branch name has some case issue.

For example: origin branch is team1-Team and the local branch has been checkout as team1-team. Then, this T in -Team and t in -team can cause such error. This happened in my case. So, by changing the local name with the origin branch's name, the error was solved.

What are some examples of commonly used practices for naming git branches?

Note, as illustrated in the commit e703d7 or commit b6c2a0d (March 2014), now part of Git 2.0, you will find another naming convention (that you can apply to branches).

"When you need to use space, use dash" is a strange way to say that you must not use a space.
Because it is more common for the command line descriptions to use dashed-multi-words, you do not even want to use spaces in these places.

A branch name cannot have space (see "Which characters are illegal within a branch name?" and git check-ref-format man page).

So for every branch name that would be represented by a multi-word expression, using a '-' (dash) as a separator is a good idea.

sqlalchemy IS NOT NULL select

In case anyone else is wondering, you can use is_ to generate foo IS NULL:

>>> from sqlalchemy.sql import column
>>> print column('foo').is_(None)
foo IS NULL
>>> print column('foo').isnot(None)
foo IS NOT NULL