Programs & Examples On #External process

How to execute a .bat file from a C# windows form app?

Here is what you are looking for:

Service hangs up at WaitForExit after calling batch file

It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.

Get drop down value

var dd = document.getElementById("dropdownID");
var selectedItem = dd.options[dd.selectedIndex].value;

ORA-06508: PL/SQL: could not find program unit being called

Based on previous answers. I resolved my issue by removing global variable at package level to procedure, since there was no impact in my case.

Original script was

create or replace PACKAGE BODY APPLICATION_VALIDATION AS 

V_ERROR_NAME varchar2(200) := '';

PROCEDURE  APP_ERROR_X47_VALIDATION (   PROCESS_ID IN VARCHAR2 ) AS BEGIN
     ------ rules for validation... END APP_ERROR_X47_VALIDATION ;

/* Some more code
*/

END APPLICATION_VALIDATION; /

Rewritten the same without global variable V_ERROR_NAME and moved to procedure under package level as

Modified Code

create or replace PACKAGE BODY APPLICATION_VALIDATION AS

PROCEDURE  APP_ERROR_X47_VALIDATION (   PROCESS_ID IN VARCHAR2 ) AS

**V_ERROR_NAME varchar2(200) := '';** 

BEGIN
     ------ rules for validation... END APP_ERROR_X47_VALIDATION ;

/* Some more code
*/

END APPLICATION_VALIDATION; /

Wait until flag=true

With Ecma Script 2017 You can use async-await and while together to do that And while will not crash or lock the program even variable never be true

_x000D_
_x000D_
//First define some delay function which is called from async function_x000D_
function __delay__(timer) {_x000D_
    return new Promise(resolve => {_x000D_
        timer = timer || 2000;_x000D_
        setTimeout(function () {_x000D_
            resolve();_x000D_
        }, timer);_x000D_
    });_x000D_
};_x000D_
_x000D_
//Then Declare Some Variable Global or In Scope_x000D_
//Depends on you_x000D_
var flag = false;_x000D_
_x000D_
//And define what ever you want with async fuction_x000D_
async function some() {_x000D_
    while (!flag)_x000D_
        await __delay__(1000);_x000D_
_x000D_
    //...code here because when Variable = true this function will_x000D_
};
_x000D_
_x000D_
_x000D_

Verilog: How to instantiate a module

This is all generally covered by Section 23.3.2 of SystemVerilog IEEE Std 1800-2012.

The simplest way is to instantiate in the main section of top, creating a named instance and wiring the ports up in order:

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  clk, rst_n, data_rx_1, data_tx ); 

endmodule

This is described in Section 23.3.2.1 of SystemVerilog IEEE Std 1800-2012.

This has a few draw backs especially regarding the port order of the subcomponent code. simple refactoring here can break connectivity or change behaviour. for example if some one else fixs a bug and reorders the ports for some reason, switching the clk and reset order. There will be no connectivity issue from your compiler but will not work as intended.

module subcomponent(
  input        rst_n,       
  input        clk,
  ...

It is therefore recommended to connect using named ports, this also helps tracing connectivity of wires in the code.

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  .clk(clk), .rst_n(rst_n), .data_rx(data_rx_1), .data_tx(data_tx) ); 

endmodule

This is described in Section 23.3.2.2 of SystemVerilog IEEE Std 1800-2012.

Giving each port its own line and indenting correctly adds to the readability and code quality.

