Programs & Examples On #Do.call

rbind error: "names do not match previous names"

Use code as follows:

mylist <- lapply(pressure, function(i)read.xlsx(i,colNames = FALSE))#
mydata <- do.call('rbind',mylist)#

Creating an R dataframe row-by-row

The reason I like Rcpp so much is that I don't always get how R Core thinks, and with Rcpp, more often than not, I don't have to.

Speaking philosophically, you're in a state of sin with regards to the functional paradigm, which tries to ensure that every value appears independent of every other value; changing one value should never cause a visible change in another value, the way you get with pointers sharing representation in C.

The problems arise when functional programming signals the small craft to move out of the way, and the small craft replies "I'm a lighthouse". Making a long series of small changes to a large object which you want to process on in the meantime puts you square into lighthouse territory.

In the C++ STL, push_back() is a way of life. It doesn't try to be functional, but it does try to accommodate common programming idioms efficiently.

With some cleverness behind the scenes, you can sometimes arrange to have one foot in each world. Snapshot based file systems are a good example (which evolved from concepts such as union mounts, which also ply both sides).

If R Core wanted to do this, underlying vector storage could function like a union mount. One reference to the vector storage might be valid for subscripts 1:N, while another reference to the same storage is valid for subscripts 1:(N+1). There could be reserved storage not yet validly referenced by anything but convenient for a quick push_back(). You don't violate the functional concept when appending outside the range that any existing reference considers valid.

Eventually appending rows incrementally, you run out of reserved storage. You'll need to create new copies of everything, with the storage multiplied by some increment. The STL implementations I've use tend to multiply storage by 2 when extending allocation. I thought I read in R Internals that there is a memory structure where the storage increments by 20%. Either way, growth operations occur with logarithmic frequency relative to the total number of elements appended. On an amortized basis, this is usually acceptable.

As tricks behind the scenes go, I've seen worse. Every time you push_back() a new row onto the dataframe, a top level index structure would need to be copied. The new row could append onto shared representation without impacting any old functional values. I don't even think it would complicate the garbage collector much; since I'm not proposing push_front() all references are prefix references to the front of the allocated vector storage.

Combine a list of data frames into one data frame by row

There is also bind_rows(x, ...) in dplyr.

> system.time({ df.Base <- do.call("rbind", listOfDataFrames) })
   user  system elapsed 
   0.08    0.00    0.07 
> 
> system.time({ df.dplyr <- as.data.frame(bind_rows(listOfDataFrames)) })
   user  system elapsed 
   0.01    0.00    0.02 
> 
> identical(df.Base, df.dplyr)
[1] TRUE

Pass a data.frame column name to a function

As an extra thought, if is needed to pass the column name unquoted to the custom function, perhaps match.call() could be useful as well in this case, as an alternative to deparse(substitute()):

df <- data.frame(A = 1:10, B = 2:11)

fun <- function(x, column){
  arg <- match.call()
  max(x[[arg$column]])
}

fun(df, A)
#> [1] 10

fun(df, B)
#> [1] 11

If there is a typo in the column name, then would be safer to stop with an error:

fun <- function(x, column) max(x[[match.call()$column]])
fun(df, typo)
#> Warning in max(x[[match.call()$column]]): no non-missing arguments to max;
#> returning -Inf
#> [1] -Inf

# Stop with error in case of typo
fun <- function(x, column){
  arg <- match.call()
  if (is.null(x[[arg$column]])) stop("Wrong column name")
  max(x[[arg$column]])
}

fun(df, typo)
#> Error in fun(df, typo): Wrong column name
fun(df, A)
#> [1] 10

Created on 2019-01-11 by the reprex package (v0.2.1)

I do not think I would use this approach since there is extra typing and complexity than just passing the quoted column name as pointed in the above answers, but well, is an approach.

Python coding standards/best practices

Yes, I try to follow it as closely as possible.

I don't follow any other coding standards.

Logging request/response messages when using HttpClient

Network tracing also available for next objects (see article on msdn)

  • System.Net.Sockets Some public methods of the Socket, TcpListener, TcpClient, and Dns classes
  • System.Net Some public methods of the HttpWebRequest, HttpWebResponse, FtpWebRequest, and FtpWebResponse classes, and SSL debug information (invalid certificates, missing issuers list, and client certificate errors.)
  • System.Net.HttpListener Some public methods of the HttpListener, HttpListenerRequest, and HttpListenerResponse classes.
  • System.Net.Cache Some private and internal methods in System.Net.Cache.
  • System.Net.Http Some public methods of the HttpClient, DelegatingHandler, HttpClientHandler, HttpMessageHandler, MessageProcessingHandler, and WebRequestHandler classes.
  • System.Net.WebSockets.WebSocket Some public methods of the ClientWebSocket and WebSocket classes.

Put next lines of code to the configuration file

<configuration>  
  <system.diagnostics>  
    <sources>  
      <source name="System.Net" tracemode="includehex" maxdatasize="1024">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Cache">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Http">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Sockets">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.WebSockets">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
    </sources>  
    <switches>  
      <add name="System.Net" value="Verbose"/>  
      <add name="System.Net.Cache" value="Verbose"/>  
      <add name="System.Net.Http" value="Verbose"/>  
      <add name="System.Net.Sockets" value="Verbose"/>  
      <add name="System.Net.WebSockets" value="Verbose"/>  
    </switches>  
    <sharedListeners>  
      <add name="System.Net"  
        type="System.Diagnostics.TextWriterTraceListener"  
        initializeData="network.log"  
      />  
    </sharedListeners>  
    <trace autoflush="true"/>  
  </system.diagnostics>  
</configuration>  

Get Multiple Values in SQL Server Cursor

This should work:

DECLARE db_cursor CURSOR FOR SELECT name, age, color FROM table; 
DECLARE @myName VARCHAR(256);
DECLARE @myAge INT;
DECLARE @myFavoriteColor VARCHAR(40);
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
WHILE @@FETCH_STATUS = 0  
BEGIN  

       --Do stuff with scalar values

       FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;

Comment out HTML and PHP together

PHP parser will search your entire code for <?php (or <? if short_open_tag = On), so HTML comment tags have no effect on PHP parser behavior & if you don't want to parse your PHP code, you have to use PHP commenting directives(/* */ or //).

How to update/modify an XML file in python?

As Edan Maor explained, the quick and dirty way to do it (for [utc-16] encoded .xml files), which you should not do for the resons Edam Maor explained, can done with the following python 2.7 code in case time constraints do not allow you to learn (propper) XML parses.

Assuming you want to:

  1. Delete the last line in the original xml file.
  2. Add a line
  3. substitute a line
  4. Close the root tag.

It worked in python 2.7 modifying an .xml file named "b.xml" located in folder "a", where "a" was located in the "working folder" of python. It outputs the new modified file as "c.xml" in folder "a", without yielding encoding errors (for me) in further use outside of python 2.7.

pattern = '<Author>'
subst = '    <Author>' + domain + '\\' + user_name + '</Author>'
line_index =0 #set line count to 0 before starting
file = io.open('a/b.xml', 'r', encoding='utf-16')
lines = file.readlines()
outFile = open('a/c.xml', 'w')
for line in lines[0:len(lines)]:
    line_index =line_index +1
    if line_index == len(lines):
        #1. & 2. delete last line and adding another line in its place not writing it
        outFile.writelines("Write extra line here" + '\n')
        # 4. Close root tag:
        outFile.writelines("</phonebook>") # as in:
        #http://tizag.com/xmlTutorial/xmldocument.php
    else:
        #3. Substitue a line if it finds the following substring in a line:
        pattern = '<Author>'
        subst = '    <Author>' + domain + '\\' + user_name + '</Author>'
        if pattern in line:
            line = subst
            print line
        outFile.writelines(line)#just writing/copying all the lines from the original xml except for the last.

Java "lambda expressions not supported at this language level"

7.0 does not support lambda expressions. Just add this to your app gradle to change your language level to 8.0:

compileOptions {
    targetCompatibility 1.8
    sourceCompatibility 1.8
}

enter image description here

SQL query for today's date minus two months

If you are using SQL Server try this:

SELECT * FROM MyTable
WHERE MyDate < DATEADD(month, -2, GETDATE())

Based on your update it would be:

SELECT * FROM FB WHERE Dte <  DATEADD(month, -2, GETDATE())

Git workflow and rebase vs merge questions

Anyway, I was following my workflow on a recent branch, and when I tried to merge it back to master, it all went to hell. There were tons of conflicts with things that should have not mattered. The conflicts just made no sense to me. It took me a day to sort everything out, and eventually culminated in a forced push to the remote master, since my local master has all conflicts resolved, but the remote one still wasn't happy.

In neither your partner's nor your suggested workflows should you have come across conflicts that didn't make sense. Even if you had, if you are following the suggested workflows then after resolution a 'forced' push should not be required. It suggests that you haven't actually merged the branch to which you were pushing, but have had to push a branch that wasn't a descendent of the remote tip.

I think you need to look carefully at what happened. Could someone else have (deliberately or not) rewound the remote master branch between your creation of the local branch and the point at which you attempted to merge it back into the local branch?

Compared to many other version control systems I've found that using Git involves less fighting the tool and allows you to get to work on the problems that are fundamental to your source streams. Git doesn't perform magic, so conflicting changes cause conflicts, but it should make it easy to do the write thing by its tracking of commit parentage.

CSS media queries: max-width OR max-height

Use a comma to specify two (or more) different rules:

@media screen and (max-width: 995px), 
       screen and (max-height: 700px) {
  ...
}

From https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries

Commas are used to combine multiple media queries into a single rule. Each query in a comma-separated list is treated separately from the others. Thus, if any of the queries in a list is true, the entire media statement returns true. In other words, lists behave like a logical or operator.

Entity Framework Provider type could not be loaded?

I had same isssue i tried many times but it did not resolve but when i install the package EntityFramework.SqlServerCompact it solved install this package from Nuget package Manager.

Install-Package EntityFramework.SqlServerCompact

Java JDBC connection status

The low-cost method, regardless of the vendor implementation, would be to select something from the process memory or the server memory, like the DB version or the name of the current database. IsClosed is very poorly implemented.

Example:

java.sql.Connection conn = <connect procedure>;
conn.close();
try {
  conn.getMetaData();
} catch (Exception e) {
  System.out.println("Connection is closed");
}

How to convert HTML to PDF using iText

This links might be helpful to convert.

https://code.google.com/p/flying-saucer/

https://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html

If it is a college Project, you can even go for these, http://pd4ml.com/examples.htm

Example is given to convert HTML to PDF

How to globally replace a forward slash in a JavaScript string?

Use a regex literal with the g modifier, and escape the forward slash with a backslash so it doesn't clash with the delimiters.

var str = 'some // slashes', replacement = '';
var replaced = str.replace(/\//g, replacement);

Align items in a stack panel?

for windows 10 use relativePanel instead of stack panel, and use

relativepanel.alignrightwithpanel="true"

for the contained elements.

IE11 Document mode defaults to IE7. How to reset?

For the website ensure that IIS HTTP response headers setting and add new key X-UA-Compatible pointing to "IE=edge"

Click here for more details

If you have access to the server, the most reliable way of doing this is to do it on the server itself, in IIS. Go in to IIS HTTP Response Headers. Add Name: X-UA-Compatible Value: IE=edge This will override your browser and your code.

MongoDB inserts float when trying to insert integer

If the value type is already double, then update the value with $set command can not change the value type double to int when using NumberInt() or NumberLong() function. So, to Change the value type, it must update the whole record.

var re = db.data.find({"name": "zero"})
re['value']=NumberInt(0)
db.data.update({"name": "zero"}, re)

hibernate could not get next sequence value

I got same error before, type this query in your database CREATE SEQUENCE hibernate_sequence START WITH 1 INCREMENT BY 1 NOCYCLE;

that's work for me, good luck ~

Draw a connecting line between two elements

Cytoscape supports this with its Architecture example which supports dragging elements.

For creating connections, there is the edgehandles extension. It does not yet support editing existing connections. Question.

For editing connection shapes, there is the edge-editing extension. Demo.

The edit-editation extension seems promising, however there is no demo yet.

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

Your class MyClass creates a new MyClassToBeTested, instead of using your mock. My article on the Mockito wiki describes two ways of dealing with this.

Direct method from SQL command text to DataSet

public DataSet GetDataSet(string ConnectionString, string SQL)
{
    SqlConnection conn = new SqlConnection(ConnectionString);
    SqlDataAdapter da = new SqlDataAdapter();
    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = SQL;
    da.SelectCommand = cmd;
    DataSet ds = new DataSet();

    ///conn.Open();
    da.Fill(ds);
    ///conn.Close();

    return ds;
}

How to use gitignore command in git

If you dont have a .gitignore file, first use:

touch .gitignore

then this command to add lines in your gitignore file:

echo 'application/cache' >> .gitignore

Be careful about new lines

Retrofit and GET using parameters

@QueryMap worked for me instead of FieldMap

If you have a bunch of GET params, another way to pass them into your url is a HashMap.

class YourActivity extends Activity {

private static final String BASEPATH = "http://www.example.com";

private interface API {
    @GET("/thing")
    void getMyThing(@QueryMap Map<String, String> params, new Callback<String> callback);
}

public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.your_layout);

   RestAdapter rest = new RestAdapter.Builder().setEndpoint(BASEPATH).build();
   API service = rest.create(API.class);

   Map<String, String> params = new HashMap<String, String>();
   params.put("key1", "val1");
   params.put("key2", "val2");
   // ... as much as you need.

   service.getMyThing(params, new Callback<String>() {
       // ... do some stuff here.
   });
}
}

The URL called will be http://www.example.com/thing/?key1=val1&key2=val2

Difference between array_push() and $array[] =

both are the same, but array_push makes a loop in it's parameter which is an array and perform $array[]=$element

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

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

For example:

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

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

So, in your case:

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

Mysql password expired. Can't connect

start MYSQL in safe mode

mysqld_safe --skip-grant-tables &

Connect to MYSQL server

mysql -u root

run SQL commands to reset password:

use mysql;
SET GLOBAL default_password_lifetime = 0;
SET PASSWORD = PASSWORD('new_password');

Last step, restart your mysql service

React Native Border Radius with background color

Try moving the button styling to the TouchableHighlight itself:

Styles:

  submit:{
    marginRight:40,
    marginLeft:40,
    marginTop:10,
    paddingTop:20,
    paddingBottom:20,
    backgroundColor:'#68a0cf',
    borderRadius:10,
    borderWidth: 1,
    borderColor: '#fff'
  },
  submitText:{
      color:'#fff',
      textAlign:'center',
  }

Button (same):

