Programs & Examples On #Scoring

How to compute precision, recall, accuracy and f1-score for the multiclass case with scikit learn?

Posed question

Responding to the question 'what metric should be used for multi-class classification with imbalanced data': Macro-F1-measure. Macro Precision and Macro Recall can be also used, but they are not so easily interpretable as for binary classificaion, they are already incorporated into F-measure, and excess metrics complicate methods comparison, parameters tuning, and so on.

Micro averaging are sensitive to class imbalance: if your method, for example, works good for the most common labels and totally messes others, micro-averaged metrics show good results.

Weighting averaging isn't well suited for imbalanced data, because it weights by counts of labels. Moreover, it is too hardly interpretable and unpopular: for instance, there is no mention of such an averaging in the following very detailed survey I strongly recommend to look through:

Sokolova, Marina, and Guy Lapalme. "A systematic analysis of performance measures for classification tasks." Information Processing & Management 45.4 (2009): 427-437.

Application-specific question

However, returning to your task, I'd research 2 topics:

  1. metrics commonly used for your specific task - it lets (a) to compare your method with others and understand if you do something wrong, and (b) to not explore this by yourself and reuse someone else's findings;
  2. cost of different errors of your methods - for example, use-case of your application may rely on 4- and 5-star reviewes only - in this case, good metric should count only these 2 labels.

Commonly used metrics. As I can infer after looking through literature, there are 2 main evaluation metrics:

  1. Accuracy, which is used, e.g. in

Yu, April, and Daryl Chang. "Multiclass Sentiment Prediction using Yelp Business."

(link) - note that the authors work with almost the same distribution of ratings, see Figure 5.

Pang, Bo, and Lillian Lee. "Seeing stars: Exploiting class relationships for sentiment categorization with respect to rating scales." Proceedings of the 43rd Annual Meeting on Association for Computational Linguistics. Association for Computational Linguistics, 2005.

(link)

  1. MSE (or, less often, Mean Absolute Error - MAE) - see, for example,

Lee, Moontae, and R. Grafe. "Multiclass sentiment analysis with restaurant reviews." Final Projects from CS N 224 (2010).

(link) - they explore both accuracy and MSE, considering the latter to be better

Pappas, Nikolaos, Rue Marconi, and Andrei Popescu-Belis. "Explaining the Stars: Weighted Multiple-Instance Learning for Aspect-Based Sentiment Analysis." Proceedings of the 2014 Conference on Empirical Methods In Natural Language Processing. No. EPFL-CONF-200899. 2014.

(link) - they utilize scikit-learn for evaluation and baseline approaches and state that their code is available; however, I can't find it, so if you need it, write a letter to the authors, the work is pretty new and seems to be written in Python.

Cost of different errors. If you care more about avoiding gross blunders, e.g. assinging 1-star to 5-star review or something like that, look at MSE; if difference matters, but not so much, try MAE, since it doesn't square diff; otherwise stay with Accuracy.

About approaches, not metrics

Try regression approaches, e.g. SVR, since they generally outperforms Multiclass classifiers like SVC or OVA SVM.

How does the class_weight parameter in scikit-learn work?

First off, it might not be good to just go by recall alone. You can simply achieve a recall of 100% by classifying everything as the positive class. I usually suggest using AUC for selecting parameters, and then finding a threshold for the operating point (say a given precision level) that you are interested in.

For how class_weight works: It penalizes mistakes in samples of class[i] with class_weight[i] instead of 1. So higher class-weight means you want to put more emphasis on a class. From what you say it seems class 0 is 19 times more frequent than class 1. So you should increase the class_weight of class 1 relative to class 0, say {0:.1, 1:.9}. If the class_weight doesn't sum to 1, it will basically change the regularization parameter.

For how class_weight="auto" works, you can have a look at this discussion. In the dev version you can use class_weight="balanced", which is easier to understand: it basically means replicating the smaller class until you have as many samples as in the larger one, but in an implicit way.

Why do some functions have underscores "__" before and after the function name?

Names surrounded by double underscores are "special" to Python. They're listed in the Python Language Reference, section 3, "Data model".

Android How to adjust layout in Full Screen Mode when softkeyboard is visible

Thank you Joseph for your answer. However, in the method possiblyResizeChildOfContent(), the portion

else {
            // keyboard probably just became hidden
            frameLayoutParams.height = usableHeightSansKeyboard;
        }

was not working for me, as the lower portion of view became hidden. So I had to take a global variable restoreHeight, and in the constructor, I inserted the last line

restoreHeight = frameLayoutParams.height;

and then I replaced the former mentioned part with

else {
            // keyboard probably just became hidden
            frameLayoutParams.height = restoreHeight;
        }

But I have no idea why your code didn't work for me. It would be of great help, if someone can shed light on this.

Calling a function within a Class method?

Try this one:

class test {
     public function newTest(){
          $this->bigTest();
          $this->smallTest();
     }

     private function bigTest(){
          //Big Test Here
     }

     private function smallTest(){
          //Small Test Here
     }

     public function scoreTest(){
          //Scoring code here;
     }
}

$testObject = new test();

$testObject->newTest();

$testObject->scoreTest();

How to Diff between local uncommitted changes and origin

If you want to compare files visually you can use:

git difftool

It will start your diff app automatically for each changed file.

PS: If you did not set a diff app, you can do it like in the example below(I use Winmerge):

git config --global merge.tool winmerge
git config --replace --global mergetool.winmerge.cmd "\"C:\Program Files (x86)\WinMerge\WinMergeU.exe\" -e -u -dl \"Base\" -dr \"Mine\" \"$LOCAL\" \"$REMOTE\" \"$MERGED\""
git config --global mergetool.prompt false

How to Set a Custom Font in the ActionBar Title?

I just did the following inside the onCreate() function:

TypefaceSpan typefaceSpan = new TypefaceSpan("font_to_be_used");
SpannableString str = new SpannableString("toolbar_text");
str.setSpan(typefaceSpan,0, str.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
getSupportActionBar().setTitle(str);

I am using the Support Libraries, if you are not using them I guess you should switch to getActionBar() instead of getSupportActionBar().

In Android Studio 3 you can add custom fonts following this instructions https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html and then use your newly added font in "font_to_be_used"

Check with jquery if div has overflowing elements

So I used the overflowing jquery library: https://github.com/kevinmarx/overflowing

After installing the library, if you want to assign the class overflowing to all overflowing elements, you simply run:

$('.targetElement').overflowing('.parentElement')

This will then give the class overflowing, as in <div class="targetElement overflowing"> to all elements that are overflowing. You could then add this to some event handler(click, mouseover) or other function that will run the above code so that it updates dynamically.

Open link in new tab or window

It shouldn't be your call to decide whether the link should open in a new tab or a new window, since ultimately this choice should be done by the settings of the user's browser. Some people like tabs; some like new windows.

Using _blank will tell the browser to use a new tab/window, depending on the user's browser configuration and how they click on the link (e.g. middle click, Ctrl+click, or normal click).

Check if string is upper, lower, or mixed case in Python

I want to give a shoutout for using re module for this. Specially in the case of case sensitivity.

We use the option re.IGNORECASE while compiling the regex for use of in production environments with large amounts of data.

>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>>
>>>
>>> pattern = re.compile('is')
>>>
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

However try to always use the in operator for string comparison as detailed in this post

faster-operation-re-match-or-str

Also detailed in the one of the best books to start learning python with

idiomatic-python

Get original URL referer with PHP?

Store it in a cookie that only lasts for the current browsing session

Generating all permutations of a given string

All the previous contributors have done a great job explaining and providing the code. I thought I should share this approach too because it might help someone too. The solution is based on (heaps' algorithm )

Couple of things:

  1. Notice the last item which is depicted in the excel is just for helping you better visualize the logic. So, the actual values in the last column would be 2,1,0 (if we were to run the code because we are dealing with arrays and arrays start with 0).

  2. The swapping algorithm happens based on even or odd values of current position. It's very self explanatory if you look at where the swap method is getting called.You can see what's going on.

Here is what happens: enter image description here

public static void main(String[] args) {

        String ourword = "abc";
        String[] ourArray = ourword.split("");
        permute(ourArray, ourArray.length);

    }

    private static void swap(String[] ourarray, int right, int left) {
        String temp = ourarray[right];
        ourarray[right] = ourarray[left];
        ourarray[left] = temp;
    }

    public static void permute(String[] ourArray, int currentPosition) {
        if (currentPosition == 1) {
            System.out.println(Arrays.toString(ourArray));
        } else {
            for (int i = 0; i < currentPosition; i++) {
                // subtract one from the last position (here is where you are
                // selecting the the next last item 
                permute(ourArray, currentPosition - 1);

                // if it's odd position
                if (currentPosition % 2 == 1) {
                    swap(ourArray, 0, currentPosition - 1);
                } else {
                    swap(ourArray, i, currentPosition - 1);
                }
            }
        }
    }

JDK was not found on the computer for NetBeans 6.5

I would first double-check that you installed the JDK, rather than just the JRE. It's easy to grab the wrong one and not even realize it. Then I'd make sure that your JAVA_HOME environment variable is pointing to your JDK install directory, NOT the bin directory. You may want to add the bin directory to the PATH environment variable, but Netbeans is more likely looking at the JAVA_HOME environment variable.

jQuery.click() vs onClick

IMHO, onclick is the preferred method over .click only when the following conditions are met:

  • there are many elements on the page
  • only one event to be registered for the click event
  • You're worried about mobile performance/battery life

I formed this opinion because of the fact that the JavaScript engines on mobile devices are 4 to 7 times slower than their desktop counterparts which were made in the same generation. I hate it when I visit a site on my mobile device and receive jittery scrolling because the jQuery is binding all of the events at the expense of my user experience and battery life. Another recent supporting factor, although this should only be a concern with government agencies ;) , we had IE7 pop-up with a message box stating that JavaScript process is taking to long...wait or cancel process. This happened every time there were a lot of elements to bind to via jQuery.

White space at top of page

This particular answer shows that h1 elements have an implicit margin-top that can cause the whitespace

https://stackoverflow.com/a/20021854/2129219

The suggestion to remove it is helpful, and certainly eye opening to how this is happening

h1 { margin-top: 0; }

How to compare objects by multiple fields

@Patrick To sort more than one field consecutively try ComparatorChain

A ComparatorChain is a Comparator that wraps one or more Comparators in sequence. The ComparatorChain calls each Comparator in sequence until either 1) any single Comparator returns a non-zero result (and that result is then returned), or 2) the ComparatorChain is exhausted (and zero is returned). This type of sorting is very similar to multi-column sorting in SQL, and this class allows Java classes to emulate that kind of behaviour when sorting a List.

To further facilitate SQL-like sorting, the order of any single Comparator in the list can >be reversed.

Calling a method that adds new Comparators or changes the ascend/descend sort after compare(Object, Object) has been called will result in an UnsupportedOperationException. However, take care to not alter the underlying List of Comparators or the BitSet that defines the sort order.

Instances of ComparatorChain are not synchronized. The class is not thread-safe at construction time, but it is thread-safe to perform multiple comparisons after all the setup operations are complete.

Determine which element the mouse pointer is on top of in JavaScript

You can use this selector to undermouse object and then manipulate it as a jQuery object:

$(':hover').last();

Importing Pandas gives error AttributeError: module 'pandas' has no attribute 'core' in iPython Notebook

There is an other weird reason this happens. If you have a file called pandas.py or a directory called pandas in the same or nested levels, that library is used instead and fails to work. Rename the folder and restart the env and it started working. Faced this

Get week of year in JavaScript like in PHP

Jacob Wright's Date.format() library implements date formatting in the style of PHP's date() function and supports the ISO-8601 week number:

new Date().format('W');

It may be a bit overkill for just a week number, but it does support PHP style formatting and is quite handy if you'll be doing a lot of this.

How do I disable the security certificate check in Python requests

If you want to send exactly post request with verify=False option, fastest way is to use this code:

import requests

requests.api.request('post', url, data={'bar':'baz'}, json=None, verify=False)

remove first element from array and return the array minus the first element

This should remove the first element, and then you can return the remaining:

_x000D_
_x000D_
var myarray = ["item 1", "item 2", "item 3", "item 4"];_x000D_
    _x000D_
myarray.shift();_x000D_
alert(myarray);
_x000D_
_x000D_
_x000D_

As others have suggested, you could also use slice(1);

_x000D_
_x000D_
var myarray = ["item 1", "item 2", "item 3", "item 4"];_x000D_
  _x000D_
alert(myarray.slice(1));
_x000D_
_x000D_
_x000D_

JavaScript .replace only replaces first Match

The same, if you need "generic" regex from string :

_x000D_
_x000D_
const textTitle = "this is a test";_x000D_
const regEx = new RegExp(' ', "g");_x000D_
const result = textTitle.replace(regEx , '%20');_x000D_
console.log(result); // "this%20is%20a%20test" will be a result_x000D_
    
_x000D_
_x000D_
_x000D_

Are there any free Xml Diff/Merge tools available?

This is a diff engine for java developers, but it comes with a demo interface - you might be able to use it: https://community.emc.com/docs/DOC-5042

SimpleXml to string

Sometimes you can simply typecast:

// this is the value of my $xml
object(SimpleXMLElement)#10227 (1) {
  [0]=>
  string(2) "en"
}

$s = (string) $xml; // returns "en";

How do I find an element position in std::vector?

Take a vector of integer and a key (that we find in vector )....Now we are traversing the vector until found the key value or last index(otherwise).....If we found key then print the position , otherwise print "-1".

     #include <bits/stdc++.h>  
     using namespace std;  

     int main()  
      {  
          vector<int>str;  
          int flag,temp key, ,len,num;

           flag=0;
           cin>>len;

           for(int i=1; i<=len; i++)  
           {
               cin>>key;
               v.push_back(key);
           }

           cin>>num;

           for(int i=1; i<=len; i++)  
           {  
             if(str[i]==num)  
             {  
                flag++;  
                temp=i-1;
                break;
             }  
           }

         if(flag!=0)    cout<<temp<<endl;
         else           cout<<"-1"<<endl;   
         str.clear();   

         return 0;  
      }