subcomponent subcomponent_instance_name (
  .clk      ( clk       ), // input
  .rst_n    ( rst_n     ), // input
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

So far all the connections that have been made have reused inputs and output to the sub module and no connectivity wires have been created. What happens if we are to take outputs from one component to another:

clk_gen( 
  .clk      ( clk_sub   ), // output
  .en       ( enable    )  // input

subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

This nominally works as a wire for clk_sub is automatically created, there is a danger to relying on this. it will only ever create a 1 bit wire by default. An example where this is a problem would be for the data:

Note that the instance name for the second component has been changed

subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_temp )  // output [9:0]
);
subcomponent subcomponent_instance_name2 (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_temp ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

The issue with the above code is that data_temp is only 1 bit wide, there would be a compile warning about port width mismatch. The connectivity wire needs to be created and a width specified. I would recommend that all connectivity wires be explicitly written out.

wire [9:0] data_temp
subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_temp )  // output [9:0]
);
subcomponent subcomponent_instance_name2 (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_temp ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

Moving to SystemVerilog there are a few tricks available that save typing a handful of characters. I believe that they hinder the code readability and can make it harder to find bugs.

Use .port with no brackets to connect to a wire/reg of the same name. This can look neat especially with lots of clk and resets but at some levels you may generate different clocks or resets or you actually do not want to connect to the signal of the same name but a modified one and this can lead to wiring bugs that are not obvious to the eye.

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  .clk,                    // input **Auto connect**
  .rst_n,                  // input **Auto connect**
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

endmodule

This is described in Section 23.3.2.3 of SystemVerilog IEEE Std 1800-2012.

Another trick that I think is even worse than the one above is .* which connects unmentioned ports to signals of the same wire. I consider this to be quite dangerous in production code. It is not obvious when new ports have been added and are missing or that they might accidentally get connected if the new port name had a counter part in the instancing level, they get auto connected and no warning would be generated.

subcomponent subcomponent_instance_name (
  .*,                      // **Auto connect**
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

This is described in Section 23.3.2.4 of SystemVerilog IEEE Std 1800-2012.

How to scroll to the bottom of a RecyclerView? scrollToPosition doesn't work

Tried a method of @galex, it worked until refactoring. So I used an answer of @yanchenko and changed a bit. Probably this is because I called scrolling from onCreateView(), where a fragment view was built (and probably didn't have right size).

private fun scrollPhotosToEnd(view: View) {
    view.recycler_view.viewTreeObserver.addOnGlobalLayoutListener(object :
        ViewTreeObserver.OnGlobalLayoutListener {
        override fun onGlobalLayout() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                view.recycler_view.viewTreeObserver.removeOnGlobalLayoutListener(this)
            } else {
                @Suppress("DEPRECATION")
                view.recycler_view.viewTreeObserver.removeGlobalOnLayoutListener(this)
            }
            adapter?.itemCount?.takeIf { it > 0 }?.let {
                view.recycler_view.scrollToPosition(it - 1)
            }
        }
    })
}

You can also add a check of viewTreeObserver.isAlive like in https://stackoverflow.com/a/39001731/2914140.

How to use ClassLoader.getResources() correctly?

This is the simplest wat to get the File object to which a certain URL object is pointing at:

File file=new File(url.toURI());

Now, for your concrete questions:

  • finding all resources in the META-INF "directory":

You can indeed get the File object pointing to this URL

Enumeration<URL> en=getClass().getClassLoader().getResources("META-INF");
if (en.hasMoreElements()) {
    URL metaInf=en.nextElement();
    File fileMetaInf=new File(metaInf.toURI());

    File[] files=fileMetaInf.listFiles();
    //or 
    String[] filenames=fileMetaInf.list();
}
  • all resources named bla.xml (recursivly)

In this case, you'll have to do some custom code. Here is a dummy example:

final List<File> foundFiles=new ArrayList<File>();

FileFilter customFilter=new FileFilter() {
    @Override
    public boolean accept(File pathname) {

        if(pathname.isDirectory()) {
            pathname.listFiles(this);
        }
        if(pathname.getName().endsWith("bla.xml")) {
            foundFiles.add(pathname);
            return true;
        }
        return false;
    }

};      
//rootFolder here represents a File Object pointing the root forlder of your search 
rootFolder.listFiles(customFilter);

When the code is run, you'll get all the found ocurrences at the foundFiles List.

How to export data from Spark SQL to CSV

With the help of spark-csv we can write to a CSV file.

val dfsql = sqlContext.sql("select * from tablename")
dfsql.write.format("com.databricks.spark.csv").option("header","true").save("output.csv")`

How do I convert csv file to rdd

I'd recommend reading the header directly from the driver, not through Spark. Two reasons for this: 1) It's a single line. There's no advantage to a distributed approach. 2) We need this line in the driver, not the worker nodes.

It goes something like this:

// Ridiculous amount of code to read one line.
val uri = new java.net.URI(filename)
val conf = sc.hadoopConfiguration
val fs = hadoop.fs.FileSystem.get(uri, conf)
val path = new hadoop.fs.Path(filename)
val stream = fs.open(path)
val source = scala.io.Source.fromInputStream(stream)
val header = source.getLines.head

Now when you make the RDD you can discard the header.

val csvRDD = sc.textFile(filename).filter(_ != header)

Then we can make an RDD from one column, for example:

val idx = header.split(",").indexOf(columnName)
val columnRDD = csvRDD.map(_.split(",")(idx))

How to use multiple databases in Laravel

Actually, DB::connection('name')->select(..) doesnt work for me, because 'name' has to be in double quotes: "name"

Still, the select query is executed on my default connection. Still trying to figure out, how to convince Laravel to work the way it is intended: change the connection.

Edit: I figured it out. After debugging Laravels DatabaseManager it turned out my database.php (config file) (inside $this->app) was wrong. In the section "connections" I had stuff like "database" with values of the one i copied it from. In clear terms, instead of

env('DB_DATABASE', 'name')

I needed to place something like

'myNewName'

since all connections were listed with the same values for the database, username, password, etc. which of course makes little sense if I want to access at least another database name

Therefore, every time I wanted to select something from another database I always ended up in my default database

How can I subset rows in a data frame in R based on a vector of values?

Per the comments to the original post, merges / joins are well-suited for this problem. In particular, an inner join will return only values that are present in both dataframes, making thesetdiff statement unnecessary.

Using the data from Dinre's example:

In base R:

cleanedA <- merge(data_A, data_B[, "index"], by = 1, sort = FALSE)
cleanedB <- merge(data_B, data_A[, "index"], by = 1, sort = FALSE)

Using the dplyr package:

library(dplyr)
cleanedA <- inner_join(data_A, data_B %>% select(index))
cleanedB <- inner_join(data_B, data_A %>% select(index))

To keep the data as two separate tables, each containing only its own variables, this subsets the unwanted table to only its index variable before joining. Then no new variables are added to the resulting table.

Console logging for react?

Here are some more console logging "pro tips":

console.table

var animals = [
    { animal: 'Horse', name: 'Henry', age: 43 },
    { animal: 'Dog', name: 'Fred', age: 13 },
    { animal: 'Cat', name: 'Frodo', age: 18 }
];

console.table(animals);

console.table

console.trace

Shows you the call stack for leading up to the console.

console.trace

You can even customise your consoles to make them stand out

console.todo = function(msg) {
    console.log(‘ % c % s % s % s‘, ‘color: yellow; background - color: black;’, ‘–‘, msg, ‘–‘);
}

console.important = function(msg) {
    console.log(‘ % c % s % s % s’, ‘color: brown; font - weight: bold; text - decoration: underline;’, ‘–‘, msg, ‘–‘);
}

console.todo(“This is something that’ s need to be fixed”);
console.important(‘This is an important message’);

console.todo

If you really want to level up don't limit your self to the console statement.

Here is a great post on how you can integrate a chrome debugger right into your code editor!

https://hackernoon.com/debugging-react-like-a-champ-with-vscode-66281760037

Mocking a function to raise an Exception to test an except block

Your mock is raising the exception just fine, but the error.resp.status value is missing. Rather than use return_value, just tell Mock that status is an attribute:

barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')

Additional keyword arguments to Mock() are set as attributes on the resulting object.

I put your foo and bar definitions in a my_tests module, added in the HttpError class so I could use it too, and your test then can be ran to success:

>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
...     barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
...     result = my_test.foo()
... 
404 - 
>>> result is None
True

You can even see the print '404 - %s' % error.message line run, but I think you wanted to use error.content there instead; that's the attribute HttpError() sets from the second argument, at any rate.

how to run a winform from console application?

You should be able to use the Application class in the same way as Winform apps do. Probably the easiest way to start a new project is to do what Marc suggested: create a new Winform project, and then change it in the options to a console application

How do I get the height of a div's full content with jQuery?

scrollHeight is a property of a DOM object, not a function:

Height of the scroll view of an element; it includes the element padding but not its margin.

Given this:

<div id="x" style="height: 100px; overflow: hidden;">
    <div style="height: 200px;">
        pancakes
    </div>
</div>

This yields 200:

$('#x')[0].scrollHeight

For example: http://jsfiddle.net/ambiguous/u69kQ/2/ (run with the JavaScript console open).

How to write a shell script that runs some commands as superuser and some commands not as superuser, without having to babysit it?

If you use this, check man sudo too:

#!/bin/bash

sudo echo "Hi, I'm root"

sudo -u nobody echo "I'm nobody"

sudo -u 1000 touch /test_user

Exception: There is already an open DataReader associated with this Connection which must be closed first

The issue you are running into is that you are starting up a second MySqlCommand while still reading back data with the DataReader. The MySQL connector only allows one concurrent query. You need to read the data into some structure, then close the reader, then process the data. Unfortunately you can't process the data as it is read if your processing involves further SQL queries.

How to open a new window on form submit

I generally use a small jQuery snippet globally to open any external links in a new tab / window. I've added the selector for a form for my own site and it works fine so far:

// URL target
    $('a[href*="//"]:not([href*="'+ location.hostname +'"]),form[action*="//"]:not([href*="'+ location.hostname +'"]').attr('target','_blank');

Excel Calculate the date difference from today from a cell of "7/6/2012 10:26:42"

=ROUND((TODAY()-A1)/365,0) will provide number of years between date in cell A1 and today's date

What does enctype='multipart/form-data' mean?

enctype='multipart/form-data' means that no characters will be encoded. that is why this type is used while uploading files to server.
So multipart/form-data is used when a form requires binary data, like the contents of a file, to be uploaded

Sql select rows containing part of string

You can use the LIKE operator to compare the content of a T-SQL string, e.g.

SELECT * FROM [table] WHERE [field] LIKE '%stringtosearchfor%'.

The percent character '%' is a wild card- in this case it says return any records where [field] at least contains the value "stringtosearchfor".

Javascript wait() function

Javascript isn't threaded, so a "wait" would freeze the entire page (and probably cause the browser to stop running the script entirely).

To specifically address your problem, you should remove the brackets after donothing in your setTimeout call, and make waitsecs a number not a string:

console.log('before');
setTimeout(donothing,500); // run donothing after 0.5 seconds
console.log('after');

But that won't stop execution; "after" will be logged before your function runs.

To wait properly, you can use anonymous functions:

console.log('before');
setTimeout(function(){
    console.log('after');
},500);

All your variables will still be there in the "after" section. You shouldn't chain these - if you find yourself needing to, you need to look at how you're structuring the program. Also you may want to use setInterval / clearInterval if it needs to loop.

T-SQL XOR Operator

Using boolean algebra, it is easy to show that:

A xor B = (not A and B) or (A and not B)


A B | f = notA and B | g = A and notB | f or g | A xor B    
----+----------------+----------------+--------+--------    
0 0 | 0              | 0              | 0      | 0    
0 1 | 1              | 0              | 1      | 1    
1 0 | 0              | 1              | 1      | 1    
1 1 | 0              | 0              | 0      | 0

How can I change default dialog button text color in android 5

Here's a natural way to do it with styles:

If your AppTheme is inherited from Theme.MaterialComponents, then:

<style name="AlertDialogTheme" parent="ThemeOverlay.MaterialComponents.Dialog.Alert">
    <item name="buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
    <item name="buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
</style>

<style name="NegativeButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
    <item name="android:textColor">#f00</item>
</style>

<style name="PositiveButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
    <item name="android:textColor">#00f</item>
</style>

If your AppTheme is inherited from Theme.AppCompat:

<style name="AlertDialogTheme" parent="ThemeOverlay.AppCompat.Dialog.Alert">
    <item name="buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
    <item name="buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
</style>

<style name="NegativeButtonStyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
    <item name="android:textColor">#f00</item>
</style>

<style name="PositiveButtonStyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
    <item name="android:textColor">#00f</item>
</style>

Use your AlertDialogTheme in your AppTheme

<item name="alertDialogTheme">@style/AlertDialogTheme</item>

or in constructor

androidx.appcompat.app.AlertDialog.Builder(context, R.style.AlertDialogTheme)

"No X11 DISPLAY variable" - what does it mean?

Don't forget to execute "host +" on your "home" display machine, and when you ssh to the machine you're doing "ssh -x hostname"

How to ignore files/directories in TFS for avoiding them to go to central source repository?

I found the perfect way to Ignore files in TFS like SVN does.
First of all, select the file that you want to ignore (e.g. the Web.config).
Now go to the menu tab and select:

File Source control > Advanced > Exclude web.config from source control

... and boom; your file is permanently excluded from source control.

How many concurrent requests does a single Flask process receive?

No- you can definitely handle more than that.

Its important to remember that deep deep down, assuming you are running a single core machine, the CPU really only runs one instruction* at a time.

Namely, the CPU can only execute a very limited set of instructions, and it can't execute more than one instruction per clock tick (many instructions even take more than 1 tick).

Therefore, most concurrency we talk about in computer science is software concurrency. In other words, there are layers of software implementation that abstract the bottom level CPU from us and make us think we are running code concurrently.

These "things" can be processes, which are units of code that get run concurrently in the sense that each process thinks its running in its own world with its own, non-shared memory.

Another example is threads, which are units of code inside processes that allow concurrency as well.

The reason your 4 worker processes will be able to handle more than 4 requests is that they will fire off threads to handle more and more requests.

The actual request limit depends on HTTP server chosen, I/O, OS, hardware, network connection etc.

Good luck!

*instructions are the very basic commands the CPU can run. examples - add two numbers, jump from one instruction to another

Return from a promise then()

You cannot return value after resolving promise. Instead call another function when promise is resolved:

function justTesting() {
    promise.then(function(output) {
        // instead of return call another function
        afterResolve(output + 1);
    });
}

function afterResolve(result) {
    // do something with result
}

var test = justTesting();

Show Youtube video source into HTML5 video tag?

how about doing it the way hooktube does it? they don't actually use the video URL for the html5 element, but the google video redirector url that calls upon that video. check out here's how they present some despacito random video...

<video id="player-obj" controls="" src="https://redirector.googlevideo.com/videoplayback?ratebypass=yes&amp;mt=1510077993----SKIPPED----amp;utmg=ytap1,,hd720"><source>Your browser does not support HTML5 video.</video>

the code is for the following video page https://hooktube.com/watch?v=72UO0v5ESUo

youtube to mp3 on the other hand has turned into extremely monetized monster that returns now download.html on half of video download requests... annoying...

the 2 links in this answer are to my personal experiences with both resources. how hooktube is nice and fresh and actually helps avoid censorship and geo restrictions.. check it out, it's pretty cool. and youtubeinmp4 is a popup monster now known as ConvertInMp4...

jQuery Set Cursor Position in Text Area

I found a solution that works for me:

$.fn.setCursorPosition = function(position){
    if(this.length == 0) return this;
    return $(this).setSelection(position, position);
}

$.fn.setSelection = function(selectionStart, selectionEnd) {
    if(this.length == 0) return this;
    var input = this[0];

    if (input.createTextRange) {
        var range = input.createTextRange();
        range.collapse(true);
        range.moveEnd('character', selectionEnd);
        range.moveStart('character', selectionStart);
        range.select();
    } else if (input.setSelectionRange) {
        input.focus();
        input.setSelectionRange(selectionStart, selectionEnd);
    }

    return this;
}

$.fn.focusEnd = function(){
    this.setCursorPosition(this.val().length);
            return this;
}

Now you can move the focus to the end of any element by calling:

$(element).focusEnd();

Or you specify the position.

$(element).setCursorPosition(3); // This will focus on the third character.

AngularJS ng-class if-else expression

You can try this method:

</p><br /><br />
<p>ng-class="{test: obj.value1 == 'someothervalue' || obj.value2 == 'somethingelse'}<br /><br /><br />

ng-class="{test: obj.value1 == 'someothervalue' || obj.value2 == 'somethingelse'}

You can get complete details from here.

How to change font size on part of the page in LaTeX?

Example:

\Large\begin{verbatim}
   <how to set font size here to 10 px ? />
\end{verbatim}
\normalsize

\Large can be obviously substituted by one of:

\tiny
\scriptsize
\footnotesize
\small
\normalsize
\large
\Large
\LARGE
\huge
\Huge

If you need arbitrary font sizes:

How do you access the value of an SQL count () query in a Java program

I have done it this way (example):

String query="SELECT count(t1.id) from t1, t2 where t1.id=t2.id and t2.email='"[email protected]"'";
int count=0;
try {
    ResultSet rs = DatabaseService.statementDataBase().executeQuery(query);
    while(rs.next())
        count=rs.getInt(1);
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    //...
}

Embedding JavaScript engine into .NET

I just tried RemObjects Script for .Net.

It works, although I had to use a static factory (var a=A.createA();) from JavaScript instead of the var a=new A() syntax. (ExposeType function only exposes statics!) Not much documentation and the source is written with Delphi Prism, which is rather unusual for me and the RedGate Reflector.

So: Easy to use and setup, but not much help for advanced scenarios.

Also having to install something instead of just dropping the assemblies in a directory is a negative for me...

How to use a SQL SELECT statement with Access VBA

Access 2007 can lose the CurrentDb: see http://support.microsoft.com/kb/167173, so in the event of getting "Object Invalid or no longer set" with the examples, use:

Dim db as Database
Dim rs As DAO.Recordset
Set db = CurrentDB
Set rs = db.OpenRecordset("SELECT * FROM myTable")

matplotlib has no attribute 'pyplot'

pyplot is a sub-module of matplotlib which doesn't get imported with a simple import matplotlib.

>>> import matplotlib
>>> print matplotlib.pyplot
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
>>> import matplotlib.pyplot
>>> 

It seems customary to do: import matplotlib.pyplot as plt at which time you can use the various functions and classes it contains:

p = plt.plot(...)

How do I fix "Expected to return a value at the end of arrow function" warning?

The most upvoted answer, from Kris Selbekk, it is totally right. It is important to highlight though that it takes a functional approach, you will be looping through the this.props.comments array twice, the second time(looping) it will most probable skip a few elements that where filtered, but in case no comment was filtered you will loop through the whole array twice. If performance is not a concern in you project that is totally fine. In case performance is important a guard clause would be more appropriated as you would loop the array only once:

return this.props.comments.map((comment) => {
  if (!comment.hasComments) return null; 

  return (
    <div key={comment.id}>         
      <CommentItem className="MainComment"/>
        {this.props.comments.map(commentReply => {             
          if (commentReply.replyTo !== comment.id) return null;

          return <CommentItem className="SubComment"/>
        })} 
    </div>          
  ) 
}

The main reason I'm pointing this out is because as a Junior Developer I did a lot of those mistakes(like looping the same array multiple times), so I thought i was worth mention it here.

PS: I would refactor your react component even more, as I'm not in favour of heavy logic in the html part of a JSX, but that is out of the topic of this question.

How can I process each letter of text using Javascript?

If the order of alerts matters, use this:

for (var i = 0; i < str.length; i++) {
  alert(str.charAt(i));
}

Or this: (see also this answer)

 for (var i = 0; i < str.length; i++) {
   alert(str[i]);
 }

If the order of alerts doesn't matter, use this:

var i = str.length;
while (i--) {
  alert(str.charAt(i));
}

Or this: (see also this answer)

 var i = str.length;
while (i--) {
  alert(str[i]);
}

_x000D_
_x000D_
var str = 'This is my string';

function matters() {
  for (var i = 0; i < str.length; i++) {
    alert(str.charAt(i));
  }
}

function dontmatter() {
  var i = str.length;
  while (i--) {
    alert(str.charAt(i));
  }
}
_x000D_
<p>If the order of alerts matters, use <a href="#" onclick="matters()">this</a>.</p>

<p>If the order of alerts doesn't matter, use <a href="#" onclick="dontmatter()">this</a>.</p>
_x000D_
_x000D_
_x000D_

ie8 var w= window.open() - "Message: Invalid argument."

I also meet this issue while I used the following code:

window.open('test.html','Window title','width=1200,height=800,scrollbars=yes');

but when I delete the blank space of the "Window title" the below code is working:

window.open('test.html','Windowtitle','width=1200,height=800,scrollbars=yes');

Git pull after forced update

This won't fix branches that already have the code you don't want in them (see below for how to do that), but if they had pulled some-branch and now want it to be clean (and not "ahead" of origin/some-branch) then you simply:

git checkout some-branch   # where some-branch can be replaced by any other branch
git branch base-branch -D  # where base-branch is the one with the squashed commits
git checkout -b base-branch origin/base-branch  # recreating branch with correct commits

Note: You can combine these all by putting && between them

Note2: Florian mentioned this in a comment, but who reads comments when looking for answers?

Note3: If you have contaminated branches, you can create new ones based off the new "dumb branch" and just cherry-pick commits over.

Ex:

git checkout feature-old  # some branch with the extra commits
git log                   # gives commits (write down the id of the ones you want)
git checkout base-branch  # after you have already cleaned your local copy of it as above
git checkout -b feature-new # make a new branch for your feature
git cherry-pick asdfasd   # where asdfasd is one of the commit ids you want
# repeat previous step for each commit id
git branch feature-old -D # delete the old branch

Now feature-new is your branch without the extra (possibly bad) commits!

How to load a UIView using a nib file created with Interface Builder

I would use UINib to instantiate a custom UIView to be reused

UINib *customNib = [UINib nibWithNibName:@"MyCustomView" bundle:nil];
MyCustomViewClass *customView = [[customNib instantiateWithOwner:self options:nil] objectAtIndex:0];
[self.view addSubview:customView];

Files needed in this case are MyCustomView.xib, MyCustomViewClass.h and MyCustomViewClass.m Note that [UINib instantiateWithOwner] returns an array, so you should use the element which reflects the UIView you want to re-use. In this case it's the first element.

Unable to copy ~/.ssh/id_rsa.pub

Try this and it will work like a charm. I was having the same error but this approach did the trick for me:

ssh USER@REMOTE "cat file"|xclip -i

Swift performSelector:withObject:afterDelay: is unavailable

Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
    // your function here
}

Swift 3

DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(0.1)) {
    // your function here
}

Swift 2

let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))) 
dispatch_after(dispatchTime, dispatch_get_main_queue(), { 
    // your function here 
})

get enum name from enum value

Since your 'value' also happens to match with ordinals you could just do:

public enum RelationActiveEnum {
    Invited,
    Active,
    Suspended;

    private final int value;

    private RelationActiveEnum() {
        this.value = ordinal();
    }
}

And getting a enum from the value:

int value = 1;
RelationActiveEnum enumInstance = RelationActiveEnum.values()[value];

I guess an static method would be a good place to put this:

public enum RelationActiveEnum {
     public static RelationActiveEnum fromValue(int value) 
             throws IllegalArgumentException {
         try {
              return RelationActiveEnum.values()[value]
         } catch(ArrayIndexOutOfBoundsException e) {
              throw new IllegalArgumentException("Unknown enum value :"+ value);
         }
     }
}   

Obviously this all falls apart if your 'value' isn't the same value as the enum ordinal.

How to copy java.util.list Collection

Use the ArrayList copy constructor, then sort that.

List oldList;
List newList = new ArrayList(oldList);
Collections.sort(newList);

After making the copy, any changes to newList do not affect oldList.

Note however that only the references are copied, so the two lists share the same objects, so changes made to elements of one list affect the elements of the other.

Convert array of strings into a string in Java

String array[]={"one","two"};
String s="";

for(int i=0;i<array.length;i++)
{
  s=s+array[i];
}

System.out.print(s);

how to properly display an iFrame in mobile safari

Purely using MSchimpf and Ahmad's code, I made adjustments so I could have the iframe within a div, therefore keeping a header and footer for back button and branding on my page. Updated code:

<script type="text/javascript">
    $("#webview").bind('pagebeforeshow', function(event){
        $("#iframe").attr('src',cwebview);
    });

    if (navigator.userAgent.indexOf('iPhone') != -1 || navigator.userAgent.indexOf('iPad') != -1)
    {
        $("#webview-content").css("width","100%");
        $("#webview-content").css("height","100%");
        $("#iframe").load(function (){ // Wait until iFrame content is loaded before checking dimensions of the content
            iframeWidth = $("#iframe").contents().width();
            if (iframeWidth > 400)
               $("#webview-content").css("width",(iframeWidth + 182) + 'px');

            iframeHeight = $("#iframe").contents().height();
            if (iframeHeight>200)
                $("#webview-content").css("height",iframeHeight + 'px');
         });
    }       
</script>  

and the html

<div class="header" data-role="header" data-position="fixed">
</div>

<div id="webview-content" data-role="content" style="height:380px;">
    <iframe id="iframe"></iframe>   
</div><!-- /content -->

<div class="footer" data-role="footer" data-position="fixed">
</div><!-- /footer -->   

In Angular, I need to search objects in an array

Saw this thread but I wanted to search for IDs that did not match my search. Code to do that:

found = $filter('filter')($scope.fish, {id: '!fish_id'}, false);

Winforms issue - Error creating window handle

I got same error in my application.I am loading many controls in single page.In button click event i am clearing the controls.clearing the controls doesnot release the controls from memory.So dispose the controls from memory. I just commented controls.clear() method and include few lines of code to dispose the controls. Something like this

for each ctl as control in controlcollection

ctl.dispose()

Next

How can I use pointers in Java?

Java does have pointers. Any time you create an object in Java, you're actually creating a pointer to the object; this pointer could then be set to a different object or to null, and the original object will still exist (pending garbage collection).

What you can't do in Java is pointer arithmetic. You can't dereference a specific memory address or increment a pointer.

If you really want to get low-level, the only way to do it is with the Java Native Interface; and even then, the low-level part has to be done in C or C++.

Split a String into an array in Swift?

Swift 2.2 Error Handling & capitalizedString Added :

func setFullName(fullName: String) {
    var fullNameComponents = fullName.componentsSeparatedByString(" ")

    self.fname = fullNameComponents.count > 0 ? fullNameComponents[0]: ""
    self.sname = fullNameComponents.count > 1 ? fullNameComponents[1]: ""

    self.fname = self.fname!.capitalizedString
    self.sname = self.sname!.capitalizedString
}

Non-static variable cannot be referenced from a static context

The very basic thing is static variables or static methods are at class level. Class level variables or methods gets loaded prior to instance level methods or variables.And obviously the thing which is not loaded can not be used. So java compiler not letting the things to be handled at run time resolves at compile time. That's why it is giving you error non-static things can not be referred from static context. You just need to read about Class Level Scope, Instance Level Scope and Local Scope.

How to extract custom header value in Web API message handler?

Create a new method - 'Returns an individual HTTP Header value' and call this method with key value everytime when you need to access multiple key Values from HttpRequestMessage.

public static string GetHeader(this HttpRequestMessage request, string key)
        {
            IEnumerable<string> keys = null;
            if (!request.Headers.TryGetValues(key, out keys))
                return null;

            return keys.First();
        }

Java Enum return Int

You can try this code .

private enum DownloadType {
    AUDIO , VIDEO , AUDIO_AND_VIDEO ;

}

You can use this enumeration as like this : DownloadType.AUDIO.ordinal(). Hope this code snippet will help you .

JavaScript DOM remove element

Seems I don't have enough rep to post a comment, so another answer will have to do.

When you unlink a node using removeChild() or by setting the innerHTML property on the parent, you also need to make sure that there is nothing else referencing it otherwise it won't actually be destroyed and will lead to a memory leak. There are lots of ways in which you could have taken a reference to the node before calling removeChild() and you have to make sure those references that have not gone out of scope are explicitly removed.

Doug Crockford writes here that event handlers are known a cause of circular references in IE and suggests removing them explicitly as follows before calling removeChild()

function purge(d) {
    var a = d.attributes, i, l, n;
    if (a) {
        for (i = a.length - 1; i >= 0; i -= 1) {
            n = a[i].name;
            if (typeof d[n] === 'function') {
                d[n] = null;
            }
        }
    }
    a = d.childNodes;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            purge(d.childNodes[i]);
        }
    }
}

And even if you take a lot of precautions you can still get memory leaks in IE as described by Jens-Ingo Farley here.

And finally, don't fall into the trap of thinking that Javascript delete is the answer. It seems to be suggested by many, but won't do the job. Here is a great reference on understanding delete by Kangax.

How do I remove repeated elements from ArrayList?

When you are filling the ArrayList, use a condition for each element. For example:

    ArrayList< Integer > al = new ArrayList< Integer >(); 

    // fill 1 
    for ( int i = 0; i <= 5; i++ ) 
        if ( !al.contains( i ) ) 
            al.add( i ); 

    // fill 2 
    for (int i = 0; i <= 10; i++ ) 
        if ( !al.contains( i ) ) 
            al.add( i ); 

    for( Integer i: al )
    {
        System.out.print( i + " ");     
    }

We will get an array {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

Show Error on the tip of the Edit Text Android

Using Kotlin Language,

EXAMPLE CODE

 login_ID.setOnClickListener {
            if(email_address_Id.text.isEmpty()){
                email_address_Id.error = "Please Enter Email Address"
            }
            if(Password_ID.text.isEmpty()){
                Password_ID.error = "Please Enter Password"
            }
        }

How can I convert string to datetime with format specification in JavaScript?

I think this can help you: http://www.mattkruse.com/javascript/date/

There's a getDateFromFormat() function that you can tweak a little to solve your problem.

Update: there's an updated version of the samples available at javascripttoolbox.com

Using module 'subprocess' with timeout

In Python 3.3+:

from subprocess import STDOUT, check_output

output = check_output(cmd, stderr=STDOUT, timeout=seconds)

output is a byte string that contains command's merged stdout, stderr data.

check_output raises CalledProcessError on non-zero exit status as specified in the question's text unlike proc.communicate() method.

I've removed shell=True because it is often used unnecessarily. You can always add it back if cmd indeed requires it. If you add shell=True i.e., if the child process spawns its own descendants; check_output() can return much later than the timeout indicates, see Subprocess timeout failure.

The timeout feature is available on Python 2.x via the subprocess32 backport of the 3.2+ subprocess module.

php string to int

If you want to leave only numbers - use preg_replace like: (int)preg_replace("/[^\d]+/","",$b).

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

The following script works for me for multiple values of $COLUMNS. I wonder if you are not setting COLUMNS prior to this call?

#!/bin/bash
COLUMNS=30
svn diff $@ --diff-cmd /usr/bin/diff -x "-y -w -p -W $COLUMNS"

Can you echo $COLUMNS inside your script to see if it set correctly?

Get the directory from a file path in java (android)

Yes. First, construct a File representing the image path:

File file = new File(a);

If you're starting from a relative path:

file = new File(file.getAbsolutePath());

Then, get the parent:

String dir = file.getParent();

Or, if you want the directory as a File object,

File dirAsFile = file.getParentFile();

How to trigger Jenkins builds remotely and to pass parameters

You can trigger Jenkins builds remotely and to pass parameters by using the following query.

JENKINS_URL/job/job-name/buildWithParameters?token=TOKEN_NAME&param_name1=value&param_name1=value

JENKINS_URL (can be) = https://<your domain name or server address>

TOKE_NAME can be created using configure tab

How to print pandas DataFrame without index

To answer the "How to print dataframe without an index" question, you can set the index to be an array of empty strings (one for each row in the dataframe), like this:

blankIndex=[''] * len(df)
df.index=blankIndex

If we use the data from your post:

row1 = (123, '2014-07-08 00:09:00', 1411)
row2 = (123, '2014-07-08 00:49:00', 1041)
row3 = (123, '2014-07-08 00:09:00', 1411)
data = [row1, row2, row3]
#set up dataframe
df = pd.DataFrame(data, columns=('User ID', 'Enter Time', 'Activity Number'))
print(df)

which would normally print out as:

   User ID           Enter Time  Activity Number
0      123  2014-07-08 00:09:00             1411
1      123  2014-07-08 00:49:00             1041
2      123  2014-07-08 00:09:00             1411

By creating an array with as many empty strings as there are rows in the data frame:

blankIndex=[''] * len(df)
df.index=blankIndex
print(df)

It will remove the index from the output:

  User ID           Enter Time  Activity Number
      123  2014-07-08 00:09:00             1411
      123  2014-07-08 00:49:00             1041
      123  2014-07-08 00:09:00             1411

And in Jupyter Notebooks would render as per this screenshot: Juptyer Notebooks dataframe with no index column

How to add a custom HTTP header to every WCF call?

If you just want to add the same header to all the requests to the service, you can do it with out any coding!
Just add the headers node with required headers under the endpoint node in your client config file

<client>  
  <endpoint address="http://localhost/..." >  
    <headers>  
      <HeaderName>Value</HeaderName>  
    </headers>   
 </endpoint>  

MySQL DELETE FROM with subquery as condition

@CodeReaper, @BennyHill: It works as expected.

However, I wonder the time complexity for having millions of rows in the table? Apparently, it took about 5ms to execute for having 5k records on a correctly indexed table.

My Query:

SET status = '1'
WHERE id IN (
    SELECT id
    FROM (
      SELECT c2.id FROM clusters as c2
      WHERE c2.assign_to_user_id IS NOT NULL
        AND c2.id NOT IN (
         SELECT c1.id FROM clusters AS c1
           LEFT JOIN cluster_flags as cf on c1.last_flag_id = cf.id
           LEFT JOIN flag_types as ft on ft.id = cf.flag_type_id
         WHERE ft.slug = 'closed'
         )
      ) x)```

Or is there something we can improve on my query above?

Checking if a number is a prime number in Python

def prime(x):
    # check that number is greater that 1
    if x > 1:
        for i in range(2, x + 1):
            # check that only x and 1 can evenly divide x
            if x % i == 0 and i != x and i != 1:
                return False
        else:
            return True
    else:
        return False # if number is negative

How to save a list to a file and read it as a list type?

If you don't want to use pickle, you can store the list as text and then evaluate it:

data = [0,1,2,3,4,5]
with open("test.txt", "w") as file:
    file.write(str(data))

with open("test.txt", "r") as file:
    data2 = eval(file.readline())

# Let's see if data and types are same.
print(data, type(data), type(data[0]))
print(data2, type(data2), type(data2[0]))

[0, 1, 2, 3, 4, 5] class 'list' class 'int'

[0, 1, 2, 3, 4, 5] class 'list' class 'int'

Complex JSON nesting of objects and arrays

The first code is an example of Javascript code, which is similar, however not JSON. JSON would not have 1) comments and 2) the var keyword

