Programs & Examples On #Diaspora

free personal web server social network platform

What does 'git remote add upstream' help achieve?

This is useful when you have your own origin which is not upstream. In other words, you might have your own origin repo that you do development and local changes in and then occasionally merge upstream changes. The difference between your example and the highlighted text is that your example assumes you're working with a clone of the upstream repo directly. The highlighted text assumes you're working on a clone of your own repo that was, presumably, originally a clone of upstream.

dictionary update sequence element #0 has length 3; 2 is required

This error raised up because you trying to update dict object by using a wrong sequence (list or tuple) structure.

cash_id.create(cr, uid, lines,context=None) trying to convert lines into dict object:

(0, 0, {
    'name': l.name,
    'date': l.date,
    'amount': l.amount,
    'type': l.type,
    'statement_id': exp.statement_id.id,
    'account_id': l.account_id.id,
    'account_analytic_id': l.analytic_account_id.id,
    'ref': l.ref,
    'note': l.note,
    'company_id': l.company_id.id
})

Remove the second zero from this tuple to properly convert it into a dict object.

To test it your self, try this into python shell:

>>> l=[(0,0,{'h':88})]
>>> a={}
>>> a.update(l)

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    a.update(l)
ValueError: dictionary update sequence element #0 has length 3; 2 is required

>>> l=[(0,{'h':88})]
>>> a.update(l)

Unable to install packages in latest version of RStudio and R Version.3.1.1

Not 100% certain that you have the same problem, but I found out the hard way that my job blocks each mirror site option that was offered and I was getting errors like this:

Installing package into ‘/usr/lib64/R/library’
(as ‘lib’ is unspecified)
--- Please select a CRAN mirror for use in this session ---
Error in download.file(url, destfile = f, quiet = TRUE) : 
  unsupported URL scheme
Warning: unable to access index for repository https://rweb.crmda.ku.edu/cran/src/contrib
Warning message:
package ‘ggplot2’ is not available (for R version 3.2.2)

Workaround (I am using CentOS)...

install.packages('package_name', dependencies=TRUE, repos='http://cran.rstudio.com/')

I hope this saves someone hours of frustration.

How do I add a new sourceset to Gradle?

I gather the documentation wasn't great back in 2012 when this question was asked, but for anyone reading this in 2020+: There's now a whole section in the docs about how to add a source set for integration tests. You really should read it instead of copy/pasting code snippets here and banging your head against the wall trying to figure out why an answer from 2012-2016 doesn't quite work.

The answer is most likely simple but more nuanced than you may think, and the exact code you'll need is likely to be different from the code I'll need. For example, do you want your integration tests to use the same dependencies as your unit tests?

LAST_INSERT_ID() MySQL

You could store the last insert id in a variable :

INSERT INTO table1 (title,userid) VALUES ('test', 1); 
SET @last_id_in_table1 = LAST_INSERT_ID();
INSERT INTO table2 (parentid,otherid,userid) VALUES (@last_id_in_table1, 4, 1);    

Or get the max id frm table1

INSERT INTO table1 (title,userid) VALUES ('test', 1); 
INSERT INTO table2 (parentid,otherid,userid) VALUES (LAST_INSERT_ID(), 4, 1); 
SELECT MAX(id) FROM table1;   

How can I read an input string of unknown length?

Take a character pointer to store required string.If you have some idea about possible size of string then use function