CURL alternative in Python

You can use HTTP Requests that are described in the Requests: HTTP for Humans user guide.

Convert character to ASCII numeric value in java

using Java 9 => String.chars()

String input = "stackoverflow";
System.out.println(input.chars().boxed().collect(Collectors.toList()));

output - [115, 116, 97, 99, 107, 111, 118, 101, 114, 102, 108, 111, 119]

How can I connect to MySQL in Python 3 on Windows?

This does not fully answer my original question, but I think it is important to let everyone know what I did and why.

I chose to continue using python 2.7 instead of python 3 because of the prevalence of 2.7 examples and modules on the web in general.

I now use both mysqldb and mysql.connector to connect to MySQL in Python 2.7. Both are great and work well. I think mysql.connector is ultimately better long term however.

How to import a Python class that is in a directory above?

import sys
sys.path.append("..") # Adds higher directory to python modules path.

Curl error: Operation timed out

In curl request add time out 0 so its infinite time set like CURLOPT_TIMEOUT set 0

Programmatically navigate using React router

To do the navigation programmatically, you need to push a new history to the props.history in your component, so something like this can do the work for you:

//using ES6
import React from 'react';

class App extends React.Component {

  constructor(props) {
    super(props)
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick(e) {
    e.preventDefault()
    /* Look at here, you can add it here */
    this.props.history.push('/redirected');
  }

  render() {
    return (
      <div>
        <button onClick={this.handleClick}>
          Redirect!!!
        </button>
      </div>
    )
  }
}

export default App;

Is the 'as' keyword required in Oracle to define an alias?

My conclusion is that(Tested on 12c):

  • AS is always optional, either with or without ""; AS makes no difference (column alias only, you can not use AS preceding table alias)
  • However, with or without "" does make difference because "" lets lower case possible for an alias

thus :

SELECT {T / t} FROM (SELECT 1 AS T FROM DUAL); -- Correct
SELECT "tEST" FROM (SELECT 1 AS "tEST" FROM DUAL); -- Correct
SELECT {"TEST" / tEST} FROM (SELECT 1 AS "tEST" FROM DUAL ); -- Incorrect

SELECT test_value AS "doggy" FROM test ORDER BY "doggy"; --Correct
SELECT test_value AS "doggy" FROM test WHERE "doggy" IS NOT NULL; --You can not do this, column alias not supported in WHERE & HAVING
SELECT * FROM test "doggy" WHERE "doggy".test_value IS NOT NULL; -- Do not use AS preceding table alias

So, the reason why USING AS AND "" causes problem is NOT AS

Note: "" double quotes are required if alias contains space OR if it contains lower-case characters and MUST show-up in Result set as lower-case chars. In all other scenarios its OPTIONAL and can be ignored.

Why do we use $rootScope.$broadcast in AngularJS?

$rootScope.$broadcast is a convenient way to raise a "global" event which all child scopes can listen for. You only need to use $rootScope to broadcast the message, since all the descendant scopes can listen for it.

The root scope broadcasts the event:

$rootScope.$broadcast("myEvent");

Any child Scope can listen for the event:

$scope.$on("myEvent",function () {console.log('my event occurred');} );

Why we use $rootScope.$broadcast? You can use $watch to listen for variable changes and execute functions when the variable state changes. However, in some cases, you simply want to raise an event that other parts of the application can listen for, regardless of any change in scope variable state. This is when $broadcast is helpful.

What is the difference between a hash join and a merge join (Oracle RDBMS )?

A "sort merge" join is performed by sorting the two data sets to be joined according to the join keys and then merging them together. The merge is very cheap, but the sort can be prohibitively expensive especially if the sort spills to disk. The cost of the sort can be lowered if one of the data sets can be accessed in sorted order via an index, although accessing a high proportion of blocks of a table via an index scan can also be very expensive in comparison to a full table scan.

A hash join is performed by hashing one data set into memory based on join columns and reading the other one and probing the hash table for matches. The hash join is very low cost when the hash table can be held entirely in memory, with the total cost amounting to very little more than the cost of reading the data sets. The cost rises if the hash table has to be spilled to disk in a one-pass sort, and rises considerably for a multipass sort.

(In pre-10g, outer joins from a large to a small table were problematic performance-wise, as the optimiser could not resolve the need to access the smaller table first for a hash join, but the larger table first for an outer join. Consequently hash joins were not available in this situation).

The cost of a hash join can be reduced by partitioning both tables on the join key(s). This allows the optimiser to infer that rows from a partition in one table will only find a match in a particular partition of the other table, and for tables having n partitions the hash join is executed as n independent hash joins. This has the following effects:

  1. The size of each hash table is reduced, hence reducing the maximum amount of memory required and potentially removing the need for the operation to require temporary disk space.
  2. For parallel query operations the amount of inter-process messaging is vastly reduced, reducing CPU usage and improving performance, as each hash join can be performed by one pair of PQ processes.
  3. For non-parallel query operations the memory requirement is reduced by a factor of n, and the first rows are projected from the query earlier.

You should note that hash joins can only be used for equi-joins, but merge joins are more flexible.

In general, if you are joining large amounts of data in an equi-join then a hash join is going to be a better bet.

This topic is very well covered in the documentation.

http://download.oracle.com/docs/cd/B28359_01/server.111/b28274/optimops.htm#i51523

12.1 docs: https://docs.oracle.com/database/121/TGSQL/tgsql_join.htm

How to create standard Borderless buttons (like in the design guideline mentioned)?

A great slide show on how to achieve the desired effect from Googles Nick Butcher (start at slide 20). He uses the standard android @attr to style the button and divider.

Transport security has blocked a cleartext HTTP

Development Example

Here is a screenshot of a plist which keeps ATS intact (=secure), but allows that connections to localhost can be made via HTTP instead of HTTPS. It works in Xcode 7.1.1.

Enter image description here

Select objects based on value of variable in object using jq

Adapted from this post on Processing JSON with jq, you can use the select(bool) like this:

$ jq '.[] | select(.location=="Stockholm")' json
{
  "location": "Stockholm",
  "name": "Walt"
}
{
  "location": "Stockholm",
  "name": "Donald"
}

Can not find the tag library descriptor of springframework

I finally configured RAD to build my Maven-based project, but was getting the following exception when I navigate to a page that uses the Spring taglib:

JSPG0047E: Unable to locate tag library for uri http://www.springframework.org/tags at com.ibm.ws.jsp.translator.visitor.tagfiledep.TagFileDependencyVisitor.visitCustomTagStart(TagFileDependencyVisitor.java:76) ...

The way I had configured my EAR, all the jars were in the EAR, not in the WAR’s WEB-INF/lib. According to the JSP 2.0 spec, I believe tag libs are searched for in all subdirectories of WEB-INF, hence the issue. My solution was to copy the tld files and place under WEB-INF/lib or WEB-INF.. Then it worked.

Difference between drop table and truncate table?

TRUNCATE TABLE is functionally identical to DELETE statement with no WHERE clause: both remove all rows in the table. But TRUNCATE TABLE is faster and uses fewer system and transaction log resources than DELETE.

The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row. TRUNCATE TABLE removes the data by deallocating the data pages used to store the table's data, and only the page deallocations are recorded in the transaction log.

TRUNCATE TABLE removes all rows from a table, but the table structure and its columns, constraints, indexes and so on remain. The counter used by an identity for new rows is reset to the seed for the column. If you want to retain the identity counter, use DELETE instead. If you want to remove table definition and its data, use the DROP TABLE statement.

You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint; instead, use DELETE statement without a WHERE clause. Because TRUNCATE TABLE is not logged, it cannot activate a trigger.

TRUNCATE TABLE may not be used on tables participating in an indexed view.

From http://msdn.microsoft.com/en-us/library/aa260621(SQL.80).aspx

What is a magic number, and why is it bad?

I assume this is a response to my answer to your earlier question. In programming, a magic number is an embedded numerical constant that appears without explanation. If it appears in two distinct locations, it can lead to circumstances where one instance is changed and not another. For both these reasons, it's important to isolate and define the numerical constants outside the places where they're used.

I want to calculate the distance between two points in Java

Math.sqrt returns a double so you'll have to cast it to int as well

distance = (int)Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));

Android Device not recognized by adb

Enabling Developer mode by tapping on Build Number 7 times worked for me.

How to set placeholder value using CSS?

From what I understand using,

::-webkit-input-placeholder::beforeor ::-webkit-input-placeholder::after,

to add more placeholder content doesn't work anymore. Think its a new Chrome update.

Really annoying as it was a great workaround, now im back to just adding lots of empty spaces between lines that I want in a placeholder. eg:

<input type="text" value="" id="email1" placeholder="I am on one line.                                              I am on a second line                                                                                     etc etc..." />

Do a "git export" (like "svn export")?

From the Git Manual:

Using git-checkout-index to "export an entire tree"

The prefix ability basically makes it trivial to use git-checkout-index as an "export as tree" function. Just read the desired tree into the index, and do:

$ git checkout-index --prefix=git-export-dir/ -a

Logger slf4j advantages of formatting with {} instead of string concatenation

I think from the author's point of view, the main reason is to reduce the overhead for string concatenation.I just read the logger's documentation, you could find following words:

/**
* <p>This form avoids superfluous string concatenation when the logger
* is disabled for the DEBUG level. However, this variant incurs the hidden
* (and relatively small) cost of creating an <code>Object[]</code> before 
  invoking the method,
* even if this logger is disabled for DEBUG. The variants taking
* {@link #debug(String, Object) one} and {@link #debug(String, Object, Object) two}
* arguments exist solely in order to avoid this hidden cost.</p>
*/
*
 * @param format    the format string
 * @param arguments a list of 3 or more arguments
 */
public void debug(String format, Object... arguments);

Create patch or diff file from git repository and apply it to another different git repository

As a complementary, to produce patch for only one specific commit, use:

git format-patch -1 <sha>

When the patch file is generated, make sure your other repo knows where it is when you use git am ${patch-name}

Before adding the patch, use git apply --check ${patch-name} to make sure that there is no confict.

PHP - Redirect and send data via POST

Your going to need CURL for that task I'm afraid. Nice easy way to do it here: http://davidwalsh.name/execute-http-post-php-curl

Hope that helps

Is there a way to programmatically minimize a window

this.WindowState = FormWindowState.Minimized;

Optimum way to compare strings in JavaScript?

Well in JavaScript you can check two strings for values same as integers so yo can do this:

  • "A" < "B"
  • "A" == "B"
  • "A" > "B"

And therefore you can make your own function that checks strings the same way as the strcmp().

So this would be the function that does the same:

function strcmp(a, b)
{   
    return (a<b?-1:(a>b?1:0));  
}

How do you say not equal to in Ruby?

Yes. In Ruby the not equal to operator is:

!=

You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.

static function in C

When there is a need to restrict access to some functions, we'll use the static keyword while defining and declaring a function.

            /* file ab.c */ 
static void function1(void) 
{ 
  puts("function1 called"); 
} 
And store the following code in another file ab1.c

/* file ab1.c  */ 
int main(void) 
{ 
 function1();  
  getchar(); 
  return 0;   
} 
/* in this code, we'll get a "Undefined reference to function1".Because function 1 is declared static in file ab.c and can't be used in ab1.c */

Hibernate Criteria for Dates

try this,

    String dateStr = "17-April-2011 19:20:23.707000000 ";
    Date dateForm = new SimpleDateFormat("dd-MMMM-yyyy HH:mm:ss").parse(dateStr);
    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");  

    String newDate = format.format(dateForm);  

    Calendar today = Calendar.getInstance();
    Date fromDate = format.parse(newDate);
    today.setTime(fromDate);
    today.add(Calendar.DAY_OF_YEAR, 1);
    Date toDate= new SimpleDateFormat("dd-MM-yyyy").parse(format.format(today.getTime()));

    Criteria crit = sessionFactory.getCurrentSession().createCriteria(Model.class);
    crit.add(Restrictions.ge("dateFieldName", fromDate));
    crit.add(Restrictions.le("dateFieldName", toDate));
    return crit.list();

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)

change ;memory_limit=512M to ;memory_limit=-1 in enter image description here

it's too dangerous for a server Your PHP code may have a memory leak somewhere and you are telling the server to just use all the memory that it wants. You wouldn't have fixed the problem at all. If you monitor your server, you will see that it is now probably using up most of the RAM and even swapping to disk.

How can I detect browser type using jQuery?

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    alert('sdfsd');_x000D_
    checkOperatingSystem();_x000D_
   });_x000D_
   function checkOperatingSystem(){_x000D_
       var  userAgent = navigator.userAgent || navigator.vendor || window.opera;_x000D_
_x000D_
       _x000D_
       if (/android/i.test(userAgent)) {_x000D_
           alert('android');_x000D_
       }_x000D_
_x000D_
       _x000D_
       if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {_x000D_
           alert('ios');_x000D_
       }_x000D_
_x000D_
      _x000D_
       if (navigator.appVersion.indexOf("Win")!=-1)_x000D_
       {_x000D_
           _x000D_
       }_x000D_
_x000D_
      _x000D_
       if (navigator.appVersion.indexOf("Mac")!=-1)_x000D_
       {_x000D_
           _x000D_
       }  _x000D_
   }
_x000D_
_x000D_
_x000D_

What is the convention for word separator in Java package names?

All three are not the conventions.

Use com.stackoverflow.mypackage.

The package names do not follow camel casing or underscores or hyphens package naming convention.

Also, Google Java Style Guide specifies exactly the same (i.e. com.stackoverflow.mypackage) convention:

5.2.1 Package names

Package names are all lowercase, with consecutive words simply concatenated together (no underscores). For example, com.example.deepspace, not com.example.deepSpace or com.example.deep_space.

Google Java Style Guide: 5.2 Rules by identifier type: 5.2.1 Package names.

JUnit Testing private variables?

I can't tell if you've found some special case code which requires you to test against private fields. But in my experience you never have to test something private - always public. Maybe you could give an example of some code where you need to test private?

PHPMailer - SMTP ERROR: Password command failed when send mail from my server

As others already suggested, you can enable the "less secure" applications or you can simply switch from ssl to tls:

$mailer->Host = 'tls://smtp.gmail.com';
$mailer->SMTPAuth = true;
$mailer->Username = "[email protected]";
$mailer->Password = "***";
$mailer->SMTPSecure = 'tls';
$mailer->Port = 587;

When using tls there's no need to grant access for less secure applications, just make sure, IMAP is enabled.

In Python How can I declare a Dynamic Array

Here's a great method I recently found on a different stack overflow post regarding multi-dimensional arrays, but the answer works beautifully for single dimensional arrays as well:

# Create an 8 x 5 matrix of 0's:
w, h = 8, 5;
MyMatrix = [ [0 for x in range( w )] for y in range( h ) ]  

# Create an array of objects:
MyList = [ {} for x in range( n ) ]

I love this because you can specify the contents and size dynamically, in one line!

One more for the road:

# Dynamic content initialization:
MyFunkyArray = [ x * a + b for x in range ( n ) ]

Build project into a JAR automatically in Eclipse

Create an Ant file and tell Eclipse to build it. There are only two steps and each is easy with the step-by-step instructions below.


Step 1 Create a build.xml file and add to package explorer:

<?xml version="1.0" ?>
<!-- Configuration of the Ant build system to generate a Jar file --> 
<project name="TestMain" default="CreateJar">
  <target name="CreateJar" description="Create Jar file">
        <jar jarfile="Test.jar" basedir="." includes="*.class" />
  </target>
</project>

Eclipse should looks something like the screenshot below. Note the Ant icon on build.xml. Build.xml in Eclipse Project

Step 2 Right-click on the root node in the project. - Select Properties - Select Builders - Select New - Select Ant Build - In the Main tab, complete the path to the build.xml file in the bin folder.

Ant builder configuration Build step - Targets Tab

Check the Output

The Eclipse output window (named Console) should show the following after a build:

Buildfile: /home/<user>/src/Test/build.xml

CreateJar:
         [jar] Building jar: /home/<user>/src/Test/Test.jar
BUILD SUCCESSFUL
Total time: 152 milliseconds

EDIT: Some helpful comments by @yeoman and @betlista

@yeoman I think the correct include would be /.class, not *.class, as most people use packages and thus recursive search for class files makes more sense than flat inclusion

@betlista I would recomment to not to have build.xml in src folder

What is the default text size on Android?

the default text size of the textview

if you not used any of the below

TextAppearance.Small

TextAppearance.Medium

TextAppearance.Large

then the default size is 14sp

Execute external program

borrowed this shamely from here

Process process = new ProcessBuilder("C:\\PathToExe\\MyExe.exe","param1","param2").start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;

System.out.printf("Output of running %s is:", Arrays.toString(args));

while ((line = br.readLine()) != null) {
  System.out.println(line);
}

More information here

Other issues on how to pass commands here and here

Creating a "logical exclusive or" operator in Java

Here's an example:

Given 2 int values, return true if one is negative and one is positive. Except if the parameter "negative" is true, then return true only if both are negative.

    public boolean posNeg(int a, int b, boolean negative) {
      if(!negative){
        return (a>0 && b<0)^(b>0 && a<0);
      }
      else return (a<0 && b<0);
    }

HTTP Get with 204 No Content: Is that normal

I use GET/204 with a RESTful collection that is a positional array of known fixed length but with holes.

GET /items
    200: ["a", "b", null]

GET /items/0
    200: "a"

GET /items/1
    200: "b"

GET /items/2
    204:

GET /items/3
    404: Not Found

Can't bind to 'ngIf' since it isn't a known property of 'div'

Just for anyone who still has an issue, I also had an issue where I typed ngif rather than ngIf (notice the capital 'I').

Timestamp with a millisecond precision: How to save them in MySQL

You need to be at MySQL version 5.6.4 or later to declare columns with fractional-second time datatypes. Not sure you have the right version? Try SELECT NOW(3). If you get an error, you don't have the right version.

For example, DATETIME(3) will give you millisecond resolution in your timestamps, and TIMESTAMP(6) will give you microsecond resolution on a *nix-style timestamp.

Read this: https://dev.mysql.com/doc/refman/8.0/en/fractional-seconds.html

NOW(3) will give you the present time from your MySQL server's operating system with millisecond precision.

If you have a number of milliseconds since the Unix epoch, try this to get a DATETIME(3) value

FROM_UNIXTIME(ms * 0.001)

Javascript timestamps, for example, are represented in milliseconds since the Unix epoch.

(Notice that MySQL internal fractional arithmetic, like * 0.001, is always handled as IEEE754 double precision floating point, so it's unlikely you'll lose precision before the Sun becomes a white dwarf star.)

If you're using an older version of MySQL and you need subsecond time precision, your best path is to upgrade. Anything else will force you into doing messy workarounds.

If, for some reason you can't upgrade, you could consider using BIGINT or DOUBLE columns to store Javascript timestamps as if they were numbers. FROM_UNIXTIME(col * 0.001) will still work OK. If you need the current time to store in such a column, you could use UNIX_TIMESTAMP() * 1000

How to Export Private / Secret ASC Key to Decrypt GPG Files

Similar to @Wolfram J's answer, here is a method to encrypt your private key with a passphrase:

gpg --output - --armor --export $KEYID | \
    gpg --output private_key.asc --armor --symmetric --cipher-algo AES256

And a corresponding method to decrypt:

gpg private_key.asc

HTML Mobile -forcing the soft keyboard to hide

I could not use some of the suggestions provided.

In my case I had Google Chrome being used to display an Oracle APEX Application. There were some very specific input fields that allowed you to start typing a value and a list of values would begin to be displayed and reduced as you became more specific in your typing. Once you selected the item from the list of available options, the focus would still be on the input field.

I found that my solution was easily accomplished with a custom event that throws a custom error like the following:

throw "throwing a custom error exits input and hides keyboard";

ojdbc14.jar vs. ojdbc6.jar

Actually, ojdbc14.jar doesn't really say anything about the real version of the driver (see JDBC Driver Downloads), except that it predates Oracle 11g. In such situation, you should provide the exact version.

Anyway, I think you'll find some explanation in What is going on with DATE and TIMESTAMP? In short, they changed the behavior in 9.2 drivers and then again in 11.1 drivers.

This might explain the differences you're experiencing (and I suggest using the most recent version i.e. the 11.2 drivers).

How to configure encoding in Maven?

OK, I have found the problem.

I use some reporting plugins. In the documentation of the failsafe-maven-plugin I found, that the <encoding> configuration - of course - uses ${project.reporting.outputEncoding} by default.

So I added the property as a child element of the project element and everything is fine now:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>

See also http://maven.apache.org/general.html#encoding-warning

ActiveX component can't create object

I know this is an old thread, but has anyone checked if their Antivirus is blocking Win32API and Scripting on their systems? I have CylanceProtect installed on my office system and i found the same issues occurring as listed by others. This can be confirmed if you check the Windows Logs in Event Viewer.

What is the difference between a symbolic link and a hard link?

Simply , Hard link : is just add new name to a file, that's mean , a file can have many name in the same time, all name are equal to each other, no one preferred, Hard link is not mean to copy the all contents of file and make new file is not that, it just create an alternative name to be known..

Symbolic link (symlink) : is a file pointer to another file, if the symbolic link points to an existing file which is later deleted, the symbolic link continues to point to the same file name even though the name no longer names any file.

How to select the last record from MySQL table using SQL syntax

SELECT MAX("field name") AS ("primary key") FROM ("table name")

example:

SELECT MAX(brand) AS brandid FROM brand_tbl

Enter key pressed event handler

You can also use PreviewKeyDown in WPF:

<TextBox PreviewKeyDown="EnterClicked" />

or in C#:

myTextBox.PreviewKeyDown += EnterClicked;

And then in the attached class:

void EnterClicked(object sender, KeyEventArgs e) {
    if(e.Key == Key.Return) {
        DoSomething();
        e.Handled = true;
    }
}

HTTPS using Jersey Client

If you are using Java 8, a shorter version for Jersey2 than the answer provided by Aleksandr.

SSLContext sslContext = null;
try {
  sslContext = SSLContext.getInstance("SSL");
  // Create a new X509TrustManager
  sslContext.init(null, getTrustManager(), null);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
  throw e;
}
final Client client = ClientBuilder.newBuilder().hostnameVerifier((s, session) -> true)
  .sslContext(sslContext).build();
return client;

private TrustManager[] getTrustManager() {
  return new TrustManager[] {
    new X509TrustManager() {
      @Override
      public X509Certificate[] getAcceptedIssuers() {
        return null;
      }
      @Override
      public void checkServerTrusted(X509Certificate[] chain, String authType)
      throws CertificateException {
      }
      @Override
      public void checkClientTrusted(X509Certificate[] chain, String authType)
      throws CertificateException {
      }
    }
  };
}

Download image with JavaScript

As @Ian explained, the problem is that jQuery's click() is not the same as the native one.

Therefore, consider using vanilla-js instead of jQuery:

var a = document.createElement('a');
a.href = "img.png";
a.download = "output.png";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);

Demo

mysql stored-procedure: out parameter

SET out_number=SQRT(input_number); 

Instead of this write:

select SQRT(input_number); 

Please don't write SET out_number and your input parameter should be:

PROCEDURE `test`.`my_sqrt`(IN input_number INT, OUT out_number FLOAT) 

Using quotation marks inside quotation marks

When you have several words like this which you want to concatenate in a string, I recommend using format or f-strings which increase readability dramatically (in my opinion).

To give an example:

s = "a word that needs quotation marks"
s2 = "another word"

Now you can do

print('"{}" and "{}"'.format(s, s2))

which will print

"a word that needs quotation marks" and "another word"

As of Python 3.6 you can use:

print(f'"{s}" and "{s2}"')

yielding the same output.

How to run DOS/CMD/Command Prompt commands from VB.NET?

You Can try This To Run Command Then cmd Exits

Process.Start("cmd", "/c YourCode")

You Can try This To Run The Command And Let cmd Wait For More Commands

Process.Start("cmd", "/k YourCode")

Set Date in a single line

You could use new GregorianCalendar(theYear, theMonth, theDay).getTime():

public GregorianCalendar(int year, int month, int dayOfMonth)

Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.

HTML5 - mp4 video does not play in IE9

If it's still not working here's what may certainly be a solution: encode the mp4 with compression format H.264. If you encode it with format mpeg4 or divx or else it will not work on IE9 and may as well crash Google Chrome. To do that, I use Any Video Converter freeware. But it could be done with any good video tool out there.

I've been trying all solutions listed here and tried other workaround for days but the problem lied in the way I created my mp4. IE9 does not decode other format than H.264.

Hope this helps, Jimmy

How do I define and use an ENUM in Objective-C?

Apple provides a macro to help provide better code compatibility, including Swift. Using the macro looks like this.

typedef NS_ENUM(NSInteger, PlayerStateType) {
  PlayerStateOff,
  PlayerStatePlaying,
  PlayerStatePaused
};

Documented here

Remove a git commit which has not been pushed

Simply type in the console :

$ git reset HEAD~

This command discards all local commits ahead of the remote HEAD

Which port we can use to run IIS other than 80?

You can run IIS on any port you like, as long as it does not conflict with other applications. I am using 88, 8888 and other easy to remember ports.

You can find the common used port here: PORT NUMBERS, and it is safer to choose an unassigned TCP port.

Quote:

The Dynamic and/or Private Ports are those from 49152 through 65535

If IIS is working and you have troubles with an ASP.NET applications, those links might be helpful:

If you are still having troubles, it would be helpful to provide more information about your environment, the steps taken so far to solve the problem, and retagging the question (append asp.net for example)

SSH to AWS Instance without key pairs

Answer to Question 1

Here's what I did on a Ubuntu EC2:

A) Login as root using the keypairs

B) Setup the necessary users and their passwords with

# sudo adduser USERNAME
# sudo passwd USERNAME

C) Edit /etc/ssh/sshd_config setting

For a valid user to login with no key

PasswordAuthentication yes

Also want root to login also with no key

PermitRootLogin yes

D) Restart the ssh daemon with

# sudo service ssh restart

just change ssh to sshd if you are using centOS

Now you can login into your ec2 instance without key pairs.

Difference between Activity and FragmentActivity

A FragmentActivity is a subclass of Activity that was built for the Android Support Package.

The FragmentActivity class adds a couple new methods to ensure compatibility with older versions of Android, but other than that, there really isn't much of a difference between the two. Just make sure you change all calls to getLoaderManager() and getFragmentManager() to getSupportLoaderManager() and getSupportFragmentManager() respectively.

XAMPP Apache Webserver localhost not working on MAC OS

Found out how to make it work!

I just moved apache2 (the Web Sharing folder) to my desktop.

  1. go to terminal and type "mv /etc/apache2/ /Users/hseungun/Desktop"

  2. actually it says you need authority so

  3. type this "sudo -s" then it'll go to bash-3.2

  4. passwd root

  5. set your password and then "mv /etc/apache2/ /Users/hseungun/Desktop"

  6. try turning on the web sharing, and then start xampp on mac

Basic HTTP authentication with Node and Express 4

TL;DR:

? express.basicAuth is gone
? basic-auth-connect is deprecated
? basic-auth doesn't have any logic
? http-auth is an overkill
? express-basic-auth is what you want

More info:

Since you're using Express then you can use the express-basic-auth middleware.

See the docs:

Example:

const app = require('express')();
const basicAuth = require('express-basic-auth');
 
app.use(basicAuth({
    users: { admin: 'supersecret123' },
    challenge: true // <--- needed to actually show the login dialog!
}));

Loading context in Spring using web.xml

You can also specify context location relatively to current classpath, which may be preferable

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:applicationContext*.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

How do I break out of a loop in Perl?

For Perl one-liners with implicit loops (using -n or -p command line options), use last or last LINE to break out of the loop that iterates over input records. For example, these simple examples all print the first 2 lines of the input:

echo 1 2 3 4 | xargs -n1 | perl -ne 'last if $. == 3; print;'
echo 1 2 3 4 | xargs -n1 | perl -ne 'last LINE if $. == 3; print;'
echo 1 2 3 4 | xargs -n1 | perl -pe 'last if $. == 3;'
echo 1 2 3 4 | xargs -n1 | perl -pe 'last LINE if $. == 3;'