You don't have any comments in your JSON, but you should remove the var and start like this:

orders: {

The [{}] notation means "object in an array" and is not what you need everywhere. It is not an error, but it's too complicated for some purposes. AssociatedDrug should work well as an object:

"associatedDrug": {
                "name":"asprin",
                "dose":"",
                "strength":"500 mg"
          }

Also, the empty object labs should be filled with something.

Other than that, your code is okay. You can either paste it into javascript, or use the JSON.parse() method, or any other parsing method (please don't use eval)

Update 2 answered:

obj.problems[0].Diabetes[0].medications[0].medicationsClasses[0].className[0].associatedDrug[0].name

returns 'aspirin'. It is however better suited for foreaches everywhere

Update React component every second

In the component's componentDidMount lifecycle method, you can set an interval to call a function which updates the state.

 componentDidMount() {
      setInterval(() => this.setState({ time: Date.now()}), 1000)
 }

Creating files and directories via Python

import os

path = chap_name

if not os.path.exists(path):
    os.makedirs(path)

filename = img_alt + '.jpg'
with open(os.path.join(path, filename), 'wb') as temp_file:
    temp_file.write(buff)

Key point is to use os.makedirs in place of os.mkdir. It is recursive, i.e. it generates all intermediate directories. See http://docs.python.org/library/os.html

Open the file in binary mode as you are storing binary (jpeg) data.

In response to Edit 2, if img_alt sometimes has '/' in it:

img_alt = os.path.basename(img_alt)

Is there a way to get version from package.json in nodejs code?

You can use ES6 to import package.json to retrieve version number and output the version on console.

import {name as app_name, version as app_version}  from './path/to/package.json';

console.log(`App ---- ${app_name}\nVersion ---- ${app_version}`);

Html Agility Pack get all elements by class

(Updated 2018-03-17)

The problem:

The problem, as you've spotted, is that String.Contains does not perform a word-boundary check, so Contains("float") will return true for both "foo float bar" (correct) and "unfloating" (which is incorrect).

The solution is to ensure that "float" (or whatever your desired class-name is) appears alongside a word-boundary at both ends. A word-boundary is either the start (or end) of a string (or line), whitespace, certain punctuation, etc. In most regular-expressions this is \b. So the regex you want is simply: \bfloat\b.

A downside to using a Regex instance is that they can be slow to run if you don't use the .Compiled option - and they can be slow to compile. So you should cache the regex instance. This is more difficult if the class-name you're looking for changes at runtime.

Alternatively you can search a string for words by word-boundaries without using a regex by implementing the regex as a C# string-processing function, being careful not to cause any new string or other object allocation (e.g. not using String.Split).

Approach 1: Using a regular-expression:

Suppose you just want to look for elements with a single, design-time specified class-name:

class Program {

    private static readonly Regex _classNameRegex = new Regex( @"\bfloat\b", RegexOptions.Compiled );

    private static IEnumerable<HtmlNode> GetFloatElements(HtmlDocument doc) {
        return doc
            .Descendants()
            .Where( n => n.NodeType == NodeType.Element )
            .Where( e => e.Name == "div" && _classNameRegex.IsMatch( e.GetAttributeValue("class", "") ) );
    }
}

If you need to choose a single class-name at runtime then you can build a regex:

private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String className) {

    Regex regex = new Regex( "\\b" + Regex.Escape( className ) + "\\b", RegexOptions.Compiled );

    return doc
        .Descendants()
        .Where( n => n.NodeType == NodeType.Element )
        .Where( e => e.Name == "div" && regex.IsMatch( e.GetAttributeValue("class", "") ) );
}

If you have multiple class-names and you want to match all of them, you could create an array of Regex objects and ensure they're all matching, or combine them into a single Regex using lookarounds, but this results in horrendously complicated expressions - so using a Regex[] is probably better:

using System.Linq;

private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String[] classNames) {

    Regex[] exprs = new Regex[ classNames.Length ];
    for( Int32 i = 0; i < exprs.Length; i++ ) {
        exprs[i] = new Regex( "\\b" + Regex.Escape( classNames[i] ) + "\\b", RegexOptions.Compiled );
    }

    return doc
        .Descendants()
        .Where( n => n.NodeType == NodeType.Element )
        .Where( e =>
            e.Name == "div" &&
            exprs.All( r =>
                r.IsMatch( e.GetAttributeValue("class", "") )
            )
        );
}

Approach 2: Using non-regex string matching:

The advantage of using a custom C# method to do string matching instead of a regex is hypothetically faster performance and reduced memory usage (though Regex may be faster in some circumstances - always profile your code first, kids!)

This method below: CheapClassListContains provides a fast word-boundary-checking string matching function that can be used the same way as regex.IsMatch:

private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String className) {

    return doc
        .Descendants()
        .Where( n => n.NodeType == NodeType.Element )
        .Where( e =>
            e.Name == "div" &&
            CheapClassListContains(
                e.GetAttributeValue("class", ""),
                className,
                StringComparison.Ordinal
            )
        );
}

/// <summary>Performs optionally-whitespace-padded string search without new string allocations.</summary>
/// <remarks>A regex might also work, but constructing a new regex every time this method is called would be expensive.</remarks>
private static Boolean CheapClassListContains(String haystack, String needle, StringComparison comparison)
{
    if( String.Equals( haystack, needle, comparison ) ) return true;
    Int32 idx = 0;
    while( idx + needle.Length <= haystack.Length )
    {
        idx = haystack.IndexOf( needle, idx, comparison );
        if( idx == -1 ) return false;

        Int32 end = idx + needle.Length;

        // Needle must be enclosed in whitespace or be at the start/end of string
        Boolean validStart = idx == 0               || Char.IsWhiteSpace( haystack[idx - 1] );
        Boolean validEnd   = end == haystack.Length || Char.IsWhiteSpace( haystack[end] );
        if( validStart && validEnd ) return true;

        idx++;
    }
    return false;
}

