Programs & Examples On #Craigslist

Craigslist is a free online community for locals to buy, sell, trade, and discuss.

Is there a developers api for craigslist.org

Good news everybody! Craigslist has actually released a bulk posting api now!

Enjoy

$("#form1").validate is not a function

I had this same issue. It turned out that I was loading the jQuery JavaScript file more than once on the page. This was due to included pages (or JSPs, in my case). Once I removed the duplicate reference to the jQuery js file, this error went away.

Simple way to read single record from MySQL

Using PDO you could do something like this:

$db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');

$stmt = $db->query('select id from games where ...');
$id = $stmt->fetchColumn(0);
if ($id !== false) {
    echo $id;
}

You obviously should also check whether PDO::query() executes the query OK (either by checking the result or telling PDO to throw exceptions instead)

Simple JavaScript Checkbox Validation

Another simple way is to create a function and check if the checkbox(es) are checked or not, and disable a button that way using jQuery.

HTML:

<input type="checkbox" id="myCheckbox" />
<input type="submit" id="myButton" />

JavaScript:

var alterDisabledState = function () {

var isMyCheckboxChecked = $('#myCheckbox').is(':checked');

     if (isMyCheckboxChecked) {
     $('myButton').removeAttr("disabled");
     } 
     else {
             $('myButton').attr("disabled", "disabled");
     }
}

Now you have a button that is disabled until they select the checkbox, and now you have a better user experience. I would make sure that you still do the server side validation though.

Rearrange columns using cut

using just the shell,

while read -r col1 col2
do
  echo $col2 $col1
done <"file"

Selecting fields from JSON output

Assuming you are dealing with a JSON-string in the input, you can parse it using the json package, see the documentation.

In the specific example you posted you would need

x = json.loads("""{
 "accountWide": true,
 "criteria": [
     {
         "description": "some description",
         "id": 7553,
         "max": 1,
         "orderIndex": 0
     }
  ]
 }""")
description = x['criteria'][0]['description']
id = x['criteria'][0]['id']
max = x['criteria'][0]['max']

What reference do I need to use Microsoft.Office.Interop.Excel in .NET?

If you have Microsoft Office installed, then you should be able to add a reference to Interop.Excel.

For example, the PC I'm typing this on has MSVS 2010 C# Express and Office 2010. I can add a reference to Microsoft.Office.Interop.Excel 11.0.0.0.

'Hope that helps

Flask ImportError: No Module Named Flask

Another thing - if you're using python3, make sure you are starting your server with python3 server.py, not python server.py

Python - Dimension of Data Frame

Summary of all ways to get info on dimensions of DataFrame or Series

There are a number of ways to get information on the attributes of your DataFrame or Series.

Create Sample DataFrame and Series

df = pd.DataFrame({'a':[5, 2, np.nan], 'b':[ 9, 2, 4]})
df

     a  b
0  5.0  9
1  2.0  2
2  NaN  4

s = df['a']
s

0    5.0
1    2.0
2    NaN
Name: a, dtype: float64

shape Attribute

The shape attribute returns a two-item tuple of the number of rows and the number of columns in the DataFrame. For a Series, it returns a one-item tuple.

df.shape
(3, 2)

s.shape
(3,)

len function

To get the number of rows of a DataFrame or get the length of a Series, use the len function. An integer will be returned.

len(df)
3

len(s)
3

size attribute

To get the total number of elements in the DataFrame or Series, use the size attribute. For DataFrames, this is the product of the number of rows and the number of columns. For a Series, this will be equivalent to the len function:

df.size
6

s.size
3

ndim attribute

The ndim attribute returns the number of dimensions of your DataFrame or Series. It will always be 2 for DataFrames and 1 for Series:

df.ndim
2

s.ndim
1

The tricky count method

The count method can be used to return the number of non-missing values for each column/row of the DataFrame. This can be very confusing, because most people normally think of count as just the length of each row, which it is not. When called on a DataFrame, a Series is returned with the column names in the index and the number of non-missing values as the values.

df.count() # by default, get the count of each column

a    2
b    3
dtype: int64


df.count(axis='columns') # change direction to get count of each row

0    2
1    2
2    1
dtype: int64

For a Series, there is only one axis for computation and so it just returns a scalar:

s.count()
2

Use the info method for retrieving metadata

The info method returns the number of non-missing values and data types of each column

df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
a    2 non-null float64
b    3 non-null int64
dtypes: float64(1), int64(1)
memory usage: 128.0 bytes

Java 8 optional: ifPresent return object orElseThrow exception

Actually what you are searching is: Optional.map. Your code would then look like:

object.map(o -> "result" /* or your function */)
      .orElseThrow(MyCustomException::new);

I would rather omit passing the Optional if you can. In the end you gain nothing using an Optional here. A slightly other variant:

public String getString(Object yourObject) {
  if (Objects.isNull(yourObject)) { // or use requireNonNull instead if NullPointerException suffices
     throw new MyCustomException();
  }
  String result = ...
  // your string mapping function
  return result;
}

If you already have the Optional-object due to another call, I would still recommend you to use the map-method, instead of isPresent, etc. for the single reason, that I find it more readable (clearly a subjective decision ;-)).

"inconsistent use of tabs and spaces in indentation"

Try deleting the indents and then systematically either pressing tab or pressing space 4 times. This usually happens to me when I have an indent using the tab key and then use the space key in the next line.

Drop primary key using script in SQL Server database

You can look up the constraint name in the sys.key_constraints table:

SELECT name
FROM   sys.key_constraints
WHERE  [type] = 'PK'
       AND [parent_object_id] = Object_id('dbo.Student');

If you don't care about the name, but simply want to drop it, you can use a combination of this and dynamic sql:

DECLARE @table NVARCHAR(512), @sql NVARCHAR(MAX);

SELECT @table = N'dbo.Student';

SELECT @sql = 'ALTER TABLE ' + @table 
    + ' DROP CONSTRAINT ' + name + ';'
    FROM sys.key_constraints
    WHERE [type] = 'PK'
    AND [parent_object_id] = OBJECT_ID(@table);

EXEC sp_executeSQL @sql;

This code is from Aaron Bertrand (source).

Do you need to dispose of objects and set them to null?

You never need to set objects to null in C#. The compiler and runtime will take care of figuring out when they are no longer in scope.

Yes, you should dispose of objects that implement IDisposable.

how to empty recyclebin through command prompt?

I use this powershell oneliner:

gci C:\`$recycle.bin -force | remove-item -recurse -force

Works for different drives than C:, too

Determine project root from a running node.js application

Preamble

This is a very old question but it seems to still hit the nerve in 2020 as in 2012. I've checked all of the other answers and could not find a technique (note that this has its limitations, but all of the others are not applicable in every situation as well).

GIT + child process

If you are using GIT as your version control system, the problem of determining the project root can be reduced to (which I would consider the proper root of the project - after all, you would want your VCS to have the fullest visibility scope possible):

retrieve repository root path

Since you have to run a CLI command to do that, we will need to spawn a child process. Additionally, as project root is highly unlikely to change mid-runtime, we can use the synchronous version of the child_process module APIs at startup.

I found spawnSync() to be the most suitable for the job. As for the actual command to run, git worktree (with a --porcelain option for ease of parsing) is all we need to retrieve the absolute root path.

In the sample, I opted to return an array of paths because there might be more than one worktree (although they are likely to have common paths) just to be sure. Note that as we utilize a CLI command, shell option should be set to true (security shouldn't be an issue as there is no untrusted input).

Approach comparison and fallbacks

Understanding that a situation where VCS can be inaccessible is possible, I've included a couple of fallbacks after analyzing docs and other answers. To sum up, the solutions proposed boil down to (excluding third-party modules & package-specific):


| Solution                 | Advantage               | Main Problem                     |
| ------------------------ | ----------------------- | -------------------------------- |
| `__filename`             | points to module file   | relative to module               |
| `__dirname`              | points to module dir    | same as `__filename`             |
| `node_modules` tree walk | nearly guaranteed root  | complex tree walking if nested   |
| `path.resolve(".")`      | root if CWD is root     | same as `process.cwd()`          |
| `process.argv[1]`        | same as `__filename`    | same as `__filename`             |
| `process.env.INIT_CWD`   | points to `npm run` dir | requires `npm` && CLI launch     |
| `process.env.PWD`        | points to current dir   | relative to (is the) launch dir  |
| `process.cwd()`          | same as `env.PWD`       | `process.chdir(path)` at runtime |
| `require.main.filename`  | root if `=== module`    | fails on `require`d modules      |

From the comparison table above, the most universal are two approaches:

  • require.main.filename as an easy way to get root if require.main === module is met
  • node_modules tree walk proposed recently uses another assumption:

if the directory of the module has node_modules dir inside, it is likely to be the root

For the main app, it will get the app root and for the module - its project root.

Fallback 1. Tree walk

My implementation uses a more lax approach by stopping once a target directory is found as for a given module its root is its project root. One can chain the calls or extend it to make search depth configurable:

/**
 * @summary gets root by walking up node_modules
 * @param {import("fs")} fs
 * @param {import("path")} pt
 */
const getRootFromNodeModules = (fs, pt) =>

    /**
     * @param {string} [startPath]
     * @returns {string[]}
     */
    (startPath = __dirname) => {

        //avoid loop if reached root path
        if (startPath === pt.parse(startPath).root) {
            return [startPath];
        }

        const isRoot = fs.existsSync(pt.join(startPath, "node_modules"));

        if (isRoot) {
            return [startPath];
        }

        return getRootFromNodeModules(fs, pt)(pt.dirname(startPath));
    };

Fallback 2. Main module

The second implementation is trivial

/**
 * @summary gets app entry point if run directly
 * @param {import("path")} pt
 */
const getAppEntryPoint = (pt) =>

    /**
     * @returns {string[]}
     */
    () => {

        const { main } = require;

        const { filename } = main;

        return main === module ?
            [pt.parse(filename).dir] :
            [];
    };

Implementation

I would suggest use the tree walker as fallback because it is more versatile:

const { spawnSync } = require("child_process");
const pt = require('path');
const fs = require("fs");

/**
 * @summary returns worktree root path(s)
 * @param {function : string[] } [fallback]
 * @returns {string[]}
 */
const getProjectRoot = (fallback) => {

    const { error, stdout } = spawnSync(
        `git worktree list --porcelain`,
        {
            encoding: "utf8",
            shell: true
        }
    );

    if (!stdout) {
        console.warn(`Could not use GIT to find root:\n\n${error}`);
        return fallback ? fallback() : [];
    }

    return stdout
        .split("\n")
        .map(line => {
            const [key, value] = line.split(/\s+/) || [];
            return key === "worktree" ? value : "";
        })
        .filter(Boolean);
};

Disadvantages

The most obvious is having GIT installed and initialized which might be undesirable / implausible (side note: having GIT installed on production servers is not uncommon, nor is it unsafe, though). Can be mediated by fallbacks as described above.

Notes

  1. A couple of ideas for further extension of approach 1:
  • introduce config as a function parameter
  • export the function to make it a module
  • check if GIT is installed and / or initialized

References

  1. git worktree reference
  2. spawnSync reference
  3. require.main reference
  4. path.dirname() reference

Get Android Device Name

Try it. You can get Device Name through Bluetooth.

Hope it will help you

public String getPhoneName() {  
        BluetoothAdapter myDevice = BluetoothAdapter.getDefaultAdapter();
        String deviceName = myDevice.getName();     
        return deviceName;
    }

Shell Script: Execute a python program from within a shell script

Just make sure the python executable is in your PATH environment variable then add in your script

python path/to/the/python_script.py

Details:

  • In the file job.sh, put this
#!/bin/sh
python python_script.py
  • Execute this command to make the script runnable for you : chmod u+x job.sh
  • Run it : ./job.sh

Delete specific line number(s) from a text file using sed?

This is very often a symptom of an antipattern. The tool which produced the line numbers may well be replaced with one which deletes the lines right away. For example;

grep -nh error logfile | cut -d: -f1 | deletelines logfile

(where deletelines is the utility you are imagining you need) is the same as

grep -v error logfile

Having said that, if you are in a situation where you genuinely need to perform this task, you can generate a simple sed script from the file of line numbers. Humorously (but perhaps slightly confusingly) you can do this with sed.

sed 's%$%d%' linenumbers

This accepts a file of line numbers, one per line, and produces, on standard output, the same line numbers with d appended after each. This is a valid sed script, which we can save to a file, or (on some platforms) pipe to another sed instance:

sed 's%$%d%' linenumbers | sed -f - logfile

On some platforms, sed -f does not understand the option argument - to mean standard input, so you have to redirect the script to a temporary file, and clean it up when you are done, or maybe replace the lone dash with /dev/stdin or /proc/$pid/fd/1 if your OS (or shell) has that.

As always, you can add -i before the -f option to have sed edit the target file in place, instead of producing the result on standard output. On *BSDish platforms (including OSX) you need to supply an explicit argument to -i as well; a common idiom is to supply an empty argument; -i ''.

Unresolved reference issue in PyCharm

Manually adding it as you have done is indeed one way of doing this, but there is a simpler method, and that is by simply telling pycharm that you want to add the src folder as a source root, and then adding the sources root to your python path.

This way, you don't have to hard code things into your interpreter's settings:

  • Add src as a source content root:

                            enter image description here

  • Then make sure to add add sources to your PYTHONPATH under:

    Preferences ~ Build, Execution, Deployment ~ Console ~ Python Console
    

enter image description here

  • Now imports will be resolved:

                      enter image description here

This way, you can add whatever you want as a source root, and things will simply work. If you unmarked it as a source root however, you will get an error:

                                  enter image description here

After all this don't forget to restart. In PyCharm menu select: File --> Invalidate Caches / Restart

How to print a number with commas as thousands separators in JavaScript

Here is a one line function with int & decimal support. I left some code in to convert the number to a string as well.

    function numberWithCommas(x) {
        return (x=x+'').replace(new RegExp('\\B(?=(\\d{3})+'+(~x.indexOf('.')?'\\.':'$')+')','g'),',');
    }

How to find schema name in Oracle ? when you are connected in sql session using read only user

How about the following 3 statements?

-- change to your schema

ALTER SESSION SET CURRENT_SCHEMA=yourSchemaName;

-- check current schema

SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL;

-- generate drop table statements

SELECT 'drop table ', table_name, 'cascade constraints;' FROM ALL_TABLES WHERE OWNER = 'yourSchemaName';

COPY the RESULT and PASTE and RUN.

.NET data structures: ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary -- Speed, memory, and when to use each?

The generic collections will perform better than their non-generic counterparts, especially when iterating through many items. This is because boxing and unboxing no longer occurs.

Capturing mobile phone traffic on Wireshark

Packet Capture Android app implements a VPN that logs all network traffic on the Android device. You don't need to setup any VPN/proxy server on your PC. Does not needs root. Supports SSL decryption which tPacketCapture does not. It also includes a good log viewer.

Get current folder path

I created a simple console application with the following code:

Console.WriteLine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
Console.WriteLine(System.AppDomain.CurrentDomain.BaseDirectory);
Console.WriteLine(System.Environment.CurrentDirectory);
Console.WriteLine(System.IO.Directory.GetCurrentDirectory());
Console.WriteLine(Environment.CurrentDirectory);

I copied the resulting executable to C:\temp2. I then placed a shortcut to that executable in C:\temp3, and ran it (once from the exe itself, and once from the shortcut). It gave the following outputs both times:

C:\temp2
C:\temp2\
C:\temp2
C:\temp2
C:\temp2

While I'm sure there must be some cockamamie reason to explain why there are five different methods that do virtually the exact same thing, I certainly don't know what it is. Nevertheless, it would appear that under most circumstances, you are free to choose whichever one you fancy.

UPDATE: I modified the Shortcut properties, changing the "Start In:" field to C:\temp3. This resulted in the following output:

C:\temp2
C:\temp2\
C:\temp3
C:\temp3
C:\temp3

...which demonstrates at least some of the distinctions between the different methods.

Steps to upload an iPhone application to the AppStore

Check that your singing identity IN YOUR TARGET properties is correct. This one over-rides what you have in your project properties.

Also: I dunno if this is true - but I wasn't getting emails detailing my binary rejections when I did the "ready for binary upload" from a PC - but I DID get an email when I did this on the MAC

Redirect to Action in another controller

You can use this:

return RedirectToAction("actionName", "controllerName", new { area = "Admin" });

Can't connect to MySQL server on 'localhost' (10061)

To connect locally to MySql, you do not have to setup a firewall with inbound rules. But, even if you already setup iptables to allow the TCP inbound port 3306 and grant the privilege to the user to access the db locally, you may have to setup the bind address in your my.cnf file, edit the default address there and put the server IP address that is running the MySql service.

Pass a local file in to URL in Java

new File("path_to_file").toURI().toURL();

What is the difference between RTP or RTSP in a streaming server?

RTSP (actually RTP) can be used for streaming video, but also many other types of media including live presentations. Rtsp is just the protocol used to setup the RTP session.

For all the details you can check out my open source RTSP Server implementation on the following address: https://net7mma.codeplex.com/

Or my article @ http://www.codeproject.com/Articles/507218/Managed-Media-Aggregation-using-Rtsp-and-Rtp

It supports re-sourcing streams as well as the dynamic creation of streams, various RFC's are implemented and the library achieves better performance and less memory then FFMPEG and just about any other solutions in the transport layer and thus makes it a good candidate to use as a centralized point of access for most scenarios.

When is a timestamp (auto) updated?

Add a trigger in database:

DELIMITER //
CREATE TRIGGER update_user_password 
  BEFORE UPDATE ON users
  FOR EACH ROW
    BEGIN
      IF OLD.password <> NEW.password THEN
        SET NEW.password_changed_on = NOW();
      END IF;
    END //
DELIMITER ;

The password changed time will update only when password column is changed.

Return value using String result=Command.ExecuteScalar() error occurs when result returns null

Value is not null, but DBNull.Value.

object value = cmd.ExecuteScalar();
if(value == DBNull.Value)

Exception is: InvalidOperationException - The current type, is an interface and cannot be constructed. Are you missing a type mapping?

Just for others (like me) who might have faced the above error. The solution in simple terms.

You might have missed to register your Interface and class (which implements that inteface) registration in your code.

e.g if the error is
"The current type, xyznamespace. Imyinterfacename, is an interface and cannot be constructed. Are you missing a type mapping?"

Then you must register the class which implements the Imyinterfacename in the UnityConfig class in the Register method. using code like below

 container.RegisterType<Imyinterfacename, myinterfaceimplclassname>();

VBA Copy Sheet to End of Workbook (with Hidden Worksheets)

If you use the following code based on @Siddharth Rout's code, you rename the just copied sheet, no matter, if it is activated or not.

Sub Sample()

    ThisWorkbook.Sheets(1).Copy After:=Sheets(Sheets.Count)
    ThisWorkbook.Sheets(Sheets.Count).Name = "copied sheet!"

End Sub

Specify sudo password for Ansible

If you are using the pass password manager, you can use the module passwordstore, which makes this very easy.

Let's say you saved your user's sudo password in pass as

Server1/User

Then you can use the decrypted value like so

{{ lookup('community.general.passwordstore', 'Server1/User')}}"

I use it in my inventory:

---
   servers:
     hosts:
       server1:
         ansible_become_pass: "{{ lookup('community.general.passwordstore', 'Server1/User')}}"

Note that you should be running gpg-agent so that you won't see a pinentry prompt every time a 'become' task is run.

Getting the encoding of a Postgres database

A programmatic solution:

SELECT pg_encoding_to_char(encoding) FROM pg_database WHERE datname = 'yourdb';

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

Export tables to an excel spreadsheet in same directory

Lawrence has given you a good answer. But if you want more control over what gets exported to where in Excel see Modules: Sample Excel Automation - cell by cell which is slow and Modules: Transferring Records to Excel with Automation You can do things such as export the recordset starting in row 2 and insert custom text in row 1. As well as any custom formatting required.

Stylesheet not loaded because of MIME-type

by going into my browsers console > network > style.css ...clicked on it and it showed "cannot get /path/to/my/CSS", this told me my link was wrong. i changed that to the path of my CSS file.

Original path before change was localhost:3000/Example/public/style.css changing it to localhost:3000/style.css solved it.

if you are serving the file from app.use(express.static(path.join(__dirname, "public"))); or app.use(express.static("public")); your server would pass "that folder" to the browser so adding a "/yourCssName.css" link in your browser solves it

By adding other routes in your browser CSS link, you'd be telling the browser to search for the css in route specified.

in summary... check where your browser CSS link points to.

python dataframe pandas drop column using int

Since there can be multiple columns with same name , we should first rename the columns. Here is code for the solution.

df.columns=list(range(0,len(df.columns)))
df.drop(columns=[1,2])#drop second and third columns

How to remove the focus from a TextBox in WinForms?

I've found a good alternative! It works best for me, without setting the focus on something else.

Try that:

private void richTextBox_KeyDown(object sender, KeyEventArgs e)
{    
    e.SuppressKeyPress = true;
}

How to compare two JSON objects with the same elements in a different order equal?

You can write your own equals function:

  • dicts are equal if: 1) all keys are equal, 2) all values are equal
  • lists are equal if: all items are equal and in the same order
  • primitives are equal if a == b

Because you're dealing with json, you'll have standard python types: dict, list, etc., so you can do hard type checking if type(obj) == 'dict':, etc.

Rough example (not tested):

def json_equals(jsonA, jsonB):
    if type(jsonA) != type(jsonB):
        # not equal
        return False
    if type(jsonA) == dict:
        if len(jsonA) != len(jsonB):
            return False
        for keyA in jsonA:
            if keyA not in jsonB or not json_equal(jsonA[keyA], jsonB[keyA]):
                return False
    elif type(jsonA) == list:
        if len(jsonA) != len(jsonB):
            return False
        for itemA, itemB in zip(jsonA, jsonB):
            if not json_equal(itemA, itemB):
                return False
    else:
        return jsonA == jsonB

How to search a Git repository by commit message?

For anyone who wants to pass in arbitrary strings which are exact matches (And not worry about escaping regex special characters), git log takes a --fixed-strings option

git log --fixed-strings --grep "$SEARCH_TERM" 

Waiting until two async blocks are executed before starting another block

I know you asked about GCD, but if you wanted, NSOperationQueue also handles this sort of stuff really gracefully, e.g.:

NSOperationQueue *queue = [[NSOperationQueue alloc] init];

NSOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^{
    NSLog(@"Starting 3");
}];

NSOperation *operation;

operation = [NSBlockOperation blockOperationWithBlock:^{
    NSLog(@"Starting 1");
    sleep(7);
    NSLog(@"Finishing 1");
}];

[completionOperation addDependency:operation];
[queue addOperation:operation];

operation = [NSBlockOperation blockOperationWithBlock:^{
    NSLog(@"Starting 2");
    sleep(5);
    NSLog(@"Finishing 2");
}];

[completionOperation addDependency:operation];
[queue addOperation:operation];

[queue addOperation:completionOperation];

How to dynamic filter options of <select > with jQuery?

using Aaron's answer, this can be the short & easiest solution:

function filterSelectList(selectListId, filterId)
{
    var filter = $("#" + filterId).val().toUpperCase();

    $("#" + selectListId + " option").each(function(i){
       if ($(this).text.toUpperCase().includes(filter))
           $(this).css("display", "block");
       else
           $(this).css("display", "none");
    });
};

How can I use the HTML5 canvas element in IE?

You can try fxCanvas: https://code.google.com/p/fxcanvas/

It implements almost all Canvas API within flash shim.

Get content of a DIV using JavaScript

function add_more() {

var text_count = document.getElementById('text_count').value;
var div_cmp = document.getElementById('div_cmp');
var values = div_cmp.innnerHTML;
var count = parseInt(text_count);
divContent = '';

for (i = 1; i <= count; i++) {

    var cmp_text = document.getElementById('cmp_name_' + i).value;
    var cmp_textarea = document.getElementById('cmp_remark_' + i).value;
    divContent += '<div id="div_cmp_' + i + '">' +
        '<input type="text" align="top" name="cmp_name[]" id="cmp_name_' + i + '" value="' + cmp_text + '" >' +
        '<textarea rows="1" cols="20" name="cmp_remark[]" id="cmp_remark_' + i + '">' + cmp_textarea + '</textarea>' +
        '</div>';
}

var newCount = count + 1;

if (document.getElementById('div_cmp_' + newCount) == null) {
    var newText = '<div id="div_cmp_' + newCount + '">' +
        '<input type="text" align="top" name="cmp_name[]" id="cmp_name_' + newCount + '" value="" >' +
        '<textarea rows="1" cols="20" name="cmp_remark[]" id="cmp_remark_' + newCount + '"  ></textarea>' +
        '</div>';
    //content = div_cmp.innerHTML;
    div_cmp.innerHTML = divContent + newText;
} else {
    document.getElementById('div_cmp_' + newCount).innerHTML = '<input type="text" align="top" name="cmp_name[]" id="cmp_name_' + newCount + '" value="" >' +
        '<textarea rows="1" cols="20" name="cmp_remark[]" id="cmp_remark_' + newCount + '"  ></textarea>';
}

document.getElementById('text_count').value = newCount;

}

React.js: Set innerHTML vs dangerouslySetInnerHTML

You can bind to dom directly

<div dangerouslySetInnerHTML={{__html: '<p>First &middot; Second</p>'}}></div>

Best way to clear a PHP array's values

Like Zack said in the comments below you are able to simply re-instantiate it using

$foo = array(); // $foo is still here

If you want something more powerful use unset since it also will clear $foo from the symbol table, if you need the array later on just instantiate it again.

unset($foo); // $foo is gone
$foo = array(); // $foo is here again

Best way to do a PHP switch with multiple values per case?

Version 1 is certainly easier on the eyes, clearer as to your intentions, and easier to add case-conditions to.

I've never tried the second version. In many languages, this wouldn't even compile because each case labels has to evaluate to a constant-expression.

How do I use hexadecimal color strings in Flutter?

The Color class expects an ARGB integer. Since you try to use it with RGB value, represent it as int and prefix it with 0xff.

Color mainColor = Color(0xffb74093);

If you get annoyed by this and still wish to use strings, you can extend Color and add a string constructor

class HexColor extends Color {
  static int _getColorFromHex(String hexColor) {
    hexColor = hexColor.toUpperCase().replaceAll("#", "");
    if (hexColor.length == 6) {
      hexColor = "FF" + hexColor;
    }
    return int.parse(hexColor, radix: 16);
  }

  HexColor(final String hexColor) : super(_getColorFromHex(hexColor));
}

usage

Color color1 = HexColor("b74093");
Color color2 = HexColor("#b74093");
Color color3 = HexColor("#88b74093"); // if you wish to use ARGB format

OnClick Send To Ajax

<textarea name='Status'> </textarea>
<input type='button' value='Status Update'>

You have few problems with your code like using . for concatenation

Try this -

$(function () {
    $('input').on('click', function () {
        var Status = $(this).val();
        $.ajax({
            url: 'Ajax/StatusUpdate.php',
            data: {
                text: $("textarea[name=Status]").val(),
                Status: Status
            },
            dataType : 'json'
        });
    });
});

PHP CURL DELETE request

To call GET,POST,DELETE,PUT All kind of request, i have created one common function

function CallAPI($method, $api, $data) {
    $url = "http://localhost:82/slimdemo/RESTAPI/" . $api;
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    switch ($method) {
        case "GET":
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
            break;
        case "POST":
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
            break;
        case "DELETE":
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); 
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            break;
    }
    $response = curl_exec($curl);
    $data = json_decode($response);

    /* Check for 404 (file not found). */
    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    // Check the HTTP Status code
    switch ($httpCode) {
        case 200:
            $error_status = "200: Success";
            return ($data);
            break;
        case 404:
            $error_status = "404: API Not found";
            break;
        case 500:
            $error_status = "500: servers replied with an error.";
            break;
        case 502:
            $error_status = "502: servers may be down or being upgraded. Hopefully they'll be OK soon!";
            break;
        case 503:
            $error_status = "503: service unavailable. Hopefully they'll be OK soon!";
            break;
        default:
            $error_status = "Undocumented error: " . $httpCode . " : " . curl_error($curl);
            break;
    }
    curl_close($curl);
    echo $error_status;
    die;
}

CALL Delete Method

$data = array('id'=>$_GET['did']);
$result = CallAPI('DELETE', "DeleteCategory", $data);

CALL Post Method

$data = array('title'=>$_POST['txtcategory'],'description'=>$_POST['txtdesc']);
$result = CallAPI('POST', "InsertCategory", $data);

CALL Get Method

$data = array('id'=>$_GET['eid']);
$result = CallAPI('GET', "GetCategoryById", $data);

CALL Put Method

$data = array('id'=>$_REQUEST['eid'],m'title'=>$_REQUEST['txtcategory'],'description'=>$_REQUEST['txtdesc']);
$result = CallAPI('POST', "UpdateCategory", $data);

How to get the previous url using PHP

But you could make an own link for every from url.

Example: http://example.com?auth=holasite

In this example your site is: example.com

If somebody open that link it's give you the holasite value for the auth variable.

Then just $_GET['auth'] and you have the variable. But you should have a database to store it, and to authorize.

Like: $holasite = http://holasite.com (You could use mysql too..)

And just match it, and you have the url.

This method is a little bit more complicated, but it works. This method is good for a referral system authentication. But where is the site name, you should write an id, and works with that id.

How to represent matrices in python

Take a look at this answer:

from numpy import matrix
from numpy import linalg
A = matrix( [[1,2,3],[11,12,13],[21,22,23]]) # Creates a matrix.
x = matrix( [[1],[2],[3]] )                  # Creates a matrix (like a column vector).
y = matrix( [[1,2,3]] )                      # Creates a matrix (like a row vector).
print A.T                                    # Transpose of A.
print A*x                                    # Matrix multiplication of A and x.
print A.I                                    # Inverse of A.
print linalg.solve(A, x)     # Solve the linear equation system.

Concatenating strings doesn't work as expected

std::string a = "Hello ";
a += "World";

What's the HTML to have a horizontal space between two objects?

CSS

div.horizontalgap {
  float: left;
  overflow: hidden;
  height: 1px;
  width: 0px;
}

Usage in HTML (for a 10px horizontal gap)

<div class="horizontalgap" style="width:10px"></div>

How to read single Excel cell value

 //THIS IS WORKING CODE                        
 Microsoft.Office.Interop.Excel.Range Range_Number,r2;
 Range_Number = wsheet.UsedRange.Find("smth");
 string f_number="";

 r2 = wsheet.Cells;

 int n_c = Range_Number.Column;
 int n_r = Range_Number.Row;
 var number = ((Range)r2[n_r + 1, n_c]).Value;

 f_number = (string)number;

Test whether string is a valid integer

For portability to pre-Bash 3.1 (when the =~ test was introduced), use expr.

if expr "$string" : '-\?[0-9]\+$' >/dev/null
then
  echo "String is a valid integer."
else
  echo "String is not a valid integer."
fi

expr STRING : REGEX searches for REGEX anchored at the start of STRING, echoing the first group (or length of match, if none) and returning success/failure. This is old regex syntax, hence the excess \. -\? means "maybe -", [0-9]\+ means "one or more digits", and $ means "end of string".

Bash also supports extended globs, though I don't recall from which version onwards.

shopt -s extglob
case "$string" of
    @(-|)[0-9]*([0-9]))
        echo "String is a valid integer." ;;
    *)
        echo "String is not a valid integer." ;;
esac

# equivalently, [[ $string = @(-|)[0-9]*([0-9])) ]]

@(-|) means "- or nothing", [0-9] means "digit", and *([0-9]) means "zero or more digits".

Calling a Variable from another Class

You need to specify an access modifier for your variable. In this case you want it public.

public class Variables
{
    public static string name = "";
}

After this you can use the variable like this.

Variables.name

Assignment makes pointer from integer without cast

  • 1) Don't use gets! You're introducing a buffer-overflow vulnerability. Use fgets(..., stdin) instead.

  • 2) In strToLower you're returning a char instead of a char-array. Either return char* as Autopulated suggested, or just return void since you're modifying the input anyway. As a result, just write

 

 strToLower(cString1);
 strToLower(cString2);
  • 3) To compare case-insensitive strings, you can use strcasecmp (Linux & Mac) or stricmp (Windows).

How to print a percentage value in python?

Then you'd want to do this instead:

print str(int(1.0/3.0*100))+'%'

The .0 denotes them as floats and int() rounds them to integers afterwards again.

git stash apply version

Just making simple to understand for beginners.

Check your git stash list with below command :

git stash list

And then apply with below command:

git stash apply stash@{n}

For example: I am applying my latest stash(latest is always index {0} on top of the stash list).

 git stash apply stash@{0}

FileNotFoundException while getting the InputStream object from HttpURLConnection

To anyone with this problem in the future, the reason is because the status code was a 404 (or in my case was a 500). It appears the InpuStream function will throw an error when the status code is not 200.

In my case I control my own server and was returning a 500 status code to indicate an error occurred. Despite me also sending a body with a string message detailing the error, the inputstream threw an error regardless of the body being completely readable.

If you control your server I suppose this can be handled by sending yourself a 200 status code and then handling whatever the string error response was.

Convert datetime to Unix timestamp and convert it back in python

If your datetime object represents UTC time, don't use time.mktime, as it assumes the tuple is in your local timezone. Instead, use calendar.timegm:

>>> import datetime, calendar
>>> d = datetime.datetime(1970, 1, 1, 0, 1, 0)
>>> calendar.timegm(d.timetuple())
60

What are the differences between Mustache.js and Handlebars.js?

I feel that one of the mentioned cons for "Handlebars" isnt' really valid anymore.

Handlebars.java now allows us to share the same template languages for both client and server which is a big win for large projects with 1000+ components that require serverside rendering for SEO

Take a look at https://github.com/jknack/handlebars.java

Import Excel Spreadsheet Data to an EXISTING sql table?

Saudate, I ran across this looking for a different problem. You most definitely can use the Sql Server Import wizard to import data into a new table. Of course, you do not wish to leave that table in the database, so my suggesting is that you import into a new table, then script the data in query manager to insert into the existing table. You can add a line to drop the temp table created by the import wizard as the last step upon successful completion of the script.

I believe your original issue is in fact related to Sql Server 64 bit and is due to your having a 32 bit Excel and these drivers don't play well together. I did run into a very similar issue when first using 64 bit excel.

ES6 modules in the browser: Uncaught SyntaxError: Unexpected token import

Many modern browsers now support ES6 modules. As long as you import your scripts (including the entrypoint to your application) using <script type="module" src="..."> it will work.

Take a look at caniuse.com for more details: https://caniuse.com/#feat=es6-module

change figure size and figure format in matplotlib

The first part (setting the output size explictly) isn't too hard:

import matplotlib.pyplot as plt
list1 = [3,4,5,6,9,12]
list2 = [8,12,14,15,17,20]
fig = plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
ax.plot(list1, list2)
fig.savefig('fig1.png', dpi = 300)
fig.close()

But after a quick google search on matplotlib + tiff, I'm not convinced that matplotlib can make tiff plots. There is some mention of the GDK backend being able to do it.

One option would be to convert the output with a tool like imagemagick's convert.

(Another option is to wait around here until a real matplotlib expert shows up and proves me wrong ;-)

How can you encode a string to Base64 in JavaScript?

Please note that this is not suitable for raw Unicode strings! See Unicode section here.

Syntax for encoding

var encodedData = window.btoa(stringToEncode);

Syntax for decoding

var decodedData = window.atob(encodedData);

PHPExcel Make first row bold

Assuming headers are on the first row of the sheet starting at A1, and you know how many of them there are, this was my solution:

$header = array(
    'Header 1',
    'Header 2'
);

$objPHPExcel = new PHPExcel();
$objPHPExcelSheet = $objPHPExcel->getSheet(0);
$objPHPExcelSheet->fromArray($header, NULL);
$first_letter = PHPExcel_Cell::stringFromColumnIndex(0);
$last_letter = PHPExcel_Cell::stringFromColumnIndex(count($header)-1);
$header_range = "{$first_letter}1:{$last_letter}1";
$objPHPExcelSheet->getStyle($header_range)->getFont()->setBold(true);

Bootstrap 3 collapse accordion: collapse all works but then cannot expand all while maintaining data-parent

For whatever reason $('.panel-collapse').collapse({'toggle': true, 'parent': '#accordion'}); only seems to work the first time and it only works to expand the collapsible. (I tried to start with a expanded collapsible and it wouldn't collapse.)

It could just be something that runs once the first time you initialize collapse with those parameters.

You will have more luck using the show and hide methods.

Here is an example:

$(function() {

  var $active = true;

  $('.panel-title > a').click(function(e) {
    e.preventDefault();
  });

  $('.collapse-init').on('click', function() {
    if(!$active) {
      $active = true;
      $('.panel-title > a').attr('data-toggle', 'collapse');
      $('.panel-collapse').collapse('hide');
      $(this).html('Click to disable accordion behavior');
    } else {
      $active = false;
      $('.panel-collapse').collapse('show');
      $('.panel-title > a').attr('data-toggle','');
      $(this).html('Click to enable accordion behavior');
    }
  });

});

http://bootply.com/98201

Update

Granted KyleMit seems to have a way better handle on this then me. I'm impressed with his answer and understanding.

I don't understand what's going on or why the show seemed to be toggling in some places.

But After messing around for a while.. Finally came with the following solution:

$(function() {
  var transition = false;
  var $active = true;

  $('.panel-title > a').click(function(e) {
    e.preventDefault();
  });

  $('#accordion').on('show.bs.collapse',function(){
    if($active){
        $('#accordion .in').collapse('hide');
    }
  });

  $('#accordion').on('hidden.bs.collapse',function(){
    if(transition){
        transition = false;
        $('.panel-collapse').collapse('show');
    }
  });

  $('.collapse-init').on('click', function() {
    $('.collapse-init').prop('disabled','true');
    if(!$active) {
      $active = true;
      $('.panel-title > a').attr('data-toggle', 'collapse');
      $('.panel-collapse').collapse('hide');
      $(this).html('Click to disable accordion behavior');
    } else {
      $active = false;
      if($('.panel-collapse.in').length){
        transition = true;
        $('.panel-collapse.in').collapse('hide');       
      }
      else{
        $('.panel-collapse').collapse('show');
      }
      $('.panel-title > a').attr('data-toggle','');
      $(this).html('Click to enable accordion behavior');
    }
    setTimeout(function(){
        $('.collapse-init').prop('disabled','');
    },800);
  });
});

http://bootply.com/98239

TCPDF output without saving file

This is what I found out in the documentation.

  • I : send the file inline to the browser (default). The plug-in is used if available. The name given by name is used when one selects the "Save as" option on the link generating the PDF.
  • D : send to the browser and force a file download with the name given by name.
  • F : save to a local server file with the name given by name.
  • S : return the document as a string (name is ignored).
  • FI : equivalent to F + I option
  • FD : equivalent to F + D option
  • E : return the document as base64 mime multi-part email attachment (RFC 2045)

Does Python's time.time() return the local or UTC timestamp?

There is no such thing as an "epoch" in a specific timezone. The epoch is well-defined as a specific moment in time, so if you change the timezone, the time itself changes as well. Specifically, this time is Jan 1 1970 00:00:00 UTC. So time.time() returns the number of seconds since the epoch.

how to use getSharedPreferences in android

After reading around alot, only this worked: In class to set Shared preferences:

 SharedPreferences userDetails = getApplicationContext().getSharedPreferences("test", MODE_PRIVATE);
                    SharedPreferences.Editor edit = userDetails.edit();
                    edit.clear();
                    edit.putString("test1", "1");
                    edit.putString("test2", "2");
                    edit.commit();

In AlarmReciever:

SharedPreferences userDetails = context.getSharedPreferences("test", Context.MODE_PRIVATE);
    String test1 = userDetails.getString("test1", "");
    String test2 = userDetails.getString("test2", "");

Extract year from date

For some time now, you can also only rely on the data.table package and its IDate class plus associated functions (Check ?as.IDate()). So, no need to additionally install lubridate.

require(data.table)

a <- c("01/01/2009", "01/01/2010" , "01/01/2011")
year(as.IDate(a, '%d/%m/%Y')) # all data.table functions

Input type "number" won't resize

Use an on onkeypress event. Example for a zip code box. It allows a maximum of 5 characters, and checks to make sure input is only numbers.

Nothing beats a server side validation of course, but this is a nifty way to go.

_x000D_
_x000D_
function validInput(e) {_x000D_
  e = (e) ? e : window.event;_x000D_
  a = document.getElementById('zip-code');_x000D_
  cPress = (e.which) ? e.which : e.keyCode;_x000D_
_x000D_
  if (cPress > 31 && (cPress < 48 || cPress > 57)) {_x000D_
    return false;_x000D_
  } else if (a.value.length >= 5) {_x000D_
    return false;_x000D_
  }_x000D_
_x000D_
  return true;_x000D_
}
_x000D_
#zip-code {_x000D_
  overflow: hidden;_x000D_
  width: 60px;_x000D_
}
_x000D_
<label for="zip-code">Zip Code:</label>_x000D_
<input type="number" id="zip-code" name="zip-code" onkeypress="return validInput(event);" required="required">
_x000D_
_x000D_
_x000D_

Creating a 3D sphere in Opengl using Visual C++

It doesn't seem like anyone so far has addressed the actual problem with your original code, so I thought I would do that even though the question is quite old at this point.

The problem originally had to do with the projection in relation to the radius and position of the sphere. I think you'll find that the problem isn't too complicated. The program actually works correctly, it's just that what is being drawn is very hard to see.

First, an orthogonal projection was created using the call

gluOrtho2D(0.0, 499.0, 0.0, 499.0);

which "is equivalent to calling glOrtho with near = -1 and far = 1." This means that the viewing frustum has a depth of 2. So a sphere with a radius of anything greater than 1 (diameter = 2) will not fit entirely within the viewing frustum.

Then the calls

glLoadIdentity();
glutSolidSphere(5.0, 20.0, 20.0);

are used, which loads the identity matrix of the model-view matrix and then "[r]enders a sphere centered at the modeling coordinates origin of the specified radius." Meaning, the sphere is rendered at the origin, (x, y, z) = (0, 0, 0), and with a radius of 5.

Now, the issue is three-fold:

  1. Since the window is 500x500 pixels and the width and height of the viewing frustum is almost 500 (499.0), the small radius of the sphere (5.0) makes its projected area only slightly over one fiftieth (2*5/499) of the size of the window in each dimension. This means that the apparent size of the sphere would be roughly 1/2,500th (actually pi*5^2/499^2, which is closer to about 1/3170th) of the entire window, so it might be difficult to see. This is assuming the entire circle is drawn within the area of the window. It is not, however, as we will see in point 2.
  2. Since the viewing frustum has it's left plane at x = 0 and bottom plane at y = 0, the sphere will be rendered with its geometric center in the very bottom left corner of the window so that only one quadrant of the projected sphere will be visible! This means that what would be seen is even smaller, about 1/10,000th (actually pi*5^2/(4*499^2), which is closer to 1/12,682nd) of the window size. This would make it even more difficult to see. Especially since the sphere is rendered so close to the edges/corner of the screen where you might not think to look.
  3. Since the depth of the viewing frustum is significantly smaller than the diameter of the sphere (less than half), only a sliver of the sphere will be within the viewing frustum, rendering only that part. So you will get more like a hollow circle on the screen than a solid sphere/circle. As it happens, the thickness of that sliver might represent less than 1 pixel on the screen which means we might even see nothing on the screen, even if part of the sphere is indeed within the viewing frustum.

The solution is simply to change the viewing frustum and radius of the sphere. For instance,

gluOrtho2D(-5.0, 5.0, -5.0, 5.0);
glutSolidSphere(5.0, 20, 20);

renders the following image.

r = 5.0

As you can see, only a small part is visible around the "equator", of the sphere with a radius of 5. (I changed the projection to fill the window with the sphere.) Another example,

gluOrtho2D(-1.1, 1.1, -1.1, 1.1);
glutSolidSphere(1.1, 20, 20);

renders the following image.

r = 1.1

The image above shows more of the sphere inside of the viewing frustum, but still the sphere is 0.2 depth units larger than the viewing frustum. As you can see, the "ice caps" of the sphere are missing, both the north and the south. So, if we want the entire sphere to fit within the viewing frustum which has depth 2, we must make the radius less than or equal to 1.

gluOrtho2D(-1.0, 1.0, -1.0, 1.0);
glutSolidSphere(1.0, 20, 20);

renders the following image.

r = 1.0

I hope this has helped someone. Take care!

How to forcefully set IE's Compatibility Mode off from the server-side?

Changing my header to the following solve the problem:

<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

How can I access getSupportFragmentManager() in a fragment?

getActivity().getFragmentManager() This worked or me.

Also take a look at here.

How to convert ActiveRecord results into an array of hashes

as_json

You should use as_json method which converts ActiveRecord objects to Ruby Hashes despite its name

tasks_records = TaskStoreStatus.all
tasks_records = tasks_records.as_json

# You can now add new records and return the result as json by calling `to_json`

tasks_records << TaskStoreStatus.last.as_json
tasks_records << { :task_id => 10, :store_name => "Koramanagala", :store_region => "India" }
tasks_records.to_json

serializable_hash

You can also convert any ActiveRecord objects to a Hash with serializable_hash and you can convert any ActiveRecord results to an Array with to_a, so for your example :

tasks_records = TaskStoreStatus.all
tasks_records.to_a.map(&:serializable_hash)

And if you want an ugly solution for Rails prior to v2.3

JSON.parse(tasks_records.to_json) # please don't do it

xpath find if node exists

I work in Ruby and using Nokogiri I fetch the element and look to see if the result is nil.

require 'nokogiri'

url = "http://somthing.com/resource"

resp = Nokogiri::XML(open(url))

first_name = resp.xpath("/movies/actors/actor[1]/first-name")

puts "first-name not found" if first_name.nil?

How to style components using makeStyles and still have lifecycle methods in Material UI?

useStyles is a React hook which are meant to be used in functional components and can not be used in class components.

From React:

Hooks let you use state and other React features without writing a class.

Also you should call useStyles hook inside your function like;

function Welcome() {
  const classes = useStyles();
...

If you want to use hooks, here is your brief class component changed into functional component;

import React from "react";
import { Container, makeStyles } from "@material-ui/core";

const useStyles = makeStyles({
  root: {
    background: "linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)",
    border: 0,
    borderRadius: 3,
    boxShadow: "0 3px 5px 2px rgba(255, 105, 135, .3)",
    color: "white",
    height: 48,
    padding: "0 30px"
  }
});

function Welcome() {
  const classes = useStyles();
  return (
    <Container className={classes.root}>
      <h1>Welcome</h1>
    </Container>
  );
}

export default Welcome;

on ↓ CodeSandBox ↓

Edit React hooks

How to compare two List<String> to each other?

If you want to check that the elements inside the list are equal and in the same order, you can use SequenceEqual:

if (a1.SequenceEqual(a2))

See it working online: ideone

Apache 2.4.3 (with XAMPP 1.8.1) not starting in windows 8

I had the exact same error.

It was because i didn't run setup_xampp.bat

This is a better solution than going through config files and changing ports.

Fastest way to find second (third...) highest/lowest value in vector or column

This will find the index of the N'th smallest or largest value in the input numeric vector x. Set bottom=TRUE in the arguments if you want the N'th from the bottom, or bottom=FALSE if you want the N'th from the top. N=1 and bottom=TRUE is equivalent to which.min, N=1 and bottom=FALSE is equivalent to which.max.

FindIndicesBottomTopN <- function(x=c(4,-2,5,-77,99),N=1,bottom=FALSE)
{

  k1 <- rank(x)
  if(bottom==TRUE){
    Nindex <- which(k1==N)
    Nindex <- Nindex[1]
  }

  if(bottom==FALSE){
    Nindex <- which(k1==(length(x)+1-N))
    Nindex <- Nindex[1]
  }

  return(Nindex)
}

Android: Create a toggle button with image and no text

  1. Can I replace the toggle text with an image

    No, we can not, although we can hide the text by overiding the default style of the toggle button, but still that won't give us a toggle button you want as we can't replace the text with an image.

  2. How can I make a normal toggle button

    Create a file ic_toggle in your res/drawable folder

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    
        <item android:state_checked="false"
              android:drawable="@drawable/ic_slide_switch_off" />
    
        <item android:state_checked="true"
              android:drawable="@drawable/ic_slide_switch_on" />
    
    </selector>
    

    Here @drawable/ic_slide_switch_on & @drawable/ic_slide_switch_off are images you create.

    Then create another file in the same folder, name it ic_toggle_bg

    <?xml version="1.0" encoding="utf-8"?>
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    
        <item android:id="@+android:id/background"  
              android:drawable="@android:color/transparent" />
    
        <item android:id="@+android:id/toggle"
              android:drawable="@drawable/ic_toggle" />
    
    </layer-list>
    

    Now add to your custom theme, (if you do not have one create a styles.xml file in your res/values/folder)

    <style name="Widget.Button.Toggle" parent="android:Widget">
       <item name="android:background">@drawable/ic_toggle_bg</item>
       <item name="android:disabledAlpha">?android:attr/disabledAlpha</item>
    </style>
    
    <style name="toggleButton"  parent="@android:Theme.Black">
       <item name="android:buttonStyleToggle">@style/Widget.Button.Toggle</item>
       <item name="android:textOn"></item>
       <item name="android:textOff"></item>
    </style>
    

    This creates a custom toggle button for you.

  3. How to use it

    Use the custom style and background in your view.

      <ToggleButton
            android:id="@+id/toggleButton"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="right"
            style="@style/toggleButton"
            android:background="@drawable/ic_toggle_bg"/>
    

How to add google-play-services.jar project dependency so my project will run and present map

Be Careful, Follow these steps and save your time

  1. Right Click on your Project Explorer.

  2. Select New-> Project -> Android Application Project from Existing Code

  3. Browse upto this path only - "C:\Users**your path**\Local\Android\android-sdk\extras\google\google_play_services"

  4. Be careful brose only upto - google_play_services and not upto google_play_services_lib

  5. And this way you are able to import the google play service lib.

Let me know if you have any queries regarding the same.

Thanks

Adding images to an HTML document with javascript

Things to ponder:

  1. Use jquery
  2. Which this is your code refering to
  3. Isnt getElementById usually document.getElementById?
  4. If the image is not found, are you sure your browser would tell you?

What are the advantages and disadvantages of recursion?

Recursion gets a bad rep, I'm always surprised by the number of developers that wont even touch recursion because someone told them it was evil incarnate.

I've learned through trial and error that when done properly recursion can be one of the fastest ways to iterate over something, it is not a steadfast rule and each language/ compiler/ engine has it's own quirks so mileage will vary.

In javascript I can reliably speed up almost any iterative process by introducing recursion with the added benefit of reducing side effects and making the code more clear concise and reusable. Also pro tip its possible to get around the stack overflow issue (and no you dont disable the warning).

My personal Pros & Cons:

Pros:

- Reduces side effects.
- Makes code more concise and easier to reason about.
- Reduces system resource usage and performs better than the traditional for loop.

Cons:

- Can lead to stack overflow.
- More complicated to setup than a traditional for loop.

Mileage will vary depending on language/ complier/ engine.

what is the difference between ajax and jquery and which one is better?

AJAX is a way of sending information between browser and server without refreshing page. It can be done with or without library like jQuery.

It is easier with the library.

Here is a list of JavaScript libraries/frameworks commonly used in AJAX development.

fork: retry: Resource temporarily unavailable

Another possibility is too many threads. We just ran into this error message when running a test harness against an app that uses a thread pool. We used

watch -n 5 -d "ps -eL <java_pid> | wc -l"

to watch the ongoing count of Linux native threads running within the given Java process ID. After this hit about 1,000 (for us--YMMV), we started getting the error message you mention.

How to insert a value that contains an apostrophe (single quote)?

Escape the apostrophe (i.e. double-up the single quote character) in your SQL:

INSERT INTO Person
    (First, Last)
VALUES
    ('Joe', 'O''Brien')
              /\
          right here  

The same applies to SELECT queries:

SELECT First, Last FROM Person WHERE Last = 'O''Brien'

The apostrophe, or single quote, is a special character in SQL that specifies the beginning and end of string data. This means that to use it as part of your literal string data you need to escape the special character. With a single quote this is typically accomplished by doubling your quote. (Two single quote characters, not double-quote instead of a single quote.)

Note: You should only ever worry about this issue when you manually edit data via a raw SQL interface since writing queries outside of development and testing should be a rare occurrence. In code there are techniques and frameworks (depending on your stack) that take care of escaping special characters, SQL injection, etc.

Trim Whitespaces (New Line and Tab space) in a String in Oracle

TRANSLATE (column_name, 'd'||CHR(10)||CHR(13), 'd')

The 'd' is a dummy character, because translate does not work if the 3rd parameter is null.

Where can I download Spring Framework jars without using Maven?

Please edit to keep this list of mirrors current

I found this maven repo where you could download from directly a zip file containing all the jars you need.

Alternate solution: Maven

The solution I prefer is using Maven, it is easy and you don't have to download each jar alone. You can do it with the following steps:

  1. Create an empty folder anywhere with any name you prefer, for example spring-source

  2. Create a new file named pom.xml

  3. Copy the xml below into this file

  4. Open the spring-source folder in your console

  5. Run mvn install

  6. After download finished, you'll find spring jars in /spring-source/target/dependencies

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>spring-source-download</groupId>
      <artifactId>SpringDependencies</artifactId>
      <version>1.0</version>
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
      <dependencies>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>3.2.4.RELEASE</version>
        </dependency>
      </dependencies>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.8</version>
            <executions>
              <execution>
                <id>download-dependencies</id>
                <phase>generate-resources</phase>
                <goals>
                  <goal>copy-dependencies</goal>
                </goals>
                <configuration>
                  <outputDirectory>${project.build.directory}/dependencies</outputDirectory>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </project>
    

Also, if you need to download any other spring project, just copy the dependency configuration from its corresponding web page.

For example, if you want to download Spring Web Flow jars, go to its web page, and add its dependency configuration to the pom.xml dependencies, then run mvn install again.

<dependency>
  <groupId>org.springframework.webflow</groupId>
  <artifactId>spring-webflow</artifactId>
  <version>2.3.2.RELEASE</version>
</dependency>

Use URI builder in Android or create URL with variables

You can do that with lambda expressions;

    private static final String BASE_URL = "http://api.example.org/data/2.5/forecast/daily";

    private String getBaseUrl(Map<String, String> params) {
        final Uri.Builder builder = Uri.parse(BASE_URL).buildUpon();
        params.entrySet().forEach(entry -> builder.appendQueryParameter(entry.getKey(), entry.getValue()));
        return builder.build().toString();
    }

and you can create params like that;

    Map<String, String> params = new HashMap<String, String>();
    params.put("zip", "94043,us");
    params.put("units", "metric");

Btw. If you will face any issue like “lambda expressions not supported at this language level”, please check this URL;

https://stackoverflow.com/a/22704620/2057154

Dropping connected users in Oracle database

Basically I believe that killing all sessions should be the solution, but...

I found similar discussion - https://community.oracle.com/thread/1054062 to my problem and that was I had no sessions for that users, but I still received the error. I tried also second the best answer:

sql>Shutdown immediate;

sql>startup restrict;

sql>drop user TEST cascade;

What worked for me at the end was to login as the user, drop all tables manually - select for creating drop statements is

select 'drop table ' || TABLE_NAME || ';'  from user_tables;

(Needs to be re-run several times because of references)

I have no idea how is that related, I dropped also functions and sequences (because that was all I had in schema)

When I did that and I logged off, I had several sessions in v$session table and when I killed those I was able to drop user.

My DB was still started in restricted mode (not sure if important or not).

Might help someone else.

BTW: my Oracle version is Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production

Test if string is a number in Ruby on Rails

Create is_number? Method.

Create a helper method:

def is_number? string
  true if Float(string) rescue false
end

And then call it like this:

my_string = '12.34'

is_number?( my_string )
# => true

Extend String Class.

If you want to be able to call is_number? directly on the string instead of passing it as a param to your helper function, then you need to define is_number? as an extension of the String class, like so:

class String
  def is_number?
    true if Float(self) rescue false
  end
end

And then you can call it with:

my_string.is_number?
# => true

can't start MySql in Mac OS 10.6 Snow Leopard

snow leopard is different to the "old" leopard therefore its not surprising that the sources won' work... you should probably wait till the official release on friday and oracle might be releasing a properly working sql version soon.

In Java, how can I determine if a char array contains a particular character?

The following snippets test for the "not contains" condition, as exemplified in the sample pseudocode in the question. For a direct solution with explicit looping, do this:

boolean contains = false;
for (char c : charArray) {
    if (c == 'q') {
        contains = true;
        break;
    }
}
if (!contains) {
    // do something
}

Another alternative, using the fact that String provides a contains() method:

if (!(new String(charArray).contains("q"))) {
    // do something
}

Yet another option, this time using indexOf():

if (new String(charArray).indexOf('q') == -1) {
    // do something
}

What is the correct way to restore a deleted file from SVN?

You should be able to just check out the one file you want to restore. Try something like svn co svn://your_repos/path/to/file/you/want/to/restore@rev where rev is the last revision at which the file existed.

I had to do exactly this a little while ago and if I remember correctly, using the -r option to svn didn't work; I had to use the :rev syntax. (Although I might have remembered it backwards...)

HTTP Request in Swift with POST method

All the answers here use JSON objects. This gave us problems with the $this->input->post() methods of our Codeigniter controllers. The CI_Controller cannot read JSON directly. We used this method to do it WITHOUT JSON

func postRequest() {
    // Create url object
    guard let url = URL(string: yourURL) else {return}

    // Create the session object
    let session = URLSession.shared

    // Create the URLRequest object using the url object
    var request = URLRequest(url: url)

    // Set the request method. Important Do not set any other headers, like Content-Type
    request.httpMethod = "POST" //set http method as POST

    // Set parameters here. Replace with your own.
    let postData = "param1_id=param1_value&param2_id=param2_value".data(using: .utf8)
    request.httpBody = postData

    // Create a task using the session object, to run and return completion handler
    let webTask = session.dataTask(with: request, completionHandler: {data, response, error in
    guard error == nil else {
        print(error?.localizedDescription ?? "Response Error")
        return
    }
    guard let serverData = data else {
        print("server data error")
        return
    }
    do {
        if let requestJson = try JSONSerialization.jsonObject(with: serverData, options: .mutableContainers) as? [String: Any]{
            print("Response: \(requestJson)")
        }
    } catch let responseError {
        print("Serialisation in error in creating response body: \(responseError.localizedDescription)")
        let message = String(bytes: serverData, encoding: .ascii)
        print(message as Any)
    }

    // Run the task
    webTask.resume()
}

Now your CI_Controller will be able to get param1 and param2 using $this->input->post('param1') and $this->input->post('param2')

What does 'corrupted double-linked list' mean

Heap overflow should be blame (but not always) for corrupted double-linked list, malloc(): memory corruption, double free or corruption (!prev)-like glibc warnings.

It should be reproduced by the following code:

#include <vector>

using std::vector;


int main(int argc, const char *argv[])
{
    int *p = new int[3];
    vector<int> vec;
    vec.resize(100);
    p[6] = 1024;
    delete[] p;
    return 0;
}

if compiled using g++ (4.5.4):

$ ./heapoverflow
*** glibc detected *** ./heapoverflow: double free or corruption (!prev): 0x0000000001263030 ***
======= Backtrace: =========
/lib64/libc.so.6(+0x7af26)[0x7f853f5d3f26]
./heapoverflow[0x40138e]
./heapoverflow[0x400d9c]
./heapoverflow[0x400bd9]
./heapoverflow[0x400aa6]
./heapoverflow[0x400a26]
/lib64/libc.so.6(__libc_start_main+0xfd)[0x7f853f57b4bd]
./heapoverflow[0x4008f9]
======= Memory map: ========
00400000-00403000 r-xp 00000000 08:02 2150398851                         /data1/home/mckelvin/heapoverflow
00602000-00603000 r--p 00002000 08:02 2150398851                         /data1/home/mckelvin/heapoverflow
00603000-00604000 rw-p 00003000 08:02 2150398851                         /data1/home/mckelvin/heapoverflow
01263000-01284000 rw-p 00000000 00:00 0                                  [heap]
7f853f559000-7f853f6fa000 r-xp 00000000 09:01 201329536                  /lib64/libc-2.15.so
7f853f6fa000-7f853f8fa000 ---p 001a1000 09:01 201329536                  /lib64/libc-2.15.so
7f853f8fa000-7f853f8fe000 r--p 001a1000 09:01 201329536                  /lib64/libc-2.15.so
7f853f8fe000-7f853f900000 rw-p 001a5000 09:01 201329536                  /lib64/libc-2.15.so
7f853f900000-7f853f904000 rw-p 00000000 00:00 0
7f853f904000-7f853f919000 r-xp 00000000 09:01 74726670                   /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libgcc_s.so.1
7f853f919000-7f853fb19000 ---p 00015000 09:01 74726670                   /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libgcc_s.so.1
7f853fb19000-7f853fb1a000 r--p 00015000 09:01 74726670                   /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libgcc_s.so.1
7f853fb1a000-7f853fb1b000 rw-p 00016000 09:01 74726670                   /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libgcc_s.so.1
7f853fb1b000-7f853fc11000 r-xp 00000000 09:01 201329538                  /lib64/libm-2.15.so
7f853fc11000-7f853fe10000 ---p 000f6000 09:01 201329538                  /lib64/libm-2.15.so
7f853fe10000-7f853fe11000 r--p 000f5000 09:01 201329538                  /lib64/libm-2.15.so
7f853fe11000-7f853fe12000 rw-p 000f6000 09:01 201329538                  /lib64/libm-2.15.so
7f853fe12000-7f853fefc000 r-xp 00000000 09:01 74726678                   /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libstdc++.so.6.0.18
7f853fefc000-7f85400fb000 ---p 000ea000 09:01 74726678                   /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libstdc++.so.6.0.18
7f85400fb000-7f8540103000 r--p 000e9000 09:01 74726678                   /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libstdc++.so.6.0.18
7f8540103000-7f8540105000 rw-p 000f1000 09:01 74726678                   /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libstdc++.so.6.0.18
7f8540105000-7f854011a000 rw-p 00000000 00:00 0
7f854011a000-7f854013c000 r-xp 00000000 09:01 201328977                  /lib64/ld-2.15.so
7f854031c000-7f8540321000 rw-p 00000000 00:00 0
7f8540339000-7f854033b000 rw-p 00000000 00:00 0
7f854033b000-7f854033c000 r--p 00021000 09:01 201328977                  /lib64/ld-2.15.so
7f854033c000-7f854033d000 rw-p 00022000 09:01 201328977                  /lib64/ld-2.15.so
7f854033d000-7f854033e000 rw-p 00000000 00:00 0
7fff92922000-7fff92943000 rw-p 00000000 00:00 0                          [stack]
7fff929ff000-7fff92a00000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
[1]    18379 abort      ./heapoverflow

and if compiled using clang++(6.0 (clang-600.0.56)):

$  ./heapoverflow
[1]    96277 segmentation fault  ./heapoverflow

If you thought you might have written a bug like that, here is some hints to trace it out.

First, compile the code with debug flag(-g):

g++ -g foo.cpp

And then, run it using valgrind:

$ valgrind ./a.out
==12693== Memcheck, a memory error detector
==12693== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==12693== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==12693== Command: ./a.out
==12693==
==12693== Invalid write of size 4
==12693==    at 0x400A25: main (foo.cpp:11)
==12693==  Address 0x5a1c058 is 12 bytes after a block of size 12 alloc'd
==12693==    at 0x4C2B800: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==12693==    by 0x4009F6: main (foo.cpp:8)
==12693==
==12693==
==12693== HEAP SUMMARY:
==12693==     in use at exit: 0 bytes in 0 blocks
==12693==   total heap usage: 2 allocs, 2 frees, 412 bytes allocated
==12693==
==12693== All heap blocks were freed -- no leaks are possible
==12693==
==12693== For counts of detected and suppressed errors, rerun with: -v
==12693== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

The bug is located in ==12693== at 0x400A25: main (foo.cpp:11)

Why can't I see the "Report Data" window when creating reports?

If the report designer is opened, Report Data Pane can be enabled using view menu.

 View -> Report Data

Javascript: best Singleton pattern

Extending the above post by Tom, if you need a class type declaration and access the singleton instance using a variable, the code below might be of help. I like this notation as the code is little self guiding.

function SingletonClass(){
    if ( arguments.callee.instance )
        return arguments.callee.instance;
    arguments.callee.instance = this;
}


SingletonClass.getInstance = function() {
    var singletonClass = new SingletonClass();
    return singletonClass;
};

To access the singleton, you would

var singleTon = SingletonClass.getInstance();

Android - set TextView TextStyle programmatically?

Kotlin Version

To retain current font in addition to text style:

textView.apply {
    setTypeface(typeface, Typeface.NORMAL)
    // or
    setTypeface(typeface, Typeface.BOLD)
    // or
    setTypeface(typeface, Typeface.ITALIC)
    // or
    setTypeface(typeface, Typeface.BOLD_ITALIC)
}

Remove non-ascii character in string

You can use the following regex to replace non-ASCII characters

str = str.replace(/[^A-Za-z 0-9 \.,\?""!@#\$%\^&\*\(\)-_=\+;:<>\/\\\|\}\{\[\]`~]*/g, '')