char *fgets (char *str, int size, FILE* file);`

else you can allocate memory on runtime too using malloc() function which dynamically provides requested memory.

Git undo local branch delete

If you deleted a branch via Source Tree, you could easily find the SHA1 of the deleted branch by going to View -> Show Command History.

It should have the next format:

Deleting branch ...
...
Deleted branch %NAME% (was %SHA1%)
...

Then just follow the original answer.

git branch branchName <sha1>

How to re-index all subarray elements of a multidimensional array?

Here you can see the difference between the way that deceze offered comparing to the simple array_values approach:

The Array:

$array['a'][0] = array('x' => 1, 'y' => 2, 'z' => 3);
$array['a'][5] = array('x' => 4, 'y' => 5, 'z' => 6);

$array['b'][1] = array('x' => 7, 'y' => 8, 'z' => 9);
$array['b'][7] = array('x' => 10, 'y' => 11, 'z' => 12);

In deceze way, here is your output:

$array = array_map('array_values', $array);
print_r($array);

/* Output */

Array
(
    [a] => Array
        (
            [0] => Array
                (
                    [x] => 1
                    [y] => 2
                    [z] => 3
                )
            [1] => Array
                (
                    [x] => 4
                    [y] => 5
                    [z] => 6
                )
        )
    [b] => Array
        (
            [0] => Array
                (
                    [x] => 7
                    [y] => 8
                    [z] => 9
                )

            [1] => Array
                (
                    [x] => 10
                    [y] => 11
                    [z] => 12
                )
        )
)

And here is your output if you only use array_values function:

$array = array_values($array);
print_r($array);

/* Output */

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [x] => 1
                    [y] => 2
                    [z] => 3
                )
            [5] => Array
                (
                    [x] => 4
                    [y] => 5
                    [z] => 6
                )
        )
    [1] => Array
        (
            [1] => Array
                (
                    [x] => 7
                    [y] => 8
                    [z] => 9
                )
            [7] => Array
                (
                    [x] => 10
                    [y] => 11
                    [z] => 12
                )
        )
)

How can I programmatically generate keypress events in C#?

To produce key events without Windows Forms Context, We can use the following method,

[DllImport("user32.dll")]
public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);

sample code is given below:

const int VK_UP = 0x26; //up key
const int VK_DOWN = 0x28;  //down key
const int VK_LEFT = 0x25;
const int VK_RIGHT = 0x27;
const uint KEYEVENTF_KEYUP = 0x0002;
const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
int press()
{
    //Press the key
    keybd_event((byte)VK_UP, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);
    return 0;
}

List of Virtual Keys are defined here.

To get the complete picture, please use the below link, http://tksinghal.blogspot.in/2011/04/how-to-press-and-hold-keyboard-key.html

GET and POST methods with the same Action name in the same Controller

I like to accept a form post for my POST actions, even if I don't need it. For me it just feels like the right thing to do as you're supposedly posting something.

public class HomeController : Controller
{
    public ActionResult Index()
    {
        //Code...
        return View();
    }

    [HttpPost]
    public ActionResult Index(FormCollection form)
    {
        //Code...
        return View();
    }
}

Checking if a double (or float) is NaN in C++

nan prevention

My answer to this question is don't use retroactive checks for nan. Use preventive checks for divisions of the form 0.0/0.0 instead.

#include <float.h>
float x=0.f ;             // I'm gonna divide by x!
if( !x )                  // Wait! Let me check if x is 0
  x = FLT_MIN ;           // oh, since x was 0, i'll just make it really small instead.
float y = 0.f / x ;       // whew, `nan` didn't appear.

nan results from the operation 0.f/0.f, or 0.0/0.0. nan is a terrible nemesis to the stability of your code that must be detected and prevented very carefully1. The properties of nan that are different from normal numbers:

  • nan is toxic, (5*nan=nan)
  • nan is not equal to anything, not even itself (nan != nan)
  • nan not greater than anything (nan !> 0)
  • nan is not less than anything (nan !< 0)

The last 2 properties listed are counter-logical and will result in odd behavior of code that relies on comparisons with a nan number (the 3rd last property is odd too but you're probably not ever going to see x != x ? in your code (unless you are checking for nan (unreliably))).

In my own code, I noticed that nan values tend to produce difficult to find bugs. (Note how this is not the case for inf or -inf. (-inf < 0) returns TRUE, ( 0 < inf ) returns TRUE, and even (-inf < inf) returns TRUE. So, in my experience, the behavior of the code is often still as desired).

what to do under nan

What you want to happen under 0.0/0.0 must be handled as a special case, but what you do must depend on the numbers you expect to come out of the code.

In the example above, the result of (0.f/FLT_MIN) will be 0, basically. You may want 0.0/0.0 to generate HUGE instead. So,

float x=0.f, y=0.f, z;
if( !x && !y )    // 0.f/0.f case
  z = FLT_MAX ;   // biggest float possible
else
  z = y/x ;       // regular division.

So in the above, if x were 0.f, inf would result (which has pretty good/nondestructive behavior as mentioned above actually).

Remember, integer division by 0 causes a runtime exception. So you must always check for integer division by 0. Just because 0.0/0.0 quietly evaluates to nan doesn't mean you can be lazy and not check for 0.0/0.0 before it happens.

1 Checks for nan via x != x are sometimes unreliable (x != x being stripped out by some optimizing compilers that break IEEE compliance, specifically when the -ffast-math switch is enabled).

MySQL wait_timeout Variable - GLOBAL vs SESSION

Your session status are set once you start a session, and by default, take the current GLOBAL value.

If you disconnected after you did SET @@GLOBAL.wait_timeout=300, then subsequently reconnected, you'd see

SHOW SESSION VARIABLES LIKE "%wait%";

Result: 300

Similarly, at any time, if you did

mysql> SET session wait_timeout=300;

You'd get

mysql> SHOW SESSION VARIABLES LIKE 'wait_timeout';

+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| wait_timeout  | 300   |
+---------------+-------+

android : Error converting byte to dex

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile fileTree(include: 'Parse-*.jar', dir: 'libs')
    compile 'com.android.support:appcompat-v7:23.2.0'
    compile 'com.android.support:cardview-v7:23.2.0'
    compile 'com.android.support:design:24.0.0-alpha1'
    compile "com.google.firebase:firebase-invites:9.2.0"
    compile "com.google.firebase:firebase-ads:9.2.0"
    compile 'com.google.firebase:firebase-database:9.2.0'
    compile 'com.google.firebase:firebase-core:9.2.0'
}

I add the com.google.firebase:firebase-core:9.2.0 line and choose the same version (9.2.0) for all firebase libraries and the issue was solved.

Is Google Play Store supported in avd emulators?

Easiest way: You should create a new emulator, before opening it for the first time follow these 3 easy steps:

1- go to C:\Users[user].android\avd[your virtual device folder] open "config.ini" with text editor like notepad

2- change

"PlayStore.enabled=false" to "PlayStore.enabled=true"

3- change

mage.sysdir.1 = system-images\android-30\google_apis\x86\

to

image.sysdir.1 = system-images\android-30\google_apis_playstore\x86\

How do I use Assert to verify that an exception has been thrown?

MSTest (v2) now has an Assert.ThrowsException function which can be used like this:

Assert.ThrowsException<System.FormatException>(() =>
            {
                Story actual = PersonalSite.Services.Content.ExtractHeader(String.Empty);
            }); 

You can install it with nuget: Install-Package MSTest.TestFramework

How to percent-encode URL parameters in Python?

Python 2

From the docs:

urllib.quote(string[, safe])

Replace special characters in string using the %xx escape. Letters, digits, and the characters '_.-' are never quoted. By default, this function is intended for quoting the path section of the URL.The optional safe parameter specifies additional characters that should not be quoted — its default value is '/'

That means passing '' for safe will solve your first issue:

>>> urllib.quote('/test')
'/test'
>>> urllib.quote('/test', safe='')
'%2Ftest'

About the second issue, there is a bug report about it here. Apparently it was fixed in python 3. You can workaround it by encoding as utf8 like this:

>>> query = urllib.quote(u"Müller".encode('utf8'))
>>> print urllib.unquote(query).decode('utf8')
Müller

By the way have a look at urlencode

Python 3

The same, except replace urllib.quote with urllib.parse.quote.

tar: add all files and directories in current directory INCLUDING .svn and so on

If you really don't want to include top directory in the tarball (and that's generally bad idea):

tar czf workspace.tar.gz -C /path/to/workspace .

Why is processing a sorted array faster than processing an unsorted array?

No doubt some of us would be interested in ways of identifying code that is problematic for the CPU's branch-predictor. The Valgrind tool cachegrind has a branch-predictor simulator, enabled by using the --branch-sim=yes flag. Running it over the examples in this question, with the number of outer loops reduced to 10000 and compiled with g++, gives these results:

Sorted:

==32551== Branches:        656,645,130  (  656,609,208 cond +    35,922 ind)
==32551== Mispredicts:         169,556  (      169,095 cond +       461 ind)
==32551== Mispred rate:            0.0% (          0.0%     +       1.2%   )

Unsorted:

==32555== Branches:        655,996,082  (  655,960,160 cond +  35,922 ind)
==32555== Mispredicts:     164,073,152  (  164,072,692 cond +     460 ind)
==32555== Mispred rate:           25.0% (         25.0%     +     1.2%   )

Drilling down into the line-by-line output produced by cg_annotate we see for the loop in question:

Sorted:

          Bc    Bcm Bi Bim
      10,001      4  0   0      for (unsigned i = 0; i < 10000; ++i)
           .      .  .   .      {
           .      .  .   .          // primary loop
 327,690,000 10,016  0   0          for (unsigned c = 0; c < arraySize; ++c)
           .      .  .   .          {
 327,680,000 10,006  0   0              if (data[c] >= 128)
           0      0  0   0                  sum += data[c];
           .      .  .   .          }
           .      .  .   .      }

Unsorted:

          Bc         Bcm Bi Bim
      10,001           4  0   0      for (unsigned i = 0; i < 10000; ++i)
           .           .  .   .      {
           .           .  .   .          // primary loop
 327,690,000      10,038  0   0          for (unsigned c = 0; c < arraySize; ++c)
           .           .  .   .          {
 327,680,000 164,050,007  0   0              if (data[c] >= 128)
           0           0  0   0                  sum += data[c];
           .           .  .   .          }
           .           .  .   .      }

This lets you easily identify the problematic line - in the unsorted version the if (data[c] >= 128) line is causing 164,050,007 mispredicted conditional branches (Bcm) under cachegrind's branch-predictor model, whereas it's only causing 10,006 in the sorted version.


Alternatively, on Linux you can use the performance counters subsystem to accomplish the same task, but with native performance using CPU counters.

perf stat ./sumtest_sorted

Sorted:

 Performance counter stats for './sumtest_sorted':

  11808.095776 task-clock                #    0.998 CPUs utilized          
         1,062 context-switches          #    0.090 K/sec                  
            14 CPU-migrations            #    0.001 K/sec                  
           337 page-faults               #    0.029 K/sec                  
26,487,882,764 cycles                    #    2.243 GHz                    
41,025,654,322 instructions              #    1.55  insns per cycle        
 6,558,871,379 branches                  #  555.455 M/sec                  
       567,204 branch-misses             #    0.01% of all branches        

  11.827228330 seconds time elapsed

Unsorted:

 Performance counter stats for './sumtest_unsorted':

  28877.954344 task-clock                #    0.998 CPUs utilized          
         2,584 context-switches          #    0.089 K/sec                  
            18 CPU-migrations            #    0.001 K/sec                  
           335 page-faults               #    0.012 K/sec                  
65,076,127,595 cycles                    #    2.253 GHz                    
41,032,528,741 instructions              #    0.63  insns per cycle        
 6,560,579,013 branches                  #  227.183 M/sec                  
 1,646,394,749 branch-misses             #   25.10% of all branches        

  28.935500947 seconds time elapsed

It can also do source code annotation with dissassembly.

perf record -e branch-misses ./sumtest_unsorted
perf annotate -d sumtest_unsorted
 Percent |      Source code & Disassembly of sumtest_unsorted
------------------------------------------------
...
         :                      sum += data[c];
    0.00 :        400a1a:       mov    -0x14(%rbp),%eax
   39.97 :        400a1d:       mov    %eax,%eax
    5.31 :        400a1f:       mov    -0x20040(%rbp,%rax,4),%eax
    4.60 :        400a26:       cltq   
    0.00 :        400a28:       add    %rax,-0x30(%rbp)
...

See the performance tutorial for more details.

connecting to phpMyAdmin database with PHP/MySQL

$db = new mysqli('Server_Name', 'Name', 'password', 'database_name');

Cannot connect to Database server (mysql workbench)

In my case I have just installed MySQL Workbench but after uninstalling MySQL Workbench and installing MySQL installer and is same for both 32 and 64 bit then after it working like a charm. Hope it could be useful.

What is the difference between getText() and getAttribute() in Selenium WebDriver?

<img src="w3schools.jpg" alt="W3Schools.com" width="104" height="142">

In above html tag we have different attributes like src, alt, width and height.

If you want to get the any attribute value from above html tag you have to pass attribute value in getAttribute() method

Syntax:

getAttribute(attributeValue)
getAttribute(src) you get w3schools.jpg
getAttribute(height) you get 142
getAttribute(width) you get 104 

Open Popup window using javascript

Change the window name in your two different calls:

function popitup(url,windowName) {
       newwindow=window.open(url,windowName,'height=200,width=150');
       if (window.focus) {newwindow.focus()}
       return false;
     }

windowName must be unique when you open a new window with same url otherwise the same window will be refreshed.

Select rows with same id but different value in another column

You can simply achieve it by

SELECT *
FROM test
WHERE ARIDNR IN
    (SELECT ARIDNR FROM test
     GROUP BY ARIDNR
     HAVING COUNT(*) > 1)
GROUP BY ARIDNR, LIEFNR;

Thanks.

How to set the java.library.path from Eclipse

the easiest way would to use the eclipse IDE itself. Go to the menu and set build path. Make it point to the JAVA JDK and JRE file path in your directory. afterwards you can check the build path where compiled files are going to be set. in the bin folder by default though. The best thing would be to allow eclipse to handle itself the build path and only to edit it similar to the solution that is given above

Get child Node of another Node, given node name

//xn=list of parent nodes......                
foreach (XmlNode xn in xnList)
{                                           
    foreach (XmlNode child in xn.ChildNodes) 
    {
        if (child.Name.Equals("name")) 
        {
            name = child.InnerText; 
        }
        if (child.Name.Equals("age"))
        {
            age = child.InnerText; 
        }
    }
}

What should I use to open a url instead of urlopen in urllib3

With gazpacho you could pipeline the page straight into a parse-able soup object:

from gazpacho import Soup
url = "http://www.thefamouspeople.com/singers.php"
soup = Soup.get(url)

And run finds on top of it:

soup.find("div")

python pandas dataframe to dictionary

This is my solution:

import pandas as pd
df = pd.read_excel('dic.xlsx')
df_T = df.set_index('id').T
dic = df_T.to_dict('records')
print(dic)

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder"

Please add the following dependencies to pom to resolve this issue.

<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-simple</artifactId>
  <version>1.7.25</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-api</artifactId>
  <version>1.7.25</version>
</dependency>

Removing elements by class name?

Recursive function might solve your problem like below

removeAllByClassName = function (className) {
    function findToRemove() {
        var sets = document.getElementsByClassName(className);
        if (sets.length > 0) {
            sets[0].remove();
            findToRemove();
        }
    }
    findToRemove();
};
//
removeAllByClassName();

Detect if device is iOS

The user-agents on iOS devices say iPhone or iPad in them. I just filter based on those keywords.

Generating random numbers with normal distribution in Excel

Rand() does generate a uniform distribution of random numbers between 0 and 1, but the norminv (or norm.inv) function is taking the uniform distributed Rand() as an input to generate the normally distributed sample set.

How to get the last element of a slice?

Bit less elegant but can also do:

sl[len(sl)-1: len(sl)]

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.testing.models.Account

I have this method for deserializing an XML and converting the type:

public <T> Object deserialize(String xml, Class objClass ,TypeReference<T> typeReference ) throws IOException {
    XmlMapper xmlMapper = new XmlMapper();
    Object obj = xmlMapper.readValue(xml,objClass);
    return  xmlMapper.convertValue(obj,typeReference );   
}

and this is the call:

List<POJO> pojos = (List<POJO>) MyUtilClass.deserialize(xml, ArrayList.class,new TypeReference< List< POJO >>(){ });

Set EditText cursor color

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">#36f0ff</item>
    <item name="colorPrimaryDark">#007781</item>
    <item name="colorAccent">#000</item>
</style>

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

change t he color of colorAccent in styles.xm, that's it simple

What is parsing in terms that a new programmer would understand?

Simple explanation: Parsing is breaking a block of data into smaller pieces (tokens) by following a set of rules (using delimiters for example), so that this data could be processes piece by piece (managed, analysed, interpreted, transmitted, ets).

Examples: Many applications (like Spreadsheet programs) use CSV (Comma Separated Values) file format to import and export data. CSV format makes it possible for the applications to process this data with a help of a special parser. Web browsers have special parsers for HTML and CSS files. JSON parsers exist. All special file formats must have some parsers designed specifically for them.

How to iterate over the keys and values with ng-repeat in AngularJS?

Here's a working example:

<div class="item item-text-wrap" ng-repeat="(key,value) in form_list">
  <b>{{key}}</b> : {{value}}
</div>

edited

How can I use an ES6 import in Node.js?

You may try esm.

Here is some introduction: esm

SQL SERVER: Get total days between two dates

SQL Server DateDiff

DECLARE @startdate datetime2 = '2007-05-05 12:10:09.3312722';
DECLARE @enddate datetime2 = '2009-05-04 12:10:09.3312722'; 
SELECT DATEDIFF(day, @startdate, @enddate);

Is there a way to create multiline comments in Python?

Using PyCharm IDE.

You can comment and uncomment lines of code using Ctrl+/. Ctrl+/ comments or uncomments the current line or several selected lines with single line comments ({# in Django templates, or # in Python scripts). Pressing Ctrl+Shift+/ for a selected block of source code in a Django template surrounds the block with {% comment %} and {% endcomment %} tags.


n = 5
while n > 0:
    n -= 1
    if n == 2:
        break
    print(n)

print("Loop ended.")

Select all lines then press Ctrl + /


# n = 5
# while n > 0:
#     n -= 1
#     if n == 2:
#         break
#     print(n)

# print("Loop ended.")

What is a stack pointer used for in microprocessors?

A stack pointer is a small register that stores the address of the top of stack. It is used for the purpose of pointing address of the top of the stack.

Open page in new window without popup blocking

This is the only one that actually worked for me in all the browsers

let newTab = window.open(); newTab.location.href = url;

How do I use dataReceived event of the SerialPort Port Object in C#?

I was having the very same problem with a modem that had previously worked and then one day just stopped raising the DataReceived event.

The solution in my case, very randomly, was to enable RTS e.g.

sp.RtsEnable = true;

No idea why that worked on this particular bit of kit (not a comms man at all really), nor why it had worked and then stopped but it may help somebody else one day so just posting it just in case...

jQuery find parent form

see also jquery/js -- How do I select the parent form based on which submit button is clicked?

$('form#myform1').submit(function(e){
     e.preventDefault(); //Prevent the normal submission action
     var form = this;
     // ... Handle form submission
});

ERROR 1064 (42000) in MySQL

(For those coming to this question from a search engine), check that your stored procedures declare a custom delimiter, as this is the error that you might see when the engine can't figure out how to terminate a statement:

ERROR 1064 (42000) at line 3: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line…

If you have a database dump and see:

DROP PROCEDURE IF EXISTS prc_test;
CREATE PROCEDURE prc_test( test varchar(50))
BEGIN
    SET @sqlstr = CONCAT_WS(' ', 'CREATE DATABASE',  test, 'CHARACTER SET utf8 COLLATE utf8_general_ci');
    SELECT @sqlstr;
    PREPARE stmt FROM @sqlstr;
    EXECUTE stmt;
END;

Try wrapping with a custom DELIMITER:

DROP PROCEDURE IF EXISTS prc_test;
DELIMITER $$
CREATE PROCEDURE prc_test( test varchar(50))
BEGIN
    SET @sqlstr = CONCAT_WS(' ', 'CREATE DATABASE',  test, 'CHARACTER SET utf8 COLLATE utf8_general_ci');
    SELECT @sqlstr;
    PREPARE stmt FROM @sqlstr;
    EXECUTE stmt;
END;
$$
DELIMITER ;

Get index of clicked element in collection with jQuery

$('selector').click(function (event) {
    alert($(this).index());
});

jsfiddle

Abstract class in Java

An abstract class can not be directly instantiated, but must be derived from to be usable. A class MUST be abstract if it contains abstract methods: either directly

abstract class Foo {
    abstract void someMethod();
}

or indirectly

interface IFoo {
    void someMethod();
}

abstract class Foo2 implements IFoo {
}

However, a class can be abstract without containing abstract methods. Its a way to prevent direct instantation, e.g.

abstract class Foo3 {
}

class Bar extends Foo3 {

}

Foo3 myVar = new Foo3(); // illegal! class is abstract
Foo3 myVar = new Bar(); // allowed!

The latter style of abstract classes may be used to create "interface-like" classes. Unlike interfaces an abstract class is allowed to contain non-abstract methods and instance variables. You can use this to provide some base functionality to extending classes.

Another frequent pattern is to implement the main functionality in the abstract class and define part of the algorithm in an abstract method to be implemented by an extending class. Stupid example:

abstract class Processor {
    protected abstract int[] filterInput(int[] unfiltered);

    public int process(int[] values) {
        int[] filtered = filterInput(values);
        // do something with filtered input
    }
}

class EvenValues extends Processor {
    protected int[] filterInput(int[] unfiltered) {
        // remove odd numbers
    }
}

class OddValues extends Processor {
    protected int[] filterInput(int[] unfiltered) {
        // remove even numbers
    }
}

Download File to server from URL

set_time_limit(0); 
$file = file_get_contents('path of your file');
file_put_contents('file.ext', $file);

TypeError: 'function' object is not subscriptable - Python

It is so simple, you have 2 objects with the same name and when you say: bank_holiday[month] python thinks you wanna run your function and got ERROR.

Just rename your array to bank_holidays <--- add a 's' at the end! like this:

bank_holidays= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month

def bank_holiday(month):
   if month <1 or month > 12:
       print("Error: Out of range")
       return
   print(bank_holidays[month-1],"holiday(s) in this month ")

bank_holiday(int(input("Which month would you like to check out: ")))

Passing Multiple route params in Angular2

As detailed in this answer, mayur & user3869623's answer's are now relating to a deprecated router. You can now pass multiple parameters as follows:

To call router:

this.router.navigate(['/myUrlPath', "someId", "another ID"]);

In routes.ts:

{ path: 'myUrlpath/:id1/:id2', component: componentToGoTo},

Remove Blank option from Select Option with AngularJS

Use ng-value instead of value.

$scope.allRecs = [{"text":"hello"},{"text":"bye"}];
$scope.X = 0;

and then in html file should be like:

<select ng-model="X">  
     <option ng-repeat="oneRec in allRecs track by $index" ng-value="$index">{{oneRec.text}}</option>
</select>

jQuery autocomplete tagging plug-in like StackOverflow's input tags?

Bootstrap: If you are using Bootstrap. This is a really good one: Select2

Also, TokenInput is an interesting one. First, it does not depend on jQuery-UI, second its config is very smooth.

The only issue I had it does not support free-tagging natively. So, I have to return the query-string back to client as a part of response JSON.


As @culithay mentioned in the comment, TokenInput supports a lot of features to customize. And highlight of some feature that the others don't have:

  • tokenLimit: The maximum number of results allowed to be selected by the user. Use null to allow unlimited selections
  • minChars: The minimum number of characters the user must enter before a search is performed.
  • queryParam: The name of the query param which you expect to contain the search term on the server-side

Thanks culithay for the input.

Difference between "Complete binary tree", "strict binary tree","full binary Tree"?

Full binary tree are a complete binary tree but reverse is not possible, and if the depth of the binary is n the no. of nodes in the full binary tree is ( 2^n-1 ). It is not necessary in the binary tree that it have two child but in the full binary it every node have no or two child.

Add image in pdf using jspdf

maybe a little bit late, but I come to this situation recently and found a simple solution, 2 functions are needed.

  1. load the image.

    function getImgFromUrl(logo_url, callback) {
        var img = new Image();
        img.src = logo_url;
        img.onload = function () {
            callback(img);
        };
    } 
    
  2. in onload event on first step, make a callback to use the jspdf doc.

    function generatePDF(img){
        var options = {orientation: 'p', unit: 'mm', format: custom};
        var doc = new jsPDF(options);
        doc.addImage(img, 'JPEG', 0, 0, 100, 50);}
    
  3. use the above functions.

    var logo_url = "/images/logo.jpg";
    getImgFromUrl(logo_url, function (img) {
        generatePDF(img);
    });
    

ggplot2 plot without axes, legends, etc

'opts' is deprecated.

in ggplot2 >= 0.9.2 use

p + theme(legend.position = "none") 

Regex Match all characters between two strings

You can simply use this: \This is .*? \sentence

Control the dashed border stroke length and distance between strokes

Css render is browser specific and I don't know any fine tuning on it, you should work with images as recommended by Ham. Reference: http://www.w3.org/TR/CSS2/box.html#border-style-properties

Win32Exception (0x80004005): The wait operation timed out

I had the same issue. Running exec sp_updatestats did work sometimes, but not always. I decided to use the NOLOCK statement in my queries to speed up the queries. Just add NOLOCK after your FROM clause, e.g.:

SELECT clicks.entryURL, clicks.entryTime, sessions.userID
FROM sessions, clicks WITH (NOLOCK)
WHERE sessions.sessionID = clicks.sessionID AND clicks.entryTime > DATEADD(day, -1, GETDATE())

Read the full article here.

Groovy built-in REST/HTTP client?

import groovyx.net.http.HTTPBuilder;

public class HttpclassgetrRoles {
     static void main(String[] args){
         def baseUrl = new URL('http://test.city.com/api/Cirtxyz/GetUser')

         HttpURLConnection connection = (HttpURLConnection) baseUrl.openConnection();
         connection.addRequestProperty("Accept", "application/json")
         connection.with {
           doOutput = true
           requestMethod = 'GET'
           println content.text
         }

     }
}

How do I find the length of an array?

Here is one implementation of ArraySize from Google Protobuf.

#define GOOGLE_ARRAYSIZE(a) \
  ((sizeof(a) / sizeof(*(a))) / static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))

// test codes...
char* ptr[] = { "you", "are", "here" };
int testarr[] = {1, 2, 3, 4};
cout << GOOGLE_ARRAYSIZE(testarr) << endl;
cout << GOOGLE_ARRAYSIZE(ptr) << endl;

ARRAYSIZE(arr) works by inspecting sizeof(arr) (the # of bytes in the array) and sizeof(*(arr)) (the # of bytes in one array element). If the former is divisible by the latter, perhaps arr is indeed an array, in which case the division result is the # of elements in the array. Otherwise, arr cannot possibly be an array, and we generate a compiler error to prevent the code from compiling.

Since the size of bool is implementation-defined, we need to cast !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final result has type size_t.

This macro is not perfect as it wrongfully accepts certain pointers, namely where the pointer size is divisible by the pointee size. Since all our code has to go through a 32-bit compiler, where a pointer is 4 bytes, this means all pointers to a type whose size is 3 or greater than 4 will be (righteously) rejected.

How to get row number from selected rows in Oracle

I think using

select rownum st.Branch 
  from student st 
 where st.name like '%ram%'

is a simple way; you should add single quotes in the LIKE statement. If you use row_number(), you should add over (order by 'sort column' 'asc/desc'), for instance:

select st.branch, row_number() over (order by 'sort column' 'asc/desc')  
  from student st 
 where st.name like '%ram%'

How to convert .pem into .key?

I assume you want the DER encoded version of your PEM private key.

openssl rsa -outform der -in private.pem -out private.key

Easiest way to convert a List to a Set in Java

You can convert List<> to Set<>

Set<T> set=new HashSet<T>();

//Added dependency -> If list is null then it will throw NullPointerExcetion.

Set<T> set;
if(list != null){
    set = new HashSet<T>(list);
}

What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?

Shuffling is the process by which intermediate data from mappers are transferred to 0,1 or more reducers. Each reducer receives 1 or more keys and its associated values depending on the number of reducers (for a balanced load). Further the values associated with each key are locally sorted.

TypeError: 'undefined' is not a function (evaluating '$(document)')

Also check for including jQuery, followed by some components/other libraries (like jQuery UI) and then accidentially including jQuery again - this will redefine jQuery and drop the component helpers (like .datepicker) off the instance.

Declare multiple module.exports in Node.js

If the files are written using ES6 export, you can write:

module.exports = {
  ...require('./foo'),
  ...require('./bar'),
};

how to configure hibernate config file for sql server

Properties that are database specific are:

  • hibernate.connection.driver_class: JDBC driver class
  • hibernate.connection.url: JDBC URL
  • hibernate.connection.username: database user
  • hibernate.connection.password: database password
  • hibernate.dialect: The class name of a Hibernate org.hibernate.dialect.Dialect which allows Hibernate to generate SQL optimized for a particular relational database.

To change the database, you must:

  1. Provide an appropriate JDBC driver for the database on the class path,
  2. Change the JDBC properties (driver, url, user, password)
  3. Change the Dialect used by Hibernate to talk to the database

There are two drivers to connect to SQL Server; the open source jTDS and the Microsoft one. The driver class and the JDBC URL depend on which one you use.

With the jTDS driver

The driver class name is net.sourceforge.jtds.jdbc.Driver.

The URL format for sqlserver is:

 jdbc:jtds:sqlserver://<server>[:<port>][/<database>][;<property>=<value>[;...]]

So the Hibernate configuration would look like (note that you can skip the hibernate. prefix in the properties):

<hibernate-configuration>
  <session-factory>
    <property name="connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property>
    <property name="connection.url">jdbc:jtds:sqlserver://<server>[:<port>][/<database>]</property>
    <property name="connection.username">sa</property>
    <property name="connection.password">lal</property>

    <property name="dialect">org.hibernate.dialect.SQLServerDialect</property>

    ...
  </session-factory>
</hibernate-configuration>

With Microsoft SQL Server JDBC 3.0:

The driver class name is com.microsoft.sqlserver.jdbc.SQLServerDriver.

The URL format is:

jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]

So the Hibernate configuration would look like:

<hibernate-configuration>
  <session-factory>
    <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
    <property name="connection.url">jdbc:sqlserver://[serverName[\instanceName][:portNumber]];databaseName=<databaseName></property>
    <property name="connection.username">sa</property>
    <property name="connection.password">lal</property>

    <property name="dialect">org.hibernate.dialect.SQLServerDialect</property>

    ...
  </session-factory>
</hibernate-configuration>

References

How to launch multiple Internet Explorer windows/tabs from batch file?

Try this in your batch file:

@echo off
start /d "C:\Program Files\Internet Explorer" IEXPLORE.EXE www.google.com
start /d "C:\Program Files\Internet Explorer" IEXPLORE.EXE www.yahoo.com

How to add days to the current date?

Dateadd(datepart,number,date)

You should use it like this:

select DATEADD(day,360,getdate())

Then you will find the same date but different year.

How to return an array from an AJAX call?

@Xeon06, nice but just as a fyi for those that read this thread and tried like me... when returning the array from php => json_encode($theArray). converts to a string which to me isn't easy to manipulate esp for soft js users like myself.

Inside js, you are trying to get the array values and/or keys of the array u r better off using JSON.parse as in var jsArray = JSON.parse(data) where data is return array from php. the json encoded string is converted to js object that can now be manipulated easily.

e.g. foo={one:1, two:2, three:3} - gotten after JSON.parse

for (key in foo){ console.log("foo["+ key +"]="+ foo[key]) } - prints to ur firebug console. voila!

Pip - Fatal error in launcher: Unable to create process using '"'

Checked the evironment path, I have two paths navigated to two pip.exe and this caused this error. After deleting the redundant one and restart the PC, this issue has been fixed. The same issue for the jupyter command fixed as well.

SpringApplication.run main method

Using:

@ComponentScan
@EnableAutoConfiguration
public class Application {

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

        //do your ReconTool stuff
    }
}

will work in all circumstances. Whether you want to launch the application from the IDE, or the build tool.

Using maven just use mvn spring-boot:run

while in gradle it would be gradle bootRun

An alternative to adding code under the run method, is to have a Spring Bean that implements CommandLineRunner. That would look like:

@Component
public class ReconTool implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
       //implement your business logic here
    }
}

Check out this guide from Spring's official guide repository.

The full Spring Boot documentation can be found here

Can't load IA 32-bit .dll on a AMD 64-bit platform

I had the same issue with a Java application using tibco dll originally intended to run on Win XP. To get it to work on Windows 7, I made the application point to 32-bit JRE. Waiting to see if there is another solution.

How to use a ViewBag to create a dropdownlist?

hope it will work

 @Html.DropDownList("accountid", (IEnumerable<SelectListItem>)ViewBag.Accounts, String.Empty, new { @class ="extra-class" })

Here String.Empty will be the empty as a default selector.

Nullable types: better way to check for null or zero in c#

public static bool nz(object obj)
{
    return obj == null || obj.Equals(Activator.CreateInstance(obj.GetType()));
}

How do change the color of the text of an <option> within a <select>?

I was recently having trouble with this same thing and I found a really simple solution.

All you have to do is set the first option to disabled and selected. Like this:

_x000D_
_x000D_
<select id="select">_x000D_
    <option disabled="disabled" selected="selected">select one option</option>_x000D_
    <option>one</option>_x000D_
    <option>two</option>_x000D_
    <option>three</option>_x000D_
    <option>four</option>_x000D_
    <option>five</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

This will display the first option (grayed out) when the page is loaded. It also prevents the user from being able to select it once they click on the list.

How do you get the index of the current iteration of a foreach loop?

I built this in LINQPad:

var listOfNames = new List<string>(){"John","Steve","Anna","Chris"};

var listCount = listOfNames.Count;

var NamesWithCommas = string.Empty;

foreach (var element in listOfNames)
{
    NamesWithCommas += element;
    if(listOfNames.IndexOf(element) != listCount -1)
    {
        NamesWithCommas += ", ";
    }
}

NamesWithCommas.Dump();  //LINQPad method to write to console.

You could also just use string.join:

var joinResult = string.Join(",", listOfNames);

Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting StackOverflowError.

Encountered a similar error, this how I resolved it:

  1. Access Project explorer view on Netbeans IDE 8.2. Proceed to your project under Dependencies hover the cursor over the log4j-over-slf4j.jar to view the which which dependencies have indirectly imported as shown below. enter image description here

  2. Right click an import jar file and select Exclude Dependency enter image description here

  3. To confirm, open your pom.xml file you will notice the exclusion element as below.

enter image description here 4. Initiate maven clean install and run your project. Good luck!

Getting key with maximum value in dictionary?

Per the iterated solutions via comments in the selected answer...

In Python 3:

max(stats.keys(), key=(lambda k: stats[k]))

In Python 2:

max(stats.iterkeys(), key=(lambda k: stats[k]))

jquery animate .css

If you are needing to use CSS with the jQuery .animate() function, you can use set the duration.

$("#my_image").css({
    'left':'1000px',
    6000, ''
});

We have the duration property set to 6000.

This will set the time in thousandth of seconds: 6 seconds.

After the duration our next property "easing" changes how our CSS happens.

We have our positioning set to absolute.

There are two default ones to the absolute function: 'linear' and 'swing'.

In this example I am using linear.

It allows for it to use a even pace.

The other 'swing' allows for a exponential speed increase.

There are a bunch of really cool properties to use with animate like bounce, etc.

$(document).ready(function(){
    $("#my_image").css({
        'height': '100px',
        'width':'100px',
        'background-color':'#0000EE',
        'position':'absolute'
    });// property than value

    $("#my_image").animate({
        'left':'1000px'
    },6000, 'linear', function(){
        alert("Done Animating");
    });
});

How to bundle vendor scripts separately and require them as needed with Webpack?

Also not sure if I fully understand your case, but here is config snippet to create separate vendor chunks for each of your bundles:

entry: {
  bundle1: './build/bundles/bundle1.js',
  bundle2: './build/bundles/bundle2.js',
  'vendor-bundle1': [
    'react',
    'react-router'
  ],
  'vendor-bundle2': [
    'react',
    'react-router',
    'flummox',
    'immutable'
  ]
},

plugins: [
  new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor-bundle1',
    chunks: ['bundle1'],
    filename: 'vendor-bundle1.js',
    minChunks: Infinity
  }),
  new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor-bundle2',
    chunks: ['bundle2'],
    filename: 'vendor-bundle2-whatever.js',
    minChunks: Infinity
  }),
]

And link to CommonsChunkPlugin docs: http://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin

Finding rows that don't contain numeric data in Oracle

You can use this one check:

create or replace function to_n(c varchar2) return number is
begin return to_number(c);
exception when others then return -123456;
end;

select id, n from t where to_n(n) = -123456;

Get Return Value from Stored procedure in asp.net

Procedure never returns a value.You have to use a output parameter in store procedure.

ALTER PROC TESTLOGIN
@UserName   varchar(50),
@password   varchar(50)
@retvalue int output
 as
 Begin
    declare @return     int 
    set @return  = (Select COUNT(*) 
    FROM    CPUser  
    WHERE   UserName = @UserName AND Password = @password)

   set @retvalue=@return
  End

Then you have to add a sqlparameter from c# whose parameter direction is out. Hope this make sense.

Clear and refresh jQuery Chosen dropdown list

Using .trigger("chosen:updated"); you can update the options list after appending.

Updating Chosen Dynamically: If you need to update the options in your select field and want Chosen to pick up the changes, you'll need to trigger the "chosen:updated" event on the field. Chosen will re-build itself based on the updated content.

Your code:

$("#refreshgallery").click(function(){
        $('#picturegallery').empty(); //remove all child nodes
        var newOption = $('<option value="1">test</option>');
        $('#picturegallery').append(newOption);
        $('#picturegallery').trigger("chosen:updated");
    });

How to negate specific word in regex?

Extracted from this comment by bkDJ:

^(?!bar$).*

The nice property of this solution is that it's possible to clearly negate (exclude) multiple words:

^(?!bar$|foo$|banana$).*

How do you UDP multicast in Python?

Just another answer to explain some subtle points in the code of the other answers:

  • socket.INADDR_ANY - (Edited) In the context of IP_ADD_MEMBERSHIP, this doesn't really bind the socket to all interfaces but just choose the default interface where multicast is up (according to routing table)
  • Joining a multicast group isn't the same as binding a socket to a local interface address

see What does it mean to bind a multicast (UDP) socket? for more on how multicast works

Multicast receiver:

import socket
import struct
import argparse


def run(groups, port, iface=None, bind_group=None):
    # generally speaking you want to bind to one of the groups you joined in
    # this script,
    # but it is also possible to bind to group which is added by some other
    # programs (like another python program instance of this)

    # assert bind_group in groups + [None], \
    #     'bind group not in groups to join'
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)

    # allow reuse of socket (to allow another instance of python running this
    # script binding to the same ip/port)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    sock.bind(('' if bind_group is None else bind_group, port))
    for group in groups:
        mreq = struct.pack(
            '4sl' if iface is None else '4s4s',
            socket.inet_aton(group),
            socket.INADDR_ANY if iface is None else socket.inet_aton(iface))

        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

    while True:
        print(sock.recv(10240))


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--port', type=int, default=19900)
    parser.add_argument('--join-mcast-groups', default=[], nargs='*',
                        help='multicast groups (ip addrs) to listen to join')
    parser.add_argument(
        '--iface', default=None,
        help='local interface to use for listening to multicast data; '
        'if unspecified, any interface would be chosen')
    parser.add_argument(
        '--bind-group', default=None,
        help='multicast groups (ip addrs) to bind to for the udp socket; '
        'should be one of the multicast groups joined globally '
        '(not necessarily joined in this python program) '
        'in the interface specified by --iface. '
        'If unspecified, bind to 0.0.0.0 '
        '(all addresses (all multicast addresses) of that interface)')
    args = parser.parse_args()
    run(args.join_mcast_groups, args.port, args.iface, args.bind_group)

sample usage: (run the below in two consoles and choose your own --iface (must be same as the interface that receives the multicast data))

python3 multicast_recv.py --iface='192.168.56.102' --join-mcast-groups '224.1.1.1' '224.1.1.2' '224.1.1.3' --bind-group '224.1.1.2'

python3 multicast_recv.py --iface='192.168.56.102' --join-mcast-groups '224.1.1.4'

Multicast sender:

import socket
import argparse


def run(group, port):
    MULTICAST_TTL = 20
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, MULTICAST_TTL)
    sock.sendto(b'from multicast_send.py: ' +
                f'group: {group}, port: {port}'.encode(), (group, port))


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--mcast-group', default='224.1.1.1')
    parser.add_argument('--port', default=19900)
    args = parser.parse_args()
    run(args.mcast_group, args.port)

sample usage: # assume the receiver binds to the below multicast group address and that some program requests to join that group. And to simplify the case, assume the receiver and the sender are under the same subnet

python3 multicast_send.py --mcast-group '224.1.1.2'

python3 multicast_send.py --mcast-group '224.1.1.4'

How to set the env variable for PHP?

It depends on your OS, but if you are on Windows XP, you need to go to Systems Properties, then Advanced, then Environment Variables, and include the php binary path to the %PATH% variable.

Locate it by browsing your WAMP directory. It's called php.exe

Setting the value of checkbox to true or false with jQuery

var checkbox = $( "#checkbox" );
checkbox.val( checkbox[0].checked ? "true" : "false" );

This will set the value of the checkbox to "true" or "false" (value property is a string), depending whether it's unchecked or checked.

Works in jQuery >= 1.0

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM

The normal layout for a maven multi module project is:

parent
+-- pom.xml
+-- module
    +-- pom.xml

Check that you use this layout.

Additionally:

  1. the relativePath looks strange. Instead of '..'

    <relativePath>..</relativePath>
    

    try '../' instead:

    <relativePath>../</relativePath>
    

    You can also remove relativePath if you use the standard layout. This is what I always do, and on the command line I can build as well the parent (and all modules) or only a single module.

  2. The module path may be wrong. In the parent you define the module as:

    <module>junitcategorizer.cutdetection</module>
    

    You must specify the name of the folder of the child module, not an artifact identifier. If junitcategorizer.cutdetection is not the name of the folder than change it accordingly.

Hope that helps..

EDIT have a look at the other post, I answered there.

What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

127.0.0.1 is normally the IP address assigned to the "loopback" or local-only interface. This is a "fake" network adapter that can only communicate within the same host. It's often used when you want a network-capable application to only serve clients on the same host. A process that is listening on 127.0.0.1 for connections will only receive local connections on that socket.

"localhost" is normally the hostname for the 127.0.0.1 IP address. It's usually set in /etc/hosts (or the Windows equivalent named "hosts" somewhere under %WINDIR%). You can use it just like any other hostname - try "ping localhost" to see how it resolves to 127.0.0.1.

0.0.0.0 has a couple of different meanings, but in this context, when a server is told to listen on 0.0.0.0 that means "listen on every available network interface". The loopback adapter with IP address 127.0.0.1 from the perspective of the server process looks just like any other network adapter on the machine, so a server told to listen on 0.0.0.0 will accept connections on that interface too.

That hopefully answers the IP side of your question. I'm not familiar with Jekyll or Vagrant, but I'm guessing that your port forwarding 8080 => 4000 is somehow bound to a particular network adapter, so it isn't in the path when you connect locally to 127.0.0.1

error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj

I make a little update on this issue, as I just had the same error today on an application which is linking against a static lib, after I migrated the old Visual 6 project to Visual Studio 2012.

In my case the error was that I mistakenly compiled the Release version of the static lib with /MDd instead of /MD, whereas the application is /MD in release. Setting the correct /MD in the static lib project solved the issue.

This is done in Project properties

  • Select Configuration Properties / C C++ / Code Generation in the tree
  • and the option Runtime Library set to the same on all your dependencies projects and application.

Set margins in a LinearLayout programmatically

I have set up margins directly using below code

LinearLayout layout = (LinearLayout)findViewById(R.id.yourrelative_layout);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);            
params.setMargins(3, 300, 3, 3); 
layout.setLayoutParams(params);

Only thing here is to notice that LayoutParams should be imported for following package android.widget.RelativeLayout.LayoutParams, or else there will be an error.

How do you change the width and height of Twitter Bootstrap's tooltips?

in bootstrap 3.0.3 you can do it by modifying the popover class

.popover {
    min-width: 200px;
    max-width: 400px;
}

Android - How to achieve setOnClickListener in Kotlin?

val saveButton:Button = findViewById(R.id.button_save)

saveButton.setOnClickListener{
// write code for click event
}

with view object
saveButton.setOnClickListener{
view -> // write code for click event
}

How to obfuscate Python code effectively?

You can use the base64 module to encode strings to stop shoulder surfing, but it's not going to stop someone finding your code if they have access to your files.

You can then use the compile() function and the eval() function to execute your code once you've decoded it.

>>> import base64
>>> mycode = "print 'Hello World!'"
>>> secret = base64.b64encode(mycode)
>>> secret
'cHJpbnQgJ2hlbGxvIFdvcmxkICEn'
>>> mydecode = base64.b64decode(secret)
>>> eval(compile(mydecode,'<string>','exec'))
Hello World!

So if you have 30 lines of code you'll probably want to encrypt it doing something like this:

>>> f = open('myscript.py')
>>> encoded = base64.b64encode(f.read())

You'd then need to write a second script that does the compile() and eval() which would probably include the encoded script as a string literal encased in triple quotes. So it would look something like this:

import base64
myscript = """IyBUaGlzIGlzIGEgc2FtcGxlIFB5d
              GhvbiBzY3JpcHQKcHJpbnQgIkhlbG
              xvIiwKcHJpbnQgIldvcmxkISIK"""
eval(compile(base64.b64decode(myscript),'<string>','exec'))

How to customize <input type="file">?

Bootstrap example

<label className="btn btn-info btn-lg">
  Upload
  <input type="file" style="display: none" />
</label>

CSS text-overflow: ellipsis; not working?

So if you reach this question because you're having trouble trying to get the ellipsis working inside a display: flex container, try adding min-width: 0 to the outmost container that's overflowing its parent even though you already set a overflow: hidden to it and see how that works for you.

More details and a working example on this codepen by aj-foster. Totally did the trick in my case.

Failed to execute removeChild on Node

Your myCoolDiv element isn't a child of the player container. It's a child of the div you created as a wrapper for it (markerDiv in the first part of the code). Which is why it fails, removeChild only removes children, not descendants.

You'd want to remove that wrapper div, or not add it at all.

Here's the "not adding it at all" option:

_x000D_
_x000D_
var markerDiv = document.createElement("div");_x000D_
markerDiv.innerHTML = "<div id='MyCoolDiv' style='color: #2b0808'>123</div>";_x000D_
document.getElementById("playerContainer").appendChild(markerDiv.firstChild);_x000D_
// -------------------------------------------------------------^^^^^^^^^^^_x000D_
_x000D_
setTimeout(function(){ _x000D_
    var myCoolDiv = document.getElementById("MyCoolDiv");_x000D_
    document.getElementById("playerContainer").removeChild(myCoolDiv);_x000D_
}, 1500);
_x000D_
<div id="playerContainer"></div>
_x000D_
_x000D_
_x000D_

Or without using the wrapper (although it's quite handy for parsing that HTML):

_x000D_
_x000D_
var myCoolDiv = document.createElement("div");_x000D_
// Don't reall need this: myCoolDiv.id = "MyCoolDiv";_x000D_
myCoolDiv.style.color = "#2b0808";_x000D_
myCoolDiv.appendChild(_x000D_
  document.createTextNode("123")_x000D_
);_x000D_
document.getElementById("playerContainer").appendChild(myCoolDiv);_x000D_
_x000D_
setTimeout(function(){ _x000D_
    // No need for this, we already have it from the above:_x000D_
    // var myCoolDiv = document.getElementById("MyCoolDiv");_x000D_
    document.getElementById("playerContainer").removeChild(myCoolDiv);_x000D_
}, 1500);
_x000D_
<div id="playerContainer"></div>
_x000D_
_x000D_
_x000D_

SQL Server format decimal places with commas

If you are using SQL Azure Reporting Services, the "format" function is unsupported. This is really the only way to format a tooltip in a chart in SSRS. So the workaround is to return a column that has a string representation of the formatted number to use for the tooltip. So, I do agree that SQL is not the place for formatting. Except in cases like this where the tool does not have proper functions to handle display formatting.

In my case I needed to show a number formatted with commas and no decimals (type decimal 2) and ended up with this gem of a calculated column in my dataset query:

,Fmt_DDS=reverse(stuff(reverse(CONVERT(varchar(25),cast(SUM(kv.DeepDiveSavingsEst) as money),1)), 1, 3, ''))

It works, but is very ugly and non-obvious to whoever maintains the report down the road. Yay Cloud!

Is it possible to make Font Awesome icons larger than 'fa-5x'?

Font awesome use SVG icons. So, you can resize it for your requirment.

just use CSS class for that,

    .large-icon{
       font-size:10em;
       //or
      font-size:200%;
      //or
      font-size:50px;
    }

How do I measure execution time of a command on the Windows command line?

In case anyone else has come here looking for an answer to this question, there's a Windows API function called GetProcessTimes(). It doesn't look like too much work to write a little C program that would start the command, make this call, and return the process times.

Unable to load DLL (Module could not be found HRESULT: 0x8007007E)

In my case one unmanaged dll was depending on another which was missing. In that case the error will point to the existing dll instead of the missing one which can be really confusing.

That is exactly what had happen in my case. Hope this helps someone else.

Getting data-* attribute for onclick event for an html element

You can achieve this $(identifier).data('id') using jquery,

    <script type="text/javascript">

        function goDoSomething(identifier){     
            alert("data-id:"+$(identifier).data('id')+", data-option:"+$(identifier).data('option'));               
        }

    </script>

    <a id="option1" 
       data-id="10" 
       data-option="21" 
       href="#" 
       onclick="goDoSomething(this);">
           Click to do something
    </a>

javascript : You can use getAttribute("attributename") if want to use javascript tag,

    <script type="text/javascript">

        function goDoSomething(d){
            alert(d.getAttribute("data-id"));
        }

    </script>

    <a id="option1" 
       data-id="10" 
       data-option="21" 
       href="#" 
       onclick="goDoSomething(this);">
           Click to do something
    </a>

Or:

    <script type="text/javascript">

        function goDoSomething(data_id, data_option){       

            alert("data-id:"+data_id+", data-option:"+data_option);
        }

    </script>

    <a id="option1" 
       data-id="10" 
       data-option="21" 
       href="#" 
       onclick="goDoSomething(this.getAttribute('data-id'), this.getAttribute('data-option'));">
           Click to do something
    </a>

Reading a plain text file in Java

What do you want to do with the text? Is the file small enough to fit into memory? I would try to find the simplest way to handle the file for your needs. The FileUtils library is very handle for this.

for(String line: FileUtils.readLines("my-text-file"))
    System.out.println(line);

Java best way for string find and replace?

When you dont want to put your hand yon regular expression (may be you should) you could first replace all "Milan Vasic" string with "Milan".

And than replace all "Milan" Strings with "Milan Vasic".

Delete a dictionary item if the key exists

There is also:

try:
    del mydict[key]
except KeyError:
    pass

This only does 1 lookup instead of 2. However, except clauses are expensive, so if you end up hitting the except clause frequently, this will probably be less efficient than what you already have.

How do I check if a SQL Server text column is empty?

Use DATALENGTH method, for example:

SELECT length = DATALENGTH(myField)
FROM myTABLE

cannot import name patterns

from django.contrib import admin
from django.urls import path


urlpatterns = [
    path('admin/', admin.site.urls),
]

How to get all privileges back to the root user in MySQL?

If you facing grant permission access denied problem, you can try mysql to fix the problem:

grant all privileges on . to root@'localhost' identified by 'Your password';

grant all privileges on . to root@'IP ADDRESS' identified by 'Your password?';

your can try this on any mysql user, its working.

Use below command to login mysql with iP address.

mysql -h 10.0.0.23 -u root -p

php hide ALL errors

In your php file just enter this code:

error_reporting(0);

This will report no errors to the user. If you somehow want, then just comment this.

Is it bad practice to use break to exit a loop in Java?

No, it is not a bad practice. It is the most easiest and efficient way.

How to provide password to a command that prompts for one in bash?

You can use the -S flag to read from std input. Find below an example:

function shutd()
{
  echo "mySuperSecurePassword" | sudo -S shutdown -h now
}    

dotnet ef not found in .NET Core 3

See the announcement for ASP.NET Core 3 Preview 4, which explains that this tool is no longer built-in and requires an explicit install:

The dotnet ef tool is no longer part of the .NET Core SDK

This change allows us to ship dotnet ef as a regular .NET CLI tool that can be installed as either a global or local tool. For example, to be able to manage migrations or scaffold a DbContext, install dotnet ef as a global tool typing the following command:

dotnet tool install --global dotnet-ef

To install a specific version of the tool, use the following command:

dotnet tool install --global dotnet-ef --version 3.1.4

The reason for the change is explained in the docs:

Why

This change allows us to distribute and update dotnet ef as a regular .NET CLI tool on NuGet, consistent with the fact that the EF Core 3.0 is also always distributed as a NuGet package.

In addition, you might need to add the following NuGet packages to your project:

Difference between OpenJDK and Adoptium/AdoptOpenJDK

Update: AdoptOpenJDK has changed its name to Adoptium, as part of its move to the Eclipse Foundation.


OpenJDK ? source code
Adoptium/AdoptOpenJDK ? builds

Difference between OpenJDK and AdoptOpenJDK

The first provides source-code, the other provides builds of that source-code.

Several vendors of Java & OpenJDK

Adoptium of the Eclipse Foundation, formerly known as AdoptOpenJDK, is only one of several vendors distributing implementations of the Java platform. These include:

  • Eclipse Foundation (Adoptium/AdoptOpenJDK)
  • Azul Systems
  • Oracle
  • Red Hat / IBM
  • BellSoft
  • SAP
  • Amazon AWS
  • … and more

See this flowchart of mine to help guide you in picking a vendor for an implementation of the Java platform. Click/tap to zoom.

Flowchart guiding you in choosing a vendor for a Java 11 implementation

Another resource: This comparison matrix by Azul Systems is useful, and seems true and fair to my mind.

Here is a list of considerations and motivations to consider in choosing a vendor and implementation.

Motivations in choosing a vendor for Java

Some vendors offer you a choice of JIT technologies.

Diagram showing history of HotSpot & JRockit merging, and OpenJ9 both available in AdoptOpenJDK

To understand more about this Java ecosystem, read Java Is Still Free

Excel - Shading entire row based on change of value

I had to do something similar for my users, with a small variant that they want to have a running number grouping the similar items. Thought I'd share it here.

  • Make a new column A
  • Assuming the first row of data is in row 2 (row 1 being header), put 1 in A2
  • Assuming your File No is in column B, in the second row (in this case A3) make the formula =IF(B3=B2,A2,A2+1)
  • Fill/copy-paste cell A3 down the column to the last row (be careful not to copy A2 by accident; that will populate all cells with 1)
  • Select the data range
  • In the Home ribbon select Conditional Formatting -> New Rule
  • Choose Use a formula to determine which cells to format
  • In the formula cell, put =MOD($A1, 2)=1 as the formula
  • Click Format, select the Fill tab
  • Select the Background Color you want, then click OK
  • Click OK

enter image description here

Which .NET Dependency Injection frameworks are worth looking into?

I use Simple Injector:

Simple Injector is an easy, flexible and fast dependency injection library that uses best practice to guide your solutions toward the pit of success.

Best way to replace multiple characters in a string?

>>> a = '&#'
>>> print a.replace('&', r'\&')
\&#
>>> print a.replace('#', r'\#')
&\#
>>> 

You want to use a 'raw' string (denoted by the 'r' prefixing the replacement string), since raw strings to not treat the backslash specially.

Android, canvas: How do I clear (delete contents of) a canvas (= bitmaps), living in a surfaceView?

Your first requirement, how to clear or redraw whole canvas - Answer - use canvas.drawColor(color.Black) method for clearing the screen with a color of black or whatever you specify .

Your second requirement, how to update part of the screen - Answer - for example if you want to keep all other things unchanged on the screen but in a small area of screen to show an integer(say counter) which increases after every five seconds. then use canvas.drawrect method to draw that small area by specifying left top right bottom and paint. then compute your counter value(using postdalayed for 5 seconds etc., llike Handler.postDelayed(Runnable_Object, 5000);) , convert it to text string, compute the x and y coordinate in this small rect and use text view to display the changing counter value.

How do you use global variables or constant values in Ruby?

One thing you need to realize is in Ruby everything is an object. Given that, if you don't define your methods within Module or Class, Ruby will put it within the Object class. So, your code will be local to the Object scope.

A typical approach on Object Oriented Programming is encapsulate all logic within a class:

class Point
  attr_accessor :x, :y

  # If we don't specify coordinates, we start at 0.
  def initialize(x = 0, y = 0)
    # Notice that `@` indicates instance variables.
    @x = x
    @y = y
  end

  # Here we override the `+' operator.
  def +(point)
    Point.new(self.x + point.x, self.y + point.y)
  end

  # Here we draw the point.
  def draw(offset = nil)
    if offset.nil?
      new_point = self
    else
      new_point = self + offset 
    end
    new_point.draw_absolute
  end

  def draw_absolute
    puts "x: #{self.x}, y: #{self.y}"
  end
