Programs & Examples On #Piracy

Piracy is the use of works under copyright, infringing the copyright holder's exclusive rights, such as the right to reproduce, distribute, display or perform the copyrighted work, or to make derivative works, without permission from the copyright holder, which is typically a publisher or other business representing or assigned by the work's creator.

How are software license keys generated?

If you aren't particularly concerned with the length of the key, a pretty tried and true method is the use of public and private key encryption.

Essentially have some kind of nonce and a fixed signature.

For example: 0001-123456789

Where 0001 is your nonce and 123456789 is your fixed signature.

Then encrypt this using your private key to get your CD key which is something like: ABCDEF9876543210

Then distribute the public key with your application. The public key can be used to decrypt the CD key "ABCDEF9876543210", which you then verify the fixed signature portion of.

This then prevents someone from guessing what the CD key is for the nonce 0002 because they don't have the private key.

The only major down side is that your CD keys will be quite long when using private / public keys 1024-bit in size. You also need to choose a nonce long enough so you aren't encrypting a trivial amount of information.

The up side is that this method will work without "activation" and you can use things like an email address or licensee name as the nonce.

How can I protect my .NET assemblies from decompilation?

Besides the third party products listed here, there is another one: NetLib Encryptionizer. However it works in a different way than the obfuscators. Obfuscators modify the assembly itself with a deobfuscation "engine" built into it. Encryptionizer encrypts the DLLs (Managed or Unmanaged) at the file level. So it does not modify the DLL except to encrypt it. The "engine" in this case is a kernel mode driver that sits between your application and the operating system. (Disclaimer: I am from NetLib Security)

Protect .NET code from reverse engineering?

  • Use online update to block those unlicensed copies.

  • Verify serial number from different modules of your application and do not use a single function call to do the verification (so that crackers cannot bypass the verification easily).

  • Not only check serial number at startup, do the verification while saving data, do it every Friday evening, do it when user is idle ...

  • Verify application file check sum, store your security check sum in different places.

  • Don't go too far on these kind of tricks, make sure your application never crash/get into malfunction while verifying registration code.

  • Build a useful app for users is much more important than make a
    unbreakable binary for crackers.

Unable to Resolve Module in React Native App

Hardware -> Erase all content and settings did the job for me (other things didn't).

Location of GlassFish Server Logs

Locate the installation path of GlassFish. Then move to domains/domain-dir/logs/ and you'll find there the log files. If you have created the domain with NetBeans, the domain-dir is most probably called domain1.

See this link for the official GlassFish documentation about logging.

Aligning a float:left div to center?

Perhaps this what you're looking for - https://www.w3schools.com/css/css3_flexbox.asp

CSS:

#container {
  display:                 flex;
  flex-wrap:               wrap;
  justify-content:         center;
}

.block {
  width:              150px;
  height:             150px;
  margin:             10px;        
}

HTML:

<div id="container">
  <div class="block">1</div>    
  <div class="block">2</div>    
  <div class="block">3</div>          
</div>

SQL Server Regular expressions in T-SQL

There is some basic pattern matching available through using LIKE, where % matches any number and combination of characters, _ matches any one character, and [abc] could match a, b, or c... There is more info on the MSDN site.

How to get last key in an array?

Dont know if this is going to be faster or not, but it seems easier to do it this way, and you avoid the error by not passing in a function to end()...

it just needed a variable... not a big deal to write one more line of code, then unset it if you needed to.

$array = array(
    'first' => 123,
    'second' => 456,
    'last' => 789, 
);

$keys = array_keys($array);
$last = end($keys);

MySQL LEFT JOIN 3 tables

You are trying to join Person_Fear.PersonID onto Person_Fear.FearID - This doesn't really make sense. You probably want something like:

SELECT Persons.Name, Persons.SS, Fears.Fear FROM Persons
LEFT JOIN Person_Fear
    INNER JOIN Fears
    ON Person_Fear.FearID = Fears.FearID
ON Person_Fear.PersonID = Persons.PersonID

This joins Persons onto Fears via the intermediate table Person_Fear. Because the join between Persons and Person_Fear is a LEFT JOIN, you will get all Persons records.

Alternatively:

SELECT Persons.Name, Persons.SS, Fears.Fear FROM Persons
LEFT JOIN Person_Fear ON Person_Fear.PersonID = Persons.PersonID
LEFT JOIN Fears ON Person_Fear.FearID = Fears.FearID

How to fix "could not find a base address that matches schema http"... in WCF

Confirmed my fix:

In your web.config file you should configure it to look as such:

<system.serviceModel >
    <serviceHostingEnvironment configSource=".\Configurations\ServiceHosting.config" />
    ...

Then, build a folder structure that looks like this:

/web.config
/Configurations/ServiceHosting.config
/Configurations/Deploy/ServiceHosting.config

The base serviceHosting.config should look like this:

<?xml version="1.0"?>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true">
    <baseAddressPrefixFilters>
    </baseAddressPrefixFilters>
</serviceHostingEnvironment>

while the one in /Deploy looks like this:

<serviceHostingEnvironment aspNetCompatibilityEnabled="true">
    <baseAddressPrefixFilters>
        <add prefix="http://myappname.web707.discountasp.net"/>
    </baseAddressPrefixFilters>
</serviceHostingEnvironment>

Beyond this, you need to add a manual or automated deployment step to copy the file from /Deploy overtop the one in /Configurations. This works incredibly well for service address and connection strings, and saves effort doing other workarounds.

If you don't like this approach (which scales well to farms, but is weaker on single machine), you might consider adding a web.config file a level up from the service deployment on the host's machine and put the serviceHostingEnvironment node there. It should cascade for you.

Begin, Rescue and Ensure in Ruby?

FYI, even if an exception is re-raised in the rescue section, the ensure block will be executed before the code execution continues to the next exception handler. For instance:

begin
  raise "Error!!"
rescue
  puts "test1"
  raise # Reraise exception
ensure
  puts "Ensure block"
end

Is it possible to use jQuery .on and hover?

If you need it to have as a condition in an other event, I solved it this way:

$('.classname').hover(
     function(){$(this).data('hover',true);},
     function(){$(this).data('hover',false);}
);

Then in another event, you can easily use it:

 if ($(this).data('hover')){
      //...
 }

(I see some using is(':hover') to solve this. But this is not (yet) a valid jQuery selector and does not work in all compatible browsers)

What is the difference between Scrum and Agile Development?

Agile and Scrum are terms used in project management. The Agile methodology employs incremental and iterative work beats that are also called sprints. Scrum, on the other hand is the type of agile approach that is used in software development.

Agile is the practice and Scrum is the process to following this practice same as eXtreme Programming (XP) and Kanban are the alternative process to following Agile development practice.

Determining the version of Java SDK on the Mac

Run this command in your terminal:

$ java -version

java version "1.8.0_181"
Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)
Cristians-MacBook-Air:~ fa$ 

Join a list of items with different types as string in Python

a=[1,2,3]
b=[str(x) for x in a]
print b

above method is the easiest and most general way to convert list into string. another short method is-

a=[1,2,3]
b=map(str,a)
print b

How to define custom sort function in javascript?

or shorter

_x000D_
_x000D_
function sortBy(field) {_x000D_
  return function(a, b) {_x000D_
    return (a[field] > b[field]) - (a[field] < b[field])_x000D_
  };_x000D_
}_x000D_
_x000D_
let myArray = [_x000D_
    {tabid: 6237, url: 'https://reddit.com/r/znation'},_x000D_
    {tabid: 8430, url: 'https://reddit.com/r/soccer'},_x000D_
    {tabid: 1400, url: 'https://reddit.com/r/askreddit'},_x000D_
    {tabid: 3620, url: 'https://reddit.com/r/tacobell'},_x000D_
    {tabid: 5753, url: 'https://reddit.com/r/reddevils'},_x000D_
]_x000D_
_x000D_
myArray.sort(sortBy('url'));_x000D_
console.log(myArray);
_x000D_
_x000D_
_x000D_

Call a "local" function within module.exports from another function in module.exports?

const Service = {
  foo: (a, b) => a + b,
  bar: (a, b) => Service.foo(a, b) * b
}

module.exports = Service

Does my application "contain encryption"?

Simple answers are Yes(App has encryption) and Yes(App uses Exempt encryption). In my application, I am just opening my company's website in WKWebView but as it uses "https", it will be considered as exempt encryption. Apple document for more info: https://developer.apple.com/documentation/security/complying_with_encryption_export_regulations?language=objc

Alternatively, you can just add key "ITSAppUsesNonExemptEncryption" and value "NO" in your app's info.plist file. and this way iTunes connect won't ask you that questions anymore. More info: https://developer.apple.com/documentation/bundleresources/information_property_list/itsappusesnonexemptencryption?language=objc

You can follow these 3 simple steps to verify if your application is exempt or not: https://help.apple.com/app-store-connect/#/dev63c95e436

You may need to submit this annual-self-classification to US gov. For more info: https://www.bis.doc.gov/index.php/policy-guidance/encryption/4-reports-and-reviews/a-annual-self-classification

How to Deserialize JSON data?

You can write your own JSON parser and make it more generic based on your requirement. Here is one which served my purpose nicely, hope will help you too.

class JsonParsor
{
    public static DataTable JsonParse(String rawJson)
    {
        DataTable dataTable = new DataTable();
        Dictionary<string, string> outdict = new Dictionary<string, string>();
        StringBuilder keybufferbuilder = new StringBuilder();
        StringBuilder valuebufferbuilder = new StringBuilder();
        StringReader bufferreader = new StringReader(rawJson);
        int s = 0;
        bool reading = false;
        bool inside_string = false;
        bool reading_value = false;
        bool reading_number = false;
        while (s >= 0)
        {
            s = bufferreader.Read();
            //open JSON
            if (!reading)
            {
                if ((char)s == '{' && !inside_string && !reading)
                {
                    reading = true;
                    continue;
                }
                if ((char)s == '}' && !inside_string && !reading)
                    break;
                if ((char)s == ']' && !inside_string && !reading)
                    continue;
                if ((char)s == ',')
                    continue;
            }
            else
            {
                if (reading_value)
                {
                    if (!inside_string && (char)s >= '0' && (char)s <= '9')
                    {
                        reading_number = true;
                        valuebufferbuilder.Append((char)s);
                        continue;
                    }
                }
                //if we find a quote and we are not yet inside a string, advance and get inside
                if (!inside_string)
                {
                    if ((char)s == '\"' && !inside_string)
                        inside_string = true;
                    if ((char)s == '[' && !inside_string)
                    {
                        keybufferbuilder.Length = 0;
                        valuebufferbuilder.Length = 0;
                                reading = false;
                                inside_string = false;
                                reading_value = false;
                    }
                    if ((char)s == ',' && !inside_string && reading_number)
                    {
                        if (!dataTable.Columns.Contains(keybufferbuilder.ToString()))
                            dataTable.Columns.Add(keybufferbuilder.ToString(), typeof(string));
                        if (!outdict.ContainsKey(keybufferbuilder.ToString()))
                            outdict.Add(keybufferbuilder.ToString(), valuebufferbuilder.ToString());
                        keybufferbuilder.Length = 0;
                        valuebufferbuilder.Length = 0;
                        reading_value = false;
                        reading_number = false;
                    }
                    continue;
                }

                //if we reach end of the string
                if (inside_string)
                {
                    if ((char)s == '\"')
                    {
                        inside_string = false;
                        s = bufferreader.Read();
                        if ((char)s == ':')
                        {
                            reading_value = true;
                            continue;
                        }
                        if (reading_value && (char)s == ',')
                        {
                            //put the key-value pair into dictionary
                            if(!dataTable.Columns.Contains(keybufferbuilder.ToString()))
                                dataTable.Columns.Add(keybufferbuilder.ToString(),typeof(string));
                            if (!outdict.ContainsKey(keybufferbuilder.ToString()))
                            outdict.Add(keybufferbuilder.ToString(), valuebufferbuilder.ToString());
                            keybufferbuilder.Length = 0;
                            valuebufferbuilder.Length = 0;
                            reading_value = false;
                        }
                        if (reading_value && (char)s == '}')
                        {
                            if (!dataTable.Columns.Contains(keybufferbuilder.ToString()))
                                dataTable.Columns.Add(keybufferbuilder.ToString(), typeof(string));
                            if (!outdict.ContainsKey(keybufferbuilder.ToString()))
                                outdict.Add(keybufferbuilder.ToString(), valuebufferbuilder.ToString());
                            ICollection key = outdict.Keys;
                            DataRow newrow = dataTable.NewRow();
                            foreach (string k_loopVariable in key)
                            {
                                CommonModule.LogTheMessage(outdict[k_loopVariable],"","","");
                                newrow[k_loopVariable] = outdict[k_loopVariable];
                            }
                            dataTable.Rows.Add(newrow);
                            CommonModule.LogTheMessage(dataTable.Rows.Count.ToString(), "", "row_count", "");
                            outdict.Clear();
                            keybufferbuilder.Length=0;
                            valuebufferbuilder.Length=0;
                            reading_value = false;
                            reading = false;
                            continue;
                        }
                    }
                    else
                    {
                        if (reading_value)
                        {
                            valuebufferbuilder.Append((char)s);
                            continue;
                        }
                        else
                        {
                            keybufferbuilder.Append((char)s);
                            continue;
                        }
                    }
                }
                else
                {
                    switch ((char)s)
                    {
                        case ':':
                            reading_value = true;
                            break;
                        default:
                            if (reading_value)
                            {
                                valuebufferbuilder.Append((char)s);
                            }
                            else
                            {
                                keybufferbuilder.Append((char)s);
                            }
                            break;
                    }
                }
            }
        }

        return dataTable;
    }
}

SELECT DISTINCT on one column

Try this:

SELECT * FROM [TestData] WHERE Id IN(SELECT DISTINCT MIN(Id) FROM [TestData] GROUP BY Product)   

MySQL - UPDATE query based on SELECT Query

You can update values from another table using inner join like this

UPDATE [table1_name] AS t1 INNER JOIN [table2_name] AS t2 ON t1.column1_name] = t2.[column1_name] SET t1.[column2_name] = t2.column2_name];

Follow here to know how to use this query http://www.voidtricks.com/mysql-inner-join-update/

or you can use select as subquery to do this

UPDATE [table_name] SET [column_name] = (SELECT [column_name] FROM [table_name] WHERE [column_name] = [value]) WHERE [column_name] = [value];

query explained in details here http://www.voidtricks.com/mysql-update-from-select/