However, note that spaces, colons and commas are all valid ASCII, so the result will be

> str
"INFO] :, , ,  (Higashikurume)"

Understanding React-Redux and mapStateToProps()

It's a simple concept. Redux creates a ubiquitous state object (a store) from the actions in the reducers. Like a React component, this state doesn't have to be explicitly coded anywhere, but it helps developers to see a default state object in the reducer file to visualise what is happening. You import the reducer in the component to access the file. Then mapStateToProps selects only the key/value pairs in the store that its component needs. Think of it like Redux creating a global version of a React component's

this.state = ({ 
cats = [], 
dogs = []
})

It is impossible to change the structure of the state by using mapStateToProps(). What you are doing is choosing only the store's key/value pairs that the component needs and passing in the values (from a list of key/values in the store) to the props (local keys) in your component. You do this one value at a time in a list. No structure changes can occur in the process.

P.S. The store is local state. Reducers usually also pass state along to the database with Action Creators getting into the mix, but understand this simple concept first for this specific posting.

P.P.S. It is good practice to separate the reducers into separate files for each one and only import the reducer that the component needs.

What is recursion and when should I use it?

In plain English: Assume you can do 3 things:

  1. Take one apple
  2. Write down tally marks
  3. Count tally marks

You have a lot of apples in front of you on a table and you want to know how many apples there are.