All print:

1
2

The perl one-liners use these command line flags:
-e : tells Perl to look for code in-line, instead of in a file.
-n : loop over the input one line at a time, assigning it to $_ by default.
-p : same as -n, also add print after each loop iteration over the input.

SEE ALSO:

last docs
last, next, redo, continue - an illustrated example
perlrun: command line switches docs


More examples of last in Perl one-liners:

Break one liner command line script after first match
Print the first N lines of a huge file

Ignore files that have already been committed to a Git repository

On my server linux server (not true on my local dev mac), directories are ignored as long as I don't add an asterisk:

www/archives/*

I don't know why but it made me loose a couple of hours, so I wanted to share...

HashSet vs LinkedHashSet

HashSet:

The underlined data structure is Hashtable. Duplicate objects are not allowed.insertion order is not preserved and it is based on hash code of objects. Null insertion is possible(only once). It implements Serializable, Clonable but not RandomAccess interface. HashSet is best choose if frequent operation is search operation.

In HashSet duplicates are not allowed.if users are trying to insert duplicates when we won't get any compile or runtime exceptions. add method returns simply false.

Constructors:

HashSet h=new HashSet(); creates an empty HashSet object with default initial capacity 16 and default fill ratio(Load factor) is 0.75 .

HashSet h=new HashSet(int initialCapacity); creates an empty HashSet object with specified initialCapacity and default fill ration is 0.75.

HashSet h=new HashSet(int initialCapacity, float fillRatio);

HashSet h=new HashSet(Collection c); creates an equivalent HashSet object for the given collection. This constructor meant for inter conversion between collection object.

LinkedHashSet:

It is a child class of HashSet. it is exactly same as HashSet including(Constructors and Methods) except the following differences.

Differences HashSet:

  1. The underlined data structure is Hashtable.
  2. Insertion order is not preserved.
  3. introduced 1.2 version.

LinkedHashSet:

  1. The underlined data structure is a combination of LinkedList and Hashtable.
  2. Insertion order is preserved.
  3. Indroduced in 1.4 version.

How to position the Button exactly in CSS

Try using absolute positioning, rather than relative positioning

this should get you close - you can adjust by tweaking margins or top/left positions

#play_button {
    position:absolute;
    transition: .5s ease;
    top: 50%;
    left: 50%;
}

http://jsfiddle.net/rolfsf/9pNqS/

.htaccess, order allow, deny, deny from all: confused?

This is a quite confusing way of using Apache configuration directives.

Technically, the first bit is equivalent to

Allow From All

This is because Order Deny,Allow makes the Deny directive evaluated before the Allow Directives. In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.

Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.

The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.

Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.

It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.

The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):

#
# The following lines prevent .htaccess and .htpasswd files from being 
# viewed by Web clients. 
#
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy all
</Files>

which forbids access to any file beginning by ".ht".

The equivalent Apache 2.4 configuration should look like:

<Files ~ "^\.ht">
    Require all denied
</Files>

Dots in URL causes 404 with ASP.NET mvc and IIS

Super easy answer for those that only have this on one webpage. Edit your actionlink and a + "/" on the end of it.

  @Html.ActionLink("Edit", "Edit", new { id = item.name + "/" }) |

Is it possible to have multiple statements in a python lambda expression?

Yes it is possible. Try below code snippet.

x = [('human', 1), ('i', 2), ('am', 1), ('.', 1), ('love', 1), ('python', 3), ('', 1),
  ('run', 1), ('is', 2), ('robust', 1), ('hello', 1), ('spark', 2), ('to', 1), ('analysis', 2), ('on', 1), ('big', 1), ('data', 1), ('with', 1), ('analysis', 1), ('great', 1)
]

rdd_filter = rdd1_word_cnt_sum.filter(lambda x: 'python' in x or 'human' in x or 'big' in x)
rdd_filter.collect()

SQL SELECT WHERE field contains words

Note that if you use LIKE to determine if a string is a substring of another string, you must escape the pattern matching characters in your search string.

If your SQL dialect supports CHARINDEX, it's a lot easier to use it instead:

SELECT * FROM MyTable
WHERE CHARINDEX('word1', Column1) > 0
  AND CHARINDEX('word2', Column1) > 0
  AND CHARINDEX('word3', Column1) > 0

Also, please keep in mind that this and the method in the accepted answer only cover substring matching rather than word matching. So, for example, the string 'word1word2word3' would still match.

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

Check the properties of SQL Sever from the Object explorer.

If Integrated Security is set to true, make the same changes in connection string as well.

check the screenshot of the property grid

It worked in case of ASP.NET Core Web Api...

Why is the apt-get function not working in the terminal on Mac OS X v10.9 (Mavericks)?

Alternatively You can use the brew or curl command for installing things, wherever apt-get is mentioned with a URL...

For example,

curl -O http://www.magentocommerce.com/downloads/assets/1.8.1.0/magento-1.8.1.0.tar.gz

Plotting multiple curves same graph and same scale

My solution is to use ggplot2. It takes care of these types of things automatically. The biggest thing is to arrange the data appropriately.

y1 <- c(100, 200, 300, 400, 500)
y2 <- c(1, 2, 3, 4, 5)
x <- c(1, 2, 3, 4, 5)
df <- data.frame(x=rep(x,2), y=c(y1, y2), class=c(rep("y1", 5), rep("y2", 5)))

Then use ggplot2 to plot it

library(ggplot2)
ggplot(df, aes(x=x, y=y, color=class)) + geom_point()

This is saying plot the data in df, and separate the points by class.

The plot generated isenter image description here

What does "for" attribute do in HTML <label> tag?

Using label for= in html form

This could permit to visualy dissociate label(s) and object while keeping them linked.

Sample: there is a checkbox and two labels. You could check/uncheck the box by clicking indifferently on any label or on box, but not on text nor on input content...

_x000D_
_x000D_
<label for="demo1"> There is a label </label>
<br />
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis sem velit, ultrices et, fermentum auctor, rhoncus ut, ligula. Phasellus at purus sed purus cursus iaculis. Suspendisse fermentum. Pellentesque et arcu. Maecenas viverra. In consectetuer, lorem eu lobortis egestas, velit odio imperdiet eros, sit amet sagittis nunc mi ac neque. Sed non ipsum. Nullam venenatis gravida orci.
<br />
<label for="demo1"> There is a 2nd label </label>
<input id="demo1" type="checkbox">Demo 1</input>
_x000D_
_x000D_
_x000D_

Some useful tricks

By use stylesheet CSS power, you could do a lot of interresting things...

_x000D_
_x000D_
#demo2:checked ~ .but2:before { content: 'Des'; }
#demo2:checked ~ .box2:before { content: '?'; }
.but2:before { content: 'S'; }
.box2:before { content: '?'; }
#demo1:checked ~ .but1:before { content: 'Des'; }
#demo1:checked ~ .box1:before { content: '?'; }
.but1:before { content: 'S'; }
.box1:before { content: '?'; }
_x000D_
<input id="demo1" type="checkbox">Demo 1</input>
<input id="demo2" type="checkbox">Demo 2</input>
<br />
<label for="demo1" class="but1">elect 2</label> - 
<label for="demo2" class="but2">elect 1</label>
<br />
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis sem velit, ultrices et, fermentum auctor, rhoncus ut, ligula. Phasellus at purus sed purus cursus iaculis. Suspendisse fermentum. Pellentesque et arcu. Maecenas viverra. In consectetuer, lorem eu lobortis egestas, velit odio imperdiet eros, sit amet sagittis nunc mi ac neque. Sed non ipsum. Nullam venenatis gravida orci.
<br />
<label for="demo1" class="but1">elect this 2nd label </label> - 
<label class="but2" for="demo2">elect this another 2nd label </label>
<br />
<label for="demo1" class="box1"> check 1</label>
<label for="demo2" class="box2"> check 2</label> 
_x000D_
_x000D_
_x000D_

Why am I getting a " Traceback (most recent call last):" error?

At the beginning of your file you set raw_input to 0. Do not do this, at it modifies the built-in raw_input() function. Therefore, whenever you call raw_input(), it is essentially calling 0(), which raises the error. To remove the error, remove the first line of your code:

M = 1.6
# Miles to Kilometers 
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54


def intro():
    print("Welcome! This program will convert measures for you.")
    main()

def main():
    print("Select operation.")
    print("1.Miles to Kilometers")
    print("2.Fahrenheit to Celsius")
    print("3.Gallons to liters")
    print("4.Pounds to kilograms")
    print("5.Inches to centimeters")

    choice = input("Enter your choice by number: ")

    if choice == '1':
        convertMK()

    elif choice == '2':
        converCF()

    elif choice == '3':
        convertGL()

    elif choice == '4':
        convertPK()

    elif choice == '5':
        convertPK()

    else:
        print("Error")


def convertMK():
    input_M = float(raw_input(("Miles: ")))
    M_conv = (M) * input_M
    print("Kilometers: %f\n" % M_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def converCF():
    input_F = float(raw_input(("Fahrenheit: ")))
    F_conv = (input_F - 32) * 5/9
    print("Celcius: %f\n") % F_conv
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def convertGL():
    input_G = float(raw_input(("Gallons: ")))
    G_conv = input_G * 3.6
    print("Centimeters: %f\n" % G_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertPK():
    input_P = float(raw_input(("Pounds: ")))
    P_conv = input_P * 0.45
    print("Centimeters: %f\n" % P_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertIC():
    input_cm = float(raw_input(("Inches: ")))
    inches_conv = input_cm * 2.54
    print("Centimeters: %f\n" % inches_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def end():
    print("This program will close.")
    exit()

intro()

Python threading.timer - repeat function every 'n' seconds

This is an alternate implementation using function instead of class. Inspired by @Andrew Wilkins above.

Because wait is more accurate than sleep ( it takes function runtime into account ):

import threading

PING_ON = threading.Event()

def ping():
  while not PING_ON.wait(1):
    print("my thread %s" % str(threading.current_thread().ident))

t = threading.Thread(target=ping)
t.start()

sleep(5)
PING_ON.set()

Get index of array element faster than O(n)

If your array has a natural order use binary search.

Use binary search.

Binary search has O(log n) access time.

Here are the steps on how to use binary search,

  • What is the ordering of you array? For example, is it sorted by name?
  • Use bsearch to find elements or indices

Code example

# assume array is sorted by name!

array.bsearch { |each| "Jamie" <=> each.name } # returns element
(0..array.size).bsearch { |n| "Jamie" <=> array[n].name } # returns index

How to display text in pygame?

When displaying I sometimes make a new file called Funk. This will have the font, size etc. This is the code for the class:

import pygame

def text_to_screen(screen, text, x, y, size = 50,
            color = (200, 000, 000), font_type = 'data/fonts/orecrusherexpand.ttf'):
    try:

        text = str(text)
        font = pygame.font.Font(font_type, size)
        text = font.render(text, True, color)
        screen.blit(text, (x, y))

    except Exception, e:
        print 'Font Error, saw it coming'
        raise e

Then when that has been imported when I want to display text taht updates E.G score I do:

Funk.text_to_screen(screen, 'Text {0}'.format(score), xpos, ypos)

If it is just normal text that isn't being updated:

Funk.text_to_screen(screen, 'Text', xpos, ypos)

You may notice {0} on the first example. That is because when .format(whatever) is used that is what will be updated. If you have something like Score then target score you'd do {0} for score then {1} for target score then .format(score, targetscore)

How to Auto resize HTML table cell to fit the text size

If you want the cells to resize depending on the content, then you must not specify a width to the table, the rows, or the cells.

If you don't want word wrap, assign the CSS style white-space: nowrap to the cells.

Automatic exit from Bash shell script on error

An alternative to the accepted answer that fits in the first line:

#!/bin/bash -e

cd some_dir  

./configure --some-flags  

make  

make install

How to set up ES cluster?

its super easy.

You'll need each machine to have it's own copy of ElasticSearch (simply copy the one you have now) -- the reason is that each machine / node whatever is going to keep it's own files that are sharded accross the cluster.

The only thing you really need to do is edit the config file to include the name of the cluster.

If all machines have the same cluster name elasticsearch will do the rest automatically (as long as the machines are all on the same network)

Read here to get you started: https://www.elastic.co/guide/en/elasticsearch/guide/current/deploy.html

When you create indexes (where the data goes) you define at that time how many replicas you want (they'll be distributed around the cluster)

Command to change the default home directory of a user

In case other readers look for information on the adduser command.

Edit /etc/adduser.conf

Set DHOME variable

How to center horizontal table-cell

Sometimes you have things other than text inside a table cell that you'd like to be horizontally centered. In order to do this, first set up some css...

<style>
    div.centered {
        margin: auto;
        width: 100%;
        display: flex;
        justify-content: center;
    }
</style>

Then declare a div with class="centered" inside each table cell you want centered.

<td>
    <div class="centered">
        Anything: text, controls, etc... will be horizontally centered.
    </div>
</td>

Get values from label using jQuery

Use .attr

$("current_month").attr("month")
$("current_month").attr("year")

And change the labels id to

<label year="2010" month="6" id="current_month"> June &nbsp;2010</label>

Find out a Git branch creator

As far as I know, you may see if you are the creator of a branch only. This is indicated by the first row in .git/ref/heads/<branch>. If it ends with "Created from HEAD" you are the creator.

Creating stored procedure and SQLite?

Answer: NO

Here's Why ... I think a key reason for having stored procs in a database is that you're executing SP code in the same process as the SQL engine. This makes sense for database engines designed to work as a network connected service but the imperative for SQLite is much less given that it runs as a DLL in your application process rather than in a separate SQL engine process. So it makes more sense to implement all your business logic including what would have been SP code in the host language.

You can however extend SQLite with your own user defined functions in the host language (PHP, Python, Perl, C#, Javascript, Ruby etc). You can then use these custom functions as part of any SQLite select/update/insert/delete. I've done this in C# using DevArt's SQLite to implement password hashing.

Converting list to numpy array

If you have a list of lists, you only needed to use ...

import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)

per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.

What is the difference between And and AndAlso in VB.NET?

If Bool1 And Bool2 Then

Evaluates both Bool1 and Bool2

If Bool1 AndAlso Bool2 Then

Evaluates Bool2 if and only if Bool1 is true.

How to use Elasticsearch with MongoDB?

Here I found another good option to migrate your MongoDB data to Elasticsearch. A go daemon that syncs mongodb to elasticsearch in realtime. Its the Monstache. Its available at : Monstache

Below the initial setp to configure and use it.

Step 1:

C:\Program Files\MongoDB\Server\4.0\bin>mongod --smallfiles --oplogSize 50 --replSet test

Step 2 :

C:\Program Files\MongoDB\Server\4.0\bin>mongo

C:\Program Files\MongoDB\Server\4.0\bin>mongo
MongoDB shell version v4.0.2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 4.0.2
Server has startup warnings:
2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten]
2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten]
2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten] ** WARNING: This server is bound to localhost.
2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten] **          Remote systems will be unable to connect to this server.
2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten] **          Start the server with --bind_ip <address> to specify which IP
2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten] **          addresses it should serve responses from, or with --bind_ip_all to
2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten] **          bind to all interfaces. If this behavior is desired, start the
2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten] **          server with --bind_ip 127.0.0.1 to disable this warning.
2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten]
MongoDB Enterprise test:PRIMARY>

Step 3 : Verify the replication.

MongoDB Enterprise test:PRIMARY> rs.status();
{
        "set" : "test",
        "date" : ISODate("2019-01-18T11:39:00.380Z"),
        "myState" : 1,
        "term" : NumberLong(2),
        "syncingTo" : "",
        "syncSourceHost" : "",
        "syncSourceId" : -1,
        "heartbeatIntervalMillis" : NumberLong(2000),
        "optimes" : {
                "lastCommittedOpTime" : {
                        "ts" : Timestamp(1547811537, 1),
                        "t" : NumberLong(2)
                },
                "readConcernMajorityOpTime" : {
                        "ts" : Timestamp(1547811537, 1),
                        "t" : NumberLong(2)
                },
                "appliedOpTime" : {
                        "ts" : Timestamp(1547811537, 1),
                        "t" : NumberLong(2)
                },
                "durableOpTime" : {
                        "ts" : Timestamp(1547811537, 1),
                        "t" : NumberLong(2)
                }
        },
        "lastStableCheckpointTimestamp" : Timestamp(1547811517, 1),
        "members" : [
                {
                        "_id" : 0,
                        "name" : "localhost:27017",
                        "health" : 1,
                        "state" : 1,
                        "stateStr" : "PRIMARY",
                        "uptime" : 736,
                        "optime" : {
                                "ts" : Timestamp(1547811537, 1),
                                "t" : NumberLong(2)
                        },
                        "optimeDate" : ISODate("2019-01-18T11:38:57Z"),
                        "syncingTo" : "",
                        "syncSourceHost" : "",
                        "syncSourceId" : -1,
                        "infoMessage" : "",
                        "electionTime" : Timestamp(1547810805, 1),
                        "electionDate" : ISODate("2019-01-18T11:26:45Z"),
                        "configVersion" : 1,
                        "self" : true,
                        "lastHeartbeatMessage" : ""
                }
        ],
        "ok" : 1,
        "operationTime" : Timestamp(1547811537, 1),
        "$clusterTime" : {
                "clusterTime" : Timestamp(1547811537, 1),
                "signature" : {
                        "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                        "keyId" : NumberLong(0)
                }
        }
}
MongoDB Enterprise test:PRIMARY>

Step 4. Download the "https://github.com/rwynn/monstache/releases". Unzip the download and adjust your PATH variable to include the path to the folder for your platform. GO to cmd and type "monstache -v" # 4.13.1 Monstache uses the TOML format for its configuration. Configure the file for migration named config.toml

Step 5.

My config.toml -->

mongo-url = "mongodb://127.0.0.1:27017/?replicaSet=test"
elasticsearch-urls = ["http://localhost:9200"]

direct-read-namespaces = [ "admin.users" ]

gzip = true
stats = true
index-stats = true

elasticsearch-max-conns = 4
elasticsearch-max-seconds = 5
elasticsearch-max-bytes = 8000000 

dropped-collections = false
dropped-databases = false

resume = true
resume-write-unsafe = true
resume-name = "default"
index-files = false
file-highlighting = false
verbose = true
exit-after-direct-reads = false

index-as-update=true
index-oplog-time=true

Step 6.

D:\15-1-19>monstache -f config.toml

Monstache Running...

Confirm Migrated Data at Elasticsearch

Add Record at Mongo

Monstache Captured the event and migrate the data to elasticsearch

How to pass the -D System properties while testing on Eclipse?

You can add command line arguments to your run configuration. Just edit the run configuration and add -Dmyprop=value (or whatever) to the VM Arguments Box.

How to enable PHP short tags?

For Wamp Server users there is easier way: You may enable that setting simply (left) click once on the WampServer icon, choose PHP -> PHP settings -> short open tag. Wait for a second, then WampServer will automatically restart your PHP and also its web service.

originally from: http://osticket.com/forums/showthread.php?t=3149

Android Studio Image Asset Launcher Icon Background Color

To make background transparent, set shape as None. See the image below:

enter image description here

EDIT:

For Android Studio 3.0, you can set it from Legacy Tab

enter image description here

How to refresh page on back button click?

First of all insert field in your code:

<input id="reloadValue" type="hidden" name="reloadValue" value="" />

then run jQuery:

<script type="text/javascript">
   jQuery(document).ready(function()
    {
            var d = new Date();
            d = d.getTime();
            if (jQuery('#reloadValue').val().length === 0)
            {
                    jQuery('#reloadValue').val(d);
                    jQuery('body').show();
            }
            else
            {
                    jQuery('#reloadValue').val('');
                    location.reload();
            }
    });

MySQL Error: : 'Access denied for user 'root'@'localhost'

I did this to set my root password in initial set up of MySQL in OSx. Open a terminal.

sudo sh -c 'echo /usr/local/mysql/bin > /etc/paths.d/mysql'

Close the terminal and open a new terminal. And followings are worked in Linux, to set root password.

sudo /usr/local/mysql/support-files/mysql.server stop
sudo mysqld_safe --skip-grant-tables

(sudo mysqld_safe --skip-grant-tables : This did not work for me in first time. But second try, out was success.)

Then login to MySQL

mysql -u root

FLUSH PRIVILEGES;

Now change the password:

ALTER USER 'root'@'localhost' IDENTIFIED BY 'newpassword';

Restart MySQL:

sudo /usr/local/mysql/support-files/mysql.server stop
sudo /usr/local/mysql/support-files/mysql.server start

Excel VBA - Sum up a column

I think you are misinterpreting the source of the error; rExternalTotal appears to be equal to a single cell. rReportData.offset(0,0) is equal to rReportData
rReportData.offset(261,0).end(xlUp) is likely also equal to rReportData, as you offset by 261 rows and then use the .end(xlUp) function which selects the top of a contiguous data range.
If you are interested in the sum of just a column, you can just refer to the whole column:

dExternalTotal = Application.WorksheetFunction.Sum(columns("A:A"))

or

dExternalTotal = Application.WorksheetFunction.Sum(columns((rReportData.column))

The worksheet function sum will correctly ignore blank spaces.

Let me know if this helps!

struct.error: unpack requires a string argument of length 4

The struct module mimics C structures. It takes more CPU cycles for a processor to read a 16-bit word on an odd address or a 32-bit dword on an address not divisible by 4, so structures add "pad bytes" to make structure members fall on natural boundaries. Consider:

struct {                   11
    char a;      012345678901
    short b;     ------------
    char c;      axbbcxxxdddd
    int d;
};

This structure will occupy 12 bytes of memory (x being pad bytes).

Python works similarly (see the struct documentation):

>>> import struct
>>> struct.pack('BHBL',1,2,3,4)
'\x01\x00\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00'
>>> struct.calcsize('BHBL')
12

Compilers usually have a way of eliminating padding. In Python, any of =<>! will eliminate padding:

>>> struct.calcsize('=BHBL')
8
>>> struct.pack('=BHBL',1,2,3,4)
'\x01\x02\x00\x03\x04\x00\x00\x00'

Beware of letting struct handle padding. In C, these structures:

struct A {       struct B {
    short a;         int a;
    char b;          char b;
};               };

are typically 4 and 8 bytes, respectively. The padding occurs at the end of the structure in case the structures are used in an array. This keeps the 'a' members aligned on correct boundaries for structures later in the array. Python's struct module does not pad at the end:

>>> struct.pack('LB',1,2)
'\x01\x00\x00\x00\x02'
>>> struct.pack('LBLB',1,2,3,4)
'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04'

Release generating .pdb files, why?

Actually without PDB files and symbolic information they have it would be impossible to create a successful crash report (memory dump files) and Microsoft would not have the complete picture what caused the problem.

And so having PDB improves crash reporting.

Read user input inside a loop

Try to change the loop like this:

for line in $(cat filename); do
    read input
    echo $input;
done

Unit test:

for line in $(cat /etc/passwd); do
    read input
    echo $input;
    echo "[$line]"
done

Which loop is faster, while or for?

Some optimizing compilers will be able to do better loop unrolling with a for loop, but odds are that if you're doing something that can be unrolled, a compiler smart enough to unroll it is probably also smart enough to interpret the loop condition of your while loop as something it can unroll as well.

Comparing user-inputted characters in C

Because comparison doesn't work that way. 'Y' || 'y' is a logical-or operator; it returns 1 (true) if either of its arguments is true. Since 'Y' and 'y' are both true, you're comparing *answer with 1.

What you want is if(*answer == 'Y' || *answer == 'y') or perhaps:

switch (*answer) {
  case 'Y':
  case 'y':
    /* Code for Y */
    break;
  default:
    /* Code for anything else */
}