How can I check if a date is the same day as datetime.today()?

  • If you need to compare only day of month value than you can use the following code:

    if yourdate.day == datetime.today().day:
        # do something
    
  • If you need to check that the difference between two dates is acceptable then you can use timedelta:

    if (datetime.today() - yourdate).days == 0:
        #do something
    
  • And if you want to compare date part only than you can simply use:

    from datetime import datetime, date
    if yourdatetime.date() < datetime.today().date()
        # do something
    

Note that timedelta has the following format:

datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])

So you are able to check diff in days, seconds, msec, minutes and so on depending on what you really need:

from datetime import datetime
if (datetime.today() - yourdate).days == 0:
    #do something

In your case when you need to check that two dates are exactly the same you can use timedelta(0):

from datetime import datetime, timedelta
if (datetime.today() - yourdate) == timedelta(0):
    #do something

How much RAM is SQL Server actually using?

Be aware that Total Server Memory is NOT how much memory SQL Server is currently using.

refer to this Microsoft article: http://msdn.microsoft.com/en-us/library/ms190924.aspx

Mocking a class: Mock() or patch()?

Key points which explain difference and provide guidance upon working with unittest.mock

  1. Use Mock if you want to replace some interface elements(passing args) of the object under test
  2. Use patch if you want to replace internal call to some objects and imported modules of the object under test
  3. Always provide spec from the object you are mocking
    • With patch you can always provide autospec
    • With Mock you can provide spec
    • Instead of Mock, you can use create_autospec, which intended to create Mock objects with specification.

In the question above the right answer would be to use Mock, or to be more precise create_autospec (because it will add spec to the mock methods of the class you are mocking), the defined spec on the mock will be helpful in case of an attempt to call method of the class which doesn't exists ( regardless signature), please see some

from unittest import TestCase
from unittest.mock import Mock, create_autospec, patch


class MyClass:
    
    @staticmethod
    def method(foo, bar):
        print(foo)


def something(some_class: MyClass):
    arg = 1
    # Would fail becuase of wrong parameters passed to methd.
    return some_class.method(arg)


def second(some_class: MyClass):
    arg = 1
    return some_class.unexisted_method(arg)


class TestSomethingTestCase(TestCase):
    def test_something_with_autospec(self):
        mock = create_autospec(MyClass)
        mock.method.return_value = True
        # Fails because of signature misuse.
        result = something(mock)
        self.assertTrue(result)
        self.assertTrue(mock.method.called)
    
    def test_something(self):
        mock = Mock()  # Note that Mock(spec=MyClass) will also pass, because signatures of mock don't have spec.
        mock.method.return_value = True
        
        result = something(mock)
        
        self.assertTrue(result)
        self.assertTrue(mock.method.called)
        
    def test_second_with_patch_autospec(self):
        with patch(f'{__name__}.MyClass', autospec=True) as mock:
            # Fails because of signature misuse.
            result = second(mock)
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)


class TestSecondTestCase(TestCase):
    def test_second_with_autospec(self):
        mock = Mock(spec=MyClass)
        # Fails because of signature misuse.
        result = second(mock)
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)
    
    def test_second_with_patch_autospec(self):
        with patch(f'{__name__}.MyClass', autospec=True) as mock:
            # Fails because of signature misuse.
            result = second(mock)
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)
    
    def test_second(self):
        mock = Mock()
        mock.unexisted_method.return_value = True
        
        result = second(mock)
        
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)

The test cases with defined spec used fail because methods called from something and second functions aren't complaint with MyClass, which means - they catch bugs, whereas default Mock will display.

As a side note there is one more option: use patch.object to mock just the class method which is called with.

The good use cases for patch would be the case when the class is used as inner part of function:

def something():
    arg = 1
    return MyClass.method(arg)

Then you will want to use patch as a decorator to mock the MyClass.

@RequestParam in Spring MVC handling optional parameters

Create 2 methods which handle the cases. You can instruct the @RequestMapping annotation to take into account certain parameters whilst mapping the request. That way you can nicely split this into 2 methods.

@RequestMapping (value="/submit/id/{id}", method=RequestMethod.GET, 
                 produces="text/xml", params={"logout"})
public String handleLogout(@PathVariable("id") String id, 
        @RequestParam("logout") String logout) { ... }

@RequestMapping (value="/submit/id/{id}", method=RequestMethod.GET, 
                 produces="text/xml", params={"name", "password"})
public String handleLogin(@PathVariable("id") String id, @RequestParam("name") 
        String username, @RequestParam("password") String password, 
        @ModelAttribute("submitModel") SubmitModel model, BindingResult errors) 
        throws LoginException {...}

Jquery and HTML FormData returns "Uncaught TypeError: Illegal invocation"

In my case, there was a mistake in the list of the parameters was not well formed. So make sure the parameters are well formed. For e.g. correct format of parameters

data: {'reporter': reporter,'partner': partner,'product': product}

Color Tint UIButton Image

Swift 4 with customType:

let button = UIButton(frame: aRectHere)
    let buttonImage = UIImage(named: "imageName")
    button.setImage(buttonImage?.withRenderingMode(.alwaysTemplate), for: .normal)
    button.tintColor = .white

How to convert comma separated string into numeric array in javascript

You can use split() to get string array from comma separated string. If you iterate and perform mathematical operation on element of string array then that element will be treated as number by run-time cast but still you have string array. To convert comma separated string int array see the edit.

arr = strVale.split(',');

Live Demo

var strVale = "130,235,342,124";
arr = strVale.split(',');
for(i=0; i < arr.length; i++)
    console.log(arr[i] + " * 2 = " + (arr[i])*2);

Output

130 * 2 = 260
235 * 2 = 470
342 * 2 = 684
124 * 2 = 248

Edit, Comma separated string to int Array In the above example the string are casted to numbers in expression but to get the int array from string array you need to convert it to number.

var strVale = "130,235,342,124";
var strArr = strVale.split(',');
var intArr = [];
for(i=0; i < strArr.length; i++)
   intArr.push(parseInt(strArr[i]));

What is the correct format to use for Date/Time in an XML file

If you are manually assembling the XML string use var.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.fffffffZ")); That will output the official XML Date Time format. But you don't have to worry about format if you use the built-in serialization methods.

Is there a way to check for both `null` and `undefined`?

Late to join this thread but I find this JavaScript hack very handy in checking whether a value is undefined

 if(typeof(something) === 'undefined'){
   // Yes this is undefined
 }

How do you divide each element in a list by an int?

The idiomatic way would be to use list comprehension:

myList = [10,20,30,40,50,60,70,80,90]
myInt = 10
newList = [x / myInt for x in myList]

or, if you need to maintain the reference to the original list:

myList[:] = [x / myInt for x in myList]

Set a button group's width to 100% and make buttons equal width?

Bootstrap 4

            <ul class="nav nav-pills nav-fill">
                <li class="nav-item">
                    <a class="nav-link active" href="#">Active</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Longer nav link</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Link</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link disabled" href="#">Disabled</a>
                </li>
            </ul>

How to change facebook login button with my custom image

I got it working with a call to something as simple as

function fb_login() {
  FB.login( function() {}, { scope: 'email,public_profile' } );
}

I don't know if facebook will ever be able to block this circumvention, but for now I can use whatever HTML or image I want to call fb_login and it works fine.

Reference: Facebook API Docs

How to get an Instagram Access Token

If you're looking for instructions, check out this article post. And if you're using C# ASP.NET, have a look at this repo.

Detect if device is iOS

var isiOSSafari = (navigator.userAgent.match(/like Mac OS X/i)) ? true: false;

What is the difference between dim and set in vba

Dim simply declares the value and the type.

Set assigns a value to the variable.

Convert Word doc, docx and Excel xls, xlsx to PDF with PHP

Step 1. Install "Apache_OpenOffice_4.1.2" in your system Step 2. Download "unoconv" library from github or any where else.

-> C:\Program Files (x86)\OpenOffice 4\program\python.exe = Path of open office install directory

-> D:\wamp\www\doc_to_pdf\libobasis4.4-pyuno\unoconv = Path of library folder

-> D:/wamp/www/doc_to_pdf/files/'.$pdf_File_name.' = path and file name of pdf

-> D:/wamp/www/doc_to_pdf/files/'.$doc_file_name = Path of your document file.

If pdf not created than last step is Go to ->Control Panel\All Control Panel Items\Administrative Tools-> services-> find "wampapache" -> right click and click on property -> click on logon tab Than check checkbox of allow service to interact with desktop

Create sample .php file and put below code and run on wamp or xampp server

$result = exec('"C:\Program Files (x86)\OpenOffice 4\program\python.exe" D:\wamp\www\doc_to_pdf\libobasis4.4-pyuno\unoconv -f pdf -o D:/wamp/www/doc_to_pdf/files/'.$pdf_File_name.' D:/wamp/www/doc_to_pdf/files/'.$doc_file_name);

This code working for me in windows-8 operating system

iframe to Only Show a Certain Part of the Page

<div style="border: 2px solid #D5CC5A; overflow: hidden; margin: 15px auto; max-width: 575px;">

Renaming branches remotely in Git

You just have to create a new local branch with the desired name, push it to your remote, and then delete the old remote branch:

$ git branch new-branch-name origin/old-branch-name
$ git push origin --set-upstream new-branch-name
$ git push origin :old-branch-name

Then, to see the old branch name, each client of the repository would have to do:

$ git fetch origin
$ git remote prune origin

NOTE: If your old branch is your main branch, you should change your main branch settings. Otherwise, when you run $ git push origin :old-branch-name, you'll get the error "deletion of the current branch prohibited".

selenium get current url after loading a page

Like you said since the xpath for the next button is the same on every page it won't work. It's working as coded in that it does wait for the element to be displayed but since it's already displayed then the implicit wait doesn't apply because it doesn't need to wait at all. Why don't you use the fact that the url changes since from your code it appears to change when the next button is clicked. I do C# but I guess in Java it would be something like:

WebDriver driver = new FirefoxDriver();
String startURL = //a starting url;
String currentURL = null;
WebDriverWait wait = new WebDriverWait(driver, 10);

foo(driver,startURL);

/* go to next page */
if(driver.findElement(By.xpath("//*[@id='someID']")).isDisplayed()){
    String previousURL = driver.getCurrentUrl();
    driver.findElement(By.xpath("//*[@id='someID']")).click();  
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

    ExpectedCondition e = new ExpectedCondition<Boolean>() {
          public Boolean apply(WebDriver d) {
            return (d.getCurrentUrl() != previousURL);
          }
        };

    wait.until(e);
    currentURL = driver.getCurrentUrl();
    System.out.println(currentURL);
} 

form with no action and where enter does not reload page

The first response is the best solution:

Add an onsubmit handler to the form (either via plain js or jquery $().submit(fn)), and return false unless your specific conditions are met.

More specific with jquery:

$('#your-form-id').submit(function(){return false;});

Unless you don't want the form to submit, ever - in which case, why not just leave out the 'action' attribute on the form element?

Writing Chrome extensions is an example of where you might have a form for user input, but you don't want it to submit. If you use action="javascript:void(0);", the code will probably work but you will end up with this problem where you get an error about running inline Javascript.

If you leave out the action completely, the form will reload which is also undesired in some cases when writing a Chrome extension. Or if you had a webpage with some sort of an embedded calculator, where the user would provide some input and click "Calculate" or something like that.

How to add items to a spinner in Android?

XML file:

<Spinner
    android:id="@+id/Spinner01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

Java file:

public class SpinnerExample extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        String[] arraySpinner = new String[] {
            "1", "2", "3", "4", "5", "6", "7"
        };
        Spinner s = (Spinner) findViewById(R.id.Spinner01);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, arraySpinner);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        s.setAdapter(adapter);
    }
}

See spinner example.

Git asks for username every time I push

Permanently authenticating with Git repositories

Run following command to enable credential caching:

$ git config credential.helper store
$ git push https://github.com/repo.git

Username for 'https://github.com': <USERNAME>
Password for 'https://[email protected]': <PASSWORD>

Use should also specify caching expire

git config --global credential.helper "cache --timeout 7200"

After enabling credential caching, it will be cached for 7200 seconds (2 hour).


Read credentials Docs

$ git help credentials

How to import image (.svg, .png ) in a React Component

I also had a similar requirement where I need to import .png images. I have stored these images in public folder. So the following approach worked for me.

<img src={process.env.PUBLIC_URL + './Images/image1.png'} alt="Image1"></img> 

In addition to the above I have tried using require as well and it also worked for me. I have included the images inside the Images folder in src directory.

<img src={require('./Images/image1.png')}  alt="Image1"/>

How can I set my Cygwin PATH to find javac?

Although all other answers are technically correct, I would recommend you adding the custom path to the beginning of your PATH, not at the end. That way it would be the first place to look for instead of the last:

Add to bottom of ~/.bash_profile:

export PATH="/cygdrive/C/Program Files/Java/jdk1.6.0_23/bin/":$PATH

That way if you have more than one java or javac it will use the one you provided first.

Pentaho Data Integration SQL connection

Turns out I will missing a class called mysql-connector-java-5.1.2.jar, I added it this folder (C:\Program Files\pentaho\design-tools\data-integration\lib) and it worked with a MySQL connection and my data and tables appear.

initialize a numpy array

You do want to avoid explicit loops as much as possible when doing array computing, as that reduces the speed gain from that form of computing. There are multiple ways to initialize a numpy array. If you want it filled with zeros, do as katrielalex said:

big_array = numpy.zeros((10,4))

EDIT: What sort of sequence is it you're making? You should check out the different numpy functions that create arrays, like numpy.linspace(start, stop, size) (equally spaced number), or numpy.arange(start, stop, inc). Where possible, these functions will make arrays substantially faster than doing the same work in explicit loops

'npm' is not recognized as internal or external command, operable program or batch file

I ran into this issue as well. It turns out Windows doesn't enjoy single quotes on the command line. The culprit was one of my npm scripts. I changed the single quotes to escaped double quotes:

'npm -s run sass-build'

to

\"npm -s run sass-build\"

Wildcards in a Windows hosts file