start
  Is the table empty?
  yes: Count the tally marks and cheer like it's your birthday!
  no:  Take 1 apple and put it aside
       Write down a tally mark
       goto start

The process of repeating the same thing till you are done is called recursion.

I hope this is the "plain english" answer you are looking for!

Cannot invoke an expression whose type lacks a call signature

Perhaps create a shared Fruit interface that provides isDecayed. fruits is now of type Fruit[] so the type can be explicit. Like this:

interface Fruit {
    isDecayed: boolean;
}

interface Apple extends Fruit {
    color: string;
}

interface Pear extends Fruit {
    weight: number;
}

interface FruitBasket {
    apples: Apple[];
    pears: Pear[];
}


const fruitBasket: FruitBasket = { apples: [], pears: [] };
const key: keyof FruitBasket = Math.random() > 0.5 ? 'apples': 'pears'; 
const fruits: Fruit[] = fruitBasket[key];

const freshFruits = fruits.filter((fruit) => !fruit.isDecayed);

DNS problem, nslookup works, ping doesn't

I think this behavior can be turned off, but Window's online help wasn't extremely clear:

If you disable NetBIOS over TCP/IP, you cannot use broadcast-based NetBIOS name resolution to resolve computer names to IP addresses for computers on the same network segment. If your computers are on the same network segment, and NetBIOS over TCP/IP is disabled, you must install a DNS server and either have the computers register with DNS (or manually configure DNS records) or configure entries in the local Hosts file for each computer.