Approach 3: Using a CSS Selector library:

HtmlAgilityPack is somewhat stagnated doesn't support .querySelector and .querySelectorAll, but there are third-party libraries that extend HtmlAgilityPack with it: namely Fizzler and CssSelectors. Both Fizzler and CssSelectors implement QuerySelectorAll, so you can use it like so:

private static IEnumerable<HtmlNode> GetDivElementsWithFloatClass(HtmlDocument doc) {

    return doc.QuerySelectorAll( "div.float" );
}

With runtime-defined classes:

private static IEnumerable<HtmlNode> GetDivElementsWithClasses(HtmlDocument doc, IEnumerable<String> classNames) {

    String selector = "div." + String.Join( ".", classNames );

    return doc.QuerySelectorAll( selector  );
}

Back to previous page with header( "Location: " ); in PHP

Just try this in Javascript:

 $previous = "javascript:history.go(-1)";

Or you can try it in PHP:

if(isset($_SERVER['HTTP_REFERER'])) {
    $previous = $_SERVER['HTTP_REFERER'];
}

Scope 'session' is not active for the current thread; IllegalStateException: No thread-bound request found

Had the same error when I had @Order annotation on a filter class. Even thou I added the filter through the HttpSecurity chain.

Removed the @Order and it worked.

How to set env variable in Jupyter notebook

A related (short-term) solution is to store your environment variables in a single file, with a predictable format, that can be sourced when starting a terminal and/or read into the notebook. For example, I have a file, .env, that has my environment variable definitions in the format VARIABLE_NAME=VARIABLE_VALUE (no blank lines or extra spaces). You can source this file in the .bashrc or .bash_profile files when beginning a new terminal session and you can read this into a notebook with something like,

import os
env_vars = !cat ../script/.env
for var in env_vars:
    key, value = var.split('=')
    os.environ[key] = value

I used a relative path to show that this .env file can live anywhere and be referenced relative to the directory containing the notebook file. This also has the advantage of not displaying the variable values within your code anywhere.

Column name or number of supplied values does not match table definition

The computed columns make the problem. Do not use SELECT *. You must specify each fields after SELECT except computed fields

How to get a path to the desktop for current user in C#?

// Environment.GetFolderPath
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // Current User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); // All User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles); // Program Files
Environment.GetFolderPath(Environment.SpecialFolder.Cookies); // Internet Cookie
Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Logical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); // Physical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.Favorites); // Favorites
Environment.GetFolderPath(Environment.SpecialFolder.History); // Internet History
Environment.GetFolderPath(Environment.SpecialFolder.InternetCache); // Internet Cache
Environment.GetFolderPath(Environment.SpecialFolder.MyComputer); // "My Computer" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // "My Documents" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyMusic); // "My Music" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); // "My Pictures" Folder
Environment.GetFolderPath(Environment.SpecialFolder.Personal); // "My Document" Folder
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); // Program files Folder
Environment.GetFolderPath(Environment.SpecialFolder.Programs); // Programs Folder
Environment.GetFolderPath(Environment.SpecialFolder.Recent); // Recent Folder
Environment.GetFolderPath(Environment.SpecialFolder.SendTo); // "Sent to" Folder
Environment.GetFolderPath(Environment.SpecialFolder.StartMenu); // Start Menu
Environment.GetFolderPath(Environment.SpecialFolder.Startup); // Startup
Environment.GetFolderPath(Environment.SpecialFolder.System); // System Folder
Environment.GetFolderPath(Environment.SpecialFolder.Templates); // Document Templates

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

To understand, let's consider below code snippet:

struct Foo{};
struct Bar{};

int main(int argc, char** argv)
{
    Foo* f = new Foo;

    Bar* b1 = f;                              // (1)
    Bar* b2 = static_cast<Bar*>(f);           // (2)
    Bar* b3 = dynamic_cast<Bar*>(f);          // (3)
    Bar* b4 = reinterpret_cast<Bar*>(f);      // (4)
    Bar* b5 = const_cast<Bar*>(f);            // (5)

    return 0;
}

Only line (4) compiles without error. Only reinterpret_cast can be used to convert a pointer to an object to a pointer to an any unrelated object type.

One this to be noted is: The dynamic_cast would fail at run-time, however on most compilers it will also fail to compile because there are no virtual functions in the struct of the pointer being casted, meaning dynamic_cast will work with only polymorphic class pointers.

When to use C++ cast:

  • Use static_cast as the equivalent of a C-style cast that does value conversion, or when we need to explicitly up-cast a pointer from a class to its superclass.
  • Use const_cast to remove the const qualifier.
  • Use reinterpret_cast to do unsafe conversions of pointer types to and from integer and other pointer types. Use this only if we know what we are doing and we understand the aliasing issues.

Are Git forks actually Git clones?

Forking is done when you decide to contribute to some project. You would make a copy of the entire project along with its history logs. This copy is made entirely in your repository and once you make these changes, you issue a pull request. Now its up-to the owner of the source to accept your pull request and incorporate the changes into the original code.

Git clone is an actual command that allows users to get a copy of the source. git clone [URL] This should create a copy of [URL] in your own local repository.

TypeLoadException says 'no implementation', but it is implemented

FWIW, I got this when there was a config file that redirected to a non-existent version of a referenced assembly. Fusion logs for the win!

Which icon sizes should my Windows application's icon include?

After some testing with an icon with 8, 16, 20, 24, 32, 40, 48, 64, 96, 128 and 256 pixels (256 in PNG) in Windows 7:

  • At 100% resolution: Explorer uses 16, 40, 48, and 256. Windows Photo Viewer uses 96. Paint uses 256.
  • At 125% resolution: Explorer uses 20, 40, and 256. Windows Photo Viewer uses 96. Paint uses 256.
  • At 150% resolution: Explorer uses 24, 48, and 256. Windows Photo Viewer uses 96. Paint uses 256.
  • At 200% resolution: Explorer uses 40, 64, 96, and 256. Windows Photo Viewer uses 128. Paint uses 256.

