Programs & Examples On #Asynchronous wcf call

Sum rows in data.frame or matrix

The rowSums function (as Greg mentions) will do what you want, but you are mixing subsetting techniques in your answer, do not use "$" when using "[]", your code should look something more like:

data$new <- rowSums( data[,43:167] )

If you want to use a function other than sum, then look at ?apply for applying general functions accross rows or columns.

How to compute the similarity between two text documents?

If you are more interested in measuring semantic similarity of two pieces of text, I suggest take a look at this gitlab project. You can run it as a server, there is also a pre-built model which you can use easily to measure the similarity of two pieces of text; even though it is mostly trained for measuring the similarity of two sentences, you can still use it in your case.It is written in java but you can run it as a RESTful service.

Another option also is DKPro Similarity which is a library with various algorithm to measure the similarity of texts. However, it is also written in java.

code example:

// this similarity measure is defined in the dkpro.similarity.algorithms.lexical-asl package
// you need to add that to your .pom to make that example work
// there are some examples that should work out of the box in dkpro.similarity.example-gpl 
TextSimilarityMeasure measure = new WordNGramJaccardMeasure(3);    // Use word trigrams

String[] tokens1 = "This is a short example text .".split(" ");   
String[] tokens2 = "A short example text could look like that .".split(" ");

double score = measure.getSimilarity(tokens1, tokens2);

System.out.println("Similarity: " + score);

Java TreeMap Comparator

You can not sort TreeMap on values.

A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used You will need to provide comparator for Comparator<? super K> so your comparator should compare on keys.

To provide sort on values you will need SortedSet. Use

SortedSet<Map.Entry<String, Double>> sortedset = new TreeSet<Map.Entry<String, Double>>(
            new Comparator<Map.Entry<String, Double>>() {
                @Override
                public int compare(Map.Entry<String, Double> e1,
                        Map.Entry<String, Double> e2) {
                    return e1.getValue().compareTo(e2.getValue());
                }
            });

  sortedset.addAll(myMap.entrySet());

To give you an example

    SortedMap<String, Double> myMap = new TreeMap<String, Double>();
    myMap.put("a", 10.0);
    myMap.put("b", 9.0);
    myMap.put("c", 11.0);
    myMap.put("d", 2.0);
    sortedset.addAll(myMap.entrySet());
    System.out.println(sortedset);

Output:

  [d=2.0, b=9.0, a=10.0, c=11.0]

Can I use tcpdump to get HTTP requests, response header and response body?

There are tcpdump filters for HTTP GET & HTTP POST (or for both plus message body):

  • Run man tcpdump | less -Ip examples to see some examples

  • Here’s a tcpdump filter for HTTP GET (GET = 0x47, 0x45, 0x54, 0x20):

    sudo tcpdump -s 0 -A 'tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420'
    
  • Here’s a tcpdump filter for HTTP POST (POST = 0x50, 0x4f, 0x53, 0x54):

    sudo tcpdump -s 0 -A 'tcp dst port 80 and (tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x504f5354)'
    
  • Monitor HTTP traffic including request and response headers and message body (source):

    tcpdump -A -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
    tcpdump -X -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
    

For more information on the bit-twiddling in the TCP header see: String-Matching Capture Filter Generator (link to Sake Blok's explanation).

JavaScript get element by name

Method document.getElementsByName returns an array of elements. You should select first, for example.

document.getElementsByName('acc')[0].value

:: (double colon) operator in Java 8

Usually, one would call the reduce method using Math.max(int, int) as follows:

reduce(new IntBinaryOperator() {
    int applyAsInt(int left, int right) {
        return Math.max(left, right);
    }
});

That requires a lot of syntax for just calling Math.max. That's where lambda expressions come into play. Since Java 8 it is allowed to do the same thing in a much shorter way:

reduce((int left, int right) -> Math.max(left, right));

How does this work? The java compiler "detects", that you want to implement a method that accepts two ints and returns one int. This is equivalent to the formal parameters of the one and only method of interface IntBinaryOperator (the parameter of method reduce you want to call). So the compiler does the rest for you - it just assumes you want to implement IntBinaryOperator.

But as Math.max(int, int) itself fulfills the formal requirements of IntBinaryOperator, it can be used directly. Because Java 7 does not have any syntax that allows a method itself to be passed as an argument (you can only pass method results, but never method references), the :: syntax was introduced in Java 8 to reference methods:

reduce(Math::max);

Note that this will be interpreted by the compiler, not by the JVM at runtime! Although it produces different bytecodes for all three code snippets, they are semantically equal, so the last two can be considered to be short (and probably more efficient) versions of the IntBinaryOperator implementation above!

(See also Translation of Lambda Expressions)

How to check if C string is empty

The shortest way to do that would be:

do {
    // Something
} while (*url);

Basically, *url will return the char at the first position in the array; since C strings are null-terminated, if the string is empty, its first position will be the character '\0', whose ASCII value is 0; since C logical statements treat every zero value as false, this loop will keep going while the first position of the string is non-null, that is, while the string is not empty.

Recommended readings if you want to understand this better:

Run/install/debug Android applications over Wi-Fi?

For Ubuntu / Linux:

  1. Make sure your device is working for debugging: http://developer.android.com/tools/help/adb.html#Enabling
  2. Go to your sdk folder and find the folder platform-tools
  3. Use ./adb devices to list the connected devices. Make sure it is only one device connected and no emulator running.
  4. Find your device IP address, you can find it in your device: http://developer.android.com/tools/help/adb.html#wireless, or got adb shell like this: ./adb shell then netcfg. You will see a list of IP addresses. Find wlan0, in my case 192.168.100.3/2.
  5. ./adb tcpip 5555
  6. Finally enter ./adb connect <Your device IP Address>:5555 in your terminal. You can now deploy the application to your device over Wi-Fi.

Replace part of a string with another string

To have the new string returned use this:

std::string ReplaceString(std::string subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while ((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
    return subject;
}

If you need performance, here is an optimized function that modifies the input string, it does not create a copy of the string:

void ReplaceStringInPlace(std::string& subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while ((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
}

Tests:

std::string input = "abc abc def";
std::cout << "Input string: " << input << std::endl;

std::cout << "ReplaceString() return value: " 
          << ReplaceString(input, "bc", "!!") << std::endl;
std::cout << "ReplaceString() input string not modified: " 
          << input << std::endl;

ReplaceStringInPlace(input, "bc", "??");
std::cout << "ReplaceStringInPlace() input string modified: " 
          << input << std::endl;

Output:

Input string: abc abc def
ReplaceString() return value: a!! a!! def
ReplaceString() input string not modified: abc abc def
ReplaceStringInPlace() input string modified: a?? a?? def

How to get all columns' names for all the tables in MySQL?

To list all the fields from a table in MySQL:

select * 
  from information_schema.columns 
 where table_schema = 'your_DB_name' 
   and table_name = 'Your_tablename'

Tab key == 4 spaces and auto-indent after curly braces in Vim

Firstly, do not use the Tab key in Vim for manual indentation. Vim has a pair of commands in insert mode for manually increasing or decreasing the indentation amount. Those commands are Ctrl-T and Ctrl-D. These commands observe the values of tabstop, shiftwidth and expandtab, and maintain the correct mixture of spaces and tabs (maximum number of tabs followed by any necessary number of spaces).

Secondly, these manual indenting keys don't have to be used very much anyway if you use automatic indentation.

If Ctrl-T instead of Tab bothers you, you can remap it:

:imap <Tab> ^T

You can also remap Shift-Tab to do the Ctrl-D deindent:

:imap <S-Tab> ^D

Here ^T and ^D are literal control characters that can be inserted as Ctrl-VCtrl-T.

With this mapping in place, you can still type literal Tab into the buffer using Ctrl-VTab. Note that if you do this, even if :set expandtab is on, you get an unexpanded tab character.

A similar effect to the <Tab> map is achieved using :set smarttab, which also causes backspace at the front of a line to behave smart.

In smarttab mode, when Tab is used not at the start of a line, it has no special meaning. That's different from my above mapping of Tab to Ctrl-T, because a Ctrl-T used anywhere in a line (in insert mode) will increase that line's indentation.

Other useful mappings may be:

:map <Tab> >
:map <S-Tab> <

Now we can do things like select some lines, and hit Tab to indent them over. Or hit Tab twice on a line (in command mode) to increase its indentation.

If you use the proper indentation management commands, then everything is controlled by the three parameters: shiftwidth, tabstop and expandtab.

The shiftwidth parameter controls your indentation size; if you want four space indents, use :set shiftwidth=4, or the abbreviation :set sw=4.

If only this is done, then indentation will be created using a mixture of spaces and tabs, because noexpandtab is the default. Use :set expandtab. This causes tab characters which you type into the buffer to expand into spaces, and for Vim-managed indentation to use only spaces.

When expandtab is on, and if you manage your indentation through all the proper Vim mechanisms, the value of tabstop becomes irrelevant. It controls how tabs appear if they happen to occur in the file. If you have set tabstop=8 expandtab and then sneak a hard tab into the file using Ctrl-VTab, it will produce an alignment to the next 8-column-based tab position, as usual.

Bootstrap collapse animation not smooth

Do not set a height on the .collapse tag. It affects the animation, if the height is overridden with css; it will not animate correctly.

Android Activity as a dialog

If your activity is being rendered as a dialog, simply add a button to your activity's xml,

<Button
    android:id="@+id/close_button"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Dismiss" />

Then attach a click listener in your Activity's Java code. In the listener, simply call finish()

Button close_button = (Button) findViewById(R.id.close_button);
close_button.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        finish();
    }
});

That should dismiss your dialog, returning you to the calling activity.

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

$parent doesn't work if there are multiple parents. instead of that we can define a parent index variable in init and use it

<div data-ng-init="parentIndex = $index" ng-repeat="f in foos">
  <div>
    <div data-ng-init="childIndex = $index" ng-repeat="b in foos.bars">
      <a ng-click="addSomething(parentIndex)">Add Something</a>
    </div>
  </div>
</div>

How to insert data using wpdb

Try this

I recently leaned about $wpdb->prepare HERE and added into our Free Class Booking plugin, plugin approved on wordpress.org and will live soon:

global $wpdb;
$tablename = $wpdb->prefix . "submitted_form";

$name     = "Kumkum"; //string value use: %s
$email    = "[email protected]"; //string value use: %s
$phone    = "3456734567"; //numeric value use: %d
$country  = "India"; //string value use: %s
$course   = "Database"; //string value use: %s
$message  = "hello i want to read db"; //string value use: %s
$now      = new DateTime(); //string value use: %s
$datesent = $now->format('Y-m-d H:i:s'); //string value use: %s

$sql = $wpdb->prepare("INSERT INTO `$tablename` (`name`, `email`, `phone`, `country`, `course`, `message`, `datesent`) values (%s, %s, %d, %s, %s, %s, %s)", $name, $email, $phone, $country, $course, $message, $datesent);

$wpdb->query($sql);

Thanks -Frank

Flatten an irregular list of lists

I used recursive to solve nested list with any depth

def combine_nlist(nlist,init=0,combiner=lambda x,y: x+y):
    '''
    apply function: combiner to a nested list element by element(treated as flatten list)
    '''
    current_value=init
    for each_item in nlist:
        if isinstance(each_item,list):
            current_value =combine_nlist(each_item,current_value,combiner)
        else:
            current_value = combiner(current_value,each_item)
    return current_value

So after i define function combine_nlist, it is easy to use this function do flatting. Or you can combine it into one function. I like my solution because it can be applied to any nested list.

def flatten_nlist(nlist):
    return combine_nlist(nlist,[],lambda x,y:x+[y])

result

In [379]: flatten_nlist([1,2,3,[4,5],[6],[[[7],8],9],10])
Out[379]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Iterate through a C array

I think you should store the size somewhere.

The null-terminated-string kind of model for determining array length is a bad idea. For instance, getting the size of the array will be O(N) when it could very easily have been O(1) otherwise.

Having that said, a good solution might be glib's Arrays, they have the added advantage of expanding automatically if you need to add more items.

P.S. to be completely honest, I haven't used much of glib, but I think it's a (very) reputable library.

How to configure static content cache per folder and extension in IIS7?

You can set specific cache-headers for a whole folder in either your root web.config:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <!-- Note the use of the 'location' tag to specify which 
       folder this applies to-->
  <location path="images">
    <system.webServer>
      <staticContent>
        <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:00:15" />
      </staticContent>
    </system.webServer>
  </location>
</configuration>

Or you can specify these in a web.config file in the content folder:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <staticContent>
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:00:15" />
    </staticContent>
  </system.webServer>
</configuration>

I'm not aware of a built in mechanism to target specific file types.

Efficient SQL test query or validation query that will work across all (or most) databases

For MSSQL.

This helped me determine if linked servers were alive. Using an Open Query connection and a TRY CATCH to put the results of the error to something useful.

IF OBJECT_ID('TEMPDB..#TEST_CONNECTION') IS NOT NULL DROP TABLE #TEST_CONNECTION
IF OBJECT_ID('TEMPDB..#RESULTSERROR') IS NOT NULL DROP TABLE #RESULTSERROR
IF OBJECT_ID('TEMPDB..#RESULTSGOOD') IS NOT NULL DROP TABLE #RESULTSGOOD

DECLARE @LINKEDSERVER AS VARCHAR(25)    SET @LINKEDSERVER = 'SERVER NAME GOES HERE'
DECLARE @SQL AS VARCHAR(MAX)
DECLARE @OPENQUERY AS VARCHAR(MAX)

--IF OBJECT_ID ('dbo.usp_GetErrorInfo', 'P' ) IS NOT NULL DROP PROCEDURE usp_GetErrorInfo;  
--GO  

---- Create procedure to retrieve error information.  
--CREATE PROCEDURE dbo.usp_GetErrorInfo  
--AS  
--SELECT     
--    ERROR_NUMBER() AS ErrorNumber  
--    ,ERROR_SEVERITY() AS ErrorSeverity  
--    ,ERROR_STATE() AS ErrorState  
--    ,ERROR_PROCEDURE() AS ErrorProcedure  
--    ,ERROR_LINE() AS ErrorLine  
--    ,ERROR_MESSAGE() AS Message;  
--GO  


BEGIN TRY
SET @SQL='
SELECT 1 
'''
--SELECT @SQL
SET @OPENQUERY = 'SELECT * INTO ##TEST_CONNECTION FROM OPENQUERY(['+ @LINKEDSERVER +'],''' + @SQL + ')'
--SELECT @OPENQUERY
EXEC(@OPENQUERY)
SELECT * INTO #TEST_CONNECTION FROM ##TEST_CONNECTION
DROP TABLE ##TEST_CONNECTION
--SELECT * FROM #TEST_CONNECTION
END TRY

BEGIN CATCH
-- Execute error retrieval routine.
IF OBJECT_ID('dbo.usp_GetErrorInfo') IS NOT NULL -- IT WILL ALWAYS HAVE SOMTHING... 
    BEGIN
        CREATE TABLE #RESULTSERROR (
        [ErrorNumber]       INT
        ,[ErrorSeverity]    INT
        ,[ErrorState]       INT
        ,[ErrorProcedure]   INT
        ,[ErrorLine]        INT
        ,[Message]          NVARCHAR(MAX) 
        )
        INSERT INTO #RESULTSERROR
        EXECUTE dbo.usp_GetErrorInfo
    END
END CATCH

BEGIN 
    IF (Select ERRORNUMBER FROM #RESULTSERROR WHERE ERRORNUMBER = '1038') IS NOT NULL --'1038' FOR ME SHOWED A CONNECTION ATLEAST. 
        SELECT
        '0' AS [ErrorNumber]        
        ,'0'AS [ErrorSeverity]  
        ,'0'AS [ErrorState]     
        ,'0'AS [ErrorProcedure] 
        ,'0'AS [ErrorLine]      
        , CONCAT('CONNECTION IS UP ON ', @LINKEDSERVER) AS [Message]            
    ELSE 
        SELECT * FROM #RESULTSERROR
END

docs.microsoft.com

Javac is not found

Easiest way: search for javac.exe in windows search bar. Then copy and paste the entire folder name and add it into the environmental variables path in advanced system settings.

Difference between readFile() and readFileSync()

readFileSync() is synchronous and blocks execution until finished. These return their results as return values. readFile() are asynchronous and return immediately while they function in the background. You pass a callback function which gets called when they finish. let's take an example for non-blocking.

following method read a file as a non-blocking way

var fs = require('fs');
fs.readFile(filename, "utf8", function(err, data) {
        if (err) throw err;
        console.log(data);
});

following is read a file as blocking or synchronous way.

var data = fs.readFileSync(filename);

LOL...If you don't want readFileSync() as blocking way then take reference from the following code. (Native)

var fs = require('fs');
function readFileAsSync(){
    new Promise((resolve, reject)=>{
        fs.readFile(filename, "utf8", function(err, data) {
                if (err) throw err;
                resolve(data);
        });
    });
}

async function callRead(){
    let data = await readFileAsSync();
    console.log(data);
}

callRead();

it's mean behind scenes readFileSync() work same as above(promise) base.

CMAKE_MAKE_PROGRAM not found

I tried to use CMake to build GammaRay for Qt on Windows with mingw. So, I had the Qt installed. And I had the same problem as other users here.

The approach that worked for me is launching cmake-gui from Qt build prompt (a shortcut created by Qt installer in "Start Menu\All programs\Qt{QT_VERSION}" folder).

mySQL :: insert into table, data from another table?

Answered by zerkms is the correct method. But, if someone looking to insert more extra column in the table then you can get it from the following:

INSERT INTO action_2_members (`campaign_id`, `mobile`, `email`, `vote`, `vote_date`, `current_time`)
SELECT `campaign_id`, `from_number`, '[email protected]', `received_msg`, `date_received`, 1502309889 FROM `received_txts` WHERE `campaign_id` = '8'

In the above query, there are 2 extra columns named email & current_time.

Local storage in Angular 2

We can easily use the localStorage for setting the data and receiving the data.

Note: it works with both angular2 and angular 4

//set the data
localStorage.setItem(key, value);   //syntax example
localStorage.setItem('tokenKey', response.json().token);

//get the data
localStorage.getItem('tokenKey')

//confirm if token is exist or not
return localStorage.getItem('tokenKey') != null;

Typescript: difference between String and string

TypeScript: String vs string

Argument of type 'String' is not assignable to parameter of type 'string'.

'string' is a primitive, but 'String' is a wrapper object.

Prefer using 'string' when possible.

demo

String Object

// error
class SVGStorageUtils {
  store: object;
  constructor(store: object) {
    this.store = store;
  }
  setData(key: String = ``, data: object) {
    sessionStorage.setItem(key, JSON.stringify(data));
  }
  getData(key: String = ``) {
    const obj = JSON.parse(sessionStorage.getItem(key));
  }
}

string primitive

// ok
class SVGStorageUtils {
  store: object;
  constructor(store: object) {
    this.store = store;
  }
  setData(key: string = ``, data: object) {
    sessionStorage.setItem(key, JSON.stringify(data));
  }
  getData(key: string = ``) {
    const obj = JSON.parse(sessionStorage.getItem(key));
  }
}

enter image description here

How does one create an InputStream from a String?

You could do this:

InputStream in = new ByteArrayInputStream(string.getBytes("UTF-8"));

Note the UTF-8 encoding. You should specify the character set that you want the bytes encoded into. It's common to choose UTF-8 if you don't specifically need anything else. Otherwise if you select nothing you'll get the default encoding that can vary between systems. From the JavaDoc:

The behavior of this method when this string cannot be encoded in the default charset is unspecified. The CharsetEncoder class should be used when more control over the encoding process is required.

MongoDb query condition on comparing 2 fields

You can use a $where. Just be aware it will be fairly slow (has to execute Javascript code on every record) so combine with indexed queries if you can.

db.T.find( { $where: function() { return this.Grade1 > this.Grade2 } } );

or more compact:

db.T.find( { $where : "this.Grade1 > this.Grade2" } );

UPD for mongodb v.3.6+

you can use $expr as described in recent answer

Twitter bootstrap scrollable modal

None of this will work as expected.. The correct way is to change position: fixed to position: absolute for .modal class

Retrieving the first digit of a number

Almost certainly more efficient than using Strings:

int firstDigit(int x) {
    while (x > 9) {
        x /= 10;
    }
    return x;
}

(Works only for nonnegative integers.)

WHERE clause on SQL Server "Text" data type

Another option would be:

SELECT * FROM [Village] WHERE PATINDEX('foo', [CastleType]) <> 0

Java NIO: What does IOException: Broken pipe mean?

You should assume the socket was closed on the other end. Wrap your code with a try catch block for IOException.

You can use isConnected() to determine if the SocketChannel is connected or not, but that might change before your write() invocation finishes. Try calling it in your catch block to see if in fact this is why you are getting the IOException.

Change the "From:" address in Unix "mail"

Plus it's good to use -F option to specify Name of sender.

Something like this:

mail -s "$SUBJECT" $MAILTO -- -F $MAILFROM -f ${MAILFROM}@somedomain.com

Or just look at available options: http://www.courier-mta.org/sendmail.html

Warning: date_format() expects parameter 1 to be DateTime

Best way is use DateTime object to convert your date.

$myDateTime = DateTime::createFromFormat('Y-m-d', $weddingdate);
$formattedweddingdate = $myDateTime->format('d-m-Y');

Note: It will support for PHP 5 >= 5.3.0 only.

What does <> mean?

Yes, it's "not equal".

Create a File object in memory from a string in Java

Usually when a method accepts a file, there's another method nearby that accepts a stream. If this isn't the case, the API is badly coded. Otherwise, you can use temporary files, where permission is usually granted in many cases. If it's applet, you can request write permission.

An example:

try {
    // Create temp file.
    File temp = File.createTempFile("pattern", ".suffix");

    // Delete temp file when program exits.
    temp.deleteOnExit();

    // Write to temp file
    BufferedWriter out = new BufferedWriter(new FileWriter(temp));
    out.write("aString");
    out.close();
} catch (IOException e) {
}

How do I get a button to open another activity?

A. Make sure your other activity is declared in manifest:

<activity
    android:name="MyOtherActivity"
    android:label="@string/app_name">
</activity>

All activities must be declared in manifest, even if they do not have an intent filter assigned to them.


B. In your MainActivity do something like this:

Button btn = (Button)findViewById(R.id.open_activity_button);    

btn.setOnClickListener(new View.OnClickListener() {         
        @Override
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this, MyOtherActivity.class));
        }
});

