Programs & Examples On #Getprocaddress

Compile a DLL in C/C++, then call it from another program

Regarding building a DLL using MinGW, here are some very brief instructions.

First, you need to mark your functions for export, so they can be used by callers of the DLL. To do this, modify them so they look like (for example)

__declspec( dllexport ) int add2(int num){
   return num + 2;
}

then, assuming your functions are in a file called funcs.c, you can compile them:

gcc -shared -o mylib.dll funcs.c

The -shared flag tells gcc to create a DLL.

To check if the DLL has actually exported the functions, get hold of the free Dependency Walker tool and use it to examine the DLL.

For a free IDE which will automate all the flags etc. needed to build DLLs, take a look at the excellent Code::Blocks, which works very well with MinGW.

Edit: For more details on this subject, see the article Creating a MinGW DLL for Use with Visual Basic on the MinGW Wiki.

Exporting functions from a DLL with dllexport

I had exactly the same problem, my solution was to use module definition file (.def) instead of __declspec(dllexport) to define exports(http://msdn.microsoft.com/en-us/library/d91k01sh.aspx). I have no idea why this works, but it does

Scala check if element is present in a list

this should work also with different predicate

myFunction(strings.find( _ == mystring ).isDefined)

How to refresh Android listview?

Also you can use this:

myListView.invalidateViews();

Could not load file or assembly System.Web.Http.WebHost after published to Azure web site

In the case if "Copy Local" is already True, I find it sometimes to work if you remove the files where it has been published to and publish again.

For example if you're using IIS, remove the websites and the contents of the directory to which they are published to, and publish again.

There might be older versions of files at the destination, so to ensure you aren't using older versions, delete everything before publishing again.

Syntax for async arrow function

My async function

const getAllRedis = async (key) => {
  let obj = [];

  await client.hgetall(key, (err, object) => {
    console.log(object);
    _.map(object, (ob)=>{
      obj.push(JSON.parse(ob));
    })
    return obj;
    // res.send(obj);
});
}

How to convert all tables in database to one collation?

For phpMyAdmin I figured this out:

SELECT GROUP_CONCAT("ALTER TABLE ", TABLE_SCHEMA, '.', TABLE_NAME," CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" SEPARATOR ' ') AS    OneSQLString
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA="yourtableschemaname"
AND TABLE_TYPE="BASE TABLE"

Just change yourtableschemaname and you're fine.

Set background color in PHP?

You better use CSS for that, after all, this is what CSS is for. If you don't want to do that, go with Dorwand's answer.

Setting unique Constraint with fluent API?

@coni2k 's answer is correct however you must add [StringLength] attribute for it to work otherwise you will get an invalid key exception (Example bellow).

[StringLength(65)]
[Index("IX_FirstNameLastName", 1, IsUnique = true)]
public string FirstName { get; set; }

[StringLength(65)]
[Index("IX_FirstNameLastName", 2, IsUnique = true)]
public string LastName { get; set; }

converting a javascript string to a html object

In addition to Gaby aka's method, we can find elements inside htmlObject in this way -

htmlObj.find("#box").html();

Fiddle is available here - http://jsfiddle.net/ashwyn/76gL3/

How to solve java.lang.NullPointerException error?

This error occures when you try to refer to a null object instance. I can`t tell you what causes this error by your given information, but you can debug it easily in your IDE. I strongly recommend you that use exception handling to avoid unexpected program behavior.

git: Your branch is ahead by X commits

I had this issue on my stage server where I do only pulls. And hard reset helped me to clean HEAD to the same as remote.

git reset --hard origin/master

So now I have again:

On branch master
Your branch is up-to-date with 'origin/master'.

How to compare datetime with only date in SQL Server

Please try this. This query can be used for date comparison

select * from [User] U where convert(varchar(10),U.DateCreated, 120) = '2014-02-07'

How to round up a number in Javascript?

Little late but, can create a reusable javascript function for this purpose:

// Arguments: number to round, number of decimal places
function roundNumber(rnum, rlength) { 
    var newnumber = Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
    return newnumber;
}

Call the function as

alert(roundNumber(192.168,2));

Why doesn't height: 100% work to expand divs to the screen height?

Here's another solution for people who don't want to use html, body, .blah { height: 100% }.

_x000D_
_x000D_
.app {_x000D_
  position: fixed;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  overflow-y: auto;_x000D_
}_x000D_
_x000D_
.full-height {_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.test {_x000D_
  width: 10px;_x000D_
  background: red;_x000D_
}
_x000D_
<div class="app">_x000D_
  <div class="full-height test">_x000D_
  </div>_x000D_
  Scroll works too_x000D_
</div>
_x000D_
_x000D_
_x000D_

Update Jenkins from a war file

when you open the Jenkins panel it will show available package from their latest version. you can download it via wget command in the server.after download the latest package you should take .war backup file.

Eg-: wget http://updates.jenkins-ci.org/download/war/2.205/jenkins.war

Jenkins war file path for Ubuntu - /usr/share/jenkins/

Jenkins war file path for centos - /usr/lib/jenkins/

after taking backup overwrite the war file and restart the jenkins service.

Ubuntu - service jenkins restart , centos - systemctl restart jenkins.service

jquery AJAX and json format

You need to parse the string you are sending from javascript object to the JSON object

var json=$.parseJSON(data);

How can I upload fresh code at github?

In Linux use below command to upload code in git
1 ) git clone repository
ask for user name and password.
2) got to respositiory directory.
3) git add project name.
4) git commit -m ' messgage '.
5) git push origin master.
- user name ,password

Update new Change code into Github

->Goto Directory That your github up code
->git commit ProjectName -m 'Message'
->git push origin master.

Which command do I use to generate the build of a Vue app?

I think you can use vue-cli

If you are using Vue CLI along with a backend framework that handles static assets as part of its deployment, all you need to do is making sure Vue CLI generates the built files in the correct location, and then follow the deployment instruction of your backend framework.

If you are developing your frontend app separately from your backend - i.e. your backend exposes an API for your frontend to talk to, then your frontend is essentially a purely static app. You can deploy the built content in the dist directory to any static file server, but make sure to set the correct baseUrl

How to draw a checkmark / tick using CSS?

Here is another CSS solution. its take less line of code.

ul li:before
{content:'\2713';
  display:inline-block;
  color:red;
  padding:0 6px 0 0;
  }
ul li{list-style-type:none;font-size:1em;}

<ul>
    <li>test1</li>
    <li>test</li>
</ul>

Here is the Demo link http://jsbin.com/keliguqi/1/

MySQL: How to allow remote connection to mysql

Just F.Y.I I pulled my hair out with this problem for hours.. finally I call my hosting provider and found that in my case using a cloud server that in the control panel for 1and1 they have a secondary firewall that you have to clone and add port 3306. Once added I got straight in..

In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

WebSockets is definitely the future.

Long polling is a dirty workaround to prevent creating connections for each request like AJAX does -- but long polling was created when WebSockets didn't exist. Now due to WebSockets, long polling is going away.

WebRTC allows for peer-to-peer communication.

I recommend learning WebSockets.

Comparison:

of different communication techniques on the web

  • AJAX - requestresponse. Creates a connection to the server, sends request headers with optional data, gets a response from the server, and closes the connection. Supported in all major browsers.

  • Long poll - requestwaitresponse. Creates a connection to the server like AJAX does, but maintains a keep-alive connection open for some time (not long though). During connection, the open client can receive data from the server. The client has to reconnect periodically after the connection is closed, due to timeouts or data eof. On server side it is still treated like an HTTP request, same as AJAX, except the answer on request will happen now or some time in the future, defined by the application logic. support chart (full) | wikipedia

  • WebSockets - clientserver. Create a TCP connection to the server, and keep it open as long as needed. The server or client can easily close the connection. The client goes through an HTTP compatible handshake process. If it succeeds, then the server and client can exchange data in both directions at any time. It is efficient if the application requires frequent data exchange in both ways. WebSockets do have data framing that includes masking for each message sent from client to server, so data is simply encrypted. support chart (very good) | wikipedia

  • WebRTC - peerpeer. Transport to establish communication between clients and is transport-agnostic, so it can use UDP, TCP or even more abstract layers. This is generally used for high volume data transfer, such as video/audio streaming, where reliability is secondary and a few frames or reduction in quality progression can be sacrificed in favour of response time and, at least, some data transfer. Both sides (peers) can push data to each other independently. While it can be used totally independent from any centralised servers, it still requires some way of exchanging endPoints data, where in most cases developers still use centralised servers to "link" peers. This is required only to exchange essential data for establishing a connection, after which a centralised server is not required. support chart (medium) | wikipedia

  • Server-Sent Events - clientserver. Client establishes persistent and long-term connection to server. Only the server can send data to a client. If the client wants to send data to the server, it would require the use of another technology/protocol to do so. This protocol is HTTP compatible and simple to implement in most server-side platforms. This is a preferable protocol to be used instead of Long Polling. support chart (good, except IE) | wikipedia

Advantages:

The main advantage of WebSockets server-side, is that it is not an HTTP request (after handshake), but a proper message based communication protocol. This enables you to achieve huge performance and architecture advantages. For example, in node.js, you can share the same memory for different socket connections, so they can each access shared variables. Therefore, you don't need to use a database as an exchange point in the middle (like with AJAX or Long Polling with a language like PHP). You can store data in RAM, or even republish between sockets straight away.

Security considerations

People are often concerned about the security of WebSockets. The reality is that it makes little difference or even puts WebSockets as better option. First of all, with AJAX, there is a higher chance of MITM, as each request is a new TCP connection that is traversing through internet infrastructure. With WebSockets, once it's connected it is far more challenging to intercept in between, with additionally enforced frame masking when data is streamed from client to server as well as additional compression, which requires more effort to probe data. All modern protocols support both: HTTP and HTTPS (encrypted).

P.S.

Remember that WebSockets generally have a very different approach of logic for networking, more like real-time games had all this time, and not like http.

How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null)

try this:

ComboBox cbx = new ComboBox();
cbx.DisplayMember = "Text";
cbx.ValueMember = "Value";

EDIT (a little explanation, sory, I also didn't notice your combobox wasn't bound, I blame the lack of caffeine):

The difference between SelectedValue and SelectedItem are explained pretty well here: ComboBox SelectedItem vs SelectedValue

So, if your combobox is not bound to datasource, DisplayMember and ValueMember doesn't do anything, and SelectedValue will always be null, SelectedValueChanged won't be called. So either bind your combobox:

            comboBox1.DisplayMember = "Text";
            comboBox1.ValueMember = "Value";

            List<ComboboxItem> list = new List<ComboboxItem>();

            ComboboxItem item = new ComboboxItem();
            item.Text = "choose a server...";
            item.Value = "-1";
            list.Add(item);

            item = new ComboboxItem();
            item.Text = "S1";
            item.Value = "1";
            list.Add(item);

            item = new ComboboxItem();
            item.Text = "S2";
            item.Value = "2";
            list.Add(item);

            cbx.DataSource = list; // bind combobox to a datasource

or use SelectedItem property:

if (cbx.SelectedItem != null)
             Console.WriteLine("ITEM: "+comboBox1.SelectedItem.ToString());

How do I make a text go onto the next line if it overflows?

word-wrap: break-word; 

add this to your container that should do the trick

Bootstrap 3 Navbar with Logo

Maybe this is too simple, but I just copied the navbar-brand line so there are two of them, the image and then the text.

<a class="navbar-brand" href="index.php"><img class="img-responsive" src="images/my-icon.png" width="30" height="25" alt=" "></a>
<a class="navbar-brand" href="index.php">My Brand</a>

And I created an image that fits inside the navbar (roughly 1/2 the height).

Get current user id in ASP.NET Identity 2.0

Just in case you are like me and the Id Field of the User Entity is an Int or something else other than a string,

using Microsoft.AspNet.Identity;

int userId = User.Identity.GetUserId<int>();

will do the trick

HTML5 required attribute seems not working

My answer is too late, but it can help others.

I had the same problem, even when I used a form tag.

I solved it by declaring Meta Charset in the header of the page:

_x000D_
_x000D_
<meta charset = "UTF-8" />
_x000D_
_x000D_
_x000D_

General error: 1364 Field 'user_id' doesn't have a default value

It's seems flaw's in your database structure. Keep default value None to your title and body column.

Try this:

$user_login_id = auth()->id();
Post::create(request([
        'body' => request('body'),
        'title' => request('title'),
        'user_id' => $user_login_id
    ]));

Pandas: Looking up the list of sheets in an excel file

You can still use the ExcelFile class (and the sheet_names attribute):

xl = pd.ExcelFile('foo.xls')

xl.sheet_names  # see all sheet names

xl.parse(sheet_name)  # read a specific sheet to DataFrame

see docs for parse for more options...

Android Bitmap to Base64 String

Try this, first scale your image to required width and height, just pass your original bitmap, required width and required height to the following method and get scaled bitmap in return:

For example: Bitmap scaledBitmap = getScaledBitmap(originalBitmap, 250, 350);

private Bitmap getScaledBitmap(Bitmap b, int reqWidth, int reqHeight)
{
    int bWidth = b.getWidth();
    int bHeight = b.getHeight();

    int nWidth = bWidth;
    int nHeight = bHeight;

    if(nWidth > reqWidth)
    {
        int ratio = bWidth / reqWidth;
        if(ratio > 0)
        {
            nWidth = reqWidth;
            nHeight = bHeight / ratio;
        }
    }

    if(nHeight > reqHeight)
    {
        int ratio = bHeight / reqHeight;
        if(ratio > 0)
        {
            nHeight = reqHeight;
            nWidth = bWidth / ratio;
        }
    }

    return Bitmap.createScaledBitmap(b, nWidth, nHeight, true);
}

Now just pass your scaled bitmap to the following method and get base64 string in return:

For example: String base64String = getBase64String(scaledBitmap);

private String getBase64String(Bitmap bitmap)
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

    byte[] imageBytes = baos.toByteArray();

    String base64String = Base64.encodeToString(imageBytes, Base64.NO_WRAP);

    return base64String;
}

To decode the base64 string back to bitmap image:

byte[] decodedByteArray = Base64.decode(base64String, Base64.NO_WRAP);
Bitmap decodedBitmap = BitmapFactory.decodeByteArray(decodedByteArray, 0, decodedString.length);

What is the cause for "angular is not defined"

I had the same problem as deke. I forgot to include the most important script: angular.js :)

<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>

Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done?

The good practice is: Dispatch Groups

dispatch_group_t imageGroup = dispatch_group_create();

dispatch_group_enter(imageGroup);
[uploadImage executeWithCompletion:^(NSURL *result, NSError* error){
    // Image successfully uploaded to S3
    dispatch_group_leave(imageGroup);
}];

dispatch_group_enter(imageGroup);
[setImage executeWithCompletion:^(NSURL *result, NSError* error){
    // Image url updated
    dispatch_group_leave(imageGroup);
}];

dispatch_group_notify(imageGroup,dispatch_get_main_queue(),^{
    // We get here when both tasks are completed
});

Check date with todays date

I assume you are using integers to represent your year, month, and day? If you want to remain consistent, use the Date methods.

Calendar cal = new Calendar();
int currentYear, currentMonth, currentDay; 
currentYear = cal.get(Calendar.YEAR); 
currentMonth = cal.get(Calendar.MONTH); 
currentDay = cal.get(Calendar.DAY_OF_WEEK);

     if(startYear < currentYear)
                {
                    message = message + "Start Date is Before Today" + "\n";
                }
            else if(startMonth < currentMonth && startYear <= currentYear)
                    {
                        message = message + "Start Date is Before Today" + "\n";
                    }
            else if(startDay < currentDay && startMonth <= currentMonth && startYear <= currentYear)
                        {
                            message = message + "Start Date is Before Today" + "\n";
                        }

Jquery - How to get the style display attribute "none / block"

If you're using jquery 1.6.2 you only need to code

$('#theid').css('display')

for example:

if($('#theid').css('display') == 'none'){ 
   $('#theid').show('slow'); 
} else { 
   $('#theid').hide('slow'); 
}

select into in mysql

In MySQL, It should be like this

INSERT INTO this_table_archive (col1, col2, ..., coln)
SELECT col1, col2, ..., coln
FROM this_table
WHERE entry_date < '2011-01-01 00:00:00';

MySQL Documentation

HTML5 iFrame Seamless Attribute

You only need to write

seamless

in your code. There is not need for:

seamless ="seamless"

I just found this out myself.

EDIT - this does not remove scrollbars. Strangely

scrolling="no" still seems to work in html5. I have tried using the overflow function with an inline style as recommended by html5 but this doesn't work for me.

HTML text input allow only numeric input

You can attach to the key down event and then filter keys according to what you need, for example:

<input id="FIELD_ID" name="FIELD_ID" onkeypress="return validateNUM(event,this);"  type="text">

And the actual JavaScript handler would be:

function validateNUM(e,field)
{
    var key = getKeyEvent(e)
    if (specialKey(key)) return true;
    if ((key >= 48 && key <= 57) || (key == 46)){
        if (key != 46)
            return true;
        else{
            if (field.value.search(/\./) == -1 && field.value.length > 0)
                return true;
            else
                return false;
        }
    }

function getKeyEvent(e){
    var keynum
    var keychar
    var numcheck
    if(window.event) // IE
        keynum = e.keyCode
    else if(e.which) // Netscape/Firefox/Opera
        keynum = e.which
    return keynum;
}

Cast object to T

Add a 'class' constraint (or more detailed, like a base class or interface of your exepected T objects):

private static T ReadData<T>(XmlReader reader, string value) where T : class
{
    reader.MoveToAttribute(value);
    object readData = reader.ReadContentAsObject();
    return (T)readData;
}

or where T : IMyInterface or where T : new(), etc

remove objects from array by object property

If you just want to remove it from the existing array and not create a new one, try:

var items = [{Id: 1},{Id: 2},{Id: 3}];
items.splice(_.indexOf(items, _.find(items, function (item) { return item.Id === 2; })), 1);

How to create localhost database using mysql?

See here for starting the service and here for how to make it permanent. In short to test it, open a "DOS" terminal with administrator privileges and write:

shell> "C:\Program Files\MySQL\[YOUR MYSQL VERSION PATH]\bin\mysqld"

How to use css style in php

css :hover kinda is like js onmouseover

row1 {
    // your css
}
row1:hover {
    color: red;
}
row1:hover #a, .b, .c:nth-child[3] {
    border: 1px solid red;
}

not too sure how it works but css applies styles to echo'ed ids

C# error: Use of unassigned local variable

The compiler doesn't know that Environment.Exit() does not return. Why not just "return" from Main()?

How is a JavaScript hash map implemented?

every javascript object is a simple hashmap which accepts a string or a Symbol as its key, so you could write your code as:

var map = {};
// add a item
map[key1] = value1;
// or remove it
delete map[key1];
// or determine whether a key exists
key1 in map;

javascript object is a real hashmap on its implementation, so the complexity on search is O(1), but there is no dedicated hashcode() function for javascript strings, it is implemented internally by javascript engine (V8, SpiderMonkey, JScript.dll, etc...)

2020 Update:

javascript today supports other datatypes as well: Map and WeakMap. They behave more closely as hash maps than traditional objects.

Telling Python to save a .txt file to a certain directory on Windows and Mac

Using an absolute or relative string as the filename.

name_of_file = input("What is the name of the file: ")
completeName = '/home/user/Documents'+ name_of_file + ".txt"
file1 = open(completeName , "w")
toFile = input("Write what you want into the field")
file1.write(toFile)
file1.close()

Case Insensitive String comp in C

Simple solution:

int str_case_ins_cmp(const char* a, const char* b) {
  int rc;

  while (1) {
    rc = tolower((unsigned char)*a) - tolower((unsigned char)*b);
    if (rc || !*a) {
      break;
    }

    ++a;
    ++b;
  }

  return rc;
}

Get last field using awk substr

Use the fact that awk splits the lines in fields based on a field separator, that you can define. Hence, defining the field separator to / you can say:

awk -F "/" '{print $NF}' input

as NF refers to the number of fields of the current record, printing $NF means printing the last one.

So given a file like this:

/home/parent/child1/child2/child3/filename
/home/parent/child1/child2/filename
/home/parent/child1/filename

This would be the output:

$ awk -F"/" '{print $NF}' file
filename
filename
filename

SQL How to Select the most recent date item

Select * 
FROM test_table 
WHERE user_id = value 
AND date_added = (select max(date_added) 
   from test_table 
   where user_id = value)

What is App.config in C#.NET? How to use it?

Simply, App.config is an XML based file format that holds the Application Level Configurations.

Example:

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="key" value="test" />
  </appSettings>
</configuration>

You can access the configurations by using ConfigurationManager as shown in the piece of code snippet below:

var value = System.Configuration.ConfigurationManager.AppSettings["key"];
// value is now "test"

Note: ConfigurationSettings is obsolete method to retrieve configuration information.

var value = System.Configuration.ConfigurationSettings.AppSettings["key"];

C++ queue - simple example

Simply declare it as below if you want to us the STL queue container.

std::queue<myclass*> my_queue;

Get the number of rows in a HTML table

var x = document.getElementById("myTable").rows.length;

Fill an array with random numbers

Fast and Easy

double[] anArray = new Random().doubles(10).toArray();

Define a struct inside a class in C++

The other answers here have demonstrated how to define structs inside of classes. There’s another way to do this, and that’s to declare the struct inside the class, but define it outside. This can be useful, for example, if the struct is decently complex and likely to be used standalone in a way that would benefit from being described in detail somewhere else.

The syntax for this is as follows:

class Container {

    ...

    struct Inner; // Declare, but not define, the struct.

    ...

};

struct Container::Inner {
   /* Define the struct here. */
};

You more commonly would see this in the context of defining nested classes rather than structs (a common example would be defining an iterator type for a collection class), but I thought for completeness it would be worth showing off here.

How can I get a List from some class properties with Java 8 Stream?

You can use map :

List<String> names = 
    personList.stream()
              .map(Person::getName)
              .collect(Collectors.toList());

EDIT :

In order to combine the Lists of friend names, you need to use flatMap :

List<String> friendNames = 
    personList.stream()
              .flatMap(e->e.getFriends().stream())
              .collect(Collectors.toList());

Check if a Class Object is subclass of another Class Object in Java

In addition to @To-kra's answer. If someone doesn't like recurrence:

    public static boolean isSubClassOf(Class<?> clazz, Class<?> superClass) {
        if(Object.class.equals(superClass)) {
            return true;
        }

        for(; !Object.class.equals(clazz); clazz = clazz.getSuperclass()) {
            if(clazz.getSuperclass().equals(superClass)) {
                return true;
            }
        }

        return false;
    }

NOTE: no null checking for clarity.

Tool to compare directories (Windows 7)

I use WinMerge. It is free and works pretty well (works for files and directories).

How to access the value of a promise?

This example I find self-explanatory. Notice how await waits for the result and so you miss the Promise being returned.

cryA = crypto.subtle.generateKey({name:'ECDH', namedCurve:'P-384'}, true, ["deriveKey", "deriveBits"])
Promise {<pending>}
cryB = await crypto.subtle.generateKey({name:'ECDH', namedCurve:'P-384'}, true, ["deriveKey", "deriveBits"])
{publicKey: CryptoKey, privateKey: CryptoKey}

Loading DLLs at runtime in C#

It's not so difficult.

You can inspect the available functions of the loaded object, and if you find the one you're looking for by name, then snoop its expected parms, if any. If it's the call you're trying to find, then call it using the MethodInfo object's Invoke method.

Another option is to simply build your external objects to an interface, and cast the loaded object to that interface. If successful, call the function natively.

This is pretty simple stuff.

'if' statement in jinja2 template

We need to remember that the {% endif %} comes after the {% else %}.

So this is an example:

{% if someTest %}
     <p> Something is True </p>
{% else %}
     <p> Something is False </p>
{% endif %}

how to convert `content://media/external/images/media/Y` to `file:///storage/sdcard0/Pictures/X.jpg` in android?

Will something like this work for you? What this does is query the content resolver to find the file path data that is stored for that content entry

public static String getRealPathFromUri(Context context, Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

This will end up giving you an absolute file path that you can construct a file uri from

rebase in progress. Cannot commit. How to proceed or stop (abort)?

I got into this state recently. After resolving conflicts during a rebase, I committed my changes, rather than running git rebase --continue. This yields the same messages you saw when you ran your git status and git rebase --continue commands. I resolved the issue by running git rebase --abort, and then re-running the rebase. One could likely also skip the rebase, but I wasn't sure what state that would leave me in.

$ git rebase --continue
Applying: <commit message>
No changes - did you forget to use 'git add'?
If there is nothing left to stage, chances are that something else
already introduced the same changes; you might want to skip this patch.

When you have resolved this problem, run "git rebase --continue".
If you prefer to skip this patch, run "git rebase --skip" instead.
To check out the original branch and stop rebasing, run "git rebase --abort".

$ git status
rebase in progress; onto 4df0775
You are currently rebasing branch '<local-branch-name>' on '4df0775'.
  (all conflicts fixed: run "git rebase --continue")

nothing to commit, working directory clean

Is there a way to make HTML5 video fullscreen?

The complete solution:

    function bindFullscreen(video) {
            $(video).unbind('click').click(toggleFullScreen);
    }

    function toggleFullScreen() {
            if (!document.fullscreenElement &&    // alternative standard method
                    !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement ) {  // current working methods
                    if (document.documentElement.requestFullscreen) {
                            document.documentElement.requestFullscreen();
                    } else if (document.documentElement.msRequestFullscreen) {
                            document.documentElement.msRequestFullscreen();
                    } else if (document.documentElement.mozRequestFullScreen) {
                            document.documentElement.mozRequestFullScreen();
                    } else if (document.documentElement.webkitRequestFullscreen) {
                            document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
                    }
            } 
            else {
                    if (document.exitFullscreen) {
                            document.exitFullscreen();
                    } else if (document.msExitFullscreen) {
                            document.msExitFullscreen();
                    } else if (document.mozCancelFullScreen) {
                            document.mozCancelFullScreen();
                    } else if (document.webkitExitFullscreen) {
                            document.webkitExitFullscreen();
                    }
            }
    }

Best C++ IDE or Editor for Windows

There are the free "Express" versions of Visual Studio. Given that you like Visual Studio and that the "Express" editions are free, there is no reason to use any other editor.

How to get screen width without (minus) scrollbar?

.prop("clientWidth") and .prop("scrollWidth")

var actualInnerWidth = $("body").prop("clientWidth"); // El. width minus scrollbar width
var actualInnerWidth = $("body").prop("scrollWidth"); // El. width minus scrollbar width

in JavaScript:

var actualInnerWidth = document.body.clientWidth;     // El. width minus scrollbar width
var actualInnerWidth = document.body.scrollWidth;     // El. width minus scrollbar width

P.S: Note that to use scrollWidth reliably your element should not overflow horizontally

jsBin demo


You could also use .innerWidth() but this will work only on the body element

var innerWidth = $('body').innerWidth(); // Width PX minus scrollbar 

git cherry-pick says "...38c74d is a merge but no -m option was given"

-m means the parent number.

From the git doc:

Usually you cannot cherry-pick a merge because you do not know which side of the merge should be considered the mainline. This option specifies the parent number (starting from 1) of the mainline and allows cherry-pick to replay the change relative to the specified parent.

For example, if your commit tree is like below:

- A - D - E - F -   master
   \     /
    B - C           branch one

then git cherry-pick E will produce the issue you faced.

git cherry-pick E -m 1 means using D-E, while git cherry-pick E -m 2 means using B-C-E.

CSS Div width percentage and padding without breaking layout

You can also use the CSS calc() function to subtract the width of your padding from the percentage of your container's width.

An example:

width: calc((100%) - (32px))

Just be sure to make the subtracted width equal to the total padding, not just one half. If you pad both sides of the inner div with 16px, then you should subtract 32px from the final width, assuming that the example below is what you want to achieve.

_x000D_
_x000D_
.outer {_x000D_
  width: 200px;_x000D_
  height: 120px;_x000D_
  background-color: black;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  height: 40px;_x000D_
  top: 30px;_x000D_
  position: relative;_x000D_
  padding: 16px;_x000D_
  background-color: teal;_x000D_
}_x000D_
_x000D_
#inner-1 {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
#inner-2 {_x000D_
  width: calc((100%) - (32px));_x000D_
}
_x000D_
<div class="outer" id="outer-1">_x000D_
  <div class="inner" id="inner-1"> width of 100% </div>_x000D_
</div>_x000D_
_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
<div class="outer" id="outer-2">_x000D_
  <div class="inner" id="inner-2"> width of 100% - 16px </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Creating the Singleton design pattern in PHP5

I agree with the first answer but I would also declare the class as final so that it cannot be extended as extending a singleton violates the singleton pattern. Also the instance variable should be private so that it cannot be accessed directly. Also make the __clone method private so that you cannot clone the singleton object.

Below is some example code.

/**
 * Singleton class
 *
 */
final class UserFactory
{
    private static $_instance = null;

    /**
     * Private constructor
     *
     */
    private function __construct() {}

    /**
     * Private clone method
     *
     */
     private function __clone() {}

    /**
     * Call this method to get singleton
     *
     * @return UserFactory
     */
    public static function getInstance()
    {
        if (self::$_instance === null) {
            self::$_instance = new UserFactory();
        }
        return self::$_instance;
    }
}

Example Usage

$user_factory = UserFactory::getInstance();

What this stops you from doing (which would violate the singleton pattern..

YOU CANNOT DO THIS!

$user_factory = UserFactory::$_instance;

class SecondUserFactory extends UserFactory { }

How do multiple clients connect simultaneously to one port, say 80, on a server?

Multiple clients can connect to the same port (say 80) on the server because on the server side, after creating a socket and binding (setting local IP and port) listen is called on the socket which tells the OS to accept incoming connections.

When a client tries to connect to server on port 80, the accept call is invoked on the server socket. This creates a new socket for the client trying to connect and similarly new sockets will be created for subsequent clients using same port 80.

Words in italics are system calls.

Ref

http://www.scs.stanford.edu/07wi-cs244b/refs/net2.pdf

Best way to generate xml?

Using lxml:

from lxml import etree

# create XML 
root = etree.Element('root')
root.append(etree.Element('child'))
# another child with text
child = etree.Element('child')
child.text = 'some text'
root.append(child)

# pretty string
s = etree.tostring(root, pretty_print=True)
print s

Output:

<root>
  <child/>
  <child>some text</child>
</root>

See the tutorial for more information.

Read and parse a Json File in C#

How about making everything easier with Json.NET?

    public void LoadJson()
    {
        using (StreamReader r = new StreamReader("file.json"))
        {
            string json = r.ReadToEnd();
            List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
        }
    }

    public class Item
    {
        public int millis;
        public string stamp;
        public DateTime datetime;
        public string light;
        public float temp;
        public float vcc;
    }

You can even get the values dynamically without declaring Item class.

    dynamic array = JsonConvert.DeserializeObject(json);
    foreach(var item in array)
    {
        Console.WriteLine("{0} {1}", item.temp, item.vcc);
    }

How to place and center text in an SVG rectangle

I had a bugger of a time getting anything centered using SVG, so I rolled my own little function. hopefully it should help you. Note that it only works for SVG elements.

function centerinparent(element) { //only works for SVG elements
    var bbox = element.getBBox();
    var parentwidth = element.parentNode.width.baseVal.value;
    var parentheight = element.parentNode.height.baseVal.value;
    var newwidth = ((parentwidth / 2) - (bbox.width / 2)) - 2; //i start everything off by 2 to account for line thickness
    var newheight = ((parentheight / 2) - (bbox.height / 2)) - 2;
    //need to adjust for line thickness??

    if (element.classList.contains("textclass")) { //text is origined from bottom left, whereas everything else origin is top left
        newheight += bbox.height; //move it down by its height
    }

    element.setAttributeNS(null, "transform", "translate(" + newwidth + "," + newheight + ")");
    // console.log("centering BOXES:  between width:"+element.parentNode.width.baseVal.value + "   height:"+parentheight);
    // console.log(bbox);
}

How to dismiss ViewController in Swift?

I have a solution for your problem. Please try this code to dismiss the view controller if you present the view using modal:

Swift 3:

self.dismiss(animated: true, completion: nil)

OR

If you present the view using "push" segue

self.navigationController?.popViewController(animated: true)

String.Format not work in TypeScript

As a workaround which achieves the same purpose, you may use the sprintf-js library and types.

I got it from another SO answer.

SQL SELECT WHERE field contains words

Instead of SELECT * FROM MyTable WHERE Column1 CONTAINS 'word1 word2 word3', add And in between those words like:

SELECT * FROM MyTable WHERE Column1 CONTAINS 'word1 And word2 And word3'

for details, see here https://msdn.microsoft.com/en-us/library/ms187787.aspx

UPDATE

For selecting phrases, use double quotes like:

SELECT * FROM MyTable WHERE Column1 CONTAINS '"Phrase one" And word2 And "Phrase Two"'

p.s. you have to first enable Full Text Search on the table before using contains keyword. for more details, See here https://docs.microsoft.com/en-us/sql/relational-databases/search/get-started-with-full-text-search

How to deep watch an array in angularjs?

This solution worked very well for me, i'm doing this in a directive:

scope.$watch(attrs.testWatch, function() {.....}, true);

the true works pretty well and react for all the chnages (add, delete, or modify a field).

Here is a working plunker for play with it.

Deeply Watching an Array in AngularJS

I hope this can be useful for you. If you have any questions, feel free for ask, I'll try to help :)

What throws an IOException in Java?

Java documentation is helpful to know the root cause of a particular IOException.

Just have a look at the direct known sub-interfaces of IOException from the documentation page:

ChangedCharSetException, CharacterCodingException, CharConversionException, ClosedChannelException, EOFException, FileLockInterruptionException, FileNotFoundException, FilerException, FileSystemException, HttpRetryException, IIOException, InterruptedByTimeoutException, InterruptedIOException, InvalidPropertiesFormatException, JMXProviderException, JMXServerErrorException, MalformedURLException, ObjectStreamException, ProtocolException, RemoteException, SaslException, SocketException, SSLException, SyncFailedException, UnknownHostException, UnknownServiceException, UnsupportedDataTypeException, UnsupportedEncodingException, UserPrincipalNotFoundException, UTFDataFormatException, ZipException

Most of these exceptions are self-explanatory.

A few IOExceptions with root causes:

EOFException: Signals that an end of file or end of stream has been reached unexpectedly during input. This exception is mainly used by data input streams to signal the end of the stream.

SocketException: Thrown to indicate that there is an error creating or accessing a Socket.

RemoteException: A RemoteException is the common superclass for a number of communication-related exceptions that may occur during the execution of a remote method call. Each method of a remote interface, an interface that extends java.rmi.Remote, must list RemoteException in its throws clause.

UnknownHostException: Thrown to indicate that the IP address of a host could not be determined (you may not be connected to Internet).

MalformedURLException: Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.

How to convert a String to JsonObject using gson library

String emailData = {"to": "[email protected]","subject":"User details","body": "The user has completed his training"
}

// Java model class
public class EmailData {
    public String to;
    public String subject;
    public String body;
}

//Final Data
Gson gson = new Gson();  
EmailData emaildata = gson.fromJson(emailData, EmailData.class);

How to copy a file to multiple directories using the gnu cp command

No - you cannot.

I've found on multiple occasions that I could use this functionality so I've made my own tool to do this for me.

http://github.com/ddavison/branch

pretty simple -
branch myfile dir1 dir2 dir3

How can I do factory reset using adb in android?

You can send intent MASTER_CLEAR in adb:

adb shell am broadcast -a android.intent.action.MASTER_CLEAR

or as root

adb shell  "su -c 'am broadcast -a android.intent.action.MASTER_CLEAR'"

What's the difference between IFrame and Frame?

The difference is an iframe is able to "float" within content in a page, that is you can create an html page and position an iframe within it. This allows you to have a page and place another document directly in it. A frameset allows you to split the screen into different pages (horizontally and vertically) and display different documents in each part.

Read IFrames security summary.

How to remove space from string?

Since you're using bash, the fastest way would be:

shopt -s extglob # Allow extended globbing
var=" lakdjsf   lkadsjf "
echo "${var//+([[:space:]])/}"

It's fastest because it uses built-in functions instead of firing up extra processes.

However, if you want to do it in a POSIX-compliant way, use sed:

var=" lakdjsf   lkadsjf "
echo "$var" | sed 's/[[:space:]]//g'

SQL LEFT JOIN Subquery Alias

I recognize that the answer works and has been accepted but there is a much cleaner way to write that query. Tested on mysql and postgres.

SELECT wpoi.order_id As No_Commande
FROM  wp_woocommerce_order_items AS wpoi
LEFT JOIN wp_postmeta AS wpp ON wpoi.order_id = wpp.post_id 
                            AND wpp.meta_key = '_shipping_first_name'
WHERE  wpoi.order_id =2198 

What is the &#xA; character?

&#xA; is the HTML representation in hex of a line feed character. It represents a new line on Unix and Unix-like (for example) operating systems.

You can find a list of such characters at (for example) http://la.remifa.so/unicode/latin1.html

How to show PIL images on the screen?

From near the beginning of the PIL Tutorial:

Once you have an instance of the Image class, you can use the methods defined by this class to process and manipulate the image. For example, let's display the image we just loaded:

     >>> im.show()

Update:

Nowadays theImage.show() method is formally documented in the Pillow fork of PIL along with an explanation of how it's implemented on different OSs.

How to change content on hover

The CSS content property along with ::after and ::before pseudo-elements have been introduced for this.

.item:hover a p.new-label:after{
    content: 'ADD';
}

JSFiddle Demo

How do I escape ampersands in batch files?

For special characters like '&' you can surround the entire expression with quotation marks

set "url=https://url?retry=true&w=majority"

Assign variable value inside if-statement

I believe that your problem is due to the fact that you are defining the variable v inside the test. As explained by @rmalchow, it will work you change it into

int v;
if((v = someMethod()) != 0) return true;

There is also another issue of variable scope. Even if what you tried were to work, what would be the point? Assuming you could define the variable scope inside the test, your variable v would not exist outside that scope. Hence, creating the variable and assigning the value would be pointless, for you would not be able to use it.

Variables exist only in the scope they were created. Since you are assigning the value to use it afterwards, consider the scope where you are creating the varible so that it may be used where needed.

When should I use curly braces for ES6 import?

Summary ES6 modules:

Exports:

You have two types of exports:

  1. Named exports
  2. Default exports, a maximum one per module

Syntax:

// Module A
export const importantData_1 = 1;
export const importantData_2 = 2;
export default function foo () {}

Imports:

The type of export (i.e., named or default exports) affects how to import something:

  1. For a named export we have to use curly braces and the exact name as the declaration (i.e. variable, function, or class) which was exported.
  2. For a default export we can choose the name.

Syntax:

// Module B, imports from module A which is located in the same directory

import { importantData_1 , importantData_2  } from './A';  // For our named imports

// Syntax single named import:
// import { importantData_1 }

// For our default export (foo), the name choice is arbitrary
import ourFunction from './A';

Things of interest:

  1. Use a comma-separated list within curly braces with the matching name of the export for named export.
  2. Use a name of your choosing without curly braces for a default export.

Aliases:

Whenever you want to rename a named import this is possible via aliases. The syntax for this is the following:

import { importantData_1 as myData } from './A';

Now we have imported importantData_1, but the identifier is myData instead of importantData_1.

"Non-static method cannot be referenced from a static context" error

You need to correctly separate static data from instance data. In your code, onLoan and setLoanItem() are instance members. If you want to reference/call them you must do so via an instance. So you either want

public void loanItem() {
    this.media.setLoanItem("Yes");
}

or

public void loanItem(Media object) {
    object.setLoanItem("Yes");
}

depending on how you want to pass that instance around.

jQuery append text inside of an existing paragraph tag

Try this...

$('p').append('<span id="add_here">new-dynamic-text</span>');

OR if there is an existing span, do this.

$('p').children('span').text('new-dynamic-text');

DEMO

Why is division in Ruby returning an integer instead of decimal value?

You can check it with irb:

$ irb
>> 2 / 3
=> 0
>> 2.to_f / 3
=> 0.666666666666667
>> 2 / 3.to_f
=> 0.666666666666667

How to declare a variable in SQL Server and use it in the same Stored Procedure

In sql 2012 (and maybe as far back as 2005), you should do this:

EXEC AddBrand @BrandName = 'Gucci', @CategoryId = 23

jQuery class within class selector

is just going to look for a div with class="outer inner", is that correct?

No, '.outer .inner' will look for all elements with the .inner class that also have an element with the .outer class as an ancestor. '.outer.inner' (no space) would give the results you're thinking of.

'.outer > .inner' will look for immediate children of an element with the .outer class for elements with the .inner class.

Both '.outer .inner' and '.outer > .inner' should work for your example, although the selectors are fundamentally different and you should be wary of this.

Adjust plot title (main) position

We can use title() function with negative line value to bring down the title.

See this example:

plot(1, 1)
title("Title", line = -2)

enter image description here

Please explain the exec() function and its family

what is the exec function and its family.

The exec function family is all functions used to execute a file, such as execl, execlp, execle, execv, and execvp.They are all frontends for execve and provide different methods of calling it.

why is this function used

Exec functions are used when you want to execute (launch) a file (program).

and how does it work.

They work by overwriting the current process image with the one that you launched. They replace (by ending) the currently running process (the one that called the exec command) with the new process that has launched.

For more details: see this link.

When to use the !important property in CSS

Using !important is generally not a good idea in the code itself, but it can be useful in various overrides.

I use Firefox and a dotjs plugin which essentially can run your own custom JS or CSS code on specified websites automatically.

Here's the code for it I use on Twitter that makes the tweet input field always stay on my screen no matter how far I scroll, and for the hyperlinks to always remain the same color.

a, a * {
  color: rgb(34, 136, 85) !important;  
}

.count-inner {
 color: white !important;   
}

.timeline-tweet-box {
 z-index: 99 !important;
position: fixed !important;
left: 5% !important;   
}

Since, thankfully, Twitter developers don't use !important properties much, I can use it to guarantee that the specified styles will be definitely overridden, because without !important they were not overridden sometimes. It really came in handy for me there.

Good PHP ORM Library?

There's a fantastic ORM included in the QCubed framework; it's based on code generation and scaffolding. Unlike the ActiveRecord that's based on reflection and is generally slow, code generation makes skeleton classes for you based on the database and lets you customize them afterward. It works like a charm.

What's the safest way to iterate through the keys of a Perl hash?

The rule of thumb is to use the function most suited to your needs.

If you just want the keys and do not plan to ever read any of the values, use keys():

foreach my $key (keys %hash) { ... }

If you just want the values, use values():

foreach my $val (values %hash) { ... }

If you need the keys and the values, use each():

keys %hash; # reset the internal iterator so a prior each() doesn't affect the loop
while(my($k, $v) = each %hash) { ... }

If you plan to change the keys of the hash in any way except for deleting the current key during the iteration, then you must not use each(). For example, this code to create a new set of uppercase keys with doubled values works fine using keys():

%h = (a => 1, b => 2);

foreach my $k (keys %h)
{
  $h{uc $k} = $h{$k} * 2;
}

producing the expected resulting hash:

(a => 1, A => 2, b => 2, B => 4)

But using each() to do the same thing:

%h = (a => 1, b => 2);

keys %h;
while(my($k, $v) = each %h)
{
  $h{uc $k} = $h{$k} * 2; # BAD IDEA!
}

produces incorrect results in hard-to-predict ways. For example:

(a => 1, A => 2, b => 2, B => 8)

This, however, is safe:

keys %h;
while(my($k, $v) = each %h)
{
  if(...)
  {
    delete $h{$k}; # This is safe
  }
}

All of this is described in the perl documentation:

% perldoc -f keys
% perldoc -f each

Understanding ibeacon distancing

iBeacon uses Bluetooth Low Energy(LE) to keep aware of locations, and the distance/range of Bluetooth LE is 160ft (http://en.wikipedia.org/wiki/Bluetooth_low_energy).

Fast check for NaN in NumPy

Related to this is the question of how to find the first occurrence of NaN. This is the fastest way to handle that that I know of:

index = next((i for (i,n) in enumerate(iterable) if n!=n), None)

how to make a specific text on TextView BOLD

If you are using Kotlin, it becomes even easier to do by using core-ktx, as it provides a domain-specific-language (DSL) for doing this:

val string: SpannedString = buildSpannedString {
    bold {
        append("foo")
    }
    append("bar")     
}

More options provided by it are:

append("Hello There")
bold {
    append("bold")
    italic {
        append("bold and italic")
        underline {
            append("then some text with underline")
        }
    }
}

At last, you can just to:

textView.text = string

Get scroll position using jquery

cross browser variant

$(document).scrollTop();

Android ADB doesn't see device

On windows, you will need to install drivers for the device for adb to recognize it. To see if the drivers are installed, check the device manager. If there is any "unrecognized device" in the device manager, the drivers are not installed. You can usually get the adb drivers from the manufacturers.

How can I use PHP to dynamically publish an ical file to be read by Google Calendar?

http://www.kanzaki.com/docs/ical/ has a slightly more readable version of the older spec. It helps as a starting point - many things are still the same.

Also on my site, I have

  1. Some lists of useful resources (see sidebar bottom right) on
    • ical Spec RFC 5545
    • ical Testing Resources
  2. Some notes recorded on my journey working with .ics over the last few years. In particular, you may find this repeating events 'cheatsheet' to be useful.

.ics areas that need careful handling:

  • 'all day' events
  • types of dates (timezone, UTC, or local 'floating') - nb to understand distinction
  • interoperability of recurrence rules

Is it good practice to make the constructor throw an exception?

Throwing exceptions in a constructor is not bad practice. In fact, it is the only reasonable way for a constructor to indicate that there is a problem; e.g. that the parameters are invalid.

I also think that throwing checked exceptions can be OK1, assuming that the checked exception is 1) declared, 2) specific to the problem you are reporting, and 3) it is reasonable to expect the caller to deal with a checked exception for this2.