So 8, 32 were never used (it's strange to me for 32) and 128 only by Windows Photo Viewer with a very high dpi screen, i.e. almot never used.

It means your icon should at least provide 16, 48 and 256 for Windows 7. For supporting newer screens with high resolutions, you should provide 16, 20, 24, 40, 48, 64, 96, and 256. For Windows 7, all pictures can be compressed using PNG but for backward compatibility with Windows XP, 16 to 48 should not be compressed.

How to get substring from string in c#?

it's easy to rewrite this code in C#...

This method works if your value it's between 2 substrings !

for example:

stringContent = "[myName]Alex[myName][color]red[color][etc]etc[etc]"

calls should be:

myNameValue = SplitStringByASubstring(stringContent , "[myName]")

colorValue = SplitStringByASubstring(stringContent , "[color]")

etcValue = SplitStringByASubstring(stringContent , "[etc]")

How to Code Double Quotes via HTML Codes

Google recommend that you don't use any of them, source.

There is no need to use entity references like &mdash, &rdquo, or &#x263a, assuming the same encoding (UTF-8) is used for files and editors as well as among teams.

Is there a reason you can't simply use "?

windows batch file rename

I am assuming you know the length of the part before the _ and after the underscore, as well as the extension. If you don't it might be more complex than a simple substring.

cd C:\path\to\the\files
for /f %%a IN ('dir /b *.jpg') do (
set p=%a:~0,3%
set q=%a:~4,4%
set b=%p_%q.jpg
ren %a %b
)

I just came up with this script, and I did not test it. Check out this and that for more info.

IF you want to assume you don't know the positions of the _ and the lengths and the extension, I think you could do something with for loops to check the index of the _, then the last index of the ., wrap it in a goto thing and make it work. If you're willing to go through that trouble, I'd suggest you use WindowsPowerShell (or Cygwin) at least (for your own sake) or install a more advanced scripting language (think Python/Perl) you'll get more support either way.

How to add image to canvas

You need to wait until the image is loaded before you draw it. Try this instead:

var canvas = document.getElementById('viewport'),
context = canvas.getContext('2d');

make_base();

function make_base()
{
  base_image = new Image();
  base_image.src = 'img/base.png';
  base_image.onload = function(){
    context.drawImage(base_image, 0, 0);
  }
}

i.e. draw the image in the onload callback of the image.

RunAs A different user when debugging in Visual Studio

You can open your command prompt as the intended user:

  • Shift + Right Click on Command Prompt icon on task bar.
  • Select (Run as differnt user)

enter image description here

  • You will be prompted with login and password

  • Once CommandP Prompt starts you can double check which user you are running as by the command whoami.

  • Now you can change directory to your project and run

dotnet run

  • In Visual Studio hit Ctrl+Alt+P (Attach to Process - can also be found from Debug menu)

enter image description here

  • Make sure "Show Processes from All users" is checked.
  • Find the running process and attach debugger.

Passing multiple argument through CommandArgument of Button in Asp.net

My approach is using the attributes collection to add HTML data- attributes from code behind. This is more inline with jquery and client side scripting.

// This would likely be done with findControl in your grid OnItemCreated handler
LinkButton targetBtn = new LinkButton();


// Add attributes
targetBtn.Attributes.Add("data-{your data name here}", value.ToString() );
targetBtn.Attributes.Add("data-{your data name 2 here}", value2.ToString() );

Then retrieve the values through the attribute collection

string val = targetBtn.Attributes["data-{your data name here}"].ToString();

Do subclasses inherit private fields?

A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass

reference: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html#:~:text=Private%20Members%20in%20a%20Superclass,be%20used%20by%20the%20subclass.

can't multiply sequence by non-int of type 'float'

In this line:

fund = fund * (1 + 0.01 * growthRates) + depositPerYear

I think you mean this:

fund = fund * (1 + 0.01 * i) + depositPerYear

When you try to multiply a float by growthRates (which is a list), you get that error.

Defining a percentage width for a LinearLayout?

Hope this can help

<LinearLayout android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:orientation="horizontal">

    <LinearLayout android:layout_width="0dip"
        android:layout_height="wrap_content" android:orientation="horizontal"
        android:id="@+id/linearLayout_dummy1" android:layout_weight=".15">
    </LinearLayout>


    <LinearLayout android:layout_height="wrap_content"
        android:id="@+id/linearLayout1" android:orientation="vertical"
        android:layout_width="0dip" android:layout_weight=".7">
        <Button android:text="Button" android:id="@+id/button1"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:layout_gravity="center">
        </Button>
        <Button android:layout_width="wrap_content" android:id="@+id/button2"
            android:layout_height="wrap_content" android:text="Button"
            android:layout_gravity="center"></Button>
        <Button android:layout_width="wrap_content" android:id="@+id/button3"
            android:layout_height="wrap_content" android:text="Button"
            android:layout_gravity="center"></Button>
    </LinearLayout>

    <LinearLayout android:layout_width="0dip"
        android:layout_height="wrap_content" android:orientation="horizontal"
        android:id="@+id/linearLayout_dummy2" android:layout_weight=".15">
    </LinearLayout>

</LinearLayout>

(1) Set layout_width to "0dip" (2) Set the layout_height to .xx (% you want)

how do I create an infinite loop in JavaScript

By omitting all parts of the head, the loop can also become infinite:

for (;;) {}

BeanFactory not initialized or already closed - call 'refresh' before

This problem can be caused also by jvm version used to compile the project and the jvm supported by the servlet container. Try to Fix the project build path. For example if you deploy on tomcat 9, use jvm 1.8.0 or lower.

PHP: Calling another class' method

If they are separate classes you can do something like the following:

class A
{
    private $name;

    public function __construct()
    {
        $this->name = 'Some Name';
    }

    public function getName()
    {
        return $this->name;
    }
}

class B
{
    private $a;

    public function __construct(A $a)
    {
        $this->a = $a;
    }

    function getNameOfA()
    {
        return $this->a->getName();
    }
}

$a = new A();
$b = new B($a);

$b->getNameOfA();

What I have done in this example is first create a new instance of the A class. And after that I have created a new instance of the B class to which I pass the instance of A into the constructor. Now B can access all the public members of the A class using $this->a.

Also note that I don't instantiate the A class inside the B class because that would mean I tighly couple the two classes. This makes it hard to:

  1. unit test your B class
  2. swap out the A class for another class

How to replace text in a column of a Pandas dataframe?

For anyone else arriving here from Google search on how to do a string replacement on all columns (for example, if one has multiple columns like the OP's 'range' column): Pandas has a built in replace method available on a dataframe object.

df.replace(',', '-', regex=True)

Source: Docs

Visual Studio Code always asking for git credentials

I managed to stop this by carrying out the following steps.

  1. Uninstall Git Desktop (Not sure this is necessary)
  2. Uninstall Credentials Manager cd "C:\Program Files\Git\mingw64\libexec\git-core" followed by git-credential-manager.exe uninstall
  3. Reset credentials helper to use wincred git config --global credential.helper wincred
  4. User VS Code to Push some changes and re-input credentials.

NOTE: I was using a Personal Access Token as my password.

Bootstrap Element 100% Width

I'd wonder why someone would try to "override" the container width, since its purpose is to keep its content with some padding, but I had a similar situation (that's why I wanted to share my solution, even though there're answers).

In my situation, I wanted to have all content (of all pages) rendered inside a container, so this was the piece of code from my _Layout.cshtml:

<div id="body">

    @RenderSection("featured", required: false)

    <section class="content-wrapper main-content clear-fix">
        <div class="container">
            @RenderBody()
        </div>
    </section>
</div>

In my Home Index page, I had a background header image I'd like to fill the whole screen width, so the solution was to make the Index.cshtml like this:

@section featured {
<!-- This content will be rendered outside the "container div" -->
<div class="intro-header">
    <div class="container">SOME CONTENT WITH A NICE BACKGROUND</div>
</div>
}

<!-- The content below will be rendered INSIDE the "container div" -->
<div class="content-section-b">
    <div class="container">
        <div class="row">
          MORE CONTENT
        </div>
    </div>
</div>

I think this is better than trying to make workarounds, since sections are made with the purpose of allowing (or forcing) views to dynamically replace some content in the layout.

Bootstrap: how do I change the width of the container?

You are tying one had behind your back saying that you won't use the LESS files. I built my first Twitter Bootstrap theme using 2.0, and I did everything in CSS -- creating an override.css file. It took days to get things to work correctly.

Now we have 3.0. Let me assure you that it takes less time to learn LESS, which is pretty straight forward if you're comfortable with CSS, than doing all of those crazy CSS overrides. Making changes like the one you want is a piece of cake.

In Bootstrap 3.0, the container class controls the width, and all of the contained styles adjust to fill the container. The container width variables are at the bottom of the variables.less file.

// Container sizes
// --------------------------------------------------

// Small screen / tablet
@container-tablet:            ((720px + @grid-gutter-width));

// Medium screen / desktop
@container-desktop:           ((940px + @grid-gutter-width));

// Large screen / wide desktop
@container-lg-desktop:        ((1020px + @grid-gutter-width));

Some sites either don't have enough content to fill the 1020 display or you want a narrower frame for aesthetic reasons. Because BS uses a 12-column grid I use a multiple like 960.

How to calculate moving average without keeping the count and data-total?

In Java8:

LongSummaryStatistics movingAverage = new LongSummaryStatistics();
movingAverage.accept(new data);
...
average = movingAverage.getAverage();

you have also IntSummaryStatistics, DoubleSummaryStatistics ...

Swift: Determine iOS Screen size

In Swift 3.0

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

In older swift: Do something like this:

let screenSize: CGRect = UIScreen.mainScreen().bounds

then you can access the width and height like this:

let screenWidth = screenSize.width
let screenHeight = screenSize.height

if you want 75% of your screen's width you can go:

let screenWidth = screenSize.width * 0.75

Swift 4.0

// Screen width.
public var screenWidth: CGFloat {
    return UIScreen.main.bounds.width
}

// Screen height.
public var screenHeight: CGFloat {
    return UIScreen.main.bounds.height
}

In Swift 5.0

let screenSize: CGRect = UIScreen.main.bounds

How do I Merge two Arrays in VBA?

My preferred way is a bit long, but has some advantages over the other answers:

  • It can combine an indefinite number of arrays at once
  • It can combine arrays with non-arrays (objects, strings, integers, etc.)
  • It accounts for the possibility that one or more of the arrays may contain objects
  • It allows the user to choose the base of the new array (0, 1, etc.)

Here it is:

Function combineArrays(ByVal toCombine As Variant, Optional ByVal newBase As Long = 1)
'Combines an array of one or more 1d arrays, objects, or values into a single 1d array
'newBase parameter indicates start position of new array (0, 1, etc.)
'Example usage:
    'combineArrays(Array(Array(1,2,3),Array(4,5,6),Array(7,8))) -> Array(1,2,3,4,5,6,7,8)
    'combineArrays(Array("Cat",Array(2,3,4))) -> Array("Cat",2,3,4)
    'combineArrays(Array("Cat",ActiveSheet)) -> Array("Cat",ActiveSheet)
    'combineArrays(Array(ThisWorkbook)) -> Array(ThisWorkbook)
    'combineArrays("Cat") -> Array("Cat")

    Dim tempObj As Object
    Dim tempVal As Variant

    If Not IsArray(toCombine) Then
        If IsObject(toCombine) Then
            Set tempObj = toCombine
            ReDim toCombine(newBase To newBase)
            Set toCombine(newBase) = tempObj
        Else
            tempVal = toCombine
            ReDim toCombine(newBase To newBase)
            toCombine(newBase) = tempVal
        End If
        combineArrays = toCombine
        Exit Function
    End If

    Dim i As Long
    Dim tempArr As Variant
    Dim newMax As Long
    newMax = 0

    For i = LBound(toCombine) To UBound(toCombine)
        If Not IsArray(toCombine(i)) Then
            If IsObject(toCombine(i)) Then
                Set tempObj = toCombine(i)
                ReDim tempArr(1 To 1)
                Set tempArr(1) = tempObj
                toCombine(i) = tempArr
            Else
                tempVal = toCombine(i)
                ReDim tempArr(1 To 1)
                tempArr(1) = tempVal
                toCombine(i) = tempArr
            End If
            newMax = newMax + 1
        Else
            newMax = newMax + (UBound(toCombine(i)) + LBound(toCombine(i)) - 1)
        End If
    Next
    newMax = newMax + (newBase - 1)

    ReDim newArr(newBase To newMax)
    i = newBase
    Dim j As Long
    Dim k As Long
    For j = LBound(toCombine) To UBound(toCombine)
        For k = LBound(toCombine(j)) To UBound(toCombine(j))
            If IsObject(toCombine(j)(k)) Then
                Set newArr(i) = toCombine(j)(k)
            Else
                newArr(i) = toCombine(j)(k)
            End If
            i = i + 1
        Next
    Next

    combineArrays = newArr

End Function

How to clean project cache in Intellij idea like Eclipse's clean?

In addition to the .Intellij* files, and invalidating the cache, if you really want to clear everything out, then also delete the .idea folder and *.iml per-project files that IntelliJ also generates...

How change default SVN username and password to commit changes?

since your local username on your laptop frequently does not match the server's username, you can set this in the ~/.subversion/servers file

Add the server to the [groups] section with a name, then add a section with that name and provide a username.

for example, for a login like [email protected] this is what your config would look like:

[groups]
exampleserver = svn.example.com

[exampleserver]
username = me

Are HTTP headers case-sensitive?

the Headers word are not case sensitive, but on the right like the Content-Type, is good practice to write it this way, because its case sensitve. like my example below

headers = headers.set('Content-Type'

Making view resize to its parent when added with addSubview

Tested in Xcode 9.4, Swift 4 Another way to solve this issue is , You can add

override func layoutSubviews() {
        self.frame = (self.superview?.bounds)!
    }

in subview class.

Javascript Audio Play on click

HTML:

<button onclick="play()">Play File</button>
<audio id="audio" src="https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3"></audio>

JavaScript:

let play = function(){document.getElementById("audio").play()}

Pandas : compute mean or std (standard deviation) over entire dataframe

You could convert the dataframe to be a single column with stack (this changes the shape from 5x3 to 15x1) and then take the standard deviation:

df.stack().std()         # pandas default degrees of freedom is one

Alternatively, you can use values to convert from a pandas dataframe to a numpy array before taking the standard deviation:

df.values.std(ddof=1)    # numpy default degrees of freedom is zero

Unlike pandas, numpy will give the standard deviation of the entire array by default, so there is no need to reshape before taking the standard deviation.

A couple of additional notes:

  • The numpy approach here is a bit faster than the pandas one, which is generally true when you have the option to accomplish the same thing with either numpy or pandas. The speed difference will depend on the size of your data, but numpy was roughly 10x faster when I tested a few different sized dataframes on my laptop (numpy version 1.15.4 and pandas version 0.23.4).

  • The numpy and pandas approaches here will not give exactly the same answers, but will be extremely close (identical at several digits of precision). The discrepancy is due to slight differences in implementation behind the scenes that affect how the floating point values get rounded.

CKEditor instance already exists

CKEDITOR.instances = new Array();

I am using this before my calls to create an instance (ones per page load). Not sure how this affects memory handling and what not. This would only work if you wanted to replace all of the instances on a page.

How to get last N records with activerecord?

Add an :order parameter to the query

Add data dynamically to an Array

$dynamicarray = array();

for($i=0;$i<10;$i++)
{
    $dynamicarray[$i]=$i;
}

How to define an enumerated type (enum) in C?

There seems to be a confusion about the declaration.

When strategycomes before {RANDOM, IMMEDIATE, SEARCH} as in the following,

enum strategy {RANDOM, IMMEDIATE, SEARCH};

you are creating a new type named enum strategy. However, when declaring the variable, you need to use enum strategy itself. You cannot just use strategy. So the following is invalid.

enum strategy {RANDOM, IMMEDIATE, SEARCH};
strategy a;

While, the following is valid

enum strategy {RANDOM, IMMEDIATE, SEARCH};

enum strategy queen = RANDOM;
enum strategy king = SEARCH;
enum strategy pawn[100];

When strategy comes after {RANDOM, IMMEDIATE, SEARCH}, you are creating an anonymous enum and then declaring strategy to be a variable of that type.

So now, you can do something like

enum {RANDOM, IMMEDIATE, SEARCH} strategy;
strategy = RANDOM;

However, you cannot declare any other variable of type enum {RANDOM, IMMEDIATE, SEARCH} because you have never named it. So the following is invalid

enum {RANDOM, IMMEDIATE, SEARCH} strategy;
enum strategy a = RANDOM;

You can combine both the definitions too

enum strategy {RANDOM, IMMEDIATE, SEARCH} a, b;

a = RANDOM;
b = SEARCH;
enum strategy c = IMMEDIATE;

Typedef as noted before is used for creating a shorter variable declaration.

typedef enum {RANDOM, IMMEDIATE, SEARCH} strategy;

Now you have told compiler that enum {RANDOM, IMMEDIATE, SEARCH} is synonomous to strategy. So now you can freely use strategy as variable type. You don't need to type enum strategy anymore. The following is valid now

strategy x = RANDOM;

You can also combine Typedef along with enum name to get

typedef enum strategyName {RANDOM, IMMEDIATE, SEARCH} strategy;

There's not much advantage of using this method apart from the fact that you can now use strategy and enum strategyName interchangeably.

typedef enum strategyName {RANDOM, IMMEDIATE, SEARCH} strategy;

enum strategyName a = RANDOM;
strategy b = SEARCH;

How do you comment out code in PowerShell?

You can make:

 (Some basic code) # Use "#" after a line and use:

 <#
    for more lines
    ...
    ...
    ...
    ..
    .
 #>

Commenting out a set of lines in a shell script

The most versatile and safe method is putting the comment into a void quoted here-document, like this:

<<"COMMENT"
    This long comment text includes ${parameter:=expansion}
    `command substitution` and $((arithmetic++ + --expansion)).
COMMENT

Quoting the COMMENT delimiter above is necessary to prevent parameter expansion, command substitution and arithmetic expansion, which would happen otherwise, as Bash manual states and POSIX shell standard specifies.

In the case above, not quoting COMMENT would result in variable parameter being assigned text expansion, if it was empty or unset, executing command command substitution, incrementing variable arithmetic and decrementing variable expansion.

Comparing other solutions to this:

Using if false; then comment text fi requires the comment text to be syntactically correct Bash code whereas natural comments are often not, if only for possible unbalanced apostrophes. The same goes for : || { comment text } construct.

Putting comments into a single-quoted void command argument, as in :'comment text', has the drawback of inability to include apostrophes. Double-quoted arguments, as in :"comment text", are still subject to parameter expansion, command substitution and arithmetic expansion, the same as unquoted here-document contents and can lead to the side-effects described above.

Using scripts and editor facilities to automatically prefix each line in a block with '#' has some merit, but doesn't exactly answer the question.

ImportError: No module named 'pygame'

  1. open the folder where your python is installed
  2. open scripts folder
  3. type cmd in the address bar. It opens a command prompt window in that location
  4. type pip install pygame and press enter
  5. it should download and install pygame module
  6. now run your code. It works fine :-)

Reading from file using read() function

Read Byte by Byte and check that each byte against '\n' if it is not, then store it into buffer
if it is '\n' add '\0' to buffer and then use atoi()

You can read a single byte like this

char c;
read(fd,&c,1);

See read()

Setting query string using Fetch GET request

Solution without external packages

to perform a GET request using the fetch api I worked on this solution that doesn't require the installation of packages.

this is an example of a call to the google's map api

// encode to scape spaces
const esc = encodeURIComponent;
const url = 'https://maps.googleapis.com/maps/api/geocode/json?';
const params = { 
    key: "asdkfñlaskdGE",
    address: "evergreen avenue",
    city: "New York"
};
// this line takes the params object and builds the query string
const query = Object.keys(params).map(k => `${esc(k)}=${esc(params[k])}`).join('&')
const res = await fetch(url+query);
const googleResponse = await res.json()

feel free to copy this code and paste it on the console to see how it works!!

the generated url is something like:

https://maps.googleapis.com/maps/api/geocode/json?key=asdkf%C3%B1laskdGE&address=evergreen%20avenue&city=New%20York

this is what I was looking before I decided to write this, enjoy :D

python pandas: Remove duplicates by columns A, keeping the row with the highest value in column B

The top answer is doing too much work and looks to be very slow for larger data sets. apply is slow and should be avoided if possible. ix is deprecated and should be avoided as well.

df.sort_values('B', ascending=False).drop_duplicates('A').sort_index()

   A   B
1  1  20
3  2  40
4  3  10

Or simply group by all the other columns and take the max of the column you need. df.groupby('A', as_index=False).max()

How to install Java SDK on CentOS?

yum install java-1.8.0

and then:

alternatives --config java

and check:

java -version

How to check string length with JavaScript

That's the function I wrote to get string in Unicode characters:

function nbUnicodeLength(string){
    var stringIndex = 0;
    var unicodeIndex = 0;
    var length = string.length;
    var second;
    var first;
    while (stringIndex < length) {

        first = string.charCodeAt(stringIndex);  // returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.
        if (first >= 0xD800 && first <= 0xDBFF && string.length > stringIndex + 1) {
            second = string.charCodeAt(stringIndex + 1);
            if (second >= 0xDC00 && second <= 0xDFFF) {
                stringIndex += 2;
            } else {
                stringIndex += 1;
            }
        } else {
            stringIndex += 1;
        }

        unicodeIndex += 1;
    }
    return unicodeIndex;
}

Read String line by line

You can use the stream api and a StringReader wrapped in a BufferedReader which got a lines() stream output in java 8:

import java.util.stream.*;
import java.io.*;
class test {
    public static void main(String... a) {
        String s = "this is a \nmultiline\rstring\r\nusing different newline styles";

        new BufferedReader(new StringReader(s)).lines().forEach(
            (line) -> System.out.println("one line of the string: " + line)
        );
    }
}

Gives

one line of the string: this is a
one line of the string: multiline
one line of the string: string
one line of the string: using different newline styles

Just like in BufferedReader's readLine, the newline character(s) themselves are not included. All kinds of newline separators are supported (in the same string even).

How can I check if given int exists in array?

Try this

#include <iostream>
#include <algorithm>


int main () {
  int myArray[] = { 3 ,6 ,8, 33 };
  int x = 8;

  if (std::any_of(std::begin(myArray), std::end(myArray), [=](int n){return n == x;}))   {
      std::cout << "found match/" << std::endl;
  }

  return 0;

}

How to solve npm install throwing fsevents warning on non-MAC OS?

I found the same problem and i tried all the solution mentioned above and in github. Some works only in local repository, when i push my PR in remote repositories with travic-CI or Pipelines give me the same error back. Finally i fixed it by using the npm command below.

npm audit fix --force

How do you run a .bat file from PHP?

<?php
 pclose(popen("start /B test.bat", "r")); die();
?> 

How do you easily create empty matrices javascript?

For a 2-d matrix I'd do the following

var data = Array(9 * 9).fill(0);
var index = (i,j) => 9*i + j;
//any reference to an index, eg. (3,4) can be done as follows
data[index(3,4)]; 

You can replace 9 with any generic ROWS and COLUMNS constants.

changing color of h2

If you absolutely must use HTML to give your text color, you have to use the (deprecated) <font>-tag:

<h2><font color="#006699">Process Report</font></h2>

But otherwise, I strongly recommend you to do as rekire said: use CSS.

Check if a string is a palindrome

Out of all the solutions, below can also be tried:

public static bool IsPalindrome(string s)
{
    return s == new string(s.Reverse().ToArray());
}

How to make a div center align in HTML

it depends if your div is in position: absolute / fixed or relative / static

for position: absolute & fixed

<div style="position: absolute; /*or fixed*/;
width: 50%;
height: 300px;
left: 50%;
top:100px;
margin: 0 0 0 -25%">blblablbalba</div>

The trick here is to have a negative margin half the width of the object

for position: relative & static

<div style="position: relative; /*or static*/;
width: 50%;
height: 300px;
margin: 0 auto">blblablbalba</div>

for both techniques, it is imperative to set the width.

Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist

For myself, I had to do:

yum remove mysql*

rm -rf /var/lib/mysql/
cp /etc/my.cnf ~/my.cnf.bkup

yum install -y mysql-server mysql-client

mysql_install_db

chown -R mysql:mysql /var/lib/mysql
chown -R mysql:mysql /var/log/mysql

service mysql start

Then I was able to get back into my databases and configure them again after I nuked them the first go around.

How to use continue in jQuery each() loop?

$('.submit').filter(':checked').each(function() {
    //This is same as 'continue'
    if(something){
        return true;
    }
    //This is same as 'break'
    if(something){
        return false;
    }
});

change cursor from block or rectangle to line?

please Press fn +ins key together

SQL Server: Best way to concatenate multiple columns?

If the fields are nullable, then you'll have to handle those nulls. Remember that null is contagious, and concat('foo', null) simply results in NULL as well:

SELECT CONCAT(ISNULL(column1, ''),ISNULL(column2,'')) etc...

Basically test each field for nullness, and replace with an empty string if so.

How to Compare two Arrays are Equal using Javascript?

A more modern version:

function arraysEqual(a, b) {
  a = Array.isArray(a) ? a : [];
  b = Array.isArray(b) ? b : [];
  return a.length === b.length && a.every((el, ix) => el === b[ix]);
}

Coercing non-array arguments to empty arrays stops a.every() from exploding.

If you just want to see if the arrays have the same set of elements then you can use Array.includes():

function arraysContainSame(a, b) {
  a = Array.isArray(a) ? a : [];
  b = Array.isArray(b) ? b : [];
  return a.length === b.length && a.every(el => b.includes(el));
}

Error "There is already an open DataReader associated with this Command which must be closed first" when using 2 distinct commands

You can get such a problem when you are two different commands on same connection - especially calling the second command in a loop. That is calling the second command for each record returned from the first command. If there are some 10,000 records returned by the first command, this issue will be more likely.

I used to avoid such a scenario by making it as a single command.. The first command returns all the required data and load it into a DataTable.

Note: MARS may be a solution - but it can be risky and many people dislike it.

Reference

  1. What does "A severe error occurred on the current command. The results, if any, should be discarded." SQL Azure error mean?
  2. Linq-To-Sql and MARS woes - A severe error occurred on the current command. The results, if any, should be discarded
  3. Complex GROUP BY on DataTable

Convert Java String to sql.Timestamp

You could use Timestamp.valueOf(String). The documentation states that it understands timestamps in the format yyyy-mm-dd hh:mm:ss[.f...], so you might need to change the field separators in your incoming string.

Then again, if you're going to do that then you could just parse it yourself and use the setNanos method to store the microseconds.

How to open standard Google Map application from my application?

You should create an Intent object with a geo-URI:

String uri = String.format(Locale.ENGLISH, "geo:%f,%f", latitude, longitude);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
context.startActivity(intent);

If you want to specify an address, you should use another form of geo-URI: geo:0,0?q=address.

reference : https://developer.android.com/guide/components/intents-common.html#Maps

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

To make it more clear(and to put it together) I had to do Two things mentioned above.

1- Create a file /etc/ld.so.conf.d/opencv.conf and write to it the paths of folder where your opencv libraries are stored.(Answer by Cookyt)

2- Include the path of your opencv's .so files in LD_LIBRARY_PATH ()

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/opencv/lib

How to configure Eclipse build path to use Maven dependencies?

I had a slight variation that caused some issues - multiple sub projects within one project. In this case I needed to go into each individual folder that contained a POM, execute the mvn eclipse:eclipse command and then manually copy/merge the classpath entries into my project classpath file.

Can someone explain mappedBy in JPA and Hibernate?

MappedBy signals hibernate that the key for the relationship is on the other side.

This means that although you link 2 tables together, only 1 of those tables has a foreign key constraint to the other one. MappedBy allows you to still link from the table not containing the constraint to the other table.

Execution sequence of Group By, Having and Where clause in SQL Server?

In Oracle 12c, you can run code both in either sequence below:

Where
Group By
Having

Or

Where 
Having
Group by

What's the difference between a proxy server and a reverse proxy server?

My understanding from an Apache perspective is that proxy means that if site x proxies for site y, then requests for x return y.

The reverse proxy means that the response from y is adjusted so that all references to y become x.

So that the user cannot tell that a proxy is involved...

Array formula on Excel for Mac


Select the range, press CONTROL+U and then press ?+RETURN.


Why not use tables for layout in HTML?

DOM Manipulation is difficult in a table-based layout.

With semantic divs:

$('#myawesomediv').click(function(){
    // Do awesome stuff
});

With tables:

$('table tr td table tr td table tr td.......').click(function(){
    // Cry self to sleep at night
});

Now, granted, the second example is kind of stupid, and you can always apply IDs or classes to a table or td element, but that would be adding semantic value, which is what table proponents so vehemently oppose.

How to reject in async/await syntax?

You can create a wrapper function that takes in a promise and returns an array with data if no error and the error if there was an error.

function safePromise(promise) {
  return promise.then(data => [ data ]).catch(error => [ null, error ]);
}

Use it like this in ES7 and in an async function:

async function checkItem() {
  const [ item, error ] = await safePromise(getItem(id));
  if (error) { return null; } // handle error and return
  return item; // no error so safe to use item
}

Python Pandas Replacing Header with Top Row

header = table_df.iloc[0]
table_df.drop([0], axis =0, inplace=True)
table_df.reset_index(drop=True)
table_df.columns = header
table_df

How to get MAC address of your machine using a C program?

You want to take a look at the getifaddrs(3) manual page. There is an example in C in the manpage itself that you can use. You want to get the address with the type AF_LINK.

How set maximum date in datepicker dialog in android?

Use setMaxDate().

For example, replace return new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay) statement with something like this:

    DatePickerDialog dialog = new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay);
    dialog.getDatePicker().setMaxDate(new Date().getTime());
    return dialog;