What are major differences between C# and Java?

Another good resource is http://www.javacamp.org/javavscsharp/ This site enumerates many examples that ilustrate almost all the differences between these two programming languages.

About the Attributes, Java has Annotations, that work almost the same way.

How to concat two ArrayLists?

add one ArrayList to second ArrayList as:

Arraylist1.addAll(Arraylist2);

EDIT : if you want to Create new ArrayList from two existing ArrayList then do as:

ArrayList<String> arraylist3=new ArrayList<String>();

arraylist3.addAll(Arraylist1); // add first arraylist

arraylist3.addAll(Arraylist2); // add Second arraylist

What are the most widely used C++ vector/matrix math/linear algebra libraries, and their cost and benefit tradeoffs?

For what it's worth, I've tried both Eigen and Armadillo. Below is a brief evaluation.

Eigen Advantages: 1. Completely self-contained -- no dependence on external BLAS or LAPACK. 2. Documentation decent. 3. Purportedly fast, although I haven't put it to the test.

Disadvantage: The QR algorithm returns just a single matrix, with the R matrix embedded in the upper triangle. No idea where the rest of the matrix comes from, and no Q matrix can be accessed.

Armadillo Advantages: 1. Wide range of decompositions and other functions (including QR). 2. Reasonably fast (uses expression templates), but again, I haven't really pushed it to high dimensions.

Disadvantages: 1. Depends on external BLAS and/or LAPACK for matrix decompositions. 2. Documentation is lacking IMHO (including the specifics wrt LAPACK, other than changing a #define statement).

Would be nice if an open source library were available that is self-contained and straightforward to use. I have run into this same issue for 10 years, and it gets frustrating. At one point, I used GSL for C and wrote C++ wrappers around it, but with modern C++ -- especially using the advantages of expression templates -- we shouldn't have to mess with C in the 21st century. Just my tuppencehapenny.

How can I make my match non greedy in vim?

With \v (as suggested in several comments)

:%s/\v(style|class)\=".{-}"//g

Which Python memory profiler is recommended?

Consider the objgraph library (see this blog post for an example use case).

Fixed width buttons with Bootstrap

Best way to the solution of your problem is to use button block btn-block with desired column width.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>_x000D_
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
    <div class="col-md-12">_x000D_
      <button class="btn btn-primary btn-block">Save</button>_x000D_
    </div>_x000D_
    <div class="col-md-12">_x000D_
        <button class="btn btn-success btn-block">Download</button>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

jQuery Popup Bubble/Tooltip

Autoresize simple Popup Bubble

index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <link href="bubble.css" type="text/css" rel="stylesheet" />
  <script language="javascript" type="text/javascript" src="jquery.js"></script>
  <script language="javascript" type="text/javascript" src="bubble.js"></script>
</head>
<body>
  <br/><br/>
  <div class="bubbleInfo">
      <div class="bubble" title="Text 1">Set cursor</div>
  </div>
  <br/><br/><br/><br/>
  <div class="bubbleInfo">
      <div class="bubble" title="Text 2">Set cursor</div>
  </div>
</body>
</html>

bubble.js

$(function () {     
  var i = 0;
  var z=1;
  do{
    title = $('.bubble:eq('+i+')').attr('title');
    if(!title){
      z=0;
    } else {
       $('.bubble:eq('+i+')').after('<table style="opacity: 0; top: -50px; left: -33px; display: none;" id="dpop" class="popup"><tbody><tr><td id="topleft" class="corner"></td><td class="top"></td><td id="topright" class="corner"></td></tr><tr><td class="left"></td><td>'+title+'</td><td class="right"></td></tr><tr><td class="corner" id="bottomleft"></td><td class="bottom"><img src="bubble/bubble-tail.png" height="25px" width="30px" /></td><td id="bottomright" class="corner"></td></tr></tbody></table>');
       $('.bubble:eq('+i+')').removeAttr('title');
    }
    i++;
  }while(z>0)

  $('.bubbleInfo').each(function () {
    var distance = 10;
    var time = 250;
    var hideDelay = 500;        
    var hideDelayTimer = null;       
    var beingShown = false;
    var shown = false;
    var trigger = $('.bubble', this);
    var info = $('.popup', this).css('opacity', 0);        

    $([trigger.get(0), info.get(0)]).mouseover(function () {
      if (hideDelayTimer) clearTimeout(hideDelayTimer);
      if (beingShown || shown) {
        // don't trigger the animation again
        return;
      } else {
        // reset position of info box
        beingShown = true;

        info.css({
        top: -40,
        left: 10,
        display: 'block'
        }).animate({
        top: '-=' + distance + 'px',
        opacity: 1
        }, time, 'swing', function() {
          beingShown = false;
          shown = true;
        });
      }          
      return false;
    }).mouseout(function () {
      if (hideDelayTimer) clearTimeout(hideDelayTimer);
      hideDelayTimer = setTimeout(function () {
        hideDelayTimer = null;
        info.animate({
          top: '-=' + distance + 'px',
          opacity: 0
        }, time, 'swing', function () {
          shown = false;
          info.css('display', 'none');
        });
      }, hideDelay);
      return false;
    });
  }); 
});

bubble.css

/* Booble */
.bubbleInfo {
    position: relative;
    width: 500px;
}
.bubble {       
}
.popup {
    position: absolute;
    display: none;
    z-index: 50;
    border-collapse: collapse;
    font-size: .8em;
}
.popup td.corner {
    height: 13px;
    width: 15px;
}
.popup td#topleft { 
    background-image: url(bubble/bubble-1.png); 
} 
.popup td.top { 
    background-image: url(bubble/bubble-2.png); 
}
.popup td#topright { 
    background-image: url(bubble/bubble-3.png); 
}
.popup td.left { 
    background-image: url(bubble/bubble-4.png); 
}
.popup td.right { 
    background-image: url(bubble/bubble-5.png); 
}
.popup td#bottomleft { 
    background-image: url(bubble/bubble-6.png); 
}
.popup td.bottom { 
    background-image: url(bubble/bubble-7.png); 
    text-align: center;
}
.popup td.bottom img { 
    display: block; 
    margin: 0 auto; 
}
.popup td#bottomright { 
    background-image: url(bubble/bubble-8.png); 
}

Calling C/C++ from Python?

The question is how to call a C function from Python, if I understood correctly. Then the best bet are Ctypes (BTW portable across all variants of Python).

>>> from ctypes import *
>>> libc = cdll.msvcrt
>>> print libc.time(None)
1438069008
>>> printf = libc.printf
>>> printf("Hello, %s\n", "World!")
Hello, World!
14
>>> printf("%d bottles of beer\n", 42)
42 bottles of beer
19

For a detailed guide you may want to refer to my blog article.

REST API error code 500 handling

The real question is why does it generate a 500 error. If it is related to any input parameters, then I would argue that it should be handled internally and returned as a 400 series error. Generally a 400, 404 or 406 would be appropriate to reflect bad input since the general convention is that a RESTful resource is uniquely identified by the URL and a URL that cannot generate a valid response is a bad request (400) or similar.

If the error is caused by anything other than the inputs explicitly or implicitly supplied by the request, then I would say a 500 error is likely appropriate. So a failed database connection or other unpredictable error is accurately represented by a 500 series error.

macOS on VMware doesn't recognize iOS device

I had the same issue, but was quite easy to solve. Follow the next steps:

1) In the Virtual Machine (VMWare) settings:

  • Set the USB compatibility to be 2.0 instead of 3.0
  • Check the setting "Show all USB input devices"

2) Add the device into the list of allowed development devices in your Apple Developer's account. Without that step there is no way to use your device in Xcode.

Next some instructions: Register a single device

Is There a Better Way of Checking Nil or Length == 0 of a String in Ruby?

As it was said here before Rails (ActiveSupport) have a handy blank? method and it is implemented like this:

class Object
  def blank?
    respond_to?(:empty?) ? empty? : !self
  end
end

Pretty easy to add to any ruby-based project.

The beauty of this solution is that it works auto-magicaly not only for Strings but also for Arrays and other types.

Https Connection Android

I make this class and found

package com.example.fakessl;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;

import android.util.Log;

public class CertificadoAceptar {
    private static TrustManager[] trustManagers;

    public static class _FakeX509TrustManager implements
            javax.net.ssl.X509TrustManager {
        private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};

        public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
        }

        public boolean isClientTrusted(X509Certificate[] chain) {
            return (true);
        }

        public boolean isServerTrusted(X509Certificate[] chain) {
            return (true);
        }

        public X509Certificate[] getAcceptedIssuers() {
            return (_AcceptedIssuers);
        }
    }

    public static void allowAllSSL() {

        javax.net.ssl.HttpsURLConnection
                .setDefaultHostnameVerifier(new HostnameVerifier() {
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                });

        javax.net.ssl.SSLContext context = null;

        if (trustManagers == null) {
            trustManagers = new javax.net.ssl.TrustManager[] { new _FakeX509TrustManager() };
        }

        try {
            context = javax.net.ssl.SSLContext.getInstance("TLS");
            context.init(null, trustManagers, new SecureRandom());
        } catch (NoSuchAlgorithmException e) {
            Log.e("allowAllSSL", e.toString());
        } catch (KeyManagementException e) {
            Log.e("allowAllSSL", e.toString());
        }
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context
                .getSocketFactory());
    }
}

in you code white this

CertificadoAceptar ca = new CertificadoAceptar();
ca.allowAllSSL();
HttpsTransportSE Transport = new HttpsTransportSE("iphost or host name", 8080, "/WS/wsexample.asmx?WSDL", 30000);

Why does instanceof return false for some literals?

Primitives are a different kind of type than objects created from within Javascript. From the Mozilla API docs:

var color1 = new String("green");
color1 instanceof String; // returns true
var color2 = "coral";
color2 instanceof String; // returns false (color2 is not a String object)

I can't find any way to construct primitive types with code, perhaps it's not possible. This is probably why people use typeof "foo" === "string" instead of instanceof.

An easy way to remember things like this is asking yourself "I wonder what would be sane and easy to learn"? Whatever the answer is, Javascript does the other thing.

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

JPQL IN clause: Java-Arrays (or Lists, Sets...)?

I'm not sure for JPA 1.0 but you can pass a Collection in JPA 2.0:

String qlString = "select item from Item item where item.name IN :names"; 
Query q = em.createQuery(qlString, Item.class);

List<String> names = Arrays.asList("foo", "bar");

q.setParameter("names", names);
List<Item> actual = q.getResultList();

assertNotNull(actual);
assertEquals(2, actual.size());

Tested with EclipseLInk. With Hibernate 3.5.1, you'll need to surround the parameter with parenthesis:

String qlString = "select item from Item item where item.name IN (:names)";

But this is a bug, the JPQL query in the previous sample is valid JPQL. See HHH-5126.

CSS: How to align vertically a "label" and "input" inside a "div"?

_x000D_
_x000D_
div {_x000D_
    display: table-cell;_x000D_
    vertical-align: middle;_x000D_
    height: 50px;_x000D_
    border: 1px solid red;_x000D_
}
_x000D_
<div>_x000D_
    <label for='name'>Name:</label>_x000D_
    <input type='text' id='name' />_x000D_
</div>
_x000D_
_x000D_
_x000D_

The advantages of this method is that you can change the height of the div, change the height of the text field and change the font size and everything will always stay in the middle.

http://jsfiddle.net/53ALd/6/

What is the difference between . (dot) and $ (dollar sign)?