However explicitly declaring or throwing java.lang.Exception is almost always bad practice.

You should pick an exception class that matches the exceptional condition that has occurred. If you throw Exception it is difficult for the caller to separate this exception from any number of other possible declared and undeclared exceptions. This makes error recovery difficult, and if the caller chooses to propagate the Exception, the problem just spreads.


1 - Some people may disagree, but IMO there is no substantive difference between this case and the case of throwing exceptions in methods. The standard checked vs unchecked advice applies equally to both cases.

2 - For example, the existing FileInputStream constructors will throw FileNotFoundException if you try to open a file that does not exist. Assuming that it is reasonable for FileNotFoundException to be a checked exception3, then the constructor is the most appropriate place for that exception to be thrown. If we threw the FileNotFoundException the first time that (say) a read or write call was made, that is liable to make application logic more complicated.

3 - Given that this is one of the motivating examples for checked exceptions, if you don't accept this you are basically saying that all exceptions should be unchecked. That is not practical ... if you are going to use Java.


Someone suggested using assert for checking arguments. The problem with this is that checking of assert assertions can be turned on and off via a JVM command-line setting. Using assertions to check internal invariants is OK, but using them to implement argument checking that is specified in your javadoc is not a good idea ... because it means your method will only strictly implement the specification when assertion checking is enabled.

