Programs & Examples On #Selenium ide

The Selenium-IDE (Integrated Development Environment) is the tool you use to develop your Selenium test cases. It’s an easy-to-use Firefox plug-in and is generally the most efficient way to develop test cases.

How to use XPath preceding-sibling correctly

I also like to build locators from up to bottom like:

//div[contains(@class,'btn-group')][./button[contains(.,'Arcade Reader')]]/button[@name='settings']

It's pretty simple, as we just search btn-group with button[contains(.,'Arcade Reader')] and get it's button[@name='settings']

That's just another option to build xPath locators

What is the profit of searching wrapper element: you can return it by method (example in java) and just build selenium constructions like:

getGroupByName("Arcade Reader").find("button[name='settings']");
getGroupByName("Arcade Reader").find("button[name='delete']");

or even simplify more

getGroupButton("Arcade Reader", "delete").click();

Click in OK button inside an Alert (Selenium IDE)

Use the Alert Interface, First switchTo() to alert and then either use accept() to click on OK or use dismiss() to CANCEL it

Alert alert_box = driver.switchTo().alert();
alert_box.accept(); 

or

Alert alert_box = driver.switchTo().alert();
alert_box.dismiss(); 

Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?

For individual element the code below could be used:

private boolean isElementPresent(By by) {
        try {
            driver.findElement(by);
            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }
for (int second = 0;; second++) {
            if (second >= 60){
                fail("timeout");
            }
            try {
                if (isElementPresent(By.id("someid"))){
                    break;
                }
                }
            catch (Exception e) {

            }
            Thread.sleep(1000);
        }

Does Google Chrome work with Selenium IDE (as Firefox does)?

There is not a Google Chrome extension comparable to Selenium IDE.

Scirocco is only a partial (and reportedly unreliable) implementation.

There is another plugin, the Bug Buster Test Recorder, but it only works with their service. I don't know it's effectiveness.

Sahi and TestComplete can also record, but neither are free, and are not browser plugins.

iMacros is a plugin that allows record and playback, but is not geared towards testing, and is not compatible with Selenium.

It sounds like there is a demand for a tool like this, and Firefox is becoming unsupported by Selenium. So, while I know Stack Overflow isn't the forum for this, anyone interested in helping make it happen, let me know.

I'd be interested in what the limitations are and why it hasn't been done. Is it just that the official Selenium team doesn't want to support it, or is there a technical limitation?

Click a button with XPath containing partial id and title in Selenium IDE

Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.

You've got:

//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]

Which translates into:

Get me all the elements that have an ID that contains ctl00_btnAircraftMapCell. Out of these elements, get any child elements that have a title that contains Select Seat.

What you actually want is:

//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]

Which translates into:

Get me all the anchor elements that have both: an id that contains ctl00_btnAircraftMapCell and a title that contains Select Seat.

click command in selenium webdriver does not work

Thanks for all the answers everyone! I have found a solution, turns out I didn't provide enough code in my question.

The problem was NOT with the click() function after all, but instead related to cas authentication used with my project. In Selenium IDE my login test executed a "open" command to the following location,

/cas/login?service=https%1F%8FAPPNAME%2FMOREURL%2Fj_spring_cas_security

That worked. I exported the test to Selenium webdriver which naturally preserved that location. The command in Selenium Webdriver was,

driver.get(baseUrl + "/cas/login?service=https%1A%2F%8FAPPNAME%2FMOREURL%2Fj_spring_cas_security");

For reasons I have yet to understand the above failed. When I changed it to,

driver.get(baseUrl + "MOREURL/");

The click command suddenly started to work... I will edit this answer if I can figure out why exactly this is.

Note: I obscured the URLs used above to protect my company's product.

How to press/click the button using Selenium if the button does not have the Id?

For Next button you can use xpath or cssSelector as below:

xpath for Next button: //input[@value='Next']

cssPath for Next button: input[value=Next]

Running Selenium Webdriver with a proxy in Python

try running tor service, add the following function to your code.

def connect_tor(port):

socks.set_default_proxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', port, True)
socket.socket = socks.socksocket

def main():

connect_tor()
driver = webdriver.Firefox()

Selenium IDE - Command to wait for 5 seconds

Before the command clickAndWait add the following code so the script will wait until the specific link to be visible:

   <tr>
        <td>waitForVisible</td>
        <td>link=do something</td>
        <td></td>
    </tr>

The practice of using the wait commands instead of pause is most of the times more efficient and more stable.

Deny access to one specific folder in .htaccess

Just put .htaccess into the folder you want to restrict

## no access to this folder

# Apache 2.4
<IfModule mod_authz_core.c>
    Require all denied
</IfModule>

# Apache 2.2
<IfModule !mod_authz_core.c>
    Order Allow,Deny
    Deny from all
</IfModule>

Source: MantisBT sources.

java.io.FileNotFoundException: /storage/emulated/0/New file.txt: open failed: EACCES (Permission denied)

I suspect you are running Android 6.0 Marshmallow (API 23) or later. If this is the case, you must implement runtime permissions before you try to read/write external storage.

Can I force a UITableView to hide the separator between empty cells?

Swift Version

The easiest method is to set the tableFooterView property:

override func viewDidLoad() {
    super.viewDidLoad()
    // This will remove extra separators from tableview
    self.tableView.tableFooterView = UIView(frame: CGRectZero)
}

How is the java memory pool divided?

The new keyword allocates memory on the Java heap. The heap is the main pool of memory, accessible to the whole of the application. If there is not enough memory available to allocate for that object, the JVM attempts to reclaim some memory from the heap with a garbage collection. If it still cannot obtain enough memory, an OutOfMemoryError is thrown, and the JVM exits.

The heap is split into several different sections, called generations. As objects survive more garbage collections, they are promoted into different generations. The older generations are not garbage collected as often. Because these objects have already proven to be longer lived, they are less likely to be garbage collected.

When objects are first constructed, they are allocated in the Eden Space. If they survive a garbage collection, they are promoted to Survivor Space, and should they live long enough there, they are allocated to the Tenured Generation. This generation is garbage collected much less frequently.

There is also a fourth generation, called the Permanent Generation, or PermGen. The objects that reside here are not eligible to be garbage collected, and usually contain an immutable state necessary for the JVM to run, such as class definitions and the String constant pool. Note that the PermGen space is planned to be removed from Java 8, and will be replaced with a new space called Metaspace, which will be held in native memory. reference:http://www.programcreek.com/2013/04/jvm-run-time-data-areas/

Diagram of Java memory for several threads Diagram of Java memory distribution

How to include file in a bash shell script

Yes, use source or the short form which is just .:

. other_script.sh

Where to put the gradle.properties file

Actually there are 3 places where gradle.properties can be placed:

  1. Under gradle user home directory defined by the GRADLE_USER_HOME environment variable, which if not set defaults to USER_HOME/.gradle
  2. The sub-project directory (myProject2 in your case)
  3. The root project directory (under myProject)

Gradle looks for gradle.properties in all these places while giving precedence to properties definition based on the order above. So for example, for a property defined in gradle user home directory (#1) and the sub-project (#2) its value will be taken from gradle user home directory (#1).

You can find more details about it in gradle documentation here.

How to move or copy files listed by 'find' command in unix?

If you're using GNU find,

find . -mtime 1 -exec cp -t ~/test/ {} +

This works as well as piping the output into xargs while avoiding the pitfalls of doing so (it handles embedded spaces and newlines without having to use find ... -print0 | xargs -0 ...).

Keep CMD open after BAT file executes

start cmd /k did the magic for me. I actually used it for preparing cordova phonegap app it runs the command, shows the result and waits for the user to close it. Below is the simple example

start cmd /k echo Hello, World!

What I did use in my case

start cmd /k cordova prepare

Update

You could even have a title for this by using

start "My Title" echo Hello, World!

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

For whatever reason, TWO of my solutions have web projects that spontaneously uninstalled asp.net MVC somehow. I installed it from Nuget and now they both work again. This happened after a recent batch of windows updates that included .net framework updates for the version I was using (4.5.1).

Edit: From the .Net Web Development and Tools Blog:

Microsoft Asp.Net MVC Security Update MS14-059 broke my build!

Numpy first occurrence of value greater than existing value

This is a little faster (and looks nicer)

np.argmax(aa>5)

Since argmax will stop at the first True ("In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned.") and doesn't save another list.

In [2]: N = 10000

In [3]: aa = np.arange(-N,N)

In [4]: timeit np.argmax(aa>N/2)
100000 loops, best of 3: 52.3 us per loop

In [5]: timeit np.where(aa>N/2)[0][0]
10000 loops, best of 3: 141 us per loop

In [6]: timeit np.nonzero(aa>N/2)[0][0]
10000 loops, best of 3: 142 us per loop

mysqli::mysqli(): (HY000/2002): Can't connect to local MySQL server through socket 'MySQL' (2)

Please check the following file

%SystemRoot%\system32\drivers\etc\host

The line which bind the host name with ip is probably missing a line which bind them togather

127.0.0.1  localhost

If the given line is missing. Add the line in the file


Could you also check your MySQL database's user table and tell us the host column value for the user which you are using. You should have user privilege for both the host "127.0.0.1" and "localhost" and use % as it is a wild char for generic host name.

Force Java timezone as GMT/UTC

Hope below code will help you.

    DateFormat formatDate = new SimpleDateFormat(ISO_DATE_TIME_PATTERN);
    formatDate.setTimeZone(TimeZone.getTimeZone("UTC")); 
    formatDate.parse(dateString);

window.onunload is not working properly in Chrome browser. Can any one help me?

There are some actions which are not working in chrome, inside of the unload event. Alert or confirm boxes are such things.

But what is possible (AFAIK):

  1. Open popups (with window.open) - but this will just work, if the popup blocker is disabled for your site
  2. Return a simple string (in beforeunload event), which triggers a confirm box, which asks the user if s/he want to leave the page.

Example for #2:

$(window).on('beforeunload', function() {
    return 'Your own message goes here...';
});

Demo: http://jsfiddle.net/PQz5k/

How to round the corners of a button

You can achieve by this RunTime Attributes

enter image description here

we can make custom button.just see screenshot attached.

kindly pay attention :

in runtime attributes to change color of border follow this instruction

  1. create category class of CALayer

  2. in h file

    @property(nonatomic, assign) UIColor* borderIBColor;
    
  3. in m file:

    -(void)setBorderIBColor:(UIColor*)color {
        self.borderColor = color.CGColor;
    }
    
    -(UIColor*)borderIBColor {
        return [UIColor colorWithCGColor:self.borderColor];
    }
    

now onwards to set border color check screenshot

updated answer

thanks

Command to collapse all sections of code?

In case of ugrading to Visual Studio 2010, 2012, 2013 or 2015, there's a Visual Studio extension to show current registered keyboard shortcuts, IntelliCommand.

JavaScript Regular Expression Email Validation

You can add a function to String Object

//Add this wherever you like in your javascript code
String.prototype.isEmail = function() {
    return !!this.match(/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/);
}

var user_email = "[email protected]";

if(user_email.isEmail()) {
    //Email is valid !
} else {
    //Email is invalid !
}

Why would anybody use C over C++?

In addition to several other points mentioned already:

Less surprise

that is, it is much easier to see what a piece of code will do do exactly . In C++ you need to approach guru level to be able to know exactly what code the compiler generates (try a combination of templates, multiple inheritance, auto generated constructors, virtual functions and mix in a bit of namespace magic and argument dependent lookup).

In many cases this magic is nice, but for example in real-time systems it can really screw up your day.

Excel tab sheet names vs. Visual Basic sheet names

There are (at least) two different ways to get to theWorksheet object

  • via the Sheets or Worksheets collections as referenced by DanM
  • by unqualified object names

When a new workbook with three worksheets is created there will exist four objects which you can access via unqualified names: ThisWorkbook; Sheet1; Sheet2; Sheet3. This lets you write things like this:

Sheet1.Range("A1").Value = "foo"

Although this may seem like a useful shortcut, the problem comes when the worksheets are renamed. The unqualified object name remains as Sheet1 even if the worksheet is renamed to something totally different.

There is some logic to this because:

  • worksheet names don't conform to the same rules as variable names
  • you might accidentally mask an existing variable

For example (tested in Excel 2003), create a new Workbook with three worksheets. Create two modules. In one module declare this:

Public Sheet4 As Integer

In the other module put:

Sub main()

Sheet4 = 4

MsgBox Sheet4

End Sub

Run this and the message box should appear correctly.

Now add a fourth worksheet to the workbook which will create a Sheet4 object. Try running main again and this time you will get an "Object does not support this property or method" error

How to find and replace all occurrences of a string recursively in a directory tree?

Try this:

find /home/user/ -type f | xargs sed -i  's/a\.example\.com/b.example.com/g'

In case you want to ignore dot directories

find . \( ! -regex '.*/\..*' \) -type f | xargs sed -i 's/a\.example\.com/b.example.com/g'

Edit: escaped dots in search expression

Count number of iterations in a foreach loop

You don't need to do it in the foreach.

Just use count($Contents).

In which conda environment is Jupyter executing?

Question 1: Find the current notebook's conda environment

Open the notebook in Jupyter Notebooks and look in the upper right corner of the screen.

It should say, for example, "Python [env_name]" if the language is Python and it's using an environment called env_name.

jupyter notebook with name of environment


Question 2: Start Jupyter Notebook from within a different conda environment

Activate a conda environment in your terminal using source activate <environment name> before you run jupyter notebook. This sets the default environment for Jupyter Notebooks. Otherwise, the [Root] environment is the default.

jupyter notebooks home screen, conda tab, create new environment

You can also create new environments from within Jupyter Notebook (home screen, Conda tab, and then click the plus sign).

And you can create a notebook in any environment you want. Select the "Files" tab on the home screen and click the "New" dropdown menu, and in that menu select a Python environment from the list.

jupyter notebooks home screen, files tab, create new notebook

Free Barcode API for .NET

There is a "3 of 9" control on CodeProject: Barcode .NET Control

Getting the length of two-dimensional array

which 3?

You've created a multi-dimentional array. nir is an array of int arrays; you've got two arrays of length three.

System.out.println(nir[0].length); 

would give you the length of your first array.

Also worth noting is that you don't have to initialize a multi-dimensional array as you did, which means all the arrays don't have to be the same length (or exist at all).

int nir[][] = new int[5][];
nir[0] = new int[5];
nir[1] = new int[3];
System.out.println(nir[0].length); // 5
System.out.println(nir[1].length); // 3
System.out.println(nir[2].length); // Null pointer exception

Update a column value, replacing part of a string

UPDATE urls
SET url = REPLACE(url, 'domain1.com/images/', 'domain2.com/otherfolder/')

How to get last month/year in java?

java.time

Using java.time framework built into Java 8:

import java.time.LocalDate;

LocalDate now = LocalDate.now(); // 2015-11-24
LocalDate earlier = now.minusMonths(1); // 2015-10-24

earlier.getMonth(); // java.time.Month = OCTOBER
earlier.getMonth.getValue(); // 10
earlier.getYear(); // 2015

Python/Json:Expecting property name enclosed in double quotes

Quite simply, that string is not valid JSON. As the error says, JSON documents need to use double quotes.

You need to fix the source of the data.

Twitter bootstrap scrollable table

I had the same issue and used a combination of the above solutions (and added a twist of my own). Note that I had to specify column widths to keep them consistent between header and body.

In my solution, the header and footer stay fixed while the body scrolls.

<div class="table-responsive">
    <table class="table table-striped table-hover table-condensed">
        <thead>
            <tr>
                <th width="25%">First Name</th>
                <th width="13%">Last Name</th>
                <th width="25%" class="text-center">Address</th>
                <th width="25%" class="text-center">City</th>
                <th width="4%" class="text-center">State</th>
                <th width="8%" class="text-center">Zip</th>
            </tr>
        </thead>
    </table>
    <div class="bodycontainer scrollable">
        <table class="table table-hover table-striped table-condensed table-scrollable">
            <tbody>
                <!-- add rows here, specifying same widths as in header, at least on one row -->
            </tbody>
        </table>
    </div>
    <table class="table table-hover table-striped table-condensed">
        <tfoot>
            <!-- add your footer here... -->
        </tfoot>
    </table>
</div>

And then just applied the following CSS:

.bodycontainer { max-height: 450px; width: 100%; margin: 0; overflow-y: auto; }
.table-scrollable { margin: 0; padding: 0; }

I hope this helps someone else.

Excel VBA to Export Selected Sheets to PDF

this is what i came up with as i was having issues with @asp8811 answer(maybe my own difficulties)

' this will do the put the first 2 sheets in a pdf ' Note each ws should be controlled with page breaks for printing which is a bit fiddly ' this will explicitly put the pdf in the current dir

Sub luxation2()
    Dim Filename As String
    Filename = "temp201"



Dim shtAry()
ReDim shtAry(1) ' this is an array of length 2
For i = 1 To 2
shtAry(i - 1) = Sheets(i).Name
Debug.Print Sheets(i).Name
Next i
Sheets(shtAry).Select
Debug.Print ThisWorkbook.Path & "\"


    ActiveSheet.ExportAsFixedFormat xlTypePDF, ThisWorkbook.Path & "/" & Filename & ".pdf", , , False

End Sub

Propagation Delay vs Transmission delay

Because they're measuring different things.

Propagation delay is how long it takes one bit to travel from one end of the "wire" to the other (it's proportional to the length of the wire, crudely).

Transmission delay is how long it takes to get all the bits into the wire in the first place (it's packet_length/data_rate).

How can I bold the fonts of a specific row or cell in an Excel worksheet with C#?

this works for me, so try it :

Microsoft.Office.Interop.Excel.Range rng =(Microsoft.Office.Interop.Excel.Range)XcelApp.Cells[1, i];
rng.Font.Bold = true; 
rng.Interior.Color =System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
rng.BorderAround(); 

Copying a rsa public key to clipboard

cat .ssh/id_rsa.pub | bcopy

This works for me.

Convert XmlDocument to String

If you are using Windows.Data.Xml.Dom.XmlDocument version of XmlDocument (used in UWP apps for example), you can use yourXmlDocument.GetXml() to get the XML as a string.

How do I turn off PHP Notices?

I found this trick out recently. Whack an @ at the start of a line that may produce an warning/error.

As if by magic, they dissapear.

Delete terminal history in Linux

If you use bash, then the terminal history is saved in a file called .bash_history. Delete it, and history will be gone.

However, for MySQL the better approach is not to enter the password in the command line. If you just specify the -p option, without a value, then you will be prompted for the password and it won't be logged.

Another option, if you don't want to enter your password every time, is to store it in a my.cnf file. Create a file named ~/.my.cnf with something like:

[client]
user = <username>
password = <password>

Make sure to change the file permissions so that only you can read the file.

Of course, this way your password is still saved in a plaintext file in your home directory, just like it was previously saved in .bash_history.

Can you change a path without reloading the controller in AngularJS?

Since about version 1.2, you can use $location.replace():

$location.path('/items');
$location.replace();

How can I check the extension of a file?

import os
source = ['test_sound.flac','ts.mp3']

for files in source:
   fileName,fileExtension = os.path.splitext(files)
   print fileExtension   # Print File Extensions
   print fileName   # It print file name

PostgreSQL how to see which queries have run

While using Django with postgres 10.6, logging was enabled by default, and I was able to simply do:

tail -f /var/log/postgresql/*

Ubuntu 18.04, django 2+, python3+

How to test the type of a thrown exception in Jest

From my (albeit limited) exposure to Jest, I have found that expect().toThrow() is suitable if you want to only test an error is thrown of a specific type:

expect(() => functionUnderTest()).toThrow(TypeError);

Or an error is thrown with a specific message:

expect(() => functionUnderTest()).toThrow('Something bad happened!');

If you try to do both, you will get a false positive. For example, if your code throws RangeError('Something bad happened!'), this test will pass:

expect(() => functionUnderTest()).toThrow(new TypeError('Something bad happened!'));

The answer by bodolsog which suggests using a try/catch is close, but rather than expecting true to be false to ensure the expect assertions in the catch are hit, you can instead use expect.assertions(2) at the start of your test where 2 is the number of expected assertions. I feel this more accurately describes the intention of the test.

A full example of testing the type and message of an error:

describe('functionUnderTest', () => {
    it('should throw a specific type of error.', () => {
        expect.assertions(2);

        try {
            functionUnderTest();
        } catch (error) {
            expect(error).toBeInstanceOf(TypeError);
            expect(error).toHaveProperty('message', 'Something bad happened!');
        }
    });
});

If functionUnderTest() does not throw an error, the assertions will be be hit, but the expect.assertions(2) will fail and the test will fail.

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

I solved my problem with the change of the parent Spring Boot Dependency.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.0.RELEASE</version>
</parent>

to

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.6.RELEASE</version>
</parent>

For more Information, take a look at the release notes: Spring Boot 2.1.0 Release Notes

Convert integer to string Jinja

The OP needed to cast as string outside the {% set ... %}. But if that not your case you can do:

{% set curYear = 2013 | string() %}

Note that you need the parenthesis on that jinja filter.

If you're concatenating 2 variables, you can also use the ~ custom operator.

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `songs` where `id` = 5 limit 1)

$song = DB::table('songs')->find($id);

here you use method find($id)

for Laravel, if you use this method, you should have column named 'id' and set it as primary key, so then you'll be able to use method find()

otherwise use where('SongID', $id) instead of find($id)

How to set the value for Radio Buttons When edit?

<td><input type="radio" name="gender" value="Male" id="male" <? if($gender=='Male')
{?> checked="" <? }?>/>Male
<input type="radio" name="gender" value="Female" id="female" <? if($gender=='Female') {?> checked="" <?}?>/>Female<br/> </td>

What to do on TransactionTooLargeException

This one line of code in writeToParcel(Parcel dest, int flags) method helped me to get rid of TransactionTooLargeException.

dest=Parcel.obtain(); 

After this code only i am writing all data to the parcel object i.e dest.writeInt() etc.

How to do a less than or equal to filter in Django queryset?

Less than or equal:

User.objects.filter(userprofile__level__lte=0)

Greater than or equal:

User.objects.filter(userprofile__level__gte=0)

Likewise, lt for less than and gt for greater than. You can find them all in the documentation.

Python speed testing - Time Difference - milliseconds

time.time() / datetime is good for quick use, but is not always 100% precise. For that reason, I like to use one of the std lib profilers (especially hotshot) to find out what's what.

concatenate char array in C

You can concatenate strings by using the sprintf() function. In your case, for example:

char file[80];
sprintf(file,"%s%s",name,extension);

And you'll end having the concatenated string in "file".

java: HashMap<String, int> not working

You can use reference type in generic arguments, not primitive type. So here you should use

Map<String, Integer> myMap = new HashMap<String, Integer>();

and store value as

myMap.put("abc", 5);

https with WCF error: "Could not find base address that matches scheme https"

I think you are trying to configure your service in a similar way to the following config. There is more information here: Specify a Service with Two Endpoints Using Different Binding Values. Also, other than for development, it's probably not a good idea to have both HTTP & HTTPS endpoints to the same service. It kinda defeats the purpose of HTTPS. Hope this helps!

<service type="HelloWorld, IndigoConfig, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null">
    <endpoint
        address="http://computer:8080/Hello"
        contract="HelloWorld, IndigoConfig, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
        binding="basicHttpBinding"
        bindingConfiguration="shortTimeout"
    </endpoint>
    <endpoint
        address="http://computer:8080/Hello"
        contract="HelloWorld, IndigoConfig, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
        binding="basicHttpBinding"
        bindingConfiguration="Secure"
     </endpoint>
</service>
<bindings>
    <basicHttpBinding 
        name="shortTimeout"
        timeout="00:00:00:01" 
     />
     <basicHttpBinding 
        name="Secure">
        <Security mode="Transport" />
     </basicHttpBinding>
</bindings>

NodeJS: How to get the server's port?

req.headers.host.split(':')[1]

How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?

Here is MySQL version which prints only one entry where there are duplicates MAX(datetime) in a group.

You could test here http://www.sqlfiddle.com/#!2/0a4ae/1

Sample Data

mysql> SELECT * from topten;
+------+------+---------------------+--------+----------+
| id   | home | datetime            | player | resource |
+------+------+---------------------+--------+----------+
|    1 |   10 | 2009-04-03 00:00:00 | john   |      399 |
|    2 |   11 | 2009-04-03 00:00:00 | juliet |      244 |
|    3 |   10 | 2009-03-03 00:00:00 | john   |      300 |
|    4 |   11 | 2009-03-03 00:00:00 | juliet |      200 |
|    5 |   12 | 2009-04-03 00:00:00 | borat  |      555 |
|    6 |   12 | 2009-03-03 00:00:00 | borat  |      500 |
|    7 |   13 | 2008-12-24 00:00:00 | borat  |      600 |
|    8 |   13 | 2009-01-01 00:00:00 | borat  |      700 |
|    9 |   10 | 2009-04-03 00:00:00 | borat  |      700 |
|   10 |   11 | 2009-04-03 00:00:00 | borat  |      700 |
|   12 |   12 | 2009-04-03 00:00:00 | borat  |      700 |
+------+------+---------------------+--------+----------+

MySQL Version with User variable

SELECT *
FROM (
    SELECT ord.*,
        IF (@prev_home = ord.home, 0, 1) AS is_first_appear,
        @prev_home := ord.home
    FROM (
        SELECT t1.id, t1.home, t1.player, t1.resource
        FROM topten t1
        INNER JOIN (
            SELECT home, MAX(datetime) AS mx_dt
            FROM topten
            GROUP BY home
          ) x ON t1.home = x.home AND t1.datetime = x.mx_dt
        ORDER BY home
    ) ord, (SELECT @prev_home := 0, @seq := 0) init
) y
WHERE is_first_appear = 1;
+------+------+--------+----------+-----------------+------------------------+
| id   | home | player | resource | is_first_appear | @prev_home := ord.home |
+------+------+--------+----------+-----------------+------------------------+
|    9 |   10 | borat  |      700 |               1 |                     10 |
|   10 |   11 | borat  |      700 |               1 |                     11 |
|   12 |   12 | borat  |      700 |               1 |                     12 |
|    8 |   13 | borat  |      700 |               1 |                     13 |
+------+------+--------+----------+-----------------+------------------------+
4 rows in set (0.00 sec)

Accepted Answers' outout

SELECT tt.*
FROM topten tt
INNER JOIN
    (
    SELECT home, MAX(datetime) AS MaxDateTime
    FROM topten
    GROUP BY home
) groupedtt ON tt.home = groupedtt.home AND tt.datetime = groupedtt.MaxDateTime
+------+------+---------------------+--------+----------+
| id   | home | datetime            | player | resource |
+------+------+---------------------+--------+----------+
|    1 |   10 | 2009-04-03 00:00:00 | john   |      399 |
|    2 |   11 | 2009-04-03 00:00:00 | juliet |      244 |
|    5 |   12 | 2009-04-03 00:00:00 | borat  |      555 |
|    8 |   13 | 2009-01-01 00:00:00 | borat  |      700 |
|    9 |   10 | 2009-04-03 00:00:00 | borat  |      700 |
|   10 |   11 | 2009-04-03 00:00:00 | borat  |      700 |
|   12 |   12 | 2009-04-03 00:00:00 | borat  |      700 |
+------+------+---------------------+--------+----------+
7 rows in set (0.00 sec)

How to convert a Drawable to a Bitmap?

Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon);

This will not work every time for example if your drawable is layer list drawable then it gives a null response, so as an alternative you need to draw your drawable into canvas then save as bitmap, please refer below a cup of code.

public void drawableToBitMap(Context context, int drawable, int widthPixels, int heightPixels) {
    try {
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/", "drawable.png");
        FileOutputStream fOut = new FileOutputStream(file);
        Drawable drw = ResourcesCompat.getDrawable(context.getResources(), drawable, null);
        if (drw != null) {
            convertToBitmap(drw, widthPixels, heightPixels).compress(Bitmap.CompressFormat.PNG, 100, fOut);
        }
        fOut.flush();
        fOut.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private Bitmap convertToBitmap(Drawable drawable, int widthPixels, int heightPixels) {
    Bitmap bitmap = Bitmap.createBitmap(widthPixels, heightPixels, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, widthPixels, heightPixels);
    drawable.draw(canvas);
    return bitmap;
}

above code save you're drawable as drawable.png in the download directory

Adding an HTTP Header to the request in a servlet filter

as https://stackoverflow.com/users/89391/miku pointed out this would be a complete ServletFilter example that uses the code that also works for Jersey to add the remote_addr header.

package com.bitplan.smartCRM.web;

import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * 
 * @author wf
 * 
 */
public class RemoteAddrFilter implements Filter {

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HeaderMapRequestWrapper requestWrapper = new HeaderMapRequestWrapper(req);
        String remote_addr = request.getRemoteAddr();
        requestWrapper.addHeader("remote_addr", remote_addr);
        chain.doFilter(requestWrapper, response); // Goes to default servlet.
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    // https://stackoverflow.com/questions/2811769/adding-an-http-header-to-the-request-in-a-servlet-filter
    // http://sandeepmore.com/blog/2010/06/12/modifying-http-headers-using-java/
    // http://bijubnair.blogspot.de/2008/12/adding-header-information-to-existing.html
    /**
     * allow adding additional header entries to a request
     * 
     * @author wf
     * 
     */
    public class HeaderMapRequestWrapper extends HttpServletRequestWrapper {
        /**
         * construct a wrapper for this request
         * 
         * @param request
         */
        public HeaderMapRequestWrapper(HttpServletRequest request) {
            super(request);
        }

        private Map<String, String> headerMap = new HashMap<String, String>();

        /**
         * add a header with given name and value
         * 
         * @param name
         * @param value
         */
        public void addHeader(String name, String value) {
            headerMap.put(name, value);
        }

        @Override
        public String getHeader(String name) {
            String headerValue = super.getHeader(name);
            if (headerMap.containsKey(name)) {
                headerValue = headerMap.get(name);
            }
            return headerValue;
        }

        /**
         * get the Header names
         */
        @Override
        public Enumeration<String> getHeaderNames() {
            List<String> names = Collections.list(super.getHeaderNames());
            for (String name : headerMap.keySet()) {
                names.add(name);
            }
            return Collections.enumeration(names);
        }

        @Override
        public Enumeration<String> getHeaders(String name) {
            List<String> values = Collections.list(super.getHeaders(name));
            if (headerMap.containsKey(name)) {
                values.add(headerMap.get(name));
            }
            return Collections.enumeration(values);
        }

    }

}

web.xml snippet:

<!--  first filter adds remote addr header -->
<filter>
    <filter-name>remoteAddrfilter</filter-name>
    <filter-class>com.bitplan.smartCRM.web.RemoteAddrFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>remoteAddrfilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Multiple file extensions in OpenFileDialog

Based on First answer here is the complete image selection options:

Filter = @"|All Image Files|*.BMP;*.bmp;*.JPG;*.JPEG*.jpg;*.jpeg;*.PNG;*.png;*.GIF;*.gif;*.tif;*.tiff;*.ico;*.ICO
           |PNG|*.PNG;*.png
           |JPEG|*.JPG;*.JPEG*.jpg;*.jpeg
           |Bitmap(.BMP,.bmp)|*.BMP;*.bmp                                    
           |GIF|*.GIF;*.gif
           |TIF|*.tif;*.tiff
           |ICO|*.ico;*.ICO";

How does java do modulus calculations with negative numbers?

According to section 15.17.3 of the JLS, "The remainder operation for operands that are integers after binary numeric promotion produces a result value such that (a/b)*b+(a%b) is equal to a. This identity holds even in the special case that the dividend is the negative integer of largest possible magnitude for its type and the divisor is -1 (the remainder is 0)."

Hope that helps.

Why does checking a variable against multiple values with `OR` only check the first value?

The or operator returns the first operand if it is true, otherwise the second operand. So in your case your test is equivalent to if name == "Jesse".

The correct application of or would be:

if (name == "Jesse") or (name == "jesse"):

How to convert an address into a Google Maps Link (NOT MAP)

How about this?

https://maps.google.com/?q=1200 Pennsylvania Ave SE, Washington, District of Columbia, 20003

https://maps.google.com/?q=term

If you have lat-long then use below URL

https://maps.google.com/?ll=latitude,longitude

Example: maps.google.com/?ll=38.882147,-76.99017

UPDATE

As of year 2017, Google now has an official way to create cross-platform Google Maps URLs:

https://developers.google.com/maps/documentation/urls/guide

You can use links like

https://www.google.com/maps/search/?api=1&query=1200%20Pennsylvania%20Ave%20SE%2C%20Washington%2C%20District%20of%20Columbia%2C%2020003 

Is std::vector copying the objects with a push_back?

std::vector always makes a copy of whatever is being stored in the vector.

If you are keeping a vector of pointers, then it will make a copy of the pointer, but not the instance being to which the pointer is pointing. If you are dealing with large objects, you can (and probably should) always use a vector of pointers. Often, using a vector of smart pointers of an appropriate type is good for safety purposes, since handling object lifetime and memory management can be tricky otherwise.

What is code coverage and how do YOU measure it?

In the previous answers Code coverage has been explained well . I am just adding some knowledge related to tools if your are working on iOS and OSX platforms, Xcode provides the facility to test and monitor code coverage.

Reference Links:

https://developer.apple.com/library/archive/documentation/DeveloperTools/Conceptual/testing_with_xcode/chapters/07-code_coverage.html

https://medium.com/zendesk-engineering/code-coverage-and-xcode-6b2fb8756a51

Both are helpful links for learning and exploring code coverage with Xcode.

Cannot connect to repo with TortoiseSVN

Try clearing the settings under "Saved Data" - refer to:

http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-settings.html

This worked for me with Windows 7.

Eric

Bootstrap 3 Navbar Collapse

these are controlled in variables, no need to muck around in source. with bootstrap, try variables first, then overrides. then go back and try variables again ;)

i used bootstrap-sass with rails, but it's the same with the default LESS.

FILE: main.css.scss
-------------------

// control the screen sizes
$screen-xs-min: 300px;
$screen-sm-min: 400px;
$screen-md-min: 800px;
$screen-lg-min: 1200px;

// this tells which screen size to use to start breaking on
// will tell navbar when to collapse
$grid-float-breakpoint: $screen-md-min;

// then import your bootstrap
@import "bootstrap";

that's it! this variables reference page is super handy: https://github.com/twbs/bootstrap/blob/master/less/variables.less

When to create variables (memory management)

In your example number is a primitive, so will be stored as a value.

If you want to use a reference then you should use one of the wrapper types (e.g. Integer)

Configure nginx with multiple locations with different root folders on subdomain

You need to use the alias directive for location /static:

server {

  index index.html;
  server_name test.example.com;

  root /web/test.example.com/www;

  location /static/ {
    alias /web/test.example.com/static/;
  }

}

The nginx wiki explains the difference between root and alias better than I can:

Note that it may look similar to the root directive at first sight, but the document root doesn't change, just the file system path used for the request. The location part of the request is dropped in the request Nginx issues.

Note that root and alias handle trailing slashes differently.

UILabel - auto-size label to fit text?

I created some methods based Daniel's reply above.

-(CGFloat)heightForLabel:(UILabel *)label withText:(NSString *)text
{
    CGSize maximumLabelSize     = CGSizeMake(290, FLT_MAX);

    CGSize expectedLabelSize    = [text sizeWithFont:label.font
                                constrainedToSize:maximumLabelSize
                                    lineBreakMode:label.lineBreakMode];

    return expectedLabelSize.height;
}

-(void)resizeHeightToFitForLabel:(UILabel *)label
{
    CGRect newFrame         = label.frame;
    newFrame.size.height    = [self heightForLabel:label withText:label.text];
    label.frame             = newFrame;
}

-(void)resizeHeightToFitForLabel:(UILabel *)label withText:(NSString *)text
{
    label.text              = text;
    [self resizeHeightToFitForLabel:label];
}

Difference between logger.info and logger.debug

Basically it depends on how your loggers are configured. Typically you'd have debug output written out during development but turned off in production - or possibly have selected debug categories writing out while debugging a particular area.

The point of having different priorities is to allow you to turn up/down the level of detail on a particular component in a reasonably fine-grained way - and only needing to change the logging configuration (rather than code) to see the difference.

How can I truncate a double to only two decimal places in Java?

A quick check is to use the Math.floor method. I created a method to check a double for two or less decimal places below:

public boolean checkTwoDecimalPlaces(double valueToCheck) {

    // Get two decimal value of input valueToCheck 
    double twoDecimalValue = Math.floor(valueToCheck * 100) / 100;

    // Return true if the twoDecimalValue is the same as valueToCheck else return false
    return twoDecimalValue == valueToCheck;
}

npm ERR! network getaddrinfo ENOTFOUND

Instead of setting the proxy usingnpm config set http_proxy=http://address:8080 go to ~/.npmrc and remove the proxy config. This resolved my issue.

jQuery Validation using the class instead of the name value

You can add the rules based on that selector using .rules("add", options), just remove any rules you want class based out of your validate options, and after calling $(".formToValidate").validate({... });, do this:

$(".checkBox").rules("add", { 
  required:true,  
  minlength:3
});

Array to Collection: Optimized code

Based on the reference of java.util.Collections.addAll(Collection<? super String> c, String... elements) its implementation is similar to your first method, it says

Adds all of the specified elements to the specified collection. Elements to be added may be specified individually or as an array. The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this method is likely to run significantly faster under most implementations.

Its implementation in jdk is (jdk7)

public static <T> boolean addAll(Collection<? super T> c, T... elements) {
    boolean result = false;
    for (T element : elements)
        result |= c.add(element);
    return result;
}

So among your samples the better approach must be Collections.addAll(list, array);

Since Java 8, we can use Stream api which may perform better

Eg:-

String[] array = {"item1", "item2", "item3"};

Stream<String> stream = Stream.of(array);

//if the array is extremely large 
stream = stream.parallel();

final List<String> list = stream.collect(Collectors.toList());

If the array is very large we can do it as a batch operation in parallel using parallel stream (stream = stream.parallel()) that will utilize all CPUs to finish the task quickly. If the array length is very small parallel stream will take more time than sequential stream.

Socket.IO handling disconnect event

Create a Map or a Set, and using "on connection" event set to it each connected socket, in reverse "once disconnect" event delete that socket from the Map we created earlier

import * as Server from 'socket.io';

const io = Server();
io.listen(3000);

const connections = new Set();

io.on('connection', function (s) {

  connections.add(s);

  s.once('disconnect', function () {
    connections.delete(s);
  });

});

How do I open an .exe from another C++ .exe?

Provide the full path of the file openfile.exe and remember not to put forward slash / in the path such as c:/users/username/etc.... instead of that use c:\\Users\\username\etc (for windows)

May be this will help you.

Best way to reset an Oracle sequence to the next value in an existing column?

Today, in Oracle 12c or newer, you probably have the column defined as GENERATED ... AS IDENTITY, and Oracle takes care of the sequence itself.

You can use an ALTER TABLE Statement to modify "START WITH" of the identity.

ALTER TABLE tbl MODIFY ("ID" NUMBER(13,0) GENERATED BY DEFAULT ON NULL AS IDENTITY MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 3580 NOT NULL ENABLE);

Temporarily change current working directory in bash to run a command

Something like this should work:

sh -c 'cd /tmp && exec pwd'

Setting timezone to UTC (0) in PHP

List of entire available timezones.

$time_zones = array (
  0 => 'Africa/Abidjan',
  1 => 'Africa/Accra',
  2 => 'Africa/Addis_Ababa',
  3 => 'Africa/Algiers',
  4 => 'Africa/Asmara',
  5 => 'Africa/Asmera',
  6 => 'Africa/Bamako',
  7 => 'Africa/Bangui',
  8 => 'Africa/Banjul',
  9 => 'Africa/Bissau',
  10 => 'Africa/Blantyre',
  11 => 'Africa/Brazzaville',
  12 => 'Africa/Bujumbura',
  13 => 'Africa/Cairo',
  14 => 'Africa/Casablanca',
  15 => 'Africa/Ceuta',
  16 => 'Africa/Conakry',
  17 => 'Africa/Dakar',
  18 => 'Africa/Dar_es_Salaam',
  19 => 'Africa/Djibouti',
  20 => 'Africa/Douala',
  21 => 'Africa/El_Aaiun',
  22 => 'Africa/Freetown',
  23 => 'Africa/Gaborone',
  24 => 'Africa/Harare',
  25 => 'Africa/Johannesburg',
  26 => 'Africa/Juba',
  27 => 'Africa/Kampala',
  28 => 'Africa/Khartoum',
  29 => 'Africa/Kigali',
  30 => 'Africa/Kinshasa',
  31 => 'Africa/Lagos',
  32 => 'Africa/Libreville',
  33 => 'Africa/Lome',
  34 => 'Africa/Luanda',
  35 => 'Africa/Lubumbashi',
  36 => 'Africa/Lusaka',
  37 => 'Africa/Malabo',
  38 => 'Africa/Maputo',
  39 => 'Africa/Maseru',
  40 => 'Africa/Mbabane',
  41 => 'Africa/Mogadishu',
  42 => 'Africa/Monrovia',
  43 => 'Africa/Nairobi',
  44 => 'Africa/Ndjamena',
  45 => 'Africa/Niamey',
  46 => 'Africa/Nouakchott',
  47 => 'Africa/Ouagadougou',
  48 => 'Africa/Porto-Novo',
  49 => 'Africa/Sao_Tome',
  50 => 'Africa/Timbuktu',
  51 => 'Africa/Tripoli',
  52 => 'Africa/Tunis',
  53 => 'Africa/Windhoek',
  54 => 'America/Adak',
  55 => 'America/Anchorage',
  56 => 'America/Anguilla',
  57 => 'America/Antigua',
  58 => 'America/Araguaina',
  59 => 'America/Argentina/Buenos_Aires',
  60 => 'America/Argentina/Catamarca',
  61 => 'America/Argentina/ComodRivadavia',
  62 => 'America/Argentina/Cordoba',
  63 => 'America/Argentina/Jujuy',
  64 => 'America/Argentina/La_Rioja',
  65 => 'America/Argentina/Mendoza',
  66 => 'America/Argentina/Rio_Gallegos',
  67 => 'America/Argentina/Salta',
  68 => 'America/Argentina/San_Juan',
  69 => 'America/Argentina/San_Luis',
  70 => 'America/Argentina/Tucuman',
  71 => 'America/Argentina/Ushuaia',
  72 => 'America/Aruba',
  73 => 'America/Asuncion',
  74 => 'America/Atikokan',
  75 => 'America/Atka',
  76 => 'America/Bahia',
  77 => 'America/Bahia_Banderas',
  78 => 'America/Barbados',
  79 => 'America/Belem',
  80 => 'America/Belize',
  81 => 'America/Blanc-Sablon',
  82 => 'America/Boa_Vista',
  83 => 'America/Bogota',
  84 => 'America/Boise',
  85 => 'America/Buenos_Aires',
  86 => 'America/Cambridge_Bay',
  87 => 'America/Campo_Grande',
  88 => 'America/Cancun',
  89 => 'America/Caracas',
  90 => 'America/Catamarca',
  91 => 'America/Cayenne',
  92 => 'America/Cayman',
  93 => 'America/Chicago',
  94 => 'America/Chihuahua',
  95 => 'America/Coral_Harbour',
  96 => 'America/Cordoba',
  97 => 'America/Costa_Rica',
  98 => 'America/Creston',
  99 => 'America/Cuiaba',
  100 => 'America/Curacao',
  101 => 'America/Danmarkshavn',
  102 => 'America/Dawson',
  103 => 'America/Dawson_Creek',
  104 => 'America/Denver',
  105 => 'America/Detroit',
  106 => 'America/Dominica',
  107 => 'America/Edmonton',
  108 => 'America/Eirunepe',
  109 => 'America/El_Salvador',
  110 => 'America/Ensenada',
  111 => 'America/Fort_Nelson',
  112 => 'America/Fort_Wayne',
  113 => 'America/Fortaleza',
  114 => 'America/Glace_Bay',
  115 => 'America/Godthab',
  116 => 'America/Goose_Bay',
  117 => 'America/Grand_Turk',
  118 => 'America/Grenada',
  119 => 'America/Guadeloupe',
  120 => 'America/Guatemala',
  121 => 'America/Guayaquil',
  122 => 'America/Guyana',
  123 => 'America/Halifax',
  124 => 'America/Havana',
  125 => 'America/Hermosillo',
  126 => 'America/Indiana/Indianapolis',
  127 => 'America/Indiana/Knox',
  128 => 'America/Indiana/Marengo',
  129 => 'America/Indiana/Petersburg',
  130 => 'America/Indiana/Tell_City',
  131 => 'America/Indiana/Vevay',
  132 => 'America/Indiana/Vincennes',
  133 => 'America/Indiana/Winamac',
  134 => 'America/Indianapolis',
  135 => 'America/Inuvik',
  136 => 'America/Iqaluit',
  137 => 'America/Jamaica',
  138 => 'America/Jujuy',
  139 => 'America/Juneau',
  140 => 'America/Kentucky/Louisville',
  141 => 'America/Kentucky/Monticello',
  142 => 'America/Knox_IN',
  143 => 'America/Kralendijk',
  144 => 'America/La_Paz',
  145 => 'America/Lima',
  146 => 'America/Los_Angeles',
  147 => 'America/Louisville',
  148 => 'America/Lower_Princes',
  149 => 'America/Maceio',
  150 => 'America/Managua',
  151 => 'America/Manaus',
  152 => 'America/Marigot',
  153 => 'America/Martinique',
  154 => 'America/Matamoros',
  155 => 'America/Mazatlan',
  156 => 'America/Mendoza',
  157 => 'America/Menominee',
  158 => 'America/Merida',
  159 => 'America/Metlakatla',
  160 => 'America/Mexico_City',
  161 => 'America/Miquelon',
  162 => 'America/Moncton',
  163 => 'America/Monterrey',
  164 => 'America/Montevideo',
  165 => 'America/Montreal',
  166 => 'America/Montserrat',
  167 => 'America/Nassau',
  168 => 'America/New_York',
  169 => 'America/Nipigon',
  170 => 'America/Nome',
  171 => 'America/Noronha',
  172 => 'America/North_Dakota/Beulah',
  173 => 'America/North_Dakota/Center',
  174 => 'America/North_Dakota/New_Salem',
  175 => 'America/Ojinaga',
  176 => 'America/Panama',
  177 => 'America/Pangnirtung',
  178 => 'America/Paramaribo',
  179 => 'America/Phoenix',
  180 => 'America/Port-au-Prince',
  181 => 'America/Port_of_Spain',
  182 => 'America/Porto_Acre',
  183 => 'America/Porto_Velho',
  184 => 'America/Puerto_Rico',
  185 => 'America/Rainy_River',
  186 => 'America/Rankin_Inlet',
  187 => 'America/Recife',
  188 => 'America/Regina',
  189 => 'America/Resolute',
  190 => 'America/Rio_Branco',
  191 => 'America/Rosario',
  192 => 'America/Santa_Isabel',
  193 => 'America/Santarem',
  194 => 'America/Santiago',
  195 => 'America/Santo_Domingo',
  196 => 'America/Sao_Paulo',
  197 => 'America/Scoresbysund',
  198 => 'America/Shiprock',
  199 => 'America/Sitka',
  200 => 'America/St_Barthelemy',
  201 => 'America/St_Johns',
  202 => 'America/St_Kitts',
  203 => 'America/St_Lucia',
  204 => 'America/St_Thomas',
  205 => 'America/St_Vincent',
  206 => 'America/Swift_Current',
  207 => 'America/Tegucigalpa',
  208 => 'America/Thule',
  209 => 'America/Thunder_Bay',
  210 => 'America/Tijuana',
  211 => 'America/Toronto',
  212 => 'America/Tortola',
  213 => 'America/Vancouver',
  214 => 'America/Virgin',
  215 => 'America/Whitehorse',
  216 => 'America/Winnipeg',
  217 => 'America/Yakutat',
  218 => 'America/Yellowknife',
  219 => 'Antarctica/Casey',
  220 => 'Antarctica/Davis',
  221 => 'Antarctica/DumontDUrville',
  222 => 'Antarctica/Macquarie',
  223 => 'Antarctica/Mawson',
  224 => 'Antarctica/McMurdo',
  225 => 'Antarctica/Palmer',
  226 => 'Antarctica/Rothera',
  227 => 'Antarctica/South_Pole',
  228 => 'Antarctica/Syowa',
  229 => 'Antarctica/Troll',
  230 => 'Antarctica/Vostok',
  231 => 'Arctic/Longyearbyen',
  232 => 'Asia/Aden',
  233 => 'Asia/Almaty',
  234 => 'Asia/Amman',
  235 => 'Asia/Anadyr',
  236 => 'Asia/Aqtau',
  237 => 'Asia/Aqtobe',
  238 => 'Asia/Ashgabat',
  239 => 'Asia/Ashkhabad',
  240 => 'Asia/Baghdad',
  241 => 'Asia/Bahrain',
  242 => 'Asia/Baku',
  243 => 'Asia/Bangkok',
  244 => 'Asia/Beirut',
  245 => 'Asia/Bishkek',
  246 => 'Asia/Brunei',
  247 => 'Asia/Calcutta',
  248 => 'Asia/Chita',
  249 => 'Asia/Choibalsan',
  250 => 'Asia/Chongqing',
  251 => 'Asia/Chungking',
  252 => 'Asia/Colombo',
  253 => 'Asia/Dacca',
  254 => 'Asia/Damascus',
  255 => 'Asia/Dhaka',
  256 => 'Asia/Dili',
  257 => 'Asia/Dubai',
  258 => 'Asia/Dushanbe',
  259 => 'Asia/Gaza',
  260 => 'Asia/Harbin',
  261 => 'Asia/Hebron',
  262 => 'Asia/Ho_Chi_Minh',
  263 => 'Asia/Hong_Kong',
  264 => 'Asia/Hovd',
  265 => 'Asia/Irkutsk',
  266 => 'Asia/Istanbul',
  267 => 'Asia/Jakarta',
  268 => 'Asia/Jayapura',
  269 => 'Asia/Jerusalem',
  270 => 'Asia/Kabul',
  271 => 'Asia/Kamchatka',
  272 => 'Asia/Karachi',
  273 => 'Asia/Kashgar',
  274 => 'Asia/Kathmandu',
  275 => 'Asia/Katmandu',
  276 => 'Asia/Khandyga',
  277 => 'Asia/Kolkata',
  278 => 'Asia/Krasnoyarsk',
  279 => 'Asia/Kuala_Lumpur',
  280 => 'Asia/Kuching',
  281 => 'Asia/Kuwait',
  282 => 'Asia/Macao',
  283 => 'Asia/Macau',
  284 => 'Asia/Magadan',
  285 => 'Asia/Makassar',
  286 => 'Asia/Manila',
  287 => 'Asia/Muscat',
  288 => 'Asia/Nicosia',
  289 => 'Asia/Novokuznetsk',
  290 => 'Asia/Novosibirsk',
  291 => 'Asia/Omsk',
  292 => 'Asia/Oral',
  293 => 'Asia/Phnom_Penh',
  294 => 'Asia/Pontianak',
  295 => 'Asia/Pyongyang',
  296 => 'Asia/Qatar',
  297 => 'Asia/Qyzylorda',
  298 => 'Asia/Rangoon',
  299 => 'Asia/Riyadh',
  300 => 'Asia/Saigon',
  301 => 'Asia/Sakhalin',
  302 => 'Asia/Samarkand',
  303 => 'Asia/Seoul',
  304 => 'Asia/Shanghai',
  305 => 'Asia/Singapore',
  306 => 'Asia/Srednekolymsk',
  307 => 'Asia/Taipei',
  308 => 'Asia/Tashkent',
  309 => 'Asia/Tbilisi',
  310 => 'Asia/Tehran',
  311 => 'Asia/Tel_Aviv',
  312 => 'Asia/Thimbu',
  313 => 'Asia/Thimphu',
  314 => 'Asia/Tokyo',
  315 => 'Asia/Ujung_Pandang',
  316 => 'Asia/Ulaanbaatar',
  317 => 'Asia/Ulan_Bator',
  318 => 'Asia/Urumqi',
  319 => 'Asia/Ust-Nera',
  320 => 'Asia/Vientiane',
  321 => 'Asia/Vladivostok',
  322 => 'Asia/Yakutsk',
  323 => 'Asia/Yekaterinburg',
  324 => 'Asia/Yerevan',
  325 => 'Atlantic/Azores',
  326 => 'Atlantic/Bermuda',
  327 => 'Atlantic/Canary',
  328 => 'Atlantic/Cape_Verde',
  329 => 'Atlantic/Faeroe',
  330 => 'Atlantic/Faroe',
  331 => 'Atlantic/Jan_Mayen',
  332 => 'Atlantic/Madeira',
  333 => 'Atlantic/Reykjavik',
  334 => 'Atlantic/South_Georgia',
  335 => 'Atlantic/St_Helena',
  336 => 'Atlantic/Stanley',
  337 => 'Australia/ACT',
  338 => 'Australia/Adelaide',
  339 => 'Australia/Brisbane',
  340 => 'Australia/Broken_Hill',
  341 => 'Australia/Canberra',
  342 => 'Australia/Currie',
  343 => 'Australia/Darwin',
  344 => 'Australia/Eucla',
  345 => 'Australia/Hobart',
  346 => 'Australia/LHI',
  347 => 'Australia/Lindeman',
  348 => 'Australia/Lord_Howe',
  349 => 'Australia/Melbourne',
  350 => 'Australia/North',
  351 => 'Australia/NSW',
  352 => 'Australia/Perth',
  353 => 'Australia/Queensland',
  354 => 'Australia/South',
  355 => 'Australia/Sydney',
  356 => 'Australia/Tasmania',
  357 => 'Australia/Victoria',
  358 => 'Australia/West',
  359 => 'Australia/Yancowinna',
  360 => 'Europe/Amsterdam',
  361 => 'Europe/Andorra',
  362 => 'Europe/Athens',
  363 => 'Europe/Belfast',
  364 => 'Europe/Belgrade',
  365 => 'Europe/Berlin',
  366 => 'Europe/Bratislava',
  367 => 'Europe/Brussels',
  368 => 'Europe/Bucharest',
  369 => 'Europe/Budapest',
  370 => 'Europe/Busingen',
  371 => 'Europe/Chisinau',
  372 => 'Europe/Copenhagen',
  373 => 'Europe/Dublin',
  374 => 'Europe/Gibraltar',
  375 => 'Europe/Guernsey',
  376 => 'Europe/Helsinki',
  377 => 'Europe/Isle_of_Man',
  378 => 'Europe/Istanbul',
  379 => 'Europe/Jersey',
  380 => 'Europe/Kaliningrad',
  381 => 'Europe/Kiev',
  382 => 'Europe/Lisbon',
  383 => 'Europe/Ljubljana',
  384 => 'Europe/London',
  385 => 'Europe/Luxembourg',
  386 => 'Europe/Madrid',
  387 => 'Europe/Malta',
  388 => 'Europe/Mariehamn',
  389 => 'Europe/Minsk',
  390 => 'Europe/Monaco',
  391 => 'Europe/Moscow',
  392 => 'Europe/Nicosia',
  393 => 'Europe/Oslo',
  394 => 'Europe/Paris',
  395 => 'Europe/Podgorica',
  396 => 'Europe/Prague',
  397 => 'Europe/Riga',
  398 => 'Europe/Rome',
  399 => 'Europe/Samara',
  400 => 'Europe/San_Marino',
  401 => 'Europe/Sarajevo',
  402 => 'Europe/Simferopol',
  403 => 'Europe/Skopje',
  404 => 'Europe/Sofia',
  405 => 'Europe/Stockholm',
  406 => 'Europe/Tallinn',
  407 => 'Europe/Tirane',
  408 => 'Europe/Tiraspol',
  409 => 'Europe/Uzhgorod',
  410 => 'Europe/Vaduz',
  411 => 'Europe/Vatican',
  412 => 'Europe/Vienna',
  413 => 'Europe/Vilnius',
  414 => 'Europe/Volgograd',
  415 => 'Europe/Warsaw',
  416 => 'Europe/Zagreb',
  417 => 'Europe/Zaporozhye',
  418 => 'Europe/Zurich',
  419 => 'Indian/Antananarivo',
  420 => 'Indian/Chagos',
  421 => 'Indian/Christmas',
  422 => 'Indian/Cocos',
  423 => 'Indian/Comoro',
  424 => 'Indian/Kerguelen',
  425 => 'Indian/Mahe',
  426 => 'Indian/Maldives',
  427 => 'Indian/Mauritius',
  428 => 'Indian/Mayotte',
  429 => 'Indian/Reunion',
  430 => 'Pacific/Apia',
  431 => 'Pacific/Auckland',
  432 => 'Pacific/Bougainville',
  433 => 'Pacific/Chatham',
  434 => 'Pacific/Chuuk',
  435 => 'Pacific/Easter',
  436 => 'Pacific/Efate',
  437 => 'Pacific/Enderbury',
  438 => 'Pacific/Fakaofo',
  439 => 'Pacific/Fiji',
  440 => 'Pacific/Funafuti',
  441 => 'Pacific/Galapagos',
  442 => 'Pacific/Gambier',
  443 => 'Pacific/Guadalcanal',
  444 => 'Pacific/Guam',
  445 => 'Pacific/Honolulu',
  446 => 'Pacific/Johnston',
  447 => 'Pacific/Kiritimati',
  448 => 'Pacific/Kosrae',
  449 => 'Pacific/Kwajalein',
  450 => 'Pacific/Majuro',
  451 => 'Pacific/Marquesas',
  452 => 'Pacific/Midway',
  453 => 'Pacific/Nauru',
  454 => 'Pacific/Niue',
  455 => 'Pacific/Norfolk',
  456 => 'Pacific/Noumea',
  457 => 'Pacific/Pago_Pago',
  458 => 'Pacific/Palau',
  459 => 'Pacific/Pitcairn',
  460 => 'Pacific/Pohnpei',
  461 => 'Pacific/Ponape',
  462 => 'Pacific/Port_Moresby',
  463 => 'Pacific/Rarotonga',
  464 => 'Pacific/Saipan',
  465 => 'Pacific/Samoa',
  466 => 'Pacific/Tahiti',
  467 => 'Pacific/Tarawa',
  468 => 'Pacific/Tongatapu',
  469 => 'Pacific/Truk',
  470 => 'Pacific/Wake',
  471 => 'Pacific/Wallis',
  472 => 'Pacific/Yap',
  473 => 'Brazil/Acre',
  474 => 'Brazil/DeNoronha',
  475 => 'Brazil/East',
  476 => 'Brazil/West',
  477 => 'Canada/Atlantic',
  478 => 'Canada/Central',
  479 => 'Canada/East-Saskatchewan',
  480 => 'Canada/Eastern',
  481 => 'Canada/Mountain',
  482 => 'Canada/Newfoundland',
  483 => 'Canada/Pacific',
  484 => 'Canada/Saskatchewan',
  485 => 'Canada/Yukon',
  486 => 'CET',
  487 => 'Chile/Continental',
  488 => 'Chile/EasterIsland',
  489 => 'CST6CDT',
  490 => 'Cuba',
  491 => 'EET',
  492 => 'Egypt',
  493 => 'Eire',
  494 => 'EST',
  495 => 'EST5EDT',
  496 => 'Etc/GMT',
  497 => 'Etc/GMT+0',
  498 => 'Etc/GMT+1',
  499 => 'Etc/GMT+10',
  500 => 'Etc/GMT+11',
  501 => 'Etc/GMT+12',
  502 => 'Etc/GMT+2',
  503 => 'Etc/GMT+3',
  504 => 'Etc/GMT+4',
  505 => 'Etc/GMT+5',
  506 => 'Etc/GMT+6',
  507 => 'Etc/GMT+7',
  508 => 'Etc/GMT+8',
  509 => 'Etc/GMT+9',
  510 => 'Etc/GMT-0',
  511 => 'Etc/GMT-1',
  512 => 'Etc/GMT-10',
  513 => 'Etc/GMT-11',
  514 => 'Etc/GMT-12',
  515 => 'Etc/GMT-13',
  516 => 'Etc/GMT-14',
  517 => 'Etc/GMT-2',
  518 => 'Etc/GMT-3',
  519 => 'Etc/GMT-4',
  520 => 'Etc/GMT-5',
  521 => 'Etc/GMT-6',
  522 => 'Etc/GMT-7',
  523 => 'Etc/GMT-8',
  524 => 'Etc/GMT-9',
  525 => 'Etc/GMT0',
  526 => 'Etc/Greenwich',
  527 => 'Etc/UCT',
  528 => 'Etc/Universal',
  529 => 'Etc/UTC',
  530 => 'Etc/Zulu',
  531 => 'Factory',
  532 => 'GB',
  533 => 'GB-Eire',
  534 => 'GMT',
  535 => 'GMT+0',
  536 => 'GMT-0',
  537 => 'GMT0',
  538 => 'Greenwich',
  539 => 'Hongkong',
  540 => 'HST',
  541 => 'Iceland',
  542 => 'Iran',
  543 => 'Israel',
  544 => 'Jamaica',
  545 => 'Japan',
  546 => 'Kwajalein',
  547 => 'Libya',
  548 => 'MET',
  549 => 'Mexico/BajaNorte',
  550 => 'Mexico/BajaSur',
  551 => 'Mexico/General',
  552 => 'MST',
  553 => 'MST7MDT',
  554 => 'Navajo',
  555 => 'NZ',
  556 => 'NZ-CHAT',
  557 => 'Poland',
  558 => 'Portugal',
  559 => 'PRC',
  560 => 'PST8PDT',
  561 => 'ROC',
  562 => 'ROK',
  563 => 'Singapore',
  564 => 'Turkey',
  565 => 'UCT',
  566 => 'Universal',
  567 => 'US/Alaska',
  568 => 'US/Aleutian',
  569 => 'US/Arizona',
  570 => 'US/Central',
  571 => 'US/East-Indiana',
  572 => 'US/Eastern',
  573 => 'US/Hawaii',
  574 => 'US/Indiana-Starke',
  575 => 'US/Michigan',
  576 => 'US/Mountain',
  577 => 'US/Pacific',
  578 => 'US/Pacific-New',
  579 => 'US/Samoa',
  580 => 'UTC',
  581 => 'W-SU',
  582 => 'WET',
  583 => 'Zulu',
)

Is there any way to return HTML in a PHP function? (without building the return value as a string)

Yes, there is: you can capture the echoed text using ob_start:

<?php function TestBlockHTML($replStr) {
    ob_start(); ?>
    <html>
    <body><h1><?php echo($replStr) ?></h1>
    </html>
<?php
    return ob_get_clean();
} ?>

How to get duration, as int milli's and float seconds from <chrono>?

Taking a guess at what it is you're asking for. I'm assuming by millisecond frame timer you're looking for something that acts like the following,

double mticks()
{
    struct timeval tv;
    gettimeofday(&tv, 0);
    return (double) tv.tv_usec / 1000 + tv.tv_sec * 1000;
}

but uses std::chrono instead,

double mticks()
{
    typedef std::chrono::high_resolution_clock clock;
    typedef std::chrono::duration<float, std::milli> duration;

    static clock::time_point start = clock::now();
    duration elapsed = clock::now() - start;
    return elapsed.count();
}

Hope this helps.

Why am I seeing "TypeError: string indices must be integers"?

data is a dict object. So, iterate over it like this:

Python 2

for key, value in data.iteritems():
    print key, value

Python 3

for key, value in data.items():
    print(key, value)

Accessing post variables using Java Servlets

For getting all post parameters there is Map which contains request param name as key and param value as key.

Map params = servReq.getParameterMap();

And to get parameters with known name normal

String userId=servReq.getParameter("user_id");

Check if a list contains an item in Ansible

Ansible has a version_compare filter since 1.6. You can do something like below in when conditional:

when: ansible_distribution_version | version_compare('12.04', '>=')

This will give you support for major & minor versions comparisons and you can compare versions using operators like:

<, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne

You can find more information about this here: Ansible - Version comparison filters

Otherwise if you have really simple case you can use what @ProfHase85 suggested

NHibernate.MappingException: No persister for: XYZ

My issue was that I forgot to put the .hbm in the name of the mapping xml. Also make sure you make it an embedded resource!

assign value using linq

Be aware that it only updates the first company it found with company id 1. For multiple

 (from c in listOfCompany where c.id == 1 select c).First().Name = "Whatever Name";

For Multiple updates

 from c in listOfCompany where c.id == 1 select c => {c.Name = "Whatever Name";  return c;}

Laravel - Return json along with http status code

I think it is better practice to keep your response under single control and for this reason I found out the most official solution.

response()->json([...])
    ->setStatusCode(Response::HTTP_OK, Response::$statusTexts[Response::HTTP_OK]);

add this after namespace declaration:

use Illuminate\Http\Response;

How can a windows service programmatically restart itself?

Dim proc As New Process()
Dim psi As New ProcessStartInfo()

psi.CreateNoWindow = True
psi.FileName = "cmd.exe"
psi.Arguments = "/C net stop YOURSERVICENAMEHERE && net start YOURSERVICENAMEHERE"
psi.LoadUserProfile = False
psi.UseShellExecute = False
psi.WindowStyle = ProcessWindowStyle.Hidden
proc.StartInfo = psi
proc.Start()

How can I add a new column and data to a datatable that already contains data?

Only you want to set default value parameter. This calling third overloading method.

dt.Columns.Add("MyRow", type(System.Int32),0);

Gradients in Internet Explorer 9

The code I use for all browser gradients:

background: #0A284B;
background: -webkit-gradient(linear, left top, left bottom, from(#0A284B), to(#135887));
background: -webkit-linear-gradient(#0A284B, #135887);
background: -moz-linear-gradient(top, #0A284B, #135887);
background: -ms-linear-gradient(#0A284B, #135887);
background: -o-linear-gradient(#0A284B, #135887);
background: linear-gradient(#0A284B, #135887);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#0A284B', endColorstr='#135887');
zoom: 1;

You will need to specify a height or zoom: 1 to apply hasLayout to the element for this to work in IE.


Update:

Here is a LESS Mixin (CSS) version for all you LESS users out there:

.gradient(@start, @end) {
    background: mix(@start, @end, 50%);
    filter: ~"progid:DXImageTransform.Microsoft.gradient(startColorStr="@start~", EndColorStr="@end~")";
    background: -webkit-gradient(linear, left top, left bottom, from(@start), to(@end));
    background: -webkit-linear-gradient(@start, @end);
    background: -moz-linear-gradient(top, @start, @end);
    background: -ms-linear-gradient(@start, @end);
    background: -o-linear-gradient(@start, @end);
    background: linear-gradient(@start, @end);
    zoom: 1;
}

Conveniently map between enum and int / String

In this code, for permanent and intense search , have memory or process for use, and I select memory, with converter array as index. I hope it's helpful

public enum Test{ 
VALUE_ONE(101, "Im value one"),
VALUE_TWO(215, "Im value two");
private final int number;
private final byte[] desc;

private final static int[] converter = new int[216];
static{
    Test[] st = values();
    for(int i=0;i<st.length;i++){
        cv[st[i].number]=i;
    }
}

Test(int value, byte[] description) {
    this.number = value;
    this.desc = description;
}   
public int value() {
    return this.number;
}
public byte[] description(){
    return this.desc;
}

public static String description(int value) {
    return values()[converter[rps]].desc;
}

public static Test fromValue(int value){
return values()[converter[rps]];
}
}

Angular 4 Pipe Filter

I know this is old, but i think i have good solution. Comparing to other answers and also comparing to accepted, mine accepts multiple values. Basically filter object with key:value search parameters (also object within object). Also it works with numbers etc, cause when comparing, it converts them to string.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'filter'})
export class Filter implements PipeTransform {
    transform(array: Array<Object>, filter: Object): any {
        let notAllKeysUndefined = false;
        let newArray = [];

        if(array.length > 0) {
            for (let k in filter){
                if (filter.hasOwnProperty(k)) {
                    if(filter[k] != undefined && filter[k] != '') {
                        for (let i = 0; i < array.length; i++) {
                            let filterRule = filter[k];

                            if(typeof filterRule === 'object') {
                                for(let fkey in filterRule) {
                                    if (filter[k].hasOwnProperty(fkey)) {
                                        if(filter[k][fkey] != undefined && filter[k][fkey] != '') {
                                            if(this.shouldPushInArray(array[i][k][fkey], filter[k][fkey])) {
                                                newArray.push(array[i]);
                                            }
                                            notAllKeysUndefined = true;
                                        }
                                    }
                                }
                            } else {
                                if(this.shouldPushInArray(array[i][k], filter[k])) {
                                    newArray.push(array[i]);
                                }
                                notAllKeysUndefined = true;
                            }
                        }
                    }
                }
            }
            if(notAllKeysUndefined) {
                return newArray;
            }
        }

        return array;
    }

    private shouldPushInArray(item, filter) {
        if(typeof filter !== 'string') {
            item = item.toString();
            filter = filter.toString();
        }

        // Filter main logic
        item = item.toLowerCase();
        filter = filter.toLowerCase();
        if(item.indexOf(filter) !== -1) {
            return true;
        }
        return false;
    }
}

jQuery: Change button text on click

its work short code

$('.SeeMore2').click(function(){ var $this = $(this).toggleClass('SeeMore2'); if($(this).hasClass('SeeMore2')) { $(this).text('See More');
} else { $(this).text('See Less'); } });

Difference between 3NF and BCNF in simple terms (must be able to explain to an 8-year old)

The subtle difference is that 3NF makes a distinction between key and non-key attributes (also called non-prime attributes) whereas BCNF does not.

This is best explained using Zaniolo's definition of 3NF, which is equivalent to Codd's:

A relation, R, is in 3NF iff for every nontrivial FD (X->A) satisfied by R at least ONE of the following conditions is true:

(a) X is a superkey for R, or

(b) A is a key attribute for R

BCNF requires (a) but doesn't treat (b) as a special case of its own. In other words BCNF requires that every nontrivial determinant is a superkey even its dependent attributes happen to be part of a key.

A relation, R, is in BCNF iff for every nontrivial FD (X->A) satisfied by R the following condition is true:

(a) X is a superkey for R

BCNF is therefore more strict.

The difference is so subtle that what many people informally describe as 3NF is actually BCNF. For example, you stated here that 3NF means "data depends on the key[s]... and nothing but the key[s]", but that is really an informal description of BCNF and not 3NF. 3NF could more accurately be described as "non-key data depends on the keys... and nothing but the keys".

You also stated:

the 3NF quote explicitly says "nothing but the key" meaning that all attributes depend solely on the primary key.

That's an oversimplification. 3NF and BCNF and all the Normal Forms are concerned with all candidate keys and/or superkeys, not just one "primary" key.

How do you stop MySQL on a Mac OS install?

After try all those command line, and it is not work.I have to do following stuff:

mv /usr/local/Cellar/mysql/5.7.16/bin/mysqld /usr/local/Cellar/mysql/5.7.16/bin/mysqld.bak
mysql.server stop

This way works, the mysqld process is gone. but the /var/log/system.log have a lot of rubbish:

Jul  9 14:10:54 xxx com.apple.xpc.launchd[1] (homebrew.mxcl.mysql[78049]): Service exited with abnormal code: 1
Jul  9 14:10:54 xxx com.apple.xpc.launchd[1] (homebrew.mxcl.mysql): Service only ran for 0 seconds. Pushing respawn out by 10 seconds.

SQL Server Output Clause into a scalar variable

Over a year later... if what you need is get the auto generated id of a table, you can just

SELECT @ReportOptionId = SCOPE_IDENTITY()

Otherwise, it seems like you are stuck with using a table.

Run multiple python scripts concurrently

I had to do this and used subprocess.

import subprocess

subprocess.run("python3 script1.py & python3 script2.py", shell=True)

How to get the function name from within that function?

This will work in ES5, ES6, all browsers and strict mode functions.

Here's how it looks with a named function.

(function myName() {
  console.log(new Error().stack.split(/\r\n|\r|\n/g)[1].trim());
})();
at myName (<anonymous>:2:15)

Here's how it looks with an anonymous function.

(() => {
  console.log(new Error().stack.split(/\r\n|\r|\n/g)[1].trim());
})();
at <anonymous>:2:15

How can I output UTF-8 from Perl?

Thanks, finally got an solution to not put utf8::encode all over code. To synthesize and complete for other cases, like write and read files in utf8 and also works with LoadFile of an YAML file in utf8

use utf8;
use open ':encoding(utf8)';
binmode(STDOUT, ":utf8");

open(FH, ">test.txt"); 
print FH "something éá";

use YAML qw(LoadFile Dump);
my $PUBS = LoadFile("cache.yaml");
my $f = "2917";
my $ref = $PUBS->{$f};
print "$f \"".$ref->{name}."\" ". $ref->{primary_uri}." ";

where cache.yaml is:

---
2917:
  id: 2917
  name: Semanário
  primary_uri: 2917.xml

How to convert unix timestamp to calendar date moment.js

moment(1454521239279).toDate()
moment(1454521239279).format()

MAX function in where clause mysql

You are using word 'max' as an alias for your column. Try to:

MAX(id) as mymax ... WHERE ID - mymax

React onClick function fires on render

JSX will evaluate JavaScript expressions in curly braces

In this case, this.props.removeTaskFunction(todo) is invoked and the return value is assigned to onClick

What you have to provide for onClick is a function. To do this, you can wrap the value in an anonymous function.

export const samepleComponent = ({todoTasks, removeTaskFunction}) => {
    const taskNodes = todoTasks.map(todo => (
                <div>
                    {todo.task}
                    <button type="submit" onClick={() => removeTaskFunction(todo)}>Submit</button>
                </div>
            );
    return (
        <div className="todo-task-list">
            {taskNodes}
        </div>
        );
    }
});

How to normalize a vector in MATLAB efficiently? Any related built-in function?

I took Mr. Fooz's code and also added Arlen's solution too and here are the timings that I've gotten for Octave:

clc; clear all;
V = rand(1024*1024*32,1);
N = 10;
tic; for i=1:N, V1 = V/norm(V);         end; toc % 7.0 s
tic; for i=1:N, V2 = V/sqrt(sum(V.*V)); end; toc % 6.4 s
tic; for i=1:N, V3 = V/sqrt(V'*V);      end; toc % 5.5 s
tic; for i=1:N, V4 = V/sqrt(sum(V.^2)); end; toc % 6.6 s
tic; for i=1:N, V1 = V/norm(V);         end; toc % 7.1 s
tic; for i=1:N, d = 1/norm(V); V1 = V*d;end; toc % 4.7 s

Then, because of something I'm currently looking at, I tested out this code for ensuring that each row sums to 1:

clc; clear all;
m = 2048;
V = rand(m);
N = 100;
tic; for i=1:N, V1 = V ./ (sum(V,2)*ones(1,m));                end; toc % 8.2 s
tic; for i=1:N, V2 = bsxfun(@rdivide, V, sum(V,2));            end; toc % 5.8 s
tic; for i=1:N, V3 = bsxfun(@rdivide, V, V*ones(m,1));         end; toc % 5.7 s
tic; for i=1:N, V4 = V ./ (V*ones(m,m));                       end; toc % 77.5 s
tic; for i=1:N, d = 1./sum(V,2);V5 = bsxfun(@times, V, d);     end; toc % 2.83 s
tic; for i=1:N, d = 1./(V*ones(m,1));V6 = bsxfun(@times, V, d);end; toc % 2.75 s
tic; for i=1:N, V1 = V ./ (sum(V,2)*ones(1,m));                end; toc % 8.2 s

how to get all markers on google-maps-v3

The one way found is to use the geoXML3 library which is suitable for usage along with KML processor Version 3 of the Google Maps JavaScript API.

How to programmatically open the Permission Screen for a specific app on Android Marshmallow?

Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);

Description

Settings.ACTION_APPLICATION_DETAILS_SETTINGS
   Opens Details setting page for App. From here user have to manually assign desired permission.

Intent.FLAG_ACTIVITY_NEW_TASK
   Optional. If set then opens Settings Screen(Activity) as new activity. Otherwise, it will be opened in currently running activity.

Uri.fromParts("package", getPackageName(), null)
   Prepares or creates URI, whereas, getPackageName() - returns name of your application package.

intent.setData(uri)
   Don't forget to set this. Otherwise, you will get android.content.ActivityNotFoundException. Because you have set your intent as Settings.ACTION_APPLICATION_DETAILS_SETTINGS and android expects some name to search.

JavaScript adding decimal numbers issue

function add(){
    var first=parseFloat($("#first").val());
    var second=parseFloat($("#second").val());
    $("#result").val(+(first+second).toFixed(2));
}

DEMO.

What is the correct JSON content type?

If you're calling ASP.NET Web Services from the client-side you have to use application/json for it to work. I believe this is the same for the jQuery and Ext frameworks.

How to remove the Flutter debug banner?

There is also another way for removing the "debug" banner from the flutter app. Now after new release there is no "debugShowCheckedModeBanner: false," code line in main .dart file. So I think these methods are effective:

  1. If you are using VS Code, then install "Dart DevTools" from extensions. After installation, you can easily find "Dart DevTools" text icon at the bottom of the VS Code. When you click on that text icon, a link will be open in google chrome. From that link page, you can easily remove the banner by just tapping on the banner icon as shown in this screenshot.

NOTE:-- Dart DevTools is a dart language debugger extension in VS Code

  1. If Dart DevTools is already installed in your VS Code, then you can directly open the google chrome and open this URL = "127.0.0.1: ZZZZZ/?hide=debugger&port=XXXXX"

NOTE:-- In this link replace "XXXXX" by 5 digit port-id (on which your flutter app is running) which will vary whenever you use "flutter run" command and replace "ZZZZZ" by your global(unchangeable) 5 digit debugger-id

NOTE:-- these dart dev tools are only for "Google Chrome Browser"

Regex to split a CSV

This one matches all i need in c#:

(?<=(^|,)(?<quote>"?))([^"]|(""))*?(?=\<quote>(?=,|$))
  • strips quotes
  • lets new lines
  • lets double quotes in the quoted string
  • lets commas in the quoted string

Can you pass parameters to an AngularJS controller on creation?

If ng-init is not for passing objects into $scope, you can always write your own directive. So here is what I got:

http://jsfiddle.net/goliney/89bLj/

Javasript:

var app = angular.module('myApp', []);
app.directive('initData', function($parse) {
    return function(scope, element, attrs) {
        //modify scope
        var model = $parse(attrs.initData);
        model(scope);
    };
});

function Ctrl1($scope) {
    //should be defined
    $scope.inputdata = {foo:"east", bar:"west"};
}

Html:

<div ng-controller="Ctrl1">
    <div init-data="inputdata.foo=123; inputdata.bar=321"></div>
</div>

But my approach can only modify objects, which are already defined at controller.

Does IMDB provide an API?

IMDB themselves seem to distribute data, but only in text files:

http://www.imdb.com/interfaces

there are several APIs around this that you can Google. Screen scraping is explicitly forbidden. A official API seems to be in the works, but has been that for years already.

Displaying standard DataTables in MVC

While I tried the approach above, it becomes a complete disaster with mvc. Your controller passing a model and your view using a strongly typed model become too difficult to work with.

Get your Dataset into a List ..... I have a repository pattern and here is an example of getting a dataset from an old school asmx web service private readonly CISOnlineSRVDEV.ServiceSoapClient _ServiceSoapClient;

    public Get_Client_Repository()
        : this(new CISOnlineSRVDEV.ServiceSoapClient())
    {

    }
    public Get_Client_Repository(CISOnlineSRVDEV.ServiceSoapClient serviceSoapClient)
    {
        _ServiceSoapClient = serviceSoapClient;
    }


    public IEnumerable<IClient> GetClient(IClient client)
    {
        // ****  Calling teh web service with passing in the clientId and returning a dataset
        DataSet dataSet = _ServiceSoapClient.get_clients(client.RbhaId,
                                                        client.ClientId,
                                                        client.AhcccsId,
                                                        client.LastName,
                                                        client.FirstName,
                                                        "");//client.BirthDate.ToString());  //TODO: NEED TO FIX

        // USE LINQ to go through the dataset to make it easily available for the Model to display on the View page
        List<IClient> clients = (from c in dataSet.Tables[0].AsEnumerable()
                                 select new Client()
                                 {
                                     RbhaId = c[5].ToString(),
                                     ClientId = c[2].ToString(),
                                     AhcccsId = c[6].ToString(),
                                     LastName = c[0].ToString(), // Add another field called   Sex M/F  c[4]
                                     FirstName = c[1].ToString(),
                                     BirthDate = c[3].ToDateTime()  //extension helper  ToDateTime()
                                 }).ToList<IClient>();

        return clients;

    }

Then in the Controller I'm doing this

IClient client = (IClient)TempData["Client"];

// Instantiate and instance of the repository 
var repository = new Get_Client_Repository();
// Set a model object to return the dynamic list from repository method call passing in the parameter data
var model = repository.GetClient(client);

// Call the View up passing in the data from the list
return View(model);

Then in the View it is easy :

@model IEnumerable<CISOnlineMVC.DAL.IClient>

@{
    ViewBag.Title = "CLIENT ALL INFORMATION";
}

<h2>CLIENT ALL INFORMATION</h2>

<table>
    <tr>
        <th></th>
        <th>Last Name</th>
        <th>First Name</th>
        <th>Client ID</th>
        <th>DOB</th>
        <th>Gender</th>
        <th>RBHA ID</th>
        <th>AHCCCS ID</th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.ActionLink("Select", "ClientDetails", "Cis", new { id = item.ClientId }, null) |
        </td>
        <td>
            @item.LastName
        </td>
        <td>
            @item.FirstName
        </td>
         <td>
            @item.ClientId
        </td>
         <td>
            @item.BirthDate
        </td>
         <td>
            Gender @* ADD in*@
        </td>
         <td>
            @item.RbhaId
        </td>
         <td>
            @item.AhcccsId
        </td>
    </tr>
}

</table>

Iterating over a numpy array

I think you're looking for the ndenumerate.

>>> a =numpy.array([[1,2],[3,4],[5,6]])
>>> for (x,y), value in numpy.ndenumerate(a):
...  print x,y
... 
0 0
0 1
1 0
1 1
2 0
2 1

Regarding the performance. It is a bit slower than a list comprehension.

X = np.zeros((100, 100, 100))

%timeit list([((i,j,k), X[i,j,k]) for i in range(X.shape[0]) for j in range(X.shape[1]) for k in range(X.shape[2])])
1 loop, best of 3: 376 ms per loop

%timeit list(np.ndenumerate(X))
1 loop, best of 3: 570 ms per loop

If you are worried about the performance you could optimise a bit further by looking at the implementation of ndenumerate, which does 2 things, converting to an array and looping. If you know you have an array, you can call the .coords attribute of the flat iterator.

a = X.flat
%timeit list([(a.coords, x) for x in a.flat])
1 loop, best of 3: 305 ms per loop

GUI-based or Web-based JSON editor that works like property explorer

Generally when I want to create a JSON or YAML string, I start out by building the Perl data structure, and then running a simple conversion on it. You could put a UI in front of the Perl data structure generation, e.g. a web form.

Converting a structure to JSON is very straightforward:

use strict;
use warnings;
use JSON::Any;

my $data = { arbitrary structure in here };
my $json_handler = JSON::Any->new(utf8=>1);
my $json_string = $json_handler->objToJson($data);

YYYY-MM-DD format date in shell script

$(date +%F_%H-%M-%S)

can be used to remove colons (:) in between

output

2018-06-20_09-55-58

how to use html2canvas and jspdf to export to pdf in a proper and simple way

I have made a jsfiddle for you.

 <canvas id="canvas" width="480" height="320"></canvas> 
      <button id="download">Download Pdf</button>

'

        html2canvas($("#canvas"), {
            onrendered: function(canvas) {         
                var imgData = canvas.toDataURL(
                    'image/png');              
                var doc = new jsPDF('p', 'mm');
                doc.addImage(imgData, 'PNG', 10, 10);
                doc.save('sample-file.pdf');
            }
        });

jsfiddle: http://jsfiddle.net/rpaul/p4s5k59s/5/

Tested in Chrome38, IE11 and Firefox 33. Seems to have issues with Safari. However, Andrew got it working in Safari 8 on Mac OSx by switching to JPEG from PNG. For details, see his comment below.

How do I run Java .class files?

To run Java class file from the command line, the syntax is:

java -classpath /path/to/jars <packageName>.<MainClassName>

where packageName (usually starts with either com or org) is the folder name where your class file is present.

For example if your main class name is App and Java package name of your app is com.foo.app, then your class file needs to be in com/foo/app folder (separate folder for each dot), so you run your app as:

$ java com.foo.app.App

Note: $ is indicating shell prompt, ignore it when typing

If your class doesn't have any package name defined, simply run as: java App.

If you've any other jar dependencies, make sure you specified your classpath parameter either with -cp/-classpath or using CLASSPATH variable which points to the folder with your jar/war/ear/zip/class files. So on Linux you can prefix the command with: CLASSPATH=/path/to/jars, on Windows you need to add the folder into system variable. If not set, the user class path consists of the current directory (.).


Practical example

Given we've created sample project using Maven as:

$ mvn archetype:generate -DgroupId=com.foo.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false 

and we've compiled our project by mvn compile in our my-app/ dir, it'll generate our class file is in target/classes/com/foo/app/App.class.

To run it, we can either specify class path via -cp or going to it directly, check examples below:

$ find . -name "*.class"
./target/classes/com/foo/app/App.class
$ CLASSPATH=target/classes/ java com.foo.app.App
Hello World!
$ java -cp target/classes com.foo.app.App
Hello World!
$ java -classpath .:/path/to/other-jars:target/classes com.foo.app.App
Hello World!
$ cd target/classes && java com.foo.app.App
Hello World!

To double check your class and package name, you can use Java class file disassembler tool, e.g.:

$ javap target/classes/com/foo/app/App.class
Compiled from "App.java"
public class com.foo.app.App {
  public com.foo.app.App();
  public static void main(java.lang.String[]);
}

Note: javap won't work if the compiled file has been obfuscated.

How to create materialized views in SQL Server?

For MS T-SQL Server, I suggest looking into creating an index with the "include" statement. Uniqueness is not required, neither is the physical sorting of data associated with a clustered index. The "Index ... Include ()" creates a separate physical data storage automatically maintained by the system. It is conceptually very similar to an Oracle Materialized View.

https://msdn.microsoft.com/en-us/library/ms190806.aspx

https://technet.microsoft.com/en-us/library/ms189607(v=sql.105).aspx

Returning an empty array

In a single line you could do:

private static File[] bar(){
    return new File[]{};
}

jQuery - Get Width of Element when Not Visible (Display: None)

As has been said before, the clone and attach elsewhere method does not guarantee the same results as styling may be different.

Below is my approach. It travels up the parents looking for the parent responsible for the hiding, then temporarily unhides it to calculate the required width, height, etc.

_x000D_
_x000D_
    var width = parseInt($image.width(), 10);_x000D_
    var height = parseInt($image.height(), 10);_x000D_
_x000D_
    if (width === 0) {_x000D_
_x000D_
        if ($image.css("display") === "none") {_x000D_
_x000D_
            $image.css("display", "block");_x000D_
            width = parseInt($image.width(), 10);_x000D_
            height = parseInt($image.height(), 10);_x000D_
            $image.css("display", "none");_x000D_
        }_x000D_
        else {_x000D_
_x000D_
            $image.parents().each(function () {_x000D_
_x000D_
                var $parent = $(this);_x000D_
                if ($parent.css("display") === "none") {_x000D_
_x000D_
                    $parent.css("display", "block");_x000D_
                    width = parseInt($image.width(), 10);_x000D_
                    height = parseInt($image.height(), 10);_x000D_
                    $parent.css("display", "none");_x000D_
                }_x000D_
            });_x000D_
        }_x000D_
    }
_x000D_
_x000D_
_x000D_

Cheap way to search a large text file for a string

This is entirely inspired by laurasia's answer above, but it refines the structure.

It also adds some checks:

  • It will correctly return 0 when searching an empty file for the empty string. In laurasia's answer, this is an edge case that will return -1.
  • It also pre-checks whether the goal string is larger than the buffer size, and raises an error if this is the case.

In practice, the goal string should be much smaller than the buffer for efficiency, and there are more efficient methods of searching if the size of the goal string is very close to the size of the buffer.

def fnd(fname, goal, start=0, bsize=4096):
    if bsize < len(goal):
        raise ValueError("The buffer size must be larger than the string being searched for.")
    with open(fname, 'rb') as f:
        if start > 0:
            f.seek(start)
        overlap = len(goal) - 1
        while True:
            buffer = f.read(bsize)
            pos = buffer.find(goal)
            if pos >= 0:
                return f.tell() - len(buffer) + pos
            if not buffer:
                return -1
            f.seek(f.tell() - overlap)

Python function attributes - uses and abuses

I've used them as static variables for a function. For example, given the following C code:

int fn(int i)
{
    static f = 1;
    f += i;
    return f;
}

I can implement the function similarly in Python:

def fn(i):
    fn.f += i
    return fn.f
fn.f = 1

This would definitely fall into the "abuses" end of the spectrum.

C++ convert string to hexadecimal and vice versa

A string like "Hello World" to hex format: 48656C6C6F20576F726C64.

Ah, here you go:

#include <string>

std::string string_to_hex(const std::string& input)
{
    static const char hex_digits[] = "0123456789ABCDEF";

    std::string output;
    output.reserve(input.length() * 2);
    for (unsigned char c : input)
    {
        output.push_back(hex_digits[c >> 4]);
        output.push_back(hex_digits[c & 15]);
    }
    return output;
}

#include <stdexcept>

int hex_value(unsigned char hex_digit)
{
    static const signed char hex_values[256] = {
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
         0,  1,  2,  3,  4,  5,  6,  7,  8,  9, -1, -1, -1, -1, -1, -1,
        -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    };
    int value = hex_values[hex_digit];
    if (value == -1) throw std::invalid_argument("invalid hex digit");
    return value;
}

std::string hex_to_string(const std::string& input)
{
    const auto len = input.length();
    if (len & 1) throw std::invalid_argument("odd length");

    std::string output;
    output.reserve(len / 2);
    for (auto it = input.begin(); it != input.end(); )
    {
        int hi = hex_value(*it++);
        int lo = hex_value(*it++);
        output.push_back(hi << 4 | lo);
    }
    return output;
}

(This assumes that a char has 8 bits, so it's not very portable, but you can take it from here.)

What causing this "Invalid length for a Base-64 char array"

This is because of a huge view state, In my case I got lucky since I was not using the viewstate. I just added enableviewstate="false" on the form tag and view state went from 35k to 100 chars

Can a table have two foreign keys?

Yes, MySQL allows this. You can have multiple foreign keys on the same table.

Get more details here FOREIGN KEY Constraints

In OS X Lion, LANG is not set to UTF-8, how to fix it?

I noticed the exact same issue when logging onto servers running Red Hat from an OSX Lion machine.

Try adding or editing the ~/.profile file for it to correctly export your locale settings upon initiating a new session.

export LC_ALL=en_US.UTF-8  
export LANG=en_US.UTF-8

These two lines added to the file should suffice to set the locale [replace en_US for your desired locale, and check beforehand that it is indeed installed on your system (locale -a)].

After that, you can start a new session and check using locale:

$ locale

The following should be the output:

LANG="en_US.UTF-8"  
LC_COLLATE="en_US.UTF-8"  
LC_CTYPE="en_US.UTF-8"  
LC_MESSAGES="en_US.UTF-8"  
LC_MONETARY="en_US.UTF-8"  
LC_NUMERIC="en_US.UTF-8"  
LC_TIME="en_US.UTF-8"  
LC_ALL="en_US.UTF-8"  

How to redirect to another page using AngularJS?

You can use Angular $window:

$window.location.href = '/index.html';

Example usage in a contoller:

(function () {
    'use strict';

    angular
        .module('app')
        .controller('LoginCtrl', LoginCtrl);

    LoginCtrl.$inject = ['$window', 'loginSrv', 'notify'];

    function LoginCtrl($window, loginSrv, notify) {
        /* jshint validthis:true */
        var vm = this;
        vm.validateUser = function () {
             loginSrv.validateLogin(vm.username, vm.password).then(function (data) {          
                if (data.isValidUser) {    
                    $window.location.href = '/index.html';
                }
                else
                    alert('Login incorrect');
            });
        }
    }
})();

"Operation must use an updateable query" error in MS Access

To update records, you need to write changes to .mdb file on disk. If your web/shared application can't write to disk, you can't update existing or add new records. So, enable read/write access in database folder or move database to other folder where your application has write permission....for more detail please check:

http://www.beansoftware.com/ASP.NET-FAQ/Operation-Must-Use-An-Updateable-Query.aspx

Automatic Preferred Max Layout Width is not available on iOS versions prior to 8.0

I got it working by selecting the original layout I had in the W / H selection. Storyboard is working as expected and the error is gone.

Be also sure that you are developing for iOS 8.0. Check that from the project's general settings.

This is where you should press.

How to align text below an image in CSS?

Easiest way excpecially if you don't know images widths is to put the caption in it's own div element an define it to be cleared:both !

...

<div class="pics">  
  <img class="marq" src="pic_1.jpg" />
  <div class="caption">My image 1</div>
</div>  
  <div class="pics">    
  <img class="marq" src="pic_2.jpg" />
  <div class="caption">My image 2</div>
  </div>

...

and in style-block define

div.caption: {
  float: left;
  clear: both;
}   

RuntimeWarning: DateTimeField received a naive datetime

Quick and dirty - Turn it off:

USE_TZ = False

in your settings.py

How do I do a HTTP GET in Java?

The simplest way that doesn't require third party libraries it to create a URL object and then call either openConnection or openStream on it. Note that this is a pretty basic API, so you won't have a lot of control over the headers.

How to scroll HTML page to given anchor?

function scrollTo(hash) {
    location.hash = "#" + hash;
}

No jQuery required at all!

MySQL INNER JOIN Alias

Use a seperate column to indicate the join condition

SELECT  t.importid, 
        case 
            when t.importid = g.home 
            then 'home' 
            else 'away' 
        end as join_condition, 
        g.network, 
        g.date_start 
FROM    game g
INNER JOIN team t ON (t.importid = g.home OR t.importid = g.away)
ORDER BY date_start DESC 
LIMIT 7

Removing All Items From A ComboBox?

I could not get clear to work. (Mac Excel) but this does.

ActiveSheet.DropDowns("CollectionComboBox").RemoveAllItems

Extract Month and Year From Date in R

Here's another solution using a package solely dedicated to working with dates and times in R:

library(tidyverse)
library(lubridate)

(df <- tibble(ID = 1:3, Date = c("2004-02-06" , "2006-03-14", "2007-07-16")))
#> # A tibble: 3 x 2
#>      ID Date      
#>   <int> <chr>     
#> 1     1 2004-02-06
#> 2     2 2006-03-14
#> 3     3 2007-07-16

df %>%
  mutate(
    Date = ymd(Date),
    Month_Yr = format_ISO8601(Date, precision = "ym")
  )
#> # A tibble: 3 x 3
#>      ID Date       Month_Yr
#>   <int> <date>     <chr>   
#> 1     1 2004-02-06 2004-02 
#> 2     2 2006-03-14 2006-03 
#> 3     3 2007-07-16 2007-07

Created on 2020-09-01 by the reprex package (v0.3.0)

Prevent browser caching of AJAX call result

Of course "cache-breaking" techniques will get the job done, but this would not happen in the first place if the server indicated to the client that the response should not be cached. In some cases it is beneficial to cache responses, some times not. Let the server decide the correct lifetime of the data. You may want to change it later. Much easier to do from the server than from many different places in your UI code.

Of course this doesn't help if you have no control over the server.

Css Move element from left to right animated

It's because you aren't giving the un-hovered state a right attribute.

right isn't set so it's trying to go from nothing to 0px. Obviously because it has nothing to go to, it just 'warps' over.

If you give the unhovered state a right:90%;, it will transition how you like.

Just as a side note, if you still want it to be on the very left of the page, you can use the calc css function.

Example:

right: calc(100% - 100px)
                     ^ width of div

You don't have to use left then.

Also, you can't transition using left or right auto and will give the same 'warp' effect.

_x000D_
_x000D_
div {_x000D_
    width:100px;_x000D_
    height:100px;_x000D_
    background:red;_x000D_
    transition:2s;_x000D_
    -webkit-transition:2s;_x000D_
    -moz-transition:2s;_x000D_
    position:absolute;_x000D_
    right:calc(100% - 100px);_x000D_
}_x000D_
div:hover {_x000D_
  right:0;_x000D_
}
_x000D_
<p>_x000D_
  <b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions._x000D_
</p>_x000D_
<div></div>_x000D_
<p>Hover over the red square to see the transition effect.</p>
_x000D_
_x000D_
_x000D_

CanIUse says that the calc() function only works on IE10+

Count Vowels in String Python

vowels = ["a","e","i","o","u"]

def checkForVowels(some_string):
  #will save all counted vowel variables as key/value
  amountOfVowels = {}
  for i in vowels:
    # check for lower vowel variables
    if i in some_string:
      amountOfVowels[i] = some_string.count(i)
    #check for upper vowel variables
    elif i.upper() in some_string:
      amountOfVowels[i.upper()] = some_string.count(i.upper())
  return amountOfVowels

print(checkForVowels("sOmE string"))

You can test this code here : https://repl.it/repls/BlueSlateblueDecagons

So have fun hope helped a lil bit.

Iterate through string array in Java

I would argue instead of testing i less than elements.length - 1 testing i + 1 less than elements.length. You aren't changing the domain of the array that you are looking at (i.e. ignoring the last element), but rather changing the greatest element you are looking at in each iteration.

String[] elements = { "a", "a","a","a" };

for(int i = 0; i + 1 < elements.length; i++) {
    String first = elements[i];
    String second = elements[i+1];
    //do something with the two strings
}

Remove the last line from a file in Bash

This is by far the fastest and simplest solution, especially on big files:

head -n -1 foo.txt > temp.txt ; mv temp.txt foo.txt

if You want to delete the top line use this:

tail -n +2 foo.txt

which means output lines starting at line 2.

Do not use sed for deleting lines from the top or bottom of a file -- it's very very slow if the file is large.

Can I install/update WordPress plugins without providing FTP access?

WordPress 2.7 lets you upload a zip file directly (there's a link at the bottom of the plugins page) -- no FTP access needed. This is a new feature in 2.7, and it works for plugins only (not themes yet).

Figuring out whether a number is a Double in Java

Since this is the first question from Google I'll add the JavaScript style typeof alternative here as well:

myObject.getClass().getName() // String

How to search JSON tree with jQuery

    var GDNUtils = {};

GDNUtils.loadJquery = function () {
    var checkjquery = window.jQuery && jQuery.fn && /^1\.[3-9]/.test(jQuery.fn.jquery);
    if (!checkjquery) {

        var theNewScript = document.createElement("script");
        theNewScript.type = "text/javascript";
        theNewScript.src = "http://code.jquery.com/jquery.min.js";

        document.getElementsByTagName("head")[0].appendChild(theNewScript);

        // jQuery MAY OR MAY NOT be loaded at this stage


    }
};



GDNUtils.searchJsonValue = function (jsonData, keytoSearch, valuetoSearch, keytoGet) {
    GDNUtils.loadJquery();
    alert('here' + jsonData.length.toString());
    GDNUtils.loadJquery();

    $.each(jsonData, function (i, v) {

        if (v[keytoSearch] == valuetoSearch) {
            alert(v[keytoGet].toString());

            return;
        }
    });



};




GDNUtils.searchJson = function (jsonData, keytoSearch, valuetoSearch) {
    GDNUtils.loadJquery();
    alert('here' + jsonData.length.toString());
    GDNUtils.loadJquery();
    var row;
    $.each(jsonData, function (i, v) {

        if (v[keytoSearch] == valuetoSearch) {


            row  = v;
        }
    });

    return row;



}

List file names based on a filename pattern and file content?

find /folder -type f -mtime -90 | grep -E "(.txt|.php|.inc|.root|.gif)" | xargs ls -l > WWWlastActivity.log

Remove an item from array using UnderscoreJS

You can use reject method of Underscore, below will return a new array which won't have array with particular match

arr = _.reject(arr, function(objArr){ return objArr.id == 3; });

Find all files with a filename beginning with a specified string?

If you want to restrict your search only to files you should consider to use -type f in your search

try to use also -iname for case-insensitive search

Example:

find /path -iname 'yourstring*' -type f

You could also perform some operations on results without pipe sign or xargs

Example:

Search for files and show their size in MB

find /path -iname 'yourstring*' -type f -exec du -sm {} \;

Amazon S3 upload file and get URL

        System.out.println("Link : " + s3Object.getObjectContent().getHttpRequest().getURI());

with this you can retrieve the link of already uploaded file to S3 bucket.

How do you display code snippets in MS Word preserving format and syntax highlighting?

There is a nice Online Tool for that : http://www.planetb.ca/syntax-highlight-word

Just copy the generated code and paste it in your word editing software. So far I've tried it on MS Word and WPS Writer, works really well. Doesn't play nice with Firefox but works just fine on Chrome (and IE too, but who wants to use that).

One of the main benefits is that, unlike the Code Format Add-In for Word, it does NOT mess with your code, and respects various languages syntax. I tried many other options offered in other answer but I found this one to be the most efficient (quick and really effective).

There is also another onlinz tool quoted in another answer (markup.su) but I find the planetB output more elegant (although less versatile).

Input :

enter image description here

Output :

enter image description here

RuntimeWarning: invalid value encountered in divide

I think your code is trying to "divide by zero" or "divide by NaN". If you are aware of that and don't want it to bother you, then you can try:

import numpy as np
np.seterr(divide='ignore', invalid='ignore')

For more details see:

What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check fails)?

you can use the return statement without any parameter to exit a function

def foo(element):
    do something
    if check is true:
        do more (because check was succesful)
    else:
        return
    do much much more...

or raise an exception if you want to be informed of the problem

def foo(element):
    do something
    if check is true:
        do more (because check was succesful)
    else:
        raise Exception("cause of the problem")
    do much much more...

Swift: Determine iOS Screen size

In Swift 3.0

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

In older swift: Do something like this:

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

then you can access the width and height like this:

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

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

let screenWidth = screenSize.width * 0.75

Swift 4.0

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

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

In Swift 5.0

let screenSize: CGRect = UIScreen.main.bounds

How to print Boolean flag in NSLog?

Note that in Swift, you can just do

let testBool: Bool = true
NSLog("testBool = %@", testBool.description)

This will log testBool = true

ORA-00060: deadlock detected while waiting for resource

I was recently struggling with a similar problem. It turned out that the database was missing indexes on foreign keys. That caused Oracle to lock many more records than required which quickly led to a deadlock during high concurrency.

Here is an excellent article with lots of good detail, suggestions, and details about how to fix a deadlock: http://www.oratechinfo.co.uk/deadlocks.html#unindex_fk

Altering a column: null to not null

I had the same problem, but the field used to default to null, and now I want to default it to 0. That required adding one more line after mdb's solution:

ALTER TABLE [Table] ADD CONSTRAINT [Constraint] DEFAULT 0 FOR [Column];

node.js require() cache - possible to invalidate?

I am not 100% certain of what you mean by 'invalidate', but you can add the following above the require statements to clear the cache:

Object.keys(require.cache).forEach(function(key) { delete require.cache[key] })

Taken from @Dancrumb's comment here

How to remove an unpushed outgoing commit in Visual Studio?

Assuming you have pushed most recent changes to the server:

  1. Close Visual Studio and delete your local copy of the project
  2. Open Visual Studio, go to Team Explorer tab, click Manage Connections. (plug)
  3. Click the dropdown arrow next to Manage Connections, Connect to a Project
  4. Select the project, confirm the local path, and click the Connect button.

Once you reopen the project both commits and changes should be zero.

How to generate UML diagrams (especially sequence diagrams) from Java code?

By far the best tool I have used for reverse engineering, and round tripping java -> UML is Borland's Together. It is based on Eclipse (not just a single plugin) and really works well.

How to generate access token using refresh token through google drive API?

It's an old question but seems to me it wasn't completely answered, and I needed this information too so I'll post my answer.

If you want to use the Google Api Client Library, then you just need to have an access token that includes the refresh token in it, and then - even though the access token will expire after an hour - the library will refresh the token for you automatically.

In order to get an access token with a refresh token, you just need to ask for the offline access type (for example in PHP: $client->setAccessType("offline");) and you will get it. Just keep in mind you will get the access token with the refresh token only in the first authorization, so make sure to save that access token in the first time, and you will be able to use it anytime.

Hope that helps anyone :-)

PHP - find entry by object property from an array of objects

$arr = [
  [
    'ID' => 1
  ]
];

echo array_search(1, array_column($arr, 'ID')); // prints 0 (!== false)

Above code echoes the index of the matching element, or false if none.

To get the corresponding element, do something like:

$i = array_search(1, array_column($arr, 'ID'));
$element = ($i !== false ? $arr[$i] : null);

array_column works both on an array of arrays, and on an array of objects.

How to execute a Python script from the Django shell?

came here with the same question as the OP, and I found my favourite answer precisely in the mistake within the question, which works also in Python 3:

./manage.py shell <<EOF
import my_script
my_script.main()
EOF

What's the point of 'meta viewport user-scalable=no' in the Google Maps API

Disabling user-scalable (namely, the ability to double tap to zoom) allows the browser to reduce the click delay. In touch-enable browsers, when the user expects the double tap to zoom, the browser generally waits 300ms before firing the click event, waiting to see if the user will double tap. Disabling user-scalable allows for the Chrome browser to fire the click event immediately, allowing for a better user experience.

From Google IO 2013 session https://www.youtube.com/watch?feature=player_embedded&v=DujfpXOKUp8#t=1435s

Update: its not true anymore, <meta name="viewport" content="width=device-width"> is enough to remove 300ms delay

git add only modified changes and ignore untracked files

To stage modified and deleted files

git add -u

Can a JSON value contain a multiline string

Per the specification, the JSON grammar's char production can take the following values:

  • any-Unicode-character-except-"-or-\-or-control-character
  • \"
  • \\
  • \/
  • \b
  • \f
  • \n
  • \r
  • \t
  • \u four-hex-digits

Newlines are "control characters", so no, you may not have a literal newline within your string. However, you may encode it using whatever combination of \n and \r you require.

The JSONLint tool confirms that your JSON is invalid.


And, if you want to write newlines inside your JSON syntax without actually including newlines in the data, then you're doubly out of luck. While JSON is intended to be human-friendly to a degree, it is still data and you're trying to apply arbitrary formatting to that data. That is absolutely not what JSON is about.

Rounding Bigdecimal values with 2 Decimal Places

You may try this:

public static void main(String[] args) {
    BigDecimal a = new BigDecimal("10.12345");
    System.out.println(toPrecision(a, 2));
}

private static BigDecimal toPrecision(BigDecimal dec, int precision) {
    String plain = dec.movePointRight(precision).toPlainString();
    return new BigDecimal(plain.substring(0, plain.indexOf("."))).movePointLeft(precision);
}

OUTPUT:

10.12

Does reading an entire file leave the file handle open?

Instead of retrieving the file content as a single string, it can be handy to store the content as a list of all lines the file comprises:

with open('Path/to/file', 'r') as content_file:
    content_list = content_file.read().strip().split("\n")

As can be seen, one needs to add the concatenated methods .strip().split("\n") to the main answer in this thread.

Here, .strip() just removes whitespace and newline characters at the endings of the entire file string, and .split("\n") produces the actual list via splitting the entire file string at every newline character \n.

Moreover, this way the entire file content can be stored in a variable, which might be desired in some cases, instead of looping over the file line by line as pointed out in this previous answer.

css overflow - only 1 line of text

if addition please, if you have a long text please you can use this css code bellow;

text-overflow: ellipsis;
overflow: visible;
white-space: nowrap;

make the whole line text visible.

Strings as Primary Keys in SQL Database

Inserts to a table having a clustered index where the insertion occurs in the middle of the sequence DOES NOT cause the index to be rewritten. It does not cause the pages comprising the data to be rewritten. If there is room on the page where the row will go, then it is placed in that page. The single page will be reformatted to place the row in the right place in the page. When the page is full, a page split will happen, with half of the rows on the page going to one page, and half going on the other. The pages are then relinked into the linked list of pages that comprise a tables data that has the clustered index. At most, you will end up writing 2 pages of database.

ImportError: cannot import name NUMPY_MKL

The reason for the error is you upgraded your numpy library of which there are some functionalities from scipy that are required by the current version for it to run which may not be found in scipy. Just upgrade your scipy library using python -m pip install scipy --upgrade. I was facing the same error and this solution worked on my python 3.5.

How to Validate Google reCaptcha on Form Submit

While using Google reCaptcha with reCaptcha DLL file, we can validate it in C# as follows :

 RecaptchaControl1.Validate();
        bool _Varify = RecaptchaControl1.IsValid;
        if (_Varify)
        {
// Pice of code after validation.
}

Its works for me.

What is the difference between field, variable, attribute, and property in Java POJOs?

My understanding is as below, and I am not saying that this is 100% correct, I might as well be mistaken..

A variable is something that you declare, which can by default change and have different values, but that can also be explicitly said to be final. In Java that would be:

public class Variables {

    List<Object> listVariable; // declared but not assigned
    final int aFinalVariableExample = 5; // declared, assigned and said to be final!

    Integer foo(List<Object> someOtherObjectListVariable) {
        // declare..
        Object iAmAlsoAVariable;

        // assign a value..
        iAmAlsoAVariable = 5;

        // change its value..
        iAmAlsoAVariable = 8;

        someOtherObjectListVariable.add(iAmAlsoAVariable);

        return new Integer();
    }
}

So basically, a variable is anything that is declared and can hold values. Method foo above returns a variable for example.. It returns a variable of type Integer which holds the memory address of the new Integer(); Everything else you see above are also variables, listVariable, aFinalVariableExample and explained here:

A field is a variable where scope is more clear (or concrete). The variable returning from method foo 's scope is not clear in the example above, so I would not call it a field. On the other hand, iAmAlsoVariable is a "local" field, limited by the scope of the method foo, and listVariable is an "instance" field where the scope of the field (variable) is limited by the objects scope.

A property is a field that can be accessed / mutated. Any field that exposes a getter / setter is a property.

I do not know about attribute and I would also like to repeat that this is my understanding of what variables, fields and properties are.

Programmatic equivalent of default(Type)

Can't find anything simple and elegant just yet, but I have one idea: If you know the type of the property you wish to set, you can write your own default(T). There are two cases - T is a value type, and T is a reference type. You can see this by checking T.IsValueType. If T is a reference type, then you can simply set it to null. If T is a value type, then it will have a default parameterless constructor that you can call to get a "blank" value.

How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?

I don't think the jar tool supports this natively, but you can just unzip a JAR file with "unzip" and specify the output directory with that with the "-d" option, so something like:

$ unzip -d /home/foo/bar/baz /home/foo/bar/Portal.ear Binaries.war

How to create a file in memory for user to download, but not through server?

If the file contains text data, a technique I use is to put the text into a textarea element and have the user select it (click in textarea then ctrl-A) then copy followed by a paste to a text editor.

How to load data to hive from HDFS without removing the source file?

An alternative to 'LOAD DATA' is available in which the data will not be moved from your existing source location to hive data warehouse location.

You can use ALTER TABLE command with 'LOCATION' option. Here is below required command

ALTER TABLE table_name ADD PARTITION (date_col='2017-02-07') LOCATION 'hdfs/path/to/location/'

The only condition here is, the location should be a directory instead of file.

Hope this will solve the problem.

IEnumerable<object> a = new IEnumerable<object>(); Can I do this?

I wanted to create a new enumerable object or list and be able to add to it.

This comment changes everything. You can't add to a generic IEnumerable<T>. If you want to stay with the interfaces in System.Collections.Generic, you need to use a class that implements ICollection<T> like List<T>.

How to place the ~/.composer/vendor/bin directory in your PATH?

MacOS Sierra User:

make sure you delete MAAP and MAAP Pro from Application folder if you have it installed on your computer

be in root directory cd ~ check homebrew (if you have homebrew installed) OR have PHP up to date

brew install php70

export PATH="$PATH:$HOME/.composer/vendor/bin"

echo 'export PATH="$PATH:$HOME/.composer/vendor/bin"' >> ~/.bash_profile

source ~/.bash_profile

cat .bash_profile

make sure this is showing : export PATH="$PATH:$HOME/.composer/vendor/bin"

laravel

now it should be global

A variable modified inside a while loop is not remembered

I use stderr to store within a loop, and read from it outside. Here var i is initially set and read inside the loop as 1.

# reading lines of content from 2 files concatenated
# inside loop: write value of var i to stderr (before iteration)
# outside: read var i from stderr, has last iterative value

f=/tmp/file1
g=/tmp/file2
i=1
cat $f $g | \
while read -r s;
do
  echo $s > /dev/null;  # some work
  echo $i > 2
  let i++
done;
read -r i < 2
echo $i

Or use the heredoc method to reduce the amount of code in a subshell. Note the iterative i value can be read outside the while loop.

i=1
while read -r s;
do
  echo $s > /dev/null
  let i++
done <<EOT
$(cat $f $g)
EOT
let i--
echo $i

Mongodb service won't start

I solved this by executing C:\mongodb\bin\mongod.exe --repair first. Then when I ran MongoDB again by C:\mongodb\bin\mongod.exe, it successfully started.

How to kill/stop a long SQL query immediately?

sp_who2 'active'

Check values under CPUTime and DiskIO. Note the SPID of process having large value comparatively.

kill {SPID value}

How can I refresh or reload the JFrame?

just use frame.setVisible(false); frame.setVisible(true); I've had this problem with JLabels with images, and this solved it

Unicode, UTF, ASCII, ANSI format differences

Some reading to get you started on character encodings: Joel on Software: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

By the way - ASP.NET has nothing to do with it. Encodings are universal.

Array vs. Object efficiency in JavaScript

It depends on usage. If the case is lookup objects is very faster.

Here is a Plunker example to test performance of array and object lookups.

https://plnkr.co/edit/n2expPWVmsdR3zmXvX4C?p=preview

You will see that; Looking up for 5.000 items in 5.000 length array collection, take over 3000 milisecons

However Looking up for 5.000 items in object has 5.000 properties, take only 2 or 3 milisecons

Also making object tree don't make huge difference

500 Internal Server Error for php file not for html

Google guides me here but it didn't fix mine, this is a very general question and there are various causes, so I post my problem and solution here for reference in case anyone might read this later.

Another possible cause of 500 error is syntax error in header(...) function, like this one:

header($_SERVER['SERVER_PROTOCOL'] . '200 OK');

Be aware there should be space between server protocol and status code, so it should be:

header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK');

So I suggest check your http header call if you have it in your code.

Android: View.setID(int id) programmatically - how to avoid ID conflicts?

This works for me:

static int id = 1;

// Returns a valid id that isn't in use
public int findId(){  
    View v = findViewById(id);  
    while (v != null){  
        v = findViewById(++id);  
    }  
    return id++;  
}

Wait until boolean value changes it state

I prefer to use mutex mechanism in such cases, but if you really want to use boolean, then you should declare it as volatile (to provide the change visibility across threads) and just run the body-less cycle with that boolean as a condition :

//.....some class

volatile boolean someBoolean; 

Thread someThread = new Thread() {

    @Override 
    public void run() {
        //some actions
        while (!someBoolean); //wait for condition 
        //some actions 
    }

};

JavaScript style.display="none" or jQuery .hide() is more efficient?

a = 2;

vs

a(2);
function a(nb) {
    lot;
    of = cross;
    browser();
    return handling(nb);
}

In your opinion, what do you think is going to be the fastest?

Add to integers in a list

fooList = [1,3,348,2]
fooList.append(3)
fooList.append(2734)
print(fooList) # [1,3,348,2,3,2734]

HTML image not showing in Gmail

My issue was similar. This is what my experience has been on testing the IMG tag on gmail (assuming most of the organization's would have a dev qa and prod server.)

I had to send emails to customers on their personal email id's and we could see that gmail would add something of its own like following to src attribute of img tag. Now when we were sending these images from our dev environment they would never render on gmail and we were always curious why?

https://ci7.googleusercontent.com/proxy/AEF54znasdUhUYhuHuHuhHkHfT7u2w5zsOnWJ7k1MwrKe8pP69hY9W9eo8_n6-tW0KdSIaG4qaBEbcXue74nbVBysdfqweAsNNmmmJyTB-JQzcgn1j=s0-d-e2-ft#https://www.prodserver.com/Folder1/Images/OurImage.PNG

so an image sent to my gmail id as following never worked for me

<img src="https://ci7.googleuser....Blah.Blah..https://devserver.com/Folder1/Images/OurImage.PNG">

and our dev server we can't render this image by hitting following URL on Chrome(or any browser).

https://www.devserver.com/folder1/folder2/myactualimage.jpg

now as long as the src has www on it worked all the time and we didnt had to add any other attributes.

<img src="https://www.**prodserver**.com/folder1/folder2/myactualimage.jpg">

Change project name on Android Studio

A very quick way to solve this as at November 2020 is by the following steps

  1. hit the shift key twice, a pop up will show search for a file named "settings.gradle" when it opens change the rootProject.name = "Old-name" to rootProject.name = "new name" then sync.

  2. hit the shift key twice, a pop up will show search for a file named "string.xml", when it opens change <string "app_name">old-name to <string "app_name">new-name

  3. close android studio

  4. locate androidStudioProject directory on your machine, open it and find the project by its old name, rename it to the new name.

  5. open Android Studio goto File > Open > "new name". open it from there.

this is currently working on Android Studio 4.1.1

Append data frames together in a for loop

You should try this:

df_total = data.frame()
for (i in 1:7){
    # vector output
    model <- #some processing

    # add vector to a dataframe
    df <- data.frame(model)
    df_total <- rbind(df_total,df)
}

How to select first child with jQuery?

$('div.alldivs :first-child');

Or you can just refer to the id directly:

$('#div1');

As suggested, you might be better of using the child selector:

$('div.alldivs > div:first-child')

If you dont have to use first-child, you could use :first as also suggested, or $('div.alldivs').children(0).

How can I avoid getting this MySQL error Incorrect column specifier for column COLUMN NAME?

I was having the same problem, but using Long type. I changed for INT and it worked for me.

CREATE TABLE lists (
 id INT NOT NULL AUTO_INCREMENT,
 desc varchar(30),
 owner varchar(20),
 visibility boolean,
 PRIMARY KEY (id)
 );

Returning null in a method whose signature says return int?

The type int is a primitive and it cannot be null, if you want to return null, mark the signature as

public Integer pollDecrementHigherKey(int x) {
    x = 10;

    if (condition) {
        return x; // This is auto-boxing, x will be automatically converted to Integer
    } else if (condition2) {
        return null; // Integer inherits from Object, so it's valid to return null
    } else {
        return new Integer(x); // Create an Integer from the int and then return
    }
    
    return 5; // Also will be autoboxed and converted into Integer
}

How does the ARM architecture differ from x86?

ARM is a RISC (Reduced Instruction Set Computing) architecture while x86 is a CISC (Complex Instruction Set Computing) one.

The core difference between those in this aspect is that ARM instructions operate only on registers with a few instructions for loading and saving data from / to memory while x86 can operate directly on memory as well. Up until v8 ARM was a native 32 bit architecture, favoring four byte operations over others.

So ARM is a simpler architecture, leading to small silicon area and lots of power save features while x86 becoming a power beast in terms of both power consumption and production.

About question on "Is the x86 Architecture specially designed to work with a keyboard while ARM expects to be mobile?". x86 isn't specially designed to work with a keyboard neither ARM for mobile. However again because of the core architectural choices actually x86 also has instructions to work directly with IO while ARM has not. However with specialized IO buses like USBs, need for such features are also disappearing.

If you need a document to quote, this is what Cortex-A Series Programmers Guide (4.0) tells about differences between RISC and CISC architectures:

An ARM processor is a Reduced Instruction Set Computer (RISC) processor.

Complex Instruction Set Computer (CISC) processors, like the x86, have a rich instruction set capable of doing complex things with a single instruction. Such processors often have significant amounts of internal logic that decode machine instructions to sequences of internal operations (microcode).

RISC architectures, in contrast, have a smaller number of more general purpose instructions, that might be executed with significantly fewer transistors, making the silicon cheaper and more power efficient. Like other RISC architectures, ARM cores have a large number of general-purpose registers and many instructions execute in a single cycle. It has simple addressing modes, where all load/store addresses can be determined from register contents and instruction fields.

ARM company also provides a paper titled Architectures, Processors, and Devices Development Article describing how those terms apply to their bussiness.

An example comparing instruction set architecture:

For example if you would need some sort of bytewise memory comparison block in your application (generated by compiler, skipping details), this is how it might look like on x86

repe cmpsb         /* repeat while equal compare string bytewise */

while on ARM shortest form might look like (without error checking etc.)

top:
ldrb r2, [r0, #1]! /* load a byte from address in r0 into r2, increment r0 after */
ldrb r3, [r1, #1]! /* load a byte from address in r1 into r3, increment r1 after */
subs r2, r3, r2    /* subtract r2 from r3 and put result into r2      */
beq  top           /* branch(/jump) if result is zero                 */

which should give you a hint on how RISC and CISC instruction sets differ in complexity.

How can I convert an Int to a CString?

If you want something more similar to your example try _itot_s. On Microsoft compilers _itot_s points to _itoa_s or _itow_s depending on your Unicode setting:

CString str;
_itot_s( 15, str.GetBufferSetLength( 40 ), 40, 10 );
str.ReleaseBuffer();

it should be slightly faster since it doesn't need to parse an input format.

Modifying location.hash without page scrolling

Use history.replaceState or history.pushState* to change the hash. This will not trigger the jump to the associated element.

Example

$(document).on('click', 'a[href^=#]', function(event) {
  event.preventDefault();
  history.pushState({}, '', this.href);
});

Demo on JSFiddle

* If you want history forward and backward support

History behaviour

If you are using history.pushState and you don't want page scrolling when the user uses the history buttons of the browser (forward/backward) check out the experimental scrollRestoration setting (Chrome 46+ only).

history.scrollRestoration = 'manual';

Browser Support

How can I strip HTML tags from a string in ASP.NET?

I've posted this on the asp.net forums, and it still seems to be one of the easiest solutions out there. I won't guarantee it's the fastest or most efficient, but it's pretty reliable. In .NET you can use the HTML Web Control objects themselves. All you really need to do is insert your string into a temporary HTML object such as a DIV, then use the built-in 'InnerText' to grab all text that is not contained within tags. See below for a simple C# example:


System.Web.UI.HtmlControls.HtmlGenericControl htmlDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
htmlDiv.InnerHtml = htmlString;
String plainText = htmlDiv.InnerText;

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

There is nothing called float:bottom in CSS. The best way is using positioning in such cases:

position:absolute;
bottom:0;

Issue with virtualenv - cannot activate

Incase you are using Anaconda / miniconda on windows - in your command prompt use

conda activate <your-environmentname>

e.g. peopleanalytics is name of my virtual environment - Is say

conda activate peopleanalytics

Select SQL Server database size

Worked perfectly for me to calculate SQL database size in SQL Server 2012

exec sp_spaceused

enter image description here

upgade python version using pip

Basically, pip comes with python itself.Therefore it carries no meaning for using pip itself to install or upgrade python. Thus,try to install python through installer itself,visit the site "https://www.python.org/downloads/" for more help. Thank you.

Postman: sending nested JSON object

To post a nested object with the key-value interface you can use a similar method to sending arrays. Pass an object key in square brackets after the object index.

Passing a nested item with Postman

"Items": [
      {
        "sku": "9257",
        "Price": "100"
      }
 ]

Passing null arguments to C# methods

Starting from C# 2.0, you can use the nullable generic type Nullable, and in C# there is a shorthand notation the type followed by ?

e.g.

private void Example(int? arg1, int? arg2)
{
    if(arg1 == null)
    {
        //do something
    }
    if(arg2 == null)
    {
        //do something else
    }
}