'dependencies.dependency.version' is missing error, but version is managed in parent

In theory, maven does not allow to use a property to set a parent version.

In your case, maven can simply not figure out that the 0.0.1-SNAPSHOT version of your parent pom is the one that is currently in your project, and so it tries to find it in your local repo. It probably finds one since it is a snapshot, but it is an old version that probably not contains your Dependency Management section.

There is a workaround though :

Simply change the parent section in the child pom with this :

<parent>
    <groupId>com.sw.system4</groupId>
    <artifactId>system4-parent</artifactId>
    <version>${system4.version}</version>
    <relativePath>../pom.xml</relativePath>  <!-- this must match your parent pom location -->
</parent>

ReactJS - Add custom event listener to component

I recommend using React.createRef() and ref=this.elementRef to get the DOM element reference instead of ReactDOM.findDOMNode(this). This way you can get the reference to the DOM element as an instance variable.

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class MenuItem extends Component {

  constructor(props) {
    super(props);

    this.elementRef = React.createRef();
  }

  handleNVFocus = event => {
      console.log('Focused: ' + this.props.menuItem.caption.toUpperCase());
  }
    
  componentDidMount() {
    this.elementRef.addEventListener('nv-focus', this.handleNVFocus);
  }

  componentWillUnmount() {
    this.elementRef.removeEventListener('nv-focus', this.handleNVFocus);
  }

  render() {
    return (
      <element ref={this.elementRef} />
    )
  }

}

export default MenuItem;

Makefile If-Then Else and Loops

Conditional Forms

Simple

conditional-directive
text-if-true
endif

Moderately Complex

conditional-directive
text-if-true
else
text-if-false
endif

More Complex

conditional-directive
text-if-one-is-true
else
conditional-directive
text-if-true
else
text-if-false
endif
endif

Conditional Directives

If Equal Syntax

ifeq (arg1, arg2)
ifeq 'arg1' 'arg2'
ifeq "arg1" "arg2"
ifeq "arg1" 'arg2'
ifeq 'arg1' "arg2"

If Not Equal Syntax

ifneq (arg1, arg2)
ifneq 'arg1' 'arg2'
ifneq "arg1" "arg2"
ifneq "arg1" 'arg2'
ifneq 'arg1' "arg2"

If Defined Syntax

ifdef variable-name

If Not Defined Syntax

ifndef variable-name  

foreach Function

foreach Function Syntax

$(foreach var, list, text)  

foreach Semantics
For each whitespace separated word in "list", the variable named by "var" is set to that word and text is executed.

What are the use cases for selecting CHAR over VARCHAR in SQL?

There are performance benefits, but here is one that has not been mentioned: row migration. With char, you reserve the entire space in advance.So let's says you have a char(1000), and you store 10 characters, you will use up all 1000 charaters of space. In a varchar2(1000), you will only use 10 characters. The problem comes when you modify the data. Let's say you update the column to now contain 900 characters. It is possible that the space to expand the varchar is not available in the current block. In that case, the DB engine must migrate the row to another block, and make a pointer in the original block to the new row in the new block. To read this data, the DB engine will now have to read 2 blocks.
No one can equivocally say that varchar or char are better. There is a space for time tradeoff, and consideration of whether the data will be updated, especially if there is a good chance that it will grow.

Inversion of Control vs Dependency Injection

IoC - Inversion of control is generic term, independent of language, it is actually not create the objects but describe in which fashion object is being created.

DI - Dependency Injection is concrete term, in which we provide dependencies of the object at run time by using different injection techniques viz. Setter Injection, Constructor Injection or by Interface Injection.

How to set date format in HTML date input tag?

You don't.

Firstly, your question is ambiguous - do you mean the format in which it is displayed to the user, or the format in which it is transmitted to the web server?

If you mean the format in which it is displayed to the user, then this is down to the end-user interface, not anything you specify in the HTML. Usually, I would expect it to be based on the date format that it is set in the operating system locale settings. It makes no sense to try to override it with your own preferred format, as the format it displays in is (generally speaking) the correct one for the user's locale and the format that the user is used to writing/understanding dates in.

If you mean the format in which it's transmitted to the server, you're trying to fix the wrong problem. What you need to do is program the server-side code to accept dates in yyyy-mm-dd format.

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

You could also add something simple to your Makefile such as

ifeq ($(DEBUG),1)
   OPTS = -g
endif

Then compile it for debugging

make DEBUG=1

How to obtain the number of CPUs/cores in Linux from the command line?

Count "core id" per "physical id" method using awk with fall-back on "processor" count if "core id" are not available (like raspberry)

echo $(awk '{ if ($0~/^physical id/) { p=$NF }; if ($0~/^core id/) { cores[p$NF]=p$NF }; if ($0~/processor/) { cpu++ } } END { for (key in cores) { n++ } } END { if (n) {print n} else {print cpu} }' /proc/cpuinfo)

Java: Finding the highest value in an array

import java.util.*;
class main9 //Find the smallest and 2lagest and  ascending and descending order of  elements in array//
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the array range");
        int no=sc.nextInt();
        System.out.println("Enter the array element");
        int a[]=new int[no];
        int i;
        for(i=0;i<no;i++)
        {
            a[i]=sc.nextInt();
        }
        Arrays.sort(a);
        int s=a[0];
        int l=a[a.length-1];
        int m=a[a.length-2];
        System.out.println("Smallest no is="+s);
        System.out.println("lagest 2 numbers are=");
        System.out.println(l);
        System.out.println(m);
        System.out.println("Array in ascending:");
        for(i=0;i<no;i++)
        {
            System.out.println(a[i]);
        }
        System.out.println("Array in descending:");
        for(i=a.length-1;i>=0;i--)
        {
            System.out.println(a[i]);
        }
    }
}

How to watch and reload ts-node when TypeScript files change

I've dumped nodemon and ts-node in favor of a much better alternative, ts-node-dev https://github.com/whitecolor/ts-node-dev

Just run ts-node-dev src/index.ts

Adding attributes to an XML node

Well id isn't really the root node: Login is.

It should just be a case of specifying the attributes (not tags, btw) using XmlElement.SetAttribute. You haven't specified how you're creating the file though - whether you're using XmlWriter, the DOM, or any other XML API.

If you could give an example of the code you've got which isn't working, that would help a lot. In the meantime, here's some code which creates the file you described:

using System;
using System.Xml;

class Test
{
    static void Main()
    {
        XmlDocument doc = new XmlDocument();
        XmlElement root = doc.CreateElement("Login");
        XmlElement id = doc.CreateElement("id");
        id.SetAttribute("userName", "Tushar");
        id.SetAttribute("passWord", "Tushar");
        XmlElement name = doc.CreateElement("Name");
        name.InnerText = "Tushar";
        XmlElement age = doc.CreateElement("Age");
        age.InnerText = "24";

        id.AppendChild(name);
        id.AppendChild(age);
        root.AppendChild(id);
        doc.AppendChild(root);

        doc.Save("test.xml");
    }
}

Shell command to tar directory excluding certain files/folders

I want to have fresh front-end version (angular folder) on localhost. Also, git folder is huge in my case, and I want to exclude it. I need to download it from server, and unpack it in order to run application.

Compress angular folder from /var/lib/tomcat7/webapps, move it to /tmp folder with name angular.23.12.19.tar.gz

Command :

tar --exclude='.git' -zcvf /tmp/angular.23.12.19.tar.gz /var/lib/tomcat7/webapps/angular/

setContentView(R.layout.main); error

if you have multiple packages with different classes then it will be confusing: try this:

import package_name_from_AndroidManifest.R;

Formatting code snippets for blogging on Blogger

I've created a blog post entry which explains how to add code syntax highlighting to blogger using the syntaxhighlighter 2.0

Here's my blog post:

http://www.craftyfella.com/2010/01/syntax-highlighting-with-blogger-engine.html

I hope it helps you guys.. I'm quite impressed with what it can do.

Above Links stopped working. Try using http://hilite.me/