end

first_point = Point.new(100, 200)
second_point = Point.new(3, 4)

second_point.draw(first_point)

Hope this clarifies a bit.

How to convert an int array to String with toString method in Java

Using the utility I describe here, you can have a more control over the string representation you get for your array.

String[] s = { "hello", "world" };
RichIterable<String> r = RichIterable.from(s);
r.mkString();                 // gives "hello, world"
r.mkString(" | ");            // gives "hello | world"
r.mkString("< ", ", ", " >"); // gives "< hello, world >"

CURL to pass SSL certifcate and password

Should be:

curl --cert certificate_file.pem:password https://www.example.com/some_protected_page

The located assembly's manifest definition does not match the assembly reference

OK, one more answer. I previously created my app as 64 bit and changed the output path (Project/Properties/Build/Output/Output Path) accordingly. Recently I changed the app to 32 Bit (x86), creating a new output path. I created a shortcut to where I thought the compiled .exe was going. No matter what I changed about the source, it got the manifest not matching error. After about an hour of frustration, I happened to check the date/time of the .exe file, saw it was old obviously referencing old .dll's. I was compiling the app into the old directory and my shortcut was referencing the newer. Changed the output path to where the .exe should go, ran the shortcut and error is gone. (slaps forehead)

How to filter data in dataview