My rule is simple (I'm beginner too):

  • do not use . if you want to pass the parameter (call the function), and
  • do not use $ if there is no parameter yet (compose a function)

That is

show $ head [1, 2]

but never:

show . head [1, 2]

Fixed size div?

This is a fairly trivial effect to accomplish. One way to achieve this is to simply place floated div elements within a common parent container, and set their width and height. In order to clear the floated elements, we set the overflow property of the parent.

<div class="container">
    <div class="cube">do</div>
    <div class="cube">ray</div>
    <div class="cube">me</div>
    <div class="cube">fa</div>
    <div class="cube">so</div>
    <div class="cube">la</div>
    <div class="cube">te</div>
    <div class="cube">do</div>
</div>

The CSS resembles the strategy outlined in the first paragraph above:

.container {
    width: 450px;
    overflow: auto;
}

.cube {
    float: left;
    width: 150px; 
    height: 150px;
}

You can see the end result here: http://jsfiddle.net/Qjum2/2/

Browsers that support pseudo elements provide an alternative way to clear:

.container::after {
    content: "";
    clear: both;
    display: block;
}

You can see the results here: http://jsfiddle.net/Qjum2/3/

I hope this helps.

What is the easiest way to parse an INI file in Java?

Using answer by @Aerospace, I realized that it is legitimate for INI files to have sections without any key-values. In this case, addition to the top-level map should happen before any key-values are found, ex (minimally updated for Java 8):

            Path location = ...;
            try (BufferedReader br = new BufferedReader(new FileReader(location.toFile()))) {
                String line;
                String section = null;
                while ((line = br.readLine()) != null) {
                    Matcher m = this.section.matcher(line);
                    if (m.matches()) {
                        section = m.group(1).trim();
                        entries.computeIfAbsent(section, k -> new HashMap<>());
                    } else if (section != null) {
                        m = keyValue.matcher(line);
                        if (m.matches()) {
                            String key = m.group(1).trim();
                            String value = m.group(2).trim();
                            entries.get(section).put(key, value);
                        }
                    }
                }
            } catch (IOException ex) {
                System.err.println("Failed to read and parse INI file '" + location + "', " + ex.getMessage());
                ex.printStackTrace(System.err);
            }

How to dynamically add elements to String array?

Arrays in Java have a defined size, you cannot change it later by adding or removing elements (you can read some basics here).

Instead, use a List:

ArrayList<String> mylist = new ArrayList<String>();
mylist.add(mystring); //this adds an element to the list.

Of course, if you know beforehand how many strings you are going to put in your array, you can create an array of that size and set the elements by using the correct position:

String[] myarray = new String[numberofstrings];
myarray[23] = string24; //this sets the 24'th (first index is 0) element to string24.

concatenate variables

set ROOT=c:\programs 
set SRC_ROOT=%ROOT%\System\Source

Serializing to JSON in jQuery

I haven't used it but you might want to try the jQuery plugin written by Mark Gibson

It adds the two functions: $.toJSON(value), $.parseJSON(json_str, [safe]).

Taking inputs with BufferedReader in Java

BufferedReader#read reads single character[0 to 65535 (0x00-0xffff)] from the stream, so it is not possible to read single integer from stream.

            String s= inp.readLine();
            int[] m= new int[2];
            String[] s1 = inp.readLine().split(" ");
            m[0]=Integer.parseInt(s1[0]);
            m[1]=Integer.parseInt(s1[1]);

            // Checking whether I am taking the inputs correctly
            System.out.println(s);
            System.out.println(m[0]);
            System.out.println(m[1]);

You can check also Scanner vs. BufferedReader.

Create list of object from another using Java 8 Streams

I prefer to solve this in the classic way, creating a new array of my desired data type:

List<MyNewType> newArray = new ArrayList<>();
myOldArray.forEach(info -> newArray.add(objectMapper.convertValue(info, MyNewType.class)));

Webdriver Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms

I got the same error "selenium_Unable to connect to host 127.0.0.1 on port 7055" Solution : I've used selenium-java-2.48.2 with Firefox version 43.0.1 and now its working well.

jQuery: How to get the event object in an event handler function without passing it as an argument?

Write your event handler declaration like this:

<a href="#" onclick="myFunc(event,1,2,3)">click</a>

Then your "myFunc()" function can access the event.

The string value of the "onclick" attribute is converted to a function in a way that's almost exactly the same as the browser (internally) calling the Function constructor:

theAnchor.onclick = new Function("event", theOnclickString);

(except in IE). However, because "event" is a global in IE (it's a window attribute), you'll be able to pass it to the function that way in any browser.

How do I get the current absolute URL in Ruby on Rails?

request.env["REQUEST_URI"]

works in rails 2.3.4 tested and do not know about other versions.

How to join two JavaScript Objects, without using JQUERY

This simple function recursively merges JSON objects, please notice that this function merges all JSON into first param (target), if you need new object modify this code.

var mergeJSON = function (target, add) {
    function isObject(obj) {
        if (typeof obj == "object") {
            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {
                    return true; // search for first object prop
                }
            }
        }
        return false;
    }
    for (var key in add) {
        if (add.hasOwnProperty(key)) {
            if (target[key] && isObject(target[key]) && isObject(add[key])) {
                this.mergeJSON(target[key], add[key]);
            } else {
                target[key] = add[key];
            }
        }
    }
    return target;
};

BTW instead of isObject() function may be used condition like this:

JSON.stringify(add[key])[0] == "{"

but this is not good solution, because it's will take a lot of resources if we have large JSON objects.

Is there a way to rollback my last push to Git?

Since you are the only user:

git reset --hard HEAD@{1}
git push -f
git reset --hard HEAD@{1}

( basically, go back one commit, force push to the repo, then go back again - remove the last step if you don't care about the commit )

Without doing any changes to your local repo, you can also do something like:

git push -f origin <sha_of_previous_commit>:master

Generally, in published repos, it is safer to do git revert and then git push

How to check version of a CocoaPods framework

pod --version

to get the version of installed pod

Transactions in .net

It also depends on what you need. For basic SQL transactions you could try doing TSQL transactions by using BEGIN TRANS and COMMIT TRANS in your code. That is the easiest way but it does have complexity and you have to be careful to commit properly (and rollback).

I would use something like

SQLTransaction trans = null;
using(trans = new SqlTransaction)
{
    ...
    Do SQL stuff here passing my trans into my various SQL executers
    ...
    trans.Commit  // May not be quite right
}

Any failure will pop you right out of the using and the transaction will always commit or rollback (depending on what you tell it to do). The biggest problem we faced was making sure it always committed. The using ensures the scope of the transaction is limited.

How to import a JSON file in ECMAScript 6?

Unfortunately ES6/ES2015 doesn't support loading JSON via the module import syntax. But...

There are many ways you can do it. Depending on your needs you can either look into how to read files in JavaScript (window.FileReader could be an option if you're running in the browser) or use some other loaders as described in other questions (assuming you are using NodeJS).

IMO simplest way is probably to just put the JSON as a JS object into an ES6 module and export it. That way you can just import it where you need it.

Also worth noting if you're using Webpack, importing of JSON files will work by default (since webpack >= v2.0.0).

import config from '../config.json';

Convert A String (like testing123) To Binary In Java

Here are my solutions. Their advantages are : easy-understanding code, works for all characters. Enjoy.

Solution 1 :

public static void main(String[] args) {

    String str = "CC%";
    String result = "";
    char[] messChar = str.toCharArray();

    for (int i = 0; i < messChar.length; i++) {
        result += Integer.toBinaryString(messChar[i]) + " ";
    }

    System.out.println(result);
}

prints :

1000011 1000011 100101

Solution 2 :

Possibility to choose the number of displayed bits per char.

public static String toBinary(String str, int bits) {
    String result = "";
    String tmpStr;
    int tmpInt;
    char[] messChar = str.toCharArray();

    for (int i = 0; i < messChar.length; i++) {
        tmpStr = Integer.toBinaryString(messChar[i]);
        tmpInt = tmpStr.length();
        if(tmpInt != bits) {
            tmpInt = bits - tmpInt;
            if (tmpInt == bits) {
                result += tmpStr;
            } else if (tmpInt > 0) {
                for (int j = 0; j < tmpInt; j++) {
                    result += "0";
                }
                result += tmpStr;
            } else {
                System.err.println("argument 'bits' is too small");
            }
        } else {
            result += tmpStr;
        }
        result += " "; // separator
    }

    return result;
}

public static void main(String args[]) {
    System.out.println(toBinary("CC%", 8));
}

prints :

01000011 01000011 00100101

how to add <script>alert('test');</script> inside a text box?

I want to alert('test'); in an input type text but it should not execute the alert(alert prompt).

<input type="text" value="<script>alert('test');</script>" />

Produces:

enter image description here

You can do this programatically via JavaScript. First obtain a reference to the input element, then set the value attribute.

var inputElement = document.querySelector("input");
inputElement.value = "<script>alert('test');<\/script>";

How is CountDownLatch used in Java Multithreading?

CountDownLatch in Java is a type of synchronizer which allows one Thread to wait for one or more Threads before it starts processing.

CountDownLatch works on latch principle, thread will wait until gate is open. One thread waits for n number of threads specified while creating CountDownLatch.

e.g. final CountDownLatch latch = new CountDownLatch(3);

Here we set the counter to 3.

Any thread, usually main thread of application, which calls CountDownLatch.await() will wait until count reaches zero or it's interrupted by another Thread. All other threads are required to do count down by calling CountDownLatch.countDown() once they are completed or ready to the job. as soon as count reaches zero, the Thread awaiting starts running.

Here the count is get decremented by CountDownLatch.countDown() method.

The Thread which calls the await() method will wait until the initial count reaches to zero.

To make count zero other threads need to call the countDown() method. Once the count become zero the thread which invoked the await() method will resume (start its execution).

The disadvantage of CountDownLatch is that it's not reusable: once the count become zero it is no longer usable.

Center/Set Zoom of Map to cover all visible Markers?

You need to use the fitBounds() method.

var markers = [];//some array
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
 bounds.extend(markers[i]);
}

map.fitBounds(bounds);

Documentation from developers.google.com/maps/documentation/javascript:

fitBounds(bounds[, padding])

Parameters:

`bounds`:  [`LatLngBounds`][1]|[`LatLngBoundsLiteral`][1]
`padding` (optional):  number|[`Padding`][1]

Return Value: None

Sets the viewport to contain the given bounds.
Note: When the map is set to display: none, the fitBounds function reads the map's size as 0x0, and therefore does not do anything. To change the viewport while the map is hidden, set the map to visibility: hidden, thereby ensuring the map div has an actual size.

How to use shell commands in Makefile

Also, in addition to torek's answer: one thing that stands out is that you're using a lazily-evaluated macro assignment.

If you're on GNU Make, use the := assignment instead of =. This assignment causes the right hand side to be expanded immediately, and stored in the left hand variable.

FILES := $(shell ...)  # expand now; FILES is now the result of $(shell ...)

FILES = $(shell ...)   # expand later: FILES holds the syntax $(shell ...)

If you use the = assignment, it means that every single occurrence of $(FILES) will be expanding the $(shell ...) syntax and thus invoking the shell command. This will make your make job run slower, or even have some surprising consequences.

IndexError: tuple index out of range ----- Python

This is because your row variable/tuple does not contain any value for that index. You can try printing the whole list like print(row) and check how many indexes there exists.

How to jump to a particular line in a huge text file?

I am suprised no one mentioned islice

line = next(itertools.islice(Fhandle,index_of_interest,index_of_interest+1),None) # just the one line

or if you want the whole rest of the file

rest_of_file = itertools.islice(Fhandle,index_of_interest)
for line in rest_of_file:
    print line

or if you want every other line from the file

rest_of_file = itertools.islice(Fhandle,index_of_interest,None,2)
for odd_line in rest_of_file:
    print odd_line

Web API Put Request generates an Http 405 Method Not Allowed error

You can remove webdav module manually from GUI for the particular in IIS.
1) Goto the IIs.
2) Goto the respective site.
3) Open "Handler Mappings"
4) Scroll downn and select WebDav module. Right click on it and delete it.

Note: this will also update your web.config of the web app.

How do you properly use namespaces in C++?

I prefer using a top-level namespace for the application and sub namespaces for the components.

The way you can use classes from other namespaces is surprisingly very similar to the way in java. You can either use "use NAMESPACE" which is similar to an "import PACKAGE" statement, e.g. use std. Or you specify the package as prefix of the class separated with "::", e.g. std::string. This is similar to "java.lang.String" in Java.

How to get a barplot with several variables side by side grouped by a factor

Using reshape2 and dplyr. Your data:

df <- read.table(text=
"tea                coke            beer             water           gender
14.55              26.50793651     22.53968254      40              1
24.92997199        24.50980392     26.05042017      24.50980393     2
23.03732304        30.63063063     25.41827542      20.91377091     1   
225.51781276       24.6064623      24.85501243      50.80645161     1
24.53662842        26.03706973     25.24271845      24.18358341     2", header=TRUE)

Getting data into correct form:

library(reshape2)
library(dplyr)
df.melt <- melt(df, id="gender")
bar <- group_by(df.melt, variable, gender)%.%summarise(mean=mean(value))

Plotting:

library(ggplot2)
ggplot(bar, aes(x=variable, y=mean, fill=factor(gender)))+
  geom_bar(position="dodge", stat="identity")

enter image description here

Why do I get a "Null value was assigned to a property of primitive type setter of" error message when using HibernateCriteriaBuilder in Grails

@Column(name ="LEAD_ID")
private int leadId; 

Change to

@Column(name ="LEAD_ID")
private Integer leadId; 

Django TemplateDoesNotExist?

in your setting.py file replace DIRS in TEMPLATES array with this

'DIRS': []

to this

'DIRS': [os.path.join(BASE_DIR, 'templates')],

but 1 think u need to know is that you have to make a folder with name templates and it should on the root path otherwise u have to change the DIRS value

How to convert a string to JSON object in PHP

you can use this for example

$array = json_decode($string,true)

but validate the Json before. You can validate from http://jsonviewer.stack.hu/

PDO with INSERT INTO through prepared statements

I have just rewritten the code to the following:

    $dbhost = "localhost";
    $dbname = "pdo";
    $dbusername = "root";
    $dbpassword = "845625";

    $link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
    $link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $statement = $link->prepare("INSERT INTO testtable(name, lastname, age)
        VALUES(?,?,?)");

    $statement->execute(array("Bob","Desaunois",18));

And it seems to work now. BUT. if I on purpose cause an error to occur, it does not say there is any. The code works, but still; should I encounter more errors, I will not know why.

How to convert number to words in java

Below java program demonstrate how to convert a number from zero to one million.

NumberToStringLiteral class :

public class NumberToStringLiteral
{

    public static void main(String[] args)
    {
        NumberToStringLiteral numberToStringLiteral = new NumberToStringLiteral();
        int number = 123456;
        String stringLiteral = numberToStringLiteral.convertIntegerToStringLiteral(number);
        System.out.println(stringLiteral);
    }
    
    private String convertIntegerToStringLiteral(int number)
    {
        if (number < 100)
            return from_0_To_100(number);
        
        if ( number >= 100 && number < 1000 )
            return from_101_To_999(number);
        
        if ( number >= 1000 && number <= 99999)
            return from_1000_To_99999(number);
        
        if (number <= 1000000)
            return from_100000_and_above(number);
        
        return Digits.OVER_ONE_MILLION.getStringLiteral();
    }
    
    private String from_0_To_100(int number)
    {
        if (number <= 19 )
            return ZeroToNineteen.getStringLiteral(number);
        
        String LastDigit = ( ZeroToNineteen.getStringLiteral(number % 10) != ZeroToNineteen.ZERO.getStringLiteral() ) ? 
                            ZeroToNineteen.getStringLiteral(number % 10) : "";
        return Tens.getStringLiteralFromNumber( (number - (number % 10 )) ) + " " + LastDigit;
    }
    
    private String from_101_To_999(int number)
    {
        String LastDigit = ( ZeroToNineteen.getStringLiteral(number % 100) != ZeroToNineteen.ZERO.getStringLiteral() ) ?
                            ZeroToNineteen.getStringLiteral(number % 100)  : "";
        
        if ( (number % 100) > 19)
            LastDigit = from_0_To_100(number % 100);
            
        if (LastDigit.isBlank())
            return ZeroToNineteen.getStringLiteral(number / 100 ) + Digits.getStringLiteral(getNumberOfDigit(0));
            
        return ZeroToNineteen.getStringLiteral(number / 100 ) + Digits.getStringLiteral(getNumberOfDigit(number)) + LastDigit;
    }
        
    private String from_1000_To_99999(int number)
    {
        String LastDigit = (number % 1000 < 20 ) ? from_0_To_100(number % 1000) : from_101_To_999(number % 1000);
        
        if (LastDigit.equalsIgnoreCase(ZeroToNineteen.ZERO.getStringLiteral()))
            LastDigit = "";
        
        return from_0_To_100(number / 1000 ) + Digits.getStringLiteral(getNumberOfDigit(number)) + LastDigit;
    }
    
    private String from_100000_and_above(int number)
    {
        if (number == 1000000)
            return Digits.ONE_MILLION.getStringLiteral();
        
        String lastThreeDigit = (number % 1000 <= 100)  ? from_0_To_100(number % 1000) : from_101_To_999(number % 1000);
        
        if (lastThreeDigit.equalsIgnoreCase(ZeroToNineteen.ZERO.toString()))
            lastThreeDigit = "";
        
        String number1 = from_101_To_999(number / 1000) + Digits.THOUSAND.getStringLiteral() +  lastThreeDigit;
        return String.valueOf(number1);
    }
    
    private int getNumberOfDigit(int number)
    {
        int count = 0;
        while ( number != 0 )
        {
            number /=  10;
            count++;
        }
        return count;
    }
}

ZeroToNineteen enum :

public enum ZeroToNineteen
{
    ZERO(0, "zero"), 
    ONE(1, "one"),
    TWO(2, "two"),
    THREE(3, "three"),
    FOUR(4, "four"),
    FIVE(5, "five"),
    SIX(6, "six"),
    SEVEN(7, "seven"),
    EIGHT(8, "eight"),
    NINE(9, "nine"),
    TEN(10, "ten"),
    ELEVEN(11, "eleven"),
    TWELVE(12, "twelve"),
    THIRTEEN(13, "thirteen"),
    FOURTEEN(14, "fourteen"),
    FIFTEEN(15, "fifteen"),
    SIXTEEN(16, "sixteen"),
    SEVENTEEN(17, "seventeen"),
    EIGHTEEN(18, "eighteen"),
    NINETEEN(19, "nineteen");
    
    
    private int number;
    private String stringLiteral;
    public static Map<Integer, String> stringLiteralMap;
    
    ZeroToNineteen(int number, String stringLiteral)
    {
        this.number = number;
        this.stringLiteral = stringLiteral;
    }
    
    public int getNumber()
    {
        return this.number;
    }
    
    public String getStringLiteral()
    {
        return this.stringLiteral;
    }
    
    public static String getStringLiteral(int number)
    {
        if (stringLiteralMap == null)
            addData();
        
        return stringLiteralMap.get(number);
    }
    
    private static void addData()
    {
        stringLiteralMap = new HashMap<>();
        for (ZeroToNineteen zeroToNineteen : ZeroToNineteen.values())
        {
            stringLiteralMap.put(zeroToNineteen.getNumber(), zeroToNineteen.getStringLiteral());
        }
    }
}

Tens enum :

public enum Tens
{
    TEN(10, "ten"),
    TWENTY(20, "twenty"),
    THIRTY(30, "thirty"),
    FORTY(40, "forty"),
    FIFTY(50, "fifty"),
    SIXTY(60, "sixty"),
    SEVENTY(70, "seventy"),
    EIGHTY(80, "eighty"),
    NINETY(90, "ninety"),
    HUNDRED(100, "one hundred");
    
    
    private int number;
    private String stringLiteral;
    private static Map<Integer, String> stringLiteralMap;
    
    Tens(int number, String stringLiteral)
    {
        this.number = number;
        this.stringLiteral = stringLiteral;
    }
    
    public int getNumber()
    {
        return this.number;
    }
    
    public String getStringLiteral()
    {
        return this.stringLiteral;
    }
    
    public static String getStringLiteralFromNumber(int number)
    {
        if (stringLiteralMap == null)
            addDataToStringLiteralMap();
        
        return stringLiteralMap.get(number);
    }
    
    private static void addDataToStringLiteralMap()
    {
        stringLiteralMap = new HashMap<Integer, String>();
        for (Tens tens : Tens.values())
            stringLiteralMap.put(tens.getNumber(), tens.getStringLiteral());
    }
}

Digits enum :

public enum Digits
{
    HUNDRED(3, " hundred and "),
    THOUSAND(4, " thousand "),
    TEN_THOUSAND(5," thousand "),
    ONLY_HUNDRED(0, " hundred" ),
    ONE_MILLION(1000000, "one million"),
    OVER_ONE_MILLION(1000001, "over one million");
    
    private int digit;
    private String stringLiteral;
    private static Map<Integer, String> stringLiteralMap;
    
    private Digits(int digit, String stringLiteral)
    {
        this.digit = digit;
        this.stringLiteral = stringLiteral;
    }
    
    public int getDigit()
    {
        return this.digit;
    }
    
    public String getStringLiteral()
    {
        return this.stringLiteral;
    }
    
    public static String getStringLiteral(int number)
    {
        if ( stringLiteralMap == null )
            addStringLiteralMap();
        
        return stringLiteralMap.get(number);
    }
    
    private static void addStringLiteralMap()
    {
        stringLiteralMap = new HashMap<Integer, String>();
        for ( Digits digits : Digits.values() )
            stringLiteralMap.put(digits.getDigit(), digits.getStringLiteral());
    }
}

Output :

one hundred and twenty three thousand four hundred and fifty six

Note: I have used all three enum for constant variables, you can also use array.

Hope this will help you, Let me know if you have any doubt in comment section.

Tesseract OCR simple example

This worked for me, I had 3-4 more PDF to Text extractor and if one doesnot work the other one will ... tesseract in particular this code can be used on Windows 7, 8, Server 2008 . Hope this is helpful to you

    do
    {
    // Sleep or Pause the Thread for 1 sec, if service is running too fast...
    Thread.Sleep(millisecondsTimeout: 1000);
    Guid tempGuid = ToSeqGuid();
    string newFileName = tempGuid.ToString().Split('-')[0];
    string outputFileName = appPath + "\\pdf2png\\" + fileNameithoutExtension + "-" + newFileName +
                            ".png";
    extractor.SaveCurrentImageToFile(outputFileName, ImageFormat.Png);
    // Create text file here using Tesseract
    foreach (var file in Directory.GetFiles(appPath + "\\pdf2png"))
    {
        try
        {
            var pngFileName = Path.GetFileNameWithoutExtension(file);
            string[] myArguments =
            {
                "/C tesseract ", file,
                " " + appPath + "\\png2text\\" + pngFileName
            }; // /C for closing process automatically whent completes
            string strParam = String.Join(" ", myArguments);

            var myCmdProcess = new Process();
            var theProcess = new ProcessStartInfo("cmd.exe", strParam)
            {
                CreateNoWindow = true,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                WindowStyle = ProcessWindowStyle.Minimized
            }; // Keep the cmd.exe window minimized
            myCmdProcess.StartInfo = theProcess;
            myCmdProcess.Exited += myCmdProcess_Exited;
            myCmdProcess.Start();

            //if (process)
            {
                /*
                MessageBox.Show("cmd.exe process started: " + Environment.NewLine +
                                "Process Name: " + myCmdProcess.ProcessName +
                                Environment.NewLine + " Process Id: " + myCmdProcess.Id
                                + Environment.NewLine + "process.Handle: " +
                                myCmdProcess.Handle);
                */
                Process.EnterDebugMode();
                //ShowWindow(hWnd: process.Handle, nCmdShow: 2);
                /*
                MessageBox.Show("After EnterDebugMode() cmd.exe process Exited: " +
                                Environment.NewLine +
                                "Process Name: " + myCmdProcess.ProcessName +
                                Environment.NewLine + " Process Id: " + myCmdProcess.Id
                                + Environment.NewLine + "process.Handle: " +
                                myCmdProcess.Handle);
                */
                myCmdProcess.WaitForExit(60000);
                /*
                MessageBox.Show("After WaitForExit() cmd.exe process Exited: " +
                                Environment.NewLine +
                                "Process Name: " + myCmdProcess.ProcessName +
                                Environment.NewLine + " Process Id: " + myCmdProcess.Id
                                + Environment.NewLine + "process.Handle: " +
                                myCmdProcess.Handle);
                */
                myCmdProcess.Refresh();
                Process.LeaveDebugMode();
                //myCmdProcess.Dispose();
                /*
                MessageBox.Show("After LeaveDebugMode() cmd.exe process Exited: " +
                                Environment.NewLine);
                */
            }


            //process.Kill();
            // Waits for the process to complete task and exites automatically
            Thread.Sleep(millisecondsTimeout: 1000);

            // This works fine in Windows 7 Environment, and not in Windows 8
            // Try following code block
            // Check, if process is not comletey exited

            if (!myCmdProcess.HasExited)
            {
                //process.WaitForExit(2000); // Try to wait for exit 2 more seconds
                /*
                MessageBox.Show(" Process of cmd.exe was exited by WaitForExit(); Method " +
                                Environment.NewLine);
                */
                try
                {
                    // If not, then Kill the process
                    myCmdProcess.Kill();
                    //myCmdProcess.Dispose();
                    //if (!myCmdProcess.HasExited)
                    //{
                    //    myCmdProcess.Kill();
                    //}

                    MessageBox.Show(" Process of cmd.exe exited ( Killed ) successfully " +
                                    Environment.NewLine);
                }
                catch (System.ComponentModel.Win32Exception ex)
                {
                    MessageBox.Show(
                        " Exception: System.ComponentModel.Win32Exception " +
                        ex.ErrorCode + Environment.NewLine);
                }
                catch (NotSupportedException notSupporEx)
                {
                    MessageBox.Show(" Exception: NotSupportedException " +
                                    notSupporEx.Message +
                                    Environment.NewLine);
                }
                catch (InvalidOperationException invalidOperation)
                {
                    MessageBox.Show(
                        " Exception: InvalidOperationException " +
                        invalidOperation.Message + Environment.NewLine);
                    foreach (
                        var textFile in Directory.GetFiles(appPath + "\\png2text", "*.txt",
                            SearchOption.AllDirectories))
                    {
                        loggingInfo += textFile +
                                       " In Reading Text from generated text file by Tesseract " +
                                       Environment.NewLine;
                        strBldr.Append(File.ReadAllText(textFile));
                    }
                    // Delete text file after reading text here
                    Directory.GetFiles(appPath + "\\pdf2png").ToList().ForEach(File.Delete);
                    Directory.GetFiles(appPath + "\\png2text").ToList().ForEach(File.Delete);
                }
            }
        }
        catch (Exception exception)
        {
            MessageBox.Show(
                " Cought Exception in Generating image do{...}while{...} function " +
                Environment.NewLine + exception.Message + Environment.NewLine);
        }
    }
    // Delete png image here
    Directory.GetFiles(appPath + "\\pdf2png").ToList().ForEach(File.Delete);
    Thread.Sleep(millisecondsTimeout: 1000);
    // Read text from text file here
    foreach (var textFile in Directory.GetFiles(appPath + "\\png2text", "*.txt",
        SearchOption.AllDirectories))
    {
        loggingInfo += textFile +
                       " In Reading Text from generated text file by Tesseract " +
                       Environment.NewLine;
        strBldr.Append(File.ReadAllText(textFile));
    }
    // Delete text file after reading text here
    Directory.GetFiles(appPath + "\\png2text").ToList().ForEach(File.Delete);
} while (extractor.GetNextImage()); // Advance image enumeration... 

Is there a Java equivalent or methodology for the typedef keyword in C++?

Perhaps this could be another possible replace :

@Data
public class MyMap {
    @Delegate //lombok
    private HashMap<String, String> value;
}

Laravel Mail::send() sending to multiple to or bcc addresses

You can loop over recipientce like:

foreach (['[email protected]', '[email protected]'] as $recipient) {
    Mail::to($recipient)->send(new OrderShipped($order));
}

See documentation here

What is the difference between screenX/Y, clientX/Y and pageX/Y?

clientX/Y refers to relative screen coordinates, for instance if your web-page is long enough then clientX/Y gives clicked point's coordinates location in terms of its actual pixel position while ScreenX/Y gives the ordinates in reference to start of page.

error: This is probably not a problem with npm. There is likely additional logging output above

Following steps solves my problem: Add "C:\Windows\System32\" to your system path variables Run npm eject, Run npm start, Run npm eject, and agian run npm start And it worked

Getting JavaScript object key list

Anurags answer is basically correct. But to support Object.keys(obj) in older browsers as well you can use the code below that is copied from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys . It adds the Object.keys(obj) method if it's not available from the browser.

if (!Object.keys) {
 Object.keys = (function() {
 'use strict';
 var hasOwnProperty = Object.prototype.hasOwnProperty,
    hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
    dontEnums = [
      'toString',
      'toLocaleString',
      'valueOf',
      'hasOwnProperty',
      'isPrototypeOf',
      'propertyIsEnumerable',
      'constructor'
    ],
    dontEnumsLength = dontEnums.length;

return function(obj) {
  if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
    throw new TypeError('Object.keys called on non-object');
  }

  var result = [], prop, i;

  for (prop in obj) {
    if (hasOwnProperty.call(obj, prop)) {
      result.push(prop);
    }
  }

  if (hasDontEnumBug) {
    for (i = 0; i < dontEnumsLength; i++) {
      if (hasOwnProperty.call(obj, dontEnums[i])) {
        result.push(dontEnums[i]);
      }
    }
  }
  return result;
};
}());
}

How to loop through file names returned by find?

TL;DR: If you're just here for the most correct answer, you probably want my personal preference, find . -name '*.txt' -exec process {} \; (see the bottom of this post). If you have time, read through the rest to see several different ways and the problems with most of them.


The full answer:

The best way depends on what you want to do, but here are a few options. As long as no file or folder in the subtree has whitespace in its name, you can just loop over the files:

for i in $x; do # Not recommended, will break on whitespace
    process "$i"
done

Marginally better, cut out the temporary variable x:

for i in $(find -name \*.txt); do # Not recommended, will break on whitespace
    process "$i"
done

It is much better to glob when you can. White-space safe, for files in the current directory:

for i in *.txt; do # Whitespace-safe but not recursive.
    process "$i"
done

By enabling the globstar option, you can glob all matching files in this directory and all subdirectories:

# Make sure globstar is enabled
shopt -s globstar
for i in **/*.txt; do # Whitespace-safe and recursive
    process "$i"
done

In some cases, e.g. if the file names are already in a file, you may need to use read:

# IFS= makes sure it doesn't trim leading and trailing whitespace
# -r prevents interpretation of \ escapes.
while IFS= read -r line; do # Whitespace-safe EXCEPT newlines
    process "$line"
done < filename

read can be used safely in combination with find by setting the delimiter appropriately:

find . -name '*.txt' -print0 | 
    while IFS= read -r -d '' line; do 
        process "$line"
    done

For more complex searches, you will probably want to use find, either with its -exec option or with -print0 | xargs -0:

# execute `process` once for each file
find . -name \*.txt -exec process {} \;

# execute `process` once with all the files as arguments*:
find . -name \*.txt -exec process {} +

# using xargs*
find . -name \*.txt -print0 | xargs -0 process

# using xargs with arguments after each filename (implies one run per filename)
find . -name \*.txt -print0 | xargs -0 -I{} process {} argument

find can also cd into each file's directory before running a command by using -execdir instead of -exec, and can be made interactive (prompt before running the command for each file) using -ok instead of -exec (or -okdir instead of -execdir).

*: Technically, both find and xargs (by default) will run the command with as many arguments as they can fit on the command line, as many times as it takes to get through all the files. In practice, unless you have a very large number of files it won't matter, and if you exceed the length but need them all on the same command line, you're SOL find a different way.

No output to console from a WPF application?

I've create a solution, mixed the information of varius post.

Its a form, that contains a label and one textbox. The console output is redirected to the textbox.

There are too a class called ConsoleView that implements three publics methods: Show(), Close(), and Release(). The last one is for leave open the console and activate the Close button for view results.

The forms is called FrmConsole. Here are the XAML and the c# code.

The use is very simple:

ConsoleView.Show("Title of the Console");

For open the console. Use:

System.Console.WriteLine("The debug message");

For output text to the console.

Use:

ConsoleView.Close();

For Close the console.

ConsoleView.Release();

Leaves open the console and enables the Close button

XAML

<Window x:Class="CustomControls.FrmConsole"
    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:CustomControls"
    mc:Ignorable="d"
    Height="500" Width="600" WindowStyle="None" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" Topmost="True" Icon="Images/icoConsole.png">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="40"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="40"/>
    </Grid.RowDefinitions>
    <Label Grid.Row="0" Name="lblTitulo" HorizontalAlignment="Center" HorizontalContentAlignment="Center" VerticalAlignment="Center" VerticalContentAlignment="Center" FontFamily="Arial" FontSize="14" FontWeight="Bold" Content="Titulo"/>
    <Grid Grid.Row="1">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="10"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="10"/>
        </Grid.ColumnDefinitions>
        <TextBox Grid.Column="1" Name="txtInner" FontFamily="Arial" FontSize="10" ScrollViewer.CanContentScroll="True" VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Visible" TextWrapping="Wrap"/>
    </Grid>
    <Button Name="btnCerrar" Grid.Row="2" Content="Cerrar" Width="100" Height="30" HorizontalAlignment="Center" HorizontalContentAlignment="Center" VerticalAlignment="Center" VerticalContentAlignment="Center"/>
</Grid>

The code of the Window:

partial class FrmConsole : Window
{
    private class ControlWriter : TextWriter
    {
        private TextBox textbox;
        public ControlWriter(TextBox textbox)
        {
            this.textbox = textbox;
        }

        public override void WriteLine(char value)
        {
            textbox.Dispatcher.Invoke(new Action(() =>
            {
                textbox.AppendText(value.ToString());
                textbox.AppendText(Environment.NewLine);
                textbox.ScrollToEnd();
            }));
        }

        public override void WriteLine(string value)
        {
            textbox.Dispatcher.Invoke(new Action(() =>
            {
                textbox.AppendText(value);
                textbox.AppendText(Environment.NewLine);
                textbox.ScrollToEnd();
            }));
        }

        public override void Write(char value)
        {
            textbox.Dispatcher.Invoke(new Action(() =>
            {
                textbox.AppendText(value.ToString());
                textbox.ScrollToEnd();
            }));
        }

        public override void Write(string value)
        {
            textbox.Dispatcher.Invoke(new Action(() =>
            {
                textbox.AppendText(value);
                textbox.ScrollToEnd();
            }));
        }

        public override Encoding Encoding
        {
            get { return Encoding.UTF8; }

        }
    }

    //DEFINICIONES DE LA CLASE
    #region DEFINICIONES DE LA CLASE

    #endregion


    //CONSTRUCTORES DE LA CLASE
    #region CONSTRUCTORES DE LA CLASE

    public FrmConsole(string titulo)
    {
        InitializeComponent();
        lblTitulo.Content = titulo;
        Clear();
        btnCerrar.Click += new RoutedEventHandler(BtnCerrar_Click);
        Console.SetOut(new ControlWriter(txtInner));
        DesactivarCerrar();
    }

    #endregion


    //PROPIEDADES
    #region PROPIEDADES

    #endregion


    //DELEGADOS
    #region DELEGADOS

    private void BtnCerrar_Click(object sender, RoutedEventArgs e)
    {
        Close();
    }

    #endregion


    //METODOS Y FUNCIONES
    #region METODOS Y FUNCIONES

    public void ActivarCerrar()
    {
        btnCerrar.IsEnabled = true;
    }

    public void Clear()
    {
        txtInner.Clear();
    }

    public void DesactivarCerrar()
    {
        btnCerrar.IsEnabled = false;
    }

    #endregion  
}

the code of ConsoleView class

static public class ConsoleView
{
    //DEFINICIONES DE LA CLASE
    #region DEFINICIONES DE LA CLASE
    static FrmConsole console;
    static Thread StatusThread;
    static bool isActive = false;
    #endregion

    //CONSTRUCTORES DE LA CLASE
    #region CONSTRUCTORES DE LA CLASE

    #endregion

    //PROPIEDADES
    #region PROPIEDADES

    #endregion

    //DELEGADOS
    #region DELEGADOS

    #endregion

    //METODOS Y FUNCIONES
    #region METODOS Y FUNCIONES

    public static void Show(string label)
    {
        if (isActive)
        {
            return;
        }

        isActive = true;
        //create the thread with its ThreadStart method
        StatusThread = new Thread(() =>
        {
            try
            {
                console = new FrmConsole(label);
                console.ShowDialog();
                //this call is needed so the thread remains open until the dispatcher is closed
                Dispatcher.Run();
            }
            catch (Exception)
            {
            }
        });

        //run the thread in STA mode to make it work correctly
        StatusThread.SetApartmentState(ApartmentState.STA);
        StatusThread.Priority = ThreadPriority.Normal;
        StatusThread.Start();

    }

    public static void Close()
    {
        isActive = false;
        if (console != null)
        {
            //need to use the dispatcher to call the Close method, because the window is created in another thread, and this method is called by the main thread
            console.Dispatcher.InvokeShutdown();
            console = null;
            StatusThread = null;
        }

        console = null;
    }

    public static void Release()
    {
        isActive = false;
        if (console != null)
        {
            console.Dispatcher.Invoke(console.ActivarCerrar);
        }

    }
    #endregion
}

I hope this result usefull.

Disabling radio buttons with jQuery

I just built a sandbox environment with your code and it worked for me. Here is what I used:

<html>
  <head>
    <title>test</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
  </head>
  <body>
    <form id="chatTickets" method="post" action="/admin/index.cfm/">
      <input id="ticketID1" type="radio" checked="checked" value="myvalue1" name="ticketID"/>
      <input id="ticketID2" type="radio" checked="checked" value="myvalue2" name="ticketID"/>
    </form>
    <a href="#" title="Load ActiveChat" id="loadActive">Load Active</a>

    <script>
      jQuery("#loadActive").click(function() {
        //I have other code in here that runs before this function call
        writeData();
      });
      function writeData() {
        jQuery("input[name='ticketID']").each(function(i) {
            jQuery(this).attr('disabled', 'disabled');
        });
      }
    </script>
  </body>
</html>

I tested in FF3.5, moving to IE8 now. And it works fine in IE8 too. What browser are you using?

Python how to write to a binary file?

As of Python 3.2+, you can also accomplish this using the to_bytes native int method:

newFileBytes = [123, 3, 255, 0, 100]
# make file
newFile = open("filename.txt", "wb")
# write to file
for byte in newFileBytes:
    newFile.write(byte.to_bytes(1, byteorder='big'))

I.e., each single call to to_bytes in this case creates a string of length 1, with its characters arranged in big-endian order (which is trivial for length-1 strings), which represents the integer value byte. You can also shorten the last two lines into a single one:

newFile.write(''.join([byte.to_bytes(1, byteorder='big') for byte in newFileBytes]))

What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?

Curly braces. Passing keyword arguments into dict(), though it works beautifully in a lot of scenarios, can only initialize a map if the keys are valid Python identifiers.

This works:

a = {'import': 'trade', 1: 7.8}
a = dict({'import': 'trade', 1: 7.8})

This won't work:

a = dict(import='trade', 1=7.8)

It will result in the following error:

    a = dict(import='trade', 1=7.8)
             ^
SyntaxError: invalid syntax

How to access SVG elements with Javascript

Is it possible to do it this way, as opposed to using something like Raphael or jQuery SVG?

Definitely.

If it is possible, what's the technique?

This annotated code snippet works:

<!DOCTYPE html>
<html>
    <head>
        <title>SVG Illustrator Test</title> 
    </head>
    <body>

        <object data="alpha.svg" type="image/svg+xml"
         id="alphasvg" width="100%" height="100%"></object>

        <script>
            var a = document.getElementById("alphasvg");

            // It's important to add an load event listener to the object,
            // as it will load the svg doc asynchronously
            a.addEventListener("load",function(){

                // get the inner DOM of alpha.svg
                var svgDoc = a.contentDocument;
                // get the inner element by id
                var delta = svgDoc.getElementById("delta");
                // add behaviour
                delta.addEventListener("mousedown",function(){
                        alert('hello world!')
                }, false);
            }, false);
        </script>
    </body>
</html>

Note that a limitation of this technique is that it is restricted by the same-origin policy, so alpha.svg must be hosted on the same domain as the .html file, otherwise the inner DOM of the object will be inaccessible.

Important thing to run this HTML, you need host HTML file to web server like IIS, Tomcat

Reducing MongoDB database file size

There has been some considerable confusion over space reclamation in MongoDB, and some recommended practice are downright dangerous to do in certain deployment types. More details below:

TL;DR repairDatabase attempts to salvage data from a standalone MongoDB deployments that is trying to recover from a disk corruption. If it recovers space, it is purely a side effect. Recovering space should never be the primary consideration of running repairDatabase.

Recover space in a standalone node

WiredTiger: For a standalone node with WiredTiger, running compact will release space to the OS, with one caveat: The compact command on WiredTiger on MongoDB 3.0.x was affected by this bug: SERVER-21833 which was fixed in MongoDB 3.2.3. Prior to this version, compact on WiredTiger could silently fail.

MMAPv1: Due to the way MMAPv1 works, there is no safe and supported method to recover space using the MMAPv1 storage engine. compact in MMAPv1 will defragment the data files, potentially making more space available for new documents, but it will not release space back to the OS.

You may be able to run repairDatabase if you fully understand the consequences of this potentially dangerous command (see below), since repairDatabase essentially rewrites the whole database by discarding corrupt documents. As a side effect, this will create new MMAPv1 data files without any fragmentation on it and release space back to the OS.

For a less adventurous method, running mongodump and mongorestore may be possible as well in an MMAPv1 deployment, subject to the size of your deployment.

Recover space in a replica set

For replica set configurations, the best and the safest method to recover space is to perform an initial sync, for both WiredTiger and MMAPv1.

If you need to recover space from all nodes in the set, you can perform a rolling initial sync. That is, perform initial sync on each of the secondaries, before finally stepping down the primary and perform initial sync on it. Rolling initial sync method is the safest method to perform replica set maintenance, and it also involves no downtime as a bonus.

Please note that the feasibility of doing a rolling initial sync also depends on the size of your deployment. For extremely large deployments, it may not be feasible to do an initial sync, and thus your options are somewhat more limited. If WiredTiger is used, you may be able to take one secondary out of the set, start it as a standalone, run compact on it, and rejoin it to the set.

Regarding repairDatabase

Please don't run repairDatabase on replica set nodes. This is very dangerous, as mentioned in the repairDatabase page and described in more details below.

The name repairDatabase is a bit misleading, since the command doesn't attempt to repair anything. The command was intended to be used when there's disk corruption on a standalone node, which could lead to corrupt documents.

The repairDatabase command could be more accurately described as "salvage database". That is, it recreates the databases by discarding corrupt documents in an attempt to get the database into a state where you can start it and salvage intact document from it.

In MMAPv1 deployments, this rebuilding of the database files releases space to the OS as a side effect. Releasing space to the OS was never the purpose.

Consequences of repairDatabase on a replica set

In a replica set, MongoDB expects all nodes in the set to contain identical data. If you run repairDatabase on a replica set node, there is a chance that the node contains undetected corruption, and repairDatabase will dutifully remove the corrupt documents for you.

Predictably, this makes that node contains a different dataset from the rest of the set. If an update happens to hit that single document, the whole set could crash.

To make matters worse, it is entirely possible that this situation could stay dormant for a long time, only to strike suddenly with no apparent reason.

How do I check if a Sql server string is null or empty

To prevent the records with Empty or Null value in SQL result

we can simply add ..... WHERE Column_name != '' or 'null'

Create XML in Javascript

xml-writer(npm package) I think this is the good way to create and write xml file easy. Also it can be used on server side with nodejs.

var XMLWriter = require('xml-writer');
xw = new XMLWriter;
xw.startDocument();
xw.startElement('root');
xw.writeAttribute('foo', 'value');
xw.text('Some content');
xw.endDocument();
console.log(xw.toString());

What's is the difference between train, validation and test set, in neural networks?

Say you train a model on a training set and then measure its performance on a test set. You think that there is still room for improvement and you try tweaking the hyper-parameters ( If the model is a Neural Network - hyper-parameters are the number of layers, or nodes in the layers ). Now you get a slightly better performance. However, when the model is subjected to another data ( not in the testing and training set ) you may not get the same level of accuracy. This is because you introduced some bias while tweaking the hyper-parameters to get better accuracy on the testing set. You basically have adapted the model and hyper-parameters to produce the best model for that particular training set.

A common solution is to split the training set further to create a validation set. Now you have

  • training set
  • testing set
  • validation set

You proceed as before but this time you use the validation set to test the performance and tweak the hyper-parameters. More specifically, you train multiple models with various hyper-parameters on the reduced training set (i.e., the full training set minus the validation set), and you select the model that performs best on the validation set.

Once you've selected the best performing model on the validation set, you train the best model on the full training set (including the valida- tion set), and this gives you the final model.

Lastly, you evaluate this final model on the test set to get an estimate of the generalization error.

Regular expression to match a dot

"In the default mode, Dot (.) matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline." (python Doc)

So, if you want to evaluate dot literaly, I think you should put it in square brackets:

>>> p = re.compile(r'\b(\w+[.]\w+)')
>>> resp = p.search("blah blah blah [email protected] blah blah")
>>> resp.group()
'test.this'

How to send HTML-formatted email?

This works for me

msg.BodyFormat = MailFormat.Html;

and then you can use html in your body

msg.Body = "<em>It's great to use HTML in mail!!</em>"

How to format numbers?

Due to the bugs found by JasperV — good points! — I have rewritten my old code. I guess I only ever used this for positive values with two decimal places.

Depending on what you are trying to achieve, you may want rounding or not, so here are two versions split across that divide.

First up, with rounding.

I've introduced the toFixed() method as it better handles rounding to specific decimal places accurately and is well support. It does slow things down however.

This version still detaches the decimal, but using a different method than before. The w|0 part removes the decimal. For more information on that, this is a good answer. This then leaves the remaining integer, stores it in k and then subtracts it again from the original number, leaving the decimal by itself.

Also, if we're to take negative numbers into account, we need to while loop (skipping three digits) until we hit b. This has been calculated to be 1 when dealing with negative numbers to avoid putting something like -,100.00

The rest of the loop is the same as before.

function formatThousandsWithRounding(n, dp){
  var w = n.toFixed(dp), k = w|0, b = n < 0 ? 1 : 0,
      u = Math.abs(w-k), d = (''+u.toFixed(dp)).substr(2, dp),
      s = ''+k, i = s.length, r = '';
  while ( (i-=3) > b ) { r = ',' + s.substr(i, 3) + r; }
  return s.substr(0, i + 3) + r + (d ? '.'+d: '');
};

In the snippet below you can edit the numbers to test yourself.

_x000D_
_x000D_
function formatThousandsWithRounding(n, dp){_x000D_
  var w = n.toFixed(dp), k = w|0, b = n < 0 ? 1 : 0,_x000D_
      u = Math.abs(w-k), d = (''+u.toFixed(dp)).substr(2, dp),_x000D_
      s = ''+k, i = s.length, r = '';_x000D_
  while ( (i-=3) > b ) { r = ',' + s.substr(i, 3) + r; }_x000D_
  return s.substr(0, i + 3) + r + (d ? '.'+d: '');_x000D_
};_x000D_
_x000D_
var dp;_x000D_
var createInput = function(v){_x000D_
  var inp = jQuery('<input class="input" />').val(v);_x000D_
  var eql = jQuery('<span>&nbsp;=&nbsp;</span>');_x000D_
  var out = jQuery('<div class="output" />').css('display', 'inline-block');_x000D_
  var row = jQuery('<div class="row" />');_x000D_
  row.append(inp).append(eql).append(out);_x000D_
  inp.keyup(function(){_x000D_
    out.text(formatThousandsWithRounding(Number(inp.val()), Number(dp.val())));_x000D_
  });_x000D_
  inp.keyup();_x000D_
  jQuery('body').append(row);_x000D_
  return inp;_x000D_
};_x000D_
_x000D_
jQuery(function(){_x000D_
  var numbers = [_x000D_
    0, 99.999, -1000, -1000000, 1000000.42, -1000000.57, -1000000.999_x000D_
  ], inputs = $();_x000D_
  dp = jQuery('#dp');_x000D_
  for ( var i=0; i<numbers.length; i++ ) {_x000D_
    inputs = inputs.add(createInput(numbers[i]));_x000D_
  }_x000D_
  dp.on('input change', function(){_x000D_
    inputs.keyup();_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id="dp" type="range" min="0" max="5" step="1" value="2" title="number of decimal places?" />
_x000D_
_x000D_
_x000D_

Now the other version, without rounding.

This takes a different route and attempts to avoid mathematical calculation (as this can introduce rounding, or rounding errors). If you don't want rounding, then you are only dealing with things as a string i.e. 1000.999 converted to two decimal places will only ever be 1000.99 and not 1001.00.

This method avoids using .split() and RegExp() however, both of which are very slow in comparison. And whilst I learned something new from Michael's answer about toLocaleString, I also was surprised to learn that it is — by quite a way — the slowest method out of them all (at least in Firefox and Chrome; Mac OSX).

Using lastIndexOf() we find the possibly existent decimal point, and from there everything else is pretty much the same. Save for the padding with extra 0s where needed. This code is limited to 5 decimal places. Out of my test this was the faster method.

var formatThousandsNoRounding = function(n, dp){
  var e = '', s = e+n, l = s.length, b = n < 0 ? 1 : 0,
      i = s.lastIndexOf('.'), j = i == -1 ? l : i,
      r = e, d = s.substr(j+1, dp);
  while ( (j-=3) > b ) { r = ',' + s.substr(j, 3) + r; }
  return s.substr(0, j + 3) + r + 
    (dp ? '.' + d + ( d.length < dp ? 
        ('00000').substr(0, dp - d.length):e):e);
};

_x000D_
_x000D_
var formatThousandsNoRounding = function(n, dp){_x000D_
  var e = '', s = e+n, l = s.length, b = n < 0 ? 1 : 0,_x000D_
      i = s.lastIndexOf('.'), j = i == -1 ? l : i,_x000D_
      r = e, d = s.substr(j+1, dp);_x000D_
  while ( (j-=3) > b ) { r = ',' + s.substr(j, 3) + r; }_x000D_
  return s.substr(0, j + 3) + r + _x000D_
   (dp ? '.' + d + ( d.length < dp ? _x000D_
     ('00000').substr(0, dp - d.length):e):e);_x000D_
};_x000D_
_x000D_
var dp;_x000D_
var createInput = function(v){_x000D_
  var inp = jQuery('<input class="input" />').val(v);_x000D_
  var eql = jQuery('<span>&nbsp;=&nbsp;</span>');_x000D_
  var out = jQuery('<div class="output" />').css('display', 'inline-block');_x000D_
  var row = jQuery('<div class="row" />');_x000D_
  row.append(inp).append(eql).append(out);_x000D_
  inp.keyup(function(){_x000D_
    out.text(formatThousandsNoRounding(Number(inp.val()), Number(dp.val())));_x000D_
  });_x000D_
  inp.keyup();_x000D_
  jQuery('body').append(row);_x000D_
  return inp;_x000D_
};_x000D_
_x000D_
jQuery(function(){_x000D_
  var numbers = [_x000D_
    0, 99.999, -1000, -1000000, 1000000.42, -1000000.57, -1000000.999_x000D_
  ], inputs = $();_x000D_
  dp = jQuery('#dp');_x000D_
  for ( var i=0; i<numbers.length; i++ ) {_x000D_
    inputs = inputs.add(createInput(numbers[i]));_x000D_
  }_x000D_
  dp.on('input change', function(){_x000D_
    inputs.keyup();_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id="dp" type="range" min="0" max="5" step="1" value="2" title="number of decimal places?" />
_x000D_
_x000D_
_x000D_

I'll update with an in-page snippet demo shortly, but for now here is a fiddle:

https://jsfiddle.net/bv2ort0a/2/



Old Method

Why use RegExp for this? — don't use a hammer when a toothpick will do i.e. use string manipulation:

var formatThousands = function(n, dp){
  var s = ''+(Math.floor(n)), d = n % 1, i = s.length, r = '';
  while ( (i -= 3) > 0 ) { r = ',' + s.substr(i, 3) + r; }
  return s.substr(0, i + 3) + r + 
    (d ? '.' + Math.round(d * Math.pow(10, dp || 2)) : '');
};

walk through

formatThousands( 1000000.42 );

First strip off decimal:

s = '1000000', d = ~ 0.42

Work backwards from the end of the string:

',' + '000'
',' + '000' + ',000'

Finalise by adding the leftover prefix and the decimal suffix (with rounding to dp no. decimal points):

'1' + ',000,000' + '.42'

fiddlesticks

http://jsfiddle.net/XC3sS/

How to update nested state properties in React

Although you asked about a state of class-based React component, the same problem exists with useState hook. Even worse: useState hook does not accept partial updates. So this question became very relevant when useState hook was introduced.

I have decided to post the following answer to make sure the question covers more modern scenarios where the useState hook is used:

If you have got:

const [state, setState] = useState({ someProperty: { flag: true, otherNestedProp: 1 }, otherProp: 2 })

you can set the nested property by cloning the current and patching the required segments of the data, for example:

setState(current => { ...current, someProperty: { ...current.someProperty, flag: false } });

Or you can use Immer library to simplify the cloning and patching of the object.

Or you can use Hookstate library (disclaimer: I am an author) to simply the management of complex (local and global) state data entirely and improve the performance (read: not to worry about rendering optimization):

import { useStateLink } from '@hookstate/core' 
const state = useStateLink({ someProperty: { flag: true, otherNestedProp: 1 }, otherProp: 2 })

get the field to render:

state.nested.someProperty.nested.flag.get()
// or 
state.get().someProperty.flag

set the nested field:

state.nested.someProperty.nested.flag.set(false)

Here is the Hookstate example, where the state is deeply / recursively nested in tree-like data structure.

SQL Server Format Date DD.MM.YYYY HH:MM:SS

A quick way to do it in sql server 2012 is as follows:

SELECT FORMAT(GETDATE() , 'dd/MM/yyyy HH:mm:ss')

"Insert if not exists" statement in SQLite

If you have a table called memos that has two columns id and text you should be able to do like this:

INSERT INTO memos(id,text) 
SELECT 5, 'text to insert' 
WHERE NOT EXISTS(SELECT 1 FROM memos WHERE id = 5 AND text = 'text to insert');

If a record already contains a row where text is equal to 'text to insert' and id is equal to 5, then the insert operation will be ignored.

I don't know if this will work for your particular query, but perhaps it give you a hint on how to proceed.

I would advice that you instead design your table so that no duplicates are allowed as explained in @CLs answer below.

Is there a Boolean data type in Microsoft SQL Server like there is in MySQL?

Use the Bit datatype. It has values 1 and 0 when dealing with it in native T-SQL

Implementing Singleton with an Enum (in Java)

Since Singleton Pattern is about having a private constructor and calling some method to control the instantiations (like some getInstance), in Enums we already have an implicit private constructor.

I don't exactly know how the JVM or some container controls the instances of our Enums, but it seems it already use an implicit Singleton Pattern, the difference is we don't call a getInstance, we just call the Enum.

How to create a listbox in HTML without allowing multiple selection?

Remove the multiple="multiple" attribute and add SIZE=6 with the number of elements you want

you may want to check this site

http://www.htmlcodetutorial.com/forms/_SELECT.html

Why should we include ttf, eot, woff, svg,... in a font-face

Woff is a compressed (zipped) form of the TrueType - OpenType font. It is small and can be delivered over the network like a graphic file. Most importantly, this way the font is preserved completely including rendering rule tables that very few people care about because they use only Latin script.

Take a look at [dead URL removed]. The font you see is an experimental web delivered smartfont (woff) that has thousands of combined characters making complex shapes. The underlying text is simple Latin code of romanized Singhala. (Copy and paste to Notepad and see).

Only woff can do this because nobody has this font and yet it is seen anywhere (Mac, Win, Linux and even on smartphones by all browsers except by IE. IE does not have full support for Open Types).

PermissionError: [Errno 13] Permission denied

This error actually also comes when using keras.preprocessing.image so for example:

img = keras.preprocessing.image.load_img(folder_path, target_size=image_size)

will throw the permission error. Strangely enough though, the problem is solved if you first import the library: from keras.preprocessing import image and only then use it. Like so:

img = image.load_img(img_path, target_size=(180,180))

Rotate a div using javascript

I recently had to build something similar. You can check it out in the snippet below.

The version I had to build uses the same button to start and stop the spinner, but you can manipulate to code if you have a button to start the spin and a different button to stop the spin

Basically, my code looks like this...

Run Code Snippet

_x000D_
_x000D_
var rocket = document.querySelector('.rocket');_x000D_
var btn = document.querySelector('.toggle');_x000D_
var rotate = false;_x000D_
var runner;_x000D_
var degrees = 0;_x000D_
_x000D_
function start(){_x000D_
    runner = setInterval(function(){_x000D_
        degrees++;_x000D_
        rocket.style.webkitTransform = 'rotate(' + degrees + 'deg)';_x000D_
    },50)_x000D_
}_x000D_
_x000D_
function stop(){_x000D_
    clearInterval(runner);_x000D_
}_x000D_
_x000D_
btn.addEventListener('click', function(){_x000D_
    if (!rotate){_x000D_
        rotate = true;_x000D_
        start();_x000D_
    } else {_x000D_
        rotate = false;_x000D_
        stop();_x000D_
    }_x000D_
})
_x000D_
body {_x000D_
  background: #1e1e1e;_x000D_
}    _x000D_
_x000D_
.rocket {_x000D_
    width: 150px;_x000D_
    height: 150px;_x000D_
    margin: 1em;_x000D_
    border: 3px dashed teal;_x000D_
    border-radius: 50%;_x000D_
    background-color: rgba(128,128,128,0.5);_x000D_
    display: flex;_x000D_
    justify-content: center;_x000D_
    align-items: center;_x000D_
  }_x000D_
  _x000D_
  .rocket h1 {_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
    font-size: .8em;_x000D_
    color: skyblue;_x000D_
    letter-spacing: 1em;_x000D_
    text-shadow: 0 0 10px black;_x000D_
  }_x000D_
  _x000D_
  .toggle {_x000D_
    margin: 10px;_x000D_
    background: #000;_x000D_
    color: white;_x000D_
    font-size: 1em;_x000D_
    padding: .3em;_x000D_
    border: 2px solid red;_x000D_
    outline: none;_x000D_
    letter-spacing: 3px;_x000D_
  }
_x000D_
<div class="rocket"><h1>SPIN ME</h1></div>_x000D_
<button class="toggle">I/0</button>
_x000D_
_x000D_
_x000D_

How to show Snackbar when Activity starts?

Simple way to show some text:

Snackbar.make(view, "Sample Text", Snackbar.LENGTH_SHORT).show();

and to show text with button:

Snackbar.make(view, "Sample Text", Snackbar.LENGTH_SHORT).setAction("Ok", new View.OnClickListener() {
            @Override 
            public void onClick(View view) {

            } 
        }).show();

How to get the host name of the current machine as defined in the Ansible hosts file?

The necessary variable is inventory_hostname.

- name: Install this only for local dev machine
  pip: name=pyramid
  when: inventory_hostname == "local"

It is somewhat hidden in the documentation at the bottom of this section.

How do I create a foreign key in SQL Server?

This script is about creating tables with foreign key and I added referential integrity constraint sql-server.

create table exams
(  
    exam_id int primary key,
    exam_name varchar(50),
);

create table question_bank 
(
    question_id int primary key,
    question_exam_id int not null,
    question_text varchar(1024) not null,
    question_point_value decimal,
    constraint question_exam_id_fk
       foreign key references exams(exam_id)
               ON DELETE CASCADE
);

How to replace four spaces with a tab in Sublime Text 2?

create a keybinding for quickest way

{ "keys": ["super+alt+t"], "command": "unexpand_tabs", "args": { "set_translate_tabs": true } }

add this to Preferences > Key Bindings (user) when you press super+alt+t it will convert spaces to tabs

Regular Expressions: Is there an AND operator?

The order is always implied in the structure of the regular expression. To accomplish what you want, you'll have to match the input string multiple times against different expressions.

What you want to do is not possible with a single regexp.

What is the best way to get the minimum or maximum value from an Array of numbers?

There isn't any reliable way to get the minimum/maximum without testing every value. You don't want to try a sort or anything like that, walking through the array is O(n), which is better than any sort algorithm can do in the general case.

Chrome says "Resource interpreted as script but transferred with MIME type text/plain.", what gives?

Check your js files actually exist on the server. I had this problem and discovered the js files hadn't been uploaded to the server and the server was actually returning the html page instead - which was the default document configured on the server (eg default.html)

PHP array() to javascript array()

When we convert PHP array into JS array then we get all values in string. For example:

var ars= '<?php echo json_encode($abc); ?>';

The issue in above method is when we try to get the first element of ars[0] then it gives us bracket where as in we need first element as compare to bracket so the better way to this is

var packing_slip_orders = JSON.parse('<?php echo json_encode($packing_slip_orders); ?>');

You should use json_parse after json_encode to get the accurate array result.

Access host database from a docker container

There are several long standing discussions about how to do this in a consistent, well understood and portable way. No complete resolution but I'll link you to the discussions below.

In any event you many want to try using the --add-host option to docker run to add the ip address of the host into the container's /etc/host file. From there it's trivial to connect to the host on any required port:

Adding entries to a container hosts file

You can add other hosts into a container's /etc/hosts file by using one or more --add-host flags. This example adds a static address for a host named docker:

 $ docker run --add-host=docker:10.180.0.1 --rm -it debian
    $$ ping docker
    PING docker (10.180.0.1): 48 data bytes
    56 bytes from 10.180.0.1: icmp_seq=0 ttl=254 time=7.600 ms
    56 bytes from 10.180.0.1: icmp_seq=1 ttl=254 time=30.705 ms
    ^C--- docker ping statistics ---
    2 packets transmitted, 2 packets received, 0% packet loss
    round-trip min/avg/max/stddev = 7.600/19.152/30.705/11.553 ms

Note: Sometimes you need to connect to the Docker host, which means getting the IP address of the host. You can use the following shell commands to simplify this process:

 $ alias hostip="ip route show 0.0.0.0/0 | grep -Eo 'via \S+' | awk '{ print $2 }'"
 $ docker run  --add-host=docker:$(hostip) --rm -it debian

Documentation:

https://docs.docker.com/engine/reference/commandline/run/

Discussions on accessing host from container:

https://github.com/docker/docker/issues/1143

https://github.com/docker/docker/issues/10023

Need to make a clickable <div> button

Just use an <a> by itself, set it to display: block; and set width and height. Get rid of the <span> and <div>. This is the semantic way to do it. There is no need to wrap things in <divs> (or any element) for layout. That is what CSS is for.

Demo: http://jsfiddle.net/ThinkingStiff/89Enq/

HTML:

<a id="music" href="Music.html">Music I Like</a>

CSS:

#music {
    background-color: black;
    color: white;
    display: block;
    height: 40px;
    line-height: 40px;
    text-decoration: none;
    width: 100px;
    text-align: center;
}

Output:

enter image description here

How to replace case-insensitive literal substrings in Java

For non-Unicode characters:

String result = Pattern.compile("(?i)????????", 
Pattern.UNICODE_CASE).matcher(source).replaceAll("???");

How do I delete an item or object from an array using ng-click?

Pass the id that you want to remove from the array to the given function 

from the controller( Function can be in the same controller but prefer to keep it in a service)

    function removeInfo(id) {
    let item = bdays.filter(function(item) {
      return bdays.id=== id;
    })[0];
    let index = bdays.indexOf(item);
    data.device.splice(indexOfTabDetails, 1);
  }

Regex to replace everything except numbers and a decimal point

Check the link Regular Expression Demo

use the below reg exp

[a-z] + [^0-9\s.]+|.(?!\d)

laravel the requested url was not found on this server

In addition to all the answers if you still encounter some variation of the problem, edit the .env file and set APP_URL to your domain name as in:

 APP_URL=similar_to_my_avatar_link 

Timestamp conversion in Oracle for YYYY-MM-DD HH:MM:SS format

INSERT INTO AM_PROGRAM_TUNING_EVENT_TMP1 
VALUES(TO_DATE('2012-03-28 11:10:00','yyyy/mm/dd hh24:mi:ss'));

http://www.sqlfiddle.com/#!4/22115/1

How does java do modulus calculations with negative numbers?

Since "mathematically" both are correct:

-13 % 64 = -13 (on modulus 64)  
-13 % 64 = 51 (on modulus 64)

One of the options had to be chosen by Java language developers and they chose:

the sign of the result equals the sign of the dividend.

Says it in Java specs:

https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3

What does the 'standalone' directive mean in XML?

standalone describes if the current XML document depends on an external markup declaration.

W3C describes its purpose in "Extensible Markup Language (XML) 1.0 (Fifth Edition)":

Traversing text in Insert mode

Many people in the Vim community argue that you should not navigate in Insert mode, that it is not the Vim way. I think this is an incorrect sentiment learned when transitioning from standard editors to Vim.

Vim is most powerful when you use its tools to create atomic, repeatable actions or finds.

It is ok to navigate while in Insert mode if you are fixing a mistake you made in the same Insert session. You should not navigate outside of the range of text you modified.

If you make a mistake while entering text and escape out of Insert mode to fix it you will not be able to repeat the intended action, . will repeat the correction.

Vim does support many Insert mode navigation keys. Obviously there are the arrow keys, Home, and End, but there are also many other shortcuts. See :h ins-special-keys.

How to know if two arrays have the same values

Simple solution for shallow equality using ES6:

const arr1test = arr1.slice().sort()
const arr2test = arr2.slice().sort()
const equal = !arr1test.some((val, idx) => val !== arr2test[idx])

Creates shallow copies of each array and sorts them. Then uses some() to loop through arr1test values, checking each value against the value in arr2test with the same index. If all values are equal, some() returns false, and in turn equal evaluates to true.

Could also use every(), but it would have to cycle through every element in the array to satisfy a true result, whereas some() will bail as soon as it finds a value that is not equal:

const equal = arr1test.every((val, idx) => val === arr2test[idx])

How to iterate over rows in a DataFrame in Pandas

Some libraries (e.g. a Java interop library that I use) require values to be passed in a row at a time, for example, if streaming data. To replicate the streaming nature, I 'stream' my dataframe values one by one, I wrote the below, which comes in handy from time to time.

class DataFrameReader:
  def __init__(self, df):
    self._df = df
    self._row = None
    self._columns = df.columns.tolist()
    self.reset()
    self.row_index = 0

  def __getattr__(self, key):
    return self.__getitem__(key)

  def read(self) -> bool:
    self._row = next(self._iterator, None)
    self.row_index += 1
    return self._row is not None

  def columns(self):
    return self._columns

  def reset(self) -> None:
    self._iterator = self._df.itertuples()

  def get_index(self):
    return self._row[0]

  def index(self):
    return self._row[0]

  def to_dict(self, columns: List[str] = None):
    return self.row(columns=columns)

  def tolist(self, cols) -> List[object]:
    return [self.__getitem__(c) for c in cols]

  def row(self, columns: List[str] = None) -> Dict[str, object]:
    cols = set(self._columns if columns is None else columns)
    return {c : self.__getitem__(c) for c in self._columns if c in cols}

  def __getitem__(self, key) -> object:
    # the df index of the row is at index 0
    try:
        if type(key) is list:
            ix = [self._columns.index(key) + 1 for k in key]
        else:
            ix = self._columns.index(key) + 1
        return self._row[ix]
    except BaseException as e:
        return None

  def __next__(self) -> 'DataFrameReader':
    if self.read():
        return self
    else:
        raise StopIteration

  def __iter__(self) -> 'DataFrameReader':
    return self

Which can be used:

for row in DataFrameReader(df):
  print(row.my_column_name)
  print(row.to_dict())
  print(row['my_column_name'])
  print(row.tolist())

And preserves the values/ name mapping for the rows being iterated. Obviously, is a lot slower than using apply and Cython as indicated above, but is necessary in some circumstances.

How do you stretch an image to fill a <div> while keeping the image's aspect-ratio?

if you working with IMG tag, it's easy.

I made this:

<style>
        #pic{
            height: 400px;
            width: 400px;
        }
        #pic img{
            height: 225px;               
            position: relative;
            margin: 0 auto;
        }
</style>

<div id="pic"><img src="images/menu.png"></div>

$(document).ready(function(){
            $('#pic img').attr({ 'style':'height:25%; display:none; left:100px; top:100px;' })
)}

but i didn't find how to make it work with #pic { background:url(img/menu.png)} Enyone? Thanks

How to capitalize the first letter of a String in Java?

This is just to show you, that you were not that wrong.

BufferedReader br = new InputstreamReader(System.in);
// Assuming name is not blank
String name = br.readLine(); 

//No more error telling that you cant convert char to string
String s1 = (""+name.charAt(0)).toUppercase());
// Or, as Carlos prefers. See the comments to this post.
String s1 = Character.toString(name.charAt(0)).toUppercase());

System.out.println(s1+name.substring(1));

Note: This is not at all the best way to do it. This is just to show the OP that it can be done using charAt() as well. ;)

AngularJS open modal on button click

Hope this will help you .

Here is Html code:-

    <body>
    <div ng-controller="MyController" class="container">
      <h1>Modal example</h1>
      <button ng-click="open()" class="btn btn-primary">Test Modal</button>

      <modal title="Login form" visible="showModal">
        <form role="form">

        </form>
      </modal>
    </div>
</body>

AngularJs code:-

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

mymodal.controller('MyController', function ($scope) {
    $scope.showModal = false;
    $scope.open = function(){
    $scope.showModal = !$scope.showModal;
    };
  });

mymodal.directive('modal', function () {
    return {
      template: '<div class="modal fade">' + 
          '<div class="modal-dialog">' + 
            '<div class="modal-content">' + 
              '<div class="modal-header">' + 
                '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' + 
                '<h4 class="modal-title">{{ title }}</h4>' + 
              '</div>' + 
              '<div class="modal-body" ng-transclude></div>' + 
            '</div>' + 
          '</div>' + 
        '</div>',
      restrict: 'E',
      transclude: true,
      replace:true,
      scope:true,
      link: function postLink(scope, element, attrs) {
        scope.title = attrs.title;

        scope.$watch(attrs.visible, function(value){
          if(value == true)
            $(element).modal('show');
          else
            $(element).modal('hide');
        });

        $(element).on('shown.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = true;
          });
        });

        $(element).on('hidden.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = false;
          });
        });
      }
    };
  });

Check this--jsfiddle

Find the host name and port using PSQL commands

From the terminal you can simply do a "postgres list clusters":

pg_lsclusters

It will return Postgres version number, cluster names, ports, status, owner, and the location of your data directories and log file.

Setting Environment Variables for Node to retrieve

You can set the environment variable through process global variable as follows:

process.env['NODE_ENV'] = 'production';

Works in all platforms.

HTML image not showing in Gmail

I am even later to this party, but after spending about 2 hours trying everything imaginable and not having any luck, I finally realized it will work if I upload the pics to GOOGLE PHOTOS instead of GOOGLE DRIVE. Then I can right-click on the pic, copy the address, paste it in, and it works beautifully.

How to programmatically set the ForeColor of a label to its default?

labelname.ForeColor = Color.Colorname;   ­­­­

Oracle's default date format is YYYY-MM-DD, WHY?

It's never wise to rely on defaults being set to a particular value, IMHO, whether it's for date formats, currency formats, optimiser modes or whatever. You should always set the value of date format that you need, in the server, the client, or the application.

In particular, never rely on defaults when converting date or numeric data types for display purposes, because a single change to the database can break your application. Always use an explicit conversion format. For years I worked on Oracle systems where the out of the box default date display format was MM/DD/RR, which drove me nuts but at least forced me to always use an explicit conversion.

Run a .bat file using python code

If you are trying to call another exe file inside the bat-file. You must use SET Path inside the bat-file that you are calling. set Path should point into the directory there the exe-file is located:

set PATH=C:\;C:\DOS     {Sets C:\;C:\DOS as the current search path.} 

Input widths on Bootstrap 3

I know this is an old thread, but I experienced the same issue with an inline form, and none of the options above solved the issue. So I fixed my inline form like so:-

<form class="form-inline" action="" method="post" accept-charset="UTF-8">
    <div class="row">
        <div class="form-group col-xs-7" style="padding-right: 0;">
            <label class="sr-only" for="term">Search</label>
            <input type="text" class="form-control" style="width: 100% !important;" name="term" id="term" placeholder="Search..." autocomplete="off">
            <span class="help-block">0 results</span>
        </div>
        <div class="form-group col-xs-2">
            <button type="submit" name="search" class="btn btn-success" id="search">Search</button>
        </div>
    </div>
</form>

That was my solution. Bit hacky hack, but did the job for an inline form.

Setting action for back button in navigation controller

Overriding navigationBar(_ navigationBar:shouldPop): This is not a good idea, even if it works. for me it generated random crashes on navigating back. I advise you to just override the back button by removing the default backButton from navigationItem and creating a custom back button like below:

override func viewDidLoad(){
   super.viewDidLoad()
   
   navigationItem.leftBarButton = .init(title: "Go Back", ... , action: #selector(myCutsomBackAction) 

   ...
 
}

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

Building on previous responses with UIAlert in Swift5 in a Asynchronous way


protocol NavigationControllerBackButtonDelegate {
    func shouldPopOnBackButtonPress(_ completion: @escaping (Bool) -> ())
}

extension UINavigationController: UINavigationBarDelegate {
    public func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
      
        if viewControllers.count < navigationBar.items!.count {
            return true
        }
        
        // Check if we have a view controller that wants to respond to being popped
        
        if let viewController = topViewController as? NavigationControllerBackButtonDelegate {
            
            viewController.shouldPopOnBackButtonPress { shouldPop in
                if (shouldPop) {
                    /// on confirm => pop
                    DispatchQueue.main.async {
                        self.popViewController(animated: true)
                    }
                } else {
                    /// on cancel => do nothing
                }
            }
            /// return false => so navigator will cancel the popBack
            /// until user confirm or cancel
            return false
        }else{
            DispatchQueue.main.async {
                self.popViewController(animated: true)
            }
        }
        return true
    }
}


On your controller


extension MyController: NavigationControllerBackButtonDelegate {
    
    func shouldPopOnBackButtonPress(_ completion: @escaping (Bool) -> ()) {
    
        let msg = "message"
        
        /// show UIAlert
        alertAttention(msg: msg, actions: [
            
            .init(title: "Continuer", style: .destructive, handler: { _ in
                completion(true)
            }),
            .init(title: "Annuler", style: .cancel, handler: { _ in
                completion(false)
            })
            ])
   
    }

}

YouTube iframe embed - full screen

React.JS People, remember allowFullScreen and frameBorder="0"

Without camel-case, react strips these tags out!

Redirect from asp.net web api post action

You can check this

[Route("Report/MyReport")]
public IHttpActionResult GetReport()
{

   string url = "https://localhost:44305/Templates/ReportPage.html";

   System.Uri uri = new System.Uri(url);

   return Redirect(uri);
}

How do I set up CLion to compile and run?

I ran into the same issue with CLion 1.2.1 (at the time of writing this answer) after updating Windows 10. It was working fine before I had updated my OS. My OS is installed in C:\ drive and CLion 1.2.1 and Cygwin (64-bit) are installed in D:\ drive.

The issue seems to be with CMake. I am using Cygwin. Below is the short answer with steps I used to fix the issue.

SHORT ANSWER (should be similar for MinGW too but I haven't tried it):

  1. Install Cygwin with GCC, G++, GDB and CMake (the required versions)
  2. Add full path to Cygwin 'bin' directory to Windows Environment variables
  3. Restart CLion and check 'Settings' -> 'Build, Execution, Deployment' to make sure CLion has picked up the right versions of Cygwin, make and gdb
  4. Check the project configuration ('Run' -> 'Edit configuration') to make sure your project name appears there and you can select options in 'Target', 'Configuration' and 'Executable' fields.
  5. Build and then Run
  6. Enjoy

LONG ANSWER:

Below are the detailed steps that solved this issue for me:

  1. Uninstall/delete the previous version of Cygwin (MinGW in your case)

  2. Make sure that CLion is up-to-date

  3. Run Cygwin setup (x64 for my 64-bit OS)

  4. Install at least the following packages for Cygwin: gcc g++ make Cmake gdb Make sure you are installing the correct versions of the above packages that CLion requires. You can find the required version numbers at CLion's Quick Start section (I cannot post more than 2 links until I have more reputation points).

  5. Next, you need to add Cygwin (or MinGW) to your Windows Environment Variable called 'Path'. You can Google how to find environment variables for your version of Windows

[On Win 10, right-click on 'This PC' and select Properties -> Advanced system settings -> Environment variables... -> under 'System Variables' -> find 'Path' -> click 'Edit']

  1. Add the 'bin' folder to the Path variable. For Cygwin, I added: D:\cygwin64\bin

  2. Start CLion and go to 'Settings' either from the 'Welcome Screen' or from File -> Settings

  3. Select 'Build, Execution, Deployment' and then click on 'Toolchains'

  4. Your 'Environment' should show the correct path to your Cygwin installation directory (or MinGW)

  5. For 'CMake executable', select 'Use bundled CMake x.x.x' (3.3.2 in my case at the time of writing this answer)

  6. 'Debugger' shown to me says 'Cygwin GDB GNU gdb (GDB) 7.8' [too many gdb's in that line ;-)]

  7. Below that it should show a checkmark for all the categories and should also show the correct path to 'make', 'C compiler' and 'C++ compiler'

See screenshot: Check all paths to the compiler, make and gdb

  1. Now go to 'Run' -> 'Edit configuration'. You should see your project name in the left-side panel and the configurations on the right side

See screenshot: Check the configuration to run the project

  1. There should be no errors in the console window. You will see that the 'Run' -> 'Build' option is now active

  2. Build your project and then run the project. You should see the output in the terminal window

Hope this helps! Good luck and enjoy CLion.

ArrayList of String Arrays

try this

ArrayList<ArrayList<String>> PriceModelList = new ArrayList<>();
    ArrayList<ArrayList<String>> PriceQtyList = new ArrayList<>();
    ArrayList<ArrayList<String>> PriceTotalList = new ArrayList<>();

    for (int i = 0; i < CustomerNames.length; i++) {
        PriceModelList.add(new ArrayList<String>());
        String[] PriceModel = {"s6", "s7", "note4", "note5", "j5", "j6"};
        for (int j = 0; j < PriceModel.length; j++) {
            PriceModelList.get(i).add(PriceModel[j]);
        }

        PriceQtyList.add(new ArrayList<String>());
        String[] PriceQut = {"12", "13", "21", "15", "43", "21"};
        for (int k = 0; k < PriceQut.length; k++) {
            PriceQtyList.get(i).add(PriceQut[k]);
        }

        PriceTotalList.add(new ArrayList<String>());
        String[] PriceTotal = {"1323", "1312321", "43123212", "43434", "12312", "43322"};
        for (int m = 0; m < PriceTotal.length; m++) {
            PriceTotalList.get(i).add(PriceTotal[m]);
        }
    }

    ArrayList<ArrayList<ArrayList<String>>> CustomersShoppingLists = new ArrayList<>();
    CustomersShoppingLists.add(PriceModelList);
    CustomersShoppingLists.add(PriceQtyList);
    CustomersShoppingLists.add(PriceTotalList);

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/JDBC_DBO]]

Check your application is building successfully by running mvn clean install over your project and correct all the errors

Usually this error comes when you have dependencies which are not present on your classpath.

If you are using tomcat maven plugin then try deploying your war using following command

tomcat7:run-war-only

Formatting Phone Numbers in PHP

United Kingdom Phone Formats

For the application I developed, I found that people entered their phone number 'correctly' from a human readable form, but inserted varous random characters such as '-' '/' '+44' etc. The problem was that the cloud app that it needed to talk to was quite specific about the format. Rather than use a regular expression (can be frustrating for the user) I created an object class which processes the entered number into the correct format before being processed by the persistence module.

The format of the output ensures that any receiving software interprets the output as text rather than an integer (which would then immediately lose the leading zero) and the format is consistent with British Telecoms guidelines on number formatting - which also aids human memorability by dividing a long number into small, easily memorised, groups.


+441234567890 produces (01234) 567 890
02012345678 produces (020) 1234 5678
1923123456 produces (01923) 123 456
01923123456 produces (01923) 123 456
01923hello this is text123456 produces (01923) 123 456

The significance of the exchange segment of the number - in parentheses - is that in the UK, and most other countries, calls between numbers in the same exchange can be made omitting the exchange segment. This does not apply to 07, 08 and 09 series phone numbers however.

I'm sure that there are more efficient solutions, but this one has proved extremely reliable. More formats can easily be accomodated by adding to the teleNum function at the end.

The procedure is invoked from the calling script thus

$telephone = New Telephone;
$formattedPhoneNumber = $telephone->toIntegerForm($num)

`

<?php
class   Telephone 
{   
    public function toIntegerForm($num) {
        /*
         * This section takes the number, whatever its format, and purifies it to just digits without any space or other characters
         * This ensures that the formatter only has one type of input to deal with
         */
        $number = str_replace('+44', '0', $num);
        $length = strlen($number);
        $digits = '';
        $i=0;
        while ($i<$length){
            $digits .= $this->first( substr($number,$i,1) , $i);
            $i++;
        }
        if (strlen($number)<10) {return '';}
        return $this->toTextForm($digits);
    }
    public function toTextForm($number) {

        /*
         * This works on the purified number to then format it according to the group code
         * Numbers starting 01 and 07 are grouped 5 3 3
         * Other numbers are grouped 3 4 4 
         * 
         */
        if (substr($number,0,1) == '+') { return $number; }
        $group = substr($number,0,2);
        switch ($group){
            case "02" :
                $formattedNumber = $this->teleNum($number, 3, 4); // If number commences '02N' then output will be (02N) NNNN NNNN
                break;
            default :
                $formattedNumber = $this->teleNum($number, 5, 3); // Otherwise the ooutput will be (0NNNN) NNN NNN
        }
        return $formattedNumber;

    }
    private function first($digit,$position){
        if ($digit == '+' && $position == 0) {return $digit;};
        if (!is_numeric($digit)){
            return '';
        }
        if ($position == 0) {
            return ($digit == '0' ) ? $digit :  '0'.$digit;
        } else {
            return $digit;
        } 
    }
    private function teleNum($number,$a,$b){
        /*
         * Formats the required output 
         */
        $c=strlen($number)-($a+$b);
        $bit1 = substr($number,0,$a);
        $bit2 = substr($number,$a,$b);
        $bit3 = substr($number,$a+$b,$c);
        return '('.$bit1.') '.$bit2." ".$bit3;
    }
}