What's your most controversial programming opinion?

Although I'm in full favor of Test-Driven Development (TDD), I think there's a vital step before developers even start the full development cycle of prototyping a solution to the problem.

We too often get caught up trying to follow our TDD practices for a solution that may be misdirected because we don't know the domain well enough. Simple prototypes can often elucidate these problems.

Prototypes are great because you can quickly churn through and throw away more code than when you're writing tests first (sometimes). You can then begin the development process with a blank slate but a better understanding.

Create a mocked list by mockito

When dealing with mocking lists and iterating them, I always use something like:

@Spy
private List<Object> parts = new ArrayList<>();

Convert datatable to JSON in C#

I am using this function for describe table.
Use it after fill datatable

static public string DataTableToJSON(DataTable dataTable,bool readableformat=true)
        {
            string JSONString="[";
            string JSONRow;
            string colVal;
            foreach(DataRow dataRow in dataTable.Rows)
            {
                if(JSONString!="[") { JSONString += ","; }
                JSONRow = "";
                if (readableformat) { JSONRow += "\r\n"; }
                JSONRow += "{";

                foreach (DataColumn col in dataTable.Columns)
                {
                    colVal = dataRow[col].ToString();
                    colVal = colVal.Replace("\"", "\\\"");
                    colVal = colVal.Replace("'", "\\\'");
                    if(JSONRow!="{"&&JSONRow!="\r\n{") {

                        JSONRow += ",";

                    }
                    JSONRow += "\"" + col.ColumnName + "\":\"" + colVal + "\"";

                }
                JSONRow += "}";
                JSONString += JSONRow;
            }
            JSONString += "\r\n]";
            return JSONString;
        }

MySQL Query: "DESCRIBE TableName;"; DataTableToJSON(dataTable) Example Output:

[
{"Field":"id","Type":"int(5)","Null":"NO","Key":"PRI","Default":"","Extra":"auto_increment"},
{"Field":"ad","Type":"int(11) unsigned","Null":"NO","Key":"MUL","Default":"","Extra":""},
{"Field":"soyad","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
{"Field":"ulke","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
{"Field":"alan","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
{"Field":"numara","Type":"varchar(20)","Null":"NO","Key":"","Default":"","Extra":""}
]

Tested With PHP:

$X='[
{"Field":"id","Type":"int(5)","Null":"NO","Key":"PRI","Default":"","Extra":"auto_increment"},
{"Field":"ad","Type":"int(11) unsigned","Null":"NO","Key":"MUL","Default":"","Extra":""},
{"Field":"soyad","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
{"Field":"ulke","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
{"Field":"alan","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
{"Field":"numara","Type":"varchar(20)","Null":"NO","Key":"","Default":"","Extra":""}
]';
$Y=json_decode($X,true);
echo $Y[0]["Field"];
var_dump($Y);

CSS-Only Scrollable Table with fixed headers

Another implementation but without any overflow on tbody and dynamic columns. Requires JavaScript though. A container div is used to house the column headings. When the table is scrolled past the view port, a fixed header appears at the top. If table is scrolled horizontally, the fixed header scrolls as well.

Column headings are created using span elements with display: inline-block and a negative margin is used to scroll header horizontally. Also optimized using RequestAnimationFrame to avoid any jank.

function rAF(scrollLeft) {
  var offsetLeft = 0 - scrollLeft;
  $('.hdr__inner span:first-child').css('margin-left', offsetLeft);
}

https://codepen.io/lloydleo/pen/NRpqEE

How can I map "insert='false' update='false'" on a composite-id key-property which is also used in a one-to-many FK?

I think the annotation you are looking for is:

public class CompanyName implements Serializable {
//...
@JoinColumn(name = "COMPANY_ID", referencedColumnName = "COMPANY_ID", insertable = false, updatable = false)
private Company company;

And you should be able to use similar mappings in a hbm.xml as shown here (in 23.4.2):

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/example-mappings.html

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

To begin - there are 4 issues that could be causing the common LocalDb SqlExpress Sql Server connectivity errors SQL Network Interfaces, error: 50 - Local Database Runtime error occurred, before you begin you need to rename the v11 or v12 to (localdb)\mssqllocaldb

Possible Issues
 \\ rename the conn string from v12.0 to MSSQLLocalDB -like so-> 
 `<connectionStrings>
      <add name="ProductsContext" connectionString="Data Source= (localdb)\mssqllocaldb; 
      ...`

I found that the simplest is to do the below - I have attached the pics and steps for help.

First verify which instance you have installed, you can do this by checking the registry& by running cmd

 1. `cmd> Sqllocaldb.exe i` 
 2. `cmd> Sqllocaldb.exe s "whicheverVersionYouWantFromListBefore"` 
if this step fails, you can delete with option `d` cmd> Sqllocaldb.exe d "someDb"
 3. `cmd> Sqllocaldb.exe c "createSomeNewDbIfyouWantDb"` 
 4. `cmd> Sqllocaldb.exe start "createSomeNewDbIfyouWantDb"`

SqlLOCALDb_edited.png


ADVANCED Trouble Shooting Registry configurations

Edit 1, from requests & comments: Here are the Registry path for all versions, in a generic format to track down the registry

Paths

// SQL SERVER RECENT VERSIONS
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\(instance-name)

// OLD SQL SERVER
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MSSQLServer
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer
// SQL SERVER 6.0 and above.

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\MSDTC
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SQLExecutive
// SQL SERVER 7.0 and above

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SQLServerAgent
HKEY_LOCAL_MACHINE\Software\Microsoft\Microsoft SQL Server 7
HKEY_LOCAL_MACHINE\Software\Microsoft\MSSQLServ65

Searching

SELECT registry_key, value_name, value_data  
FROM sys.dm_server_registry  
WHERE registry_key LIKE N'%SQLAgent%';

or Run this in SSMS Sql Management Studio, it will give a full list of all installs you have on the server

DECLARE     @SQL VARCHAR(MAX)
SET         @SQL = 'DECLARE @returnValue NVARCHAR(100)'
SELECT @SQL = @SQL + CHAR(13) + 'EXEC   master.dbo.xp_regread

 @rootkey      = N''HKEY_LOCAL_MACHINE'',
 @key          = N''SOFTWARE\Microsoft\Microsoft SQL Server\' + RegPath + '\MSSQLServer'',
 @value_name   = N''DefaultData'',
 @value        = @returnValue OUTPUT; 

 UPDATE #tempInstanceNames SET DefaultDataPath = @returnValue WHERE RegPath = ''' + RegPath + '''' + CHAR(13) FROM #tempInstanceNames 

 -- now, with these results, you can search the reg for the values inside reg
 EXEC (@SQL)
 SELECT      InstanceName, RegPath, DefaultDataPath
 FROM        #tempInstanceNames

Trouble Shooting Network configurations

SELECT registry_key, value_name, value_data  
FROM sys.dm_server_registry  
WHERE registry_key LIKE N'%SuperSocketNetLib%';  

How to select a column name with a space in MySQL

Generally the first step is to not do that in the first place, but if this is already done, then you need to resort to properly quoting your column names:

SELECT `Business Name` FROM annoying_table

Usually these sorts of things are created by people who have used something like Microsoft Access and always use a GUI to do their thing.

Read only file system on Android

As chen-xing mentioned the simplest way is:

adb reboot

But for me I had to change my settings first:

Settings ? Developer options ? Root access

Make sure ADB has Root access:

enter image description here

How to hide only the Close (x) button?

Well you can hide the close button by changing the FormBorderStyle from the properties section or programmatically in the constructor using:

public Form1()
{
InitializeComponent();
this.FormBorderStyle = FormBorderStyle.None;
}

then you create a menu strip item to exit the application.

cheers

The listener supports no services

You need to add your ORACLE_HOME definition in your listener.ora file. Right now its not registered with any ORACLE_HOME.

Sample listener.ora

abc =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = abc.kma.com)(PORT = 1521))
    )
  )

SID_LIST_abc =
  (SID_LIST =
    (SID_DESC =
      (ORACLE_HOME= /abc/DbTier/11.2.0)
      (SID_NAME = abc)
    )
  )

Oracle (ORA-02270) : no matching unique or primary key for this column-list error

The ORA-2270 error is a straightforward logical error: it happens when the columns we list in the foreign key do not match a primary key or unique constraint on the parent table. Common reasons for this are

  • the parent lacks a PRIMARY KEY or UNIQUE constraint altogether
  • the foreign key clause references the wrong column in the parent table
  • the parent table's constraint is a compound key and we haven't referenced all the columns in the foreign key statement.

Neither appears to be the case in your posted code. But that's a red herring, because your code does not run as you have posted it. Judging from the previous edits I presume you are not posting your actual code but some simplified example. Unfortunately in the process of simplification you have eradicated whatever is causing the ORA-2270 error.

SQL> CREATE TABLE JOB
 (
   ID       NUMBER NOT NULL ,
   USERID   NUMBER,
   CONSTRAINT B_PK PRIMARY KEY ( ID ) ENABLE
 );  2    3    4    5    6  

Table created.

SQL> CREATE TABLE USER
 (
   ID       NUMBER NOT NULL ,
   CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
 );  2    3    4    5  
CREATE TABLE USER
             *
ERROR at line 1:
ORA-00903: invalid table name


SQL> 

That statement failed because USER is a reserved keyword so we cannot name a table USER. Let's fix that:

SQL> 1
  1* CREATE TABLE USER
SQL> a s
  1* CREATE TABLE USERs
SQL> l
  1  CREATE TABLE USERs
  2   (
  3     ID       NUMBER NOT NULL ,
  4     CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
  5*  )
SQL> r
  1  CREATE TABLE USERs
  2   (
  3     ID       NUMBER NOT NULL ,
  4     CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
  5*  )

Table created.

SQL> Alter Table JOB ADD CONSTRAINT FK_USERID FOREIGN KEY(USERID) REFERENCES USERS(ID);   

Table altered.

SQL> 

And lo! No ORA-2270 error.

Alas, there's not much we can do here to help you further. You have a bug in your code. You can post your code here and one of us can spot your mistake. Or you can check your own code and discover it for yourself.


Note: an earlier version of the code defined HOB.USERID as VARCHAR2(20). Because USER.ID is defined as a NUMBER the attempt to create a foreign key would have hurl a different error:

ORA-02267: column type incompatible with referenced column type

An easy way to avoid mismatches is to use foreign key syntax to default the datatype of the column:

CREATE TABLE USERs
 (
   ID    number NOT NULL ,
   CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
 );

CREATE TABLE JOB
 (
   ID       NUMBER NOT NULL ,
   USERID   constraint FK_USERID references users,
   CONSTRAINT B_PK PRIMARY KEY ( ID ) ENABLE
 );

Programmatically change input type of the EditText from PASSWORD to NORMAL & vice versa

I would remove android:inputType="textPassword" from your layout. That is why it is switching back to password when the orientation changes. Because each time the orientation changes the view is being recreated.

As for the first problem try this:

String text = password.getText();
password.setText("");
password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
password.setText(text);

basically emptying out the text before you change the input type and then add it back.

How do we update URL or query strings using javascript/jQuery without reloading the page?

Yes

document.location is the normal way.

However document.location is effectively the same as window.location, except for window.location is a bit more supported in older browsers so may be the prefferable choice.

Check out this thread on SO for more info:

What's the difference between window.location and document.location in JavaScript?

How can I compare strings in C using a `switch` statement?

If you mean, how to write something similar to this:

// switch statement
switch (string) {
  case "B1": 
    // do something
    break;
  /* more case "xxx" parts */
}

Then the canonical solution in C is to use an if-else ladder:

if (strcmp(string, "B1") == 0) 
{
  // do something
} 
else if (strcmp(string, "xxx") == 0)
{
  // do something else
}
/* more else if clauses */
else /* default: */
{
}

PhoneGap Eclipse Issue - eglCodecCommon glUtilsParamSize: unknow param errors

I Get the same message, when using Intel XHAM emulator (instead of ARM) and have "Use Host GPU" option enabled. I belive when you disable it, it goes away.

How can I de-install a Perl module installed via `cpan`?

You can't. There isn't a feature in my CPAN client to do such a thing. We were talking about how we might do something like that at this weekend's Perl QA Workshop, but it's generally hard for all the reasons that Ether mentioned.

Linear regression with matplotlib / numpy

This code:

from scipy.stats import linregress

linregress(x,y) #x and y are arrays or lists.

gives out a list with the following:

slope : float
slope of the regression line
intercept : float
intercept of the regression line
r-value : float
correlation coefficient
p-value : float
two-sided p-value for a hypothesis test whose null hypothesis is that the slope is zero
stderr : float
Standard error of the estimate

Source

Creating a new column based on if-elif-else condition

When you have multiple if conditions, numpy.select is the way to go:

In [4102]: import numpy as np
In [4098]: conditions = [df.A.eq(df.B), df.A.gt(df.B), df.A.lt(df.B)]
In [4096]: choices = [0, 1, -1]

In [4100]: df['C'] = np.select(conditions, choices)

In [4101]: df
Out[4101]: 
   A  B  C
a  2  2  0
b  3  1  1
c  1  3 -1

Java: How to stop thread?

The recommended way will be to build this into the thread. So no you can't (or rather shouldn't) kill the thread from outside.

Have the thread check infrequently if it is required to stop. (Instead of blocking on a socket until there is data. Use a timeout and every once in a while check if the user indicated wanting to stop)

ssl.SSLError: tlsv1 alert protocol version

I believe TLSV1_ALERT_PROTOCOL_VERSION is alerting you that the server doesn't want to talk TLS v1.0 to you. Try to specify TLS v1.2 only by sticking in these lines:

import ssl
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)

# Create HTTPS connection
c = HTTPSConnection("0.0.0.0", context=context)

Note, you may need sufficiently new versions of Python (2.7.9+ perhaps?) and possibly OpenSSL (I have "OpenSSL 1.0.2k 26 Jan 2017" and the above seems to work, YMMV)

PostgreSQL - query from bash script as database user 'postgres'

Try this one:

#!/bin/bash
psql -U postgres -d database_name -c "SELECT c_defaults  FROM user_info WHERE c_uid = 'testuser'"

Or using su:

#!/bin/bash
su -c "psql -d database_name -c \"SELECT c_defaults  FROM user_info WHERE c_uid = 'testuser'\"" postgres

And also sudo:

#!/bin/bash
sudo -u postgres -H -- psql -d database_name -c "SELECT c_defaults  FROM user_info WHERE c_uid = 'testuser'"

Split a string by a delimiter in python

You may be interested in the csv module, which is designed for comma-separated files but can be easily modified to use a custom delimiter.

import csv
csv.register_dialect( "myDialect", delimiter = "__", <other-options> )
lines = [ "MATCHES__STRING" ]

for row in csv.reader( lines ):
    ...

Request Monitoring in Chrome

don't know as of which chrome version this is available, but i found a setting 'Console - Log XMLHttpRequests' (clicking on the icon in the bottom right corner of developer tools in chrome on mac)

Closing a Userform with Unload Me doesn't work

It should also be noted that if you have buttons grouped together on your user form that it can link it to a different button in the group despite the one you intended being clicked.

download a file from Spring boot rest service

If you need to download a huge file from the server's file system, then ByteArrayResource can take all Java heap space. In that case, you can use FileSystemResource

DLL load failed error when importing cv2

this happens because the compiler or the interpreter is finding more than one package of the file, delete all the number of same package you have and then keep only one and then try to install. It serves

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

I was getting this warning when I wanted to show a popup (bootstrap modal) on success/failure callback of Ajax request. Additionally setState was not working and my popup modal was not being shown.

Below was my situation-

<Component /> (Containing my Ajax function)
    <ChildComponent />
        <GrandChildComponent /> (Containing my PopupModal, onSuccess callback)

I was calling ajax function of component from grandchild component passing a onSuccess Callback (defined in grandchild component) which was setting state to show popup modal.

I changed it to -

<Component /> (Containing my Ajax function, PopupModal)
    <ChildComponent />
        <GrandChildComponent /> 

Instead I called setState (onSuccess Callback) to show popup modal in component (ajax callback) itself and problem solved.

In 2nd case: component was being rendered twice (I had included bundle.js two times in html).

ES6 modules implementation, how to load a json file

With json-loader installed, now you can simply use:

import suburbs from '../suburbs.json';

or, even more simply:

import suburbs from '../suburbs';

How to append one DataTable to another DataTable

use loop

  for (int i = 0; i < dt1.Rows.Count; i++)
        {      
           dt2.Rows.Add(dt1.Rows[i][0], dt1.Rows[i][1], ...);//you have to insert all Columns...
        }

Checking if type == list in python

Your issue is that you have re-defined list as a variable previously in your code. This means that when you do type(tmpDict[key])==list if will return False because they aren't equal.

That being said, you should instead use isinstance(tmpDict[key], list) when testing the type of something, this won't avoid the problem of overwriting list but is a more Pythonic way of checking the type.

Force IE8 Into IE7 Compatiblity Mode

This can be done in IIS: http://weblogs.asp.net/joelvarty/archive/2009/03/23/force-ie7-compatibility-mode-in-ie8-with-iis-settings.aspx

Read the comments as well: Wednesday, April 01, 2009 8:57 AM by John Moore

A quick follow-up. This worked great for my site as long as I use the IE=EmulateIE7 value. Trying to use the IE=7 resulted in my site essentially hanging when run on IE8.

Regex date validation for yyyy-mm-dd

This will match yyyy-mm-dd and also yyyy-m-d:

^\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])$

Regular expression visualization

If you're looking for an exact match for yyyy-mm-dd then try this

^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$

or use this one if you need to find a date inside a string like The date is 2017-11-30

\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])*

https://regex101.com/r/acvpss/1

What is the difference between char array and char pointer in C?

char* and char[] are different types, but it's not immediately apparent in all cases. This is because arrays decay into pointers, meaning that if an expression of type char[] is provided where one of type char* is expected, the compiler automatically converts the array into a pointer to its first element.

Your example function printSomething expects a pointer, so if you try to pass an array to it like this:

char s[10] = "hello";
printSomething(s);

The compiler pretends that you wrote this:

char s[10] = "hello";
printSomething(&s[0]);

How to set the background image of a html 5 canvas to .png image

You can give the background image in css :

#canvas { background:url(example.jpg) }

it will show you canvas back ground image

How to create a self-signed certificate with OpenSSL