The second problem with assert is that if an assertion fails, then AssertionError will be thrown, and received wisdom is that it is a bad idea to attempt to catch Error and any of its subtypes.

VBA (Excel) Initialize Entire Array without Looping

I want to initialize every single element of the array to some initial value. So if I have an array Dim myArray(300) As Integer of 300 integers, for example, all 300 elements would hold the same initial value (say, the number 13).

Can anyone explain how to do this, without looping? I'd like to do it in one statement if possible.

What do I win?

Sub SuperTest()
   Dim myArray
   myArray = Application.Transpose([index(Row(1:300),)-index(Row(1:300),)+13])
End Sub

Remove row lines in twitter bootstrap

In Bootstrap 3 I've added a table-no-border class

.table-no-border>thead>tr>th, 
.table-no-border>tbody>tr>th, 
.table-no-border>tfoot>tr>th, 
.table-no-border>thead>tr>td, 
.table-no-border>tbody>tr>td, 
.table-no-border>tfoot>tr>td {
  border-top: none; 
}

C#: HttpClient with POST parameters

As Ben said, you are POSTing your request ( HttpMethod.Post specified in your code )

The querystring (get) parameters included in your url probably will not do anything.

Try this:

string url = "http://myserver/method";    
string content = "param1=1&param2=2";
HttpClientHandler handler = new HttpClientHandler();
HttpClient httpClient = new HttpClient(handler);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
HttpResponseMessage response = await httpClient.SendAsync(request,content);