Any way to declare an array in-line?

You can create a method somewhere

public static <T> T[] toArray(T... ts) {
    return ts;
}

then use it

m(toArray("blah", "hey", "yo"));

for better look.

OSX El Capitan: sudo pip install OSError: [Errno: 1] Operation not permitted

Instructions telling sudo pip install are inherently wrong.

If there is any tutorial out there which says you should do sudo pip then please file a bug against this package. The author is dis-educating Python community, as time has proven sudo pip to be a broken practice.

OSX El Capitan introduced a mechanisms to prevent damaging the operating system files. /System/Library/Frameworks/Python.framework/Versions/2.7/share is one of the protected locations. A normal user has no reason to put or write any files there. This is because the operating system itself relies on these files and sudo pip, with all force given from the above, would unconditionally overwrite them. Usually bad things would not happen, but the chances are there. Apple wants to protect their OS users to accidentally bricking their installation.

Instead, you need to install a Python package, like IPython, locally to the home folder of your user. The easiest way is to create a virtual environment, activate it and then run pip in the virtual environment.

Example:

cd ~  # Go to home directory
virtualenv my-venv
source my-venv/bin/activate
pip install IPython

More info

Alternatively, one should be able to do pip install --user. But again, no sudo needed and you need to manually set up PATH environment variable.

Enter key pressed event handler

In WPF, TextBox element will not get opportunity to use "Enter" button for creating KeyUp Event until you will not set property: AcceptsReturn="True".