You can use echoipdns for this (https://github.com/zapty/echoipdns).

By running echoipdns local all requests for .local subdomains are redirected to 127.0.0.1, so any domain with xyz.local etc will resolve to 127.0.0.1. You can use any other suffix also just replace local with name you want.

Echoipdns is even more powerful, when you want to use your url from other machines in network you can still use it with zero configuration.

For e.g. If your machine ip address is 192.168.1.100 you could now use a domain name xyz.192-168-1-100.local which will always resolve to 192.168.1.100. This magic is done by the echoipdns by looking at the ip address in the second part of the domain name and returning the same ip address on DNS query. You will have to run the echoipdns on the machine from which you want to access the remote system.

echoipdns also can be setup as a standalone DNS proxy, so by just point to this DNS, you can now use all the above benefits without running a special command every time, and you can even use it from mobile devices.

So essentially this simplifies the wildcard domain based DNS development for local as well as team environment.

echoipdns works on Mac, Linux and Windows.

NOTE: I am author for echoipdns.

Func delegate with no return type

All Func delegates return something; all the Action delegates return void.

Func<TResult> takes no arguments and returns TResult:

public delegate TResult Func<TResult>()

Action<T> takes one argument and does not return a value:

public delegate void Action<T>(T obj)

Action is the simplest, 'bare' delegate:

public delegate void Action()

There's also Func<TArg1, TResult> and Action<TArg1, TArg2> (and others up to 16 arguments). All of these (except for Action<T>) are new to .NET 3.5 (defined in System.Core).

How can I solve the error LNK2019: unresolved external symbol - function?

One option would be to include function.cpp in your UnitTest1 project, but that may not be the most ideal solution structure. The short answer to your problem is that when building your UnitTest1 project, the compiler and linker have no idea that function.cpp exists, and also have nothing to link that contains a definition of multiple. A way to fix this is making use of linking libraries.

Since your unit tests are in a different project, I'm assuming your intention is to make that project a standalone unit-testing program. With the functions you are testing located in another project, it's possible to build that project to either a dynamically or statically linked library. Static libraries are linked to other programs at build time, and have the extension .lib, and dynamic libraries are linked at runtime, and have the extension .dll. For my answer I'll prefer static libraries.

You can turn your first program into a static library by changing it in the projects properties. There should be an option under the General tab where the project is set to build to an executable (.exe). You can change this to .lib. The .lib file will build to the same place as the .exe.

In your UnitTest1 project, you can go to its properties, and under the Linker tab in the category Additional Library Directories, add the path to which MyProjectTest builds. Then, for Additional Dependencies under the Linker - Input tab, add the name of your static library, most likely MyProjectTest.lib.

That should allow your project to build. Note that by doing this, MyProjectTest will not be a standalone executable program unless you change its build properties as needed, which would be less than ideal.

HTTP post XML data in C#

In General:

An example of an easy way to post XML data and get the response (as a string) would be the following function:

public string postXMLData(string destinationUrl, string requestXml)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
    byte[] bytes;
    bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
    request.ContentType = "text/xml; encoding='utf-8'";
    request.ContentLength = bytes.Length;
    request.Method = "POST";
    Stream requestStream = request.GetRequestStream();
    requestStream.Write(bytes, 0, bytes.Length);
    requestStream.Close();
    HttpWebResponse response;
    response = (HttpWebResponse)request.GetResponse();
    if (response.StatusCode == HttpStatusCode.OK)
    {
        Stream responseStream = response.GetResponseStream();
        string responseStr = new StreamReader(responseStream).ReadToEnd();
        return responseStr;
    }
    return null;
}

In your specific situation:

Instead of:

request.ContentType = "application/x-www-form-urlencoded";

use:

request.ContentType = "text/xml; encoding='utf-8'";

Also, remove:

string postData = "XMLData=" + Sendingxml;

And replace:

byte[] byteArray = Encoding.UTF8.GetBytes(postData);

with:

byte[] byteArray = Encoding.UTF8.GetBytes(Sendingxml.ToString());

What is the difference between --save and --save-dev?

You generally don't want to bloat production package with things that you only intend to use for Development purposes.

Use --save-dev (or -D) option to separate packages such as Unit Test frameworks (jest, jasmine, mocha, chai, etc.)

Any other packages that your app needs for Production, should be installed using --save (or -S).

npm install --save lodash       //prod dependency
npm install -S moment           // "       "
npm install -S opentracing      // "       "

npm install -D jest                 //dev only dependency
npm install --save-dev typescript   //dev only dependency

If you open the package.json file then you will see these entries listed under two different sections:

"dependencies": {
  "lodash": "4.x",
  "moment": "2.x",
  "opentracing": "^0.14.1"
},

"devDependencies": {
    "jest": "22.x",
    "typescript": "^2.8.3"
},

Fragment Inside Fragment

I solved this problem. You can use Support library and ViewPager. If you don't need swiping by gesture you can disable swiping. So here is some code to improve my solution:

public class TestFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.frag, container, false);
    final ArrayList<Fragment> list = new ArrayList<Fragment>();

    list.add(new TrFrag());
    list.add(new TrFrag());
    list.add(new TrFrag());

    ViewPager pager = (ViewPager) v.findViewById(R.id.pager);
    pager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
        @Override
        public Fragment getItem(int i) {
            return list.get(i);
        }

        @Override
        public int getCount() {
            return list.size();
        }
    });
    return v;
}
}

P.S.It is ugly code for test, but it improves that it is possible.

P.P.S Inside fragment ChildFragmentManager should be passed to ViewPagerAdapter

How can I get form data with JavaScript/jQuery?

showing form input element fields and input file to submit your form without page refresh and grab all values with file include in it here it is

_x000D_
_x000D_
<form id="imageUploadForm"   action="" method="post" enctype="multipart/form-data">_x000D_
<input type="text" class="form-control" id="fname" name='fname' placeholder="First Name" >_x000D_
<input type="text" class="form-control" name='lname' id="lname" placeholder="Last Name">_x000D_
<input type="number" name='phoneno'  class="form-control" id="phoneno" placeholder="Phone Number">_x000D_
<textarea class="form-control" name='address' id="address" rows="5" cols="5" placeholder="Your Address"></textarea>_x000D_
<input type="file" name="file" id="file" >_x000D_
<input type="submit" id="sub" value="Registration">        _x000D_
</form>
_x000D_
_x000D_
_x000D_ on Submit button page will send ajax request to your php file.
_x000D_
_x000D_
$('#imageUploadForm').on('submit',(function(e) _x000D_
{_x000D_
     fname = $('#fname').val();_x000D_
     lname =  $('#lname').val();_x000D_
     address =  $('#address').val();_x000D_
     phoneno =  $('#phoneno').val();_x000D_
     file =  $('#file').val();_x000D_
     e.preventDefault();_x000D_
     var formData = new FormData(this);_x000D_
     formData.append('file', $('#file')[0]);_x000D_
     formData.append('fname',$('#fname').val());_x000D_
     formData.append('lname',$('#lname').val());_x000D_
     formData.append('phoneno',$('#phoneno').val());_x000D_
     formData.append('address',$('#address').val());_x000D_
     $.ajax({_x000D_
  type:'POST',_x000D_
                url: "test.php",_x000D_
                //url: '<?php echo base_url().'edit_profile/edit_profile2';?>',_x000D_
_x000D_
                data:formData,_x000D_
                cache:false,_x000D_
                contentType: false,_x000D_
                processData: false,_x000D_
                success:function(data)_x000D_
                {_x000D_
                     alert('Data with file are submitted !');_x000D_
_x000D_
                }_x000D_
_x000D_
     });_x000D_
_x000D_
}))
_x000D_
_x000D_
_x000D_

Getting RAW Soap Data from a Web Reference Client running in ASP.net

Here's a simplified version of the top answer. Add this to the <configuration> element of your web.config or App.config file. It will create a trace.log file in your project's bin/Debug folder. Or, you can specify an absolute path for the log file using the initializeData attribute.

  <system.diagnostics>
    <trace autoflush="true"/>
    <sources>
      <source name="System.Net" maxdatasize="9999" tracemode="protocolonly">
        <listeners>
          <add name="TraceFile" type="System.Diagnostics.TextWriterTraceListener" initializeData="trace.log"/>
        </listeners>
      </source>
    </sources>
    <switches>
      <add name="System.Net" value="Verbose"/>
    </switches>
  </system.diagnostics>

It warns that the maxdatasize and tracemode attributes are not allowed, but they increase the amount of data that can be logged, and avoid logging everything in hex.

Add to Array jQuery

push is a native javascript method. You could use it like this:

var array = [1, 2, 3];
array.push(4); // array now is [1, 2, 3, 4]
array.push(5, 6, 7); // array now is [1, 2, 3, 4, 5, 6, 7]

Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH

If this is related to docker, try stopping the erroneous container and starting a new container using docker run command from the same image.

Ansible playbook shell output

Perhaps not relevant if you're looking to do this ONLY using ansible. But it's much easier for me to have a function in my .bash_profile and then run _check_machine host1 host2

function _check_machine() {
    echo 'hostname,num_physical_procs,cores_per_procs,memory,Gen,RH Release,bios_hp_power_profile,bios_intel_qpi_link_power_management,bios_hp_power_regulator,bios_idle_power_state,bios_memory_speed,'
    hostlist=$1
    for h in `echo $hostlist | sed 's/ /\n/g'`;
    do
        echo $h | grep -qE '[a-zA-Z]'
        [ $? -ne 0 ] && h=plabb$h
        echo -n $h,
        ssh root@$h 'grep "^physical id" /proc/cpuinfo | sort -u | wc -l; grep "^cpu cores" /proc/cpuinfo |sort -u | awk "{print \$4}"; awk "{print \$2/1024/1024; exit 0}" /proc/meminfo; /usr/sbin/dmidecode | grep "Product Name"; cat /etc/redhat-release; /etc/facter/bios_facts.sh;' | sed 's/Red at Enterprise Linux Server release //g; s/.*=//g; s/\tProduct Name: ProLiant BL460c //g; s/-//g' | sed 's/Red Hat Enterprise Linux Server release //g; s/.*=//g; s/\tProduct Name: ProLiant BL460c //g; s/-//g' | tr "\n" ","
         echo ''
    done
}

E.g.

$ _machine_info '10 20 1036'
hostname,num_physical_procs,cores_per_procs,memory,Gen,RH Release,bios_hp_power_profile,bios_intel_qpi_link_power_management,bios_hp_power_regulator,bios_idle_power_state,bios_memory_speed,
plabb10,2,4,47.1629,G6,5.11 (Tikanga),Maximum_Performance,Disabled,HP_Static_High_Performance_Mode,No_CStates,1333MHz_Maximum,
plabb20,2,4,47.1229,G6,6.6 (Santiago),Maximum_Performance,Disabled,HP_Static_High_Performance_Mode,No_CStates,1333MHz_Maximum,
plabb1036,2,12,189.12,Gen8,6.6 (Santiago),Custom,Disabled,HP_Static_High_Performance_Mode,No_CStates,1333MHz_Maximum,
$ 

Needless to say function won't work for you as it is. You need to update it appropriately.

Getting list of pixel values from PIL

data = numpy.asarray(im)

Notice:In PIL, img is RGBA. In cv2, img is BGRA.

My robust solution:

def cv_from_pil_img(pil_img):
    assert pil_img.mode=="RGBA"
    return cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGBA2BGRA)

How can I use modulo operator (%) in JavaScript?

That would be the modulo operator, which produces the remainder of the division of two numbers.

Real world use of JMS/message queues?

I've had so many amazing uses for JMS:

  • Web chat communication for customer service.

  • Debug logging on the backend. All app servers broadcasted debug messages at various levels. A JMS client could then be launched to watch for debug messages. Sure I could've used something like syslog, but this gave me all sorts of ways to filter the output based on contextual information (e.q. by app server name, api call, log level, userid, message type, etc...). I also colorized the output.

  • Debug logging to file. Same as above, only specific pieces were pulled out using filters, and logged to file for general logging.

  • Alerting. Again, a similar setup to the above logging, watching for specific errors, and alerting people via various means (email, text message, IM, Growl pop-up...)

  • Dynamically configuring and controlling software clusters. Each app server would broadcast a "configure me" message, then a configuration daemon that would respond with a message containing all kinds of config info. Later, if all the app servers needed their configurations changed at once, it could be done from the config daemon.

  • And the usual - queued transactions for delayed activity such as billing, order processing, provisioning, email generation...

It's great anywhere you want to guarantee delivery of messages asynchronously.

Ansible Ignore errors in tasks and fail at end of the playbook if any tasks had errors

Fail module works great! Thanks.

I had to define my fact before checking it, otherwise I'd get an undefined variable error.

And I had issues when doing setting the fact with quotes and without spaces.

This worked:

set_fact: flag="failed"

This threw errors:

set_fact: flag = failed 

How do I obtain the frequencies of each value in an FFT?

Take a look at my answer here.

Answer to comment:

The FFT actually calculates the cross-correlation of the input signal with sine and cosine functions (basis functions) at a range of equally spaced frequencies. For a given FFT output, there is a corresponding frequency (F) as given by the answer I posted. The real part of the output sample is the cross-correlation of the input signal with cos(2*pi*F*t) and the imaginary part is the cross-correlation of the input signal with sin(2*pi*F*t). The reason the input signal is correlated with sin and cos functions is to account for phase differences between the input signal and basis functions.

By taking the magnitude of the complex FFT output, you get a measure of how well the input signal correlates with sinusoids at a set of frequencies regardless of the input signal phase. If you are just analyzing frequency content of a signal, you will almost always take the magnitude or magnitude squared of the complex output of the FFT.

Default parameters with C++ constructors

If creating constructors with arguments is bad (as many would argue), then making them with default arguments is even worse. I've recently started to come around to the opinion that ctor arguments are bad, because your ctor logic should be as minimal as possible. How do you deal with error handling in the ctor, should somebody pass in an argument that doesn't make any sense? You can either throw an exception, which is bad news unless all of your callers are prepared to wrap any "new" calls inside of try blocks, or setting some "is-initialized" member variable, which is kind of a dirty hack.

Therefore, the only way to make sure that the arguments passed into the initialization stage of your object is to set up a separate initialize() method where you can check the return code.

The use of default arguments is bad for two reasons; first of all, if you want to add another argument to the ctor, then you are stuck putting it at the beginning and changing the entire API. Furthermore, most programmers are accustomed to figuring out an API by the way that it's used in practice -- this is especially true for non-public API's used inside of an organization where formal documentation may not exist. When other programmers see that the majority of the calls don't contain any arguments, they will do the same, remaining blissfully unaware of the default behavior your default arguments impose on them.

Also, it's worth noting that the google C++ style guide shuns both ctor arguments (unless absolutely necessary), and default arguments to functions or methods.

Loading an image to a <img> from <input file>