<TouchableHighlight
  style={styles.submit}
  onPress={() => this.submitSuggestion(this.props)}
  underlayColor='#fff'>
    <Text style={[this.getFontSize(),styles.submitText]}>Submit</Text>
</TouchableHighlight>

enter image description here

Database corruption with MariaDB : Table doesn't exist in engine

Something has deleted your ibdata1 file where InnoDB keeps the dictionary. Definitely it's not MySQL who does it.

UPDATE: I made a tutorial on how to fix the error - https://youtu.be/014KbCYayuE

How to force reloading php.ini file?

To force a reload of the php.ini you should restart apache.

Try sudo service apache2 restart from the command line. Or sudo /etc/init.d/apache2 restart

How to prevent scanf causing a buffer overflow in C?

Directly using scanf(3) and its variants poses a number of problems. Typically, users and non-interactive use cases are defined in terms of lines of input. It's rare to see a case where, if enough objects are not found, more lines will solve the problem, yet that's the default mode for scanf. (If a user didn't know to enter a number on the first line, a second and third line will probably not help.)

At least if you fgets(3) you know how many input lines your program will need, and you won't have any buffer overflows...

Converting between datetime and Pandas Timestamp objects

You can use the to_pydatetime method to be more explicit:

In [11]: ts = pd.Timestamp('2014-01-23 00:00:00', tz=None)

In [12]: ts.to_pydatetime()
Out[12]: datetime.datetime(2014, 1, 23, 0, 0)

It's also available on a DatetimeIndex:

In [13]: rng = pd.date_range('1/10/2011', periods=3, freq='D')

In [14]: rng.to_pydatetime()
Out[14]:
array([datetime.datetime(2011, 1, 10, 0, 0),
       datetime.datetime(2011, 1, 11, 0, 0),
       datetime.datetime(2011, 1, 12, 0, 0)], dtype=object)

How to debug in Android Studio using adb over WiFi

just open settings / plugins / search " Android wifi adb and download it and connect your mobile using usb cabble once and its done

Git log out user from command line

Try this on Windows:

cmdkey /delete:LegacyGeneric:target=git:https://github.com

IOException: Too many open files

Aside from looking into root cause issues like file leaks, etc. in order to do a legitimate increase the "open files" limit and have that persist across reboots, consider editing

/etc/security/limits.conf

by adding something like this

jetty soft nofile 2048
jetty hard nofile 4096

where "jetty" is the username in this case. For more details on limits.conf, see http://linux.die.net/man/5/limits.conf

log off and then log in again and run

ulimit -n

to verify that the change has taken place. New processes by this user should now comply with this change. This link seems to describe how to apply the limit on already running processes but I have not tried it.

The default limit 1024 can be too low for large Java applications.

How to write log file in c#?

From the performance point of view your solution is not optimal. Every time you add another log entry with +=, the whole string is copied to another place in memory. I would recommend using StringBuilder instead:

StringBuilder sb = new StringBuilder();
...
sb.Append("log something");

...
// flush every 20 seconds as you do it
File.AppendAllText(filePath+"log.txt", sb.ToString());
sb.Clear();

By the way your timer event is probably executed on another thread. So you may want to use a mutex when accessing your sb object.

Another thing to consider is what happens to the log entries that were added within the last 20 seconds of the execution. You probably want to flush your string to the file right before the app exits.

How to change symbol for decimal point in double.ToString()?

You can change the decimal separator by changing the culture used to display the number. Beware however that this will change everything else about the number (eg. grouping separator, grouping sizes, number of decimal places). From your question, it looks like you are defaulting to a culture that uses a comma as a decimal separator.

To change just the decimal separator without changing the culture, you can modify the NumberDecimalSeparator property of the current culture's NumberFormatInfo.

Thread.CurrentCulture.NumberFormat.NumberDecimalSeparator = ".";

This will modify the current culture of the thread. All output will now be altered, meaning that you can just use value.ToString() to output the format you want, without worrying about changing the culture each time you output a number.

(Note that a neutral culture cannot have its decimal separator changed.)

Access index of the parent ng-repeat from child ng-repeat

You can simply use use $parent.$index .where parent will represent object of parent repeating object .

How do you copy a record in a SQL table but swap out the unique id of the new row?

Ok, I know that it's an old issue but I post my answer anyway.

I like this solution. I only have to specify the identity column(s).

SELECT * INTO TempTable FROM MyTable_T WHERE id = 1;
ALTER TABLE TempTable DROP COLUMN id;
INSERT INTO MyTable_T SELECT * FROM TempTable;
DROP TABLE TempTable;

The "id"-column is the identity column and that's the only column I have to specify. It's better than the other way around anyway. :-)

I use SQL Server. You may want to use "CREATE TABLE" and "UPDATE TABLE" at row 1 and 2. Hmm, I saw that I did not really give the answer that he wanted. He wanted to copy the id to another column also. But this solution is nice for making a copy with a new auto-id.

I edit my solution with the idéas from Michael Dibbets.

use MyDatabase; 
SELECT * INTO #TempTable FROM [MyTable] WHERE [IndexField] = :id;
ALTER TABLE #TempTable DROP COLUMN [IndexField]; 
INSERT INTO [MyTable] SELECT * FROM #TempTable; 
DROP TABLE #TempTable;

You can drop more than one column by separating them with a ",". The :id should be replaced with the id of the row you want to copy. MyDatabase, MyTable and IndexField should be replaced with your names (of course).

Android SQLite Example

Using Helper class you can access SQLite Database and can perform the various operations on it by overriding the onCreate() and onUpgrade() methods.

http://technologyguid.com/android-sqlite-database-app-example/

Javascript - remove an array item by value

I like to use filter:

var id_tag = [1,2,3,78,5,6,7,8,47,34,90];

// delete where id_tag = 90
id_tag = id_tag.filter(function(x) {
    if (x !== 90) {
      return x;
    }
});

Save internal file in my own internal folder in Android

Save:

public boolean saveFile(Context context, String mytext){
    Log.i("TESTE", "SAVE");
    try {
        FileOutputStream fos = context.openFileOutput("file_name"+".txt",Context.MODE_PRIVATE);
        Writer out = new OutputStreamWriter(fos);
        out.write(mytext);
        out.close();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

Load:

public String load(Context context){
    Log.i("TESTE", "FILE");
    try {
        FileInputStream fis = context.openFileInput("file_name"+".txt");
        BufferedReader r = new BufferedReader(new InputStreamReader(fis));
        String line= r.readLine();
        r.close();
        return line;
    } catch (IOException e) {
        e.printStackTrace();
        Log.i("TESTE", "FILE - false");
        return null;
    }
}

Android: Expand/collapse animation

I stumbled over the same problem today and I guess the real solution to this question is this

<LinearLayout android:id="@+id/container"
android:animateLayoutChanges="true"
...
 />

You will have to set this property for all topmost layouts, which are involved in the shift. If you now set the visibility of one layout to GONE, the other will take the space as the disappearing one is releasing it. There will be a default animation which is some kind of "fading out", but I think you can change this - but the last one I have not tested, for now.

How to make a website secured with https

For business data, if the data is private I would use a secured connection, otherwise a forms authentication is sufficient.

If you do decide to use a secured connection, please note that I do not have experience with securing websites, I am just recanting off what I encountered during my own personal experience. If I am wrong in anyway, please feel free to correct me.

What should I do to prepare my website for https. (Do I need to alter the code / Config)

In order to enable SSL (Secure Sockets Layer) for your website, you would need to set-up a certificate, code or config is not altered.

I have enabled SSL for an internal web-server, by using OpenSSL and ActivePerl from this online tutorial. If this is used for a larger audience (my audience was less than 10 people) and is in the public domain, I suggest seeking professional alternatives.

Is SSL and https one and the same...

Not exactly, but they go hand in hand! SSL ensures that data is encrypted and decrypted back and forth while you are viewing the website, https is the URI that is need to access the secure website. You will notice when you try to access http://secure.mydomain.com it displays an error message.

Do I need to apply with someone to get some license or something.

You would not need to obtain a license, but rather a certificate. You can look into companies that offer professional services with securing websites, such as VeriSign as an example.

Do I need to make all my pages secured or only the login page...

Once your certificate is enabled for mydomain.com every page that falls under *.mydomain.com will be secured.

How does Python's super() work with multiple inheritance?

About @calfzhou's comment, you can use, as usually, **kwargs:

Online running example

class A(object):
  def __init__(self, a, *args, **kwargs):
    print("A", a)

class B(A):
  def __init__(self, b, *args, **kwargs):
    super(B, self).__init__(*args, **kwargs)
    print("B", b)

class A1(A):
  def __init__(self, a1, *args, **kwargs):
    super(A1, self).__init__(*args, **kwargs)
    print("A1", a1)

class B1(A1, B):
  def __init__(self, b1, *args, **kwargs):
    super(B1, self).__init__(*args, **kwargs)
    print("B1", b1)


B1(a1=6, b1=5, b="hello", a=None)

Result:

A None
B hello
A1 6
B1 5

You can also use them positionally:

B1(5, 6, b="hello", a=None)

but you have to remember the MRO, it's really confusing. You can avoid this by using keyword-only parameters:

class A(object):
  def __init__(self, *args, a, **kwargs):
    print("A", a)

etcetera.

I can be a little annoying, but I noticed that people forgot every time to use *args and **kwargs when they override a method, while it's one of few really useful and sane use of these 'magic variables'.

?: ?? Operators Instead Of IF|ELSE

The ?: Operator returns one of two values depending on the value of a Boolean expression.

Condition-Expression ? Expression1 : Expression2

Find here more on ?: operator, also know as a Ternary Operator:

If '<selector>' is an Angular component, then verify that it is part of this module

This might be late ,but i got the same issue but I rebuild(ng serve) the project and the error was gone

Drop Down Menu/Text Field in one

Option 1

Include the script from dhtmlgoodies and initialize like this:

<input type="text" name="myText" value="Norway"
       selectBoxOptions="Canada;Denmark;Finland;Germany;Mexico"> 
createEditableSelect(document.forms[0].myText);

Option 2

Here's a custom solution which combines a <select> element and <input> element, styles them, and toggles back and forth via JavaScript

<div style="position:relative;width:200px;height:25px;border:0;padding:0;margin:0;">
  <select style="position:absolute;top:0px;left:0px;width:200px; height:25px;line-height:20px;margin:0;padding:0;"
          onchange="document.getElementById('displayValue').value=this.options[this.selectedIndex].text; document.getElementById('idValue').value=this.options[this.selectedIndex].value;">
    <option></option>
    <option value="one">one</option>
    <option value="two">two</option>
    <option value="three">three</option>
  </select>
  <input type="text" name="displayValue" id="displayValue" 
         placeholder="add/select a value" onfocus="this.select()"
         style="position:absolute;top:0px;left:0px;width:183px;width:180px\9;#width:180px;height:23px; height:21px\9;#height:18px;border:1px solid #556;"  >
  <input name="idValue" id="idValue" type="hidden">
</div>

How to convert TimeStamp to Date in Java?

I feel obliged to respond since other answers seem to be time zone agnostic which a real world application cannot afford to be. To make timestamp-to-date conversion correct when the timestamp and the JVM are using different time zones you can use Joda Time's LocalDateTime (or LocalDateTime in Java8) like this:

Timestamp timestamp = resultSet.getTimestamp("time_column");
LocalDateTime localDateTime = new LocalDateTime(timestamp);
Date trueDate = localDateTime.toDate(DateTimeZone.UTC.toTimeZone());

The example below assumes that the timestamp is UTC (as is usually the case with databases). In case your timestamps are in different timezone, change the timezone parameter of the toDatestatement.

Should I make HTML Anchors with 'name' or 'id'?

ID method will not work on older browsers, anchor name method will be deprecated in newer HTML versions... I'd go with id.

vuejs update parent data from child component

It is also possible to pass props as Object or Array. In this case data will be two-way binded:

(This is noted at the end of topic: https://vuejs.org/v2/guide/components.html#One-Way-Data-Flow )

_x000D_
_x000D_
Vue.component('child', {_x000D_
  template: '#child',_x000D_
  props: {post: Object},_x000D_
  methods: {_x000D_
    updateValue: function () {_x000D_
      this.$emit('changed');_x000D_
    }_x000D_
  }_x000D_
});_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    post: {msg: 'hello'},_x000D_
    changed: false_x000D_
  },_x000D_
  methods: {_x000D_
    saveChanges() {_x000D_
        this.changed = true;_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
  <p>Parent value: {{post.msg}}</p>_x000D_
  <p v-if="changed == true">Parent msg: Data been changed - received signal from child!</p>_x000D_
  <child :post="post" v-on:changed="saveChanges"></child>_x000D_
</div>_x000D_
_x000D_
<template id="child">_x000D_
   <input type="text" v-model="post.msg" v-on:input="updateValue()">_x000D_
</template>
_x000D_
_x000D_
_x000D_

How to _really_ programmatically change primary and accent color in Android Lollipop?

I've created some solution to make any-color themes, maybe this can be useful for somebody. API 9+

1. first create "res/values-v9/" and put there this file: styles.xml and regular "res/values" folder will be used with your styles.

2. put this code in your res/values/styles.xml:

<resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light">
        <item name="colorPrimary">#000</item>
        <item name="colorPrimaryDark">#000</item>
        <item name="colorAccent">#000</item>
        <item name="android:windowAnimationStyle">@style/WindowAnimationTransition</item>
    </style>

    <style name="AppThemeDarkActionBar" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">#000</item>
        <item name="colorPrimaryDark">#000</item>
        <item name="colorAccent">#000</item>
        <item name="android:windowAnimationStyle">@style/WindowAnimationTransition</item>
    </style>

    <style name="WindowAnimationTransition">
        <item name="android:windowEnterAnimation">@android:anim/fade_in</item>
        <item name="android:windowExitAnimation">@android:anim/fade_out</item>
    </style>
</resources>

3. in to AndroidManifest:

<application android:theme="@style/AppThemeDarkActionBar">

4. create a new class with name "ThemeColors.java"

public class ThemeColors {

    private static final String NAME = "ThemeColors", KEY = "color";

    @ColorInt
    public int color;

    public ThemeColors(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
        String stringColor = sharedPreferences.getString(KEY, "004bff");
        color = Color.parseColor("#" + stringColor);

        if (isLightActionBar()) context.setTheme(R.style.AppTheme);
        context.setTheme(context.getResources().getIdentifier("T_" + stringColor, "style", context.getPackageName()));
    }

    public static void setNewThemeColor(Activity activity, int red, int green, int blue) {
        int colorStep = 15;
        red = Math.round(red / colorStep) * colorStep;
        green = Math.round(green / colorStep) * colorStep;
        blue = Math.round(blue / colorStep) * colorStep;

        String stringColor = Integer.toHexString(Color.rgb(red, green, blue)).substring(2);
        SharedPreferences.Editor editor = activity.getSharedPreferences(NAME, Context.MODE_PRIVATE).edit();
        editor.putString(KEY, stringColor);
        editor.apply();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) activity.recreate();
        else {
            Intent i = activity.getPackageManager().getLaunchIntentForPackage(activity.getPackageName());
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            activity.startActivity(i);
        }
    }

    private boolean isLightActionBar() {// Checking if title text color will be black
        int rgb = (Color.red(color) + Color.green(color) + Color.blue(color)) / 3;
        return rgb > 210;
    }
}

5. MainActivity:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new ThemeColors(this);
        setContentView(R.layout.activity_main);
    }

    public void buttonClick(View view){
        int red= new Random().nextInt(255);
        int green= new Random().nextInt(255);
        int blue= new Random().nextInt(255);
        ThemeColors.setNewThemeColor(MainActivity.this, red, green, blue);
    }
}

To change color, just replace Random with your RGB, Hope this helps.

enter image description here

There is a complete example: ColorTest.zip

Detect all changes to a <input type="text"> (immediately) using JQuery

Although this question was posted 10 years ago, I believe that it still needs some improvements. So here is my solution.

$(document).on('propertychange change click keyup input paste', 'selector', function (e) {
    // Do something here
});

The only problem with this solution is, it won't trigger if the value changes from javascript like $('selector').val('some value'). You can fire any event to your selector when you change the value from javascript.

$(selector).val('some value');
// fire event
$(selector).trigger('change');

No String-argument constructor/factory method to deserialize from String value ('')

This exception says that you are trying to deserialize the object "Address" from string "\"\"" instead of an object description like "{…}". The deserializer can't find a constructor of Address with String argument. You have to replace "" by {} to avoid this error.

Getting byte array through input type = file

This is simple way to convert files to Base64 and avoid "maximum call stack size exceeded at FileReader.reader.onload" with the file has big size.

_x000D_
_x000D_
document.querySelector('#fileInput').addEventListener('change',   function () {_x000D_
_x000D_
    var reader = new FileReader();_x000D_
    var selectedFile = this.files[0];_x000D_
_x000D_
    reader.onload = function () {_x000D_
        var comma = this.result.indexOf(',');_x000D_
        var base64 = this.result.substr(comma + 1);_x000D_
        console.log(base64);_x000D_
    }_x000D_
    reader.readAsDataURL(selectedFile);_x000D_
}, false);
_x000D_
<input id="fileInput" type="file" />
_x000D_
_x000D_
_x000D_

In Matplotlib, what does the argument mean in fig.add_subplot(111)?

enter image description here

import matplotlib.pyplot as plt
plt.figure(figsize=(8,8))
plt.subplot(3,2,1)
plt.subplot(3,2,3)
plt.subplot(3,2,5)
plt.subplot(2,2,2)
plt.subplot(2,2,4)

The first code creates the first subplot in a layout that has 3 rows and 2 columns.

The three graphs in the first column denote the 3 rows. The second plot comes just below the first plot in the same column and so on.

The last two plots have arguments (2, 2) denoting that the second column has only two rows, the position parameters move row wise.

When or Why to use a "SET DEFINE OFF" in Oracle Database

Here is the example:

SQL> set define off;
SQL> select * from dual where dummy='&var';

no rows selected

SQL> set define on
SQL> /
Enter value for var: X
old   1: select * from dual where dummy='&var'
new   1: select * from dual where dummy='X'

D
-
X

With set define off, it took a row with &var value, prompted a user to enter a value for it and replaced &var with the entered value (in this case, X).

How to extract one column of a csv file

You can't do it without a full CSV parser.

Given final block not properly padded

I met this issue due to operation system, simple to different platform about JRE implementation.

new SecureRandom(key.getBytes())

will get the same value in Windows, while it's different in Linux. So in Linux need to be changed to

SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(key.getBytes());
kgen.init(128, secureRandom);

"SHA1PRNG" is the algorithm used, you can refer here for more info about algorithms.

Find indices of elements equal to zero in a NumPy array

There is np.argwhere,

import numpy as np
arr = np.array([[1,2,3], [0, 1, 0], [7, 0, 2]])
np.argwhere(arr == 0)

which returns all found indices as rows:

array([[1, 0],    # Indices of the first zero
       [1, 2],    # Indices of the second zero
       [2, 1]],   # Indices of the third zero
      dtype=int64)

How to set the max size of upload file

put this in your application.yml file to allow uploads of files up to 900 MB

server:
  servlet:
    multipart:
      enabled: true
      max-file-size: 900000000  #900M
      max-request-size: 900000000

Subtracting 1 day from a timestamp date

Use the INTERVAL type to it. E.g:

--yesterday
SELECT NOW() - INTERVAL '1 DAY';

--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;

Then you can do the following on your query:

SELECT 
    org_id,
    count(accounts) AS COUNT,
    ((date_at) - INTERVAL '1 DAY') AS dateat
FROM 
    sourcetable
WHERE 
    date_at <= now() - INTERVAL '130 DAYS'
GROUP BY 
    org_id,
    dateat;


TIPS

Tip 1

You can append multiple operands. E.g.: how to get last day of current month?

SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';

Tip 2

You can also create an interval using make_interval function, useful when you need to create it at runtime (not using literals):

SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);