In Windows XP, there is a checkbox:

Advanced TCP/IP Settings

[ ] Enable LMHOSTS lookup

There is also a book that covers this at length, "Networking Personal Computers with TCP/IP: Building TCP/IP Networks (old O'Reilly book)". Unfortunately, I cannot look it up because I disposed of my copy a while ago.

AngularJS: ng-repeat list is not updated when a model element is spliced from the model array

There's an easy way to do that. Very easy. Since I noticed that

$scope.yourModel = [];

removes all $scope.yourModel array list you can do like this

function deleteAnObjectByKey(objects, key) {
    var clonedObjects = Object.assign({}, objects);

     for (var x in clonedObjects)
        if (clonedObjects.hasOwnProperty(x))
             if (clonedObjects[x].id == key)
                 delete clonedObjects[x];

    $scope.yourModel = clonedObjects;
}

The $scope.yourModel will be updated with the clonedObjects.

Hope that helps.

Pass parameter to EventHandler

If I understand your problem correctly, you are calling a method instead of passing it as a parameter. Try the following:

myTimer.Elapsed += PlayMusicEvent;

where

public void PlayMusicEvent(object sender, ElapsedEventArgs e)
{
    music.player.Stop();
    System.Timers.Timer myTimer = (System.Timers.Timer)sender;
    myTimer.Stop();
}

But you need to think about where to store your note.

How can I add a variable to console.log?

You can use the backslash to include both the story and the players name in one line.

var name=prompt("what is your name?"); console.log("story"\name\"story");

Conversion between UTF-8 ArrayBuffer and String

function stringToUint(string) {
    var string = btoa(unescape(encodeURIComponent(string))),
        charList = string.split(''),
        uintArray = [];
    for (var i = 0; i < charList.length; i++) {
        uintArray.push(charList[i].charCodeAt(0));
    }
    return new Uint8Array(uintArray);
}

function uintToString(uintArray) {
    var encodedString = String.fromCharCode.apply(null, uintArray),
        decodedString = decodeURIComponent(escape(atob(encodedString)));
    return decodedString;
}

I have done, with some help from the internet, these little functions, they should solve your problems! Here is the working JSFiddle.

EDIT:

Since the source of the Uint8Array is external and you can't use atob you just need to remove it(working fiddle):

function uintToString(uintArray) {
    var encodedString = String.fromCharCode.apply(null, uintArray),
        decodedString = decodeURIComponent(escape(encodedString));
    return decodedString;
}

Warning: escape and unescape is removed from web standards. See this.

error: No resource identifier found for attribute 'adSize' in package 'com.google.example' main.xml

Replace /res/ with /lib/ in your custom layout nampespace.

xmlns:android="http://schemas.android.com/apk/res/android"

in your case, would be:

xmlns:yourApp="http://schemas.android.com/apk/lib/com.yourAppPackege.yourClass"

I hope it helps.

How to expand 'select' option width after the user wants to select an option

I improved the cychan's solution, to be like that:

<html>
<head>

<style>
    .wrapper{
        display: inline;
        float: left; 
        width: 180px; 
        overflow: hidden; 
    }
    .selectArrow{
        display: inline;
        float: left;
        width: 17px;
        height: 20px;
        border:1px solid #7f9db9;
        border-left: none;
        background: url('selectArrow.png') no-repeat 1px 1px;
    }
    .selectArrow-mousedown{background: url('selectArrow-mousedown.png') no-repeat 1px 1px;}
    .selectArrow-mouseover{background: url('selectArrow-mouseover.png') no-repeat 1px 1px;}
</style>
<script language="javascript" src="jquery-1.3.2.min.js"></script>

<script language="javascript">
    $(document).ready(function(){
        $('#w1').wrap("<div class='wrapper'></div>");
        $('.wrapper').after("<div class='selectArrow'/>");
        $('.wrapper').find('select').mousedown(function(){
            $(this).parent().next().addClass('selectArrow-mousedown').removeClass('selectArrow-mouseover');
        }).
        mouseup(function(){
            $(this).parent().next().removeClass('selectArrow-mousedown').addClass('selectArrow-mouseover');
        }).
        hover(function(){
            $(this).parent().next().addClass('selectArrow-mouseover');
        }, function(){
            $(this).parent().next().removeClass('selectArrow-mouseover');
        });

        $('.selectArrow').click(function(){
            $(this).prev().find('select').focus();
        });

        $('.selectArrow').mousedown(function(){
            $(this).addClass('selectArrow-mousedown').removeClass('selectArrow-mouseover');
        }).
        mouseup(function(){
            $(this).removeClass('selectArrow-mousedown').addClass('selectArrow-mouseover');
        }).
        hover(function(){
            $(this).addClass('selectArrow-mouseover');
        }, function(){
            $(this).removeClass('selectArrow-mouseover');
        });
    });