_x000D_
_x000D_
var outImage ="imagenFondo";_x000D_
function preview_2(obj)_x000D_
{_x000D_
 if (FileReader)_x000D_
 {_x000D_
  var reader = new FileReader();_x000D_
  reader.readAsDataURL(obj.files[0]);_x000D_
  reader.onload = function (e) {_x000D_
  var image=new Image();_x000D_
  image.src=e.target.result;_x000D_
  image.onload = function () {_x000D_
   document.getElementById(outImage).src=image.src;_x000D_
  };_x000D_
  }_x000D_
 }_x000D_
 else_x000D_
 {_x000D_
      // Not supported_x000D_
 }_x000D_
}
_x000D_
<!doctype html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>preview photo</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<form>_x000D_
 <input type="file" onChange="preview_2(this);"><br>_x000D_
 <img id="imagenFondo" style="height: 300px;width: 300px;">_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

getting JRE system library unbound error in build path

oh boy, this got resolved, I just had to name my Installed JRE appropriately. I had only the jdk installed and eclipse had taken the default jdk name, i renamed it to JavaSE-1.6 and voila it worked, though i had to redo everthing from the scratch.

Rename specific column(s) in pandas

Use the pandas.DataFrame.rename funtion. Check this link for description.

data.rename(columns = {'gdp': 'log(gdp)'}, inplace = True)

If you intend to rename multiple columns then

data.rename(columns = {'gdp': 'log(gdp)', 'cap': 'log(cap)', ..}, inplace = True)

Datetime format Issue: String was not recognized as a valid DateTime

This can also be the problem if your string is 6/15/2019. DateTime Parse expects it to be 06/15/2019.

So first split it by slash

var dateParts = "6/15/2019"
var month = dateParts[0].PadLeft(2, '0');
var day = dateParts[1].PadLeft(2, '0');
var year = dateParts[2] 


var properFormat = month + "/" +day +"/" + year;

Now you can use DateTime.Parse(properFormat, "MM/dd/yyyy"). It is very strange but this is only thing working for me.

How to fix Array indexOf() in JavaScript for Internet Explorer browsers

You should check if it's not defined using if (!Array.prototype.indexOf).

Also, your implementation of indexOf is not correct. You must use === instead of == in your if (this[i] == obj) statement, otherwise [4,"5"].indexOf(5) would be 1 according to your implementation, which is incorrect.

I recommend you use the implementation on MDC.

Why is using the JavaScript eval function a bad idea?

  1. Improper use of eval opens up your code for injection attacks

  2. Debugging can be more challenging (no line numbers, etc.)

  3. eval'd code executes slower (no opportunity to compile/cache eval'd code)

Edit: As @Jeff Walden points out in comments, #3 is less true today than it was in 2008. However, while some caching of compiled scripts may happen this will only be limited to scripts that are eval'd repeated with no modification. A more likely scenario is that you are eval'ing scripts that have undergone slight modification each time and as such could not be cached. Let's just say that SOME eval'd code executes more slowly.

How do I point Crystal Reports at a new database

Choose Database | Set Datasource Location... Select the database node (yellow-ish cylinder) of the current connection, then select the database node of the desired connection (you may need to authenticate), then click Update.

You will need to do this for the 'Subreports' nodes as well.

FYI, you can also do individual tables by selecting each individually, then choosing Update.

Keylistener in Javascript

Here's an update for modern browsers in 2019

_x000D_
_x000D_
let playerSpriteX = 0;_x000D_
_x000D_
document.addEventListener('keyup', (e) => {_x000D_
  if (e.code === "ArrowUp")        playerSpriteX += 10_x000D_
  else if (e.code === "ArrowDown") playerSpriteX -= 10_x000D_
_x000D_
  document.getElementById('test').innerHTML = 'playerSpriteX = ' + playerSpriteX;_x000D_
});
_x000D_
Click on this window to focus it, and hit keys up and down_x000D_
<br><br><br>_x000D_
<div id="test">playerSpriteX = 0</div>
_x000D_
_x000D_
_x000D_


Original answer from 2013

window.onkeyup = function(e) {
   var key = e.keyCode ? e.keyCode : e.which;

   if (key == 38) {
       playerSpriteX += 10;
   }else if (key == 40) {
       playerSpriteX -= 10;
   }
}

FIDDLE

How to horizontally align ul to center of div?

You can check this solved your problem...

    #headermenu ul{ 
        text-align: center;
    }
    #headermenu li { 
list-style-type: none;
        display: inline-block;
    }
    #headermenu ul li a{
        float: left;
    }

http://jsfiddle.net/thirtydot/VCZgW/

Run chrome in fullscreen mode on Windows

It's very easy.

"your chrome path" -kiosk -fullscreen "your URL"

Example:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -kiosk -fullscreen http://google.com

Close all Chrome sessions first !

To exit: Press ALT-TAB > hold ALT and press X in the windows task. (win10)

What is the difference between \r and \n?

They're different characters. \r is carriage return, and \n is line feed.

On "old" printers, \r sent the print head back to the start of the line, and \n advanced the paper by one line. Both were therefore necessary to start printing on the next line.

Obviously that's somewhat irrelevant now, although depending on the console you may still be able to use \r to move to the start of the line and overwrite the existing text.

More importantly, Unix tends to use \n as a line separator; Windows tends to use \r\n as a line separator and Macs (up to OS 9) used to use \r as the line separator. (Mac OS X is Unix-y, so uses \n instead; there may be some compatibility situations where \r is used instead though.)

For more information, see the Wikipedia newline article.

EDIT: This is language-sensitive. In C# and Java, for example, \n always means Unicode U+000A, which is defined as line feed. In C and C++ the water is somewhat muddier, as the meaning is platform-specific. See comments for details.

Check if table exists without using "select from"

None of the options except SELECT doesn't allow database name as used in SELECT, so I wrote this:

SELECT COUNT(*) AS cnt FROM information_schema.TABLES 
WHERE CONCAT(table_schema,".",table_name)="db_name.table_name";

Convert a string to int using sql query

Try this one, it worked for me in Athena:

cast(MyVarcharCol as integer)

Javascript onclick hide div

HTML

<div id='hideme'><strong>Warning:</strong>These are new products<a href='#' class='close_notification' title='Click to Close'><img src="images/close_icon.gif" width="6" height="6" alt="Close" onClick="hide('hideme')" /></a

Javascript:

function hide(obj) {

    var el = document.getElementById(obj);

        el.style.display = 'none';

}

How do I get unique elements in this array?

Errr, it's a bit messy in the view. But I think I've gotten it to work with group (http://mongoid.org/docs/querying/)

Controller

@event_attendees = Activity.only(:user_id).where(:action => 'Attend').order_by(:created_at.desc).group

View

<% @event_attendees.each do |event_attendee| %>    
  <%= event_attendee['group'].first.user.first_name %>
<% end %>

Adding close button in div to close the box

Here's the updated FIDDLE

Your HTML should look like this (I only added the button):

<a class="fragment" href="google.com">
    <button id="closeButton">close</button>
    <div>
        <img src ="http://placehold.it/116x116" alt="some description"/> 
        <h3>the title will go here</h3>
        <h4> www.myurlwill.com </h4>
        <p class="text">
        this is a short description yada yada peanuts etc this is a short description yada yada peanuts etc this is a short description yada yada peanuts etc this is a short description yada yada peanuts etcthis is a short description yada yada peanuts etc 
        </p>
    </div>
</a>

and you should add the following CSS:

.fragment {
    position: relative;
}
#closeButton {
    position: absolute;
    top: 0;
    right: 0;
}

Then, to make the button actually work, you should add this javascript:

document.getElementById('closeButton').addEventListener('click', function(e) {
    e.preventDefault();
    this.parentNode.style.display = 'none';
}, false);

We're using e.preventDefault() here to prevent the anchor from following the link.

Create table with jQuery - append

<table id="game_table" border="1">

and Jquery

var i;
for (i = 0; ii < 10; i++) 
{

        var tr = $("<tr></tr>")
        var ii;
        for (ii = 0; ii < 10; ii++) 
        {
        tr.append(`<th>Firstname</th>`)
        }

$('#game_table').append(tr)
}

How to use Redirect in the new react-router-dom of Reactjs

Alternatively, you can use withRouter. You can get access to the history object's properties and the closest <Route>'s match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.

import React from "react"
import PropTypes from "prop-types"
import { withRouter } from "react-router"

// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }

  render() {
    const { match, location, history } = this.props

    return <div>You are now at {location.pathname}</div>
  }
}
// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation)

Or just:

import { withRouter } from 'react-router-dom'

const Button = withRouter(({ history }) => (
  <button
    type='button'
    onClick={() => { history.push('/new-location') }}
  >
    Click Me!
  </button>
))

How to calculate the intersection of two sets?

Yes there is retainAll check out this

Set<Type> intersection = new HashSet<Type>(s1);
intersection.retainAll(s2);

Where should my npm modules be installed on Mac OS X?

If you want to know the location of you NPM packages, you should:

which npm // locate a program file in the user's path SEE man which
// OUTPUT SAMPLE
/usr/local/bin/npm
la /usr/local/bin/npm // la: aliased to ls -lAh SEE which la THEN man ls
lrwxr-xr-x  1 t04435  admin    46B 18 Sep 10:37 /usr/local/bin/npm -> /usr/local/lib/node_modules/npm/bin/npm-cli.js

So given that npm is a NODE package itself, it is installed in the same location as other packages(EUREKA). So to confirm you should cd into node_modules and list the directory.

cd /usr/local/lib/node_modules/
ls
#SAMPLE OUTPUT
@angular npm .... all global npm packages installed

OR

npm root -g

As per @anthonygore 's comment

SQL Server: combining multiple rows into one row

Using MySQL inbuilt function group_concat() will be a good choice for getting the desired result. The syntax will be -

SELECT group_concat(STRINGVALUE) 
FROM Jira.customfieldvalue
WHERE CUSTOMFIELD = 12534
AND ISSUE = 19602

Before you execute the above command make sure you increase the size of group_concat_max_len else the the whole output may not fit in that cell.

To set the value of group_concat_max_len, execute the below command-

SET group_concat_max_len = 50000;

You can change the value 50000 accordingly, you increase it to a higher value as required.

MSIE and addEventListener Problem in Javascript?

Internet Explorer (IE8 and lower) doesn't support addEventListener(...). It has its own event model using the attachEvent method. You could use some code like this:

var element = document.getElementById('container');
if (document.addEventListener){
    element .addEventListener('copy', beforeCopy, false); 
} else if (el.attachEvent){
    element .attachEvent('oncopy', beforeCopy);
}

Though I recommend avoiding writing your own event handling wrapper and instead use a JavaScript framework (such as jQuery, Dojo, MooTools, YUI, Prototype, etc) and avoid having to create the fix for this on your own.

By the way, the third argument in the W3C model of events has to do with the difference between bubbling and capturing events. In almost every situation you'll want to handle events as they bubble, not when they're captured. It is useful when using event delegation on things like "focus" events for text boxes, which don't bubble.

What are some ways of accessing Microsoft SQL Server from Linux?

pymssql is a DB-API Python module, based on FreeTDS. It worked for me. Create some helper functions, if you need, and use it from Python shell.

How to deal with INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES without uninstall?

I ran into this while testing on a new Xoom. I had previously installed my app from the Marketplace. Later while trying to test a new version of the app I ran into this error.

I fixed it by removing the app that was installed via Marketplace (just hold and drag to the trash). Thereafter I was able to deploy my development version without any issue.

How to define a variable in a Dockerfile?

To answer your question:

In my Dockerfile, I would like to define variables that I can use later in the Dockerfile.

You can define a variable with:

ARG myvalue=3

Spaces around the equal character are not allowed.

And use it later with:

RUN echo $myvalue > /test

Root user/sudo equivalent in Cygwin?

I met this discussion looking for some details on the sudo implementation in different operating systems. Reading it I found that the solution by @brian-white (https://stackoverflow.com/a/42956057/3627676) is useful but can be improved slightly. I avoided creating the temporary file and implemented to execute everything by the single script.

Also I investigated the next step of the improvement to output within the single window/console. Unfortunately, without any success. I tried to use named pipes to capture STDOUT/STDERR and print in the main window. But child process didn't write to named pipes. However writing to a regular file works well.

I dropped any attempts to find the root cause and left the current solution as is. Hope my post can be useful as well.

Improvements:

  • no temporary file
  • no parsing and reconstructing the command line options
  • wait the elevated command
  • use mintty or bash, if the first one not found
  • return the command exit code

    #!/bin/bash

    # Being Administrators, invoke the command directly
    id -G | grep -qw 544 && {
        "$@"
        exit $?
    }

    # The CYG_SUDO variable is used to control the command invocation
    [ -z "$CYG_SUDO" ] && {
        mintty="$( which mintty 2>/dev/null )"
        export CYG_SUDO="$$"
        cygstart --wait --action=runas $mintty /bin/bash "$0" "$@"
        exit $?
    }

    # Now we are able to:
    # -- launch the command
    # -- display the message
    # -- return the exit code
    "$@"
    RETVAL=$?

    echo "$0: Press  to close window..."
    read

    exit $RETVAL

Storing SHA1 hash values in MySQL

If you need an index on the sha1 column, I suggest CHAR(40) for performance reasons. In my case the sha1 column is an email confirmation token, so on the landing page the query enters only with the token. In this case CHAR(40) with INDEX, in my opinion, is the best choice :)

If you want to adopt this method, remember to leave $raw_output = false.

Error message "Forbidden You don't have permission to access / on this server"

If you are using MAMP Pro the way to fix this is by checking the Indexes checkbox under the Hosts - Extended tab.

In MAMP Pro v3.0.3 this is what that looks like: enter image description here

Select Row number in postgres

SELECT tab.*,
    row_number() OVER () as rnum
  FROM tab;

Here's the relevant section in the docs.

P.S. This, in fact, fully matches the answer in the referenced question.

C# error: "An object reference is required for the non-static field, method, or property"

The Main method is Static. You can not invoke a non-static method from a static method.

GetRandomBits()

is not a static method. Either you have to create an instance of Program

Program p = new Program();
p.GetRandomBits();

or make

GetRandomBits() static.

How to set String's font size, style in Java using the Font class?

Look here http://docs.oracle.com/javase/6/docs/api/java/awt/Font.html#deriveFont%28float%29

JComponent has a setFont() method. You will control the font there, not on the String.

Such as

JButton b = new JButton();
b.setFont(b.getFont().deriveFont(18.0f));

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