HTH,

bovako

How to solve : SQL Error: ORA-00604: error occurred at recursive SQL level 1

One possible explanation is a database trigger that fires for each DROP TABLE statement. To find the trigger, query the _TRIGGERS dictionary views:

select * from all_triggers
where trigger_type in ('AFTER EVENT', 'BEFORE EVENT')

disable any suspicious trigger with

   alter trigger <trigger_name> disable;

and try re-running your DROP TABLE statement

How can I tell when HttpClient has timed out?

As of .NET 5, the implementation has changed. HttpClient still throws a TaskCanceledException, but now wraps a TimeoutException as InnerException. So you can easily check whether a request was canceled or timed out (code sample copied from linked blog post):

try
{
    using var response = await _client.GetAsync("http://localhost:5001/sleepFor?seconds=100");
}
// Filter by InnerException.
catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException)
{
    // Handle timeout.
    Console.WriteLine("Timed out: "+ ex.Message);
}
catch (TaskCanceledException ex)
{
    // Handle cancellation.
    Console.WriteLine("Canceled: " + ex.Message);   
}

LINQ - Full Outer Join

Performs a in-memory streaming enumeration over both inputs and invokes the selector for each row. If there is no correlation at the current iteration, one of the selector arguments will be null.

Example:

   var result = left.FullOuterJoin(
         right, 
         x=>left.Key, 
         x=>right.Key, 
         (l,r) => new { LeftKey = l?.Key, RightKey=r?.Key });
  • Requires an IComparer for the correlation type, uses the Comparer.Default if not provided.

  • Requires that 'OrderBy' is applied to the input enumerables

    /// <summary>
    /// Performs a full outer join on two <see cref="IEnumerable{T}" />.
    /// </summary>
    /// <typeparam name="TLeft"></typeparam>
    /// <typeparam name="TValue"></typeparam>
    /// <typeparam name="TRight"></typeparam>
    /// <typeparam name="TResult"></typeparam>
    /// <param name="left"></param>
    /// <param name="right"></param>
    /// <param name="leftKeySelector"></param>
    /// <param name="rightKeySelector"></param>
    /// <param name="selector">Expression defining result type</param>
    /// <param name="keyComparer">A comparer if there is no default for the type</param>
    /// <returns></returns>
    [System.Diagnostics.DebuggerStepThrough]
    public static IEnumerable<TResult> FullOuterJoin<TLeft, TRight, TValue, TResult>(
        this IEnumerable<TLeft> left,
        IEnumerable<TRight> right,
        Func<TLeft, TValue> leftKeySelector,
        Func<TRight, TValue> rightKeySelector,
        Func<TLeft, TRight, TResult> selector,
        IComparer<TValue> keyComparer = null)
        where TLeft: class
        where TRight: class
        where TValue : IComparable
    {
    
        keyComparer = keyComparer ?? Comparer<TValue>.Default;
    
        using (var enumLeft = left.OrderBy(leftKeySelector).GetEnumerator())
        using (var enumRight = right.OrderBy(rightKeySelector).GetEnumerator())
        {
    
            var hasLeft = enumLeft.MoveNext();
            var hasRight = enumRight.MoveNext();
            while (hasLeft || hasRight)
            {
    
                var currentLeft = enumLeft.Current;
                var valueLeft = hasLeft ? leftKeySelector(currentLeft) : default(TValue);
    
                var currentRight = enumRight.Current;
                var valueRight = hasRight ? rightKeySelector(currentRight) : default(TValue);
    
                int compare =
                    !hasLeft ? 1
                    : !hasRight ? -1
                    : keyComparer.Compare(valueLeft, valueRight);
    
                switch (compare)
                {
                    case 0:
                        // The selector matches. An inner join is achieved
                        yield return selector(currentLeft, currentRight);
                        hasLeft = enumLeft.MoveNext();
                        hasRight = enumRight.MoveNext();
                        break;
                    case -1:
                        yield return selector(currentLeft, default(TRight));
                        hasLeft = enumLeft.MoveNext();
                        break;
                    case 1:
                        yield return selector(default(TLeft), currentRight);
                        hasRight = enumRight.MoveNext();
                        break;
                }
            }
    
        }
    
    }
    

How do I automatically play a Youtube video (IFrame API) muted?

Youtube don't provide muting through url parameter (see http://code.google.com/apis/youtube/player_parameters.html).

You have to use javascript for that. see http://code.google.com/apis/youtube/js_api_reference.html for details.

However, please note the warning on the page linked above: "The deprecation of the YouTube JavaScript Player API was announced on January 27, 2015. YouTube Flash embeds have also been deprecated. See the deprecation policy for more information. Please migrate your applications to the IFrame API, which can intelligently use whichever embedded player – HTML () or Flash () – the client supports."

Html

<iframe class="youtube-player" id="player" type="text/html" src="http://www.youtube.com/embed/JW5meKfy3fY?wmode=opaque&autohide=1&autoplay=1&enablejsapi=1" frameborder="0">&lt;br /&gt;</iframe>

please note enablejsapi=1 in the url.

Javascript

var player =  iframe.getElementById('player');
player.mute();

Update

Previous code had some issues and did not work with current API (playerVars syntax was wrong). Here is the updated code. You may need to tinker with the parameters you need.

_x000D_
_x000D_
         _x000D_
    <div id="player"></div>_x000D_
    <script>_x000D_
      // 1. This code loads the IFrame Player API code asynchronously._x000D_
      var tag = document.createElement('script');_x000D_
_x000D_
      tag.src = "https://www.youtube.com/iframe_api";_x000D_
      var firstScriptTag = document.getElementsByTagName('script')[0];_x000D_
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);_x000D_
_x000D_
      // 2. This function creates an <iframe> (and YouTube player)_x000D_
      //    after the API code downloads._x000D_
      var player;_x000D_
      function onYouTubeIframeAPIReady() {_x000D_
        player = new YT.Player('player', {_x000D_
          height: '100%',_x000D_
          width: '100%',_x000D_
          playerVars: {_x000D_
                    autoplay: 1,_x000D_
                    loop: 1,_x000D_
                    controls: 0,_x000D_
                    showinfo: 0,_x000D_
                    autohide: 1,_x000D_
                    modestbranding: 1,_x000D_
                    vq: 'hd1080'},_x000D_
          videoId: '1pzWROvY7gY',_x000D_
          events: {_x000D_
            'onReady': onPlayerReady,_x000D_
            'onStateChange': onPlayerStateChange_x000D_
          }_x000D_
        });_x000D_
      }_x000D_
_x000D_
      // 3. The API will call this function when the video player is ready._x000D_
      function onPlayerReady(event) {_x000D_
        event.target.playVideo();_x000D_
        player.mute();_x000D_
      }_x000D_
_x000D_
      var done = false;_x000D_
      function onPlayerStateChange(event) {_x000D_
        _x000D_
      }_x000D_
      function stopVideo() {_x000D_
        player.stopVideo();_x000D_
      }_x000D_
    </script>
_x000D_
_x000D_
_x000D_

SQL SERVER: Get total days between two dates

See DateDiff:

DECLARE @startdate date = '2011/1/1'
DECLARE @enddate date = '2011/3/1'
SELECT DATEDIFF(day, @startdate, @enddate)

How does paintComponent work?

Two things you can do here:

  1. Read Painting in AWT and Swing
  2. Use a debugger and put a breakpoint in the paintComponent method. Then travel up the stacktrace and see how provides the Graphics parameter.

Just for info, here is the stacktrace that I got from the example of code I posted at the end:

Thread [AWT-EventQueue-0] (Suspended (breakpoint at line 15 in TestPaint))  
    TestPaint.paintComponent(Graphics) line: 15 
    TestPaint(JComponent).paint(Graphics) line: 1054    
    JPanel(JComponent).paintChildren(Graphics) line: 887    
    JPanel(JComponent).paint(Graphics) line: 1063   
    JLayeredPane(JComponent).paintChildren(Graphics) line: 887  
    JLayeredPane(JComponent).paint(Graphics) line: 1063 
    JLayeredPane.paint(Graphics) line: 585  
    JRootPane(JComponent).paintChildren(Graphics) line: 887 
    JRootPane(JComponent).paintToOffscreen(Graphics, int, int, int, int, int, int) line: 5228   
    RepaintManager$PaintManager.paintDoubleBuffered(JComponent, Image, Graphics, int, int, int, int) line: 1482 
    RepaintManager$PaintManager.paint(JComponent, JComponent, Graphics, int, int, int, int) line: 1413  
    RepaintManager.paint(JComponent, JComponent, Graphics, int, int, int, int) line: 1206   
    JRootPane(JComponent).paint(Graphics) line: 1040    
    GraphicsCallback$PaintCallback.run(Component, Graphics) line: 39    
    GraphicsCallback$PaintCallback(SunGraphicsCallback).runOneComponent(Component, Rectangle, Graphics, Shape, int) line: 78    
    GraphicsCallback$PaintCallback(SunGraphicsCallback).runComponents(Component[], Graphics, int) line: 115 
    JFrame(Container).paint(Graphics) line: 1967    
    JFrame(Window).paint(Graphics) line: 3867   
    RepaintManager.paintDirtyRegions(Map<Component,Rectangle>) line: 781    
    RepaintManager.paintDirtyRegions() line: 728    
    RepaintManager.prePaintDirtyRegions() line: 677 
    RepaintManager.access$700(RepaintManager) line: 59  
    RepaintManager$ProcessingRunnable.run() line: 1621  
    InvocationEvent.dispatch() line: 251    
    EventQueue.dispatchEventImpl(AWTEvent, Object) line: 705    
    EventQueue.access$000(EventQueue, AWTEvent, Object) line: 101   
    EventQueue$3.run() line: 666    
    EventQueue$3.run() line: 664    
    AccessController.doPrivileged(PrivilegedAction<T>, AccessControlContext) line: not available [native method]    
    ProtectionDomain$1.doIntersectionPrivilege(PrivilegedAction<T>, AccessControlContext, AccessControlContext) line: 76    
    EventQueue.dispatchEvent(AWTEvent) line: 675    
    EventDispatchThread.pumpOneEventForFilters(int) line: 211   
    EventDispatchThread.pumpEventsForFilter(int, Conditional, EventFilter) line: 128    
    EventDispatchThread.pumpEventsForHierarchy(int, Conditional, Component) line: 117   
    EventDispatchThread.pumpEvents(int, Conditional) line: 113  
    EventDispatchThread.pumpEvents(Conditional) line: 105   
    EventDispatchThread.run() line: 90  

The Graphics parameter comes from here:

RepaintManager.paintDirtyRegions(Map) line: 781 

The snippet involved is the following:

Graphics g = JComponent.safelyGetGraphics(
                        dirtyComponent, dirtyComponent);
                // If the Graphics goes away, it means someone disposed of
                // the window, don't do anything.
                if (g != null) {
                    g.setClip(rect.x, rect.y, rect.width, rect.height);
                    try {
                        dirtyComponent.paint(g); // This will eventually call paintComponent()
                    } finally {
                        g.dispose();
                    }
                }

If you take a look at it, you will see that it retrieve the graphics from the JComponent itself (indirectly with javax.swing.JComponent.safelyGetGraphics(Component, Component)) which itself takes it eventually from its first "Heavyweight parent" (clipped to the component bounds) which it self takes it from its corresponding native resource.