</script>
</head>
<body>
    <select id="w1">
       <option value="0">AnyAnyAnyAnyAnyAnyAny</option>
       <option value="1">AnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAny</option>
    </select>

</body>
</html>

The PNGs used in css classes are uploaded here...

And you still need JQuery.....

Python popen command. Wait until the command is finished

You can you use subprocess to achieve this.

import subprocess

#This command could have multiple commands separated by a new line \n
some_command = "export PATH=$PATH://server.sample.mo/app/bin \n customupload abc.txt"

p = subprocess.Popen(some_command, stdout=subprocess.PIPE, shell=True)

(output, err) = p.communicate()  

#This makes the wait possible
p_status = p.wait()

#This will give you the output of the command being executed
print "Command output: " + output

Find the smallest positive integer that does not occur in a given sequence

Here is an efficient python solution:

def solution(A):
    m = max(A)
    if m < 1:
       return 1

    A = set(A)
    B = set(range(1, m + 1))
    D = B - A
    if len(D) == 0:
        return m + 1
    else:
        return min(D)

jQuery Scroll To bottom of the page

js

var el = document.getElementById("el");
el.scrollTop = el.scrollHeight - el.scrollTop;

htaccess <Directory> deny from all

You can also use RedirectMatch directive to deny access to a folder.

To deny access to a folder, you can use the following RedirectMatch in htaccess :

 RedirectMatch 403 ^/folder/?$

This will forbid an external access to /folder/ eg : http://example.com/folder/ will return a 403 forbidden error.

To deny access to everything inside the folder, You can use this :

RedirectMatch 403 ^/folder/.*$

This will block access to the entire folder eg : http://example.com/folder/anyURI will return a 403 error response to client.

How to change Git log date formats

I needed the same thing and found the following working for me:

git log -n1 --pretty='format:%cd' --date=format:'%Y-%m-%d %H:%M:%S'

The --date=format formats the date output where the --pretty tells what to print.

How to fill OpenCV image with one solid color?

The simplest is using the OpenCV Mat class:

img=cv::Scalar(blue_value, green_value, red_value);

where img was defined as a cv::Mat.

Python - abs vs fabs

Edit: as @aix suggested, a better (more fair) way to compare the speed difference:

In [1]: %timeit abs(5)
10000000 loops, best of 3: 86.5 ns per loop

In [2]: from math import fabs

In [3]: %timeit fabs(5)
10000000 loops, best of 3: 115 ns per loop

In [4]: %timeit abs(-5)
10000000 loops, best of 3: 88.3 ns per loop

In [5]: %timeit fabs(-5)
10000000 loops, best of 3: 114 ns per loop

In [6]: %timeit abs(5.0)
10000000 loops, best of 3: 92.5 ns per loop

In [7]: %timeit fabs(5.0)
10000000 loops, best of 3: 93.2 ns per loop

In [8]: %timeit abs(-5.0)
10000000 loops, best of 3: 91.8 ns per loop

In [9]: %timeit fabs(-5.0)
10000000 loops, best of 3: 91 ns per loop

So it seems abs() only has slight speed advantage over fabs() for integers. For floats, abs() and fabs() demonstrate similar speed.


In addition to what @aix has said, one more thing to consider is the speed difference:

In [1]: %timeit abs(-5)
10000000 loops, best of 3: 102 ns per loop

In [2]: import math

In [3]: %timeit math.fabs(-5)
10000000 loops, best of 3: 194 ns per loop

So abs() is faster than math.fabs().

Spring Boot War deployed to Tomcat

Hey make sure to do this changes to the pom.xml

<packaging>war</packaging>

in the dependencies section make sure to indicated the tomcat is provided so you dont need the embeded tomcat plugin.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>       

    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>       

This is the whole pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <start-class>com.example.Application</start-class>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>       

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>       

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

And the Application class should be like this

Application.java

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

@SpringBootApplication
public class Application extends SpringBootServletInitializer {


    /**
     * Used when run as JAR
     */
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    /**
     * Used when run as WAR
     */
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(Application.class);
    }

}

And you can add a controller for testing MyController.java

package com.example;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {

    @RequestMapping("/hi")
    public @ResponseBody String hiThere(){
        return "hello world!";
    }
}

Then you can run the project in a tomcat 8 version and access the controller like this

http://localhost:8080/demo/hi

If for some reason you are not able to add the project to tomcat do a right click in the project and then go to the Build Path->configure build path->Project Faces

make sure only this 3 are selected

Dynamic web Module 3.1 Java 1.8 Javascript 1.0

How to determine if a list of polygon points are in clockwise order?

Start at one of the vertices, and compute the angle subtended by each side.

The first and the last will be zero (so skip those); for the rest, the sine of the angle will be given by the cross product of the normalizations to unit length of (point[n]-point[0]) and (point[n-1]-point[0]).

If the sum of the values is positive, then your polygon is drawn in the anti-clockwise sense.

Proxy Error 502 : The proxy server received an invalid response from an upstream server

The HTTP 502 "Bad Gateway" response is generated when Apache web server does not receive a valid HTTP response from the upstream server, which in this case is your Tomcat web application.

Some reasons why this might happen:

  • Tomcat may have crashed
  • The web application did not respond in time and the request from Apache timed out
  • The Tomcat threads are timing out
  • A network device is blocking the request, perhaps as some sort of connection timeout or DoS attack prevention system

If the problem is related to timeout settings, you may be able to resolve it by investigating the following:

  • ProxyTimeout directive of Apache's mod_proxy
  • Connector config of Apache Tomcat
  • Your network device's manual

PostgreSQL: Why psql can't connect to server?