My issue was similar - I had a new table i was creating that ahd to tie in to the identity users. After reading the above answers, realized it had to do with IsdentityUser and the inherited properites. I already had Identity set up as its own Context, so to avoid inherently tying the two together, rather than using the related user table as a true EF property, I set up a non-mapped property with the query to get the related entities. (DataManager is set up to retrieve the current context in which OtherEntity exists.)

    [Table("UserOtherEntity")]
        public partial class UserOtherEntity
        {
            public Guid UserOtherEntityId { get; set; }
            [Required]
            [StringLength(128)]
            public string UserId { get; set; }
            [Required]
            public Guid OtherEntityId { get; set; }
            public virtual OtherEntity OtherEntity { get; set; }
        }

    public partial class UserOtherEntity : DataManager
        {
            public static IEnumerable<OtherEntity> GetOtherEntitiesByUserId(string userId)
            {
                return Connect2Context.UserOtherEntities.Where(ue => ue.UserId == userId).Select(ue => ue.OtherEntity);
            }
        }

public partial class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }

        [NotMapped]
        public IEnumerable<OtherEntity> OtherEntities
        {
            get
            {
                return UserOtherEntities.GetOtherEntitiesByUserId(this.Id);
            }
        }
    }

Hiding axis text in matplotlib plots

Instead of hiding each element, you can hide the whole axis:

frame1.axes.get_xaxis().set_visible(False)
frame1.axes.get_yaxis().set_visible(False)

Or, you can set the ticks to an empty list:

frame1.axes.get_xaxis().set_ticks([])
frame1.axes.get_yaxis().set_ticks([])

In this second option, you can still use plt.xlabel() and plt.ylabel() to add labels to the axes.

<strong> vs. font-weight:bold & <em> vs. font-style:italic

HTML represents meaning; CSS represents appearance. How you mark up text in a document is not determined by how that text appears on screen, but simply what it means. As another example, some other HTML elements, like headings, are styled font-weight: bold by default, but they are marked up using <h1><h6>, not <strong> or <b>.

In HTML5, you use <strong> to indicate important parts of a sentence, for example:

<p><strong>Do not touch.</strong> Contains <strong>hazardous</strong> materials.

And you use <em> to indicate linguistic stress, for example:

<p>A Gentleman: I suppose he does. But there's no point in asking.
<p>A Lady: Why not?
<p>A Gentleman: Because he doesn't row.
<p>A Lady: He doesn't <em>row</em>?
<p>A Gentleman: No. He <em>doesn't</em> row.
<p>A Lady: Ah. I see what you mean.

These elements are semantic elements that just happen to have bold and italic representations by default, but you can style them however you like. For example, in the <em> sample above, you could represent stress emphasis in uppercase instead of italics, but the functional purpose of the <em> element remains the same — to change the context of a sentence by emphasizing specific words or phrases over others:

em {
    font-style: normal;
    text-transform: uppercase;
}

Note that the original answer (below) applied to HTML standards prior to HTML5, in which <strong> and <em> had somewhat different meanings, <b> and <i> were purely presentational and had no semantic meaning whatsoever. Like <strong> and <em> respectively, they have similar presentational defaults but may be styled differently.


You use <strong> and <em> to indicate intense emphasis and normal emphasis respectively.

Or think of it this way: font-weight: bold is closer to <b> than <strong>, and font-style: italic is closer to <i> than <em>. These visual styles are purely visual: tools like screen readers aren't going to understand what bold and italic mean, but some screen readers are able to read <strong> and <em> text in a more emphasized tone.

Check that a input to UITextField is numeric only

There are a few ways you could do this:

  1. Use NSNumberFormatter's numberFromString: method. This will return an NSNumber if it can parse the string correctly, or nil if it cannot.
  2. Use NSScanner
  3. Strip any non-numeric character and see if the string still matches
  4. Use a regular expression

IMO, using something like -[NSString doubleValue] wouldn't be the best option because both @"0.0" and @"abc" will have a doubleValue of 0. The *value methods all return 0 if they're not able to convert the string properly, so it would be difficult to distinguish between a legitimate string of @"0" and a non-valid string. Something like C's strtol function would have the same issue.

I think using NSNumberFormatter would be the best option, since it takes locale into account (ie, the number @"1,23" in Europe, versus @"1.23" in the USA).

How do malloc() and free() work?

Your strcpy line attempts to store 9 bytes, not 8, because of the NUL terminator. It invokes undefined behaviour.

The call to free may or may not crash. The memory "after" the 4 bytes of your allocation might be used for something else by your C or C++ implementation. If it is used for something else, then scribbling all over it will cause that "something else" to go wrong, but if it isn't used for anything else, then you could happen to get away with it. "Getting away with it" might sound good, but is actually bad, since it means your code will appear to run OK, but on a future run you might not get away with it.

With a debugging-style memory allocator, you might find that a special guard value has been written there, and that free checks for that value and panics if it doesn't find it.

Otherwise, you might find that the next 5 bytes includes part of a link node belonging to some other block of memory which hasn't been allocated yet. Freeing your block could well involved adding it to a list of available blocks, and because you've scribbled in the list node, that operation could dereference a pointer with an invalid value, causing a crash.

It all depends on the memory allocator - different implementations use different mechanisms.

how to modify the size of a column

Regardless of what error Oracle SQL Developer may indicate in the syntax highlighting, actually running your alter statement exactly the way you originally had it works perfectly:

ALTER TABLE TEST_PROJECT2 MODIFY proj_name VARCHAR2(300);

You only need to add parenthesis if you need to alter more than one column at once, such as:

ALTER TABLE TEST_PROJECT2 MODIFY (proj_name VARCHAR2(400), proj_desc VARCHAR2(400));

Is there any difference between GROUP BY and DISTINCT

For the query you posted, they are identical. But for other queries that may not be true.

For example, it's not the same as:

SELECT C FROM myTbl GROUP BY C, D

Can I pass column name as input parameter in SQL stored Procedure

This is not possible. Either use dynamic SQL (dangerous) or a gigantic case expression (slow).

Colouring plot by factor in R

Like Maiasaura, I prefer ggplot2. The transparent reference manual is one of the reasons. However, this is one quick way to get it done.

require(ggplot2)
data(diamonds)
qplot(carat, price, data = diamonds, colour = color)
# example taken from Hadley's ggplot2 book

And cause someone famous said, plot related posts are not complete without the plot, here's the result:

enter image description here

Here's a couple of references: qplot.R example, note basically this uses the same diamond dataset I use, but crops the data before to get better performance.

http://ggplot2.org/book/ the manual: http://docs.ggplot2.org/current/

Inline labels in Matplotlib

Update: User cphyc has kindly created a Github repository for the code in this answer (see here), and bundled the code into a package which may be installed using pip install matplotlib-label-lines.


Pretty Picture:

semi-automatic plot-labeling

In matplotlib it's pretty easy to label contour plots (either automatically or by manually placing labels with mouse clicks). There does not (yet) appear to be any equivalent capability to label data series in this fashion! There may be some semantic reason for not including this feature which I am missing.

Regardless, I have written the following module which takes any allows for semi-automatic plot labelling. It requires only numpy and a couple of functions from the standard math library.

Description

The default behaviour of the labelLines function is to space the labels evenly along the x axis (automatically placing at the correct y-value of course). If you want you can just pass an array of the x co-ordinates of each of the labels. You can even tweak the location of one label (as shown in the bottom right plot) and space the rest evenly if you like.

In addition, the label_lines function does not account for the lines which have not had a label assigned in the plot command (or more accurately if the label contains '_line').

Keyword arguments passed to labelLines or labelLine are passed on to the text function call (some keyword arguments are set if the calling code chooses not to specify).

Issues

  • Annotation bounding boxes sometimes interfere undesirably with other curves. As shown by the 1 and 10 annotations in the top left plot. I'm not even sure this can be avoided.
  • It would be nice to specify a y position instead sometimes.
  • It's still an iterative process to get annotations in the right location
  • It only works when the x-axis values are floats

Gotchas

  • By default, the labelLines function assumes that all data series span the range specified by the axis limits. Take a look at the blue curve in the top left plot of the pretty picture. If there were only data available for the x range 0.5-1 then then we couldn't possibly place a label at the desired location (which is a little less than 0.2). See this question for a particularly nasty example. Right now, the code does not intelligently identify this scenario and re-arrange the labels, however there is a reasonable workaround. The labelLines function takes the xvals argument; a list of x-values specified by the user instead of the default linear distribution across the width. So the user can decide which x-values to use for the label placement of each data series.

Also, I believe this is the first answer to complete the bonus objective of aligning the labels with the curve they're on. :)

label_lines.py:

from math import atan2,degrees
import numpy as np

#Label line with line2D label data
def labelLine(line,x,label=None,align=True,**kwargs):

    ax = line.axes
    xdata = line.get_xdata()
    ydata = line.get_ydata()

    if (x < xdata[0]) or (x > xdata[-1]):
        print('x label location is outside data range!')
        return

    #Find corresponding y co-ordinate and angle of the line
    ip = 1
    for i in range(len(xdata)):
        if x < xdata[i]:
            ip = i
            break

    y = ydata[ip-1] + (ydata[ip]-ydata[ip-1])*(x-xdata[ip-1])/(xdata[ip]-xdata[ip-1])

    if not label:
        label = line.get_label()

    if align:
        #Compute the slope
        dx = xdata[ip] - xdata[ip-1]
        dy = ydata[ip] - ydata[ip-1]
        ang = degrees(atan2(dy,dx))

        #Transform to screen co-ordinates
        pt = np.array([x,y]).reshape((1,2))
        trans_angle = ax.transData.transform_angles(np.array((ang,)),pt)[0]

    else:
        trans_angle = 0

    #Set a bunch of keyword arguments
    if 'color' not in kwargs:
        kwargs['color'] = line.get_color()

    if ('horizontalalignment' not in kwargs) and ('ha' not in kwargs):
        kwargs['ha'] = 'center'

    if ('verticalalignment' not in kwargs) and ('va' not in kwargs):
        kwargs['va'] = 'center'

    if 'backgroundcolor' not in kwargs:
        kwargs['backgroundcolor'] = ax.get_facecolor()

    if 'clip_on' not in kwargs:
        kwargs['clip_on'] = True

    if 'zorder' not in kwargs:
        kwargs['zorder'] = 2.5

    ax.text(x,y,label,rotation=trans_angle,**kwargs)

def labelLines(lines,align=True,xvals=None,**kwargs):

    ax = lines[0].axes
    labLines = []
    labels = []

    #Take only the lines which have labels other than the default ones
    for line in lines:
        label = line.get_label()
        if "_line" not in label:
            labLines.append(line)
            labels.append(label)

    if xvals is None:
        xmin,xmax = ax.get_xlim()
        xvals = np.linspace(xmin,xmax,len(labLines)+2)[1:-1]

    for line,x,label in zip(labLines,xvals,labels):
        labelLine(line,x,label,align,**kwargs)

Test code to generate the pretty picture above:

from matplotlib import pyplot as plt
from scipy.stats import loglaplace,chi2

from labellines import *

X = np.linspace(0,1,500)
A = [1,2,5,10,20]
funcs = [np.arctan,np.sin,loglaplace(4).pdf,chi2(5).pdf]

plt.subplot(221)
for a in A:
    plt.plot(X,np.arctan(a*X),label=str(a))

labelLines(plt.gca().get_lines(),zorder=2.5)

plt.subplot(222)
for a in A:
    plt.plot(X,np.sin(a*X),label=str(a))

labelLines(plt.gca().get_lines(),align=False,fontsize=14)

plt.subplot(223)
for a in A:
    plt.plot(X,loglaplace(4).pdf(a*X),label=str(a))

xvals = [0.8,0.55,0.22,0.104,0.045]
labelLines(plt.gca().get_lines(),align=False,xvals=xvals,color='k')

plt.subplot(224)
for a in A:
    plt.plot(X,chi2(5).pdf(a*X),label=str(a))

lines = plt.gca().get_lines()
l1=lines[-1]
labelLine(l1,0.6,label=r'$Re=${}'.format(l1.get_label()),ha='left',va='bottom',align = False)
labelLines(lines[:-1],align=False)

plt.show()

SQL Not Like Statement not working

Is the value of your particular COMMENT column null?

Sometimes NOT LIKE doesn't know how to behave properly around nulls.

How do I clear all options in a dropdown box?

Using JQuery is a prettier, shorter & smarter way to do it!

$('#selection_box_id').empty();

The best way to calculate the height in a binary search tree? (balancing an AVL-tree)

Here's an alternate way of finding height. Add an additional attribute to your node called height:

class Node
{
data value; //data is a custom data type
node right;
node left;
int height;
}

Now, we'll do a simple breadth-first traversal of the tree, and keep updating the height value for each node:

int height (Node root)
{
Queue<Node> q = Queue<Node>();
Node lastnode;
//reset height
root.height = 0;

q.Enqueue(root);
while(q.Count > 0)
{
   lastnode = q.Dequeue();
   if (lastnode.left != null){
      lastnode.left.height = lastnode.height + 1; 
      q.Enqueue(lastnode.left);
   }

   if (lastnode.right != null){
      lastnode.right.height = lastnode.height + 1;
      q.Enqueue(lastnode.right);
   }
}
return lastnode.height; //this will return a 0-based height, so just a root has a height of 0
}

Cheers,

Cannot find pkg-config error

For Ubuntu/Debian OS,

apt-get install -y pkg-config

For Redhat/Yum OS,

yum install -y pkgconfig

For Archlinux OS,

pacman -S pkgconf

Angular JS - angular.forEach - How to get key of the object?

The first parameter to the iterator in forEach is the value and second is the key of the object.

angular.forEach(objectToIterate, function(value, key) {
    /* do something for all key: value pairs */
});

In your example, the outer forEach is actually:

angular.forEach($scope.filters, function(filterObj , filterKey)

How to add button tint programmatically

I had a similar problem. I wished to colour a complex drawable background for a view based on a color (int) value. I succeeded by using the code:

ColorStateList csl = new ColorStateList(new int[][]{{}}, new int[]{color});
textView.setBackgroundTintList(csl);

Where color is an int value representing the colour required. This represents the simple xml ColorStateList:

<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:color="color here"/>
</selector>

Hope this helps.

change values in array when doing foreach

Let's try to keep it simple and discuss how it is actually working. It has to do with variable types and function parameters.

Here is your code we are talking about:

var arr = ["one","two","three"];

arr.forEach(function(part) {
  part = "four";
  return "four";
})

alert(arr);

First off, here is where you should be reading about Array.prototype.forEach():

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Second, let's talk briefly about value types in JavaScript.

Primitives (undefined, null, String, Boolean, Number) store an actual value.

ex: var x = 5;

Reference Types (custom objects) store the memory location of the object.

ex: var xObj = { x : 5 };

And third, how function parameters work.

In functions, parameters are always passed by value.

Because arr is an array of Strings, it's an array of primitive objects, which means they are stored by value.

So for your code above, this means that each time the forEach() iterates, part is equal to the same value as arr[index], but not the same object.

part = "four"; will change the part variable, but will leave arr alone.

The following code will change the values you desire:

var arr = ["one","two","three"];

arr.forEach(function(part, index) {
  arr[index] = "four";
});

alert(arr);

Now if array arr was an array of reference types, the following code will work because reference types store a memory location of an object instead of the actual object.

var arr = [{ num : "one" }, { num : "two"}, { num : "three"}];

arr.forEach(function(part, index) {
  // part and arr[index] point to the same object
  // so changing the object that part points to changes the object that arr[index] points to

  part.num = "four";
});

alert(arr[0].num);
alert(arr[1].num);
alert(arr[2].num);

The following illustrates that you can change part to point to a new object while leaving the objects stored in arr alone:

var arr = [{ num : "one" }, { num : "two"}, { num : "three"}];

arr.forEach(function(part, index) {
  // the following will not change the object that arr[index] points to because part now points at a new object
  part = 5;
});

alert(arr[0].num);
alert(arr[1].num);
alert(arr[2].num);

Displaying output of a remote command with Ansible

Prints pubkey and avoid the changed status by adding changed_when: False to cat task:

- name: Generate SSH keys for vagrant user   
  user: name=vagrant generate_ssh_key=yes ssh_key_bits=2048

- name: Check SSH public key   
  command: /bin/cat $home_directory/.ssh/id_rsa.pub
  register: cat
  changed_when: False

- name: Print SSH public key
  debug: var=cat.stdout

- name: Wait for user to copy SSH public key   
  pause: prompt="Please add the SSH public key above to your GitHub account"

How do you get the width and height of a multi-dimensional array?

Some of the other posts are confused about which dimension is which. Here's an NUNIT test that shows how 2D arrays work in C#

[Test]
public void ArraysAreRowMajor()
{
    var myArray = new int[2,3]
        {
            {1, 2, 3},
            {4, 5, 6}
        };

    int rows = myArray.GetLength(0);
    int columns = myArray.GetLength(1);
    Assert.AreEqual(2,rows);
    Assert.AreEqual(3,columns);
    Assert.AreEqual(1,myArray[0,0]);
    Assert.AreEqual(2,myArray[0,1]);
    Assert.AreEqual(3,myArray[0,2]);
    Assert.AreEqual(4,myArray[1,0]);
    Assert.AreEqual(5,myArray[1,1]);
    Assert.AreEqual(6,myArray[1,2]);
}

Play audio as microphone input

Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.

I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.

If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1922-1' for key 'IDX_STOCK_PRODUCT'

I just added an @ symbol and it started working. Like this: @$product->save();

How to uncheck checkbox using jQuery Uniform library

_x000D_
_x000D_
 $("#checkall").change(function () {_x000D_
            var checked = $(this).is(':checked');_x000D_
            if (checked) {_x000D_
                $(".custom-checkbox").each(function () {_x000D_
                    $(this).prop("checked", true).uniform();_x000D_
                });_x000D_
            } else {_x000D_
                $(".custom-checkbox").each(function () {_x000D_
                    $(this).prop("checked", false).uniform();_x000D_
                });_x000D_
            }_x000D_
        });_x000D_
_x000D_
        // Changing state of CheckAll custom-checkbox_x000D_
        $(".custom-checkbox").click(function () {_x000D_
            if ($(".custom-checkbox").length == $(".custom-checkbox:checked").length) {_x000D_
                $("#chk-all").prop("checked", true).uniform();_x000D_
            } else {_x000D_
                $("#chk-all").removeAttr("checked").uniform();_x000D_
            }_x000D_
        });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="checkbox" id='checkall' /> Select All<br/>_x000D_
 <input type="checkbox" class='custom-checkbox' name="languages" value="PHP"> PHP<br/>_x000D_
 <input type="checkbox" class='custom-checkbox' name="languages" value="AngularJS"> AngularJS<br/>_x000D_
 <input type="checkbox" class='custom-checkbox' name="languages" value="Python"> Python<br/>_x000D_
 <input type="checkbox" class='custom-checkbox' name="languages" value="Java"> Java<br/>
_x000D_
_x000D_
_x000D_

'MOD' is not a recognized built-in function name

for your exact sample, it should be like this.

DECLARE @m INT
SET @m = 321%11
SELECT @m

gpg: no valid OpenPGP data found

export https_proxy=http://user:pswd@host:port
                   ^^^^

Use http for https_proxy instead of https

Enzyme - How to access and set <input> value?

I think what you want is:

input.simulate('change', { target: { value: 'Hello' } })

Here's my source.

You shouldn't need to use render() anywhere to set the value. And just FYI, you are using two different render()'s. The one in your first code block is from Enzyme, and is a method on the wraper object mount and find give you. The second one, though it's not 100% clear, is probably the one from react-dom. If you're using Enzyme, just use shallow or mount as appropriate and there's no need for render from react-dom.

Read/Write 'Extended' file properties (C#)

  • After looking at a number of solutions on this thread and elsewhere the following code was put together. This is only to read a property.
  • I could not get the Shell32.FolderItem2.ExtendedProperty function to work, it is supposed to take a string value and return the correct value and type for that property... this was always null for me and developer reference resources were very thin.
  • The WindowsApiCodePack seems to have been abandoned by Microsoft which brings us the code below.

Use:

string propertyValue = GetExtendedFileProperty("c:\\temp\\FileNameYouWant.ext","PropertyYouWant");
  1. Will return you the value of the extended property you want as a string for the given file and property name.
  2. Only loops until it found the specified property - not until all properties are discovered like some sample code
  3. Will work on Windows versions like Windows server 2008 where you will get the error "Unable to cast COM object of type 'System.__ComObject' to interface type 'Shell32.Shell'" if just trying to create the Shell32 Object normally.

    public static string GetExtendedFileProperty(string filePath, string propertyName)
    {
        string value = string.Empty;
        string baseFolder = Path.GetDirectoryName(filePath);
        string fileName = Path.GetFileName(filePath);
    
        //Method to load and execute the Shell object for Windows server 8 environment otherwise you get "Unable to cast COM object of type 'System.__ComObject' to interface type 'Shell32.Shell'"
        Type shellAppType = Type.GetTypeFromProgID("Shell.Application");
        Object shell = Activator.CreateInstance(shellAppType);
        Shell32.Folder shellFolder = (Shell32.Folder)shellAppType.InvokeMember("NameSpace", System.Reflection.BindingFlags.InvokeMethod, null, shell, new object[] { baseFolder });
    
        //Parsename will find the specific file I'm looking for in the Shell32.Folder object
        Shell32.FolderItem folderitem = shellFolder.ParseName(fileName);
        if (folderitem != null)
        {
            for (int i = 0; i < short.MaxValue; i++)
            {
                //Get the property name for property index i
                string property = shellFolder.GetDetailsOf(null, i);
    
                //Will be empty when all possible properties has been looped through, break out of loop
                if (String.IsNullOrEmpty(property)) break;
    
                //Skip to next property if this is not the specified property
                if (property != propertyName) continue;    
    
                //Read value of property
                value = shellFolder.GetDetailsOf(folderitem, i);
            }
        }
        //returns string.Empty if no value was found for the specified property
        return value;
    }
    

CSS - Expand float child DIV height to parent's height

Does the parent have a height? If you set the parents height like so.

div.parent { height: 300px };

Then you can make the child stretch to the full height like this.

div.child-right { height: 100% };

EDIT

Here is how you would do it using JavaScript.

Project Links do not work on Wamp Server

Re: Wampserver LocalHost links not working correctly
This is as of June 2014 with Wampserver2.5 (maybe they'll fix this in later builds).
Note: to use LocalHost:8080 instead of LocalHost just make the appropriate changes in the edits mentioned below.

There are 2 aspects of this issue -
The first is to be able to access items under "Your Projects" from the Wamp localhost homepage.
The second is to be able to correctly access items listed in the Wampserver Icon Taskbar's "My Projects" list.

To fix the first (to be able to access items under "Your Projects" from the Wamp localhost homepage) you will need to do the following...

There are 2 edits that you must make in the index.php file located in your wamp\www folder (usually C:\wamp\www)

1) on Line 30 change

  $suppress_localhost = true;

to

  $suppress_localhost = false;

2) on line 338 change

  $projectContents .= '<li><a href="'.($suppress_localhost ? 'http://' : '').$file.'">'.$file.'</a></li>';

to

  $projectContents .= '<li><a href="'.($suppress_localhost ? 'http://' : 'http://localhost//').$file.'">'.$file.'</a></li>';

After you've made the above edits - if the Wampserver is running just refresh the local host page and the changes become immediately effective.

To fix the 2nd item (the Wampserver Icon Taskbar's "My Projects" list): You need to edit C:\wamp\scripts\refresh.php

Locate line 651 and change the section of the line that reads

   Parameters: "http://'.$projectContents[$i].'/"; Glyph: 5

to

   Parameters: "http://localhost//'.$projectContents[$i].'/"; Glyph: 5

After you make these 2nd set of changes you may have to force Wampserver to refresh the "My Projects" list by toggling the Put Online/Offline option at the bottom of the Wamp Icon Tray App.

Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2

open the gradlew file with android studio, everything will be downloaded

How to convert java.util.Date to java.sql.Date?

This function will return a converted SQL date from java date object.

public static java.sql.Date convertFromJAVADateToSQLDate(
            java.util.Date javaDate) {
        java.sql.Date sqlDate = null;
        if (javaDate != null) {
            sqlDate = new Date(javaDate.getTime());
        }
        return sqlDate;
    }

ValueError: shape mismatch: objects cannot be broadcast to a single shape

This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n and the output of np.add.reduce() are both scalars, this implies that the problem lies with xm and ym, the two of which are simply your x and y inputs minus their respective means.

Based on this, my guess is that your x and y inputs have different shapes from one another, making them incompatible for element-wise multiplication.

** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.

Ruby 'require' error: cannot load such file

Just do this:

require_relative 'tokenizer'

If you put this in a Ruby file that is in the same directory as tokenizer.rb, it will work fine no matter what your current working directory (CWD) is.

Explanation of why this is the best way

The other answers claim you should use require './tokenizer', but that is the wrong answer, because it will only work if you run your Ruby process in the same directory that tokenizer.rb is in. Pretty much the only reason to consider using require like that would be if you need to support Ruby 1.8, which doesn't have require_relative.

The require './tokenizer' answer might work for you today, but it unnecessarily limits the ways in which you can run your Ruby code. Tomorrow, if you want to move your files to a different directory, or just want to start your Ruby process from a different directory, you'll have to rethink all of those require statements.

Using require to access files that are on the load path is a fine thing and Ruby gems do it all the time. But you shouldn't start the argument to require with a . unless you are doing something very special and know what you are doing.

When you write code that makes assumptions about its environment, you should think carefully about what assumptions to make. In this case, there are up to three different ways to require the tokenizer file, and each makes a different assumption:

  1. require_relative 'path/to/tokenizer': Assumes that the relative path between the two Ruby source files will stay the same.
  2. require 'path/to/tokenizer': Assumes that path/to/tokenizer is inside one of the directories on the load path ($LOAD_PATH). This generally requires extra setup, since you have to add something to the load path.
  3. require './path/to/tokenizer': Assumes that the relative path from the Ruby process's current working directory to tokenizer.rb is going to stay the same.

I think that for most people and most situations, the assumptions made in options #1 and #2 are more likely to hold true over time.

Error in MySQL when setting default value for DATE or DATETIME

Option combinations for mysql Ver 14.14 Distrib 5.7.18, for Linux (x86_64).

Doesn't throw:

STRICT_TRANS_TABLES + NO_ZERO_DATE

Throws:

STRICT_TRANS_TABLES + NO_ZERO_IN_DATE

My settings in /etc/mysql/my.cnf on Ubuntu:

[mysqld]
sql_mode = "STRICT_TRANS_TABLES,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

How do you set the startup page for debugging in an ASP.NET MVC application?

While you can have a default page in the MVC project, the more conventional implementation for a default view would be to use a default controller, implememented in the global.asax, through the 'RegisterRoutes(...)' method. For instance if you wanted your Public\Home controller to be your default route/view, the code would be:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Public", action = "Home", id = UrlParameter.Optional } // Parameter defaults
        );

    }

For this to be functional, you are required to have have a set Start Page in the project.

Why does my 'git branch' have no master?

If you create a new repository from the Github web GUI, you sometimes get the name 'main' instead of 'master'. By using the command git status from your terminal you'd see which location you are. In some cases, you'd see origin/main.

If you are trying to push your app to a cloud service via CLI then use 'main', not 'master'.

example: git push heroku main

What do >> and << mean in Python?

<< Mean any given number will be multiply by 2the power
for exp:- 2<<2=2*2'1=4
          6<<2'4=6*2*2*2*2*2=64

How do I send a POST request as a JSON?

This works perfect for Python 3.5, if the URL contains Query String / Parameter value,

Request URL = https://bah2.com/ws/rest/v1/concept/
Parameter value = 21f6bb43-98a1-419d-8f0c-8133669e40ca

import requests

url = 'https://bahbah2.com/ws/rest/v1/concept/21f6bb43-98a1-419d-8f0c-8133669e40ca'
data = {"name": "Value"}
r = requests.post(url, auth=('username', 'password'), verify=False, json=data)
print(r.status_code)

Unable to start the mysql server in ubuntu

I think this is because you are using client software and not the server.

  • mysql is client
  • mysqld is the server

Try: sudo service mysqld start

To check that service is running use: ps -ef | grep mysql | grep -v grep.

Uninstalling:

sudo apt-get purge mysql-server
sudo apt-get autoremove
sudo apt-get autoclean

Re-Installing:

sudo apt-get update
sudo apt-get install mysql-server

Backup entire folder before doing this:

sudo rm /etc/apt/apt.conf.d/50unattended-upgrades*
sudo apt-get update
sudo apt-get upgrade

Using getResources() in non-activity class

This always works for me:

import android.app.Activity;
import android.content.Context;

public class yourClass {

 Context ctx;

 public yourClass (Handler handler, Context context) {
 super(handler);
    ctx = context;
 }

 //Use context (ctx) in your code like this:
 XmlPullParser xpp = ctx.getResources().getXml(R.xml.samplexml);
 //OR
 final Intent intent = new Intent(ctx, MainActivity.class);
 //OR
 NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
 //ETC...

}

Not related to this question but example using a Fragment to access system resources/activity like this:

public boolean onQueryTextChange(String newText) {
 Activity activity = getActivity();
 Context context = activity.getApplicationContext();
 returnSomething(newText);
 return false;
}

View customerInfo = getActivity().getLayoutInflater().inflate(R.layout.main_layout_items, itemsLayout, false);
 itemsLayout.addView(customerInfo);

C#, Looping through dataset and show each record from a dataset column

foreach (DataRow dr in ds.Tables[0].Rows)
{
    //your code here
}

What is the use of "assert"?

Here is a simple example, save this in file (let's say b.py)

def chkassert(num):
    assert type(num) == int


chkassert('a')

and the result when $python b.py

Traceback (most recent call last):
  File "b.py", line 5, in <module>
    chkassert('a')
  File "b.py", line 2, in chkassert
    assert type(num) == int
AssertionError

Sorting Values of Set

You need to pass in a Comparator instance to the sort method otherwise the elements will be sorted in their natural order.

For more information check Collections.sort(List, Comparator)

Run a Java Application as a Service on Linux

However once started I don't know how to access it to stop it

You can write a simple stop script that greps for your java process, extracts the PID and calls kill on it. It's not fancy, but it's straight forward. Something like that may be of help as a start:

#!/bin/bash
PID = ps ax | grep "name of your app" | cut -d ' ' -f 1
kill $PID

Link error "undefined reference to `__gxx_personality_v0'" and g++

If g++ still gives error Try using:

g++ file.c -lstdc++

Look at this post: What is __gxx_personality_v0 for?

Make sure -lstdc++ is at the end of the command. If you place it at the beginning (i.e. before file.c), you still can get this same error.

Installation error: INSTALL_FAILED_OLDER_SDK

You will see the same error if you are trying to install an apk that was built using

compileSdkVersion "android-L"

Even for devices running the final version of Android 5.0. Simply change this to

compileSdkVersion 21

Understanding lambda in python and using it to pass multiple arguments

Why do you need to state both 'x' and 'y' before the ':'?

Because a lambda is (conceptually) the same as a function, just written inline. Your example is equivalent to

def f(x, y) : return x + y

just without binding it to a name like f.

Also how do you make it return multiple arguments?

The same way like with a function. Preferably, you return a tuple:

lambda x, y: (x+y, x-y)

Or a list, or a class, or whatever.

The thing with self.entry_1.bind should be answered by Demosthenex.

How to get a file directory path from file path?

On a related note, if you only have the filename or relative path, dirname on its own won't help. For me, the answer ended up being readlink.

fname='txtfile'    
echo $(dirname "$fname")                # output: .
echo $(readlink -f "$fname")            # output: /home/me/work/txtfile

You can then combine the two to get just the directory.

echo $(dirname $(readlink -f "$fname")) # output: /home/me/work

Authorize attribute in ASP.NET MVC

Using Authorize attribute seems more convenient and feels more 'MVC way'. As for technical advantages there are some.

One scenario that comes to my mind is when you're using output caching in your app. Authorize attribute handles that well.

Another would be extensibility. The Authorize attribute is just basic out of the box filter, but you can override its methods and do some pre-authorize actions like logging etc. I'm not sure how you would do that through configuration.

How do I Sort a Multidimensional Array in PHP

You can use array_multisort()

Try something like this:

foreach ($mdarray as $key => $row) {
    // replace 0 with the field's index/key
    $dates[$key]  = $row[0];
}

array_multisort($dates, SORT_DESC, $mdarray);

For PHP >= 5.5.0 just extract the column to sort by. No need for the loop:

array_multisort(array_column($mdarray, 0), SORT_DESC, $mdarray);

Avoiding "resource is out of sync with the filesystem"

This happens to me all the time.

Go to the error log, find the exception, and open a few levels until you can see something more like a root cause. Does it says "Resource is out of sync with the file system" ?

When renaming packages, of course, Eclipse has to move files around in the file system. Apparently what happens is that it later discovers that something it thinks it needs to clean up has been renamed, can't find it, throws an exception.

There are a couple of things you might try. First, go to Window: Preferences, Workspace, and enable "Refresh Automatically". In theory this should fix the problem, but for me, it didn't.

Second, if you are doing a large refactoring with subpackages, do the subpackages one at a time, from the bottom up, and explicitly refresh with the file system after each subpackage is renamed.

Third, just ignore the error: when the error dialog comes up, click Abort to preserve the partial change, instead of rolling it back. Try it again, and again, and you may find you can get through the entire operation using multiple retries.

MySQL convert date string to Unix timestamp

You will certainly have to use both STR_TO_DATE to convert your date to a MySQL standard date format, and UNIX_TIMESTAMP to get the timestamp from it.

Given the format of your date, something like

UNIX_TIMESTAMP(STR_TO_DATE(Sales.SalesDate, '%M %e %Y %h:%i%p'))

Will gives you a valid timestamp. Look the STR_TO_DATE documentation to have more information on the format string.

ruby 1.9: invalid byte sequence in UTF-8

This seems to work:

def sanitize_utf8(string)
  return nil if string.nil?
  return string if string.valid_encoding?
  string.chars.select { |c| c.valid_encoding? }.join
end

What does it mean by command cd /d %~dp0 in Windows

~dp0 : d=drive, p=path, %0=full path\name of this batch-file.

cd /d %~dp0 will change the path to the same, where the batch file resides.

See for /? or call / for more details about the %~... modifiers.
See cd /? about the /d switch.

How to copy a dictionary and only edit the copy

When you assign dict2 = dict1, you are not making a copy of dict1, it results in dict2 being just another name for dict1.

To copy the mutable types like dictionaries, use copy / deepcopy of the copy module.

import copy

dict2 = copy.deepcopy(dict1)

How do I check if an object's type is a particular subclass in C++?

You can do it with templates (or SFINAE (Substitution Failure Is Not An Error)). Example:

#include <iostream>

class base
{
public:
    virtual ~base() = default;
};

template <
    class type,
    class = decltype(
        static_cast<base*>(static_cast<type*>(0))
    )
>
bool check(type)
{
    return true;
}

bool check(...)
{
    return false;
}

class child : public base
{
public:
    virtual ~child() = default;
};

class grandchild : public child {};

int main()
{
    std::cout << std::boolalpha;

    std::cout << "base:       " << check(base())       << '\n';
    std::cout << "child:      " << check(child())      << '\n';
    std::cout << "grandchild: " << check(grandchild()) << '\n';
    std::cout << "int:        " << check(int())        << '\n';

    std::cout << std::flush;
}

Output:

base:       true
child:      true
grandchild: true
int:        false

ssh : Permission denied (publickey,gssapi-with-mic)

I had the same problem. In my case, macOS doesn't load my SSH keys, but I fix it with:

ssh-add <SSH private key>
ssh-add <SSH public key>

I couldn't connect to a Droplet on DigitalOcean, but the subsequent commands work for me.

You can go to the forum here.

All com.android.support libraries must use the exact same version specification

For all cases, not just for these versions or libraries:

Pay attention to the little information window that say something about the error, it says the examples that you have to change and add.

In this case:

Found versions 25.1.1, 24.0.0. Examples include com.android.support:animated-vector-drawable:25.1.1 and com.android.support:mediarouter-v7:24.0.0

Your

com.android.support:animated-vector-drawable:25.1.1

is version 25.1.1, and your

com.android.support:mediarouter-v7:24.0.0

is version 24.0.0, so you have to add the mediarouter with the same version:

com.android.support:mediarouter-v7:25.1.1

And do that for every example that the little information window says, in this case all the libraries that doesn't have the version 25.1.1.

You have to sync the gradle after you fix the indicated library to see the next library and package that you have to change.

IMPORTANT:

If you are not explicitly using one or more specified libraries and it is giving you the error, it means that is being used internally by another library, compile it explicitly anyway.

You also can use another method to see the difference of the versions of all the libraries that you are actually compiling (like run a gradle dependency report or go to your libraries files), the real objetive is compile all the libraries that you are using with the same version.

How do I install PIL/Pillow for Python 3.6?

For python version 2.x you can simply use

  • pip install pillow

But for python version 3.X you need to specify

  • (sudo) pip3 install pillow

when you enter pip in bash hit tab and you will see what options you have

Javascript: getFullyear() is not a function

You are overwriting the start date object with the value of a DOM Element with an id of Startdate.

This should work:

var start = new Date(document.getElementById('Stardate').value);

var y = start.getFullYear();

Why am I getting a "401 Unauthorized" error in Maven?

We have had this issue quite recently and found out it was to do with the version of Maven we were using. We were using 3.1.0 and could not upload to nexus, we kept getting 401's, we reverted back to 3.0.3 and the issue went away.

Easiest way to confirm is to work through the maven versions and run "mvn deploy" on your project.

Further details can be found here: https://issues.apache.org/jira/browse/WAGON-421

Converting data frame column from character to numeric

If we need only one column to be numeric

yyz$b <- as.numeric(as.character(yyz$b))

But, if all the columns needs to changed to numeric, use lapply to loop over the columns and convert to numeric by first converting it to character class as the columns were factor.

yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))

Both the columns in the OP's post are factor because of the string "n/a". This could be easily avoided while reading the file using na.strings = "n/a" in the read.table/read.csv or if we are using data.frame, we can have character columns with stringsAsFactors=FALSE (the default is stringsAsFactors=TRUE)


Regarding the usage of apply, it converts the dataset to matrix and matrix can hold only a single class. To check the class, we need

lapply(yyz, class)

Or

sapply(yyz, class)

Or check

str(yyz)

How to run Nginx within a Docker container without halting?

Adding this command to Dockerfile can disable it:

RUN echo "daemon off;" >> /etc/nginx/nginx.conf

Pandas How to filter a Series

If you like a chained operation, you can also use compress function:

test = pd.Series({
383:    3.000000,
663:    1.000000,
726:    1.000000,
737:    9.000000,
833:    8.166667
})

test.compress(lambda x: x != 1)

# 383    3.000000
# 737    9.000000
# 833    8.166667
# dtype: float64

Working with Enums in android

public enum Gender {
    MALE,
    FEMALE
}

How do I extract value from Json

we can use the below to get key as string from JSON OBJECT

JsonObject json = new JsonObject(); 
 json.get("key").getAsString();

this gives the string without double quotes " " in the string

Dealing with HTTP content in HTTPS pages

I realise that this is an old thread but one option is just to remove the http: part from the image URL so that 'http://some/image.jpg' becomes '//some/image.jpg'. This will also work with CDNs

AngularJS : When to use service instead of factory

Both the factory and the service result in singleton objects which are able to be configured by providers and injected into controllers and run blocks. From the point of view of the injectee, there is absolutely no difference whether the object came from a factory or a service.

So, when to use a factory, and when to use a service? It boils down to your coding preference, and nothing else. If you like the modular JS pattern then go for the factory. If you like the constructor function ("class") style then go for the service. Note that both styles support private members.

The advantage of the service might be that it's more intuitive from the OOP point of view: create a "class", and, in conjunction with a provider, reuse the same code across modules, and vary the behavior of the instantiated objects simply by supplying different parameters to the constructor in a config block.

How to express a One-To-Many relationship in Django

While rolling stone's answer is good, straightforward and functional, I think there are two things it does not solve.

  1. If OP wanted to enforce a phone number cannot belong to both a Dude and a Business
  2. The inescapable feeling of sadness as a result of defining the relationship on the PhoneNumber model and not on the Dude/Business models. When extra terrestrials come to Earth, and we want to add an Alien model, we need to modify the PhoneNumber (assuming the ETs have phone numbers) instead of simply adding a "phone_numbers" field to the Alien model.

Introduce the content types framework, which exposes some objects that allow us to create a "generic foreign key" on the PhoneNumber model. Then, we can define the reverse relationship on Dude and Business

from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db import models

class PhoneNumber(models.Model):
    number = models.CharField()

    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    owner = GenericForeignKey()

class Dude(models.Model):
    numbers = GenericRelation(PhoneNumber)

class Business(models.Model):
    numbers = GenericRelation(PhoneNumber)

See the docs for details, and perhaps check out this article for a quick tutorial.

Also, here is an article that argues against the use of Generic FKs.

What are Runtime.getRuntime().totalMemory() and freeMemory()?

Runtime#totalMemory - the memory that the JVM has allocated thus far. This isn't necessarily what is in use or the maximum.

Runtime#maxMemory - the maximum amount of memory that the JVM has been configured to use. Once your process reaches this amount, the JVM will not allocate more and instead GC much more frequently.

Runtime#freeMemory - I'm not sure if this is measured from the max or the portion of the total that is unused. I am guessing it is a measurement of the portion of total which is unused.

Pylint "unresolved import" error in Visual Studio Code

None of the solutions worked except this one. Replacing "Pylance" or "Microsoft" in the settings.json solved mine.

"python.languageServer": "Jedi"

Side-by-side plots with ggplot2

Using the patchwork package, you can simply use + operator:

library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))


p1 + p2

patchwork

Other operators include / to stack plots to place plots side by side, and () to group elements. For example you can configure a top row of 3 plots and a bottom row of one plot with (p1 | p2 | p3) /p. For more examples, see the package documentation.

Datagridview full row selection but get single cell value

Use Cell Click as other methods mentioned will fire upon data binding, not useful if you want the selected value, then the form to close.

private void dgvProducts_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (dgvProducts.SelectedCells.Count > 0) // Checking to see if any cell is selected
    {
        int mSelectedRowIndex = dgvProducts.SelectedCells[0].RowIndex;

        DataGridViewRow mSelectedRow = dgvProducts.Rows[mSelectedRowIndex];

        string mCatagoryName = Convert.ToString(mSelectedRow.Cells[1].Value);

        SomeOtherMethod(mProductName); // Passing the name to where ever you need it

        this.close();
    }
}

How to read file using NPOI

It might be helpful to rely on the Workbook factory to instantiate the workbook object since the factory method will do the detection of xls or xlsx for you. Reference: http://apache-poi.1045710.n5.nabble.com/How-to-check-for-valid-excel-files-using-POI-without-checking-the-file-extension-td2341055.html

IWorkbook workbook = WorkbookFactory.Create(inputStream);

If you're not sure of the Sheet's name but you are sure of the index (0 based), you can grab the sheet like this:

ISheet sheet = workbook.GetSheetAt(sheetIndex);

You can then iterate through the rows using code supplied by the accepted answer from mj82

Reading multiple Scanner inputs

If every input asks the same question, you should use a for loop and an array of inputs:

Scanner dd = new Scanner(System.in);
int[] vars = new int[3];

for(int i = 0; i < vars.length; i++) {
  System.out.println("Enter next var: ");
  vars[i] = dd.nextInt();
}