But, it would`t solve the problem with handling KeyUp Event in TextBox element. After pressing "ENTER" you will get a new text line in TextBox.

I had solved problem of using KeyUp Event of TextBox element by using Bubble event strategy. It's short and easy. You have to attach a KeyUp Event handler in some (any) parent element:

XAML:

<Window x:Class="TextBox_EnterButtomEvent.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:TextBox_EnterButtomEvent"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid KeyUp="Grid_KeyUp">
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height ="0.3*"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <TextBlock Grid.Row="1" Grid.Column="1" Padding="0" TextWrapping="WrapWithOverflow">
        Input text end press ENTER:
    </TextBlock>
    <TextBox Grid.Row="2" Grid.Column="1" HorizontalAlignment="Stretch"/>
    <TextBlock Grid.Row="4" Grid.Column="1" Padding="0" TextWrapping="WrapWithOverflow">
        You have entered:
    </TextBlock>
    <TextBlock Name="txtBlock" Grid.Row="5" Grid.Column="1" HorizontalAlignment="Stretch"/>
</Grid></Window>

C# logical part (KeyUp Event handler is attached to a grid element):

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Grid_KeyUp(object sender, KeyEventArgs e)
    {
        if(e.Key == Key.Enter)
        {
            TextBox txtBox = e.Source as TextBox;
            if(txtBox != null)
            {
                this.txtBlock.Text = txtBox.Text;
                this.txtBlock.Background = new SolidColorBrush(Colors.LightGray);
            }
        }
    }
}

Result:

Image with result

How can I control the speed that bootstrap carousel slides in items?

With Bootstrap 4, just use this CSS:

.carousel .carousel-item {
    transition-duration: 3s;
}

Change 3s to the duration of your choice.

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname

I had the same problem, my code is below:

private Connection conn = DriverManager.getConnection(Constant.MYSQL_URL, Constant.MYSQL_USER, Constant.MYSQL_PASSWORD);
private Statement stmt = conn.createStatement();

I have not loaded the driver class, but it works locally, I can query the results from MySQL, however, it does not work when I deploy it to Tomcat, and the errors below occur:

No suitable driver found for jdbc:mysql://172.16.41.54:3306/eduCloud

so I loaded the driver class, as below, when I saw other answers posted:

Class.forName("com.mysql.jdbc.Driver");

It works now! I don't know why it works well locally, I need your help, thank you so much!

How can I get the key value in a JSON object?

First off, you're not dealing with a "JSON object." You're dealing with a JavaScript object. JSON is a textual notation, but if your example code works ([0].amount), you've already deserialized that notation into a JavaScript object graph. (What you've quoted isn't valid JSON at all; in JSON, the keys must be in double quotes. What you've quoted is a JavaScript object literal, which is a superset of JSON.)

Here, length of this array is 2.

No, it's 3.

So, i need to get the name (like amount or job... totally four name) and also to count how many names are there?

If you're using an environment that has full ECMAScript5 support, you can use Object.keys (spec | MDN) to get the enumerable keys for one of the objects as an array. If not (or if you just want to loop through them rather than getting an array of them), you can use for..in:

var entry;
var name;
entry = array[0];
for (name in entry) {
    // here, `name` will be "amount", "job", "month", then "year" (in no defined order)
}

Full working example:

_x000D_
_x000D_
(function() {_x000D_
  _x000D_
  var array = [_x000D_
    {_x000D_
      amount: 12185,_x000D_
      job: "GAPA",_x000D_
      month: "JANUARY",_x000D_
      year: "2010"_x000D_
    },_x000D_
    {_x000D_
      amount: 147421,_x000D_
      job: "GAPA",_x000D_
      month: "MAY",_x000D_
      year: "2010"_x000D_
    },_x000D_
    {_x000D_
      amount: 2347,_x000D_
      job: "GAPA",_x000D_
      month: "AUGUST",_x000D_
      year: "2010"_x000D_
    }_x000D_
  ];_x000D_
  _x000D_
  var entry;_x000D_
  var name;_x000D_
  var count;_x000D_
  _x000D_
  entry = array[0];_x000D_
  _x000D_
  display("Keys for entry 0:");_x000D_
  count = 0;_x000D_
  for (name in entry) {_x000D_
    display(name);_x000D_
    ++count;_x000D_
  }_x000D_
  display("Total enumerable keys: " + count);_x000D_
_x000D_
  // === Basic utility functions_x000D_
  _x000D_
  function display(msg) {_x000D_
    var p = document.createElement('p');_x000D_
    p.innerHTML = msg;_x000D_
    document.body.appendChild(p);_x000D_
  }_x000D_
  _x000D_
})();
_x000D_
_x000D_
_x000D_

Since you're dealing with raw objects, the above for..in loop is fine (unless someone has committed the sin of mucking about with Object.prototype, but let's assume not). But if the object you want the keys from may also inherit enumerable properties from its prototype, you can restrict the loop to only the object's own keys (and not the keys of its prototype) by adding a hasOwnProperty call in there:

for (name in entry) {
  if (entry.hasOwnProperty(name)) {
    display(name);
    ++count;
  }
}

How to make a stable two column layout in HTML/CSS

Piece of cake.

Use 960Grids Go to the automatic layout builder and make a two column, fluid design. Build a left column to the width of grids that works....this is the only challenge using grids and it's very easy once you read a tutorial. In a nutshell, each column in a grid is a certain width, and you set the amount of columns you want to use. To get a column that's exactly a certain width, you have to adjust your math so that your column width is exact. Not too tough.

No chance of wrapping because others have already fought that battle for you. Compatibility back as far as you likely will ever need to go. Quick and easy....Now, download, customize and deploy.

Voila. Grids FTW.

How do I add python3 kernel to jupyter (IPython)

None of the other answers were working for me immediately on ElementaryOS Freya (based on Ubuntu 14.04); I was getting the

[TerminalIPythonApp] WARNING | File not found: 'kernelspec'

error that quickbug described under Matt's answer. I had to first do:

sudo apt-get install pip3, then

sudo pip3 install ipython[all]

At that point you can then run the commands that Matt suggested; namely: ipython kernelspec install-self and ipython3 kernelspec install-self

Now when I launch ipython notebook and then open a notebook, I am able to select the Python 3 kernel from the Kernel menu.

How to download a file from a website in C#

You may need to know the status during the file download or use credentials before making the request.

Here is an example that covers these options:

Uri ur = new Uri("http://remotehost.do/images/img.jpg");

using (WebClient client = new WebClient()) {
    //client.Credentials = new NetworkCredential("username", "password");
    String credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("Username" + ":" + "MyNewPassword"));
    client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}";

    client.DownloadProgressChanged += WebClientDownloadProgressChanged;
    client.DownloadDataCompleted += WebClientDownloadCompleted;
    client.DownloadFileAsync(ur, @"C:\path\newImage.jpg");
}

And the callback's functions implemented as follows:

void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);

    // updating the UI
    Dispatcher.Invoke(() => {
        progressBar.Value = e.ProgressPercentage;
    });
}

void WebClientDownloadCompleted(object sender, DownloadDataCompletedEventArgs e)
{
    Console.WriteLine("Download finished!");
}

(Ver 2) - Lambda notation: other possible option for handling the events

client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(delegate(object sender, DownloadProgressChangedEventArgs e) {
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);

    // updating the UI
    Dispatcher.Invoke(() => {
        progressBar.Value = e.ProgressPercentage;
    });
});

client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(delegate(object sender, DownloadDataCompletedEventArgs e){
    Console.WriteLine("Download finished!");
});

(Ver 3) - We can do better

client.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs e) =>
{
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);

    // updating the UI
    Dispatcher.Invoke(() => {
        progressBar.Value = e.ProgressPercentage;
    });
};

client.DownloadDataCompleted += (object sender, DownloadDataCompletedEventArgs e) => 
{
    Console.WriteLine("Download finished!");
};

(Ver 4) - Or

client.DownloadProgressChanged += (o, e) =>
{
    Console.WriteLine($"Download status: {e.ProgressPercentage}%.");

    // updating the UI
    Dispatcher.Invoke(() => {
        progressBar.Value = e.ProgressPercentage;
    });
};

client.DownloadDataCompleted += (o, e) => 
{
    Console.WriteLine("Download finished!");
};

display: flex not working on Internet Explorer

Am afraid this question has been answered a few times, Pls take a look at the following if it's related

How to Remove the last char of String in C#?

If you are using string datatype, below code works:

string str = str.Remove(str.Length - 1);

But when you have StringBuilder, you have to specify second parameter length as well.

SB

That is,

string newStr = sb.Remove(sb.Length - 1, 1).ToString();

To avoid below error:

SB2

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

I think this query will do a case insensitive search:

SELECT * FROM trees WHERE trees.`title` ILIKE '%elm%';

Swift: How to get substring from start to last index of character

I also build a simple String-extension for Swift 4:

extension String {
    func subStr(s: Int, l: Int) -> String { //s=start, l=lenth
        let r = Range(NSRange(location: s, length: l))!
        let fromIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
        let toIndex = self.index(self.startIndex, offsetBy: r.upperBound)
        let indexRange = Range<String.Index>(uncheckedBounds: (lower: fromIndex, upper: toIndex))

        return String(self[indexRange])
     }
}

So you can easily call it like this:

"Hallo world".subStr(s: 1, l: 3) //prints --> "all"

Where does application data file actually stored on android device?

Application Private Data files are stored within <internal_storage>/data/data/<package>

Files being stored in the internal storage can be accessed with openFileOutput() and openFileInput()

When those files are created as MODE_PRIVATE it is not possible to see/access them within another application such as a FileManager.

Adding elements to an xml file in C#

This is extension to answers above, if your xml has namespace defined (xmlns) then you will get a nasty side effect when adding children - xmlns = "" being added to your new child element.

What you want to do (assuming element you are adding belongs to same namespace as his parent) is to take namespace from parent element parentElement.GetDefaultNamespace().

var child = new XElement(parentElement.GetDefaultNamespace()+"Snippet", new XAttribute("Attr1", "42"), new XAttribute("Attr2", "22"));
child.Add(new XAttribute("Attr3", "777"));
parentElement.Add(child);

for parent elements with multiple namespaces you can choose which one to use by changing from parentElement.GetDefaultNamespace()+"Snippet" to parentElement.GetNamespaceOfPrefix("namespacePrefixThatGoesWithColon")+"Snippet" e.g

var child = new XElement(parentElement.GetNamespaceOfPrefix("namespacePrefixThatGoesWithColon")+"Snippet", new XAttribute("Attr1", "42"), new XAttribute("Attr2", "22"));

oracle sql: update if exists else insert

You could use the SQL%ROWCOUNT Oracle variable:

UPDATE table1
  SET field2 = value2, 
      field3 = value3 
WHERE field1 = value1; 

IF (SQL%ROWCOUNT = 0) THEN 

  INSERT INTO table (field1, field2, field3)
  VALUES (value1, value2, value3);

END IF; 

It would be easier just to determine if your primary key (i.e. field1) has a value and then perform an insert or update accordingly. That is, if you use said values as parameters for a stored procedure.

How to capture a backspace on the onkeydown event

Nowadays, code to do this should look something like:

document.getElementById('foo').addEventListener('keydown', function (event) {
    if (event.keyCode == 8) {
        console.log('BACKSPACE was pressed');

        // Call event.preventDefault() to stop the character before the cursor
        // from being deleted. Remove this line if you don't want to do that.
        event.preventDefault();
    }
    if (event.keyCode == 46) {
        console.log('DELETE was pressed');

        // Call event.preventDefault() to stop the character after the cursor
        // from being deleted. Remove this line if you don't want to do that.
        event.preventDefault();
    }
});

although in the future, once they are broadly supported in browsers, you may want to use the .key or .code attributes of the KeyboardEvent instead of the deprecated .keyCode.

Details worth knowing:

  • Calling event.preventDefault() in the handler of a keydown event will prevent the default effects of the keypress. When pressing a character, this stops it from being typed into the active text field. When pressing backspace or delete in a text field, it prevents a character from being deleted. When pressing backspace without an active text field, in a browser like Chrome where backspace takes you back to the previous page, it prevents that behaviour (as long as you catch the event by adding your event listener to document instead of a text field).

  • Documentation on how the value of the keyCode attribute is determined can be found in section B.2.1 How to determine keyCode for keydown and keyup events in the W3's UI Events Specification. In particular, the codes for Backspace and Delete are listed in B.2.3 Fixed virtual key codes.

  • There is an effort underway to deprecate the .keyCode attribute in favour of .key and .code. The W3 describe the .keyCode property as "legacy", and MDN as "deprecated".

    One benefit of the change to .key and .code is having more powerful and programmer-friendly handling of non-ASCII keys - see the specification that lists all the possible key values, which are human-readable strings like "Backspace" and "Delete" and include values for everything from modifier keys specific to Japanese keyboards to obscure media keys. Another, which is highly relevant to this question, is distinguishing between the meaning of a modified keypress and the physical key that was pressed.

    On small Mac keyboards, there is no Delete key, only a Backspace key. However, pressing Fn+Backspace is equivalent to pressing Delete on a normal keyboard - that is, it deletes the character after the text cursor instead of the one before it. Depending upon your use case, in code you might want to handle a press of Backspace with Fn held down as either Backspace or Delete. That's why the new key model lets you choose.

    The .key attribute gives you the meaning of the keypress, so Fn+Backspace will yield the string "Delete". The .code attribute gives you the physical key, so Fn+Backspace will still yield the string "Backspace".

    Unfortunately, as of writing this answer, they're only supported in 18% of browsers, so if you need broad compatibility you're stuck with the "legacy" .keyCode attribute for the time being. But if you're a reader from the future, or if you're targeting a specific platform and know it supports the new interface, then you could write code that looked something like this:

    document.getElementById('foo').addEventListener('keydown', function (event) {
        if (event.code == 'Delete') {
            console.log('The physical key pressed was the DELETE key');
        }
        if (event.code == 'Backspace') {
            console.log('The physical key pressed was the BACKSPACE key');
        } 
        if (event.key == 'Delete') {
            console.log('The keypress meant the same as pressing DELETE');
            // This can happen for one of two reasons:
            // 1. The user pressed the DELETE key
            // 2. The user pressed FN+BACKSPACE on a small Mac keyboard where
            //    FN+BACKSPACE deletes the character in front of the text cursor,
            //    instead of the one behind it.
        }
        if (event.key == 'Backspace') {
            console.log('The keypress meant the same as pressing BACKSPACE');
        }
    });
    

Passing multiple parameters to pool.map() function in Python

You can use functools.partial for this (as you suspected):

from functools import partial

def target(lock, iterable_item):
    for item in iterable_item:
        # Do cool stuff
        if (... some condition here ...):
            lock.acquire()
            # Write to stdout or logfile, etc.
            lock.release()

def main():
    iterable = [1, 2, 3, 4, 5]
    pool = multiprocessing.Pool()
    l = multiprocessing.Lock()
    func = partial(target, l)
    pool.map(func, iterable)
    pool.close()
    pool.join()

Example:

def f(a, b, c):
    print("{} {} {}".format(a, b, c))

def main():
    iterable = [1, 2, 3, 4, 5]
    pool = multiprocessing.Pool()
    a = "hi"
    b = "there"
    func = partial(f, a, b)
    pool.map(func, iterable)
    pool.close()
    pool.join()

if __name__ == "__main__":
    main()

Output:

hi there 1
hi there 2
hi there 3
hi there 4
hi there 5

Cleaning up old remote git branches

This command will "dry run" delete all remote (origin) merged branches, apart from master. You can change that, or, add additional branches after master: grep -v for-example-your-branch-here |

git branch -r --merged | 
  grep origin | 
  grep -v '>' | 
  grep -v master | 
  xargs -L1 | 
  awk '{sub(/origin\//,"");print}'| 
  xargs git push origin --delete --dry-run

If it looks good, remove the --dry-run. Additionally, you may like to test this on a fork first.

Getting random numbers in Java

int max = 50;
int min = 1;

1. Using Math.random()

double random = Math.random() * 49 + 1;
or
int random = (int )(Math.random() * 50 + 1);

This will give you value from 1 to 50 in case of int or 1.0 (inclusive) to 50.0 (exclusive) in case of double

Why?

random() method returns a random number between 0.0 and 0.9..., you multiply it by 50, so upper limit becomes 0.0 to 49.999... when you add 1, it becomes 1.0 to 50.999..., now when you truncate to int, you get 1 to 50. (thanks to @rup in comments). leepoint's awesome write-up on both the approaches.

2. Using Random class in Java.

Random rand = new Random(); 
int value = rand.nextInt(50); 

This will give value from 0 to 49.

For 1 to 50: rand.nextInt((max - min) + 1) + min;

Source of some Java Random awesomeness.

HTML - How to do a Confirmation popup to a Submit button and then send the request?

Another option that you can use is:

onclick="if(confirm('Do you have sure ?')){}else{return false;};"

using this function on submit button you will get what you expect.

Filter an array using a formula (without VBA)

=VLOOKUP(A2,IF(B1:B3="B",A1:C3,""),1,FALSE)

Ctrl+Shift+Enter to enter.

How can I show a hidden div when a select option is selected?

try this:

_x000D_
_x000D_
function showDiv(divId, element)_x000D_
{_x000D_
    document.getElementById(divId).style.display = element.value == 1 ? 'block' : 'none';_x000D_
}
_x000D_
#hidden_div {_x000D_
    display: none;_x000D_
}
_x000D_
<select id="test" name="form_select" onchange="showDiv('hidden_div', this)">_x000D_
   <option value="0">No</option>_x000D_
   <option value="1">Yes</option>_x000D_
</select>_x000D_
<div id="hidden_div">This is a hidden div</div>
_x000D_
_x000D_
_x000D_

Image comparison - fast algorithm

The best method I know of is to use a Perceptual Hash. There appears to be a good open source implementation of such a hash available at:

http://phash.org/

The main idea is that each image is reduced down to a small hash code or 'fingerprint' by identifying salient features in the original image file and hashing a compact representation of those features (rather than hashing the image data directly). This means that the false positives rate is much reduced over a simplistic approach such as reducing images down to a tiny thumbprint sized image and comparing thumbprints.

phash offers several types of hash and can be used for images, audio or video.

Can I serve multiple clients using just Flask app.run() as standalone?

flask.Flask.run accepts additional keyword arguments (**options) that it forwards to werkzeug.serving.run_simple - two of those arguments are threaded (a boolean) and processes (which you can set to a number greater than one to have werkzeug spawn more than one process to handle requests).

threaded defaults to True as of Flask 1.0, so for the latest versions of Flask, the default development server will be able to serve multiple clients simultaneously by default. For older versions of Flask, you can explicitly pass threaded=True to enable this behaviour.

For example, you can do

if __name__ == '__main__':
    app.run(threaded=True)

to handle multiple clients using threads in a way compatible with old Flask versions, or

if __name__ == '__main__':
    app.run(threaded=False, processes=3)

to tell Werkzeug to spawn three processes to handle incoming requests, or just

if __name__ == '__main__':
    app.run()

to handle multiple clients using threads if you know that you will be using Flask 1.0 or later.

That being said, Werkzeug's serving.run_simple wraps the standard library's wsgiref package - and that package contains a reference implementation of WSGI, not a production-ready web server. If you are going to use Flask in production (assuming that "production" is not a low-traffic internal application with no more than 10 concurrent users) make sure to stand it up behind a real web server (see the section of Flask's docs entitled Deployment Options for some suggested methods).

How do I get Fiddler to stop ignoring traffic to localhost?

For Fiddler to capture traffic from localhost on local IIS, there are 3 steps (It worked on my computer):

  1. Click Tools > Fiddler Options. Ensure Allow remote clients to connect is checked. Close Fiddler.

enter image description here

  1. Create a new DWORD named ReverseProxyForPort inside KEY_CURRENT_USER\SOFTWARE\Microsoft\Fiddler2. Set the DWORD to port 80 (choose decimal here). Restart Fiddler.

enter image description here

  1. Add port 8888 to the addresses defined in your client. For example localhost:8888/MyService/WebAPI/v1/

Edit a text file on the console using Powershell

install vim from online, and then you can just do: vim "filename" to edit that file

How to copy text programmatically in my Android app?

To enable the standard copy/paste for TextView, U can choose one of the following:

Change in layout file: add below property to your TextView

android:textIsSelectable="true"

In your Java class write this line two set the grammatically.

myTextView.setTextIsSelectable(true);

And long press on the TextView you can see copy/paste action bar.

sed one-liner to convert all uppercase to lowercase?

I like some of the answers here, but there is a sed command that should do the trick on any platform:

sed 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/'

Anyway, it's easy to understand. And knowing about the y command can come in handy sometimes.

Jest spyOn function called

You were almost done without any changes besides how you spyOn. When you use the spy, you have two options: spyOn the App.prototype, or component component.instance().

const spy = jest.spyOn(Class.prototype, "method")

The order of attaching the spy on the class prototype and rendering (shallow rendering) your instance is important.

const spy = jest.spyOn(App.prototype, "myClickFn");
const instance = shallow(<App />);

The App.prototype bit on the first line there are what you needed to make things work. A JavaScript class doesn't have any of its methods until you instantiate it with new MyClass(), or you dip into the MyClass.prototype. For your particular question, you just needed to spy on the App.prototype method myClickFn.

jest.spyOn(component.instance(), "method")

const component = shallow(<App />);
const spy = jest.spyOn(component.instance(), "myClickFn");

This method requires a shallow/render/mount instance of a React.Component to be available. Essentially spyOn is just looking for something to hijack and shove into a jest.fn(). It could be:

A plain object:

const obj = {a: x => (true)};
const spy = jest.spyOn(obj, "a");

A class:

class Foo {
    bar() {}
}

const nope = jest.spyOn(Foo, "bar");
// THROWS ERROR. Foo has no "bar" method.
// Only an instance of Foo has "bar".
const fooSpy = jest.spyOn(Foo.prototype, "bar");
// Any call to "bar" will trigger this spy; prototype or instance

const fooInstance = new Foo();
const fooInstanceSpy = jest.spyOn(fooInstance, "bar");
// Any call fooInstance makes to "bar" will trigger this spy.

Or a React.Component instance:

const component = shallow(<App />);
/*
component.instance()
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(component.instance(), "myClickFn");

Or a React.Component.prototype:

/*
App.prototype
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(App.prototype, "myClickFn");
// Any call to "myClickFn" from any instance of App will trigger this spy.

I've used and seen both methods. When I have a beforeEach() or beforeAll() block, I might go with the first approach. If I just need a quick spy, I'll use the second. Just mind the order of attaching the spy.

EDIT: If you want to check the side effects of your myClickFn you can just invoke it in a separate test.

const app = shallow(<App />);
app.instance().myClickFn()
/*
Now assert your function does what it is supposed to do...
eg.
expect(app.state("foo")).toEqual("bar");
*/

EDIT: Here is an example of using a functional component. Keep in mind that any methods scoped within your functional component are not available for spying. You would be spying on function props passed into your functional component and testing the invocation of those. This example explores the use of jest.fn() as opposed to jest.spyOn, both of which share the mock function API. While it does not answer the original question, it still provides insight on other techniques that could suit cases indirectly related to the question.

function Component({ myClickFn, items }) {
   const handleClick = (id) => {
       return () => myClickFn(id);
   };
   return (<>
       {items.map(({id, name}) => (
           <div key={id} onClick={handleClick(id)}>{name}</div>
       ))}
   </>);
}

const props = { myClickFn: jest.fn(), items: [/*...{id, name}*/] };
const component = render(<Component {...props} />);
// Do stuff to fire a click event
expect(props.myClickFn).toHaveBeenCalledWith(/*whatever*/);

Scripting SQL Server permissions

declare @DBRoleName varchar(40) = 'yourUserName'
SELECT 'GRANT ' + dbprm.permission_name + ' ON ' + OBJECT_SCHEMA_NAME(major_id) + '.' + OBJECT_NAME(major_id) + ' TO ' + dbrol.name + char(13) COLLATE Latin1_General_CI_AS
from sys.database_permissions dbprm
join sys.database_principals dbrol on
dbprm.grantee_principal_id = dbrol.principal_id
where dbrol.name = @DBRoleName

http://www.sqlserver-dba.com/2014/10/how-to-script-database-role-permissions-and-securables.html

I found this to be an excellent solution for generating a script to replicate access between environments

Bootstrap close responsive menu "on click"

I'm assuming you have a line like this defining the nav area, based on Bootstrap examples and all

<div class="nav-collapse collapse" >

Simply add the properties as such, like on the MENU button

<div class="nav-collapse collapse" data-toggle="collapse"  data-target=".nav-collapse">

I've added to <body> as well, worked. Can't say I've profiled it or anything, but seems a treat to me...until you click on a random spot of the UI to open the menu, so not so good that.

DK

iframe to Only Show a Certain Part of the Page

I needed an iframe that would embed a portion of an external page with a vertical scroll bar, cropping out the navigation menus on the top and left of the page. I was able to do it with some simple HTML and CSS.

HTML

<div id="container">
    <iframe id="embed" src="http://www.example.com"></iframe>
</div>

CSS

div#container
{
    width:840px;
    height:317px;
    overflow:scroll;     /* if you don't want a scrollbar, set to hidden */
    overflow-x:hidden;   /* hides horizontal scrollbar on newer browsers */

    /* resize and min-height are optional, allows user to resize viewable area */
    -webkit-resize:vertical; 
    -moz-resize:vertical;
    resize:vertical;
    min-height:317px;
}

iframe#embed
{
    width:1000px;       /* set this to approximate width of entire page you're embedding */
    height:2000px;      /* determines where the bottom of the page cuts off */
    margin-left:-183px; /* clipping left side of page */
    margin-top:-244px;  /* clipping top of page */
    overflow:hidden;

    /* resize seems to inherit in at least Firefox */
    -webkit-resize:none;
    -moz-resize:none;
    resize:none;
}

What is the difference between tinyint, smallint, mediumint, bigint and int in MySQL?

Data type Range Storage

bigint  -2^63 (-9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807)    8 Bytes
int -2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647)    4 Bytes
smallint    -2^15 (-32,768) to 2^15-1 (32,767)  2 Bytes
tinyint 0 to 255    1 Byte

Example

The following example creates a table using the bigint, int, smallint, and tinyint data types. Values are inserted into each column and returned in the SELECT statement.

CREATE TABLE dbo.MyTable
(
  MyBigIntColumn bigint
 ,MyIntColumn  int
 ,MySmallIntColumn smallint
 ,MyTinyIntColumn tinyint
);

GO

INSERT INTO dbo.MyTable VALUES (9223372036854775807, 214483647,32767,255);
 GO
SELECT MyBigIntColumn, MyIntColumn, MySmallIntColumn, MyTinyIntColumn
FROM dbo.MyTable;

MySQL GROUP BY two columns

Using Concat on the group by will work

SELECT clients.id, clients.name, portfolios.id, SUM ( portfolios.portfolio + portfolios.cash ) AS total
FROM clients, portfolios
WHERE clients.id = portfolios.client_id
GROUP BY CONCAT(portfolios.id, "-", clients.id)
ORDER BY total DESC
LIMIT 30

Bash script and /bin/bash^M: bad interpreter: No such file or directory

I develop on Windows and Mac/Linux at the same time and I avoid this ^M-error by simply running my scripts as I do in Windows:

$ php ./my_script

No need to change line endings.

Quickest way to find missing number in an array of numbers

Now I'm now too sharp with the Big O notations but couldn't you also do something like (in Java)

for (int i = 0; i < numbers.length; i++) {
    if(numbers[i] != i+1){
        System.out.println(i+1);
    }
}

where numbers is the array with your numbers from 1-100. From my reading of the question it did not say when to write out the missing number.

Alternatively if you COULD throw the value of i+1 into another array and print that out after the iteration.

Of course it might not abide by the time and space rules. As I said. I have to strongly brush up on Big O.