quick howto on debian to remotely access postgres database on server from the psql client: (the changed config is doc'd in the files):

  1. edit /etc/postgresql/10/main/postgresql.conf with listen_address *
  2. edit /etc/postgresql/10/main/pg_hba.conf and add line in the end with host all all 0/0 md5
  3. create login role postgres=# CREATE ROLE remoteuser LOGIN WITH PASSWORD 'foo'
  4. sudo /etc/init.d/postgresql restart changes take effect

  5. login from clientside with psql --host=ipofserver --port=5432 --username=remoteuser --password --dbname=mydb

  6. the password is interactivly asked which in this case is foo

How to get df linux command output always in GB

If you also want it to be a command you can reference without remembering the arguments, you could simply alias it:

alias df-gb='df -BG'

So if you type:

df-gb

into a terminal, you'll get your intended output of the disk usage in GB.

EDIT: or even use just df -h to get it in a standard, human readable format.

http://www.thegeekstuff.com/2012/05/df-examples/

What's the best way to store co-ordinates (longitude/latitude, from Google Maps) in SQL Server?

Take a look at the new Spatial data-types that were introduced in SQL Server 2008. They are designed for this kind of task and make indexing and querying much easier and more efficient.

More information:

Eclipse JUnit - possible causes of seeing "initializationError" in Eclipse window

Junit 4.11 doesn't work with Spring Test framework. Also this link InitializationError When Use Spring + Junit explains how to debug junit initalizationError in eclipse.

How to use 'cp' command to exclude a specific directory?

Expanding on mvds’s comment, this works for me

cd dotfiles
tar -c --exclude .git --exclude README . | tar -x -C ~/dotfiles2

Handling errors in Promise.all

You would need to know how to identify an error in your results. If you do not have a standard expected error, I suggest that you run a transformation on each error in the catch block that makes it identifiable in your results.

try {
  let resArray = await Promise.all(
    state.routes.map(route => route.handler.promiseHandler().catch(e => e))
  );

  // in catch(e => e) you can transform your error to a type or object
  // that makes it easier for you to identify whats an error in resArray
  // e.g. if you expect your err objects to have e.type, you can filter
  // all errors in the array eg
  // let errResponse = resArray.filter(d => d && d.type === '<expected type>')
  // let notNullResponse = resArray.filter(d => d)

  } catch (err) {
    // code related errors
  }

Word wrap for a label in Windows Forms

Have a better one based on @hypo 's answer

public class GrowLabel : Label {
    private bool mGrowing;
    public GrowLabel() {
        this.AutoSize = false;
    }
    private void resizeLabel() {
        if (mGrowing)
            return;
        try {
            mGrowing = true;
            int width = this.Parent == null ? this.Width : this.Parent.Width;

            Size sz = new Size(this.Width, Int32.MaxValue);
            sz = TextRenderer.MeasureText(this.Text, this.Font, sz, TextFormatFlags.WordBreak);
            this.Height = sz.Height + Padding.Bottom + Padding.Top;
        } finally {
            mGrowing = false;
        }
    }
    protected override void OnTextChanged(EventArgs e) {
        base.OnTextChanged(e);
        resizeLabel();
    }
    protected override void OnFontChanged(EventArgs e) {
        base.OnFontChanged(e);
        resizeLabel();
    }
    protected override void OnSizeChanged(EventArgs e) {
        base.OnSizeChanged(e);
        resizeLabel();
    }
}

int width = this.Parent == null ? this.Width : this.Parent.Width; this allows you to use auto-grow label when docked to a parent, e.g. a panel.

this.Height = sz.Height + Padding.Bottom + Padding.Top; here we take care of padding for top and bottom.

AngularJS $http, CORS and http authentication

For making a CORS request one must add headers to the request along with the same he needs to check of mode_header is enabled in Apache.

For enabling headers in Ubuntu:

sudo a2enmod headers

For php server to accept request from different origin use:

Header set Access-Control-Allow-Origin *
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"

How to access the value of a promise?

There are some good answer above and here is the ES6 Arrow function version

var something = async() => {
   let result = await functionThatReturnsPromiseA();
   return result + 1;
}

CURL and HTTPS, "Cannot resolve host"

I had the same problem. Coudn't resolve google.com. There was a bug somewhere in php fpm, which i am using. Restarting php-fpm solved it for me.

Twitter Bootstrap and ASP.NET GridView

Just for the record, I got borders in the table and to get rid of it I needed to set following properties in the GridView:

GridLines="None"
CellSpacing="-1"

tsconfig.json: Build:No inputs were found in config file

This can occur because typescript server can't find any files described by the include array:

// tsconfig.json
{
  //...
  "include": [
    "./src/"
  ],
}

If you're using VSCode, you can restart your TS server within your editor super easily to prompt it to re-evaluate the file like this:

  1. Navigate to any .ts or .tsx file

  2. Open the command palette (CMD + SHIFT + P on mac)

  3. Run the TypeScript: Restart TS server command:

    TypeScript - Restart TS Server

Why isn't this code to plot a histogram on a continuous value Pandas column working?

Here's another way to plot the data, involves turning the date_time into an index, this might help you for future slicing

#convert column to datetime
trip_data['lpep_pickup_datetime'] = pd.to_datetime(trip_data['lpep_pickup_datetime'])
#turn the datetime to an index
trip_data.index = trip_data['lpep_pickup_datetime']
#Plot
trip_data['Trip_distance'].plot(kind='hist')
plt.show()

What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?

The issue as others have stated more elegantly is that you either have a Cartesian product of the OneToMany columns or you're doing N+1 Selects. Either possible gigantic resultset or chatty with the database, respectively.

I'm surprised this isn't mentioned but this how I have gotten around this issue... I make a semi-temporary ids table. I also do this when you have the IN () clause limitation.

This doesn't work for all cases (probably not even a majority) but it works particularly well if you have a lot of child objects such that the Cartesian product will get out of hand (ie lots of OneToMany columns the number of results will be a multiplication of the columns) and its more of a batch like job.

First you insert your parent object ids as batch into an ids table. This batch_id is something we generate in our app and hold onto.

INSERT INTO temp_ids 
    (product_id, batch_id)
    (SELECT p.product_id, ? 
    FROM product p ORDER BY p.product_id
    LIMIT ? OFFSET ?);

Now for each OneToMany column you just do a SELECT on the ids table INNER JOINing the child table with a WHERE batch_id= (or vice versa). You just want to make sure you order by the id column as it will make merging result columns easier (otherwise you will need a HashMap/Table for the entire result set which may not be that bad).

Then you just periodically clean the ids table.

This also works particularly well if the user selects say 100 or so distinct items for some sort of bulk processing. Put the 100 distinct ids in the temporary table.

Now the number of queries you are doing is by the number of OneToMany columns.

Google Maps API v3: InfoWindow not sizing correctly

EDITED (to standout): Trust me, out of the hundred other answers to this question, this is the only correct one that also explains WHY it's happening

Ok, so I know this thread is old, and has a thousand answers, but none of them is correct and I feel the need to post the correct answer.

Firstly, you do not ever need to specify width's or height's on anything in order to get your infoWindow to display without scrollbars, although sometimes you may accidentally get it working by doing this (but it's will eventually fail).

Second, Google Maps API infoWindow's do not have a scrolling bug, it's just very difficult to find the correct information on how they work. Well, here it is:

When you tell the Google Maps API to open in infoWindow like this:

var infoWindow = new google.maps.InfoWindow({...});
....
infoWindow.setContent('<h1>Hello!</h1><p>And welcome to my infoWindow!</p>');
infoWindow.open(map);

For all intents and purposes, google maps temporarily places a div at the end of your page (actually it creates a detached DOM tree - but it's conceptually easier to understand if I say you imagine a div being places at the end of your page) with the HTML content that you specified. It then measures that div (which means that, in this example, whatever CSS rules in my document apply to h1 and p tags will be applied to it) to get it's width and height. Google then takes that div, assigns the measurements to it that it got when it was appended to your page, and places it on the map at the location you specified.

Here's where the problem happens for a lot of people - they may have HTML that looks like this:

<body>
 <div id="map-canvas"><!-- google map goes here --></div>
</body>

and, for whatever reason, CSS that looks like this:

h1 { font-size: 18px; }
#map-canvas h1 { font-size: 32px; }

Can you see the problem? When the API tries to take the measurements for your infoWindow (immediately before displaying it), the h1 part of the content will have a size of 18px (because the temporary "measuring div" is appended to the body), but when the API actually places the infoWindow on the map, the #map-canvas h1 selector will take precedence causing the font size to be much different than what it was when the API measured the size of the infoWindow and in this circumstance you will always get scrollbars.

There may be more slightly different nuances for the specific reason why you have scrollbars in your infoWindow, but the reason behind it is because of this:

The same CSS rules must apply to the content inside your infoWindow regardless of where the actual HTML element appears in the markup. If they do not, then you will be guaranteed to get scrollbars in your infoWindow

So what I always do, is something like this:

infoWindow.setContent('<div class="info-window-content">...your content here...</div>');

and in my CSS:

.info-window-content { ... }
.info-window-content h1 { .... }
.info-window-content p { ... }
etc...

So no matter where the API appends it's measurement div - before the closing body or inside a #map-canvas, the CSS rules applied to it will always be the same.

EDIT RE: Font Families

Google seems to be actively working on the font loading issue (described below) and functionality has changed very recently so you may or may not see the Roboto font load when your infoWindow opens the first time, depending on the version of the API you are using. There is an open bug report (even though in the changelog this bug report was already marked as fixed) that illustrates that google is still having difficulty with this problem.

ONE MORE THING: WATCH YOUR FONT FAMILIES!!!

In the latest incarnation of the API, google tried to be clever and wrap it's infoWindow content in something that could be targeted with a CSS selector - .gm-style-iw. For people that didn't understand the rules that I explained above, this didn't really help, and in some cases made it even worse. Scrollbars would almost always appear the first time an infoWindow was opened, but if you opened any infoWindow again, even with the exact same content the scrollbars would be gone. Seriously, if you weren't confused before this would make you lose your mind. Here's what was happening:

If you look at the styles that google loads on the page when it's API loads, you'll be able to see this:

.gm-style {
     font-family: Roboto,Arial,sans-serif
 ...
}

Ok, so Google wanted to make it's maps a bit more consistent by always making them use the Roboto font-family. The problem is, for the majority of people, the before you opened an infoWindow, the browser hadn't yet downloaded the Roboto font (because nothing else on your page used it so the browser is smart enough to know that it doesn't need to download this font). Downloading this font isn't instantaneous, even though it is very fast. The first time you open an infoWindow and the API appends the div with your infoWindow content to the body to take it's measurements, it starts downloading the Roboto font, but your infoWindow's measurements are taken and the window is placed on the map before Roboto finishes downloading. The result, quite often, was an infoWindow whose measurements were taken when it's content was rendered using Arial or a sans-serif font, but when it was displayed on the map (and Roboto had finished downloading) it's content was being displayed in a font that was a different size - and voila - scrollbars appear the first time you open the infoWindow. Open the exact same infoWindow a second time - at which point the Roboto has been downloaded and will be used when the API is taking it's measurements of infoWindow content and you won't see any scrollbars.

How to add a changed file to an older (not last) commit in Git

with git 1.7, there's a really easy way using git rebase:

stage your files:

git add $files

create a new commit and re-use commit message of your "broken" commit

git commit -c master~4

prepend fixup! in the subject line (or squash! if you want to edit commit (message)):

fixup! Factored out some common XPath Operations

use git rebase -i --autosquash to fixup your commit

Form/JavaScript not working on IE 11 with error DOM7011

Go to

Tools > Compatibility View settings > Uncheck the option "Display intranet sites in Compatibility View".

Click on Close. It may re-launch the page and then your problem would be resolved.

Flask Download a File

You need to make sure that the value you pass to the directory argument is an absolute path, corrected for the current location of your application.

The best way to do this is to configure UPLOAD_FOLDER as a relative path (no leading slash), then make it absolute by prepending current_app.root_path:

@app.route('/uploads/<path:filename>', methods=['GET', 'POST'])
def download(filename):
    uploads = os.path.join(current_app.root_path, app.config['UPLOAD_FOLDER'])
    return send_from_directory(directory=uploads, filename=filename)

It is important to reiterate that UPLOAD_FOLDER must be relative for this to work, e.g. not start with a /.

A relative path could work but relies too much on the current working directory being set to the place where your Flask code lives. This may not always be the case.

Nested or Inner Class in PHP

I think I wrote an elegant solution to this problem by using namespaces. In my case, the inner class does not need to know his parent class (like the static inner class in Java). As an example I made a class called 'User' and a subclass called 'Type', used as a reference for the user types (ADMIN, OTHERS) in my example. Regards.

User.php (User class file)

<?php
namespace
{   
    class User
    {
        private $type;

        public function getType(){ return $this->type;}
        public function setType($type){ $this->type = $type;}
    }
}

namespace User
{
    class Type
    {
        const ADMIN = 0;
        const OTHERS = 1;
    }
}
?>

Using.php (An example of how to call the 'subclass')

<?php
    require_once("User.php");

    //calling a subclass reference:
    echo "Value of user type Admin: ".User\Type::ADMIN;
?>

How do I detect whether 32-bit Java is installed on x64 Windows, only looking at the filesystem and registry?

just write "java -d64 -version" or d32 and if you have It installed it will give a response with current version installed

Python equivalent of a given wget command

Here's the code adopted from the torchvision library:

import urllib

def download_url(url, root, filename=None):
    """Download a file from a url and place it in root.
    Args:
        url (str): URL to download file from
        root (str): Directory to place downloaded file in
        filename (str, optional): Name to save the file under. If None, use the basename of the URL
    """

    root = os.path.expanduser(root)
    if not filename:
        filename = os.path.basename(url)
    fpath = os.path.join(root, filename)

    os.makedirs(root, exist_ok=True)

    try:
        print('Downloading ' + url + ' to ' + fpath)
        urllib.request.urlretrieve(url, fpath)
    except (urllib.error.URLError, IOError) as e:
        if url[:5] == 'https':
            url = url.replace('https:', 'http:')
            print('Failed download. Trying https -> http instead.'
                    ' Downloading ' + url + ' to ' + fpath)
            urllib.request.urlretrieve(url, fpath)

If you are ok to take dependency on torchvision library then you also also simply do:

from torchvision.datasets.utils import download_url
download_url('http://something.com/file.zip', '~/my_folder`)

How do you render primitives as wireframes in OpenGL?

A good and simple way of drawing anti-aliased lines on a non anti-aliased render target is to draw rectangles of 4 pixel width with an 1x4 texture, with alpha channel values of {0.,1.,1.,0.}, and use linear filtering with mip-mapping off. This will make the lines 2 pixels thick, but you can change the texture for different thicknesses. This is faster and easier than barymetric calculations.

Insertion Sort vs. Selection Sort

Selection Sort: As you start building the sorted sublist, the algorithm ensures that the sorted sublist is always completely sorted, not only in terms of it's own elements but also in terms of the complete array i.e. both sorted and unsorted sublist. Thus the new smallest element once found from the unsorted sublist would just be appended at the end of the sorted sublist.

Insertion Sort: The algorithm again divide the array into two part, but here the element is picked from second part and inserted at correct position to the first part. This never guarantees that the first part is sorted in terms of the complete array, though ofcourse in the final pass every element is at its correct sorted position.

How to apply style classes to td classes?

table.classname td {
    font-size: 90%;
}

worked for me. thanks.

Version vs build in Xcode

Thanks to @nekno and @ale84 for great answers.

However, I modified @ale84's script it little to increment build numbers for floating point.

the value of incl can be changed according to your floating format requirements. For eg: if incl = .01, output format would be ... 1.19, 1.20, 1.21 ...

buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFOPLIST_FILE")
incl=.01
buildNumber=`echo $buildNumber + $incl|bc`
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "$INFOPLIST_FILE"

Laravel Eloquent LEFT JOIN WHERE NULL

I would dump your query so you can take a look at the SQL that was actually executed and see how that differs from what you wrote.

You should be able to do that with the following code:

$queries = DB::getQueryLog();
$last_query = end($queries);
var_dump($last_query);
die();

Hopefully that should give you enough information to allow you to figure out what's gone wrong.

Accessing localhost (xampp) from another computer over LAN network - how to?

I am Fully agree With BugFinder.

In simple Words, just put ip address 192.168.1.56 in your browser running on 192.168.1.2!

if it does not work then there are following possible reasons for that :

  1. Network Connectivity Issue :

    • First of all Check your network Connectivity using ping 192.168.1.56 command in command prompt/terminal on 192.168.1.2 computer.
  2. Firewall Problem : Your windows firewall setting do not have allowing rule for XAMPP(apache). (Most probable problem)

    • (solution) go to advanced firewall settings and add inbound and outbound rules for Apache executable file.
  3. Apache Configuration problem. : Your apache is configured to listen only local requests.

    • (Solution) you can it by opening httpd.conf file and replace Listen 127.0.0.1:80 to Listen 80 or *Listen :80
  4. Port Conflict with other Servers(IIS etc.)

    • (Solution) Turn off apache server and then open local host in browser. if any response is obtained then turnoff that server then start Apache.

if all above does not work then probably there is some configuration problem on your apache server.try to find it out otherwise just reinstall it and transfer all php files(htdocs) to new installation of XAMPP/WAMP.

VBA Date as integer

Public SUB test()
    Dim mdate As Date
    mdate = now()
    MsgBox (Round(CDbl(mdate), 0))
End SUB

How can I debug what is causing a connection refused or a connection time out?

The problem

The problem is in the network layer. Here are the status codes explained:

  • Connection refused: The peer is not listening on the respective network port you're trying to connect to. This usually means that either a firewall is actively denying the connection or the respective service is not started on the other site or is overloaded.

  • Connection timed out: During the attempt to establish the TCP connection, no response came from the other side within a given time limit. In the context of urllib this may also mean that the HTTP response did not arrive in time. This is sometimes also caused by firewalls, sometimes by network congestion or heavy load on the remote (or even local) site.

In context

That said, it is probably not a problem in your script, but on the remote site. If it's occuring occasionally, it indicates that the other site has load problems or the network path to the other site is unreliable.

Also, as it is a problem with the network, you cannot tell what happened on the other side. It is possible that the packets travel fine in the one direction but get dropped (or misrouted) in the other.

It is also not a (direct) DNS problem, that would cause another error (Name or service not known or something similar). It could however be the case that the DNS is configured to return different IP addresses on each request, which would connect you (DNS caching left aside) to different addresses hosts on each connection attempt. It could in turn be the case that some of these hosts are misconfigured or overloaded and thus cause the aforementioned problems.

Debugging this

As suggested in the another answer, using a packet analyzer can help to debug the issue. You won't see much however except the packets reflecting exactly what the error message says.

To rule out network congestion as a problem you could use a tool like mtr or traceroute or even ping to see if packets get lost to the remote site. Note that, if you see loss in mtr (and any traceroute tool for that matter), you must always consider the first host where loss occurs (in the route from yours to remote) as the one dropping packets, due to the way ICMP works. If the packets get lost only at the last hop over a long time (say, 100 packets), that host definetly has an issue. If you see that this behaviour is persistent (over several days), you might want to contact the administrator.

Loss in a middle of the route usually corresponds to network congestion (possibly due to maintenance), and there's nothing you could do about it (except whining at the ISP about missing redundance).

If network congestion is not a problem (i.e. not more than, say, 5% of the packets get lost), you should contact the remote server administrator to figure out what's wrong. He may be able to see relevant infos in system logs. Running a packet analyzer on the remote site might also be more revealing than on the local site. Checking whether the port is open using netstat -tlp is definetly recommended then.

ngrok command not found

For installation in Windows : Download and extract to any directory (lets say c drive)

  • Then double click on the extracted ngrok.exe file and you'll be able to see the command prompt.

  • And just type ngrok http 4040 // here I am exposing [port 4040]

How to download a file from a website in C#

Use WebClient.DownloadFile:

using (WebClient client = new WebClient())
{
    client.DownloadFile("http://csharpindepth.com/Reviews.aspx", 
                        @"c:\Users\Jon\Test\foo.txt");
}

Is there such a thing as min-font-size and max-font-size?

Rucksack is brilliant, but you don't necessarily have to resort to build tools like Gulp or Grunt etc.

I made a demo using CSS Custom Properties (CSS Variables) to easily control the min and max font sizes.

Like so:

* {
  /* Calculation */
  --diff: calc(var(--max-size) - var(--min-size));
  --responsive: calc((var(--min-size) * 1px) + var(--diff) * ((100vw - 420px) / (1200 - 420))); /* Ranges from 421px to 1199px */
}

h1 {
  --max-size: 50;
  --min-size: 25;
  font-size: var(--responsive);
}

h2 {
  --max-size: 40;
  --min-size: 20;
  font-size: var(--responsive);
}

Vim 80 column layout concerns

Simon Howard's answer is great. But /\%81v.\+/ fails to highlight tabs that exceed column 81 . So I did a little tweak, based on the stuff I found on VIM wiki and HS's choice of colors above:

highlight OverLength ctermbg=darkred ctermfg=white guibg=#FFD9D9
match OverLength /\%>80v.\+/

And now VIM will highlight anything that exceeds column 80.

Angularjs ng-model doesn't work inside ng-if

You can do it like this and you mod function will work perfect let me know if you want a code pen

  <div ng-repeat="icon in icons">                   
                <div class="row" ng-if="$index % 3 == 0 ">
                    <i class="col col-33 {{icons[$index + n].icon}} custom-icon"></i>
                    <i class="col col-33 {{icons[$index + n + 1].icon}} custom-icon"></i>
                    <i class="col col-33 {{icons[$index + n + 2].icon}} custom-icon"></i>
                </div>
         </div>

How to wait for a number of threads to complete?

Depending on your needs, you may also want to check out the classes CountDownLatch and CyclicBarrier in the java.util.concurrent package. They can be useful if you want your threads to wait for each other, or if you want more fine-grained control over the way your threads execute (e.g., waiting in their internal execution for another thread to set some state). You could also use a CountDownLatch to signal all of your threads to start at the same time, instead of starting them one by one as you iterate through your loop. The standard API docs have an example of this, plus using another CountDownLatch to wait for all threads to complete their execution.

beyond top level package error in relative import

if you have an __init__.py in an upper folder, you can initialize the import as import file/path as alias in that init file. Then you can use it on lower scripts as:

import alias

Can I install the "app store" in an IOS simulator?

No, according to Apple here:

Note: You cannot install apps from the App Store in simulation environments.

How to define servlet filter order of execution using annotations in WAR

The Servlet 3.0 spec doesn't seem to provide a hint on how a container should order filters that have been declared via annotations. It is clear how about how to order filters via their declaration in the web.xml file, though.

Be safe. Use the web.xml file order filters that have interdependencies. Try to make your filters all order independent to minimize the need to use a web.xml file.

How to load external webpage in WebView

Add WebView Client

mWebView.setWebViewClient(new WebViewClient());

How to access a preexisting collection with Mongoose?

Here's an abstraction of Will Nathan's answer if anyone just wants an easy copy-paste add-in function:

function find (name, query, cb) {
    mongoose.connection.db.collection(name, function (err, collection) {
       collection.find(query).toArray(cb);
   });
}

simply do find(collection_name, query, callback); to be given the result.

for example, if I have a document { a : 1 } in a collection 'foo' and I want to list its properties, I do this:

find('foo', {a : 1}, function (err, docs) {
            console.dir(docs);
        });
//output: [ { _id: 4e22118fb83406f66a159da5, a: 1 } ]

SSL Error When installing rubygems, Unable to pull data from 'https://rubygems.org/

For windows users

Goto link http://rubygems.org/pages/download

  1. Download the latest zip file (In my case 2.4.5)
  2. Unzip it
  3. run "ruby setup.rb" in unzipped folder
  4. now run gem install command

Row names & column names in R

Just to expand a little on Dirk's example:

It helps to think of a data frame as a list with equal length vectors. That's probably why names works with a data frame but not a matrix.

The other useful function is dimnames which returns the names for every dimension. You will notice that the rownames function actually just returns the first element from dimnames.

Regarding rownames and row.names: I can't tell the difference, although rownames uses dimnames while row.names was written outside of R. They both also seem to work with higher dimensional arrays:

>a <- array(1:5, 1:4)
> a[1,,,]
> rownames(a) <- "a"
> row.names(a)
[1] "a"
> a
, , 1, 1    
  [,1] [,2]
a    1    2

> dimnames(a)
[[1]]
[1] "a"

[[2]]
NULL

[[3]]
NULL

[[4]]
NULL

How to increase font size in NeatBeans IDE?

press alt and scroll down or up to change the size

Add swipe to delete UITableViewCell

Add these two functions:

func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
}

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.Delete) {
        // handle delete (by removing the data from your array and updating the tableview)
    }
}

Swift 3.0:

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.delete) {
        // handle delete (by removing the data from your array and updating the tableview)
    }
}