More info:

Date/Time Functions and Operators

datatype-datetime (Especial values).

Using Mockito to stub and execute methods for testing

You've nearly got it. The problem is that the Class Under Test (CUT) is not built for unit testing - it has not really been TDD'd.

Think of it like this…

  • I need to test a function of a class - let's call it myFunction
  • That function makes a call to a function on another class/service/database
  • That function also calls another method on the CUT

In the unit test

  • Should create a concrete CUT or @Spy on it
  • You can @Mock all of the other class/service/database (i.e. external dependencies)
  • You could stub the other function called in the CUT but it is not really how unit testing should be done

In order to avoid executing code that you are not strictly testing, you could abstract that code away into something that can be @Mocked.

In this very simple example, a function that creates an object will be difficult to test

public void doSomethingCool(String foo) {
    MyObject obj = new MyObject(foo);

    // can't do much with obj in a unit test unless it is returned
}

But a function that uses a service to get MyObject is easy to test, as we have abstracted the difficult/impossible to test code into something that makes this method testable.

public void doSomethingCool(String foo) {
    MyObject obj = MyObjectService.getMeAnObject(foo);
}

as MyObjectService can be mocked and also verified that .getMeAnObject() is called with the foo variable.

How do I print the percent sign(%) in c

Try printing out this way

printf("%%");

What is %timeit in python?

I just wanted to add a very subtle point about %%timeit. Given it runs the "magics" on the cell, you'll get error...

UsageError: Line magic function %%timeit not found

...if there is any code/comment lines above %%timeit. In other words, ensure that %%timeit is the first command in your cell.

I know it's a small point all the experts will say duh to, but just wanted to add my half a cent for the young wizards starting out with magic tricks.

Fetch the row which has the Max value for a column

(T-SQL) First get all the users and their maxdate. Join with the table to find the corresponding values for the users on the maxdates.

create table users (userid int , value int , date datetime)
insert into users values (1, 1, '20010101')
insert into users values (1, 2, '20020101')
insert into users values (2, 1, '20010101')
insert into users values (2, 3, '20030101')

select T1.userid, T1.value, T1.date 
    from users T1,
    (select max(date) as maxdate, userid from users group by userid) T2    
    where T1.userid= T2.userid and T1.date = T2.maxdate

results:

userid      value       date                                    
----------- ----------- -------------------------- 
2           3           2003-01-01 00:00:00.000
1           2           2002-01-01 00:00:00.000

How to insert pandas dataframe via mysqldb into database?

You might output your DataFrame as a csv file and then use mysqlimport to import your csv into your mysql.

EDIT

Seems pandas's build-in sql util provide a write_frame function but only works in sqlite.

I found something useful, you might try this

In nodeJs is there a way to loop through an array without using array size?

What you probably want is for...of, a relatively new construct built for the express purpose of enumerating the values of iterable objects:

_x000D_
_x000D_
let myArray = ["a","b","c","d"];_x000D_
for (let item of myArray) {_x000D_
  console.log(item);_x000D_
}
_x000D_
_x000D_
_x000D_

... as distinct from for...in, which enumerates property names (presumably1 numeric indices in the case of arrays). Your loop displayed unexpected results because you didn't use the property names to get the corresponding values via bracket notation... but you could have:

_x000D_
_x000D_
let myArray = ["a","b","c","d"];_x000D_
for (let key in myArray) {_x000D_
  let value =  myArray[key]; // get the value by key_x000D_
  console.log("key: %o, value: %o", key, value);_x000D_
}
_x000D_
_x000D_
_x000D_

1 Unfortunately, someone may have added enumerable properties to the array or its prototype chain which are not numeric indices... or they may have assigned an index leaving unassigned indices in the interim range. The issues are explained pretty well here. The main takeaway is that it's best to loop explicitly from 0 to array.length - 1 rather than using for...in.