DataView view = new DataView();
view.Table = DataSet1.Tables["Suppliers"];
view.RowFilter = "City = 'Berlin'";
view.RowStateFilter = DataViewRowState.ModifiedCurrent;
view.Sort = "CompanyName DESC";

// Simple-bind to a TextBox control
Text1.DataBindings.Add("Text", view, "CompanyName");

Ref: http://www.csharp-examples.net/dataview-rowfilter/

http://msdn.microsoft.com/en-us/library/system.data.dataview.rowfilter.aspx

String MinLength and MaxLength validation don't work (asp.net mvc)

MaxLength is used for the Entity Framework to decide how large to make a string value field when it creates the database.

From MSDN:

Specifies the maximum length of array or string data allowed in a property.

StringLength is a data annotation that will be used for validation of user input.

From MSDN:

Specifies the minimum and maximum length of characters that are allowed in a data field.

Non Customized

Use [String Length]

[RegularExpression(@"^.{3,}$", ErrorMessage = "Minimum 3 characters required")]
[Required(ErrorMessage = "Required")]
[StringLength(30, MinimumLength = 3, ErrorMessage = "Maximum 30 characters")]

30 is the Max Length
Minimum length = 3

Customized StringLengthAttribute Class

public class MyStringLengthAttribute : StringLengthAttribute
{
    public MyStringLengthAttribute(int maximumLength)
        : base(maximumLength)
    {
    }