You can do that in one command:

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365

You can also add -nodes (short for no DES) if you don't want to protect your private key with a passphrase. Otherwise it will prompt you for "at least a 4 character" password.

The days parameter (365) you can replace with any number to affect the expiration date. It will then prompt you for things like "Country Name", but you can just hit Enter and accept the defaults.

Add -subj '/CN=localhost' to suppress questions about the contents of the certificate (replace localhost with your desired domain).

Self-signed certificates are not validated with any third party unless you import them to the browsers previously. If you need more security, you should use a certificate signed by a certificate authority (CA).

How to create a .jar file or export JAR in IntelliJ IDEA (like Eclipse Java archive export)?

In intellij8 I was using a specific plugin "Jar Tool" that is configurable and allows to pack a JAR archive.

git: diff between file in local repo and origin

For that I wrote a bash script:

#set -x 
branchname=`git branch | grep -F '*' |  awk '{print $2}'`
echo $branchname
git fetch origin ${branchname}
for file in `git status | awk '{if ($1 == "modified:") print $2;}'`
do
echo "PLEASE CHECK OUT GIT DIFF FOR "$file 
git difftool  FETCH_HEAD $file ;
done

In the above script, I fetch the remote main branch (not necessary its master branch ANY branch) to FETCH_HEAD, then make a list of my modified file only and compare modified files to git difftool.

There are many difftool supported by git, I configured Meld Diff Viewer for good GUI comparison.
From the above script, I have prior knowledge what changes done by other teams in same file, before I follow git stages untrack-->staged-->commit which help me to avoid unnecessary resolve merge conflict with remote team or make new local branch and compare and merge on the main branch.

Re-ordering columns in pandas dataframe based on column name

If you need an arbitrary sequence instead of sorted sequence, you could do:

sequence = ['Q1.1','Q1.2','Q1.3',.....'Q6.1',......]
your_dataframe = your_dataframe.reindex(columns=sequence)

I tested this in 2.7.10 and it worked for me.

flutter run: No connected devices

open the termina in vs-code, write the below commands:

flutter devices

flutter daemon -v

after that connect using cmd

cd (adb folder)

adb tcpip 4455
adb connect 192.168.1.11:4455 (user your device IP)

How to compare two double values in Java?

double a = 1.000001;
double b = 0.000001;

System.out.println( a.compareTo(b) );

Returns:

  • -1 : 'a' is numerically less than 'b'.

  • 0 : 'a' is equal to 'b'.

  • 1 : 'a' is greater than 'b'.

When adding a Javascript library, Chrome complains about a missing source map, why?

I had similar problem when i was trying to work with coco-ssd. I think this problem is caused because of the version. I changed version of tfjs to 0.9.0 and coco-ssd version to 1.1.0 and it worked for me. (you can search for posenet versions on : https://www.jsdelivr.com/package/npm/@tensorflow-models/posenet)

<!-- Load TensorFlow.js-->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]"></script>
<!-- Load the coco-ssd model. -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/[email protected]"</script>

Matching special characters and letters in regex

Add them to the allowed characters, but you'll need to escape some of them, such as -]/\

var pattern = /^[a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/

That way you can remove any individual character you want to disallow.

Also, you want to include the start and end of string placemarkers ^ and $

Update:

As elclanrs understood (and the rest of us didn't, initially), the only special characters needing to be allowed in the pattern are &-._

/^[\w&.\-]+$/

[\w] is the same as [a-zA-Z0-9_]

Though the dash doesn't need escaping when it's at the start or end of the list, I prefer to do it in case other characters are added. Additionally, the + means you need at least one of the listed characters. If zero is ok (ie an empty value), then replace it with a * instead:

/^[\w&.\-]*$/

Creating your own header file in C

#ifndef MY_HEADER_H
# define MY_HEADER_H

//put your function headers here

#endif

MY_HEADER_H serves as a double-inclusion guard.

For the function declaration, you only need to define the signature, that is, without parameter names, like this:

int foo(char*);

If you really want to, you can also include the parameter's identifier, but it's not necessary because the identifier would only be used in a function's body (implementation), which in case of a header (parameter signature), it's missing.

This declares the function foo which accepts a char* and returns an int.

In your source file, you would have:

#include "my_header.h"

int foo(char* name) {
   //do stuff
   return 0;
}

Storing and retrieving datatable from session

this is just as a side note, but generally what you want to do is keep size on the Session and ViewState small. I generally just store IDs and small amounts of packets in Session and ViewState.

for instance if you want to pass large chunks of data from one page to another, you can store an ID in the querystring and use that ID to either get data from a database or a file.

PS: but like I said, this might be totally unrelated to your query :)

Git: Find the most recent common ancestor of two branches

With gitk you can view the two branches graphically:

gitk branch1 branch2

And then it's easy to find the common ancestor in the history of the two branches.

How can I show line numbers in Eclipse?

Update November 2015:

In Eclipse Mars 4.5.1, line numbers are (annoyingly) turned off by default again. Follow the below instructions to enable it.


Update December 2013:

Lars Vogel just published on his blog:

Line numbers are default in Eclipse SDK Luna (4.4) as of today

(December 10, 2013)

We conducted a user survey if users want to have line numbers activated in text editors in the Eclipse IDE by default.
The response was very clear:

YES : 80.07% (1852 responses)
NO  : 19.93% (461 responses)
Total  : 2313
Skipped:   15

With Bug 421313, Review - Line number should be activated by default, we enabled it for the Eclipse SDK build, I assume other Eclipse packages will follow.


Update August 2014

Line number default length is now 120 (instead of 80) for Eclipse Mars 4.5M1.
See "How to customize Eclipse's text editor code formating".


Original answer (March 2009)

To really have it by default, you can write a script which ensure, before launching eclipse, that:
[workspace]\.metadata\.plugins\org.eclipse.core.runtime\.settings\org.eclipse.ui.editors.prefs does contain:

lineNumberRuler=true

(with [workspace] being the root directory of your eclipse workspace)
Then eclipse will be opened with "line numbers shown 'by default' "


Otherwise, you can also type 'CTRL+1' and then "line", which will give you access to the command "Show line numbers"
(that will switch to option "show line numbers" in the text editors part of the option.

Or you can just type "numb" in Windows Preferences to access to the Text Editor part:

show line number

Picture from "How to display line numbers in Eclipse" of blog "Mkyong.com"

"This operation requires IIS integrated pipeline mode."

Press F4 in your Project for the property window. Then change the pipeline mode

enter image description here

java.lang.OutOfMemoryError: Java heap space in Maven

In order to resolve java.lang.OutOfMemoryError: Java heap space in Maven, try to configure below configuration in pom

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>${maven-surefire-plugin.version}</version>
     <configuration>
        <verbose>true</verbose>
        <fork>true</fork>
        <argLine>-XX:MaxPermSize=500M</argLine>
    </configuration>
</plugin>

Get text from DataGridView selected cells

or, we can use something like this

dim i = dgv1.CurrentCellAddress.X
dim j = dgv1.CurrentCellAddress.Y
MsgBox(dgv1.Item(i,j).Value.ToString())

Fetching data from MySQL database to html dropdown list

What you are asking is pretty straight forward

  1. execute query against your db to get resultset or use API to get the resultset

  2. loop through the resultset or simply the result using php

  3. In each iteration simply format the output as an element

the following refernce should help

HTML option tag

Getting Datafrom MySQL database

hope this helps :)

Update MongoDB field using value of another field

Regarding this answer, the snapshot function is deprecated in version 3.6, according to this update. So, on version 3.6 and above, it is possible to perform the operation this way:

db.person.find().forEach(
    function (elem) {
        db.person.update(
            {
                _id: elem._id
            },
            {
                $set: {
                    name: elem.firstname + ' ' + elem.lastname
                }
            }
        );
    }
);

How do I cancel an HTTP fetch() request?

This works in browser and nodejs Live browser demo

const cpFetch= require('cp-fetch');
const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=3s';
 
const chain = cpFetch(url, {timeout: 10000})
    .then(response => response.json())
    .then(data => console.log(`Done: `, data), err => console.log(`Error: `, err))
 
setTimeout(()=> chain.cancel(), 1000); // abort the request after 1000ms 

How to do something to each file in a directory with a batch script

Command line usage:

for /f %f in ('dir /b c:\') do echo %f

Batch file usage:

for /f %%f in ('dir /b c:\') do echo %%f

Update: if the directory contains files with space in the names, you need to change the delimiter the for /f command is using. for example, you can use the pipe char.

for /f "delims=|" %%f in ('dir /b c:\') do echo %%f

Update 2: (quick one year and a half after the original answer :-)) If the directory name itself has a space in the name, you can use the usebackq option on the for:

for /f "usebackq delims=|" %%f in (`dir /b "c:\program files"`) do echo %%f

And if you need to use output redirection or command piping, use the escape char (^):

for /f "usebackq delims=|" %%f in (`dir /b "c:\program files" ^| findstr /i microsoft`) do echo %%f

What is the JavaScript version of sleep()?

To summarize (like it has been said in previous answers):

There is no built-in sleep function in JavaScript. You should use setTimeout or setInterval to achieve a similar effect.

If you really wanted to, you could simulate sleep functionality with a for loop such as the one shown in the original question, but that would make your CPU work like crazy. Inside a Web Worker an alternative solution would be to make a synchronous XMLHttpRequest to a non-responsive IP and set a proper timeout. This would avoid the CPU utilization problem. Here's a code example:

_x000D_
_x000D_
// Works only inside a web worker_x000D_
_x000D_
function sleep(milliseconds) {_x000D_
 var req = new XMLHttpRequest();_x000D_
 req.open("GET", "http://192.0.2.0/", false);_x000D_
 req.timeout = milliseconds;_x000D_
 try {_x000D_
  req.send();_x000D_
 } catch (ex) {_x000D_
  _x000D_
 }_x000D_
}_x000D_
_x000D_
console.log('Sleeping for 1 second...');_x000D_
sleep(1000);_x000D_
console.log('Slept!');_x000D_
_x000D_
console.log('Sleeping for 5 seconds...')_x000D_
sleep(5000);_x000D_
console.log('Slept!');
_x000D_
_x000D_
_x000D_

How do I download a binary file over HTTP?

Following solutions will first read the whole content to memory before writing it to disc (for more i/o efficient solutions look at the other answers).

You can use open-uri, which is a one liner

require 'open-uri'
content = open('http://example.com').read

Or by using net/http

require 'net/http'
File.write("file_name", Net::HTTP.get(URI.parse("http://url.com")))

-XX:MaxPermSize with or without -XX:PermSize

-XX:PermSize specifies the initial size that will be allocated during startup of the JVM. If necessary, the JVM will allocate up to -XX:MaxPermSize.

How do I see if Wi-Fi is connected on Android?

Try

wifiManager.getConnectionInfo().getIpAddress()

This returns 0 until the device has a usable connection (on my machine, a Samsung SM-T280, Android 5.1.1).

Call child method from parent

I'm using useEffect hook to overcome the headache of doing all this so now I pass a variable down to child like this:

<ParentComponent>
 <ChildComponent arbitrary={value} />
</ParentComponent>
useEffect(() => callTheFunctionToBeCalled(value) , [value]);

What is *.o file?

It is important to note that object files are assembled to binary code in a format that is relocatable. This is a form which allows the assembled code to be loaded anywhere into memory for use with other programs by a linker.

Instructions that refer to labels will not yet have an address assigned for these labels in the .o file.

These labels will be written as '0' and the assembler creates a relocation record for these unknown addresses. When the file is linked and output to an executable the unknown addresses are resolved and the program can be executed.

You can use the nm tool on an object file to list the symbols defined in a .o file.

How to check whether a int is not null or empty?

I think you can initialize the variables a value like -1, because if the int type variables is not initialized it can't be used. When you want to check if it is not the value you want you can check if it is -1.

Use PPK file in Mac Terminal to connect to remote connection over SSH

You can ssh directly from the Terminal on Mac, but you need to use a .PEM key rather than the putty .PPK key. You can use PuttyGen on Windows to convert from .PEM to .PPK, I'm not sure about the other way around though.

You can also convert the key using putty for Mac via port or brew:

sudo port install putty

or

brew install putty

This will also install puttygen. To get puttygen to output a .PEM file:

puttygen privatekey.ppk -O private-openssh -o privatekey.pem

Once you have the key, open a terminal window and:

ssh -i privatekey.pem [email protected]

The private key must have tight security settings otherwise SSH complains. Make sure only the user can read the key.

chmod go-rw privatekey.pem

Post multipart request with Android SDK

I highly recommend Loopj.

I have successfully used it to upload multiple files at once, including different mime types. Simply do this:

File myVideo = new File("/path/to/myvideo.mp4");
File myPic = new File("/path/to/mypic.jpg");
RequestParams params = new RequestParams();
try {
  params.put("profile_picture", myPic);
  params.put("my_video", myVideo);
} catch(FileNotFoundException e) {}

For large or many files you might have to increase the timeout amount else the default timeout is used which might be too short:

client.setTimeout(500000) //make this the appropriate timeout in milliseconds

Please see this links for a full description of loopj and how to use it, by far the easiest async http library I have come across:

http://loopj.com/android-async-http/ http://loopj.com/android-async-http/doc/com/loopj/android/http/AsyncHttpClient.html

Return multiple values to a method caller

You can use three different ways

1. ref / out parameters

using ref:

static void Main(string[] args)
{
    int a = 10;
    int b = 20;
    int add = 0;
    int multiply = 0;
    Add_Multiply(a, b, ref add, ref multiply);
    Console.WriteLine(add);
    Console.WriteLine(multiply);
}

private static void Add_Multiply(int a, int b, ref int add, ref int multiply)
{
    add = a + b;
    multiply = a * b;
}

using out:

static void Main(string[] args)
{
    int a = 10;
    int b = 20;
    int add;
    int multiply;
    Add_Multiply(a, b, out add, out multiply);
    Console.WriteLine(add);
    Console.WriteLine(multiply);
}

private static void Add_Multiply(int a, int b, out int add, out int multiply)
{
    add = a + b;
    multiply = a * b;
}

2. struct / class

using struct:

struct Result
{
    public int add;
    public int multiply;
}
static void Main(string[] args)
{
    int a = 10;
    int b = 20;
    var result = Add_Multiply(a, b);
    Console.WriteLine(result.add);
    Console.WriteLine(result.multiply);
}

private static Result Add_Multiply(int a, int b)
{
    var result = new Result
    {
        add = a * b,
        multiply = a + b
    };
    return result;
}

using class:

class Result
{
    public int add;
    public int multiply;
}
static void Main(string[] args)
{
    int a = 10;
    int b = 20;
    var result = Add_Multiply(a, b);
    Console.WriteLine(result.add);
    Console.WriteLine(result.multiply);
}

private static Result Add_Multiply(int a, int b)
{
    var result = new Result
    {
        add = a * b,
        multiply = a + b
    };
    return result;
}

3. Tuple

Tuple class

static void Main(string[] args)
{
    int a = 10;
    int b = 20;
    var result = Add_Multiply(a, b);
    Console.WriteLine(result.Item1);
    Console.WriteLine(result.Item2);
}

private static Tuple<int, int> Add_Multiply(int a, int b)
{
    var tuple = new Tuple<int, int>(a + b, a * b);
    return tuple;
}

C# 7 Tuples

static void Main(string[] args)
{
    int a = 10;
    int b = 20;
    (int a_plus_b, int a_mult_b) = Add_Multiply(a, b);
    Console.WriteLine(a_plus_b);
    Console.WriteLine(a_mult_b);
}

private static (int a_plus_b, int a_mult_b) Add_Multiply(int a, int b)
{
    return(a + b, a * b);
}

How to insert a line break in a SQL Server VARCHAR/NVARCHAR string

I got here because I was concerned that cr-lfs that I specified in C# strings were not being shown in SQl Server Management Studio query responses.

It turns out, they are there, but are not being displayed.

To "see" the cr-lfs, use the print statement like:

declare @tmp varchar(500)    
select @tmp = msgbody from emailssentlog where id=6769;
print @tmp

Import-Module : The specified module 'activedirectory' was not loaded because no valid module file was found in any module directory

This may be an old post, but if anyone is still facing this issue after trying all the above mentioned steps, ensure whether the default path of PowerShell module is specified under the "PSModulePath" environment variable.

The default path should be "%SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\"

Adding options to a <select> using jQuery?

Based on dule's answer for appending a collection of items, a one-liner for...in will also work wonders:

_x000D_
_x000D_
let cities = {'ny':'New York','ld':'London','db':'Dubai','pk':'Beijing','tk':'Tokyo','nd':'New Delhi'};_x000D_
_x000D_
for(let c in cities){$('#selectCity').append($('<option>',{value: c,text: cities[c]}))}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>_x000D_
<select  id="selectCity"></select>
_x000D_
_x000D_
_x000D_

Both object values and indexes are assigned to the options. This solution works even in the old jQuery (v1.4)!

python convert list to dictionary

If you are still thinking what the! You would not be alone, its actually not that complicated really, let me explain.

How to turn a list into a dictionary using built-in functions only

We want to turn the following list into a dictionary using the odd entries (counting from 1) as keys mapped to their consecutive even entries.

l = ["a", "b", "c", "d", "e"]

dict()

To create a dictionary we can use the built in dict function for Mapping Types as per the manual the following methods are supported.

dict(one=1, two=2)
dict({'one': 1, 'two': 2})
dict(zip(('one', 'two'), (1, 2)))
dict([['two', 2], ['one', 1]])

The last option suggests that we supply a list of lists with 2 values or (key, value) tuples, so we want to turn our sequential list into:

l = [["a", "b"], ["c", "d"], ["e",]]

We are also introduced to the zip function, one of the built-in functions which the manual explains:

returns a list of tuples, where the i-th tuple contains the i-th element from each of the arguments

In other words if we can turn our list into two lists a, c, e and b, d then zip will do the rest.

slice notation

Slicings which we see used with Strings and also further on in the List section which mainly uses the range or short slice notation but this is what the long slice notation looks like and what we can accomplish with step:

>>> l[::2]
['a', 'c', 'e']

>>> l[1::2]
['b', 'd']

>>> zip(['a', 'c', 'e'], ['b', 'd'])
[('a', 'b'), ('c', 'd')]

>>> dict(zip(l[::2], l[1::2]))
{'a': 'b', 'c': 'd'}

Even though this is the simplest way to understand the mechanics involved there is a downside because slices are new list objects each time, as can be seen with this cloning example:

>>> a = [1, 2, 3]
>>> b = a
>>> b
[1, 2, 3]

>>> b is a
True

>>> b = a[:]
>>> b
[1, 2, 3]

>>> b is a
False

Even though b looks like a they are two separate objects now and this is why we prefer to use the grouper recipe instead.

grouper recipe

Although the grouper is explained as part of the itertools module it works perfectly fine with the basic functions too.

Some serious voodoo right? =) But actually nothing more than a bit of syntax sugar for spice, the grouper recipe is accomplished by the following expression.

*[iter(l)]*2

Which more or less translates to two arguments of the same iterator wrapped in a list, if that makes any sense. Lets break it down to help shed some light.

zip for shortest

>>> l*2
['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e']

>>> [l]*2
[['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e']]

>>> [iter(l)]*2
[<listiterator object at 0x100486450>, <listiterator object at 0x100486450>]

>>> zip([iter(l)]*2)
[(<listiterator object at 0x1004865d0>,),(<listiterator object at 0x1004865d0>,)]

>>> zip(*[iter(l)]*2)
[('a', 'b'), ('c', 'd')]

>>> dict(zip(*[iter(l)]*2))
{'a': 'b', 'c': 'd'}

As you can see the addresses for the two iterators remain the same so we are working with the same iterator which zip then first gets a key from and then a value and a key and a value every time stepping the same iterator to accomplish what we did with the slices much more productively.

You would accomplish very much the same with the following which carries a smaller What the? factor perhaps.

>>> it = iter(l)     
>>> dict(zip(it, it))
{'a': 'b', 'c': 'd'}

What about the empty key e if you've noticed it has been missing from all the examples which is because zip picks the shortest of the two arguments, so what are we to do.

Well one solution might be adding an empty value to odd length lists, you may choose to use append and an if statement which would do the trick, albeit slightly boring, right?

>>> if len(l) % 2:
...     l.append("")

>>> l
['a', 'b', 'c', 'd', 'e', '']

>>> dict(zip(*[iter(l)]*2))
{'a': 'b', 'c': 'd', 'e': ''}

Now before you shrug away to go type from itertools import izip_longest you may be surprised to know it is not required, we can accomplish the same, even better IMHO, with the built in functions alone.

map for longest

I prefer to use the map() function instead of izip_longest() which not only uses shorter syntax doesn't require an import but it can assign an actual None empty value when required, automagically.

>>> l = ["a", "b", "c", "d", "e"]
>>> l
['a', 'b', 'c', 'd', 'e']

>>> dict(map(None, *[iter(l)]*2))
{'a': 'b', 'c': 'd', 'e': None} 

Comparing performance of the two methods, as pointed out by KursedMetal, it is clear that the itertools module far outperforms the map function on large volumes, as a benchmark against 10 million records show.

$ time python -c 'dict(map(None, *[iter(range(10000000))]*2))'
real    0m3.755s
user    0m2.815s
sys     0m0.869s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(10000000))]*2, fillvalue=None))'
real    0m2.102s
user    0m1.451s
sys     0m0.539s