I ran into a merge conflict. How can I abort the merge?

If your git version is >= 1.6.1, you can use git reset --merge.

Also, as @Michael Johnson mentions, if your git version is >= 1.7.4, you can also use git merge --abort.

As always, make sure you have no uncommitted changes before you start a merge.

From the git merge man page

git merge --abort is equivalent to git reset --merge when MERGE_HEAD is present.

MERGE_HEAD is present when a merge is in progress.

Also, regarding uncommitted changes when starting a merge:

If you have changes you don't want to commit before starting a merge, just git stash them before the merge and git stash pop after finishing the merge or aborting it.

How to check if array element exists or not in javascript?

(typeof files[1] === undefined)?
            this.props.upload({file: files}):
            this.props.postMultipleUpload({file: files widgetIndex: 0, id})

Check if the second item in the array is undefined using the typeof and checking for undefined

Transfer data between iOS and Android via Bluetooth?

Maybe a bit delayed, but technologies have evolved since so there is certainly new info around which draws fresh light on the matter...

As iOS has yet to open up an API for WiFi Direct and Multipeer Connectivity is iOS only, I believe the best way to approach this is to use BLE, which is supported by both platforms (some better than others).

On iOS a device can act both as a BLE Central and BLE Peripheral at the same time, on Android the situation is more complex as not all devices support the BLE Peripheral state. Also the Android BLE stack is very unstable (to date).