Regarding the fact that you have to cast the Graphics to a Graphics2D, it just happens that when working with the Window Toolkit, the Graphics actually extends Graphics2D, yet you could use other Graphics which do "not have to" extends Graphics2D (it does not happen very often but AWT/Swing allows you to do that).

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

class TestPaint extends JPanel {

    public TestPaint() {
        setBackground(Color.WHITE);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawOval(0, 0, getWidth(), getHeight());
    }

    public static void main(String[] args) {
        JFrame jFrame = new JFrame();
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.setSize(300, 300);
        jFrame.add(new TestPaint());
        jFrame.setVisible(true);
    }
}

Convert UTC to local time in Rails 3

If you're actually doing it just because you want to get the user's timezone then all you have to do is change your timezone in you config/applications.rb.

Like this:

Rails, by default, will save your time record in UTC even if you specify the current timezone.

config.time_zone = "Singapore"

So this is all you have to do and you're good to go.

How do I compile a Visual Studio project from the command-line?

MSBuild usually works, but I've run into difficulties before. You may have better luck with

devenv YourSolution.sln /Build 

How to check if there exists a process with a given pid in Python?

mluebke code is not 100% correct; kill() can also raise EPERM (access denied) in which case that obviously means a process exists. This is supposed to work:

(edited as per Jason R. Coombs comments)

import errno
import os

def pid_exists(pid):
    """Check whether pid exists in the current process table.
    UNIX only.
    """
    if pid < 0:
        return False
    if pid == 0:
        # According to "man 2 kill" PID 0 refers to every process
        # in the process group of the calling process.
        # On certain systems 0 is a valid PID but we have no way
        # to know that in a portable fashion.
        raise ValueError('invalid PID 0')
    try:
        os.kill(pid, 0)
    except OSError as err:
        if err.errno == errno.ESRCH:
            # ESRCH == No such process
            return False
        elif err.errno == errno.EPERM:
            # EPERM clearly means there's a process to deny access to
            return True
        else:
            # According to "man 2 kill" possible error values are
            # (EINVAL, EPERM, ESRCH)
            raise
    else:
        return True

You can't do this on Windows unless you use pywin32, ctypes or a C extension module. If you're OK with depending from an external lib you can use psutil:

>>> import psutil
>>> psutil.pid_exists(2353)
True

JavaScript listener, "keypress" doesn't detect backspace?

Try keydown instead of keypress.

The keyboard events occur in this order: keydown, keyup, keypress

The problem with backspace probably is, that the browser will navigate back on keyup and thus your page will not see the keypress event.

Request Monitoring in Chrome

Open up your DevTools and press F1 to access the settings. Look for the console section and check the checkbox for "Log XMLHttpRequests".

Now all of your ajax and other similar requests will be logged in the console.

I prefer this method because it usually allows me to see everything that I'm looking for in the console without having to go to the network tab.

Deleting an element from an array in PHP

Follow the default functions:

  • PHP: unset

unset() destroys the specified variables. For more info, you can refer to PHP unset

$Array = array("test1", "test2", "test3", "test3");

unset($Array[2]);
  • PHP: array_pop

The array_pop() function deletes the last element of an array. For more info, you can refer to PHP array_pop

$Array = array("test1", "test2", "test3", "test3");

array_pop($Array);
  • PHP: array_splice

The array_splice() function removes selected elements from an array and replaces it with new elements. For more info, you can refer to PHP array_splice

$Array = array("test1", "test2", "test3", "test3");

array_splice($Array,1,2);
  • PHP: array_shift

The array_shift() function removes the first element from an array. For more info, you can refer to PHP array_shift

$Array = array("test1", "test2", "test3", "test3");

array_shift($Array);

How can I check MySQL engine type for a specific table?

SHOW CREATE TABLE <tablename>\G

will format it much nicer compared to the output of

SHOW CREATE TABLE <tablename>;

The \G trick is also useful to remember for many other queries/commands.

Query to count the number of tables I have in MySQL

SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'dbo' and TABLE_TYPE='BASE TABLE'

How do I show a console output/window in a forms application?

Building on Chaz's answer, in .NET 5 there is a breaking change, so two modifications are required in the project file, i.e. changing OutputType and adding DisableWinExeOutputInference. Example:

<PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net5.0-windows10.0.17763.0</TargetFramework>
    <UseWindowsForms>true</UseWindowsForms>
    <DisableWinExeOutputInference>true</DisableWinExeOutputInference>
    <Platforms>AnyCPU;x64;x86</Platforms>
</PropertyGroup>

.htaccess file to allow access to images folder to view pictures?

Create a .htaccess file in the images folder and add this

<IfModule mod_rewrite.c>
RewriteEngine On
# directory browsing
Options All +Indexes
</IfModule>

you can put this Options All -Indexes in the project file .htaccess ,file to deny direct access to other folders.

This does what you want

How to solve Object reference not set to an instance of an object.?

You need to initialize the list first:

protected List<string> list = new List<string>();

Is it possible to serialize and deserialize a class in C++?

As far as "built-in" libraries go, the << and >> have been reserved specifically for serialization.

You should override << to output your object to some serialization context (usually an iostream) and >> to read data back from that context. Each object is responsible for outputting its aggregated child objects.

This method works fine so long as your object graph contains no cycles.

If it does, then you will have to use a library to deal with those cycles.

How do I execute a command and get the output of the command within C++ using POSIX?

Two possible approaches:

  1. I don't think popen() is part of the C++ standard (it's part of POSIX from memory), but it's available on every UNIX I've worked with (and you seem to be targeting UNIX since your command is ./some_command).

  2. On the off-chance that there is no popen(), you can use system("./some_command >/tmp/some_command.out");, then use the normal I/O functions to process the output file.

Multiple input in JOptionPane.showInputDialog

Yes. You know that you can put any Object into the Object parameter of most JOptionPane.showXXX methods, and often that Object happens to be a JPanel.

In your situation, perhaps you could use a JPanel that has several JTextFields in it:

import javax.swing.*;

public class JOptionPaneMultiInput {
   public static void main(String[] args) {
      JTextField xField = new JTextField(5);
      JTextField yField = new JTextField(5);

      JPanel myPanel = new JPanel();
      myPanel.add(new JLabel("x:"));
      myPanel.add(xField);
      myPanel.add(Box.createHorizontalStrut(15)); // a spacer
      myPanel.add(new JLabel("y:"));
      myPanel.add(yField);

      int result = JOptionPane.showConfirmDialog(null, myPanel, 
               "Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION);
      if (result == JOptionPane.OK_OPTION) {
         System.out.println("x value: " + xField.getText());
         System.out.println("y value: " + yField.getText());
      }
   }
}

Zoom in on a point (using scale and translate)

I want to put here some information for those, who do separately drawing of picture and moving -zooming it.

This may be useful when you want to store zooms and position of viewport.

Here is drawer:

function redraw_ctx(){
   self.ctx.clearRect(0,0,canvas_width, canvas_height)
   self.ctx.save()
   self.ctx.scale(self.data.zoom, self.data.zoom) // 
   self.ctx.translate(self.data.position.left, self.data.position.top) // position second
   // Here We draw useful scene My task - image:
   self.ctx.drawImage(self.img ,0,0) // position 0,0 - we already prepared
   self.ctx.restore(); // Restore!!!
}

Notice scale MUST be first.

And here is zoomer:

function zoom(zf, px, py){
    // zf - is a zoom factor, which in my case was one of (0.1, -0.1)
    // px, py coordinates - is point within canvas 
    // eg. px = evt.clientX - canvas.offset().left
    // py = evt.clientY - canvas.offset().top
    var z = self.data.zoom;
    var x = self.data.position.left;
    var y = self.data.position.top;

    var nz = z + zf; // getting new zoom
    var K = (z*z + z*zf) // putting some magic

    var nx = x - ( (px*zf) / K ); 
    var ny = y - ( (py*zf) / K);

    self.data.position.left = nx; // renew positions
    self.data.position.top = ny;   
    self.data.zoom = nz; // ... and zoom
    self.redraw_ctx(); // redraw context
    }

and, of course, we would need a dragger:

this.my_cont.mousemove(function(evt){
    if (is_drag){
        var cur_pos = {x: evt.clientX - off.left,
                       y: evt.clientY - off.top}
        var diff = {x: cur_pos.x - old_pos.x,
                    y: cur_pos.y - old_pos.y}

        self.data.position.left += (diff.x / self.data.zoom);  // we want to move the point of cursor strictly
        self.data.position.top += (diff.y / self.data.zoom);

        old_pos = cur_pos;
        self.redraw_ctx();

    }


})

PHP - Check if the page run on Mobile or Desktop browser

<?php //-- Very simple variant
$useragent = $_SERVER['HTTP_USER_AGENT']; 
$iPod = stripos($useragent, "iPod"); 
$iPad = stripos($useragent, "iPad"); 
$iPhone = stripos($useragent, "iPhone");
$Android = stripos($useragent, "Android"); 
$iOS = stripos($useragent, "iOS");
//-- You can add billion devices 

$DEVICE = ($iPod||$iPad||$iPhone||$Android||$iOS||$webOS||$Blackberry||$IEMobile||$OperaMini);

if ($DEVICE !=true) {?>

<!-- What you want for all non-mobile devices. Anything with all HTML codes-->

<?php }else{ ?> 

<!-- What you want for all mobile devices. Anything with all HTML codes --> 
<?php } ?>

Convert special characters to HTML in Javascript

This doesn't direcly answer your question, but if you are using innerHTML in order to write text within an element and you ran into encoding issues, just use textContent, i.e.:

var s = "Foo 'bar' baz <qux>";

var element = document.getElementById('foo');
element.textContent = s;

// <div id="foo">Foo 'bar' baz <qux></div>

How do I deploy Node.js applications as a single executable file?

In addition to nexe, browserify can be used to bundle up all your dependencies as a single .js file. This does not bundle the actual node executable, just handles the javascript side. It too does not handle native modules. The command line options for pure node compilation would be browserify --output bundle.js --bare --dg false input.js.

How to cast List<Object> to List<MyClass>

As others have pointed out, you cannot savely cast them, since a List<Object> isn't a List<Customer>. What you could do, is to define a view on the list that does in-place type checking. Using Google Collections that would be:

return Lists.transform(list, new Function<Object, Customer>() {
  public Customer apply(Object from) {
    if (from instanceof Customer) {
      return (Customer)from;
    }
    return null; // or throw an exception, or do something else that makes sense.
  }
});

ValueError: Length of values does not match length of index | Pandas DataFrame.unique()

The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:

A data frame of four rows:

df = pd.DataFrame({'A': [1,2,3,4]})

Now trying to assign a list/array of two elements to it:

df['B'] = [3,4]   # or df['B'] = np.array([3,4])

Both errors out:

ValueError: Length of values does not match length of index

Because the data frame has four rows but the list and array has only two elements.

Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:

df['B'] = pd.Series([3,4])

df
#   A     B
#0  1   3.0
#1  2   4.0
#2  3   NaN          # NaN because the value at index 2 and 3 doesn't exist in the Series
#3  4   NaN

For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:

df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))

#   A     B
#0  1   1.0
#1  2   5.0
#2  7   9.0
#3  8   NaN

"if not exist" command in batch file

if not exist "%USERPROFILE%\.qgis-custom\" (
    mkdir "%USERPROFILE%\.qgis-custom" 2>nul
    if not errorlevel 1 (
        xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
    )
)

You have it almost done. The logic is correct, just some little changes.

This code checks for the existence of the folder (see the ending backslash, just to differentiate a folder from a file with the same name).

If it does not exist then it is created and creation status is checked. If a file with the same name exists or you have no rights to create the folder, it will fail.

If everyting is ok, files are copied.

All paths are quoted to avoid problems with spaces.

It can be simplified (just less code, it does not mean it is better). Another option is to always try to create the folder. If there are no errors, then copy the files

mkdir "%USERPROFILE%\.qgis-custom" 2>nul 
if not errorlevel 1 (
    xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
)

In both code samples, files are not copied if the folder is not being created during the script execution.

EDITED - As dbenham comments, the same code can be written as a single line

md "%USERPROFILE%\.qgis-custom" 2>nul && xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e

The code after the && will only be executed if the previous command does not set errorlevel. If mkdir fails, xcopy is not executed.

printing all contents of array in C#

Another approach with the Array.ForEach<T> Method (T[], Action<T>) method of the Array class

Array.ForEach(myArray, Console.WriteLine);

That takes only one iteration compared to array.ToList().ForEach(Console.WriteLine) which takes two iterations and creates internally a second array for the List (double iteration runtime and double memory consumtion)

What's the proper way to install pip, virtualenv, and distribute for Python?

  • You can do this without installing anything into python itself.

  • You don't need sudo or any privileges.

  • You don't need to find the latest version of a virtualenv tar file

  • You don't need to edit version info in a bash script to keep things up-to-date.

  • You don't need curl/wget or tar installed, nor pip or easy_install

  • this works for 2.7 as well as for 3.X

Save the following to /tmp/initvenv.py:

from future import print_function

import os, sys, shutil, tempfile, subprocess, tarfile, hashlib

try:
    from urllib2 import urlopen
except ImportError:
    from urllib.request import urlopen

tmp_dir = tempfile.mkdtemp(prefix='initvenv_')
try:
    # read the latest version from PyPI
    f = urlopen("https://pypi.python.org/pypi/virtualenv/")
    # retrieve the .tar.gz file
    tar_found = False
    url = None
    sha256 = None
    for line in f.read().splitlines():
        if isinstance(line, bytes):
            line = line.decode('utf-8')
        if tar_found:
            if 'sha256' in line:
                sha256 = line.split('data-clipboard-text')[1].split('"')[1]
                break
            continue
        if not tar_found and 'tar.gz">' not in line:
            continue
        tar_found = True
        for url in line.split('"'):
            if url.startswith('https'):
                break
    else:
        print('tar.gz not found')
        sys.exit(1)
    file_name = url.rsplit('/', 1)[1]
    print(file_name)
    os.chdir(tmp_dir)
    data = urlopen(url).read()
    data_sha256 = hashlib.sha256(data).hexdigest()
    if sha256 != data_sha256:
        print('sha256 not correct')
        print(sha256)
        print(data_sha256)
        sys.exit(1)
    with open(file_name, 'wb') as fp:
        fp.write(data)
    tar = tarfile.open(file_name)
    tar.extractall()
    tar.close()
    os.chdir(file_name.replace('.tar.gz', ''))
    print(subprocess.check_output([sys.executable, 'virtualenv.py'] +
                                  [sys.argv[1]]).decode('utf-8'), end='')
    if len(sys.argv) > 2:
        print(subprocess.check_output([
            os.path.join(sys.argv[1], 'bin', 'pip'), 'install', 'virtualenv'] +

            sys.argv[2:]).decode('utf-8'), end='')
except:
    raise
finally:
    shutil.rmtree(tmp_dir)  # always clean up

and use it as

python_binary_to_use_in_venv /tmp/initvenv.py your_venv_name [optional packages]

e.g. (if you really need the distribute compatibility layer for setuptools)

python /tmp/initvenv.py venv distribute

Please note that, with older python versions, this might give you InsecurePlatformWarnings¹.