However the cost of importing the module has its toll on smaller datasets with map returning much quicker up to around 100 thousand records when they start arriving head to head.

$ time python -c 'dict(map(None, *[iter(range(100))]*2))'
real    0m0.046s
user    0m0.029s
sys     0m0.015s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(100))]*2, fillvalue=None))'
real    0m0.067s
user    0m0.042s
sys     0m0.021s

$ time python -c 'dict(map(None, *[iter(range(100000))]*2))'
real    0m0.074s
user    0m0.050s
sys     0m0.022s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(100000))]*2, fillvalue=None))'
real    0m0.075s
user    0m0.047s
sys     0m0.024s

See nothing to it! =)

nJoy!

Calling a JSON API with Node.js

Another solution is to user axios:

npm install axios

Code will be like:

const url = `${this.env.someMicroservice.address}/v1/my-end-point`;

const { data } = await axios.get<MyInterface>(url, {
  auth: {
    username: this.env.auth.user,
    password: this.env.auth.pass
  }
});

return data;

Check the current number of connections to MongoDb

db.serverStatus() gives no of connections opend and avail but not shows the connections from which client. For more info you can use this command sudo lsof | grep mongod | grep TCP. I need it when i did replication and primary node have many client connection greater than secondary.

$ sudo lsof | grep mongod | grep TCP
mongod    5733             Al    6u     IPv4 0x08761278       0t0       TCP *:28017 (LISTEN)
mongod    5733             Al    7u     IPv4 0x07c7eb98       0t0       TCP *:27017 (LISTEN)
mongod    5733             Al    9u     IPv4 0x08761688       0t0       TCP 192.168.1.103:27017->192.168.1.103:64752 (ESTABLISHED)
mongod    5733             Al   12u     IPv4 0x08761a98       0t0       TCP 192.168.1.103:27017->192.168.1.103:64754 (ESTABLISHED)
mongod    5733             Al   13u     IPv4 0x095fa748       0t0       TCP 192.168.1.103:27017->192.168.1.103:64770 (ESTABLISHED)
mongod    5733             Al   14u     IPv4 0x095f86c8       0t0       TCP 192.168.1.103:27017->192.168.1.103:64775 (ESTABLISHED)
mongod    5733             Al   17u     IPv4 0x08764748       0t0       TCP 192.168.1.103:27017->192.168.1.103:64777 (ESTABLISHED)

This shows that I currently have five connections open to the MongoDB port (27017) on my computer. In my case I'm connecting to MongoDB from a Scalatra server, and I'm using the MongoDB Casbah driver, but you'll see the same lsof TCP connections regardless of the client used (as long as they're connecting using TCP/IP).

How to make modal dialog in WPF?

Did you try showing your window using the ShowDialog method?

Don't forget to set the Owner property on the dialog window to the main window. This will avoid weird behavior when Alt+Tabbing, etc.

Pointers, smart pointers or shared pointers?

To avoid memory leaks you may use smart pointers whenever you can. There are basically 2 different types of smart pointers in C++

  • Reference counted (e.g. boost::shared_ptr / std::tr1:shared_ptr)
  • non reference counted (e.g. boost::scoped_ptr / std::auto_ptr)

The main difference is that reference counted smart pointers can be copied (and used in std:: containers) while scoped_ptr cannot. Non reference counted pointers have almost no overhead or no overhead at all. Reference counting always introduces some kind of overhead.

(I suggest to avoid auto_ptr, it has some serious flaws if used incorrectly)

c# Image resizing to different size while preserving aspect ratio

This should do it.

private void resizeImage(string path, string originalFilename, 
                     /* note changed names */
                     int canvasWidth, int canvasHeight, 
                     /* new */
                     int originalWidth, int originalHeight)
{
    Image image = Image.FromFile(path + originalFilename);

    System.Drawing.Image thumbnail = 
        new Bitmap(canvasWidth, canvasHeight); // changed parm names
    System.Drawing.Graphics graphic = 
                 System.Drawing.Graphics.FromImage(thumbnail);

    graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
    graphic.SmoothingMode = SmoothingMode.HighQuality;
    graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
    graphic.CompositingQuality = CompositingQuality.HighQuality;

    /* ------------------ new code --------------- */

    // Figure out the ratio
    double ratioX = (double) canvasWidth / (double) originalWidth;
    double ratioY = (double) canvasHeight / (double) originalHeight;
    // use whichever multiplier is smaller
    double ratio = ratioX < ratioY ? ratioX : ratioY;

    // now we can get the new height and width
    int newHeight = Convert.ToInt32(originalHeight * ratio);
    int newWidth = Convert.ToInt32(originalWidth * ratio);

    // Now calculate the X,Y position of the upper-left corner 
    // (one of these will always be zero)
    int posX = Convert.ToInt32((canvasWidth - (originalWidth * ratio)) / 2);
    int posY = Convert.ToInt32((canvasHeight - (originalHeight * ratio)) / 2);

    graphic.Clear(Color.White); // white padding
    graphic.DrawImage(image, posX, posY, newWidth, newHeight);

    /* ------------- end new code ---------------- */

    System.Drawing.Imaging.ImageCodecInfo[] info =
                     ImageCodecInfo.GetImageEncoders();
    EncoderParameters encoderParameters;
    encoderParameters = new EncoderParameters(1);
    encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality,
                     100L);            
    thumbnail.Save(path + newWidth + "." + originalFilename, info[1], 
                     encoderParameters);
}

Edited to add:

Those who want to improve this code should put it in the comments, or a new answer. Don't edit this code directly.

How to get full width in body element

You can use CSS to do it for example

<style>
html{
    width:100%;
    height:100%;
}
body{
    width:100%;
    height:100%;
    background-color:#DDD;
}
</style>

How to remove package using Angular CLI?

It's an open issue #900 on GitHub, unfortunately at this point of time it looks that in Angular CLI there's nothing like ng remove/rm/..., only using npm uninstall DEPENDENCY is the current workaround.

Bootstrap change carousel height

The following should work

.carousel .item {
  height: 300px;
}

.item img {
    position: absolute;
    top: 0;
    left: 0;
    min-height: 300px;
}

JSFille for reference.

How SQL query result insert in temp table?

Suppose your existing reporting query is

Select EmployeeId,EmployeeName 
from Employee 
Where EmployeeId>101 order by EmployeeName

and you have to save this data into temparory table then you query goes to

Select EmployeeId,EmployeeName 
into #MyTempTable 
from Employee 
Where EmployeeId>101 order by EmployeeName  

Incrementing a date in JavaScript

Two methods:

1:

var a = new Date()
// no_of_days is an integer value
var b = new Date(a.setTime(a.getTime() + no_of_days * 86400000)

2: Similar to the previous method

var a = new Date()
// no_of_days is an integer value
var b = new Date(a.setDate(a.getDate() + no_of_days)