So, this is not (as I'd originally thought) an academic question, i.e.:

Without regard for practicality, is it possible to avoid length when iterating over an array?

According to your comment (emphasis mine):

[...] why do I need to calculate the size of an array whereas the interpreter can know it.

You have a misguided aversion to Array.length. It's not calculated on the fly; it's updated whenever the length of the array changes. You're not going to see performance gains by avoiding it (apart from caching the array length rather than accessing the property):

loop test

Now, even if you did get some marginal performance increase, I doubt it would be enough to justify the risk of dealing with the aforementioned issues.

How to SELECT by MAX(date)?

This is a very old question but I came here due to the same issue, so I am leaving this here to help any others.

I was trying to optimize the query because it was taking over 5 minutes to query the DB due to the amount of data. My query was similar to the accepted answer's query. Pablo's comment pushed me in the right direction and my 5 minute query became 0.016 seconds. So to help any others that are having very long query times try using an uncorrelated subquery.

The example for the OP would be:

SELECT 
    a.report_id, 
    a.computer_id, 
    a.date_entered
FROM reports AS a
    JOIN (
        SELECT report_id, computer_id, MAX(date_entered) as max_date_entered
        FROM reports
        GROUP BY report_id, computer_id
    ) as b
WHERE a.report_id = b.report_id
    AND a.computer_id = b.computer_id
    AND a.date_entered = b.max_date_entered

Thank you Pablo for the comment. You saved me big time!

How can the default node version be set using NVM?

The current answers did not solve the problem for me, because I had node installed in /usr/bin/node and /usr/local/bin/node - so the system always resolved these first, and ignored the nvm version.

I solved the issue by moving the existing versions to /usr/bin/node-system and /usr/local/bin/node-system

Then I had no node command anymore, until I used nvm use :(

I solved this issue by creating a symlink to the version that would be installed by nvm.

sudo mv /usr/local/bin/node /usr/local/bin/node-system    
sudo mv /usr/bin/node /usr/bin/node-system 
nvm use node
  Now using node v12.20.1 (npm v6.14.10)
which node
  /home/paul/.nvm/versions/node/v12.20.1/bin/node
sudo ln -s /home/paul/.nvm/versions/node/v12.20.1/bin/node /usr/bin/node

Then open a new shell

node -v
  v12.20.1

How to store Query Result in variable using mysql

Select count(*) from table_name into @var1; 
Select @var1;

Start and stop a timer PHP

You can use microtime and calculate the difference:

$time_pre = microtime(true);
exec(...);
$time_post = microtime(true);
$exec_time = $time_post - $time_pre;

Here's the PHP docs for microtime: http://php.net/manual/en/function.microtime.php

Push item to associative array in PHP

This is a cool function

function array_push_assoc($array, $key, $value){
   $array[$key] = $value;
   return $array;
}

Just use

$myarray = array_push_assoc($myarray, 'h', 'hello');

Credits & Explanation

How do you round to 1 decimal place in Javascript?

In general, decimal rounding is done by scaling: round(num * p) / p

Naive implementation

Using the following function with halfway numbers, you will get either the upper rounded value as expected, or the lower rounded value sometimes depending on the input.

This inconsistency in rounding may introduce hard to detect bugs in the client code.

_x000D_
_x000D_
function naiveRound(num, decimalPlaces) {
    var p = Math.pow(10, decimalPlaces);
    return Math.round(num * p) / p;
}

console.log( naiveRound(1.245, 2) );  // 1.25 correct (rounded as expected)
console.log( naiveRound(1.255, 2) );  // 1.25 incorrect (should be 1.26)
_x000D_
_x000D_
_x000D_

Better implementations

By converting the number to a string in the exponential notation, positive numbers are rounded as expected. But, be aware that negative numbers round differently than positive numbers.

In fact, it performs what is basically equivalent to "round half up" as the rule, you will see that round(-1.005, 2) evaluates to -1 even though round(1.005, 2) evaluates to 1.01. The lodash _.round method uses this technique.

_x000D_
_x000D_
/**
 * Round half up ('round half towards positive infinity')
 * Uses exponential notation to avoid floating-point issues.
 * Negative numbers round differently than positive numbers.
 */
function round(num, decimalPlaces) {
    num = Math.round(num + "e" + decimalPlaces);
    return Number(num + "e" + -decimalPlaces);
}

// test rounding of half
console.log( round(0.5, 0) );  // 1
console.log( round(-0.5, 0) ); // 0

// testing edge cases
console.log( round(1.005, 2) );   // 1.01
console.log( round(2.175, 2) );   // 2.18
console.log( round(5.015, 2) );   // 5.02

console.log( round(-1.005, 2) );  // -1
console.log( round(-2.175, 2) );  // -2.17
console.log( round(-5.015, 2) );  // -5.01
_x000D_
_x000D_
_x000D_

If you want the usual behavior when rounding negative numbers, you would need to convert negative numbers to positive before calling Math.round(), and then convert them back to negative numbers before returning.

// Round half away from zero
function round(num, decimalPlaces) {
    num = Math.round(Math.abs(num) + "e" + decimalPlaces) * Math.sign(num);
    return Number(num + "e" + -decimalPlaces);
}

There is a different purely mathematical technique to perform round-to-nearest (using "round half away from zero"), in which epsilon correction is applied before calling the rounding function.

Simply, we add the smallest possible float value (= 1.0 ulp; unit in the last place) to the number before rounding. This moves to the next representable value after the number, away from zero.

_x000D_
_x000D_
/**
 * Round half away from zero ('commercial' rounding)
 * Uses correction to offset floating-point inaccuracies.
 * Works symmetrically for positive and negative numbers.
 */
function round(num, decimalPlaces) {
    var p = Math.pow(10, decimalPlaces);
    var e = Number.EPSILON * num * p;
    return Math.round((num * p) + e) / p;
}

// test rounding of half
console.log( round(0.5, 0) );  // 1
console.log( round(-0.5, 0) ); // -1

// testing edge cases
console.log( round(1.005, 2) );  // 1.01
console.log( round(2.175, 2) );  // 2.18
console.log( round(5.015, 2) );  // 5.02

console.log( round(-1.005, 2) ); // -1.01
console.log( round(-2.175, 2) ); // -2.18
console.log( round(-5.015, 2) ); // -5.02
_x000D_
_x000D_
_x000D_

This is needed to offset the implicit round-off error that may occur during encoding of decimal numbers, particularly those having "5" in the last decimal position, like 1.005, 2.675 and 16.235. Actually, 1.005 in decimal system is encoded to 1.0049999999999999 in 64-bit binary float; while, 1234567.005 in decimal system is encoded to 1234567.0049999998882413 in 64-bit binary float.

It is worth noting that the maximum binary round-off error is dependent upon (1) the magnitude of the number and (2) the relative machine epsilon (2^-52).

Count of "Defined" Array Elements

In recent browser, you can use filter

var size = arr.filter(function(value) { return value !== undefined }).length;

console.log(size);

Another method, if the browser supports indexOf for arrays:

var size = arr.slice(0).sort().indexOf(undefined);

If for absurd you have one-digit-only elements in the array, you could use that dirty trick:

console.log(arr.join("").length);

There are several methods you can use, but at the end we have to see if it's really worthy doing these instead of a loop.

Finding sum of elements in Swift array

Swift3 has changed to :

let multiples = [...]
sum = multiples.reduce(0, +)

What is the best way to declare global variable in Vue.js?

Warning: The following answer is using Vue 1.x. The twoWay data mutation is removed from Vue 2.x (fortunately!).

In case of "global" variables—that are attached to the global object, which is the window object in web browsers—the most reliable way to declare the variable is to set it on the global object explicitly:

window.hostname = 'foo';

However form Vue's hierarchy perspective (the root view Model and nested components) the data can be passed downwards (and can be mutated upwards if twoWay binding is specified).

For instance if the root viewModel has a hostname data, the value can be bound to a nested component with v-bind directive as v-bind:hostname="hostname" or in short :hostname="hostname".

And within the component the bound value can be accessed through component's props property.

Eventually the data will be proxied to this.hostname and can be used inside the current Vue instance if needed.

_x000D_
_x000D_
var theGrandChild = Vue.extend({_x000D_
  template: '<h3>The nested component has also a "{{foo}}" and a "{{bar}}"</h3>',_x000D_
    props: ['foo', 'bar']_x000D_
});_x000D_
_x000D_
var theChild = Vue.extend({_x000D_
  template: '<h2>My awesome component has a "{{foo}}"</h2> \_x000D_
             <the-grandchild :foo="foo" :bar="bar"></the-grandchild>',_x000D_
  props: ['foo'],_x000D_
  data: function() {_x000D_
    return {_x000D_
      bar: 'bar'_x000D_
    };_x000D_
  },_x000D_
  components: {_x000D_
    'the-grandchild': theGrandChild_x000D_
  }_x000D_
});_x000D_
_x000D_
_x000D_
// the root view model_x000D_
new Vue({_x000D_
  el: 'body',_x000D_
  data: {_x000D_
    foo: 'foo'_x000D_
  },_x000D_
  components: {_x000D_
    'the-child': theChild_x000D_
  }_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.16/vue.js"></script>_x000D_
<h1>The root view model has a "{{foo}}"</h1>_x000D_
<the-child :foo="foo"></the-child>
_x000D_
_x000D_
_x000D_


In cases that we need to mutate the parent's data upwards, we can add a .sync modifier to our binding declaration like :foo.sync="foo" and specify that the given 'props' is supposed to be a twoWay bound data.

Hence by mutating the data in a component, the parent's data would be changed respectively.

For instance:

_x000D_
_x000D_
var theGrandChild = Vue.extend({_x000D_
  template: '<h3>The nested component has also a "{{foo}}" and a "{{bar}}"</h3> \_x000D_
             <input v-model="foo" type="text">',_x000D_
    props: {_x000D_
      'foo': {_x000D_
        twoWay: true_x000D_
      },  _x000D_
      'bar': {}_x000D_
    }_x000D_
});_x000D_
_x000D_
var theChild = Vue.extend({_x000D_
  template: '<h2>My awesome component has a "{{foo}}"</h2> \_x000D_
             <the-grandchild :foo.sync="foo" :bar="bar"></the-grandchild>',_x000D_
  props: {_x000D_
    'foo': {_x000D_
      twoWay: true_x000D_
    }_x000D_
  },_x000D_
  data: function() {_x000D_
    return { bar: 'bar' };_x000D_
  },  _x000D_
  components: {_x000D_
    'the-grandchild': theGrandChild_x000D_
  }_x000D_
});_x000D_
_x000D_
// the root view model_x000D_
new Vue({_x000D_
  el: 'body',_x000D_
  data: {_x000D_
    foo: 'foo'_x000D_
  },_x000D_
  components: {_x000D_
    'the-child': theChild_x000D_
  }_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.16/vue.js"></script>_x000D_
<h1>The root view model has a "{{foo}}"</h1>_x000D_
<the-child :foo.sync="foo"></the-child>
_x000D_
_x000D_
_x000D_

Check date with todays date

another way to do this operation:

public class TimeUtils {

    /**
     * @param timestamp
     * @return
     */
    public static boolean isToday(long timestamp) {
        Calendar now = Calendar.getInstance();
        Calendar timeToCheck = Calendar.getInstance();
        timeToCheck.setTimeInMillis(timestamp);
        return (now.get(Calendar.YEAR) == timeToCheck.get(Calendar.YEAR)
                && now.get(Calendar.DAY_OF_YEAR) == timeToCheck.get(Calendar.DAY_OF_YEAR));
    }

}

HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers

I had the same issue, and spent quite a bit of time trying to track down the solution. I had Anonymous Authentication set up at two different levels with two different users. Make sure that you're not overwriting your set up at a lower level.

Android Studio - Importing external Library/Jar

You don't need to close the project and go to command line to invoke grade:clean. Go to Build-> Rebuild Project

TypeError: can't pickle _thread.lock objects

I had the same problem with Pool() in Python 3.6.3.

Error received: TypeError: can't pickle _thread.RLock objects

Let's say we want to add some number num_to_add to each element of some list num_list in parallel. The code is schematically like this:

class DataGenerator:
    def __init__(self, num_list, num_to_add)
        self.num_list = num_list # e.g. [4,2,5,7]
        self.num_to_add = num_to_add # e.g. 1 

        self.run()

    def run(self):
        new_num_list = Manager().list()

        pool = Pool(processes=50)
        results = [pool.apply_async(run_parallel, (num, new_num_list)) 
                      for num in num_list]
        roots = [r.get() for r in results]
        pool.close()
        pool.terminate()
        pool.join()

    def run_parallel(self, num, shared_new_num_list):
        new_num = num + self.num_to_add # uses class parameter
        shared_new_num_list.append(new_num)

The problem here is that self in function run_parallel() can't be pickled as it is a class instance. Moving this parallelized function run_parallel() out of the class helped. But it's not the best solution as this function probably needs to use class parameters like self.num_to_add and then you have to pass it as an argument.

Solution:

def run_parallel(num, shared_new_num_list, to_add): # to_add is passed as an argument
    new_num = num + to_add
    shared_new_num_list.append(new_num)

class DataGenerator:
    def __init__(self, num_list, num_to_add)
        self.num_list = num_list # e.g. [4,2,5,7]
        self.num_to_add = num_to_add # e.g. 1

        self.run()

    def run(self):
        new_num_list = Manager().list()

        pool = Pool(processes=50)
        results = [pool.apply_async(run_parallel, (num, new_num_list, self.num_to_add)) # num_to_add is passed as an argument
                      for num in num_list]
        roots = [r.get() for r in results]
        pool.close()
        pool.terminate()
        pool.join()

Other suggestions above didn't help me.

Counting number of lines, words, and characters in a text file

I'm no Java expert, but I would presume that the .hasNext, .hasNextLine and .hasNextByte all use and increment the same file position indicator. You'll need to reset that, either by creating a new Scanner as Aashray mentioned, or using a RandomAccessFile and calling file.seek(0); after each loop.

Maven in Eclipse: step by step installation

Maven Eclipse plugin installation step by step:

Open Eclipse IDE Click Help -> Install New Software Click Add button at top right corner At pop up: fill up Name as you want and Location as http://download.eclipse.org/technology/m2e/milestones/1.0 Now click OK And follow the instruction

C++ Cout & Cin & System "Ambiguous"

This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.

Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.

In this case I'd ask why you're including both cstdlib and stdlib.h; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib puts them in the namespace std in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!

Anyway, your use of using namespace std (which I would recommend against, in future) means that std::system from cstdlib now conflicts with system from stdlib.h. I can't explain what's going on with std::cout and std::cin.

Try removing #include <stdlib.h> and see what happens.

If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.

Validation of file extension before uploading file

It's possible to check only the file extension, but user can easily rename virus.exe to virus.jpg and "pass" the validation.

For what it's worth, here is the code to check file extension and abort if does not meet one of the valid extensions: (choose invalid file and try to submit to see the alert in action)

_x000D_
_x000D_
var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];    _x000D_
function Validate(oForm) {_x000D_
    var arrInputs = oForm.getElementsByTagName("input");_x000D_
    for (var i = 0; i < arrInputs.length; i++) {_x000D_
        var oInput = arrInputs[i];_x000D_
        if (oInput.type == "file") {_x000D_
            var sFileName = oInput.value;_x000D_
            if (sFileName.length > 0) {_x000D_
                var blnValid = false;_x000D_
                for (var j = 0; j < _validFileExtensions.length; j++) {_x000D_
                    var sCurExtension = _validFileExtensions[j];_x000D_
                    if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {_x000D_
                        blnValid = true;_x000D_
                        break;_x000D_
                    }_x000D_
                }_x000D_
                _x000D_
                if (!blnValid) {_x000D_
                    alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));_x000D_
                    return false;_x000D_
                }_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
  _x000D_
    return true;_x000D_
}
_x000D_
<form onsubmit="return Validate(this);">_x000D_
  File: <input type="file" name="my file" /><br />_x000D_
  <input type="submit" value="Submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Note, the code will allow user to send without choosing file... if it's required, remove the line if (sFileName.length > 0) { and it's associate closing bracket. The code will validate any file input in the form, regardless of its name.

This can be done with jQuery in less lines, but I'm comfortable enough with "raw" JavaScript and the final result is the same.

In case you have more files, or want to trigger the check upon changing the file and not only in form submission, use such code instead:

_x000D_
_x000D_
var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];    _x000D_
function ValidateSingleInput(oInput) {_x000D_
    if (oInput.type == "file") {_x000D_
        var sFileName = oInput.value;_x000D_
         if (sFileName.length > 0) {_x000D_
            var blnValid = false;_x000D_
            for (var j = 0; j < _validFileExtensions.length; j++) {_x000D_
                var sCurExtension = _validFileExtensions[j];_x000D_
                if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {_x000D_
                    blnValid = true;_x000D_
                    break;_x000D_
                }_x000D_
            }_x000D_
             _x000D_
            if (!blnValid) {_x000D_
                alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));_x000D_
                oInput.value = "";_x000D_
                return false;_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
    return true;_x000D_
}
_x000D_
File 1: <input type="file" name="file1" onchange="ValidateSingleInput(this);" /><br />_x000D_
File 2: <input type="file" name="file2" onchange="ValidateSingleInput(this);" /><br />_x000D_
File 3: <input type="file" name="file3" onchange="ValidateSingleInput(this);" /><br />
_x000D_
_x000D_
_x000D_

This will show alert and reset the input in case of invalid file extension.

How to see full query from SHOW PROCESSLIST

I just read in the MySQL documentation that SHOW FULL PROCESSLIST by default only lists the threads from your current user connection.

Quote from the MySQL SHOW FULL PROCESSLIST documentation:

If you have the PROCESS privilege, you can see all threads.

So you can enable the Process_priv column in your mysql.user table. Remember to execute FLUSH PRIVILEGES afterwards :)

How to connect from windows command prompt to mysql command line

Go to your MySQL directory. As in my case its...

cd C:\Program Files\MySQL\MySQL Server 8.0\bin
mysql -uroot -p

root can be changed to your user whatever MySQL user you've set.

It will ask for your password. If you have a password, Type your password and press "Enter", If no password set just press Enter without typing. You will be connected to MySQL.

There is another way to directly connect to MySQL without every time, going to the directory and typing down the commands.

Create a .bat file. First, add your path to MySQL. In my case it was,

cd C:\Program Files\MySQL\MySQL Server 8.0\bin

Then add these two lines

net start MySQL 
mysql -u root -p

If you don't want to type password every time you can simply add password with -p e.g. -proot (in case root was the password) but that is not recommended.

Also, If you want to connect to other host than local (staging/production server). You can also add -h22.345.80.09 E.g. 22.345.80.09 is your server ip.

net start MySQL 
mysql -u root -p -h22.345.80.0

Save the file. Just double click to open and connect directly to MySQL.

The target principal name is incorrect. Cannot generate SSPI context

I have tried all the solutions here and none of them have worked yet. A workaround that is working is to Click Connect, enter the server name, select Options, Connection Properties tab. Set the "Network protocol" to "Named Pipes". This allows users to remote connect using their network credentials. I'll post an update when I get a fix.

How can I pop-up a print dialog box using Javascript?

I know the answer has already been provided. But I just wanted to elaborate with regards to doing this in a Blazor app (razor)...

You will need to inject IJSRuntime, in order to perform JSInterop (running javascript functions from C#)

IN YOUR RAZOR PAGE:

@inject IJSRuntime JSRuntime

Once you have that injected, create a button with a click event that calls a C# method:

<MatFAB Icon="@MatIconNames.Print" OnClick="@(async () => await print())"></MatFAB>

(or something more simple if you don't use MatBlazor)

<button @onclick="@(async () => await print())">PRINT</button>

For the C# method:

public async Task print()
{
    await JSRuntime.InvokeVoidAsync("printDocument");
}

NOW IN YOUR index.html:

<script>
    function printDocument() {
        window.print();
    }
</script>

Something to note, the reason the onclick events are asynchronous is because IJSRuntime awaits it's calls such as InvokeVoidAsync

PS: If you wanted to message box in asp net core for instance:

await JSRuntime.InvokeAsync<string>("alert", "Hello user, this is the message box");

To have a confirm message box:

bool question = await JSRuntime.InvokeAsync<bool>("confirm", "Are you sure you want to do this?");
    if(question == true)
    {
        //user clicked yes
    }
    else
    {
        //user clicked no
    }

Hope this helps :)

add/remove active class for ul list with jquery?

you can use siblings and removeClass method

$('.nav-link li').click(function() {
    $(this).addClass('active').siblings().removeClass('active');
});

Java file path in Linux

I think Todd is correct, but I think there's one other thing you should consider. You can reliably get the home directory from the JVM at runtime, and then you can create files objects relative to that location. It's not that much more trouble, and it's something you'll appreciate if you ever move to another computer or operating system.

File homedir = new File(System.getProperty("user.home"));
File fileToRead = new File(homedir, "java/ex.txt");

Copying text to the clipboard using Java

I found a better way of doing it so you can get a input from a txtbox or have something be generated in that text box and be able to click a button to do it.!

import java.awt.datatransfer.*;
import java.awt.Toolkit;

private void /* Action performed when the copy to clipboard button is clicked */ {
    String ctc = txtCommand.getText().toString();
    StringSelection stringSelection = new StringSelection(ctc);
    Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
    clpbrd.setContents(stringSelection, null);
}

// txtCommand is the variable of a text box

How to compile Tensorflow with SSE4.2 and AVX instructions?

2.0 COMPATIBLE SOLUTION:

Execute the below commands in Terminal (Linux/MacOS) or in Command Prompt (Windows) to install Tensorflow 2.0 using Bazel:

git clone https://github.com/tensorflow/tensorflow.git
cd tensorflow

#The repo defaults to the master development branch. You can also checkout a release branch to build:
git checkout r2.0

#Configure the Build => Use the Below line for Windows Machine
python ./configure.py 

#Configure the Build => Use the Below line for Linux/MacOS Machine
./configure
#This script prompts you for the location of TensorFlow dependencies and asks for additional build configuration options. 

#Build Tensorflow package

#CPU support
bazel build --config=opt //tensorflow/tools/pip_package:build_pip_package 

#GPU support
bazel build --config=opt --config=cuda --define=no_tensorflow_py_deps=true //tensorflow/tools/pip_package:build_pip_package

How to convert a string to an integer in JavaScript?

There are many ways in JavaScript to convert a string to a number value... All simple and handy, choose the way which one works for you:

var num = Number("999.5"); //999.5
var num = parseInt("999.5", 10); //999
var num = parseFloat("999.5"); //999.5
var num = +"999.5"; //999.5

Also any Math operation converts them to number, for example...

var num = "999.5" / 1; //999.5
var num = "999.5" * 1; //999.5
var num = "999.5" - 1 + 1; //999.5
var num = "999.5" - 0; //999.5
var num = Math.floor("999.5"); //999
var num = ~~"999.5"; //999

My prefer way is using + sign, which is the elegant way to convert a string to number in JavaScript.

How to add a JAR in NetBeans

You want to add libraries to your project and in doing so you have two options as you yourself identified:

Compile-time libraries are libraries which is needed to compile your application. They are not included when your application is assembled (e.g., into a war-file). Libraries of this kind must be provided by the container running your project.

This is useful in situation when you want to vary API and implementation, or when the library is supplied by the container (which is typically the case with javax.servlet which is required to compile but provided by the application server, e.g., Apache Tomcat).

Run-time libraries are libraries which is needed both for compilation and when running your project. This is probably what you want in most cases. If for instance your project is packaged into a war/ear, then these libraries will be included in the package.

As for the other alernatives you have either global libraries using Library Manageror jdk libraries. The latter is simply your regular java libraries, while the former is just a way for your to store a set of libraries under a common name. For all your future projects, instead of manually assigning the libraries you can simply select to import them from your Library Manager.

IsNothing versus Is Nothing

VB is full of things like that trying to make it both "like English" and comfortable for people who are used to languages that use () and {} a lot. And on the other side, as you already probably know, most of the time you can use () with function calls if you want to, but don't have to.

I prefer IsNothing()... but I use C and C#, so that's just what is comfortable. And I think it's more readable. But go with whatever feels more comfortable to you.

How to stop/terminate a python script from running?

Press Ctrl+Alt+Delete and Task Manager will pop up. Find the Python command running, right click on it and and click Stop or Kill.

Make TextBox uneditable

You can try using:

textBox.ReadOnly = true;
textBox.BackColor = System.Drawing.SystemColors.Window;

The last line is only neccessary if you want a non-grey background color.

Converting between strings and ArrayBuffers

You can use TextEncoder and TextDecoder from the Encoding standard, which is polyfilled by the stringencoding library, to convert string to and from ArrayBuffers:

var uint8array = new TextEncoder().encode(string);
var string = new TextDecoder(encoding).decode(uint8array);

How to see if an object is an array without using reflection?

One can access each element of an array separately using the following code:

Object o=...;
if ( o.getClass().isArray() ) {
    for(int i=0; i<Array.getLength(o); i++){
        System.out.println(Array.get(o, i));
    }
}

Notice that it is unnecessary to know what kind of underlying array it is, as this will work for any array.

How to get ER model of database from server with Workbench

On mac, press Command + R or got to Database -> Reverse Engineer and keep selecting your requirements and continue

enter image description here

Get timezone from users browser using moment(timezone).js

When using moment.js, use:

var tz = moment.tz.guess();

It will return an IANA time zone identifier, such as America/Los_Angeles for the US Pacific time zone.

It is documented here.

Internally, it first tries to get the time zone from the browser using the following call:

Intl.DateTimeFormat().resolvedOptions().timeZone

If you are targeting only modern browsers that support this function, and you don't need Moment-Timezone for anything else, then you can just call that directly.

If Moment-Timezone doesn't get a valid result from that function, or if that function doesn't exist, then it will "guess" the time zone by testing several different dates and times against the Date object to see how it behaves. The guess is usually a good enough approximation, but not guaranteed to exactly match the time zone setting of the computer.

DB2 Timestamp select statement

@bhamby is correct. By leaving the microseconds off of your timestamp value, your query would only match on a usagetime of 2012-09-03 08:03:06.000000

If you don't have the complete timestamp value captured from a previous query, you can specify a ranged predicate that will match on any microsecond value for that time:

...WHERE id = 1 AND usagetime BETWEEN '2012-09-03 08:03:06' AND '2012-09-03 08:03:07'

or

...WHERE id = 1 AND usagetime >= '2012-09-03 08:03:06' 
   AND usagetime < '2012-09-03 08:03:07'

How do I use checkboxes in an IF-THEN statement in Excel VBA 2010?

If Sheets("Sheet1").OLEObjects("CheckBox1").Object.Value = True Then

I believe Tim is right. You have a Form Control. For that you have to use this

If ActiveSheet.Shapes("Check Box 1").ControlFormat.Value = 1 Then

jQuery.ajax returns 400 Bad Request

Add this to your ajax call:

contentType: "application/json; charset=utf-8",
dataType: "json"

How to sort mongodb with pymongo

TLDR: Aggregation pipeline is faster as compared to conventional .find().sort().

Now moving to the real explanation. There are two ways to perform sorting operations in MongoDB:

  1. Using .find() and .sort().
  2. Or using the aggregation pipeline.

As suggested by many .find().sort() is the simplest way to perform the sorting.

.sort([("field1",pymongo.ASCENDING), ("field2",pymongo.DESCENDING)])

However, this is a slow process compared to the aggregation pipeline.

Coming to the aggregation pipeline method. The steps to implement simple aggregation pipeline intended for sorting are:

  1. $match (optional step)
  2. $sort

NOTE: In my experience, the aggregation pipeline works a bit faster than the .find().sort() method.

Here's an example of the aggregation pipeline.

db.collection_name.aggregate([{
    "$match": {
        # your query - optional step
    }
},
{
    "$sort": {
        "field_1": pymongo.ASCENDING,
        "field_2": pymongo.DESCENDING,
        ....
    }
}])

Try this method yourself, compare the speed and let me know about this in the comments.

Edit: Do not forget to use allowDiskUse=True while sorting on multiple fields otherwise it will throw an error.

git command to move a folder inside another

I solved this on windows by doing this:

  • Open Power shell console
  • run dir
  • Alt-click and drag over the file/folder name column, then copy
  • Paste to notepad++
  • run replace with regex: replace (.*) with git mv ".\\\1" ".\\<New_Folder_Here>\"
  • copy all text from notepad++ into powershell
  • hit enter

django import error - No module named core.management

==================================SOLUTION=========================================

First goto: virtualenv

by running the command: source bin/activate

and install django because you are getting the error related to 'import django':

pip install django

Then run:

python manage.py runserver

(Note: please change 'runserver' to the program name you want to run)

For the same issue, it worked in my case. ==================================Synopsis=========================================

ERROR:
(Development) Rakeshs-MacBook-Pro:src rakesh$ python manage.py runserver
Traceback (most recent call last):
  File "manage.py", line 8, in <module>
    from django.core.management import execute_from_command_line
ModuleNotFoundError: No module named 'django'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 14, in <module>
    import django
ModuleNotFoundError: No module named 'django'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 17, in <module>
    "Couldn't import Django. Are you sure it's installed and "
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
(Development) Rakeshs-MacBook-Pro:src rakesh$ 
(Development) Rakeshs-MacBook-Pro:src rakesh$ 
(Development) Rakeshs-MacBook-Pro:src rakesh$ python -Wall manage.py test
Traceback (most recent call last):
  File "manage.py", line 8, in <module>
    from django.core.management import execute_from_command_line
ModuleNotFoundError: No module named 'django'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 14, in <module>
    import django
ModuleNotFoundError: No module named 'django'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 17, in <module>
    "Couldn't import Django. Are you sure it's installed and "
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?

AFTER INSTALLATION of django:

(Development) MacBook-Pro:src rakesh$ pip install django
Collecting django
  Downloading https://files.pythonhosted.org/packages/51/1a/e0ac7886c7123a03814178d7517dc822af0fe51a72e1a6bff26153103322/Django-2.1-py3-none-any.whl (7.3MB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 7.3MB 1.1MB/s 
Collecting pytz (from django)
  Downloading https://files.pythonhosted.org/packages/30/4e/27c34b62430286c6d59177a0842ed90dc789ce5d1ed740887653b898779a/pytz-2018.5-py2.py3-none-any.whl (510kB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 512kB 4.7MB/s 
Installing collected packages: pytz, django

AFTER RESOLVING:

(Development) MacBook-Pro:src rakesh$ python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).

You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

August 05, 2018 - 04:39:02
Django version 2.1, using settings 'trydjango.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[05/Aug/2018 04:39:15] "GET / HTTP/1.1" 200 16348
[05/Aug/2018 04:39:15] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423
[05/Aug/2018 04:39:15] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 82564
[05/Aug/2018 04:39:15] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 81348
[05/Aug/2018 04:39:15] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 80304
Not Found: /favicon.ico
[05/Aug/2018 04:39:16] "GET /favicon.ico HTTP/1.1" 404 1976

Good luck!!

What is the relative performance difference of if/else versus switch statement in Java?

For most switch and most if-then-else blocks, I can't imagine that there are any appreciable or significant performance related concerns.

But here's the thing: if you're using a switch block, its very use suggests that you're switching on a value taken from a set of constants known at compile time. In this case, you really shouldn't be using switch statements at all if you can use an enum with constant-specific methods.

Compared to a switch statement, an enum provides better type safety and code that is easier to maintain. Enums can be designed so that if a constant is added to the set of constants, your code won't compile without providing a constant-specific method for the new value. On the other hand, forgetting to add a new case to a switch block can sometimes only be caught at run time if you're lucky enough to have set your block up to throw an exception.

Performance between switch and an enum constant-specific method should not be significantly different, but the latter is more readable, safer, and easier to maintain.

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

Keep in mind that if you're doing a cross-domain Ajax call (by using JSONP) - you can't do it synchronously, the async flag will be ignored by jQuery.

$.ajax({
    url: "testserver.php",
    dataType: 'jsonp', // jsonp
    async: false //IGNORED!!
});

For JSONP-calls you could use:

  1. Ajax-call to your own domain - and do the cross-domain call server-side
  2. Change your code to work asynchronously
  3. Use a "function sequencer" library like Frame.js (this answer)
  4. Block the UI instead of blocking the execution (this answer) (my favourite way)

How can INSERT INTO a table 300 times within a loop in SQL?

DECLARE @first AS INT = 1
DECLARE @last AS INT = 300

WHILE(@first <= @last)
BEGIN
    INSERT INTO tblFoo VALUES(@first)
    SET @first += 1
END

How can I remove a trailing newline?

I'm bubbling up my regular expression based answer from one I posted earlier in the comments of another answer. I think using re is a clearer more explicit solution to this problem than str.rstrip.

>>> import re

If you want to remove one or more trailing newline chars:

>>> re.sub(r'[\n\r]+$', '', '\nx\r\n')
'\nx'

If you want to remove newline chars everywhere (not just trailing):

>>> re.sub(r'[\n\r]+', '', '\nx\r\n')
'x'

If you want to remove only 1-2 trailing newline chars (i.e., \r, \n, \r\n, \n\r, \r\r, \n\n)

>>> re.sub(r'[\n\r]{1,2}$', '', '\nx\r\n\r\n')
'\nx\r'
>>> re.sub(r'[\n\r]{1,2}$', '', '\nx\r\n\r')
'\nx\r'
>>> re.sub(r'[\n\r]{1,2}$', '', '\nx\r\n')
'\nx'

I have a feeling what most people really want here, is to remove just one occurrence of a trailing newline character, either \r\n or \n and nothing more.

>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\n\n', count=1)
'\nx\n'
>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\r\n\r\n', count=1)
'\nx\r\n'
>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\r\n', count=1)
'\nx'
>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\n', count=1)
'\nx'

(The ?: is to create a non-capturing group.)

(By the way this is not what '...'.rstrip('\n', '').rstrip('\r', '') does which may not be clear to others stumbling upon this thread. str.rstrip strips as many of the trailing characters as possible, so a string like foo\n\n\n would result in a false positive of foo whereas you may have wanted to preserve the other newlines after stripping a single trailing one.)

Colouring plot by factor in R

There are two ways that I know of to color plot points by factor and then also have a corresponding legend automatically generated. I'll give examples of both:

  1. Using ggplot2 (generally easier)
  2. Using R's built in plotting functionality in combination with the colorRampPallete function (trickier, but many people prefer/need R's built-in plotting facilities)

For both examples, I will use the ggplot2 diamonds dataset. We'll be using the numeric columns diamond$carat and diamond$price, and the factor/categorical column diamond$color. You can load the dataset with the following code if you have ggplot2 installed:

library(ggplot2)
data(diamonds)

Using ggplot2 and qplot

It's a one liner. Key item here is to give qplot the factor you want to color by as the color argument. qplot will make a legend for you by default.

qplot(
  x = carat,
  y = price,
  data = diamonds,
  color = diamonds$color # color by factor color (I know, confusing)
)

Your output should look like this: qplot output colored by factor "diamond$color"

Using R's built in plot functionality

Using R's built in plot functionality to get a plot colored by a factor and an associated legend is a 4-step process, and it's a little more technical than using ggplot2.

First, we will make a colorRampPallete function. colorRampPallete() returns a new function that will generate a list of colors. In the snippet below, calling color_pallet_function(5) would return a list of 5 colors on a scale from red to orange to blue:

color_pallete_function <- colorRampPalette(
  colors = c("red", "orange", "blue"),
  space = "Lab" # Option used when colors do not represent a quantitative scale
  )

Second, we need to make a list of colors, with exactly one color per diamond color. This is the mapping we will use both to assign colors to individual plot points, and to create our legend.

num_colors <- nlevels(diamonds$color)
diamond_color_colors <- color_pallet_function(num_colors)

Third, we create our plot. This is done just like any other plot you've likely done, except we refer to the list of colors we made as our col argument. As long as we always use this same list, our mapping between colors and diamond$colors will be consistent across our R script.

plot(
  x = diamonds$carat,
  y = diamonds$price,
  xlab = "Carat",
  ylab = "Price",
  pch = 20, # solid dots increase the readability of this data plot
  col = diamond_color_colors[diamonds$color]
)

Fourth and finally, we add our legend so that someone reading our graph can clearly see the mapping between the plot point colors and the actual diamond colors.

legend(
  x ="topleft",
  legend = paste("Color", levels(diamonds$color)), # for readability of legend
  col = diamond_color_colors,
  pch = 19, # same as pch=20, just smaller
  cex = .7 # scale the legend to look attractively sized
)

Your output should look like this: standard R plot output colored by factor "diamond$color"

Nifty, right?

Different ways of clearing lists

del list[:] 

Will delete the values of that list variable

del list

Will delete the variable itself from memory

Oracle PL Sql Developer cannot find my tnsnames.ora file

I had the same problema, but as described in the manual.pdf, you have to:

You are using an Oracle Instant Client but have not set all required environment variables:

  • PATH: Needs to include the Instant Client directory where oci.dll is located
  • TNS_ADMIN: Needs to point to the directory where tnsnames.ora is located.
  • NLS_LANG: Defines the language, territory, and character set for the client.

Regards

DataColumn Name from DataRow (not DataTable)

You would still need to go through the DataTable class. But you can do so using your DataRow instance by using the Table property.

foreach (DataColumn c in dr.Table.Columns)  //loop through the columns. 
{
    MessageBox.Show(c.ColumnName);
}

Pure css close button

My attempt at a close icon, no text

_x000D_
_x000D_
.close-icon_x000D_
{_x000D_
  display:block;_x000D_
  box-sizing:border-box;_x000D_
  width:20px;_x000D_
  height:20px;_x000D_
  border-width:3px;_x000D_
  border-style: solid;_x000D_
  border-color:red;_x000D_
  border-radius:100%;_x000D_
  background: -webkit-linear-gradient(-45deg, transparent 0%, transparent 46%, white 46%,  white 56%,transparent 56%, transparent 100%), -webkit-linear-gradient(45deg, transparent 0%, transparent 46%, white 46%,  white 56%,transparent 56%, transparent 100%);_x000D_
  background-color:red;_x000D_
  box-shadow:0px 0px 5px 2px rgba(0,0,0,0.5);_x000D_
  transition: all 0.3s ease;_x000D_
}
_x000D_
<a href="#" class="close-icon"></a>
_x000D_
_x000D_
_x000D_

Error:(9, 5) error: resource android:attr/dialogCornerRadius not found

This error occurs because of mismatched compileSdkVersion and library version.

for example:

compileSdkVersion 27
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:design:26.1.0'

and also avoid to use + sign with library as in the following:

implementation 'com.android.support:appcompat-v7:26.+'

use exact library version like this

implementation 'com.android.support:appcompat-v7:26.1.0'

Using + sign with the library makes it difficult for the building process to gather the exact version that is required, making system unstable, hence should be discouraged.

Convert NSDate to NSString

Define your own utility for format your date required date format for eg.

NSString * stringFromDate(NSDate *date)  
 {   NSDateFormatter *formatter
    [[NSDateFormatter alloc] init];  
    [formatter setDateFormat:@"MM / dd / yyyy, hh?mm a"];    
    return [formatter stringFromDate:date]; 
}

Does a "Find in project..." feature exist in Eclipse IDE?

You should check out the new Eclipse 2019-09 4.13 Quick Search feature

The new Quick Search dialog provides a convenient, simple and fast way to run a textual search across your workspace and jump to matches in your code.

The dialog provides a quick overview showing matching lines of text at a glance.
It updates as quickly as you can type and allows for quick navigation using only the keyboard.

https://www.eclipse.org/eclipse/news/4.13/images/quick-search.png

A typical workflow starts by pressing the keyboard shortcut Ctrl+Alt+Shift+L
(or Cmd+Alt+Shift+L on Mac).
Typing a few letters updates the search result as you type.
Use Up-Down arrow keys to select a match, then hit Enter to open it in an editor.

Numpy first occurrence of value greater than existing value

I was also interested in this and I've compared all the suggested answers with perfplot. (Disclaimer: I'm the author of perfplot.)

If you know that the array you're looking through is already sorted, then

numpy.searchsorted(a, alpha)

is for you. It's O(log(n)) operation, i.e., the speed hardly depends on the size of the array. You can't get faster than that.

If you don't know anything about your array, you're not going wrong with

numpy.argmax(a > alpha)

Already sorted:

enter image description here

Unsorted:

enter image description here

Code to reproduce the plot:

import numpy
import perfplot


alpha = 0.5
numpy.random.seed(0)


def argmax(data):
    return numpy.argmax(data > alpha)


def where(data):
    return numpy.where(data > alpha)[0][0]


def nonzero(data):
    return numpy.nonzero(data > alpha)[0][0]


def searchsorted(data):
    return numpy.searchsorted(data, alpha)


perfplot.save(
    "out.png",
    # setup=numpy.random.rand,
    setup=lambda n: numpy.sort(numpy.random.rand(n)),
    kernels=[argmax, where, nonzero, searchsorted],
    n_range=[2 ** k for k in range(2, 23)],
    xlabel="len(array)",
)

Github Windows 'Failed to sync this branch'

I had the same problem when I tried from inside Visual Studio and "git status" in shell showed no problem. But I managed to push the local changes with "git push" via shell.

How to test for $null array in PowerShell

It's an array, so you're looking for Count to test for contents.

I'd recommend

$foo.count -gt 0

The "why" of this is related to how PSH handles comparison of collection objects

WHERE statement after a UNION in SQL?

If you want to apply the WHERE clause to the result of the UNION, then you have to embed the UNION in the FROM clause:

SELECT *
  FROM (SELECT * FROM TableA
        UNION
        SELECT * FROM TableB
       ) AS U
 WHERE U.Col1 = ...

I'm assuming TableA and TableB are union-compatible. You could also apply a WHERE clause to each of the individual SELECT statements in the UNION, of course.

JCheckbox - ActionListener and ItemListener?

Both ItemListener as well as ActionListener, in case of JCheckBox have the same behaviour. However, major difference is ItemListener can be triggered by calling the setSelected(true) on the checkbox. As a coding practice do not register both ItemListener as well as ActionListener with the JCheckBox, in order to avoid inconsistency.

How do I programmatically set device orientation in iOS 7?

If you want only portrait mode, in iOS 9 (Xcode 7) you can:

  • Going to Info.plist
  • Select "Supported interface orientations" item
  • Delete "Landscape(left home button)" and "Landscape(right home button)"

enter image description here

How to use RANK() in SQL Server

You have to use DENSE_RANK rather than RANK. The only difference is that it doesn't leave gaps. You also shouldn't partition by contender_num, otherwise you're ranking each contender in a separate group, so each is 1st-ranked in their segregated groups!

SELECT contendernum,totals, DENSE_RANK() OVER (ORDER BY totals desc) AS xRank FROM
(
SELECT ContenderNum ,SUM(Criteria1+Criteria2+Criteria3+Criteria4) AS totals
FROM dbo.Cat1GroupImpersonation
 GROUP BY ContenderNum
) AS a
order by contendernum

A hint for using StackOverflow, please post DDL and sample data so people can help you using less of their own time!

create table Cat1GroupImpersonation (
contendernum int,
criteria1 int,
criteria2 int,
criteria3 int,
criteria4 int);

insert Cat1GroupImpersonation select
1,196,0,0,0 union all select
2,181,0,0,0 union all select
3,192,0,0,0 union all select
4,181,0,0,0 union all select
5,179,0,0,0;

Labels for radio buttons in rails form

<% form_for(@message) do |f| %>
  <%= f.radio_button :contactmethod, 'email', :checked => true %> 
  <%= label :contactmethod_email, 'Email' %>
  <%= f.radio_button :contactmethod, 'sms' %>
  <%= label :contactmethod_sms, 'SMS' %>
<% end %>

Big-O summary for Java Collections Framework implementations?

The Javadocs from Sun for each collection class will generally tell you exactly what you want. HashMap, for example:

This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings).

TreeMap:

This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.

TreeSet:

This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).

(emphasis mine)

Regular expression to match a dot

This expression,

(?<=\s|^)[^.\s]+\.[^.\s]+(?=@)

might also work OK for those specific types of input strings.

Demo

Test

import re

expression = r'(?<=^|\s)[^.\s]+\.[^.\s]+(?=@)'
string = '''
blah blah blah [email protected] blah blah
blah blah blah test.this @gmail.com blah blah
blah blah blah [email protected] blah blah
'''

matches = re.findall(expression, string)

print(matches)

Output

['test.this']

If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


SQL Server 2005 Using CHARINDEX() To split a string

Try the following query:

DECLARE @item VARCHAR(MAX) = 'LD-23DSP-1430'

SELECT
SUBSTRING( @item, 0, CHARINDEX('-', @item)) ,
SUBSTRING(
               SUBSTRING( @item, CHARINDEX('-', @item)+1,LEN(@ITEM)) ,
               0 ,
               CHARINDEX('-', SUBSTRING( @item, CHARINDEX('-', @item)+1,LEN(@ITEM)))
              ),
REVERSE(SUBSTRING( REVERSE(@ITEM), 0, CHARINDEX('-', REVERSE(@ITEM))))

Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default

Maybe you should reset frame of the button, I had some problem too, and nslog the view of keyboard like this:

ios8:

"<UIInputSetContainerView: 0x7fef0364b0d0; frame = (0 0; 320 568); autoresize = W+H; layer = <CALayer: 0x7fef0364b1e0>>"

before8:

"<UIPeripheralHostView: 0x11393c860; frame = (0 352; 320 216); autoresizesSubviews = NO; layer = <CALayer: 0x11393ca10>>"

When to use extern in C++

It's all about the linkage.

The previous answers provided good explainations about extern.

But I want to add an important point.

You ask about extern in C++ not in C and I don't know why there is no answer mentioning about the case when extern comes with const in C++.

In C++, a const variable has internal linkage by default (not like C).

So this scenario will lead to linking error:

Source 1 :

const int global = 255; //wrong way to make a definition of global const variable in C++

Source 2 :

extern const int global; //declaration

It need to be like this:

Source 1 :

extern const int global = 255; //a definition of global const variable in C++

Source 2 :

extern const int global; //declaration

Why use HttpClient for Synchronous Connection

If you're building a class library, then perhaps the users of your library would like to use your library asynchronously. I think that's the biggest reason right there.

You also don't know how your library is going to be used. Perhaps the users will be processing lots and lots of requests, and doing so asynchronously will help it perform faster and more efficient.

If you can do so simply, try not to put the burden on the users of your library trying to make the flow asynchronous when you can take care of it for them.

The only reason I wouldn't use the async version is if I were trying to support an older version of .NET that does not already have built in async support.

SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

Update for MySQL 8.0

Your sql-mode will not have NO_AUTO_CREATE_USER as it has been removed as mentioned here - how-to-set-sql-mode-in-my-cnf-in-mysql-8

[mysqld]
sql-mode = "STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION"

Also if someone doesn't have a my.cnf file then they create a new one in /etc/my.cnf and then add the above lines.

Adding CSRFToken to Ajax request

Here is code that I used to prevent CSRF token problem when sending POST request with ajax

$(document).ready(function(){
    function getCookie(c_name) {
        if(document.cookie.length > 0) {
            c_start = document.cookie.indexOf(c_name + "=");
            if(c_start != -1) {
                c_start = c_start + c_name.length + 1;
                c_end = document.cookie.indexOf(";", c_start);
                if(c_end == -1) c_end = document.cookie.length;
                return unescape(document.cookie.substring(c_start,c_end));
            }
        }
        return "";
    }

    $(function () {
        $.ajaxSetup({
            headers: {
                "X-CSRFToken": getCookie("csrftoken")
            }
        });
    });

});

font size in html code

There are a couple of answers posted here that will give you the text effects you want, but...

The thing about tables is that they are organized collections of labels and data. Having both a label ("Datum") and the value that it labels in the same cell is oh so very wrong. The label should be in a <th> element, with the value in a <td> either in the same row or the same column (depending on the data arrangement you are trying to achieve). You can have <th> elements running either vertically or horizontally or both, but if you don't have heading cells (which is what <th> means), you don't have a table, you just have a meaningless grid of text. It would be preferable, too, to have a <caption> element to label the table as a whole (you don't have to display the caption, but it should be there for accessibility) and have a summary="blah blah blah" attribute in the table tag, again for accessibility. So your HTML should probably look a lot more like this:

<html>
  <head>
    <title>Test page with Table<title>
    <style type="text/css">
      th {
        font-size: 35px;
        font-weight: bold;
        padding-left: 5px;
        padding-bottom: 3px;
      }
    </style>
  </head>
  <body>
    <table id="table_1" summary="This table has both labels and values">
      <caption>Table of Stuff</caption>
      <tr>
        <th>Datum</th>
        <td>November 2010</td>
      </tr>
    </table>
  </body>
</html>

That may not be exactly what you want -- it's hard to tell whether November 2010 is a data point or a label from what you've posted, and "Datum" isn't a helpful label in any case. Play with it a bit, but make sure that when your table is finished it actually has some kind of semantic meaning. If it's not a real table of data, then don't use a <table> to lay it out.

How can I delete a user in linux when the system says its currently used in a process

It worked i used userdell --force USERNAME Some times eventhough -f and --force is same -f is not working sometimes After i removed the account i exit back to that removed username which i removed from root then what happened is this

image description here

XPath: select text node

your xpath should work . i have tested your xpath and mine in both MarkLogic and Zorba Xquery/ Xpath implementation.

Both should work.

/node/child::text()[1] - should return Text1
/node/child::text()[2] - should return text2


/node/text()[1] - should return Text1
/node/text()[2] - should return text2

How to fix 'sudo: no tty present and no askpass program specified' error?

I think I can help someone with my case.

First, I changed the user setting in /etc/sudoers referring to above answer. But It still didn't work.

myuser   ALL=(ALL) NOPASSWD: ALL
%mygroup  ALL=(ALL:ALL) ALL

In my case, myuser was in the mygroup.

And I didn't need groups. So, deleted that line.

(Shouldn't delete that line like me, just marking the comment.)

myuser   ALL=(ALL) NOPASSWD: ALL

It works!

Django return redirect() with parameters

urls.py:

#...    
url(r'element/update/(?P<pk>\d+)/$', 'element.views.element_update', name='element_update'),

views.py:

from django.shortcuts import redirect
from .models import Element


def element_info(request):
    # ...
    element = Element.object.get(pk=1)
    return redirect('element_update', pk=element.id)

def element_update(request, pk)
    # ...

Python recursive folder read

import glob
import os

root_dir = <root_dir_here>

for filename in glob.iglob(root_dir + '**/**', recursive=True):
    if os.path.isfile(filename):
        with open(filename,'r') as file:
            print(file.read())

**/** is used to get all files recursively including directory.

if os.path.isfile(filename) is used to check if filename variable is file or directory, if it is file then we can read that file. Here I am printing file.

Running Node.Js on Android

Dory - node.js

Great New Application
No Need to root your Phone and You Can Run your js File From anywere.

  • node.js runtime(run ES2015/ES6, ES2016 javascript and node.js APIs in android)
  • API Documents and instant code run from doc
  • syntax highlighting code editor
  • npm supports
  • linux terminal(toybox 0.7.4). node.js REPL and npm command in shell (add '--no-bin-links' option if you execute npm in /sdcard)
  • StartOnBoot / LiveReload
  • native node.js binary and npm are included. no need to be online.

Update instruction to node js 8 (async await)

  1. Download node.js v8.3.0 arm zip file and unzip.

  2. copy 'node' to android's sdcard(/sdcard or /sdcard/path/to/...)

  3. open the shell(check it out in the app's menu)

  4. cd /data/user/0/io.tmpage.dorynode/files/bin (or, just type cd && cd .. && cd files/bin )

  5. rm node

  6. cp /sdcard/node .

  7. (chmod a+x node

(https://play.google.com/store/apps/details?id=io.tempage.dorynode&hl=en)

How do I create a chart with multiple series using different X values for each series?

You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.

PHP mPDF save file as PDF

The Go trough this link state that the first argument of Output() is the file path, second is the saving mode - you need to set it to 'F'.

 $upload_dir = public_path(); 
             $filename = $upload_dir.'/testing7.pdf'; 
              $mpdf = new \Mpdf\Mpdf();
              //$test = $mpdf->Image($pro_image, 0, 0, 50, 50);

              $html ='<h1> Project Heading </h1>';
              $mail = ' <p> Project Heading </p> ';
              
              $mpdf->autoScriptToLang = true;
              $mpdf->autoLangToFont = true;
              $mpdf->WriteHTML($mail);

              $mpdf->Output($filename,'F'); 
              $mpdf->debug = true;

Example :

 $mpdf->Output($filename,'F');

Example #2

$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML('Hello World');

// Saves file on the server as 'filename.pdf'
$mpdf->Output('filename.pdf', \Mpdf\Output\Destination::FILE);

Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

I want to give a different view of MONEY vs. NUMERICAL, largely based my own expertise and experience... My point of view here is MONEY, because I have worked with it for a considerable long time and never really used NUMERICAL much...

MONEY Pro:

  • Native Data Type. It uses a native data type (integer) as the same as a CPU register (32 or 64 bit), so the calculation doesn't need unnecessary overhead so it's smaller and faster... MONEY needs 8 bytes and NUMERICAL(19, 4) needs 9 bytes (12.5% bigger)...

    MONEY is faster as long as it is used for it was meant to be (as money). How fast? My simple SUM test on 1 million data shows that MONEY is 275 ms and NUMERIC 517 ms... That is almost twice as fast... Why SUM test? See next Pro point

  • Best for Money. MONEY is best for storing money and do operations, for example, in accounting. A single report can run millions of additions (SUM) and a few multiplications after the SUM operation is done. For very big accounting applications it is almost twice as fast, and it is extremely significant...
  • Low Precision of Money. Money in real life doesn't need to be very precise. I mean, many people may care about 1 cent USD, but how about 0.01 cent USD? In fact, in my country, banks no longer care about cents (digit after decimal comma); I don't know about US bank or other country...

MONEY Con:

  • Limited Precision. MONEY only has four digits (after the comma) precision, so it has to be converted before doing operations such as division... But then again money doesn't need to be so precise and is meant to be used as money, not just a number...

But... Big, but here is even your application involved real-money, but do not use it in lots of SUM operations, like in accounting. If you use lots of divisions and multiplications instead then you should not use MONEY...

How to manually send HTTP POST requests from Firefox or Chrome browser?

Here's the Advanced REST Client extension for Chrome.

It works great for me -- do remember that you can still use the debugger with it. The Network pane is particularly useful; it'll give you rendered JSON objects and error pages.

How to get the browser language using JavaScript

Try this script to get your browser language

_x000D_
_x000D_
<script type="text/javascript">_x000D_
var userLang = navigator.language || navigator.userLanguage; _x000D_
alert ("The language is: " + userLang);_x000D_
</script>
_x000D_
_x000D_
_x000D_

Cheers

Java ArrayList - how can I tell if two lists are equal, order not mattering?

Solution which leverages CollectionUtils subtract method:

import static org.apache.commons.collections15.CollectionUtils.subtract;

public class CollectionUtils {
  static public <T> boolean equals(Collection<? extends T> a, Collection<? extends T> b) {
    if (a == null && b == null)
      return true;
    if (a == null || b == null || a.size() != b.size())
      return false;
    return subtract(a, b).size() == 0 && subtract(a, b).size() == 0;
  }
}

Handling the window closing event with WPF / MVVM Light Toolkit

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        MessageBox.Show("closing");
    }

Execute a PHP script from another PHP script

The OP refined his question to how a php script is called from a script. The php statement 'require' is good for dependancy as the script will stop if required script is not found.

#!/usr/bin/php
<?
require '/relative/path/to/someotherscript.php';

/* The above script runs as though executed from within this one. */

printf ("Hello world!\n");

?>

How to put a delay on AngularJS instant search?

For those who uses keyup/keydown in the HTML markup. This doesn't uses watch.

JS

app.controller('SearchCtrl', function ($scope, $http, $timeout) {
  var promise = '';
  $scope.search = function() {
    if(promise){
      $timeout.cancel(promise);
    }
    promise = $timeout(function() {
    //ajax call goes here..
    },2000);
  };
});

HTML

<input type="search" autocomplete="off" ng-model="keywords" ng-keyup="search()" placeholder="Search...">

Java - removing first character of a string

public String removeFirst(String input)
{
    return input.substring(1);
}

Javascript - Append HTML to container element without innerHTML

To give an alternative (as using DocumentFragment does not seem to work): You can simulate it by iterating over the children of the newly generated node and only append those.

var e = document.createElement('div');
e.innerHTML = htmldata;

while(e.firstChild) {
    element.appendChild(e.firstChild);
}

pandas groupby sort descending order

Do your groupby, and use reset_index() to make it back into a DataFrame. Then sort.

grouped = df.groupby('mygroups').sum().reset_index()
grouped.sort_values('mygroups', ascending=False)

Adding blur effect to background in swift

In a UIView extension:

func addBlurredBackground(style: UIBlurEffect.Style) {
    let blurEffect = UIBlurEffect(style: style)
    let blurView = UIVisualEffectView(effect: blurEffect)
    blurView.frame = self.frame
    blurView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    self.addSubview(blurView)
    self.sendSubviewToBack(blurView)
}

Visual Studio Code always asking for git credentials

You should be able to set your credentials like this:

git remote set-url origin https://<USERNAME>:<PASSWORD>@bitbucket.org/path/to/repo.git

You can get the remote url like this:

git config --get remote.origin.url

jQuery - multiple $(document).ready ...?

$(document).ready(); is the same as any other function. it fires once the document is ready - ie loaded. the question is about what happens when multiple $(document).ready()'s are fired not when you fire the same function within multiple $(document).ready()'s

//this
<div id="target"></div>

$(document).ready(function(){
   jQuery('#target').append('target edit 1<br>');
});
$(document).ready(function(){
   jQuery('#target').append('target edit 2<br>');
});
$(document).ready(function(){
   jQuery('#target').append('target edit 3<br>');
});

//is the same as
<div id="target"></div>

$(document).ready(function(){

    jQuery('#target').append('target edit 1<br>');

    jQuery('#target').append('target edit 2<br>');

    jQuery('#target').append('target edit 3<br>');

});

both will behave exactly the same. the only difference is that although the former will achieve the same results. the latter will run a fraction of a second faster and requires less typing. :)

in conclusion where ever possible only use 1 $(document).ready();

//old answer

They will both get called in order. Best practice would be to combine them. but dont worry if its not possible. the page will not explode.

How do I include a path to libraries in g++

In your MakeFile or CMakeLists.txt you can set CMAKE_CXX_FLAGS as below:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/path/to/your/folder")

Custom method names in ASP.NET Web API

See this article for a longer discussion of named actions. It also shows that you can use the [HttpGet] attribute instead of prefixing the action name with "get".

http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

Undo a particular commit in Git that's been pushed to remote repos

If the commit you want to revert is a merged commit (has been merged already), then you should either -m 1 or -m 2 option as shown below. This will let git know which parent commit of the merged commit to use. More details can be found HERE.

  • git revert <commit> -m 1
  • git revert <commit> -m 2

How to check if a python module exists without importing it

You can also use importlib directly

import importlib

try:
    importlib.import_module(module_name)
except ImportError:
    # Handle error

Python script to copy text to clipboard

I try this clipboard 0.0.4 and it works well.

https://pypi.python.org/pypi/clipboard/0.0.4

import clipboard
clipboard.copy("abc")  # now the clipboard content will be string "abc"
text = clipboard.paste()  # text will have the content of clipboard

Getting values from JSON using Python

What error is it giving you?

If you do exactly this:

data = json.loads('{"lat":444, "lon":555}')

Then:

data['lat']

SHOULD NOT give you any error at all.

Starting a shell in the Docker Alpine container

Usually, an Alpine Linux image doesn't contain bash, Instead you can use /bin/ash, /bin/sh, ash or only sh.

/bin/ash

docker run -it --rm alpine /bin/ash

/bin/sh

docker run -it --rm alpine /bin/sh

ash

docker run -it --rm alpine ash

sh

docker run -it --rm alpine sh

I hope this information helps you.

Delete from a table based on date

This is pretty vague. Do you mean like in SQL:

DELETE FROM myTable
WHERE dateColumn < '2007'

How to Clear Console in Java?

If your terminal supports ANSI escape codes, this clears the screen and moves the cursor to the first row, first column:

System.out.print("\033[H\033[2J");
System.out.flush();

This works on almost all UNIX terminals and terminal emulators. The Windows cmd.exe does not interprete ANSI escape codes.

Custom pagination view in Laravel 5

In 5.5 links() is replaced with render() which appears to work similarly. [Official DOC]

replace

{{ $replies->links() }}

with

{{ $replies->render("pagination::default") }}

Following commands will generate Pagination template in resources/views/vendor/pagination

artisan vendor:publish --tag=laravel-pagination
artisan vendor:publish

In any view file (blade files) you can use those template like following ex:

  • {{ $replies->render("pagination::default") }}
  • {{ $replies->render("pagination::bootstrap-4") }}
  • {{ $replies->render("pagination::simple-bootstrap-4") }}
  • {{ $replies->render("pagination::semantic-ui") }}

How to include (source) R script in other scripts

There is no such thing built-in, since R does not track calls to source and is not able to figure out what was loaded from where (this is not the case when using packages). Yet, you may use same idea as in C .h files, i.e. wrap the whole in:

if(!exists('util_R')){
 util_R<-T

 #Code

}

MySQL table is marked as crashed and last (automatic?) repair failed

If your MySQL process is running, stop it. On Debian:

sudo service mysql stop

Go to your data folder. On Debian:

cd /var/lib/mysql/$DATABASE_NAME

Try running:

myisamchk -r $TABLE_NAME

If that doesn't work, you can try:

myisamchk -r -v -f $TABLE_NAME

You can start your MySQL server again. On Debian:

sudo service mysql start

An error when I add a variable to a string

This problem also arise when we don't give the single or double quotes to the database value.

Wrong way:

$query ="INSERT INTO tabel_name VALUE ($value1,$value2)";

As database inserting values must be in quotes ' '/" "

Right way:

$query ="INSERT INTO STUDENT VALUE ('$roll_no','$name','$class')";

How to return a file using Web API?

Another way to download file is to write the stream content to the response's body directly:

[HttpGet("pdfstream/{id}")]
public async Task  GetFile(long id)
{        
    var stream = GetStream(id);
    Response.StatusCode = (int)HttpStatusCode.OK;
    Response.Headers.Add( HeaderNames.ContentDisposition, $"attachment; filename=\"{Guid.NewGuid()}.pdf\"" );
    Response.Headers.Add( HeaderNames.ContentType, "application/pdf"  );            
    await stream.CopyToAsync(Response.Body);
    await Response.Body.FlushAsync();           
}

Merging two arrayLists into a new arrayList, with no duplicates and in order, in Java

Add ArrayList1, ArrayList2 and produce a Single arraylist ArrayList3. Now convert it into

Set Unique_set = new HashSet(Arraylist3);

in the unique set you will get the unique elements.
Note

ArrayList allows to duplicate values. Set doesn't allow the values to duplicate. Hope your problem solves.

How to use a global array in C#?

Your class shoud look something like this:

class Something {     int[] array; //global array, replace type of course     void function1() {        array = new int[10]; //let say you declare it here that will be 10 integers in size     }     void function2() {        array[0] = 12; //assing value at index 0 to 12.     } } 

That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.

What's the difference between TRUNCATE and DELETE in SQL

DROP

The DROP command removes a table from the database. All the tables' rows, indexes and privileges will also be removed. No DML triggers will be fired. The operation cannot be rolled back.

TRUNCATE

TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be fired. As such, TRUNCATE is faster and doesn't use as much undo space as a DELETE. Table level lock will be added when Truncating.

DELETE

The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it. Note that this operation will cause all DELETE triggers on the table to fire. Row level lock will be added when deleting.

From: http://www.orafaq.com/faq/difference_between_truncate_delete_and_drop_commands

Center-align a HTML table

For your design, it is common practice to use divs rather than a table. This way, your layout will be more maintainable and changeable through proper styling. It does take some getting used to, but it will help you a ton in the long run and you will learn a lot about how styling works. However, I will provide you with a solution to the problem at hand.

In your stylesheets you have margins and padding set to 0 pixels. This overrides your align="center" attribute. I would recommend taking these settings out of your CSS as you don't normally want all of your elements to be affected in this manner. If you already know what's going on in the CSS, and you want to keep it that way, then you have to apply a style to your table to override the previous sets. You could either give the table a class or you can put the style inline with the HTML. Here are the two options:

  1. With a class:

    <table class="centerTable"></table>

In your style.css file you would have something like this:

.centerTable { margin: 0px auto; }
  1. Inline with your HTML:

    <table style="margin: 0px auto;"></table>

If you decide to wipe out the margins and padding being set to 0px, then you can keep align="center" on your <td> tags for whatever column you wish to align.

How to browse localhost on Android device?

I needed to see localhost on my android device as well (Samsung S3) as I was developing a Java Web-application.
By far the fastest and easiest way is to go to this link and follow instructions: https://developer.chrome.com/devtools/docs/remote-debugging

* Note: You have to use Google Chrome.*
My summary of the above link:

  • Connect PC with Phone over USB.
  • Turn on Phone's "Developer options" from Settings
  • Go to about:inspect URL in PC's browser
  • Check "Discover USB Devices" (forward Ports if you are using them in your web-application)
  • Copy/paste localhost required link to text field in browser and click Open.

Piece of cake

Git - How to use .netrc file on Windows to save user and password

Is it possible to use a .netrc file on Windows?

Yes: You must:

  • define environment variable %HOME% (pre-Git 2.0, no longer needed with Git 2.0+)
  • put a _netrc file in %HOME%

If you are using Windows 7/10, in a CMD session, type:

setx HOME %USERPROFILE%

and the %HOME% will be set to 'C:\Users\"username"'.
Go that that folder (cd %HOME%) and make a file called '_netrc'

Note: Again, for Windows, you need a '_netrc' file, not a '.netrc' file.

Its content is quite standard (Replace the <examples> with your values):

machine <hostname1>
login <login1>
password <password1>
machine <hostname2>
login <login2>
password <password2>

Luke mentions in the comments:

Using the latest version of msysgit on Windows 7, I did not need to set the HOME environment variable. The _netrc file alone did the trick.

This is indeed what I mentioned in "Trying to “install” github, .ssh dir not there":
git-cmd.bat included in msysgit does set the %HOME% environment variable:

@if not exist "%HOME%" @set HOME=%HOMEDRIVE%%HOMEPATH%
@if not exist "%HOME%" @set HOME=%USERPROFILE%

??? believes in the comments that "it seems that it won't work for http protocol"

However, I answered that netrc is used by curl, and works for HTTP protocol, as shown in this example (look for 'netrc' in the page): . Also used with HTTP protocol here: "_netrc/.netrc alternative to cURL".


A common trap with with netrc support on Windows is that git will bypass using it if an origin https url specifies a user name.

For example, if your .git/config file contains:

[remote "origin"]
     fetch = +refs/heads/*:refs/remotes/origin/*
     url = https://[email protected]/p/my-project/

Git will not resolve your credentials via _netrc, to fix this remove your username, like so:

[remote "origin"]
     fetch = +refs/heads/*:refs/remotes/origin/*
     url = https://code.google.com/p/my-project/

Alternative solution: With git version 1.7.9+ (January 2012): This answer from Mark Longair details the credential cache mechanism which also allows you to not store your password in plain text as shown below.


With Git 1.8.3 (April 2013):

You now can use an encrypted .netrc (with gpg).
On Windows: %HOME%/_netrc (_, not '.')

A new read-only credential helper (in contrib/) to interact with the .netrc/.authinfo files has been added.

That script would allow you to use gpg-encrypted netrc files, avoiding the issue of having your credentials stored in a plain text file.

Files with the .gpg extension will be decrypted by GPG before parsing.
Multiple -f arguments are OK. They are processed in order, and the first matching entry found is returned via the credential helper protocol.

When no -f option is given, .authinfo.gpg, .netrc.gpg, .authinfo, and .netrc files in your home directory are used in this order.

To enable this credential helper:

git config credential.helper '$shortname -f AUTHFILE1 -f AUTHFILE2'

(Note that Git will prepend "git-credential-" to the helper name and look for it in the path.)

# and if you want lots of debugging info:
git config credential.helper '$shortname -f AUTHFILE -d'

#or to see the files opened and data found:
git config credential.helper '$shortname -f AUTHFILE -v'

See a full example at "Is there a way to skip password typing when using https:// github"


With Git 2.18+ (June 2018), you now can customize the GPG program used to decrypt the encrypted .netrc file.

See commit 786ef50, commit f07eeed (12 May 2018) by Luis Marsano (``).
(Merged by Junio C Hamano -- gitster -- in commit 017b7c5, 30 May 2018)

git-credential-netrc: accept gpg option

git-credential-netrc was hardcoded to decrypt with 'gpg' regardless of the gpg.program option.
This is a problem on distributions like Debian that call modern GnuPG something else, like 'gpg2'

Requests -- how to tell if you're getting a 404

Look at the r.status_code attribute:

if r.status_code == 404:
    # A 404 was issued.

Demo:

>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404

If you want requests to raise an exception for error codes (4xx or 5xx), call r.raise_for_status():

>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "requests/models.py", line 664, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.

You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:

if r:
    # successful response

If you want to be more explicit, use if r.ok:.

Laravel 5 Clear Views Cache

To get all the artisan command, type...

php artisan

If you want to clear view cache, just use:

php artisan view:clear

If you don't know how to use specific artisan command, just add "help" (see below)

php artisan help view:clear

Reading values from DataTable

For VB.Net is

        Dim con As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + "database path")
        Dim cmd As New OleDb.OleDbCommand
        Dim dt As New DataTable
        Dim da As New OleDb.OleDbDataAdapter
        con.Open()
        cmd.Connection = con
        cmd.CommandText = sql
        da.SelectCommand = cmd

        da.Fill(dt)

        For i As Integer = 0 To dt.Rows.Count
            someVar = dt.Rows(i)("fieldName")
        Next

How can I split a JavaScript string by white space or comma?

"my, tags are, in here".split(/[ ,]+/)

the result is :

["my", "tags", "are", "in", "here"]

Streaming video from Android camera to server

I'm looking into this as well, and while I don't have a good solution for you I did manage to dig up SIPDroid's video code:

http://code.google.com/p/sipdroid/source/browse/trunk/src/org/sipdroid/sipua/ui/VideoCamera.java

How to use BufferedReader in Java

As far as i understand fr is the object of your FileReadExample class. So it is obvious it will not have any method like fr.readLine() if you dont create one yourself.

secondly, i think a correct constructor of the BufferedReader class will help you do your task.

String str;
BufferedReader buffread = new BufferedReader(new FileReader(new File("file.dat")));
str = buffread.readLine();
.
.
buffread.close();

this should help you.

Spring Boot - Loading Initial Data

If you want to insert only few rows and u have JPA Setup. You can use below

    @SpringBootApplication
        @Slf4j
        public class HospitalManagementApplication {

            public static void main(String[] args) {
                SpringApplication.run(HospitalManagementApplication.class, args);
            }            

            @Bean
            ApplicationRunner init(PatientRepository repository) {
                return (ApplicationArguments args) ->  dataSetup(repository);
            } 

            public void dataSetup(PatientRepository repository){
            //inserts

     }

PHP multiline string with PHP

To do that, you must remove all ' charachters in your string or use an escape character. Like:

<?php
    echo '<?php
              echo \'hello world\';
          ?>';
?>

Filename too long in Git for Windows

Steps to follow (Windows):

  1. Run Git Bash as administrator
  2. Run the following command:
git config --system core.longpaths true

Note: if step 2 does not work or gives any error, you can also try running this command:

git config --global core.longpaths true

Read more about git config here.

Making a <button> that's a link in HTML

A little bit easier and it looks exactly like the button in the form. Just use the input and wrap the anchor tag around it.

<a href="#"><input type="button" value="Button Text"></a>

Element-wise addition of 2 lists?

The others gave examples how to do this in pure python. If you want to do this with arrays with 100.000 elements, you should use numpy:

In [1]: import numpy as np
In [2]: vector1 = np.array([1, 2, 3])
In [3]: vector2 = np.array([4, 5, 6])

Doing the element-wise addition is now as trivial as

In [4]: sum_vector = vector1 + vector2
In [5]: print sum_vector
[5 7 9]

just like in Matlab.

Timing to compare with Ashwini's fastest version:

In [16]: from operator import add
In [17]: n = 10**5
In [18]: vector2 = np.tile([4,5,6], n)
In [19]: vector1 = np.tile([1,2,3], n)
In [20]: list1 = [1,2,3]*n
In [21]: list2 = [4,5,6]*n
In [22]: timeit map(add, list1, list2)
10 loops, best of 3: 26.9 ms per loop

In [23]: timeit vector1 + vector2
1000 loops, best of 3: 1.06 ms per loop

So this is a factor 25 faster! But use what suits your situation. For a simple program, you probably don't want to install numpy, so use standard python (and I find Henry's version the most Pythonic one). If you are into serious number crunching, let numpy do the heavy lifting. For the speed freaks: it seems that the numpy solution is faster starting around n = 8.

How do I make an HTML text box show a hint when empty?

Use a background image to render the text:

 input.foo { }
 input.fooempty { background-image: url("blah.png"); }

Then all you have to do is detect value == 0 and apply the right class:

 <input class="foo fooempty" value="" type="text" name="bar" />

And the jQuery JavaScript code looks like this:

jQuery(function($)
{
    var target = $("input.foo");
    target.bind("change", function()
    {
        if( target.val().length > 1 )
        {
            target.addClass("fooempty");
        }
        else
        {
            target.removeClass("fooempty");
        }
    });
});

SQL Update Multiple Fields FROM via a SELECT Statement

You should be able to do something along the lines of the following

UPDATE s
SET
    OrgAddress1 = bd.OrgAddress1,
    OrgAddress2 = bd.OrgAddress2,
    ...
    DestZip = bd.DestZip
FROM
    Shipment s, ProfilerTest.dbo.BookingDetails bd
WHERE
    bd.MyID = @MyId AND s.MyID2 = @MyID2

FROM statement can be made more optimial (using more specific joins), but the above should do the trick. Also, a nice side benefit to writing it this way, to see a preview of the UPDATE change UPDATE s SET to read SELECT! You will then see that data as it would appear if the update had taken place.

INSERT IF NOT EXISTS ELSE UPDATE?

I think it's worth pointing out that there can be some unexpected behaviour here if you don't thoroughly understand how PRIMARY KEY and UNIQUE interact.

As an example, if you want to insert a record only if the NAME field isn't currently taken, and if it is, you want a constraint exception to fire to tell you, then INSERT OR REPLACE will not throw and exception and instead will resolve the UNIQUE constraint itself by replacing the conflicting record (the existing record with the same NAME). Gaspard's demonstrates this really well in his answer above.

If you want a constraint exception to fire, you have to use an INSERT statement, and rely on a separate UPDATE command to update the record once you know the name isn't taken.

How to stop text from taking up more than 1 line?

In JSX/ React prevent text from wrapping

<div style={{ whiteSpace: "nowrap", overflow: "hidden" }}>
   Text that will never wrap
</div>

How do I call a SQL Server stored procedure from PowerShell?

Here is a function that I use (slightly redacted). It allows input and output parameters. I only have uniqueidentifier and varchar types implemented, but any other types are easy to add. If you use parameterized stored procedures (or just parameterized sql...this code is easily adapted to that), this will make your life a lot easier.

To call the function, you need a connection to the SQL server (say $conn),

$res=exec-storedprocedure -storedProcName 'stp_myProc' -parameters @{Param1="Hello";Param2=50} -outparams @{ID="uniqueidentifier"} $conn

retrieve proc output from returned object

$res.data #dataset containing the datatables returned by selects

$res.outputparams.ID #output parameter ID (uniqueidentifier)

The function:

function exec-storedprocedure($storedProcName,  
        [hashtable] $parameters=@{},
        [hashtable] $outparams=@{},
        $conn,[switch]$help){ 

        function put-outputparameters($cmd, $outparams){
            foreach($outp in $outparams.Keys){
                $cmd.Parameters.Add("@$outp", (get-paramtype $outparams[$outp])).Direction=[System.Data.ParameterDirection]::Output
            }
        }
        function get-outputparameters($cmd,$outparams){
            foreach($p in $cmd.Parameters){
                if ($p.Direction -eq [System.Data.ParameterDirection]::Output){
                $outparams[$p.ParameterName.Replace("@","")]=$p.Value
                }
            }
        }

        function get-paramtype($typename,[switch]$help){
            switch ($typename){
                'uniqueidentifier' {[System.Data.SqlDbType]::UniqueIdentifier}
                'int' {[System.Data.SqlDbType]::Int}
                'xml' {[System.Data.SqlDbType]::Xml}
                'nvarchar' {[System.Data.SqlDbType]::NVarchar}
                default {[System.Data.SqlDbType]::Varchar}
            }
        }
        if ($help){
            $msg = @"
    Execute a sql statement.  Parameters are allowed.  
    Input parameters should be a dictionary of parameter names and values.
    Output parameters should be a dictionary of parameter names and types.
    Return value will usually be a list of datarows. 

    Usage: exec-query sql [inputparameters] [outputparameters] [conn] [-help]
    "@
            Write-Host $msg
            return
        }
        $close=($conn.State -eq [System.Data.ConnectionState]'Closed')
        if ($close) {
           $conn.Open()
        }

        $cmd=new-object system.Data.SqlClient.SqlCommand($sql,$conn)
        $cmd.CommandType=[System.Data.CommandType]'StoredProcedure'
        $cmd.CommandText=$storedProcName
        foreach($p in $parameters.Keys){
            $cmd.Parameters.AddWithValue("@$p",[string]$parameters[$p]).Direction=
                  [System.Data.ParameterDirection]::Input
        }

        put-outputparameters $cmd $outparams
        $ds=New-Object system.Data.DataSet
        $da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd)
        [Void]$da.fill($ds)
        if ($close) {
           $conn.Close()
        }
        get-outputparameters $cmd $outparams

        return @{data=$ds;outputparams=$outparams}
    }