Once you have your virtualenv (name e.g. venv) you can setup another virtualenv by using the virtualenv just installed:

venv/bin/virtualenv venv2

virtualenvwrapper

I recommend taking a look at virtualenvwrapper as well, after a one time setup:

% /opt/python/2.7.10/bin/python /tmp/initvenv.py venv virtualenvwrapper

and activation (can be done from your login script):

% source venv/bin/virtualenvwrapper.sh

you can do things like:

% mktmpenv 
New python executable in tmp-17bdc3054a46b2b/bin/python
Installing setuptools, pip, wheel...done.
This is a temporary environment. It will be deleted when you run 'deactivate'.
(tmp-17bdc3054a46b2b)% 

¹ I have not found a way to suppress the warning. It could be solved in pip and/or request, but the developers point to each other as the cause. I got the, often non-realistic, recommendation to upgrade the python version I was using to the latest version. I am sure this would break e.g my Linux Mint 17 install. Fortunately pip caches packages, so the Warning is made only once per package install.

Difference between parameter and argument

Generally, the parameters are what are used inside the function and the arguments are the values passed when the function is called. (Unless you take the opposite view — Wikipedia mentions alternative conventions when discussing parameters and arguments).

double sqrt(double x)
{
    ...
    return x;
}

void other(void)
{
     double two = sqrt(2.0);
}

Under my thesis, x is the parameter to sqrt() and 2.0 is the argument.

The terms are often used at least somewhat interchangeably.

How to compare two dates in Objective-C

If you make both dates NSDates you can use NSDate's compare: method:

NSComparisonResult result = [Date2 compare:Date1];

if(result==NSOrderedAscending)
    NSLog(@"Date1 is in the future");
else if(result==NSOrderedDescending)
    NSLog(@"Date1 is in the past");
else
    NSLog(@"Both dates are the same");

You can take a look at the docs here.

How can I print out all possible letter combinations a given phone number can represent?

During a job interview I received this question regarding creating an array of and printing out all possible letter combinations of a phone number. During the interview I received a whisper from my interviewer about recursion and how it can't be done using loops. Very unnatural for me to receive input from another programmer, I trusted his advice instead of my own tuition and proceeded to write up a sloppy recursion mess. It didn't go so well. Before receiving input, as I had never received this problem before, my brain was calculating up the underlying replicable mathematical formula. Whispers under my breath, "can't just multiply by three, some of them are four" as my mind started racing against a short clock thinking about one answer while beginning to write another. It was not until the end of the week I received my call to let me know the sad news. It was later that night I decided to see if it really is a recursion problem. Turns out for me it isn't.

My solution below is coded in PHP, is non-recursive, works with any length of input and I've even included some comments to help describe what my variables mean. Its my official and unchanging final answer to this question. I hope this helps somebody else in the future, please feel free to translate this into other languages.

Me method involves calculating the total number of combinations and creating a buffer large enough to hold every byte. The length of my buffer is the same length you would expect to receive from a working recursive algorithm. I make an array that contains the groups of letters that represent each number. My method primarily works because your combo total will always be divisible by the number of letters in the current group. If you can imagine in your head a vertical list of the output of this algorithm, or see the list vertically as opposed to a horizontally written list of the combinations, my algorithm will begin to make sense. This algorithm allows us to loop through each byte vertically from top to bottom starting from the left instead of horizontally left to right, and populate each byte individually without requiring recursion. I use the buffer as though its a byte array to save time and energy.


NON-RECURSIVE, ITERATIVE PHP

<?php

// Display all possible combinations of letters for each number.

$input = '23456789';

// ====================

if(!isset($input[0]))
    die('Nothing to see here!');

$phone_letters = array(
    2 => array('a', 'b', 'c'),
    3 => array('d', 'e', 'f'),
    4 => array('g', 'h', 'i'),
    5 => array('j', 'k', 'l'),
    6 => array('m', 'n', 'o'),
    7 => array('p', 'q', 'r', 's'),
    8 => array('t', 'u', 'v'),
    9 => array('w', 'x', 'y', 'z')
);

$groups = array();
$combos_total = 1;
$l = strlen($input);
for($i = 0; $i < $l; ++$i) {
    $groups[] = $phone_letters[$input[$i]];
    $combos_total *= count($phone_letters[$input[$i]]);
}
$count = $combos_total / count($groups[0]);
$combos = array_fill(0, $combos_total, str_repeat(chr(0), strlen($input)));

for(
    $group = 0,                     // Index for the current group of letters.
    $groups_count = count($groups), // Total number of letter groups.
    $letters = count($groups[0]),   // Total number of letters in the current group.
    $width = $combos_total,         // Number of bytes to repeat the current letter.
    $repeat = 1;                    // Total number of times the group will repeat.
    ;
) {
    for($byte = 0, $width /= $letters, $r = 0; $r < $repeat; ++$r)
        for($l = 0; $l < $letters; ++$l)
            for($w = 0; $w < $width; ++$w)
                $combos[$byte++][$group] = $groups[$group][$l];

    if(++$group < $groups_count) {
        $repeat *= $letters;
        $letters = count($groups[$group]);
    }
    else
        break;
}

// ==================== 


if(is_array($combos)) {
    print_r($combos);
    echo 'Total combos:', count($combos), "\n";
}
else
    echo 'No combos.', "\n";
echo 'Expected combos: ', $combos_total, "\n";

NON-RECURSIVE, NON-ITERATIVE, NO-BUFFER, THREAD FRIENDLY, MATH ONLY + NON-RECURSIVE, ITERATIVE PHP OBJECT USING MULTI-BASE BIG ENDIAN

While I was working on the new house the other day, I had a realisation that I could use the mathematics from my first function coupled with my knowledge of base to treat all possible letter combinations of my input as a multi-dimensional number.

My object provides the functions necessary to store a prefered combination into a database, convert letters and numbers if it were required, pick out a combination from anywhere in the combination space using a prefered combination or byte and it all plays very well with multi-threading.

That being said, using my object I can provide a second answer that uses base, no buffer, no iterations and most importantly no recursion.

<?php
class phone {
    public static $letters = array(
        2 => array('a', 'b', 'c'),
        3 => array('d', 'e', 'f'),
        4 => array('g', 'h', 'i'),
        5 => array('j', 'k', 'l'),
        6 => array('m', 'n', 'o'),
        7 => array('p', 'q', 'r', 's'),
        8 => array('t', 'u', 'v'),
        9 => array('w', 'x', 'y', 'z')
    );

    // Convert a letter into its respective number.
    public static function letter_number($letter) {
        if(!isset($letter[0]) || isset($letter[1]))
            return false;

        for($i = 2; $i < 10; ++$i)
            if(in_array($letter, phone::$letters[$i], true))
                return $i;

        return false;
    }

    // Convert letters into their respective numbers.
    public static function letters_numbers($letters) {
        if(!isset($letters[0]))
            return false;

        $length = strlen($letters);
        $numbers = str_repeat(chr(0), $length);
        for($i = 0; $i < $length; ++$i) {
            for($j = 2; $j < 10; ++$j) {
                if(in_array($letters[$i], phone::$letters[$j], true)) {
                    $numbers[$i] = $j;
                    break;
                }
            }
        }
        return $numbers;
    }

    // Calculate the maximum number of combinations that could occur within a particular input size.
    public static function combination_size($groups) {
        return $groups <= 0 ? false : pow(4, $groups);
    }

    // Calculate the minimum bytes reqired to store a group using the current input.
    public static function combination_bytes($groups) {
        if($groups <= 0)
            return false;

        $size = $groups * 4;
        $bytes = 0;
        while($groups !== 0) {
            $groups >> 8;
            ++$bytes;
        }
        return $bytes;
    }

    public $input = '';
    public $input_len = 0;
    public $combinations_total = 0;
    public $combinations_length = 0;

    private $iterations = array();
    private $branches = array();

    function __construct($number) {
        if(!isset($number[0]))
            return false;

        $this->input = $number;
        $input_len = strlen($number);

        $combinations_total = 1;
        for($i = 0; $i < $input_len; ++$i) {
            $combinations_total *= count(phone::$letters[$number[$i]]);
        }

        $this->input_len = $input_len;
        $this->combinations_total = $combinations_total;
        $this->combinations_length = $combinations_total * $input_len;

        for($i = 0; $i < $input_len; ++$i) {
            $this->branches[] = $this->combination_branches($i);
            $this->iterations[] = $this->combination_iteration($i);
        }
    }

    // Calculate a particular combination in the combination space and return the details of that combination.
    public function combination($combination) {
        $position = $combination * $this->input_len;
        if($position < 0 || $position >= $this->combinations_length)
                return false;

        $group = $position % $this->input_len;
        $first = $position - $group;
        $last = $first + $this->input_len - 1;
        $combination = floor(($last + 1) / $this->input_len) - 1;

        $bytes = str_repeat(chr(0), $this->input_len);
        for($i = 0; $i < $this->input_len; ++$i)
            $bytes[$i] = phone::$letters[$this->input[$i]][($combination / $this->branches[$i]) % count(phone::$letters[$this->input[$i]])];

        return array(
            'combination' => $combination,
            'branches' => $this->branches[$group],
            'iterations' => $this->iterations[$group],
            'first' => $first,
            'last' => $last,
            'bytes' => $bytes
        );
    }

    // Calculate a particular byte in the combination space and return the details of that byte.
    public function combination_position($position) {
        if($position < 0 || $position >= $this->combinations_length)
                return false;

        $group = $position % $this->input_len;
        $group_count = count(phone::$letters[$this->input[$group]]);
        $first = $position - $group;
        $last = $first + $this->input_len - 1;
        $combination = floor(($last + 1) / $this->input_len) - 1;
        $index = ($combination / $this->branches[$group]) % $group_count;

        $bytes = str_repeat(chr(0), $this->input_len);
        for($i = 0; $i < $this->input_len; ++$i)
            $bytes[$i] = phone::$letters[$this->input[$i]][($combination / $this->branches[$i]) % count(phone::$letters[$this->input[$i]])];

        return array(
            'position' => $position,
            'combination' => $combination - 1,
            'group' => $group,
            'group_count' => $group_count,
            'group_index' => $index,
            'number' => $this->input[$group],
            'branches' => $this->branches[$group],
            'iterations' => $this->iterations[$group],
            'first' => $first,
            'last' => $last,
            'byte' => phone::$letters[$this->input[$group]][$index],
            'bytes' => $bytes
        );
    }

    // Convert letters into a combination number using Multi-Base Big Endian.
    public function combination_letters($letters) {
        if(!isset($letters[$this->input_len - 1]) || isset($letters[$this->input_len]))
            return false;

        $combination = 0;
        for($byte = 0; $byte < $this->input_len; ++$byte) {
            $base = count(phone::$letters[$this->input[$byte]]);
            $found = false;
            for($value = 0; $value < $base; ++$value) {
                if($letters[$byte] === phone::$letters[$this->input[$byte]][$value]) {
                    $combination += $value * $this->branches[$byte];
                    $found = true;
                    break;
                }
            }
            if($found === false)
                return false;
        }
        return $combination;
    }

    // Calculate the number of branches after a particular group.
    public function combination_branches($group) {
        if($group >= 0 && ++$group < $this->input_len) {
            $branches = 1;
            for($i = $group; $i < $this->input_len; ++$i)
                $branches *= count(phone::$letters[$this->input[$i]]);
            return $branches === 1 ? 1 : $branches;
        }
        elseif($group === $this->input_len)
            return 1;
        else
        return false;   
    }

    // Calculate the number of iterations before a particular group.
    public function combination_iteration($group) {
        if($group > 0 && $group < $this->input_len) {
            $iterations = 1;
            for($i = $group - 1; $i >= 0; --$i)
                $iterations *= count(phone::$letters[$this->input[$i]]);
            return $iterations;
        }
        elseif($group === 0)
            return 1;
        else
            return false;
    }

    // Iterations, Outputs array of all combinations using a buffer.
    public function combinations() {
        $count = $this->combinations_total / count(phone::$letters[$this->input[0]]);
        $combinations = array_fill(0, $this->combinations_total, str_repeat(chr(0), $this->input_len));
        for(
            $group = 0,                                         // Index for the current group of letters.
            $groups_count = $this->input_len,                   // Total number of letter groups.
            $letters = count(phone::$letters[$this->input[0]]), // Total number of letters in the current group.
            $width = $this->combinations_total,                         // Number of bytes to repeat the current letter.
            $repeat = 1;                                        // Total number of times the group will repeat.
            ;
        ) {
            for($byte = 0, $width /= $letters, $r = 0; $r < $repeat; ++$r)
                for($l = 0; $l < $letters; ++$l)
                    for($w = 0; $w < $width; ++$w)
                        $combinations[$byte++][$group] = phone::$letters[$this->input[$group]][$l];

            if(++$group < $groups_count) {
                $repeat *= $letters;
                $letters = count(phone::$letters[$this->input[$group]]);
            }
            else
                break;
        }
        return $combinations;
    }
}

// ====================

$phone = new phone('23456789');
print_r($phone);
//print_r($phone->combinations());
for($i = 0; $i < $phone->combinations_total; ++$i) {
    echo $i, ': ', $phone->combination($i)['bytes'], "\n";
}

iPhone hide Navigation Bar only on first page

If what you want is to hide the navigation bar completely in the controller, a much cleaner solution is to, in the root controller, have something like:

@implementation MainViewController
- (void)viewDidLoad {
    self.navigationController.navigationBarHidden=YES;
    //...extra code on view load  
}

When you push a child view in the controller, the Navigation Bar will remain hidden; if you want to display it just in the child, you'll add the code for displaying it(self.navigationController.navigationBarHidden=NO;) in the viewWillAppear callback, and similarly the code for hiding it on viewWillDisappear

Java: Retrieving an element from a HashSet

You can HashMap<MyHashObject,MyHashObject> instead of HashSet<MyHashObject>.

Calling ContainsKey() on your "reconstructed" MyHashObject will first hashCode()-check the collection, and if a duplicate hashcode is hit, finally equals()-check your "reconstructed" against the original, at which you can retrieve the original using get()

This is O(1) but the downside is you will likely have to override both equals() and hashCode() methods.

Cannot call getSupportFragmentManager() from activity

Simply Use

 FragmentManager fm = getActivity().getSupportFragmentManager();

Remember always when accessing fragment inflating in MainLayout use Casting or getActivity().

Recommended SQL database design for tags or tagging

Three tables (one for storing all items, one for all tags, and one for the relation between the two), properly indexed, with foreign keys set running on a proper database, should work well and scale properly.

Table: Item
Columns: ItemID, Title, Content

Table: Tag
Columns: TagID, Title

Table: ItemTag
Columns: ItemID, TagID

Disable submit button ONLY after submit

  $(function(){

    $("input[type='submit']").click(function () {
        $(this).attr("disabled", true);   
     });
  });

thant's it.

Manage toolbar's navigation and back button from fragment in android

Add a toolbar to your xml

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fragment title"/>

</android.support.v7.widget.Toolbar>

Then inside your onCreateView method in the Fragment:

Toolbar toolbar = view.findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.ic_back_button);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
         getActivity().onBackPressed();
    }
});