If your use case is feature driven, I would suggest to look at Frameworks and Libraries that can achieve cross platform communication for you, without you needing to build it up from scratch.

For example: http://p2pkit.io or google nearby

Disclaimer: I work for Uepaa, developing p2pkit.io for Android and iOS.

Quick way to list all files in Amazon S3 bucket?

In PHP you can get complete list of AWS-S3 objects inside specific bucket using following call

$S3 = \Aws\S3\S3Client::factory(array('region' => $region,));
$iterator = $S3->getIterator('ListObjects', array('Bucket' => $bucket));
foreach ($iterator as $obj) {
    echo $obj['Key'];
}

You can redirect output of the above code in to a file to get list of keys.

HTML.ActionLink method

I think that Joseph flipped controller and action. First comes the action then the controller. This is somewhat strange, but the way the signature looks.

Just to clarify things, this is the version that works (adaption of Joseph's example):

Html.ActionLink(article.Title, 
    "Login",  // <-- ActionMethod
    "Item",   // <-- Controller Name
    new { id = article.ArticleID }, // <-- Route arguments.
    null  // <-- htmlArguments .. which are none
    )

Close virtual keyboard on button press

If you set android:singleLine="true", automatically the button hides the keyboard¡

Google API for location, based on user IP address

Here's a script that will use the Google API to acquire the users postal code and populate an input field.

function postalCodeLookup(input) {
    var head= document.getElementsByTagName('head')[0],
        script= document.createElement('script');
    script.src= '//maps.googleapis.com/maps/api/js?sensor=false';
    head.appendChild(script);
    script.onload = function() {
        if (navigator.geolocation) {
            var a = input,
                fallback = setTimeout(function () {
                    fail('10 seconds expired');
                }, 10000);

            navigator.geolocation.getCurrentPosition(function (pos) {
                clearTimeout(fallback);
                var point = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
                new google.maps.Geocoder().geocode({'latLng': point}, function (res, status) {
                    if (status == google.maps.GeocoderStatus.OK && typeof res[0] !== 'undefined') {
                        var zip = res[0].formatted_address.match(/,\s\w{2}\s(\d{5})/);
                        if (zip) {
                            a.value = zip[1];
                        } else fail('Unable to look-up postal code');
                    } else {
                        fail('Unable to look-up geolocation');
                    }
                });
            }, function (err) {
                fail(err.message);
            });
        } else {
            alert('Unable to find your location.');
        }
        function fail(err) {
            console.log('err', err);
            a.value('Try Again.');
        }
    };
}

You can adjust accordingly to acquire different information. For more info, check out the Google Maps API documentation.

How do I do a case-insensitive string comparison?

The usual approach is to uppercase the strings or lower case them for the lookups and comparisons. For example:

>>> "hello".upper() == "HELLO".upper()
True
>>> 

Pandas: Return Hour from Datetime Column Directly

For posterity: as of 0.15.0, there is a handy .dt accessor you can use to pull such values from a datetime/period series (in the above case, just sales.timestamp.dt.hour!

How to access Spring MVC model object in javascript file?

You can't access java objects from JavaScript because there are no objects on client side. It only receives plain HTML page (hidden fields can help but it's not very good approach).

I suggest you to use ajax and @ResponseBody.

Sequelize.js delete query?

Delete all, no conditions:

Model.destroy({
    truncate: true,
})

How to add header data in XMLHttpRequest when using formdata?

Check to see if the key-value pair is actually showing up in the request:

In Chrome, found somewhere like: F12: Developer Tools > Network Tab > Whatever request you have sent > "view source" under Response Headers

Depending on your testing workflow, if whatever pair you added isn't there, you may just need to clear your browser cache. To verify that your browser is using your most up-to-date code, you can check the page's sources, in Chrome this is found somewhere like: F12: Developer Tools > Sources Tab > YourJavascriptSrc.js and check your code.

But as other answers have said:

xhttp.setRequestHeader(key, value);

should add a key-value pair to your request header, just make sure to place it after your open() and before your send()

How to cherry-pick from a remote branch?

Need to pull both branch data on your local drive first.

What is happening is your trying to cherry-pick from branch-a to branch-b, where in you are currently on branch-b, but the local copy of branch-a is not updated yet (you need to perform a git pull on both branches first).

steps:
- git checkout branch-a
- git pull origin branch-a
- git checkout branch-b
- git pull origin branch-b
- git cherry-pick <hash>

output:
[branch-b <hash>] log data
Author: Author <Author
1 file changed, 1 insertion(+), 3 deletions(-)

How do I use a regular expression to match any string, but at least 3 characters?

Try this .{3,} this will match any characher except new line (\n)

How to use Global Variables in C#?

First examine if you really need a global variable instead using it blatantly without consideration to your software architecture.

Let's assuming it passes the test. Depending on usage, Globals can be hard to debug with race conditions and many other "bad things", it's best to approach them from an angle where you're prepared to handle such bad things. So,

  1. Wrap all such Global variables into a single static class (for manageability).
  2. Have Properties instead of fields(='variables'). This way you have some mechanisms to address any issues with concurrent writes to Globals in the future.

The basic outline for such a class would be:

public class Globals
{
    private static bool _expired;
    public static bool Expired 
    {
        get
        {
            // Reads are usually simple
            return _expired;
        }
        set
        {
            // You can add logic here for race conditions,
            // or other measurements
            _expired = value;
        }
    }
    // Perhaps extend this to have Read-Modify-Write static methods
    // for data integrity during concurrency? Situational.
}

Usage from other classes (within same namespace)

// Read
bool areWeAlive = Globals.Expired;

// Write
// past deadline
Globals.Expired = true;

Why doesn't CSS ellipsis work in table cell?

As said before, you can use td { display: block; } but this defeats the purpose of using a table.

You can use table { table-layout: fixed; } but maybe you want it to behave differently for some colums.

So the best way to achieve what you want would be to wrap your text in a <div> and apply your CSS to the <div> (not to the <td>) like this :

td {
  border: 1px solid black;
}
td > div {
  width: 50px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

Links not going back a directory?

You need to give a relative file path of <a href="../index.html">Home</a>

Alternately you can specify a link from the root of your site with <a href="/pages/en/index.html">Home</a>

.. and . have special meanings in file paths, .. means up one directory and . means current directory.

so <a href="index.html">Home</a> is the same as <a href="./index.html">Home</a>

What's a good, free serial port monitor for reverse-engineering?

Oops, can't comment yet (!) but re: Nick and logic analyser, beware: RS232 signal levels not typically Logic Analyser compatible unless you get/make a special serial probe. A 'proper' RS232/Serial port can use +/-12v swings (on all signals) and sometimes more. A laptop sometimes uses 0-5v swings (and often won't work with real serial interfaces) so could work with a vbasic 'ttl-level' LA interface.

How can I initialize base class member variables in derived class constructor?

You can't initialize a and b in B because they are not members of B. They are members of A, therefore only A can initialize them. You can make them public, then do assignment in B, but that is not a recommended option since it would destroy encapsulation. Instead, create a constructor in A to allow B (or any subclass of A) to initialize them:

class A 
{
protected:
    A(int a, int b) : a(a), b(b) {} // Accessible to derived classes
    // Change "protected" to "public" to allow others to instantiate A.
private:
    int a, b; // Keep these variables private in A
};

class B : public A 
{
public:
    B() : A(0, 0) // Calls A's constructor, initializing a and b in A to 0.
    {
    } 
};

How to increase Heap size of JVM

Java command line parameters

-Xms: initial heap size
-Xmx: Maximum heap size

if you are using Tomcat. Update CATALINA_OPTS environment variable

export CATALINA_OPTS=-Xms16m -Xmx256m;

How can I join on a stored procedure?

I actually like the previous answer (don't use the SP), but if you're tied to the SP itself for some reason, you could use it to populate a temp table, and then join on the temp table. Note that you're going to cost yourself some additional overhead there, but it's the only way I can think of to use the actual stored proc.

Again, you may be better off in-lining the query from the SP into the original query.

CSS for grabbing cursors (drag & drop)

"more custom" than CSS cursors means a plugin of some type, but you can totally specify your own cursors using CSS. I think this list has what you want:

_x000D_
_x000D_
.alias {cursor: alias;}_x000D_
.all-scroll {cursor: all-scroll;}_x000D_
.auto {cursor: auto;}_x000D_
.cell {cursor: cell;}_x000D_
.context-menu {cursor: context-menu;}_x000D_
.col-resize {cursor: col-resize;}_x000D_
.copy {cursor: copy;}_x000D_
.crosshair {cursor: crosshair;}_x000D_
.default {cursor: default;}_x000D_
.e-resize {cursor: e-resize;}_x000D_
.ew-resize {cursor: ew-resize;}_x000D_
.grab {cursor: grab;}_x000D_
.grabbing {cursor: grabbing;}_x000D_
.help {cursor: help;}_x000D_
.move {cursor: move;}_x000D_
.n-resize {cursor: n-resize;}_x000D_
.ne-resize {cursor: ne-resize;}_x000D_
.nesw-resize {cursor: nesw-resize;}_x000D_
.ns-resize {cursor: ns-resize;}_x000D_
.nw-resize {cursor: nw-resize;}_x000D_
.nwse-resize {cursor: nwse-resize;}_x000D_
.no-drop {cursor: no-drop;}_x000D_
.none {cursor: none;}_x000D_
.not-allowed {cursor: not-allowed;}_x000D_
.pointer {cursor: pointer;}_x000D_
.progress {cursor: progress;}_x000D_
.row-resize {cursor: row-resize;}_x000D_
.s-resize {cursor: s-resize;}_x000D_
.se-resize {cursor: se-resize;}_x000D_
.sw-resize {cursor: sw-resize;}_x000D_
.text {cursor: text;}_x000D_
.url {cursor: url(https://www.w3schools.com/cssref/myBall.cur),auto;}_x000D_
.w-resize {cursor: w-resize;}_x000D_
.wait {cursor: wait;}_x000D_
.zoom-in {cursor: zoom-in;}_x000D_
.zoom-out {cursor: zoom-out;}
_x000D_
<h1>The cursor Property</h1>_x000D_
<p>Hover mouse over each to see how the cursor looks</p>_x000D_
_x000D_
<p class="alias">cursor: alias</p>_x000D_
<p class="all-scroll">cursor: all-scroll</p>_x000D_
<p class="auto">cursor: auto</p>_x000D_
<p class="cell">cursor: cell</p>_x000D_
<p class="context-menu">cursor: context-menu</p>_x000D_
<p class="col-resize">cursor: col-resize</p>_x000D_
<p class="copy">cursor: copy</p>_x000D_
<p class="crosshair">cursor: crosshair</p>_x000D_
<p class="default">cursor: default</p>_x000D_
<p class="e-resize">cursor: e-resize</p>_x000D_
<p class="ew-resize">cursor: ew-resize</p>_x000D_
<p class="grab">cursor: grab</p>_x000D_
<p class="grabbing">cursor: grabbing</p>_x000D_
<p class="help">cursor: help</p>_x000D_
<p class="move">cursor: move</p>_x000D_
<p class="n-resize">cursor: n-resize</p>_x000D_
<p class="ne-resize">cursor: ne-resize</p>_x000D_
<p class="nesw-resize">cursor: nesw-resize</p>_x000D_
<p class="ns-resize">cursor: ns-resize</p>_x000D_
<p class="nw-resize">cursor: nw-resize</p>_x000D_
<p class="nwse-resize">cursor: nwse-resize</p>_x000D_
<p class="no-drop">cursor: no-drop</p>_x000D_
<p class="none">cursor: none</p>_x000D_
<p class="not-allowed">cursor: not-allowed</p>_x000D_
<p class="pointer">cursor: pointer</p>_x000D_
<p class="progress">cursor: progress</p>_x000D_
<p class="row-resize">cursor: row-resize</p>_x000D_
<p class="s-resize">cursor: s-resize</p>_x000D_
<p class="se-resize">cursor: se-resize</p>_x000D_
<p class="sw-resize">cursor: sw-resize</p>_x000D_
<p class="text">cursor: text</p>_x000D_
<p class="url">cursor: url</p>_x000D_
<p class="w-resize">cursor: w-resize</p>_x000D_
<p class="wait">cursor: wait</p>_x000D_
<p class="zoom-in">cursor: zoom-in</p>_x000D_
<p class="zoom-out">cursor: zoom-out</p>
_x000D_
_x000D_
_x000D_

Source: CSS cursor Property @ W3Schools

How to specify in crontab by what user to run script?

Mike's suggestion sounds like the "right way". I came across this thread wanting to specify the user to run vncserver under on reboot and wanted to keep all my cron jobs in one place.

I was getting the following error for the VNC cron:

vncserver: The USER environment variable is not set. E.g.:

In my case, I was able to use sudo to specify who to run the task as.

@reboot sudo -u [someone] vncserver ...

Multiple values in single-value context

Yes, there is.

Surprising, huh? You can get a specific value from a multiple return using a simple mute function:

package main

import "fmt"
import "strings"

func µ(a ...interface{}) []interface{} {
    return a
}

type A struct {
    B string
    C func()(string)
}

func main() {
    a := A {
        B:strings.TrimSpace(µ(E())[1].(string)),
        C:µ(G())[0].(func()(string)),
    }

    fmt.Printf ("%s says %s\n", a.B, a.C())
}

func E() (bool, string) {
    return false, "F"
}

func G() (func()(string), bool) {
    return func() string { return "Hello" }, true
}

https://play.golang.org/p/IwqmoKwVm-

Notice how you select the value number just like you would from a slice/array and then the type to get the actual value.

You can read more about the science behind that from this article. Credits to the author.

How to roundup a number to the closest ten?

You can use the function MROUND(<reference cell>, <round to multiple of digit needed>).

Example:

  1. For a value A1 = 21 round to multiple of 10 it would be written as =MROUND(A1,10) for which Result = 20

  2. For a value Z4 = 55.1 round to multiple of 10 it would be written as =MROUND(Z4,10) for which Result = 60

Find where java class is loaded from

Jon's version fails when the object's ClassLoader is registered as null which seems to imply that it was loaded by the Boot ClassLoader.

This method deals with that issue:

public static String whereFrom(Object o) {
  if ( o == null ) {
    return null;
  }
  Class<?> c = o.getClass();
  ClassLoader loader = c.getClassLoader();
  if ( loader == null ) {
    // Try the bootstrap classloader - obtained from the ultimate parent of the System Class Loader.
    loader = ClassLoader.getSystemClassLoader();
    while ( loader != null && loader.getParent() != null ) {
      loader = loader.getParent();
    }
  }
  if (loader != null) {
    String name = c.getCanonicalName();
    URL resource = loader.getResource(name.replace(".", "/") + ".class");
    if ( resource != null ) {
      return resource.toString();
    }
  }
  return "Unknown";
}

Using Docker-Compose, how to execute multiple commands

I run pre-startup stuff like migrations in a separate ephemeral container, like so (note, compose file has to be of version '2' type):

db:
  image: postgres
web:
  image: app
  command: python manage.py runserver 0.0.0.0:8000
  volumes:
    - .:/code
  ports:
    - "8000:8000"
  links:
    - db
  depends_on:
    - migration
migration:
  build: .
  image: app
  command: python manage.py migrate
  volumes:
    - .:/code
  links:
    - db
  depends_on:
    - db

This helps things keeping clean and separate. Two things to consider:

  1. You have to ensure the correct startup sequence (using depends_on).

  2. You want to avoid multiple builds which is achieved by tagging it the first time round using build and image; you can refer to image in other containers then.

Finding all cycles in a directed graph

Regarding your question about the Permutation Cycle, read more here: https://www.codechef.com/problems/PCYCLE

You can try this code (enter the size and the digits number):

# include<cstdio>
using namespace std;

int main()
{
    int n;
    scanf("%d",&n);

    int num[1000];
    int visited[1000]={0};
    int vindex[2000];
    for(int i=1;i<=n;i++)
        scanf("%d",&num[i]);

    int t_visited=0;
    int cycles=0;
    int start=0, index;

    while(t_visited < n)
    {
        for(int i=1;i<=n;i++)
        {
            if(visited[i]==0)
            {
                vindex[start]=i;
                visited[i]=1;
                t_visited++;
                index=start;
                break;
            }
        }
        while(true)
        {
            index++;
            vindex[index]=num[vindex[index-1]];

            if(vindex[index]==vindex[start])
                break;
            visited[vindex[index]]=1;
            t_visited++;
        }
        vindex[++index]=0;
        start=index+1;
        cycles++;
    }

    printf("%d\n",cycles,vindex[0]);

    for(int i=0;i<(n+2*cycles);i++)
    {
        if(vindex[i]==0)
            printf("\n");
        else
            printf("%d ",vindex[i]);
    }
}

Checking if my Windows application is running

Enter a guid in your assembly data. Add this guid to the registry. Enter a reg key where the application read it's own name and add the name as value there.

The other task watcher read the reg key and knows the app name.

Django - iterate number in for loop of a template

I think you could call the id, like this

{% for days in days_list %}
    <h2># Day {{ days.id }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
{% endfor %}

How to generate sample XML documents from their DTD or XSD?

Seems like nobody was able to answer the question so far :)

I use EclipseLink's MOXy to dynamically generate binding classes and then recursively go through the bound types. It is somewhat heavy, but it allows XPath value injection once the object tree is instantiated:

InputStream in = new FileInputStream(PATH_TO_XSD);
DynamicJAXBContext jaxbContext = 
            DynamicJAXBContextFactory.createContextFromXSD(in, null, Thread.currentThread().getContextClassLoader(), null);
DynamicType rootType = jaxbContext.getDynamicType(YOUR_ROOT_TYPE);
DynamicEntity root = rootType.newDynamicEntity();
traverseProps(jaxbContext, root, rootType, 0);

TraverseProps is pretty simple recursive method:

private void traverseProps(DynamicJAXBContext c, DynamicEntity e, DynamicType t, int level) throws DynamicException, InstantiationException, IllegalAccessException{
        if (t!=null) {
            logger.info(indent(level) + "type [" + t.getName() + "] of class [" + t.getClassName() + "] has " + t.getNumberOfProperties() + " props");
            for (String pName:t.getPropertiesNames()){
                Class<?> clazz = t.getPropertyType(pName);
                logger.info(indent(level) + "prop [" + pName + "] in type: " + clazz);
                //logger.info("prop [" + pName + "] in entity: " + e.get(pName));

                if (clazz==null){
                    // need to create an instance of object
                    String updatedClassName = pName.substring(0, 1).toUpperCase() + pName.substring(1);
                    logger.info(indent(level) + "Creating new type instance for " + pName + " using following class name: " + updatedClassName );
                    DynamicType child = c.getDynamicType("generated." + updatedClassName);
                    DynamicEntity childEntity = child.newDynamicEntity();
                    e.set(pName, childEntity);
                    traverseProps(c, childEntity, child, level+1);
                } else {
                    // just set empty value
                    e.set(pName, clazz.newInstance());
                }
            }
        } else {
            logger.warn("type is null");
        }
    }

Converting everything to XML is pretty easy:

Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);

How to set and reference a variable in a Jenkinsfile

According to the documentation, you can also set global environment variables if you later want to use the value of the variable in other parts of your script. In your case, it would be setting it in the root pipeline:

pipeline {
  ...
  environment {
    FILENAME = readFile ...
  }
  ...
}

How to execute my SQL query in CodeIgniter

I can see what @Þaw mentioned :

$ENROLLEES = $this->load->database('ENROLLEES', TRUE);
$ACCOUNTS = $this->load->database('ACCOUNTS', TRUE);

CodeIgniter supports multiple databases. You need to keep both database reference in separate variable as you did above. So far you are right/correct.

Next you need to use them as below:

$ENROLLEES->query();
$ENROLLEES->result();

and

$ACCOUNTS->query();
$ACCOUNTS->result();

Instead of using

$this->db->query();
$this->db->result();

See this for reference: http://ellislab.com/codeigniter/user-guide/database/connecting.html

Unzip All Files In A Directory

If by 'current directory' you mean the directory in which the zip file is, then I would use this command:

find . -name '*.zip' -execdir unzip {} \; 

excerpt from find's man page

-execdir command ;
-execdir command {} +

Like -exec, but the specified command is run from the subdirectory containing the matched file, which is not normally the directory in which you started find. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec option, the '+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your $PATH environment variable does not reference the current directory; otherwise, an attacker can run any commands they like by leaving an appropriately-named file in a directory in which you will run -execdir.

see if two files have the same content in python

I'm not sure if you want to find duplicate files or just compare two single files. If the latter, the above approach (filecmp) is better, if the former, the following approach is better.

There are lots of duplicate files detection questions here. Assuming they are not very small and that performance is important, you can

  • Compare file sizes first, discarding all which doesn't match
  • If file sizes match, compare using the biggest hash you can handle, hashing chunks of files to avoid reading the whole big file

Here's is an answer with Python implementations (I prefer the one by nosklo, BTW)

Powershell: convert string to number

Since this topic never received a verified solution, I can offer a simple solution to the two issues I see you asked solutions for.

  1. Replacing the "." character when value is a string

The string class offers a replace method for the string object you want to update:

Example:

$myString = $myString.replace(".","") 
  1. Converting the string value to an integer

The system.int32 class (or simply [int] in powershell) has a method available called "TryParse" which will not only pass back a boolean indicating whether the string is an integer, but will also return the value of the integer into an existing variable by reference if it returns true.

Example:

[string]$convertedInt = "1500"
[int]$returnedInt = 0
[bool]$result = [int]::TryParse($convertedInt, [ref]$returnedInt)

I hope this addresses the issue you initially brought up in your question.

Clear screen in shell

Here are some options that you can use on Windows

First option:

import os
cls = lambda: os.system('cls')

>>> cls()

Second option:

cls = lambda: print('\n' * 100)

>>> cls()

Third option if you are in Python REPL window:

Ctrl+L

How to scroll the window using JQuery $.scrollTo() function

$('html, body').animate({scrollTop: $("#page").offset().top}, 2000);

How do I get the value of text input field using JavaScript?

If you are using jQuery then by using plugin formInteract, you just need to do this:

// Just keep the HTML as it is.

<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>

At bottom of the page just include this plugin file and write this code:

// Initialize one time at the bottom of the page.
var search= $("#searchTxt).formInteract();

search.getAjax("http://www.myurl.com/search/", function(rsp){
    // Now do whatever you want to with your response
});

Or if using a parameterized URL then use this:

$.get("http://www.myurl.com/search/"+search.get().searchTxt, {}, function(rsp){
    // Now do work with your response;
})

Here is the link to project https://bitbucket.org/ranjeet1985/forminteract

You can use this plugin for many purposes like getting the value of a form, putting values into a form, validation of forms and many more. You can see some example of code in the index.html file of the project.

Of course I am the author of this project and all are welcome to make it better.

What does .pack() do?

The pack method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location). In general, using pack is preferable to calling setSize, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.

From Java tutorial

You should also refer to Javadocs any time you need additional information on any Java API

IF... OR IF... in a windows batch file

Even if this question is a little older:

If you want to use if cond1 or cond 2 - you should not use complicated loops or stuff like that.

Simple provide both ifs after each other combined with goto - that's an implicit or.

//thats an implicit IF cond1 OR cond2 OR cond3
if cond1 GOTO doit
if cond2 GOTO doit
if cond3 GOTO doit

//thats our else.
GOTO end

:doit
  echo "doing it"

:end

Without goto but an "inplace" action, you might execute the action 3 times, if ALL conditions are matching.

Image vs Bitmap class

This is a clarification because I have seen things done in code which are honestly confusing - I think the following example might assist others.

As others have said before - Bitmap inherits from the Abstract Image class

Abstract effectively means you cannot create a New() instance of it.

    Image imgBad1 = new Image();        // Bad - won't compile
    Image imgBad2 = new Image(200,200); // Bad - won't compile

But you can do the following:

    Image imgGood;  // Not instantiated object!
    // Now you can do this
    imgGood = new Bitmap(200, 200);

You can now use imgGood as you would the same bitmap object if you had done the following:

    Bitmap bmpGood = new Bitmap(200,200);

The nice thing here is you can draw the imgGood object using a Graphics object

    Graphics gr = default(Graphics);
    gr = Graphics.FromImage(new Bitmap(1000, 1000));
    Rectangle rect = new Rectangle(50, 50, imgGood.Width, imgGood.Height); // where to draw
    gr.DrawImage(imgGood, rect);

Here imgGood can be any Image object - Bitmap, Metafile, or anything else that inherits from Image!

Maximum call stack size exceeded on npm install

For those having this issue when building a Docker image with Jenkins (or any CI), make sure the package-lock.json is also copied to the container.

COPY ./src/package*.json /home/node/
RUN npm install

For us, the install actually went fine, the error only occurred when running npm prune production for the production image.

Submit HTML form, perform javascript function (alert then redirect)

<form action="javascript:completeAndRedirect();">
    <input type="text" id="Edit1" 
    style="width:280; height:50; font-family:'Lucida Sans Unicode', 'Lucida Grande', sans-serif; font-size:22px">
</form>

Changing action to point at your function would solve the problem, in a different way.

Unique on a dataframe with only selected columns

Ok, if it doesn't matter which value in the non-duplicated column you select, this should be pretty easy:

dat <- data.frame(id=c(1,1,3),id2=c(1,1,4),somevalue=c("x","y","z"))
> dat[!duplicated(dat[,c('id','id2')]),]
  id id2 somevalue
1  1   1         x
3  3   4         z

Inside the duplicated call, I'm simply passing only those columns from dat that I don't want duplicates of. This code will automatically always select the first of any ambiguous values. (In this case, x.)

How can you get the build/version number of your Android application?

For API 28 (Android 9 (Pie)), the PackageInfo.versionCode is deprecated, so use this code below:

Context context = getApplicationContext();
PackageManager manager = context.getPackageManager();
try {
    PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
    myversionName = info.versionName;
    versionCode = (int) PackageInfoCompat.getLongVersionCode(info);
}
catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
    myversionName = "Unknown-01";
}

What does the "@" symbol do in SQL?

The @CustID means it's a parameter that you will supply a value for later in your code. This is the best way of protecting against SQL injection. Create your query using parameters, rather than concatenating strings and variables. The database engine puts the parameter value into where the placeholder is, and there is zero chance for SQL injection.

Django Cookies, how can I set them?

You could manually set the cookie, but depending on your use case (and if you might want to add more types of persistent/session data in future) it might make more sense to use Django's sessions feature. This will let you get and set variables tied internally to the user's session cookie. Cool thing about this is that if you want to store a lot of data tied to a user's session, storing it all in cookies will add a lot of weight to HTTP requests and responses. With sessions the session cookie is all that is sent back and forth (though there is the overhead on Django's end of storing the session data to keep in mind).

Which characters are valid/invalid in a JSON key name?

The following characters must be escaped in JSON data to avoid any problems:

  • " (double quote)
  • \ (backslash)
  • all control characters like \n, \t

JSON Parser can help you to deal with JSON.