    public override bool IsValid(object value)
    {
        string val = Convert.ToString(value);
        if (val.Length < base.MinimumLength)
            base.ErrorMessage = "Minimum length should be 3";
        if (val.Length > base.MaximumLength)
            base.ErrorMessage = "Maximum length should be 6";
        return base.IsValid(value);
    }
}

public class MyViewModel
{
    [MyStringLength(6, MinimumLength = 3)]
    public String MyProperty { get; set; }
}

Split string into string array of single characters

I believe this is what you're looking for:

char[] characters = "this is a test".ToCharArray();

CSS fixed width in a span

_x000D_
_x000D_
ul {_x000D_
  list-style-type: none;_x000D_
  padding-left: 0px;_x000D_
}_x000D_
_x000D_
ul li span {_x000D_
  float: left;_x000D_
  width: 40px;_x000D_
}
_x000D_
<ul>_x000D_
  <li><span></span> The lazy dog.</li>_x000D_
  <li><span>AND</span> The lazy cat.</li>_x000D_
  <li><span>OR</span> The active goldfish.</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Like Eoin said, you need to put a non-breaking space into your "empty" spans, but you can't assign a width to an inline element, only padding/margin so you'll need to make it float so that you can give it a width.

For a jsfiddle example, see http://jsfiddle.net/laurensrietveld/JZ2Lg/

requestFeature() must be called before adding content

In my case I showed DialogFragment in Activity. In this dialog fragment I wrote as in DialogFragment remove black border:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setStyle(STYLE_NO_FRAME, 0)
}

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    super.onCreateDialog(savedInstanceState)

    val dialog = Dialog(context!!, R.style.ErrorDialogTheme)
    val inflater = LayoutInflater.from(context)
    val view = inflater.inflate(R.layout.fragment_error_dialog, null, false)
    dialog.setTitle(null)
    dialog.setCancelable(true)
    dialog.setContentView(view)
    return dialog
}

Either remove setStyle(STYLE_NO_FRAME, 0) in onCreate() or chande/remove onCreateDialog. Because dialog settings have changed after the dialog has been created.

How to check if running in Cygwin, Mac or Linux?

http://en.wikipedia.org/wiki/Uname

All the info you'll ever need. Google is your friend.

Use uname -s to query the system name.

  • Mac: Darwin
  • Cygwin: CYGWIN_...
  • Linux: various, LINUX for most

Comment out HTML and PHP together

I found the following solution pretty effective if you need to comment a lot of nested HTML + PHP code.

Wrap all the content in this:

<?php
    if(false){
?>

Here goes your PHP + HTML code

<?php
    }
?>

What is the Java ?: operator called and what does it do?

You might be interested in a proposal for some new operators that are similar to the conditional operator. The null-safe operators will enable code like this:

String s = mayBeNull?.toString() ?: "null";

It would be especially convenient where auto-unboxing takes place.

Integer ival = ...;  // may be null
int i = ival ?: -1;  // no NPE from unboxing

It has been selected for further consideration under JDK 7's "Project Coin."

Summarizing count and conditional aggregate functions on the same factor

Assuming that your original dataset is similar to the one you created (i.e. with NA as character. You could specify na.strings while reading the data using read.table. But, I guess NAs would be detected automatically.

The price column is factor which needs to be converted to numeric class. When you use as.numeric, all the non-numeric elements (i.e. "NA", FALSE) gets coerced to NA) with a warning.

library(dplyr)
df %>%
     mutate(price=as.numeric(as.character(price))) %>%  
     group_by(company, year, product) %>%
     summarise(total.count=n(), 
               count=sum(is.na(price)), 
               avg.price=mean(price,na.rm=TRUE),
               max.price=max(price, na.rm=TRUE))

data

I am using the same dataset (except the ... row) that was showed.

df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
 year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
 "Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
 "7.12", "12.99", "10.99", "NA",FALSE)))

Disabling buttons on react native