How to insert a timestamp in Oracle?

Kind of depends on where the value you want to insert is coming from. If you want to insert the current time you can use CURRENT_TIMESTAMP as shown in other answers (or SYSTIMESTAMP).

If you have a time as a string and want to convert it to a timestamp, use an expression like

to_timestamp(:timestamp_as_string,'MM/DD/YYYY HH24:MI:SS.FF3')

The time format components are, I hope, self-explanatory, except that FF3 means 3 digits of sub-second precision. You can go as high as 6 digits of precision.

If you are inserting from an application, the best answer may depend on how the date/time value is stored in your language. For instance you can map certain Java objects directly to a TIMESTAMP column, but you need to understand the JDBC type mappings.

How to add class active on specific li on user click with jQuery

        // Remove active for all items.
        $('.sidebar-menu li').removeClass('active');
        // highlight submenu item
        $('li a[href="' + this.location.pathname + '"]').parent().addClass('active');
        // Highlight parent menu item.
        $('ul a[href="' + this.location.pathname + '"]').parents('li').addClass('active')

How do I show the number keyboard on an EditText in android?

If you are using your EditText in Dialog or creating dynamically and You can't set it from xml then this example will help you in setting that type of key board while you are using dynamic Edit Text etc

myEditTxt.setInputType(InputType.TYPE_CLASS_NUMBER);

where myEditTxt is the dynamic EDIT TEXT object(name)

Unable to import a module that is definitely installed

If you learn how to use virtualenv (which is pretty dead-simple), you will have less of these issues. You'll just source the virtualenv and then you will be using local (to the project) packages.

It solves a lot of headache for me with paths, versions, etc.

Check if a value is within a range of numbers

Here is an option with only a single comparison.

// return true if in range, otherwise false
function inRange(x, min, max) {
    return ((x-min)*(x-max) <= 0);
}

console.log(inRange(5, 1, 10));     // true
console.log(inRange(-5, 1, 10));    // false
console.log(inRange(20, 1, 10));    // false

IE throws JavaScript Error: The value of the property 'googleMapsQuery' is null or undefined, not a Function object (works in other browsers)

Just a few minutes ago i was facing the same problem. I got the problem that is after just placing your jQuery start the other jQuery scripting. After all it will work fine.

intl extension: installing php_intl.dll

When I faced this issue it was sorted out by using below mentioned steps:

Edit php.ini:

Make

;extension=php_intl.dll to

extension=php_intl.dll Simply copy all icu* * * *.dll files(any icu file with dll extension) from

C:\xampp\php to C:\xampp\apache\bin

Also If you have the msvcp110.dll missing file error. You have to download the right .dll or just go here http://www.microsoft.com/es-es/download/confirmation.aspx?id=30679 and install the vcredist_x64.exe and vcredist_x86.exe.

Now the intl extension should work :-)

How to insert a new line in strings in Android

Try using System.getProperty("line.separator") to get a new line.

ValueError when checking if variable is None or numpy.array

To stick to == without consideration of the other type, the following is also possible.
type(a) == type(None)

Is there a way to pass javascript variables in url?

Try this:

window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=\''+elemA+'\'&lon=\''+elemB+'\'&setLatLon=Set";

Running a command in a new Mac OS X Terminal window

Partial solution:

Put the things you want done in a shell-script, like so

#!/bin/bash
ls
echo "yey!"

And don't forget to 'chmod +x file' to make it executable. Then you can

open -a Terminal.app scriptfile

and it will run in a new window. Add 'bash' at the end of the script to keep the new session from exiting. (Although you might have to figure out how to load the users rc-files and stuff..)

PHP: Return all dates between two dates in an array

many ways of getting this done, but finally it all depends on PHP version you are using. Here is summary of all solutions:

get PHP version:

echo phpinfo();

PHP 5.3+

$period = new DatePeriod(
     new DateTime('2010-10-01'),
     new DateInterval('P1D'),
     new DateTime('2010-10-05')
);

PHP 4+

/**
 * creating between two date
 * @param string since
 * @param string until
 * @param string step
 * @param string date format
 * @return array
 * @author Ali OYGUR <[email protected]>
 */
function dateRange($first, $last, $step = '+1 day', $format = 'd/m/Y' ) { 

    $dates = array();
    $current = strtotime($first);
    $last = strtotime($last);

    while( $current <= $last ) { 

        $dates[] = date($format, $current);
        $current = strtotime($step, $current);
    }

    return $dates;
}

PHP < 4

you should upgrade :)

How to transform numpy.matrix or array to scipy sparse matrix

You can pass a numpy array or matrix as an argument when initializing a sparse matrix. For a CSR matrix, for example, you can do the following.

>>> import numpy as np
>>> from scipy import sparse
>>> A = np.array([[1,2,0],[0,0,3],[1,0,4]])
>>> B = np.matrix([[1,2,0],[0,0,3],[1,0,4]])

>>> A
array([[1, 2, 0],
       [0, 0, 3],
       [1, 0, 4]])

>>> sA = sparse.csr_matrix(A)   # Here's the initialization of the sparse matrix.
>>> sB = sparse.csr_matrix(B)

>>> sA
<3x3 sparse matrix of type '<type 'numpy.int32'>'
        with 5 stored elements in Compressed Sparse Row format>

>>> print sA
  (0, 0)        1
  (0, 1)        2
  (1, 2)        3
  (2, 0)        1
  (2, 2)        4

How do I find out my root MySQL password?

Under MYSQL 5.7, If you are using mysql for development purpose, just :

1.kill mysql :

$ sudo service mysql stop

2.start mysql under --skip-grant-tables mode:

$ sudo mysqld_safe --skip-grant-tables 

and, further, you could try to change the user table under "skip-grant-table" mode, however I failed.

so, this is just a workaround.

Maven Install on Mac OS X

A simple approach to install Maven.

  1. Open Terminal

Finder -> Go -> Utilities -> Terminal

  1. Install Homebrew using the below command

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

  1. After that install maven

brew install maven

Change the mouse pointer using JavaScript

document.body.style.cursor = 'cursorurl';

TSQL select into Temp table from dynamic sql

declare @sql varchar(100);

declare @tablename as varchar(100);

select @tablename = 'your_table_name';

create table #tmp 
    (col1 int, col2 int, col3 int);

set @sql = 'select aa, bb, cc from ' + @tablename;

insert into #tmp(col1, col2, col3) exec( @sql );

select * from #tmp;

This page didn't load Google Maps correctly. See the JavaScript console for technical details

You could also get the error if your Billing is not set up correctly.

Google hands out credit worth $300 or 12 months of free usage whichever runs out faster. After that you would need to enable billing.

enter image description here

Makefile ifeq logical or

ifeq ($(GCC_MINOR), 4)
    CFLAGS += -fno-strict-overflow
endif
ifeq ($(GCC_MINOR), 5)
    CFLAGS += -fno-strict-overflow
endif

Another you can consider using in this case is:

GCC42_OR_LATER = $(shell $(CXX) -v 2>&1 | $(EGREP) -c "^gcc version (4.[2-9]|[5-9])")

# -Wstrict-overflow: http://www.airs.com/blog/archives/120
ifeq ($(GCC42_OR_LATER),1)
  CFLAGS += -Wstrict-overflow
endif

I actually use the same in my code because I don't want to maintain a separate config or Configure.

But you have to use a portable, non-anemic make, like GNU make (gmake), and not Posix's make.

And it does not address the issue of logical AND and OR.

Declaring functions in JSP?

You need to enclose that in <%! %> as follows:

<%!

public String getQuarter(int i){
String quarter;
switch(i){
        case 1: quarter = "Winter";
        break;

        case 2: quarter = "Spring";
        break;

        case 3: quarter = "Summer I";
        break;

        case 4: quarter = "Summer II";
        break;

        case 5: quarter = "Fall";
        break;

        default: quarter = "ERROR";
}

return quarter;
}

%>

You can then invoke the function within scriptlets or expressions:

<%
     out.print(getQuarter(4));
%>

or

<%= getQuarter(17) %>

Python: Total sum of a list of numbers with the for loop

l = [1,2,3,4,5]
sum = 0
for x in l:
    sum = sum + x

And you can change l for any list you want.

Easiest way to loop through a filtered list with VBA?

The SpecialCells Does not actually work as it needs to be continuous. I have solved this by adding a sort funtion in order to sort the data based on the coloumns i need.

Sorry for no comments on the code as i was not planning to share it:

Sub testtt()
    arr = FilterAndGetData(Worksheets("Data").range("A:K"), Array(1, 9), Array("george", "WeeklyCash"), Array(1, 2, 3, 10, 11), 1)
    Debug.Print sms(arr)
End Sub
Function FilterAndGetData(ByVal rng As Variant, ByVal fields As Variant, ByVal criterias As Variant, ByVal colstoreturn As Variant, ByVal headers As Boolean) As Variant
Dim SUset, EAset, CMset
If Application.ScreenUpdating Then Application.ScreenUpdating = False: SUset = False Else SUset = True
If Application.EnableEvents Then Application.EnableEvents = False: EAset = False Else EAset = True
If Application.Calculation = xlCalculationAutomatic Then Application.Calculation = xlCalculationManual: CMset = False Else CMset = True
For Each col In rng.Columns: col.Hidden = False: Next col

Dim oldsheet, scol, ecol, srow, hyesno As String
Dim i, counter As Integer

oldsheet = ActiveSheet.Name


Worksheets(rng.Worksheet.Name).Activate

Worksheets(rng.Worksheet.Name).AutoFilterMode = False

scol = Chr(rng.Column + 64)
ecol = Chr(rng.Columns.Count + rng.Column + 64 - 1)
srow = rng.row

If UBound(fields) - LBound(fields) <> UBound(criterias) - LBound(criterias) Then FilterAndGetData = "Fields&Crit. counts dont match": GoTo done

dd = sortrange(rng, colstoreturn, headers)

For i = LBound(fields) To UBound(fields)
    rng.AutoFilter Field:=CStr(fields(i)), Criteria1:=CStr(criterias(i))
Next i

Dim rngg As Variant

rngg = rng.SpecialCells(xlCellTypeVisible)
Debug.Print ActiveSheet.AutoFilter.range.address
FilterAndGetData = ActiveSheet.AutoFilter.range.SpecialCells(xlCellTypeVisible).Value

For Each row In rng.Rows
    If row.EntireRow.Hidden Then Debug.Print yes
Next row


done:
    'Worksheets("Data").AutoFilterMode = False
    Worksheets(oldsheet).Activate
    If SUset Then Application.ScreenUpdating = True
    If EAset Then Application.EnableEvents = True
    If CMset Then Application.Calculation = xlCalculationAutomatic
End Function
Function sortrange(ByVal rng As Variant, ByVal colnumbers As Variant, ByVal headers As Boolean)

    Dim SUset, EAset, CMset
    If Application.ScreenUpdating Then Application.ScreenUpdating = False: SUset = False Else SUset = True
    If Application.EnableEvents Then Application.EnableEvents = False: EAset = False Else EAset = True
    If Application.Calculation = xlCalculationAutomatic Then Application.Calculation = xlCalculationManual: CMset = False Else CMset = True
    For Each col In rng.Columns: col.Hidden = False: Next col

    Dim oldsheet, scol, srow, sortcol, hyesno As String
    Dim i, counter As Integer
    oldsheet = ActiveSheet.Name
    Worksheets(rng.Worksheet.Name).Activate
    Worksheets(rng.Worksheet.Name).AutoFilterMode = False
    scol = rng.Column
    srow = rng.row

    If headers Then hyesno = xlYes Else hyesno = xlNo

    For i = LBound(colnumbers) To UBound(colnumbers)
        rng.Sort key1:=range(Chr(scol + colnumbers(i) + 63) + CStr(srow)), order1:=xlAscending, Header:=hyesno
    Next i
    sortrange = "123"
done:
    Worksheets(oldsheet).Activate
    If SUset Then Application.ScreenUpdating = True
    If EAset Then Application.EnableEvents = True
    If CMset Then Application.Calculation = xlCalculationAutomatic
End Function

How to make an empty div take space

Why not just add "min-width" to your css-class?

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

Despite of most people recommend here, that is how Google Analytics's dynamic protocol snipped looked like for ages (before they moved from ga.js to analytics.js recently):

ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';

More info: https://developers.google.com/analytics/devguides/collection/gajs/

In new version they used '//' so browser can automatically add protocol:

'//www.google-analytics.com/analytics.js'

So if Google prefers document.location to window.location when they need protocol in JS, I guess they have some reasons for that.

OVERALL: I personally believe that document.location and window.location are the same, but if giant with biggest stats about usage of browsers like Google using document.location, I recommend to follow them.

ImportError: No module named 'Tkinter'

As you are using Python 3, the module has been renamed to tkinter, as stated in the documentation:

Note Tkinter has been renamed to tkinter in Python 3. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.

Randomize numbers with jQuery?

Javascript has a random() available. Take a look at Math.random().

How to know if .keyup() is a character key (jQuery)

I never liked the key code validation. My approach was to see if the input have text (any character), confirming that the user is entering text and no other characters

_x000D_
_x000D_
$('#input').on('keyup', function() {_x000D_
    var words = $(this).val();_x000D_
    // if input is empty, remove the word count data and return_x000D_
    if(!words.length) {_x000D_
        $(this).removeData('wcount');_x000D_
        return true;_x000D_
    }_x000D_
    // if word count data equals the count of the input, return_x000D_
    if(typeof $(this).data('wcount') !== "undefined" && ($(this).data('wcount') == words.length)){_x000D_
        return true;_x000D_
    }_x000D_
    // update or initialize the word count data_x000D_
    $(this).data('wcount', words.length);_x000D_
    console.log('user tiped ' + words);_x000D_
    // do you stuff..._x000D_
});
_x000D_
<html lang="en">_x000D_
  <head>_x000D_
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
  </head>_x000D_
  <body>_x000D_
  <input type="text" name="input" id="input">_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Styling HTML email for Gmail

I had the same problem while designing a template in Mailjet. Solution of the problem was minified CSS code inside <style> tags.

WebSockets and Apache proxy : how to configure mod_proxy_wstunnel?

With help from these answers, I finally got reverse proxy for Node-RED running on a Raspberry Pi with Ubuntu Mate and Apache2 working, using this Apache2 site config:

<VirtualHost *:80>
    ServerName nodered.domain.com
    RewriteEngine On
    RewriteCond %{HTTP:Upgrade} =websocket [NC]
    RewriteRule /(.*)           ws://localhost:1880/$1 [P,L]
    RewriteCond %{HTTP:Upgrade} !=websocket [NC]
    RewriteRule /(.*)           http://localhost:1880/$1 [P,L]
</VirtualHost>

I also had to enable modules like this:

sudo a2enmod proxy
sudo a2enmod proxy_http
sudo a2enmod proxy_wstunnel

How do I center an SVG in a div?

You can also do this:

<center>
<div style="width: 40px; height: 40px;">
    <svg class="sqs-svg-icon--social" viewBox="0 0 64 64">
        <use class="sqs-use--icon" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#twitter-icon">
            <svg id="twitter-icon" viewBox="0 0 64 64" width="100%" height="100%">
                <path
                    d="M48,22.1c-1.2,0.5-2.4,0.9-3.8,1c1.4-0.8,2.4-2.1,2.9-3.6c-1.3,0.8-2.7,1.3-4.2,1.6 C41.7,19.8,40,19,38.2,19c-3.6,0-6.6,2.9-6.6,6.6c0,0.5,0.1,1,0.2,1.5c-5.5-0.3-10.3-2.9-13.5-6.9c-0.6,1-0.9,2.1-0.9,3.3 c0,2.3,1.2,4.3,2.9,5.5c-1.1,0-2.1-0.3-3-0.8c0,0,0,0.1,0,0.1c0,3.2,2.3,5.8,5.3,6.4c-0.6,0.1-1.1,0.2-1.7,0.2c-0.4,0-0.8,0-1.2-0.1 c0.8,2.6,3.3,4.5,6.1,4.6c-2.2,1.8-5.1,2.8-8.2,2.8c-0.5,0-1.1,0-1.6-0.1c2.9,1.9,6.4,2.9,10.1,2.9c12.1,0,18.7-10,18.7-18.7 c0-0.3,0-0.6,0-0.8C46,24.5,47.1,23.4,48,22.1z"
                    />
            </svg>
        </use>
    </svg>
</div>
</center>

NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext

I faced the same error, but only with files cloned from git that were assigned to a proprietary plugin. I realized that even after cloning the files from git, I needed to create a new project or import a project in eclipse and this resolved the error.

Git diff --name-only and copy that list

#!/bin/bash
# Target directory
TARGET=/target/directory/here

for i in $(git diff --name-only)
    do
        # First create the target directory, if it doesn't exist.
        mkdir -p "$TARGET/$(dirname $i)"
        # Then copy over the file.
        cp -rf "$i" "$TARGET/$i"
    done

https://stackoverflow.com/users/79061/sebastian-paaske-t%c3%b8rholm

Run reg command in cmd (bat file)?

You will probably get an UAC prompt when importing the reg file. If you accept that, you have more rights.

Since you are writing to the 'policies' key, you need to have elevated rights. This part of the registry protected, because it contains settings that are administered by your system administrator.

Alternatively, you may try to run regedit.exe from the command prompt.

regedit.exe /S yourfile.reg

.. should silently import the reg file. See RegEdit Command Line Options Syntax for more command line options.

Xcode Error: "The app ID cannot be registered to your development team."

Changing Bundle Identifier worked for me.

  1. Go to Signing & Capabilities tab
  2. Change my Bundle Identifier. "MyApp" > "MyCompanyName.MyApp"
  3. Enter and wait a seconds for generating Signing Certificate

If it still doesn't work, try again with these steps before:

  1. Remove your Provisioning Profiles: cd /Users/my_username/Library/MobileDevice/Provisioning Profiles && rm * (in my case)
  2. Clearn your project
  3. ...

How do you calculate log base 2 in Java for integers?

If you are thinking about using floating-point to help with integer arithmetics, you have to be careful.

I usually try to avoid FP calculations whenever possible.

Floating-point operations are not exact. You can never know for sure what will (int)(Math.log(65536)/Math.log(2)) evaluate to. For example, Math.ceil(Math.log(1<<29) / Math.log(2)) is 30 on my PC where mathematically it should be exactly 29. I didn't find a value for x where (int)(Math.log(x)/Math.log(2)) fails (just because there are only 32 "dangerous" values), but it does not mean that it will work the same way on any PC.

The usual trick here is using "epsilon" when rounding. Like (int)(Math.log(x)/Math.log(2)+1e-10) should never fail. The choice of this "epsilon" is not a trivial task.

More demonstration, using a more general task - trying to implement int log(int x, int base):

The testing code:

static int pow(int base, int power) {
    int result = 1;
    for (int i = 0; i < power; i++)
        result *= base;
    return result;
}

private static void test(int base, int pow) {
    int x = pow(base, pow);
    if (pow != log(x, base))
        System.out.println(String.format("error at %d^%d", base, pow));
    if(pow!=0 && (pow-1) != log(x-1, base))
        System.out.println(String.format("error at %d^%d-1", base, pow));
}

public static void main(String[] args) {
    for (int base = 2; base < 500; base++) {
        int maxPow = (int) (Math.log(Integer.MAX_VALUE) / Math.log(base));
        for (int pow = 0; pow <= maxPow; pow++) {
            test(base, pow);
        }
    }
}

If we use the most straight-forward implementation of logarithm,

static int log(int x, int base)
{
    return (int) (Math.log(x) / Math.log(base));
}

this prints:

error at 3^5
error at 3^10
error at 3^13
error at 3^15
error at 3^17
error at 9^5
error at 10^3
error at 10^6
error at 10^9
error at 11^7
error at 12^7
...

To completely get rid of errors I had to add epsilon which is between 1e-11 and 1e-14. Could you have told this before testing? I definitely could not.

Amazon S3 upload file and get URL

To make the file public before uploading you can use the #withCannedAcl method of PutObjectRequest:

myAmazonS3Client.putObject(new PutObjectRequest('some-grails-bucket',  'somePath/someKey.jpg', new    File('/Users/ben/Desktop/photo.jpg')).withCannedAcl(CannedAccessControlList.PublicRead))

How to access SVG elements with Javascript

If you are using an <img> tag for the SVG, then you cannot manipulate its contents (as far as I know).

As the accepted answer shows, using <object> is an option.

I needed this recently and used gulp-inject during my gulp build to inject the contents of an SVG file directly into the HTML document as an <svg> element, which is then very easy to work with using CSS selectors and querySelector/getElementBy*.

Generating combinations in c++

A simple way using std::next_permutation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
            }
        }
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;
}

or a slight variation that outputs the results in an easier to follow order:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
   int n, r;
   std::cin >> n;
   std::cin >> r;

   std::vector<bool> v(n);
   std::fill(v.begin(), v.begin() + r, true);

   do {
       for (int i = 0; i < n; ++i) {
           if (v[i]) {
               std::cout << (i + 1) << " ";
           }
       }
       std::cout << "\n";
   } while (std::prev_permutation(v.begin(), v.end()));
   return 0;
}

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v.


You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
{
    typedef vector<int> combination_t;

    // initialize status
   combinations(int N, int R) :
       completed(N < 1 || R > N),
       generated(0),
       N(N), R(R)
   {
       for (int c = 1; c <= R; ++c)
           curr.push_back(c);
   }

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

   // get current and compute next combination
   combination_t next()
   {
       combination_t ret = curr;

       // find what to increment
       completed = true;
       for (int i = R - 1; i >= 0; --i)
           if (curr[i] < N - R + i + 1)
           {
               int j = curr[i] + 1;
               while (i <= R-1)
                   curr[i++] = j++;
               completed = false;
               ++generated;
               break;
           }

       return ret;
   }

private:

   int N, R;
   combination_t curr;
};

int main(int argc, char **argv)
{
    int N = argc >= 2 ? atoi(argv[1]) : 5;
    int R = argc >= 3 ? atoi(argv[2]) : 2;
    combinations cs(N, R);
    while (!cs.completed)
    {
        combinations::combination_t c = cs.next();
        copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
        cout << endl;
    }
    return cs.generated;
}

test output:

1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,

C# how to create a Guid value?

var guid = new Guid();

Hey, its a 'valid', although not very useful, Guid.

(the guid is all zeros, if you don't know. Sometimes this is needed to indicate no guid, in cases where you don't want to use a nullable Guid)

Get Element value with minidom with Python

Probably something like this if it's the text part you want...

from xml.dom.minidom import parse
dom = parse("C:\\eve.xml")
name = dom.getElementsByTagName('name')

print " ".join(t.nodeValue for t in name[0].childNodes if t.nodeType == t.TEXT_NODE)

The text part of a node is considered a node in itself placed as a child-node of the one you asked for. Thus you will want to go through all its children and find all child nodes that are text nodes. A node can have several text nodes; eg.

<name>
  blabla
  <somestuff>asdf</somestuff>
  znylpx
</name>

You want both 'blabla' and 'znylpx'; hence the " ".join(). You might want to replace the space with a newline or so, or perhaps by nothing.

NLTK and Stopwords Fail #lookuperror

import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
STOPWORDS = set(stopwords.words('english'))

Can Python test the membership of multiple values in a list?

I would say we can even leave those square brackets out.

array = ['b', 'a', 'foo', 'bar']
all([i in array for i in 'a', 'b'])

how to git commit a whole folder?

To stage an entire folder, you'd enter this command:

    $git add .

The period will add all files in the folder.

Separators for Navigation

I believe the best solution for this, is what I use, and that is a natural css border:

border-right:1px solid;

You might need to take care of padding like:

padding-left: 5px;
padding-right: 5px;

Finally, if you don't want the last li to have that seperating border, give it's last-child "none" in "border-right" like this:

li:last-child{
  border-right:none;
}

Good luck :)

How to set iPhone UIView z index?

You can use the zPosition property of the view's layer (it's a CALayer object) to change the z-index of the view.

theView.layer.zPosition = 1;

As Viktor Nordling added, "big values are on top. You can use any values you want, including negative values." The default value is 0.

You need to import the QuartzCore framework to access the layer. Just add this line of code at the top of your implementation file.

#import "QuartzCore/QuartzCore.h"

How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?

This suggestion is based on pixel manipulation in canvas 2d context.

From MDN:

You can directly manipulate pixel data in canvases at the byte level

To manipulate pixels we'll use two functions here - getImageData and putImageData.

getImageData usage:

var myImageData = context.getImageData(left, top, width, height);

The putImageData syntax:

context.putImageData(myImageData, x, y); 

Where context is your canvas 2d context, and x and y are the position on the canvas.

So to get red green blue and alpha values, we'll do the following:

var r = imageData.data[((x*(imageData.width*4)) + (y*4))];
var g = imageData.data[((x*(imageData.width*4)) + (y*4)) + 1];
var b = imageData.data[((x*(imageData.width*4)) + (y*4)) + 2];
var a = imageData.data[((x*(imageData.width*4)) + (y*4)) + 3];

Where x is the horizontal offset, y is the vertical offset.

The code making image half-transparent:

var canvas = document.getElementById('myCanvas');
var c = canvas.getContext('2d');
var img = new Image();
img.onload  = function() {
   c.drawImage(img, 0, 0);
   var ImageData = c.getImageData(0,0,img.width,img.height);
   for(var i=0;i<img.height;i++)
      for(var j=0;j<img.width;j++)
         ImageData.data[((i*(img.width*4)) + (j*4) + 3)] = 127;//opacity = 0.5 [0-255]
   c.putImageData(ImageData,0,0);//put image data back
}
img.src = 'image.jpg';

You can make you own "shaders" - see full MDN article here

Program does not contain a static 'Main' method suitable for an entry point

Check the properties of App.xaml. Is the Build Action still ApplicationDefinition?

Why am I getting the error "connection refused" in Python? (Sockets)

Instead of

host = socket.gethostname() #Get the local machine name
port = 12397 # Reserve a port for your service
s.bind((host,port)) #Bind to the port

you should try

port = 12397 # Reserve a port for your service
s.bind(('', port)) #Bind to the port

so that the listening socket isn't too restricted. Maybe otherwise the listening only occurs on one interface which, in turn, isn't related with the local network.

One example could be that it only listens to 127.0.0.1, which makes connecting from a different host impossible.

Copy a file in a sane, safe and efficient way

Too many!

The "ANSI C" way buffer is redundant, since a FILE is already buffered. (The size of this internal buffer is what BUFSIZ actually defines.)

The "OWN-BUFFER-C++-WAY" will be slow as it goes through fstream, which does a lot of virtual dispatching, and again maintains internal buffers or each stream object. (The "COPY-ALGORITHM-C++-WAY" does not suffer this, as the streambuf_iterator class bypasses the stream layer.)

I prefer the "COPY-ALGORITHM-C++-WAY", but without constructing an fstream, just create bare std::filebuf instances when no actual formatting is needed.

For raw performance, you can't beat POSIX file descriptors. It's ugly but portable and fast on any platform.

The Linux way appears to be incredibly fast — perhaps the OS let the function return before I/O was finished? In any case, that's not portable enough for many applications.

EDIT: Ah, "native Linux" may be improving performance by interleaving reads and writes with asynchronous I/O. Letting commands pile up can help the disk driver decide when is best to seek. You might try Boost Asio or pthreads for comparison. As for "can't beat POSIX file descriptors"… well that's true if you're doing anything with the data, not just blindly copying.

How to create unique keys for React elements?

There are many ways in which you can create unique keys, the simplest method is to use the index when iterating arrays.

Example

    var lists = this.state.lists.map(function(list, index) {
        return(
            <div key={index}>
                <div key={list.name} id={list.name}>
                    <h2 key={"header"+list.name}>{list.name}</h2>
                    <ListForm update={lst.updateSaved} name={list.name}/>
                </div>
            </div>
        )
    });

Wherever you're lopping over data, here this.state.lists.map, you can pass second parameter function(list, index) to the callback as well and that will be its index value and it will be unique for all the items in the array.

And then you can use it like

<div key={index}>

You can do the same here as well

    var savedLists = this.state.savedLists.map(function(list, index) {
        var list_data = list.data;
        list_data.map(function(data, index) {
            return (
                <li key={index}>{data}</li>
            )
        });
        return(
            <div key={index}>
                <h2>{list.name}</h2>
                <ul>
                    {list_data}
                </ul>
            </div>
        )
    });

Edit

However, As pointed by the user Martin Dawson in the comment below, This is not always ideal.

So whats the solution then?

Many

  • You can create a function to generate unique keys/ids/numbers/strings and use that
  • You can make use of existing npm packages like uuid, uniqid, etc
  • You can also generate random number like new Date().getTime(); and prefix it with something from the item you're iterating to guarantee its uniqueness
  • Lastly, I recommend using the unique ID you get from the database, If you get it.

Example:

const generateKey = (pre) => {
    return `${ pre }_${ new Date().getTime() }`;
}

const savedLists = this.state.savedLists.map( list => {
    const list_data = list.data.map( data => <li key={ generateKey(data) }>{ data }</li> );
    return(
        <div key={ generateKey(list.name) }>
            <h2>{ list.name }</h2>
            <ul>
                { list_data }
            </ul>
        </div>
    )
});

Difference between string and StringBuilder in C#

A String is an immutable type. This means that whenever you start concatenating strings with each other you're creating new strings each time. If you do so many times you end up with a lot of heap overhead and the risk of running out of memory.

A StringBuilder instance is used to be able to append strings to the same instance, creating a string when you call the ToString method on it.

Due to the overhead of instantiating a StringBuilder object it's said by Microsoft that it's useful to use when you have more than 5-10 string concatenations.

For sample code I suggest you take a look here:

MySQL Insert with While Loop

drop procedure if exists doWhile;
DELIMITER //  
CREATE PROCEDURE doWhile()   
BEGIN
DECLARE i INT DEFAULT 2376921001; 
WHILE (i <= 237692200) DO
    INSERT INTO `mytable` (code, active, total) values (i, 1, 1);
    SET i = i+1;
END WHILE;
END;
//  

CALL doWhile();