Swift 4.2

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == .delete) {
        // handle delete (by removing the data from your array and updating the tableview)
    }
}

getActionBar() returns null

If you are using the support library

import android.support.v7.app.ActionBarActivity;

public class MainActivity extends ActionBarActivity {

use getSupportActionBar() instead of getActionBar()

* Update:

The class ActionBarActivity now is deprecated:

import android.support.v7.app.ActionBarActivity;

I recommend to use:

import android.support.v7.app.AppCompatActivity

How do I modify the URL without reloading the page?

This code works for me. I used it into my application in ajax.

history.pushState({ foo: 'bar' }, '', '/bank');

Once a page load into an ID using ajax, It does change the browser url automatically without reloading the page.

This is ajax function bellow.

function showData(){
    $.ajax({
      type: "POST",
      url: "Bank.php", 
      data: {}, 
      success: function(html){          
        $("#viewpage").html(html).show();
        $("#viewpage").css("margin-left","0px");
      }
    });
  }

Example: From any page or controller like "Dashboard", When I click on the bank, it loads bank list using the ajax code without reloading the page. At this time, browser URL will not be changed.

history.pushState({ foo: 'bar' }, '', '/bank');

But when I use this code into the ajax, it change the browser url without reloading the page. This is the full ajax code here in the bellow.

function showData(){
        $.ajax({
          type: "POST",
          url: "Bank.php", 
          data: {}, 
          success: function(html){          
            $("#viewpage").html(html).show();
            $("#viewpage").css("margin-left","0px");
            history.pushState({ foo: 'bar' }, '', '/bank');
          }
        });
      }

How do I get some variable from another class in Java?

I am trying to get int x equal to 5 (as seen in the setNum() method) but when it prints it gives me 0.

To run the code in setNum you have to call it. If you don't call it, the default value is 0.

How do I pass multiple parameters into a function in PowerShell?

The correct answer has already been provided, but this issue seems prevalent enough to warrant some additional details for those wanting to understand the subtleties.

I would have added this just as a comment, but I wanted to include an illustration--I tore this off my quick reference chart on PowerShell functions. This assumes function f's signature is f($a, $b, $c):

Syntax pitfalls of a function call

Thus, one can call a function with space-separated positional parameters or order-independent named parameters. The other pitfalls reveal that you need to be cognizant of commas, parentheses, and white space.

For further reading, see my article Down the Rabbit Hole: A Study in PowerShell Pipelines, Functions, and Parameters. The article contains a link to the quick reference/wall chart as well.

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

General ? Appearance ? Colors and Fonts ? Java Editor text font

See the image:

enter image description here

How do I add a auto_increment primary key in SQL Server database?

You can also perform this action via SQL Server Management Studio.

Right click on your selected table -> Modify

Right click on the field you want to set as PK --> Set Primary Key

Under Column Properties set "Identity Specification" to Yes, then specify the starting value and increment value.

Then in the future if you want to be able to just script this kind of thing out you can right click on the table you just modified and select

"SCRIPT TABLE AS" --> CREATE TO

so that you can see for yourself the correct syntax to perform this action.

How to use glyphicons in bootstrap 3.0

There you go:

<i class="glyphicon glyphicon-search"></i>

More information:

http://getbootstrap.com/components/#glyphicons

Btw. you can use this conversion tool, this will also update the code for the icons:

Maven – Always download sources and javadocs

In my case the "settings.xml" solution didn't work so I use this command in order to download all the sources:

mvn dependency:sources

You also can use it with other maven commands, for example:

mvn clean install dependency:sources -Dmaven.test.skip=true

To download all documentation, use the following command:

mvn dependency:resolve -Dclassifier=javadoc

How to execute a function when page has fully loaded?

Usually you can use window.onload, but you may notice that recent browsers don't fire window.onload when you use the back/forward history buttons.

Some people suggest weird contortions to work around this problem, but really if you just make a window.onunload handler (even one that doesn't do anything), this caching behavior will be disabled in all browsers. The MDC documents this "feature" pretty well, but for some reason there are still people using setInterval and other weird hacks.

Some versions of Opera have a bug that can be worked around by adding the following somewhere in your page:

<script>history.navigationMode = 'compatible';</script>

If you're just trying to get a javascript function called once per-view (and not necessarily after the DOM is finished loading), you can do something like this:

<img src="javascript:location.href='javascript:yourFunction();';">

For example, I use this trick to preload a very large file into the cache on a loading screen:

<img src="bigfile"
onload="this.location.href='javascript:location.href=\'javascript:doredir();\';';doredir();">

python pandas extract year from datetime: df['year'] = df['date'].year is not working

If you're running a recent-ish version of pandas then you can use the datetime attribute dt to access the datetime components:

In [6]:

df['date'] = pd.to_datetime(df['date'])
df['year'], df['month'] = df['date'].dt.year, df['date'].dt.month
df
Out[6]:
        date  Count  year  month
0 2010-06-30    525  2010      6
1 2010-07-30    136  2010      7
2 2010-08-31    125  2010      8
3 2010-09-30     84  2010      9
4 2010-10-29   4469  2010     10

EDIT

It looks like you're running an older version of pandas in which case the following would work:

In [18]:

df['date'] = pd.to_datetime(df['date'])
df['year'], df['month'] = df['date'].apply(lambda x: x.year), df['date'].apply(lambda x: x.month)
df
Out[18]:
        date  Count  year  month
0 2010-06-30    525  2010      6
1 2010-07-30    136  2010      7
2 2010-08-31    125  2010      8
3 2010-09-30     84  2010      9
4 2010-10-29   4469  2010     10

Regarding why it didn't parse this into a datetime in read_csv you need to pass the ordinal position of your column ([0]) because when True it tries to parse columns [1,2,3] see the docs

In [20]:

t="""date   Count
6/30/2010   525
7/30/2010   136
8/31/2010   125
9/30/2010   84
10/29/2010  4469"""
df = pd.read_csv(io.StringIO(t), sep='\s+', parse_dates=[0])
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 5 entries, 0 to 4
Data columns (total 2 columns):
date     5 non-null datetime64[ns]
Count    5 non-null int64
dtypes: datetime64[ns](1), int64(1)
memory usage: 120.0 bytes

So if you pass param parse_dates=[0] to read_csv there shouldn't be any need to call to_datetime on the 'date' column after loading.

How to use UTF-8 in resource properties with ResourceBundle

http://sourceforge.net/projects/eclipse-rbe/

as already stated property files should be encoded in ISO 8859-1

You can use the above plugin for eclipse IDE to make the Unicode conversion for you.

Use jQuery to scroll to the bottom of a div with lots of text

_x000D_
_x000D_
$(function() {_x000D_
  var wtf    = $('#scroll');_x000D_
  var height = wtf[0].scrollHeight;_x000D_
  wtf.scrollTop(height);_x000D_
});
_x000D_
 #scroll {_x000D_
   width: 200px;_x000D_
   height: 300px;_x000D_
   overflow-y: scroll;_x000D_
 }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="scroll">_x000D_
    <br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/> <center><b>Voila!! You have already reached the bottom :)<b></center>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I override nested NPM dependency versions?

You can use npm shrinkwrap functionality, in order to override any dependency or sub-dependency.

I've just done this in a grunt project of ours. We needed a newer version of connect, since 2.7.3. was causing trouble for us. So I created a file named npm-shrinkwrap.json:

{
  "dependencies": {
    "grunt-contrib-connect": {
      "version": "0.3.0",
      "from": "[email protected]",
      "dependencies": {
        "connect": {
          "version": "2.8.1",
          "from": "connect@~2.7.3"
        }
      }
    }
  }
}

npm should automatically pick it up while doing the install for the project.

(See: https://nodejs.org/en/blog/npm/managing-node-js-dependencies-with-shrinkwrap/)

A select query selecting a select statement

I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:

SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;

Thanks for answering, it helped my train of thought.

Call a function after previous function is complete

If you're using jQuery 1.5 you can use the new Deferreds pattern:

$('a.button').click(function(){
    if(condition == 'true'){
        $.when(function1()).then(function2());
    }
    else {
        doThis(someVariable);
    }
});

Edit: Updated blog link:

Rebecca Murphy had a great write-up on this here: http://rmurphey.com/blog/2010/12/25/deferreds-coming-to-jquery/

Sieve of Eratosthenes - Finding Primes Python

I prefer NumPy because of speed.

import numpy as np

# Find all prime numbers using Sieve of Eratosthenes
def get_primes1(n):
    m = int(np.sqrt(n))
    is_prime = np.ones(n, dtype=bool)
    is_prime[:2] = False  # 0 and 1 are not primes

    for i in range(2, m):
        if is_prime[i] == False:
            continue
        is_prime[i*i::i] = False

    return np.nonzero(is_prime)[0]

# Find all prime numbers using brute-force.
def isprime(n):
    ''' Check if integer n is a prime '''
    n = abs(int(n))  # n is a positive integer
    if n < 2:  # 0 and 1 are not primes
        return False
    if n == 2:  # 2 is the only even prime number
        return True
    if not n & 1:  # all other even numbers are not primes
        return False
    # Range starts with 3 and only needs to go up the square root
    # of n for all odd numbers
    for x in range(3, int(n**0.5)+1, 2):
        if n % x == 0:
            return False
    return True

# To apply a function to a numpy array, one have to vectorize the function
def get_primes2(n):
    vectorized_isprime = np.vectorize(isprime)
    a = np.arange(n)
    return a[vectorized_isprime(a)]

Check the output:

n = 100
print(get_primes1(n))
print(get_primes2(n))    
    [ 2  3  5  7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97]
    [ 2  3  5  7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97]

Compare the speed of Sieve of Eratosthenes and brute-force on Jupyter Notebook. Sieve of Eratosthenes in 539 times faster than brute-force for million elements.

%timeit get_primes1(1000000)
%timeit get_primes2(1000000)
4.79 ms ± 90.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.58 s ± 31.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

How to add a class to a given element?

You can use the classList.add OR classList.remove method to add/remove a class from a element.

var nameElem = document.getElementById("name")
nameElem.classList.add("anyclss")

The above code will add(and NOT replace) a class "anyclass" to nameElem. Similarly you can use classList.remove() method to remove a class.

nameElem.classList.remove("anyclss")

E: Unable to locate package npm

Download the the repository key with:

curl -s https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -

Then setup the repository:

sudo sh -c "echo deb https://deb.nodesource.com/node_8.x cosmic main \
                 > /etc/apt/sources.list.d/nodesource.list"
sudo apt-get update
sudo apt-get install nodejs

How do you import classes in JSP?

Use the following import statement to import java.util.List:

<%@ page import="java.util.List" %>

BTW, to import more than one class, use the following format:

<%@ page import="package1.myClass1,package2.myClass2,....,packageN.myClassN" %>

How to set time zone of a java.util.Date?

Here you be able to get date like "2020-03-11T20:16:17" and return "11/Mar/2020 - 20:16"

 private String transformLocalDateTimeBrazillianUTC(String dateJson) throws  ParseException {
    String localDateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss";
    SimpleDateFormat formatInput = new SimpleDateFormat(localDateTimeFormat);

    //Here is will set the time zone
    formatInput.setTimeZone(TimeZone.getTimeZone("UTC-03"));

    String brazilianFormat = "dd/MMM/yyyy - HH:mm";
    SimpleDateFormat formatOutput = new SimpleDateFormat(brazilianFormat);
    Date date = formatInput.parse(dateJson);
    return formatOutput.format(date);
}

Multiple rows to one comma-separated value in Sql Server

Test Data

DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)

Query

SELECT  ID
       ,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
         FROM @Table1 
         WHERE ID = t.ID
         FOR XML PATH(''), TYPE)
        .value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

SQL Server 2017 and Later Versions

If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:

DECLARE @Table1 TABLE(ID INT, Value INT);
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);


SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1
GROUP BY ID;

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

Swift how to sort array of custom objects by property value

Two alternatives

1) Ordering the original array with sortInPlace

self.assignments.sortInPlace({ $0.order < $1.order })
self.printAssignments(assignments)

2) Using an alternative array to store the ordered array

var assignmentsO = [Assignment] ()
assignmentsO = self.assignments.sort({ $0.order < $1.order })
self.printAssignments(assignmentsO)

How can I stop .gitignore from appearing in the list of untracked files?

Watch out for the following "problem" Sometimes you want to add directories but no files within those directories. The simple solution is to create a .gitignore with the following content:

*

This seams to work fine until you realize that the directory was not added (as expected to your repository. The reason for that is that the .gitignore will also be ignored, and thereby the directory is empty. Thus, you should do something like this:

*
!.gitignore

How to tell CRAN to install package dependencies automatically?

Another possibility is to select the Install Dependencies checkbox In the R package installer, on the bottom right:

enter image description here

how to get the current working directory's absolute path from irb

As for the path relative to the current executing script, since Ruby 2.0 you can also use

__dir__

So this is basically the same as

File.dirname(__FILE__)

How can I adjust DIV width to contents

You could try using float:left; or display:inline-block;.

Both of these will change the element's behaviour from defaulting to 100% width to defaulting to the natural width of its contents.

However, note that they'll also both have an impact on the layout of the surrounding elements as well. I would suggest that inline-block will have less of an impact though, so probably best to try that first.

SQL Server : GROUP BY clause to get comma-separated values

try this:

SELECT ReportId, Email = 
    STUFF((SELECT ', ' + Email
           FROM your_table b 
           WHERE b.ReportId = a.ReportId 
          FOR XML PATH('')), 1, 2, '')
FROM your_table a
GROUP BY ReportId


SQL fiddle demo

QString to char* conversion

EDITED

this way also works

QString str ("Something");

char* ch = str.toStdString().C_str();

Where does Git store files?

usually it goes to Documents folder in windows : C:\Users\<"name of user account">\Documents\GitHub