You can enable and disable button or by using condition or directly by default it will be disable : true

 // in calling function of button 
    handledisableenable()
        {
         // set the state for disabling or enabling the button
           if(ifSomeConditionReturnsTrue)
            {
                this.setState({ Isbuttonenable : true })
            }
          else
          {
             this.setState({ Isbuttonenable : false})
          }
        }

<TouchableOpacity onPress ={this.handledisableenable} disabled= 
     {this.state.Isbuttonenable}>

    <Text> Button </Text>
</TouchableOpacity>

How to define Singleton in TypeScript

Here is yet another way to do it with a more conventional javascript approach using an IFFE:

module App.Counter {
    export var Instance = (() => {
        var i = 0;
        return {
            increment: (): void => {
                i++;
            },
            getCount: (): number => {
                return i;
            }
        }
    })();
}

module App {
    export function countStuff() {
        App.Counter.Instance.increment();
        App.Counter.Instance.increment();
        alert(App.Counter.Instance.getCount());
    }
}

App.countStuff();

View a demo

Convert Char to String in C

Using fgetc(fp) only to be able to call strcpy(buffer,c); doesn't seem right.

You could simply build this buffer on your own:

char buffer[MAX_SIZE_OF_MY_BUFFER];

int i = 0;
char ch;
while (i < MAX_SIZE_OF_MY_BUFFER - 1 && (ch = fgetc(fp)) != EOF) {
    buffer[i++] = ch;
}
buffer[i] = '\0';  // terminating character

Note that this relies on the fact that you will read less than MAX_SIZE_OF_MY_BUFFER characters

How can I pass a Bitmap object from one activity to another

You can create a bitmap transfer. try this....

In the first class:

1) Create:

private static Bitmap bitmap_transfer;

2) Create getter and setter

public static Bitmap getBitmap_transfer() {
    return bitmap_transfer;
}

public static void setBitmap_transfer(Bitmap bitmap_transfer_param) {
    bitmap_transfer = bitmap_transfer_param;
}

3) Set the image:

ImageView image = (ImageView) view.findViewById(R.id.image);
image.buildDrawingCache();
setBitmap_transfer(image.getDrawingCache());

Then, in the second class:

ImageView image2 = (ImageView) view.findViewById(R.id.img2);
imagem2.setImageDrawable(new BitmapDrawable(getResources(), classe1.getBitmap_transfer()));

Get Number of Rows returned by ResultSet in Java

You could use a do ... while loop instead of a while loop, so that rs.next() is called after the loop is executed, like this:

if (!rs.next()) {                            //if rs.next() returns false
                                             //then there are no rows.
    System.out.println("No records found");

}
else {
    do {
        // Get data from the current row and use it
    } while (rs.next());
}

Or count the rows yourself as you're getting them:

int count = 0;

while (rs.next()) {
    ++count;
    // Get data from the current row and use it
}

if (count == 0) {
    System.out.println("No records found");
}

Changing element style attribute dynamically using JavaScript

Assuming you have HTML like this:

<div id='thediv'></div>

If you want to modify the style attribute of this div, you'd use

document.getElementById('thediv').style.[ATTRIBUTE] = '[VALUE]'

Replace [ATTRIBUTE] with the style attribute you want. Remember to remove '-' and make the following letter uppercase.

Examples

document.getElementById('thediv').style.display = 'none'; //changes the display
document.getElementById('thediv').style.paddingLeft = 'none'; //removes padding

How to delete a line from a text file in C#?

For very large files I'd do something like this

string tempFile = Path.GetTempFileName();

using(var sr = new StreamReader("file.txt"))
using(var sw = new StreamWriter(tempFile))
{
    string line;

    while((line = sr.ReadLine()) != null)
    {
         if(line != "removeme")
             sw.WriteLine(line);
    }
}

File.Delete("file.txt");
File.Move(tempFile, "file.txt");

Update I originally wrote this back in 2009 and I thought it might be interesting with an update. Today you could accomplish the above using LINQ and deferred execution

var tempFile = Path.GetTempFileName();
var linesToKeep = File.ReadLines(fileName).Where(l => l != "removeme");

File.WriteAllLines(tempFile, linesToKeep);

File.Delete(fileName);
File.Move(tempFile, fileName);

The code above is almost exactly the same as the first example, reading line by line and while keeping a minimal amount of data in memory.

A disclaimer might be in order though. Since we're talking about text files here you'd very rarely have to use the disk as an intermediate storage medium. If you're not dealing with very large log files there should be no problem reading the contents into memory instead and avoid having to deal with the temporary file.

File.WriteAllLines(fileName, 
    File.ReadLines(fileName).Where(l => l != "removeme").ToList());

Note that The .ToList is crucial here to force immediate execution. Also note that all the examples assume the text files are UTF-8 encoded.

PostgreSQL database default location on Linux

On Centos 6.5/PostgreSQL 9.3:

Change the value of "PGDATA=/var/lib/pgsql/data" to whatever location you want in the initial script file /etc/init.d/postgresql.

Remember to chmod 700 and chown postgres:postgres to the new location and you're the boss.

What is an uber jar?

A self-contained, executable Java archive. In the case of WildFly Swarm uberjars, it is a single .jar file containing your application, the portions of WildFly required to support it, an internal Maven repository of dependencies, plus a shim to bootstrap it all. see this

Convert seconds value to hours minutes seconds?

If you want the units h, min and sec for a duration you can use this:

public static String convertSeconds(int seconds) {
    int h = seconds/ 3600;
    int m = (seconds % 3600) / 60;
    int s = seconds % 60;
    String sh = (h > 0 ? String.valueOf(h) + " " + "h" : "");
    String sm = (m < 10 && m > 0 && h > 0 ? "0" : "") + (m > 0 ? (h > 0 && s == 0 ? String.valueOf(m) : String.valueOf(m) + " " + "min") : "");
    String ss = (s == 0 && (h > 0 || m > 0) ? "" : (s < 10 && (h > 0 || m > 0) ? "0" : "") + String.valueOf(s) + " " + "sec");
    return sh + (h > 0 ? " " : "") + sm + (m > 0 ? " " : "") + ss;
}

int seconds = 3661;
String duration = convertSeconds(seconds);

That's a lot of conditional operators. The method will return those strings:

0    -> 0 sec
5    -> 5 sec
60   -> 1 min
65   -> 1 min 05 sec
3600 -> 1 h
3601 -> 1 h 01 sec
3660 -> 1 h 01
3661 -> 1 h 01 min 01 sec
108000 -> 30 h

How to get POSTed JSON in Flask?

To give another approach.

from flask import Flask, jsonify, request
app = Flask(__name__)

@app.route('/service', methods=['POST'])
def service():
    data = json.loads(request.data)
    text = data.get("text",None)
    if text is None:
        return jsonify({"message":"text not found"})
    else:
        return jsonify(data)

if __name__ == '__main__':
    app.run(host= '0.0.0.0',debug=True)

Simple GUI Java calculator

assuming that string1 is your whole operation

use mdas

double result;
string recurAndCheck(string operation){
  if(operation.indexOf("/")){
     String leftSide = recurAndCheck(operation.split("/")[0]);
     string rightSide = recurAndCheck(operation.split("/")[1]);
     result = Double.parseDouble(leftSide)/Double.parseDouble(rightSide);

  } else if (..continue w/ *...) {
    //same as above but change / with *
  } else if (..continue w/ -) { 
    //change as above but change with -
  } else if (..continuew with +) {
    //change with add
  } else {
    return;
  }
}

How do I access Configuration in any class in ASP.NET Core?

Update

Using ASP.NET Core 2.0 will automatically add the IConfiguration instance of your application in the dependency injection container. This also works in conjunction with ConfigureAppConfiguration on the WebHostBuilder.

For example:

public static void Main(string[] args)
{
    var host = WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration(builder =>
        {
            builder.AddIniFile("foo.ini");
        })
        .UseStartup<Startup>()
        .Build();

    host.Run();
}

It's just as easy as adding the IConfiguration instance to the service collection as a singleton object in ConfigureServices:

public void ConfigureServices(IServiceCollection services)
{
   services.AddSingleton<IConfiguration>(Configuration);

   // ...
}

Where Configuration is the instance in your Startup class.

This allows you to inject IConfiguration in any controller or service:

public class HomeController
{
   public HomeController(IConfiguration configuration)
   {
      // Use IConfiguration instance
   }
}

How to add new activity to existing project in Android Studio?

In Android Studio 2, just right click on app and select New > Activity > ... to create desired activity type.

enter image description here

Display the current time and date in an Android application

Calendar c = Calendar.getInstance();
int month=c.get(Calendar.MONTH)+1;
String sDate = c.get(Calendar.YEAR) + "-" + month+ "-" + c.get(Calendar.DAY_OF_MONTH) +
"T" + c.get(Calendar.HOUR_OF_DAY)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND);

This will give date time format like 2010-05-24T18:13:00

java: How can I do dynamic casting of a variable from one type to another?

Try this for Dynamic Casting. It will work!!!

    String something = "1234";
    String theType = "java.lang.Integer";
    Class<?> theClass = Class.forName(theType);
    Constructor<?> cons = theClass.getConstructor(String.class);
    Object ob =  cons.newInstance(something);
    System.out.println(ob.equals(1234));

How to open a web page from my application?

While a good answer has been given (using Process.Start), it is safer to encapsulate it in a function that checks that the passed string is indeed a URI, to avoid accidentally starting random processes on the machine.

public static bool IsValidUri(string uri)
{
    if (!Uri.IsWellFormedUriString(uri, UriKind.Absolute))
        return false;
    Uri tmp;
    if (!Uri.TryCreate(uri, UriKind.Absolute, out tmp))
        return false;
    return tmp.Scheme == Uri.UriSchemeHttp || tmp.Scheme == Uri.UriSchemeHttps;
}

public static bool OpenUri(string uri) 
{
    if (!IsValidUri(uri))
        return false;
     System.Diagnostics.Process.Start(uri);
     return true;
}

How to reload / refresh model data from the server programmatically?

You're half way there on your own. To implement a refresh, you'd just wrap what you already have in a function on the scope:

function PersonListCtrl($scope, $http) {
  $scope.loadData = function () {
     $http.get('/persons').success(function(data) {
       $scope.persons = data;
     });
  };

  //initial load
  $scope.loadData();
}

then in your markup

<div ng-controller="PersonListCtrl">
    <ul>
        <li ng-repeat="person in persons">
            Name: {{person.name}}, Age {{person.age}}
        </li>
    </ul>
   <button ng-click="loadData()">Refresh</button>
</div>

As far as "accessing your model", all you'd need to do is access that $scope.persons array in your controller:

for example (just puedo code) in your controller:

$scope.addPerson = function() {
     $scope.persons.push({ name: 'Test Monkey' });
};

Then you could use that in your view or whatever you'd want to do.

Setup a Git server with msysgit on Windows

GitStack should meet your goal. I has a wizard setup. It is free for 2 users and has a web based user interface. It is based on msysgit.

What is the actual use of Class.forName("oracle.jdbc.driver.OracleDriver") while connecting to a database?

It registers the driver; something of the form:

public class SomeDriver implements Driver {
  static {
    try {
      DriverManager.registerDriver(new SomeDriver());
    } catch (SQLException e) {
      // TODO Auto-generated catch block
    }
  }

  //etc: implemented methods
}

Rock, Paper, Scissors Game Java

You could insert something like this:

personPlay = "B";

while (!personPlay.equals("R") && !personPlay.equals("P") && !personPlay.equals("S")) {

    //Get player's play from input-- note that this is 
    // stored as a string 
    System.out.println("Enter your play: "); 
    personPlay = scan.next();

    //Make player's play uppercase for ease of comparison 
    personPlay = personPlay.toUpperCase();

    if (!personPlay.equals("R") && !personPlay.equals("P") && !personPlay.equals("S"))
        System.out.println("Invalid move. Try again.");

}

How to establish ssh key pair when "Host key verification failed"

Most likely, the remote host ip or ip_alias is not in the ~/.ssh/known_hosts file. You can use the following command to add the host name to known_hosts file.

$ssh-keyscan -H -t rsa ip_or_ipalias >> ~/.ssh/known_hosts

Also, I have generated the following script to check if the particular ip or ipalias is in the know_hosts file.

#!/bin/bash
#Jason Xiong: Dec 2013   
# The ip or ipalias stored in known_hosts file is hashed and   
# is not human readable.This script check if the supplied ip    
# or ipalias exists in ~/.ssh/known_hosts file