Or as Chip suggested, you can parse the input from one line:

Scanner in = new Scanner(System.in);
int[] vars = new int[3];

System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
  vars[i] = in.nextInt();

You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.

Comment out HTML and PHP together

Instead of using HTML comments (which have no effect on PHP code -- which will still be executed), you should use PHP comments:

<?php /*
<tr>
      <td><?php echo $entry_keyword; ?></td>
      <td><input type="text" name="keyword" value="<?php echo $keyword; ?>" /></td>
    </tr>
    <tr>
      <td><?php echo $entry_sort_order; ?></td>
      <td><input name="sort_order" value="<?php echo $sort_order; ?>" size="1" /></td>
    </tr>
*/ ?>


With that, the PHP code inside the HTML will not be executed; and nothing (not the HTML, not the PHP, not the result of its non-execution) will be displayed.


Just one note: you cannot nest C-style comments... which means the comment will end at the first */ encountered.

How can I position my div at the bottom of its container?

Yes you can do this without absolute positioning and without using tables (which screw with markup and such).

DEMO
This is tested to work on IE>7, chrome, FF & is a really easy thing to add to your existing layout.

<div id="container">
    Some content you don't want affected by the "bottom floating" div
    <div>supports not just text</div>

    <div class="foot">
        Some other content you want kept to the bottom
        <div>this is in a div</div>
    </div>
</div>
#container {
    height:100%;
    border-collapse:collapse;
    display : table;
}

.foot {
    display : table-row;
    vertical-align : bottom;
    height : 1px;
}

It effectively does what float:bottom would, even accounting for the issue pointed out in @Rick Reilly's answer!

error: the details of the application error from being viewed remotely

This can be the message you receive even when custom errors is turned off in web.config file. It can mean you have run out of free space on the drive that hosts the application. Clean your log files if you have no other space to gain on the drive.

How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?

developer.android.com has nice example code for this: https://developer.android.com/guide/topics/providers/document-provider.html

A condensed version to just extract the file name (assuming "this" is an Activity):

public String getFileName(Uri uri) {
  String result = null;
  if (uri.getScheme().equals("content")) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    try {
      if (cursor != null && cursor.moveToFirst()) {
        result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
      }
    } finally {
      cursor.close();
    }
  }
  if (result == null) {
    result = uri.getPath();
    int cut = result.lastIndexOf('/');
    if (cut != -1) {
      result = result.substring(cut + 1);
    }
  }
  return result;
}

Getting HTTP headers with Node.js

I'm not sure how you might do this with Node, but the general idea would be to send an HTTP HEAD request to the URL you're interested in.

HEAD

Asks for the response identical to the one that would correspond to a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content.


Something like this, based it on this question:

var cli = require('cli');
var http = require('http');
var url = require('url');

cli.parse();

cli.main(function(args, opts) {
        this.debug(args[0]);

        var siteUrl = url.parse(args[0]);
        var site = http.createClient(80, siteUrl.host);
        console.log(siteUrl);

        var request = site.request('HEAD', siteUrl.pathname, {'host' : siteUrl.host})
        request.end();

        request.on('response', function(response) {
                response.setEncoding('utf8');
                console.log('STATUS: ' + response.statusCode);
                response.on('data', function(chunk) {
                        console.log("DATA: " + chunk);
                });
        });
});

Git Push ERROR: Repository not found

I had the same problem, with a private repo.

do the following:

remove the remote origin

git remote rm origin

re-add the origin but with your username and pwd with writing privileges on this pvt repo

git remote add origin  https://USERNAME:[email protected]/username/reponame.git

When I catch an exception, how do I get the type, file, and line number?

Without any imports, but also incompatible with imported modules:

try:
    raise TypeError("Hello, World!")  # line 2
except Exception as e:
    print(
        type(e).__name__,          # TypeError
        __file__,                  # /tmp/example.py
        e.__traceback__.tb_lineno  # 2
    )

$ python3 /tmp/example.py
TypeError /tmp/example.py 2

To reiterate, this does not work across imports or modules, so if you do import X; try: X.example(); then the filename and line number will point to the line containing X.example() instead of the line where it went wrong within X.example(). If anyone knows how to easily get the file name and line number from the last stack trace line (I expected something like e[-1].filename, but no such luck), please improve this answer.

Import multiple csv files into pandas and concatenate into one DataFrame

Almost all of the answers here are either unnecessarily complex (glob pattern matching) or rely on additional 3rd party libraries. You can do this in 2 lines using everything Pandas and python (all versions) already have built in.

For a few files - 1 liner:

df = pd.concat(map(pd.read_csv, ['data/d1.csv', 'data/d2.csv','data/d3.csv']))

For many files:

from os import listdir

filepaths = [f for f in listdir("./data") if f.endswith('.csv')]
df = pd.concat(map(pd.read_csv, filepaths))

This pandas line which sets the df utilizes 3 things:

  1. Python's map (function, iterable) sends to the function (the pd.read_csv()) the iterable (our list) which is every csv element in filepaths).
  2. Panda's read_csv() function reads in each CSV file as normal.
  3. Panda's concat() brings all these under one df variable.

How to select rows with NaN in particular column?

Try the following:

df[df['Col2'].isnull()]

2D arrays in Python

>>> a = []

>>> for i in xrange(3):
...     a.append([])
...     for j in xrange(3):
...             a[i].append(i+j)
...
>>> a
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
>>>

Static constant string (class member)

This is just extra information, but if you really want the string in a header file, try something like:

class foo
{
public:
    static const std::string& RECTANGLE(void)
    {
        static const std::string str = "rectangle";

        return str;
    }
};

Though I doubt that's recommended.

Fatal error: Call to undefined function: ldap_connect()

If you are a Windows user, this is a common error when you use XAMPP since LDAP is not enabled by default.

You can follow this steps to make sure LDAP works in your XAMPP:

  • [Your Drive]:\xampp\php\php.ini: In this file uncomment the following line:

     extension=php_ldap.dll
    
  • Move the file: libsasl.dll, from [Your Drive]:\xampp\php to [Your Drive]:\xampp\apache\bin (Note: moving the file is needed only for XAMPP prior to version: 5.6.28)

  • Restart Apache.

  • You can now use functions of the LDAP Module!

If you use Linux:

For php5:

sudo apt-get install php5-ldap

For php7:

sudo apt-get install php7.0-ldap

If you are using the latest version of PHP you can do

sudo apt-get install php-ldap

running the above command should do the trick.

if for any reason it doesn't work check your php.ini configuration to enable ldap, remove the semicolon before extension=ldap to uncomment, save and restart Apache

constant pointer vs pointer on a constant value

char * const a;

means that the pointer is constant and immutable but the pointed data is not.
You could use const_cast(in C++) or c-style cast to cast away the constness in this case as data itself is not constant.

const char * a;

means that the pointed data cannot be written to using the pointer a. Using a const_cast(C++) or c-style cast to cast away the constness in this case causes Undefined Behavior.

how to write javascript code inside php

At the time the script is executed, the button does not exist because the DOM is not fully loaded. The easiest solution would be to put the script block after the form.

Another solution would be to capture the window.onload event or use the jQuery library (overkill if you only have this one JavaScript).

How do you pass a function as a parameter in C?

Pass address of a function as parameter to another function as shown below

#include <stdio.h>

void print();
void execute(void());

int main()
{
    execute(print); // sends address of print
    return 0;
}

void print()
{
    printf("Hello!");
}

void execute(void f()) // receive address of print
{
    f();
}

Also we can pass function as parameter using function pointer

#include <stdio.h>

void print();
void execute(void (*f)());

int main()
{
    execute(&print); // sends address of print
    return 0;
}

void print()
{
    printf("Hello!");
}

void execute(void (*f)()) // receive address of print
{
    f();
}

update query with join on two tables

update addresses set cid=id where id in (select id from customers)

How do I get ruby to print a full backtrace instead of a truncated one?

I was getting these errors when trying to load my test environment (via rake test or autotest) and the IRB suggestions didn't help. I ended up wrapping my entire test/test_helper.rb in a begin/rescue block and that fixed things up.

begin
  class ActiveSupport::TestCase
    #awesome stuff
  end
rescue => e
  puts e.backtrace
end

Reading settings from app.config or web.config in .NET

Right click on your class library, and choose the "Add References" option from the Menu.

And from the .NET tab, select System.Configuration. This would include the System.Configuration DLL file into your project.

How do I set up access control in SVN?

One gotcha which caught me out:

[repos:/path/to/dir/] # this won't work

but

[repos:/path/to/dir]  # this is right

You need to not include a trailing slash on the directory, or you'll see 403 for the OPTIONS request.

What is the difference between "expose" and "publish" in Docker?

EXPOSE is used to map local port container port ie : if you specify expose in docker file like

EXPOSE 8090

What will does it will map localhost port 8090 to container port 8090

HTML 5: Is it <br>, <br/>, or <br />?

<br> works just fine in HTML5. HTML5 allows a little more leeway than XHTML.

How to retrieve the dimensions of a view?

You are trying to get width and height of an elements, that weren't drawn yet.

If you use debug and stop at some point, you'll see, that your device screen is still empty, that's because your elements weren't drawn yet, so you can't get width and height of something, that doesn't yet exist.

And, I might be wrong, but setWidth() is not always respected, Layout lays out it's children and decides how to measure them (calling child.measure()), so If you set setWidth(), you are not guaranteed to get this width after element will be drawn.

What you need, is to use getMeasuredWidth() (the most recent measure of your View) somewhere after the view was actually drawn.

Look into Activity lifecycle for finding the best moment.

http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

I believe a good practice is to use OnGlobalLayoutListener like this:

yourView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (!mMeasured) {
                // Here your view is already layed out and measured for the first time
                mMeasured = true; // Some optional flag to mark, that we already got the sizes
            }
        }
    });

You can place this code directly in onCreate(), and it will be invoked when views will be laid out.

How to empty a char array?

I had similar problem. I was trying to display results of Analog to Digital value from a Char type Array. The problem was when I was turning the Pot to get lower voltage or lower converted decimal value like 5 from between (1023 - 0), the lift over characters from array was staying beside the number 5. I used this method to get rid of the problem:

LCD_Send_String(" "); \ used spaces as string characters LCD_Send_Command (LCD_THIRD_ROW); \Returned the cursor back at the start of line.

Show/hide div if checkbox selected

You would need to always consider the state of all checkboxes!

You could increase or decrease a number on checking or unchecking, but imagine the site loads with three of them checked.

So you always need to check all of them:

<script type="text/javascript">
<!--
function showMe (it, box) {
  // consider all checkboxes with same name
  var checked = amountChecked(box.name);

  var vis = (checked >= 3) ? "block" : "none";
  document.getElementById(it).style.display = vis;
}

function amountChecked(name) {
  var all = document.getElementsByName(name);

  // count checked
  var result = 0;
  all.forEach(function(el) {
    if (el.checked) result++;
  });

  return result;
}
//-->
</script>

Show / hide div on click with CSS

Fiddle to your heart's content

HTML

<div>
<a tabindex="1" class="testA">Test A</a> | <a tabindex="2" class="testB">Test B</a>
<div class="hiddendiv" id="testA">1</div>
<div class="hiddendiv" id="testB">2</div>
</div>

CSS

.hiddendiv {display: none; }
.testA:focus ~ #testA {display: block; }
.testB:focus ~ #testB {display: block; }

Benefits

You can put your menu links horizontally = one after the other in HTML code, and then you can put all the content one after another in the HTML code, after the menu.

In other words - other solutions offer an accordion approach where you click a link and the content appears immediately after the link. The next link then appears after that content.

With this approach you don't get the accordion effect. Rather, all links remain in a fixed position and clicking any link simply updates the displayed content. There is also no limitation on content height.

How it works

In your HTML, you first have a DIV. Everything else sits inside this DIV. This is important - it means every element in your solution (in this case, A for links, and DIV for content), is a sibling to every other element.

Secondly, the anchor tags (A) have a tabindex property. This makes them clickable and therefore they can get focus. We need that for the CSS to work. These could equally be DIVs but I like using A for links - and they'll be styled like my other anchors.

Third, each menu item has a unique class name. This is so that in the CSS we can identify each menu item individually.

Fourth, every content item is a DIV, and has the class="hiddendiv". However each each content item has a unique id.

In your CSS, we set all .hiddendiv elements to display:none; - that is, we hide them all.

Secondly, for each menu item we have a line of CSS. This means if you add more menu items (ie. and more hidden content), you will have to update your CSS, yes.

Third, the CSS is saying that when .testA gets focus (.testA:focus) then the corresponding DIV, identified by ID (#testA) should be displayed.

Last, when I just said "the corresponding DIV", the trick here is the tilde character (~) - this selector will select a sibling element, and it does not have to be the very next element, that matches the selector which, in this case, is the unique ID value (#testA).

It is this tilde that makes this solution different than others offered and this lets you simply update some "display panel" with different content, based on clicking one of those links, and you are not as constrained when it comes to where/how you organise your HTML. All you need, though, is to ensure your hidden DIVs are contained within the same parent element as your clickable links.

Season to taste.

Iterate a certain number of times without storing the iteration number anywhere

This will print 'hello' 3 times without storing i...

[print('hello') for i in range(3)]

ASP.NET MVC 404 Error Handling

In IIS, you can specify a redirect to "certain" page based on error code. In you example, you can configure 404 - > Your customized 404 error page.

VBA module that runs other modules

I just learned something new thanks to Artiso. I gave each module a name in the properties box. These names were also what I declared in the module. When I tried to call my second module, I kept getting an error: Compile error: Expected variable or procedure, not module

After reading Artiso's comment above about not having the same names, I renamed my second module, called it from the first, and problem solved. Interesting stuff! Thanks for the info Artiso!

In case my experience is unclear:

Module Name: AllFSGroupsCY Public Sub AllFSGroupsCY()

Module Name: AllFSGroupsPY Public Sub AllFSGroupsPY()

From AllFSGroupsCY()

Public Sub FSGroupsCY()

    AllFSGroupsPY 'will error each time until the properties name is changed

End Sub

Remove all special characters except space from a string using JavaScript

Try to use this one

var result= stringToReplace.replace(/[^\w\s]/g, '')

[^] is for negation, \w for [a-zA-Z0-9_] word characters and \s for space, /[]/g for global

SQL is null and = null

It's important to note, that NULL doesn't equal NULL.

NULL is not a value, and therefore cannot be compared to another value.

where x is null checks whether x is a null value.

where x = null is checking whether x equals NULL, which will never be true