if [[ $# != 2 ]]; then
   echo "Usage: ./search_known_hosts -i ip_or_ipalias"
   exit;
fi
ip_or_alias=$2;
known_host_file=/home/user/.ssh/known_hosts
entry=1;

cat $known_host_file | while read -r line;do
  if [[ -z "$line" ]]; then
    continue;
  fi   
  hash_type=$(echo $line | sed -e 's/|/ /g'| awk '{print $1}'); 
  key=$(echo $line | sed -e 's/|/ /g'| awk '{print $2}');
  stored_value=$(echo $line | sed -e 's/|/ /g'| awk '{print $3}'); 
  hex_key=$(echo $key | base64 -d | xxd -p); 
  if  [[ $hash_type = 1 ]]; then      
     gen_value=$(echo -n $ip_or_alias | openssl sha1 -mac HMAC \
         -macopt hexkey:$hex_key | cut -c 10-49 | xxd -r -p | base64);     
     if [[ $gen_value = $stored_value ]]; then
       echo $gen_value;
       echo "Found match in known_hosts file : entry#"$entry" !!!!"
     fi
  else
     echo "unknown hash_type"
  fi
  entry=$((entry + 1));
done

Why is the Java main method static?

If the main method would not be static, you would need to create an object of your main class from outside the program. How would you want to do that?

How to get size of mysql database?

First login to MySQL using

mysql -u username -p

Command to Display the size of a single Database along with its table in MB.

SELECT table_name AS "Table",
ROUND(((data_length + index_length) / 1024 / 1024), 2) AS "Size (MB)"
FROM information_schema.TABLES
WHERE table_schema = "database_name"
ORDER BY (data_length + index_length) DESC;

Change database_name to your Database

Command to Display all the Databases with its size in MB.

SELECT table_schema AS "Database", 
ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS "Size (MB)" 
FROM information_schema.TABLES 
GROUP BY table_schema;

Flutter command not found

You can do these..

  1. First, open your Mac Terminal
  2. Run 'open -e .bash_profile'
  3. Then add 'PATH="/Volumes/Application/Mobile/flutter/bin:${PATH}" export PATH'
  4. Then Save file & close

Get changes from master into branch in Git

This (from here) worked for me:

git checkout aq
git pull origin master
...
git push

Quoting:

git pull origin master fetches and merges the contents of the master branch with your branch and creates a merge commit. If there are any merge conflicts you'll be notified at this stage and you must resolve the merge commits before proceeding. When you are ready to push your local commits, including your new merge commit, to the remote server, run git push.

Measure the time it takes to execute a t-sql query

DECLARE @StartTime datetime
DECLARE @EndTime datetime
SELECT @StartTime=GETDATE() 

 -- Write Your Query


SELECT @EndTime=GETDATE()

--This will return execution time of your query
SELECT DATEDIFF(MS,@StartTime,@EndTime) AS [Duration in millisecs]

You can also See this solution

Call to undefined function curl_init().?

If you're on Windows:

Go to your php.ini file and remove the ; mark from the beginning of the following line:

;extension=php_curl.dll

After you have saved the file you must restart your HTTP server software (e.g. Apache) before this can take effect.


For Ubuntu 13.0 and above, simply use the debundled package. In a terminal type the following to install it and do not forgot to restart server.

sudo apt-get install php-curl

Or if you're using the old PHP5

sudo apt-get install php5-curl

or

sudo apt-get install php5.6-curl

Then restart apache to activate the package with

sudo service apache2 restart

How to change border color of textarea on :focus

Try out this probably it will work

input{
outline-color: #fff //your color
outline-style: none // it depend on you 
}

CSS selector - element with a given child

I agree that it is not possible in general.

The only thing CSS3 can do (which helped in my case) is to select elements that have no children:

table td:empty
{
   background-color: white;
}

Or have any children (including text):

table td:not(:empty)
{
   background-color: white;
}

Status bar and navigation bar appear over my view's bounds in iOS 7

Swift 3

override func viewWillAppear(_ animated: Bool) {
    self.edgesForExtendedLayout = []
}

How to change font size in Eclipse for Java text editors?

This worked for me:

  1. On the Eclipse toolbar, select Window ? Preferences.

  2. Set the font size (General ? Appearance ? Colors and Fonts ? Basic ? Text Font):

    Enter image description here

  3. Save the preferences.

How to create a density plot in matplotlib?

Sven has shown how to use the class gaussian_kde from Scipy, but you will notice that it doesn't look quite like what you generated with R. This is because gaussian_kde tries to infer the bandwidth automatically. You can play with the bandwidth in a way by changing the function covariance_factor of the gaussian_kde class. First, here is what you get without changing that function:

alt text

However, if I use the following code:

import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import gaussian_kde
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
density = gaussian_kde(data)
xs = np.linspace(0,8,200)
density.covariance_factor = lambda : .25
density._compute_covariance()
plt.plot(xs,density(xs))
plt.show()

I get

alt text

which is pretty close to what you are getting from R. What have I done? gaussian_kde uses a changable function, covariance_factor to calculate its bandwidth. Before changing the function, the value returned by covariance_factor for this data was about .5. Lowering this lowered the bandwidth. I had to call _compute_covariance after changing that function so that all of the factors would be calculated correctly. It isn't an exact correspondence with the bw parameter from R, but hopefully it helps you get in the right direction.

How can I nullify css property?

You need to provide a selector with higher specificity than the one in Main.css. With that selector, set the values of the properties you want to their default, e.g.

body .c1 {
    height: auto;
}

There is no "default" value that will work for all properties, you need to look up what the default is for each one and use that.

Event binding on dynamically created elements?

This is a pure JavaScript solution without any libraries or plugins:

document.addEventListener('click', function (e) {
    if (hasClass(e.target, 'bu')) {
        // .bu clicked
        // Do your thing
    } else if (hasClass(e.target, 'test')) {
        // .test clicked
        // Do your other thing
    }
}, false);

where hasClass is

function hasClass(elem, className) {
    return elem.className.split(' ').indexOf(className) > -1;
}

Live demo

Credit goes to Dave and Sime Vidas

Using more modern JS, hasClass can be implemented as:

function hasClass(elem, className) {
    return elem.classList.contains(className);
}

ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d

I had the exact same error. It turned out that it was something was caused by something completely, though. It was missing write permissions in a cache folder. But IIS reported error 0x8007000d which is wildly confusing.

Best way to compare 2 XML documents in Java

I'm using Altova DiffDog which has options to compare XML files structurally (ignoring string data).

This means that (if checking the 'ignore text' option):

<foo a="xxx" b="xxx">xxx</foo>

and

<foo b="yyy" a="yyy">yyy</foo> 

are equal in the sense that they have structural equality. This is handy if you have example files that differ in data, but not structure!

Getting datarow values into a string?

You can get a columns value by doing this

 rows["ColumnName"]

You will also have to cast to the appropriate type.

 output += (string)rows["ColumnName"]

JavaScript variable assignments from tuples

A frozen array behaves identically to a python tuple:

const tuple = Object.freeze(["Bob", 24]);
let [name, age]; = tuple
console.debug(name); // "Bob"
console.debug(age); // 24

Be fancy and define a class

class Tuple extends Array { 
  constructor(...items) { 
    super(...items); 
    Object.freeze(this);
  } 
}

let tuple = new Tuple("Jim", 35);
let [name, age] = tuple;
console.debug(name); // Jim
console.debug(age); // 35
tuple = ["Bob", 24]; // no effect 
console.debug(name); // Jim
console.debug(age); // 25

Works today in all the latest browsers.

Get min and max value in PHP Array

foreach ($array as $k => $v) {
  $tArray[$k] = $v['Weight'];
}
$min_value = min($tArray);
$max_value = max($tArray);

How to pass data to view in Laravel?

You can also write for passing multiple data from your controller to a view

 return \View::make('myHome')
            ->with(compact('project'))
            ->with(['hello'=>$hello])
            ->with(['hello2'=>$hello2])
            ->with(['hello3'=>$hello3]);

How does origin/HEAD get set?

What moves origin/HEAD "organically"?

  • git clone sets it once to the spot where HEAD is on origin
    • it serves as the default branch to checkout after cloning with git clone

What does HEAD on origin represent?

  • on bare repositories (often repositories “on servers”) it serves as a marker for the default branch, because git clone uses it in such a way
  • on non-bare repositories (local or remote), it reflects the repository’s current checkout

What sets origin/HEAD?

  • git clone fetches and sets it
  • it would make sense if git fetch updates it like any other reference, but it doesn’t
  • git remote set-head origin -a fetches and sets it
    • useful to update the local knowledge of what remote considers the “default branch”

Trivia

  • origin/HEAD can also be set to any other value without contacting the remote: git remote set-head origin <branch>
    • I see no use-case for this, except for testing
  • unfortunately nothing is able to set HEAD on the remote
  • older versions of git did not know which branch HEAD points to on the remote, only which commit hash it finally has: so it just hopefully picked a branch name pointing to the same hash

Batchfile to create backup and rename with timestamp

Renames all .pdf files based on current system date. For example a file named Gross Profit.pdf is renamed to Gross Profit 2014-07-31.pdf. If you run it tomorrow, it will rename it to Gross Profit 2014-08-01.pdf.

You could replace the ? with the report name Gross Profit, but it will only rename the one report. The ? renames everything in the Conduit folder. The reason there are so many ?, is that some .pdfs have long names. If you just put 12 ?s, then any name longer than 12 characters will be clipped off at the 13th character. Try it with 1 ?, then try it with many ?s. The ? length should be a little longer or as long as the longest report name.

@ECHO OFF
SET NETWORKSOURCE=\\flcorpfile\shared\"SHORE Reports"\2014\Conduit
REN %NETWORKSOURCE%\*.pdf "????????????????????????????????????????????????? %date:~-4,4%-%date:~-10,2%-%date:~7,2%.pdf"

How to add/update child entities when updating a parent entity in EF

@Charles McIntosh really gave me the answer for my situation in that the passed in model was detached. For me what ultimately worked was saving the passed in model first... then continuing to add the children as I already was before:

public async Task<IHttpActionResult> GetUPSFreight(PartsExpressOrder order)
{
    db.Entry(order).State = EntityState.Modified;
    db.SaveChanges();
  ...
}

Detect application heap size in Android

Runtime rt = Runtime.getRuntime();
rt.maxMemory()

value is b

ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
am.getMemoryClass()

value is MB

Android Error Building Signed APK: keystore.jks not found for signing config 'externalOverride'

open key.properties and check your path is correct. (replace from \ to /)

example:-

replace from "storeFile=D:\Projects\Flutter\Key\key.jks" to "storeFile=D:/Projects/Flutter/Key/key.jks"

response.sendRedirect() from Servlet to JSP does not seem to work

I'm posting this answer because the one with the most votes led me astray. To redirect from a servlet, you simply do this:

response.sendRedirect("simpleList.do")

In this particular question, I think @M-D is correctly explaining why the asker is having his problem, but since this is the first result on google when you search for "Redirect from Servlet" I think it's important to have an answer that helps most people, not just the original asker.

How can I switch language in google play?

Answer below the dotted line below is the original that's now outdated.

Here is the latest information ( Thank you @deadfish ):

add &hl=<language> like &hl=pl or &hl=en

example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl

All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en

......................................................................

To change the actual local market:

Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html

To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720

java, get set methods

your panel class don't have a constructor that accepts a string

try change

RLS_strid_panel p = new RLS_strid_panel(namn1);

to

RLS_strid_panel p = new RLS_strid_panel();
p.setName1(name1);

How to sort a HashMap in Java

http://snipplr.com/view/2789/sorting-map-keys-by-comparing-its-values/

get the keys

List keys = new ArrayList(yourMap.keySet());

Sort them

 Collections.sort(keys)

print them.

In any case, you can't have sorted values in HashMap (according to API This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time ].

Though you can push all these values to LinkedHashMap, for later use as well.

How to generate classes from wsdl using Maven and wsimport?

The key here is keep option of wsimport. And it is configured using element in About keep from the wsimport documentation :

-keep                     keep generated files

How to loop through a dataset in powershell?

The PowerShell string evaluation is calling ToString() on the DataSet. In order to evaluate any properties (or method calls), you have to force evaluation by enclosing the expression in $()

for($i=0;$i -lt $ds.Tables[1].Rows.Count;$i++)
{ 
  write-host "value is : $i $($ds.Tables[1].Rows[$i][0])"
}

Additionally foreach allows you to iterate through a collection or array without needing to figure out the length.

Rewritten (and edited for compile) -

foreach ($Row in $ds.Tables[1].Rows)
{ 
  write-host "value is : $($Row[0])"
}

How to locate and insert a value in a text box (input) using Python Selenium?

Assuming your page is available under "http://example.com"

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://example.com")

Select element by id:

inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')

Now you can simulate hitting ENTER:

inputElement.send_keys(Keys.ENTER)

or if it is a form you can submit:

inputElement.submit() 

How to get WooCommerce order details

ONLY FOR WOOCOMMERCE VERSIONS 2.5.x AND 2.6.x

For WOOCOMMERCE VERSION 3.0+ see THIS UPDATE

Here is a custom function I have made, to make the things clear for you, related to get the data of an order ID. You will see all the different RAW outputs you can get and how to get the data you need…

Using print_r() function (or var_dump() function too) allow to output the raw data of an object or an array.

So first I output this data to show the object or the array hierarchy. Then I use different syntax depending on the type of that variable (string, array or object) to output the specific data needed.

IMPORTANT: With $order object you can use most of WC_order or WC_Abstract_Order methods (using the object syntax)…


Here is the code:

function get_order_details($order_id){

    // 1) Get the Order object
    $order = wc_get_order( $order_id );

    // OUTPUT
    echo '<h3>RAW OUTPUT OF THE ORDER OBJECT: </h3>';
    print_r($order);
    echo '<br><br>';
    echo '<h3>THE ORDER OBJECT (Using the object syntax notation):</h3>';
    echo '$order->order_type: ' . $order->order_type . '<br>';
    echo '$order->id: ' . $order->id . '<br>';
    echo '<h4>THE POST OBJECT:</h4>';
    echo '$order->post->ID: ' . $order->post->ID . '<br>';
    echo '$order->post->post_author: ' . $order->post->post_author . '<br>';
    echo '$order->post->post_date: ' . $order->post->post_date . '<br>';
    echo '$order->post->post_date_gmt: ' . $order->post->post_date_gmt . '<br>';
    echo '$order->post->post_content: ' . $order->post->post_content . '<br>';
    echo '$order->post->post_title: ' . $order->post->post_title . '<br>';
    echo '$order->post->post_excerpt: ' . $order->post->post_excerpt . '<br>';
    echo '$order->post->post_status: ' . $order->post->post_status . '<br>';
    echo '$order->post->comment_status: ' . $order->post->comment_status . '<br>';
    echo '$order->post->ping_status: ' . $order->post->ping_status . '<br>';
    echo '$order->post->post_password: ' . $order->post->post_password . '<br>';
    echo '$order->post->post_name: ' . $order->post->post_name . '<br>';
    echo '$order->post->to_ping: ' . $order->post->to_ping . '<br>';
    echo '$order->post->pinged: ' . $order->post->pinged . '<br>';
    echo '$order->post->post_modified: ' . $order->post->post_modified . '<br>';
    echo '$order->post->post_modified_gtm: ' . $order->post->post_modified_gtm . '<br>';
    echo '$order->post->post_content_filtered: ' . $order->post->post_content_filtered . '<br>';
    echo '$order->post->post_parent: ' . $order->post->post_parent . '<br>';
    echo '$order->post->guid: ' . $order->post->guid . '<br>';
    echo '$order->post->menu_order: ' . $order->post->menu_order . '<br>';
    echo '$order->post->post_type: ' . $order->post->post_type . '<br>';
    echo '$order->post->post_mime_type: ' . $order->post->post_mime_type . '<br>';
    echo '$order->post->comment_count: ' . $order->post->comment_count . '<br>';
    echo '$order->post->filter: ' . $order->post->filter . '<br>';
    echo '<h4>THE ORDER OBJECT (again):</h4>';
    echo '$order->order_date: ' . $order->order_date . '<br>';
    echo '$order->modified_date: ' . $order->modified_date . '<br>';
    echo '$order->customer_message: ' . $order->customer_message . '<br>';
    echo '$order->customer_note: ' . $order->customer_note . '<br>';
    echo '$order->post_status: ' . $order->post_status . '<br>';
    echo '$order->prices_include_tax: ' . $order->prices_include_tax . '<br>';
    echo '$order->tax_display_cart: ' . $order->tax_display_cart . '<br>';
    echo '$order->display_totals_ex_tax: ' . $order->display_totals_ex_tax . '<br>';
    echo '$order->display_cart_ex_tax: ' . $order->display_cart_ex_tax . '<br>';
    echo '$order->formatted_billing_address->protected: ' . $order->formatted_billing_address->protected . '<br>';
    echo '$order->formatted_shipping_address->protected: ' . $order->formatted_shipping_address->protected . '<br><br>';
    echo '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <br><br>';

    // 2) Get the Order meta data
    $order_meta = get_post_meta($order_id);

    echo '<h3>RAW OUTPUT OF THE ORDER META DATA (ARRAY): </h3>';
    print_r($order_meta);
    echo '<br><br>';
    echo '<h3>THE ORDER META DATA (Using the array syntax notation):</h3>';
    echo '$order_meta[_order_key][0]: ' . $order_meta[_order_key][0] . '<br>';
    echo '$order_meta[_order_currency][0]: ' . $order_meta[_order_currency][0] . '<br>';
    echo '$order_meta[_prices_include_tax][0]: ' . $order_meta[_prices_include_tax][0] . '<br>';
    echo '$order_meta[_customer_user][0]: ' . $order_meta[_customer_user][0] . '<br>';
    echo '$order_meta[_billing_first_name][0]: ' . $order_meta[_billing_first_name][0] . '<br><br>';
    echo 'And so on ……… <br><br>';
    echo '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <br><br>';

    // 3) Get the order items
    $items = $order->get_items();

    echo '<h3>RAW OUTPUT OF THE ORDER ITEMS DATA (ARRAY): </h3>';

    foreach ( $items as $item_id => $item_data ) {

        echo '<h4>RAW OUTPUT OF THE ORDER ITEM NUMBER: '. $item_id .'): </h4>';
        print_r($item_data);
        echo '<br><br>';
        echo 'Item ID: ' . $item_id. '<br>';
        echo '$item_data["product_id"] <i>(product ID)</i>: ' . $item_data['product_id'] . '<br>';
        echo '$item_data["name"] <i>(product Name)</i>: ' . $item_data['name'] . '<br>';

        // Using get_item_meta() method
        echo 'Item quantity <i>(product quantity)</i>: ' . $order->get_item_meta($item_id, '_qty', true) . '<br><br>';
        echo 'Item line total <i>(product quantity)</i>: ' . $order->get_item_meta($item_id, '_line_total', true) . '<br><br>';
        echo 'And so on ……… <br><br>';
        echo '- - - - - - - - - - - - - <br><br>';
    }
    echo '- - - - - - E N D - - - - - <br><br>';
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Usage (if your order ID is 159 for example):

get_order_details(159);

This code is tested and works.

Updated code on November 21, 2016

PHP cURL, extract an XML response

Example:

<songs>
<song dateplayed="2011-07-24 19:40:26">
    <title>I left my heart on Europa</title>
    <artist>Ship of Nomads</artist>
</song>
<song dateplayed="2011-07-24 19:27:42">
    <title>Oh Ganymede</title>
    <artist>Beefachanga</artist>
</song>
<song dateplayed="2011-07-24 19:23:50">
    <title>Kallichore</title>
    <artist>Jewitt K. Sheppard</artist>
</song>

then:

<?php
$mysongs = simplexml_load_file('songs.xml');
echo $mysongs->song[0]->artist;
?>

Output on your browser: Ship of Nomads

credits: http://blog.teamtreehouse.com/how-to-parse-xml-with-php5

Replace single quotes in SQL Server

select replace ( colname, '''', '') AS colname FROM .[dbo].[Db Name]

add a string prefix to each value in a string column using Pandas

As an alternative, you can also use an apply combined with format (or better with f-strings) which I find slightly more readable if one e.g. also wants to add a suffix or manipulate the element itself:

df = pd.DataFrame({'col':['a', 0]})

df['col'] = df['col'].apply(lambda x: "{}{}".format('str', x))

which also yields the desired output:

    col
0  stra
1  str0

If you are using Python 3.6+, you can also use f-strings:

df['col'] = df['col'].apply(lambda x: f"str{x}")

yielding the same output.

The f-string version is almost as fast as @RomanPekar's solution (python 3.6.4):

df = pd.DataFrame({'col':['a', 0]*200000})

%timeit df['col'].apply(lambda x: f"str{x}")
117 ms ± 451 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit 'str' + df['col'].astype(str)
112 ms ± 1.04 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Using format, however, is indeed far slower:

%timeit df['col'].apply(lambda x: "{}{}".format('str', x))
185 ms ± 1.07 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

How to update the value stored in Dictionary in C#?

  1. update - modify existent only. To avoid side effect of indexer use:

    int val;
    if (dic.TryGetValue(key, out val))
    {
        // key exist
        dic[key] = val;
    }
    
  2. update or (add new if value doesn't exist in dic)

    dic[key] = val;
    

    for instance:

    d["Two"] = 2; // adds to dictionary because "two" not already present
    d["Two"] = 22; // updates dictionary because "two" is now present
    

How do I see all foreign keys to a table or column?

The solution I came up with is fragile; it relies on django's naming convention for foreign keys.

USE information_schema;
tee mysql_output
SELECT * FROM TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_SCHEMA = 'database_name';
notee

Then, in the shell,

grep 'refs_tablename_id' mysql_output

implement time delay in c

In standard C (C99), you can use time() to do this, something like:

#include <time.h>
:
void waitFor (unsigned int secs) {
    unsigned int retTime = time(0) + secs;   // Get finishing time.
    while (time(0) < retTime);               // Loop until it arrives.
}

By the way, this assumes time() returns a 1-second resolution value. I don't think that's mandated by the standard so you may have to adjust for it.


In order to clarify, this is the only way I'm aware of to do this with ISO C99 (and the question is tagged with nothing more than "C" which usually means portable solutions are desirable although, of course, vendor-specific solutions may still be given).

By all means, if you're on a platform that provides a more efficient way, use it. As several comments have indicated, there may be specific problems with a tight loop like this, with regard to CPU usage and battery life.

Any decent time-slicing OS would be able to drop the dynamic priority of a task that continuously uses its full time slice but the battery power may be more problematic.

However C specifies nothing about the OS details in a hosted environment, and this answer is for ISO C and ISO C alone (so no use of sleep, select, Win32 API calls or anything like that).

And keep in mind that POSIX sleep can be interrupted by signals. If you are going to go down that path, you need to do something like:

int finishing = 0; // set finishing in signal handler 
                   // if you want to really stop.

void sleepWrapper (unsigned int secs) {
    unsigned int left = secs;
    while ((left > 0) && (!finishing)) // Don't continue if signal has
        left = sleep (left);           //   indicated exit needed.
}

How to implement 2D vector array?

//initialize the 2D vector first

vector<vector<int>> matrix;

//initialize the 1D vector you would like to insert into matrix

vector<int> row;

//initializing row with values

row.push_back(val1);

row.push_back(val2);

//now inserting values into matrix

matrix.push_back(row);

//output- [[val1,val2]]

How do I add a placeholder on a CharField in Django?

After looking at your method, I used this method to solve it.

class Register(forms.Form):
    username = forms.CharField(label='???', max_length=32)
    email = forms.EmailField(label='??', max_length=64)
    password = forms.CharField(label="??", min_length=6, max_length=16)
    captcha = forms.CharField(label="???", max_length=4)

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    for field_name in self.fields:
        field = self.fields.get(field_name)
        self.fields[field_name].widget.attrs.update({
            "placeholder": field.label,
            'class': "input-control"
        })

Occurrences of substring in a string

A lot of the given answers fail on one or more of:

  • Patterns of arbitrary length
  • Overlapping matches (such as counting "232" in "23232" or "aa" in "aaa")
  • Regular expression meta-characters

Here's what I wrote:

static int countMatches(Pattern pattern, String string)
{
    Matcher matcher = pattern.matcher(string);

    int count = 0;
    int pos = 0;
    while (matcher.find(pos))
    {
        count++;
        pos = matcher.start() + 1;
    }

    return count;
}

Example call:

Pattern pattern = Pattern.compile("232");
int count = countMatches(pattern, "23232"); // Returns 2

If you want a non-regular-expression search, just compile your pattern appropriately with the LITERAL flag:

Pattern pattern = Pattern.compile("1+1", Pattern.LITERAL);
int count = countMatches(pattern, "1+1+1"); // Returns 2

Iframe transparent background

Why not just load the frame off screen or hidden and then display it once it has finished loading. You could show a loading icon in its place to begin with to give the user immediate feedback that it's loading.

PHP : send mail in localhost

I spent hours on this. I used to not get errors but mails were never sent. Finally I found a solution and I would like to share it.

<?php
include 'nav.php';
/*
    Download PhpMailer from the following link:
    https://github.com/Synchro/PHPMailer (CLick on Download zip on the right side)
    Extract the PHPMailer-master folder into your xampp->htdocs folder
    Make changes in the following code and its done :-)

    You will receive the mail with the name Root User.
    To change the name, go to class.phpmailer.php file in your PHPMailer-master folder,
    And change the name here: 
    public $FromName = 'Root User';
*/
require("PHPMailer-master/PHPMailerAutoload.php"); //or select the proper destination for this file if your page is in some   //other folder
ini_set("SMTP","ssl://smtp.gmail.com"); 
ini_set("smtp_port","465"); //No further need to edit your configuration files.
$mail = new PHPMailer();
$mail->SMTPAuth = true;
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->SMTPSecure = "ssl";
$mail->Username = "[email protected]"; //account with which you want to send mail. Or use this account. i dont care :-P
$mail->Password = "trials.php.php"; //this account's password.
$mail->Port = "465";
$mail->isSMTP();  // telling the class to use SMTP
$rec1="[email protected]"; //receiver. email addresses to which u want to send the mail.
$mail->AddAddress($rec1);
$mail->Subject  = "Eventbook";
$mail->Body     = "Hello hi, testing";
$mail->WordWrap = 200;
if(!$mail->Send()) {
echo 'Message was not sent!.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo  //Fill in the document.location thing
'<script type="text/javascript">
                        if(confirm("Your mail has been sent"))
                        document.location = "/";
        </script>';
}
?>

Simple Vim commands you wish you'd known earlier

vimcryption

vim -x filename.txt

You will be asked for a passphrase, edit and save. Now whenever you open the file in vi again you will have to enter the password to view.

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

Custom thread pool in Java 8 parallel stream

The parallel streams use the default ForkJoinPool.commonPool which by default has one less threads as you have processors, as returned by Runtime.getRuntime().availableProcessors() (This means that parallel streams leave one processor for the calling thread).

For applications that require separate or custom pools, a ForkJoinPool may be constructed with a given target parallelism level; by default, equal to the number of available processors.

This also means if you have nested parallel streams or multiple parallel streams started concurrently, they will all share the same pool. Advantage: you will never use more than the default (number of available processors). Disadvantage: you may not get "all the processors" assigned to each parallel stream you initiate (if you happen to have more than one). (Apparently you can use a ManagedBlocker to circumvent that.)

To change the way parallel streams are executed, you can either

  • submit the parallel stream execution to your own ForkJoinPool: yourFJP.submit(() -> stream.parallel().forEach(soSomething)).get(); or
  • you can change the size of the common pool using system properties: System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "20") for a target parallelism of 20 threads. However, this no longer works after the backported patch https://bugs.openjdk.java.net/browse/JDK-8190974.

Example of the latter on my machine which has 8 processors. If I run the following program:

long start = System.currentTimeMillis();
IntStream s = IntStream.range(0, 20);
//System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "20");
s.parallel().forEach(i -> {
    try { Thread.sleep(100); } catch (Exception ignore) {}
    System.out.print((System.currentTimeMillis() - start) + " ");
});

The output is:

215 216 216 216 216 216 216 216 315 316 316 316 316 316 316 316 415 416 416 416

So you can see that the parallel stream processes 8 items at a time, i.e. it uses 8 threads. However, if I uncomment the commented line, the output is:

215 215 215 215 215 216 216 216 216 216 216 216 216 216 216 216 216 216 216 216

This time, the parallel stream has used 20 threads and all 20 elements in the stream have been processed concurrently.