Programs & Examples On #Language theory

How do I store and retrieve a blob from sqlite?

In C++ (without error checking):

std::string blob = ...; // assume blob is in the string


std::string query = "INSERT INTO foo (blob_column) VALUES (?);";

sqlite3_stmt *stmt;
sqlite3_prepare_v2(db, query, query.size(), &stmt, nullptr);
sqlite3_bind_blob(stmt, 1, blob.data(), blob.size(), 
                  SQLITE_TRANSIENT);

That can be SQLITE_STATIC if the query will be executed before blob gets destructed.

How to construct a set out of list items in python?

The most direct solution is this:

s = set(filelist)

The issue in your original code is that the values weren't being assigned to the set. Here's the fixed-up version of your code:

s = set()
for filename in filelist:
    s.add(filename)
print(s)

In jQuery, how do I get the value of a radio button when they all have the same name?

You might want to change selector:

$('input[name=q12_3]:checked').val()

Ping all addresses in network, windows

This post asks the same question, but for linux - you may find it helpful. Send a ping to each IP on a subnet

nmap is probably the best tool to use, as it can help identify host OS as well as being faster. It is available for the windows platform on the nmap.org site

Difference between ApiController and Controller in ASP.NET MVC

I love the fact that ASP.NET Core's MVC6 merged the two patterns into one because I often need to support both worlds. While it's true that you can tweak any standard MVC Controller (and/or develop your own ActionResult classes) to act & behave just like an ApiController, it can be very hard to maintain and to test: on top of that, having Controllers methods returning ActionResult mixed with others returning raw/serialized/IHttpActionResult data can be very confusing from a developer perspective, expecially if you're not working alone and need to bring other developers to speed with that hybrid approach.

The best technique I've come so far to minimize that issue in ASP.NET non-Core web applications is to import (and properly configure) the Web API package into the MVC-based Web Application, so I can have the best of both worlds: Controllers for Views, ApiControllers for data.

In order to do that, you need to do the following:

  • Install the following Web API packages using NuGet: Microsoft.AspNet.WebApi.Core and Microsoft.AspNet.WebApi.WebHost.
  • Add one or more ApiControllers to your /Controllers/ folder.
  • Add the following WebApiConfig.cs file to your /App_Config/ folder:

using System.Web.Http;

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Finally, you'll need to register the above class to your Startup class (either Startup.cs or Global.asax.cs, depending if you're using OWIN Startup template or not).

Startup.cs

 public void Configuration(IAppBuilder app)
 {
    // Register Web API routing support before anything else
    GlobalConfiguration.Configure(WebApiConfig.Register);

    // The rest of your file goes there
    // ...
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    ConfigureAuth(app);
    // ...
}

Global.asax.cs

protected void Application_Start()
{
    // Register Web API routing support before anything else
    GlobalConfiguration.Configure(WebApiConfig.Register);

    // The rest of your file goes there
    // ...
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    // ...
}

This approach - together with its pros and cons - is further explained in this post I wrote on my blog.

Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

Thank you Kris!

It worked for me without using parameters to the query, whenever I used more than one parameter it showed me the error: 32 Could not authenticate you.

The problem for me, was in the ampersand encoding. So in your code where it's the following line

$url .= "?".http_build_query($query);

I added the following line below:

$url=str_replace("&","&",$url);

And it worked using two or more parameters like screen_name and count.

The whole code looks like this:

$token = 'YOUR TOKEN';
$token_secret = 'TOKEN SECRET';
$consumer_key = 'YOUR KEY';
$consumer_secret = 'KEY SECRET';

$host = 'api.twitter.com';
$method = 'GET';
$path = '/1.1/statuses/user_timeline.json'; // api call path

$query = array( // query parameters
    'screen_name' => 'twitterapi',
    'count' => '2'
);

$oauth = array(
    'oauth_consumer_key' => $consumer_key,
    'oauth_token' => $token,
    'oauth_nonce' => (string)mt_rand(), // a stronger nonce is recommended
    'oauth_timestamp' => time(),
    'oauth_signature_method' => 'HMAC-SHA1',
    'oauth_version' => '1.0'
);

$oauth = array_map("rawurlencode", $oauth); // must be encoded before sorting
$query = array_map("rawurlencode", $query);

$arr = array_merge($oauth, $query); // combine the values THEN sort

asort($arr); // secondary sort (value)
ksort($arr); // primary sort (key)

// http_build_query automatically encodes, but our parameters
// are already encoded, and must be by this point, so we undo
// the encoding step
$querystring = urldecode(http_build_query($arr, '', '&'));

$url = "https://$host$path";

// mash everything together for the text to hash
$base_string = $method."&".rawurlencode($url)."&".rawurlencode($querystring);

// same with the key
$key = rawurlencode($consumer_secret)."&".rawurlencode($token_secret);

// generate the hash
$signature = rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));

// this time we're using a normal GET query, and we're only encoding the query params
// (without the oauth params)
$url .= "?".http_build_query($query);
$url=str_replace("&","&",$url); //Patch by @Frewuill

$oauth['oauth_signature'] = $signature; // don't want to abandon all that work!
ksort($oauth); // probably not necessary, but twitter's demo does it

// also not necessary, but twitter's demo does this too
function add_quotes($str) { return '"'.$str.'"'; }
$oauth = array_map("add_quotes", $oauth);

// this is the full value of the Authorization line
$auth = "OAuth " . urldecode(http_build_query($oauth, '', ', '));

// if you're doing post, you need to skip the GET building above
// and instead supply query parameters to CURLOPT_POSTFIELDS
$options = array( CURLOPT_HTTPHEADER => array("Authorization: $auth"),
                  //CURLOPT_POSTFIELDS => $postfields,
                  CURLOPT_HEADER => false,
                  CURLOPT_URL => $url,
                  CURLOPT_RETURNTRANSFER => true,
                  CURLOPT_SSL_VERIFYPEER => false);

// do our business
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);

$twitter_data = json_decode($json);

Hope It helps somebody with the same problem I had.

how to add a day to a date using jquery datepicker

The datepicker('setDate') sets the date in the datepicket not in the input.

You should add the date and set it in the input.

var date2 = $('.pickupDate').datepicker('getDate');
var nextDayDate = new Date();
nextDayDate.setDate(date2.getDate() + 1);
$('input').val(nextDayDate);

Insert Data Into Tables Linked by Foreign Key

Not with a regular statement, no.

What you can do is wrap the functionality in a PL/pgsql function (or another language, but PL/pgsql seems to be the most appropriate for this), and then just call that function. That means it'll still be a single statement to your app.

Handle file download from ajax post

For those looking a more modern approach, you can use the fetch API. The following example shows how to download a spreadsheet file. It is easily done with the following code.

fetch(url, {
    body: JSON.stringify(data),
    method: 'POST',
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    },
})
.then(response => response.blob())
.then(response => {
    const blob = new Blob([response], {type: 'application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
    const downloadUrl = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = downloadUrl;
    a.download = "file.xlsx";
    document.body.appendChild(a);
    a.click();
})

I believe this approach to be much easier to understand than other XMLHttpRequest solutions. Also, it has a similar syntax to the jQuery approach, without the need to add any additional libraries.

Of course, I would advise checking to which browser you are developing, since this new approach won't work on IE. You can find the full browser compatibility list on the following [link][1].

Important: In this example I am sending a JSON request to a server listening on the given url. This url must be set, on my example I am assuming you know this part. Also, consider the headers needed for your request to work. Since I am sending a JSON, I must add the Content-Type header and set it to application/json; charset=utf-8, as to let the server know the type of request it will receive.

How to determine if a String has non-alphanumeric characters?

One approach is to do that using the String class itself. Let's say that your string is something like that:

String s = "some text";
boolean hasNonAlpha = s.matches("^.*[^a-zA-Z0-9 ].*$");

one other is to use an external library, such as Apache commons:

String s = "some text";
boolean hasNonAlpha = !StringUtils.isAlphanumeric(s);

How to affect other elements when one element is hovered

If the cube is directly inside the container:

#container:hover > #cube { background-color: yellow; }

If cube is next to (after containers closing tag) the container:

#container:hover + #cube { background-color: yellow; }

If the cube is somewhere inside the container:

#container:hover #cube { background-color: yellow; }

If the cube is a sibling of the container:

#container:hover ~ #cube { background-color: yellow; }

Normalizing images in OpenCV

If you want to change the range to [0, 1], make sure the output data type is float.

image = cv2.imread("lenacolor512.tiff", cv2.IMREAD_COLOR)  # uint8 image
norm_image = cv2.normalize(image, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)

onchange file input change img src and change image color

Try with this code, you will get the image preview while uploading

<input type='file' id="upload" onChange="readURL(this);"/>
<img id="img" src="#" alt="your image" />

 function readURL(input){
 var ext = input.files[0]['name'].substring(input.files[0]['name'].lastIndexOf('.') + 1).toLowerCase();
if (input.files && input.files[0] && (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg")) 
    var reader = new FileReader();
    reader.onload = function (e) {
        $('#img').attr('src', e.target.result);
    }

    reader.readAsDataURL(input.files[0]);
}else{
     $('#img').attr('src', '/assets/no_preview.png');
}
}

How to prevent a double-click using jQuery?

I had a similar issue, but disabling the button didn't fully did the trick. There were some other actions that took place when the button was clicked and, sometimes, button wasn't disabled soon enough and when the user double-clicked, 2 events where fired.
I took Pangui's timeout idea, and combined both techniques, disabling the button and includeding a timeout, just in case. And I created a simple jQuery plugin:

var SINGLECLICK_CLICKED = 'singleClickClicked';
$.fn.singleClick = function () {
    var fncHandler; 
    var eventData;
    var fncSingleClick = function (ev) {
        var $this = $(this);
        if (($this.data(SINGLECLICK_CLICKED)) || ($this.prop('disabled'))) {
            ev.preventDefault();
            ev.stopPropagation();
        }
        else {
            $this.data(SINGLECLICK_CLICKED, true);
            window.setTimeout(function () {
                $this.removeData(SINGLECLICK_CLICKED);
            }, 1500);
            if ($.isFunction(fncHandler)) {
                fncHandler.apply(this, arguments);
            }
        }
    }

    switch (arguments.length) {
        case 0:
            return this.click();
        case 1:
            fncHandler = arguments[0];
            this.click(fncSingleClick);
            break;
        case 2: 
            eventData = arguments[0];
            fncHandler = arguments[1];
            this.click(eventData, fncSingleClick);
            break;
    }
    return this;
}

And then use it like this:

$("#button1").singleClick(function () {
   $(this).prop('disabled', true);
   //...
   $(this).prop('disabled', false);
})

How to import data from text file to mysql database

If your table is separated by others than tabs, you should specify it like...

LOAD DATA LOCAL 
    INFILE '/tmp/mydata.txt' INTO TABLE PerformanceReport 
    COLUMNS TERMINATED BY '\t'  ## This should be your delimiter
    OPTIONALLY ENCLOSED BY '"'; ## ...and if text is enclosed, specify here

How to connect mySQL database using C++

I had to include -lmysqlcppconn to my build in order to get it to work.

Re-sign IPA (iPhone)

Thank you, Erik, for posting this. This worked for me. I'd like to add a note about an extra step I needed. Within "Payload/Application.app/" there was a directory named "CACertChains" that contained a file named "cacert.pem". I had to remove the directory and the .pem to complete these steps. Thanks again! –

C++ Singleton design pattern

The paper that was linked to above describes the shortcoming of double checked locking is that the compiler may allocate the memory for the object and set a pointer to the address of the allocated memory, before the object's constructor has been called. It is quite easy in c++ however to use allocaters to allocate the memory manually, and then use a construct call to initialize the memory. Using this appraoch, the double-checked locking works just fine.

UIDevice uniqueIdentifier deprecated - What to do now?

Dont use these libraries - libOmnitureAppMeasurement, It does use uniqueIdentifier which apple doesnt support anymore

How to fix C++ error: expected unqualified-id

For anyone with this situation: I saw this error when I accidentally used my_first_scope::my_second_scope::true in place of simply true, like this:

bool my_var = my_first_scope::my_second_scope::true;

instead of:

bool my_var = true;

This is because I had a macro which caused MY_MACRO(true) to expand into my_first_scope::my_second_scope::true, by mistake, and I was actually calling bool my_var = MY_MACRO(true);.

Here's a quick demo of this type of scoping error:

Program (you can run it online here: https://onlinegdb.com/BkhFBoqUw):

#include <iostream>
#include <cstdio>

namespace my_first_scope 
{
namespace my_second_scope
{
} // namespace my_second_scope
} // namespace my_first_scope

int main()
{
    printf("Hello World\n");
    
    bool my_var = my_first_scope::my_second_scope::true;
    
    std::cout << my_var << std::endl;

    return 0;
}

Output (build error):

main.cpp: In function ‘int main()’:
main.cpp:27:52: error: expected unqualified-id before ‘true’
     bool my_var = my_first_scope::my_second_scope::true;
                                                    ^~~~

Notice the error: error: expected unqualified-id before ‘true’, and where the arrow under the error is pointing. Apparently the "unqualified-id" in my case is the double colon (::) scope operator I have just before true.

When I add in the macro and use it (run this new code here: https://onlinegdb.com/H1eevs58D):

#define MY_MACRO(input) my_first_scope::my_second_scope::input

...

bool my_var = MY_MACRO(true);

I get this new error instead:

main.cpp: In function ‘int main()’:
main.cpp:29:28: error: expected unqualified-id before ‘true’
     bool my_var = MY_MACRO(true);
                            ^
main.cpp:16:58: note: in definition of macro ‘MY_MACRO’
 #define MY_MACRO(input) my_first_scope::my_second_scope::input
                                                          ^~~~~

System.IO.IOException: file used by another process

I realize that I is kinda late, but still better late than never. I was having similar problem recently. I used XMLWriter to subsequently update XML file and was receiving the same errors. I found the clean solution for this:

The XMLWriter uses underlying FileStream to access the modified file. Problem is that when you call XMLWriter.Close() method, the underlying stream doesn't get closed and is locking the file. What you need to do is to instantiate your XMLWriter with settings and specify that you need that underlying stream closed.

Example:

XMLWriterSettings settings = new Settings();
settings.CloseOutput = true;
XMLWriter writer = new XMLWriter(filepath, settings);

Hope it helps.

How to force the input date format to dd/mm/yyyy?

No such thing. the input type=date will pick up whatever your system default is and show that in the GUI but will always store the value in ISO format (yyyy-mm-dd). Beside be aware that not all browsers support this so it's not a good idea to depend on this input type yet.

If this is a corporate issue, force all the computer to use local regional format (dd-mm-yyyy) and your UI will show it in this format (see wufoo link before after changing your regional settings, you need to reopen the browser).

Your best bet is still to use JavaScript based component that will allow you to customize this to whatever you wish.

Spring MVC Controller redirect using URL parameters instead of in response

This problem is caused (as others have stated) by model attributes being persisted into the query string - this is usually undesirable and is at risk of creating security holes as well as ridiculous query strings. My usual solution is to never use Strings for redirects in Spring MVC, instead use a RedirectView which can be configured not to expose model attributes (see: http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/servlet/view/RedirectView.html)

RedirectView(String url, boolean contextRelative, boolean http10Compatible, boolean exposeModelAttributes)

So I tend to have a util method which does a 'safe redirect' like:

public static RedirectView safeRedirect(String url) {
    RedirectView rv = new RedirectView(url);
    rv.setExposeModelAttributes(false);
    return rv;
}

The other option is to use bean configuration XML:

<bean id="myBean" class="org.springframework.web.servlet.view.RedirectView">
   <property name="exposeModelAttributes" value="false" />
   <property name="url" value="/myRedirect"/>
</bean>

Again, you could abstract this into its own class to avoid repetition (e.g. SafeRedirectView).


A note about 'clearing the model' - this is not the same as 'not exposing the model' in all circumstances. One site I worked on had a lot of filters which added things to the model, this meant that clearing the model before redirecting would not prevent a long query string. I would also suggest that 'not exposing model attributes' is a more semantic approach than 'clearing the model before redirecting'.

How to replace NaN values by Zeroes in a column of a Pandas Dataframe?

You can also use dictionaries to fill NaN values of the specific columns in the DataFrame rather to fill all the DF with some oneValue.

import pandas as pd

df = pd.read_excel('example.xlsx')
df.fillna( {
        'column1': 'Write your values here',
        'column2': 'Write your values here',
        'column3': 'Write your values here',
        'column4': 'Write your values here',
        .
        .
        .
        'column-n': 'Write your values here'} , inplace=True)

Cannot resolve symbol AppCompatActivity - Support v7 libraries aren't recognized?

Replace the

import android.support.v7.app.AppCompatActivity;

with import androidx.appcompat.app.AppCompatActivity

How to add parameters to a HTTP GET request in Android?

The method

setParams() 

like

httpget.getParams().setParameter("http.socket.timeout", new Integer(5000));

only adds HttpProtocol parameters.

To execute the httpGet you should append your parameters to the url manually

HttpGet myGet = new HttpGet("http://foo.com/someservlet?param1=foo&param2=bar");

or use the post request the difference between get and post requests are explained here, if you are interested

Drag and drop elements from list into separate blocks

_x000D_
_x000D_
 function dragStart(event) {_x000D_
            event.dataTransfer.setData("Text", event.target.id);_x000D_
        }_x000D_
_x000D_
        function allowDrop(event) {_x000D_
            event.preventDefault();_x000D_
        }_x000D_
_x000D_
        function drop(event) {_x000D_
            $("#maincontainer").append("<br/><table style='border:1px solid black; font-size:20px;'><tr><th>Name</th><th>Country</th><th>Experience</th><th>Technologies</th></tr><tr><td>  Bhanu Pratap   </td><td> India </td><td>  3 years   </td><td>  Javascript,Jquery,AngularJS,ASP.NET C#, XML,HTML,CSS,Telerik,XSLT,AJAX,etc...</td></tr></table>");_x000D_
        }
_x000D_
 .droptarget {_x000D_
            float: left;_x000D_
            min-height: 100px;_x000D_
            min-width: 200px;_x000D_
            border: 1px solid black;_x000D_
            margin: 15px;_x000D_
            padding: 10px;_x000D_
            border: 1px solid #aaaaaa;_x000D_
        }_x000D_
_x000D_
        [contentEditable=true]:empty:not(:focus):before {_x000D_
            content: attr(data-text);_x000D_
        }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>_x000D_
<div class="droptarget" ondrop="drop(event)" ondragover="allowDrop(event)">_x000D_
        <p ondragstart="dragStart(event)" draggable="true" id="dragtarget">Drag Table</p>_x000D_
    </div>_x000D_
_x000D_
    <div id="maincontainer" contenteditable=true data-text="Drop here..." class="droptarget" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
_x000D_
_x000D_
_x000D_

  1. this is just simple here i'm appending html table into a div at the end
  2. we can achieve this or any thing with a simple concept of calling a JavaScript function when we want (here on drop.)
  3. In this example you can drag & drop any number of tables, new table will be added below the last table exists in the div other wise it will be the first table in the div.
  4. here we can add text between tables or we can say the section where we drop tables is editable we can type text between tables. enter image description here

Thanks... :)

How to get Android GPS location

The initial issue is solved by changing lat and lon to double.

I want to add comment to solution with Location location = locationManager.getLastKnownLocation(bestProvider); It works to find out last known location when other app was lisnerning for that. If, for example, no app did that since device start, the code will return zeros (spent some time myself recently to figure that out).

Also, it's a good practice to stop listening when there is no need for that by locationManager.removeUpdates(this);

Also, even with permissions in manifest, the code works when location service is enabled in Android settings on a device.

What is <scope> under <dependency> in pom.xml for?

Scope tag is always use to limit the transitive dependencies and availability of the jar at class path level.If we don't provide any scope then the default scope will work i.e. Compile .

What version of Python is on my Mac?

You could have multiple Python versions on your macOS.

You may check that by command, type or which command, like:

which -a python python2 python2.7 python3 python3.6

Or type python in Terminal and hit Tab few times for auto completion, which is equivalent to:

compgen -c python

By default python/pip commands points to the first binary found in PATH environment variable depending what's actually installed. So before installing Python packages with Homebrew, the default Python is installed in /usr/bin which is shipped with your macOS (e.g. Python 2.7.10 on High Sierra). Any versions found in /usr/local (such as /usr/local/bin) are provided by external packages.

It is generally advised, that when working with multiple versions, for Python 2 you may use python2/pip2 command, respectively for Python 3 you can use python3/pip3, but it depends on your configuration which commands are available.

It is also worth to mention, that since release of Homebrew 1.5.0+ (on 19 January 2018), the python formula has been upgraded to Python 3.x and a python@2 formula will be added for installing Python 2.7. Before, python formula was pointing to Python 2.

For instance, if you've installed different version via Homebrew, try the following command:

brew list python python3

or:

brew list | grep ^python

it'll show you all Python files installed with the package.

Alternatively you may use apropos or locate python command to locate more Python related files.

To check any environment variables related to Python, run:

env | grep ^PYTHON

To address your issues:

  • Error: No such keg: /usr/local/Cellar/python

    Means you don't have Python installed via Homebrew. However double check by specifying only one package at a time (like brew list python python2 python3).

  • The locate database (/var/db/locate.database) does not exist.

    Follow the advice and run:

    sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist
    

    After the database is rebuild, you can use locate command.

git still shows files as modified after adding to .gitignore

In my case, the .gitignore file is somehow corrupted. It sometimes shows up OK but sometimes is gibberish. I guess the encoding might be to blame but cannot be sure. To solve the issue, I deleted the file (previously created through echo > .gitgore in VS Code commandline) and created a new one manually in the file system (Explorer), then added my ignore rules. After the new .ignore was in place, everything works fine.

What is the significance of 1/1/1753 in SQL Server?

Your great great great great great great great grandfather should upgrade to SQL Server 2008 and use the DateTime2 data type, which supports dates in the range: 0001-01-01 through 9999-12-31.

GoogleMaps API KEY for testing

There seems no way to have google maps api key free without credit card. To test the functionality of google map you can use it while leaving the api key field "EMPTY". It will show a message saying "For Development Purpose Only". And that way you can test google map functionality without putting billing information for google map api key.

<script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap" async defer></script>

how to delete a specific row in codeigniter?

**multiple delete not working**

function delete_selection() 
{
        $id_array = array();
        $selection = $this->input->post("selection", TRUE);
        $id_array = explode("|", $selection);

        foreach ($id_array as $item):
            if ($item != ''):
                //DELETE ROW
                $this->db->where('entry_id', $item);
                $this->db->delete('helpline_entry');
            endif;
        endforeach;
    }

Sites not accepting wget user agent header

You need to set both the user-agent and the referer:

 wget  --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" --referrer  connect.wso2.com http://dist.wso2.org/products/carbon/4.2.0/wso2carbon-4.2.0.zip

how to configure config.inc.php to have a loginform in phpmyadmin

$cfg['Servers'][$i]['AllowNoPassword'] = false;

When is a C++ destructor called?

Others have already addressed the other issues, so I'll just look at one point: do you ever want to manually delete an object.

The answer is yes. @DavidSchwartz gave one example, but it's a fairly unusual one. I'll give an example that's under the hood of what a lot of C++ programmers use all the time: std::vector (and std::deque, though it's not used quite as much).

As most people know, std::vector will allocate a larger block of memory when/if you add more items than its current allocation can hold. When it does this, however, it has a block of memory that's capable of holding more objects than are currently in the vector.

To manage that, what vector does under the covers is allocate raw memory via the Allocator object (which, unless you specify otherwise, means it uses ::operator new). Then, when you use (for example) push_back to add an item to the vector, internally the vector uses a placement new to create an item in the (previously) unused part of its memory space.

Now, what happens when/if you erase an item from the vector? It can't just use delete -- that would release its entire block of memory; it needs to destroy one object in that memory without destroying any others, or releasing any of the block of memory it controls (for example, if you erase 5 items from a vector, then immediately push_back 5 more items, it's guaranteed that the vector will not reallocate memory when you do so.

To do that, the vector directly destroys the objects in the memory by explicitly calling the destructor, not by using delete.

If, perchance, somebody else were to write a container using contiguous storage roughly like a vector does (or some variant of that, like std::deque really does), you'd almost certainly want to use the same technique.

Just for example, let's consider how you might write code for a circular ring-buffer.

#ifndef CBUFFER_H_INC
#define CBUFFER_H_INC

template <class T>
class circular_buffer {
    T *data;
    unsigned read_pos;
    unsigned write_pos;
    unsigned in_use;
    const unsigned capacity;
public:
    circular_buffer(unsigned size) :
        data((T *)operator new(size * sizeof(T))),
        read_pos(0),
        write_pos(0),
        in_use(0),
        capacity(size)
    {}

    void push(T const &t) {
        // ensure there's room in buffer:
        if (in_use == capacity) 
            pop();

        // construct copy of object in-place into buffer
        new(&data[write_pos++]) T(t);
        // keep pointer in bounds.
        write_pos %= capacity;
        ++in_use;
    }

    // return oldest object in queue:
    T front() {
        return data[read_pos];
    }

    // remove oldest object from queue:
    void pop() { 
        // destroy the object:
        data[read_pos++].~T();

        // keep pointer in bounds.
        read_pos %= capacity;
        --in_use;
    }
  
~circular_buffer() {
    // first destroy any content
    while (in_use != 0)
        pop();

    // then release the buffer.
    operator delete(data); 
}

};

#endif

Unlike the standard containers, this uses operator new and operator delete directly. For real use, you probably do want to use an allocator class, but for the moment it would do more to distract than contribute (IMO, anyway).

How do you set EditText to only accept numeric values in Android?

the simplest for me

android:numeric="integer" 

although this also more customize

android:digits="0123456789"

XPath to fetch SQL XML value

I always go back to this article SQL Server 2005 XQuery and XML-DML - Part 1 to know how to use the XML features in SQL Server 2005.

For basic XPath know-how, I'd recommend the W3Schools tutorial.

Android: how do I check if activity is running?

I think the accepted answer is an awful way of handling this.

I don't know what the use case is, but please consider a protected method in the base class

@protected
void doSomething() {
}

and override it in the derived class.

When the event occurs, just call this method in the base class. The correct 'active' class will handle it then. The class itself can then check if it is not Paused().

Better yet, use an event bus like GreenRobot's, Square's, but that one is deprecated and suggests using RxJava

Dynamically load a JavaScript file

Keep it nice, short, simple, and maintainable! :]

// 3rd party plugins / script (don't forget the full path is necessary)
var FULL_PATH = '', s =
[
    FULL_PATH + 'plugins/script.js'      // Script example
    FULL_PATH + 'plugins/jquery.1.2.js', // jQuery Library 
    FULL_PATH + 'plugins/crypto-js/hmac-sha1.js',      // CryptoJS
    FULL_PATH + 'plugins/crypto-js/enc-base64-min.js'  // CryptoJS
];

function load(url)
{
    var ajax = new XMLHttpRequest();
    ajax.open('GET', url, false);
    ajax.onreadystatechange = function ()
    {
        var script = ajax.response || ajax.responseText;
        if (ajax.readyState === 4)
        {
            switch(ajax.status)
            {
                case 200:
                    eval.apply( window, [script] );
                    console.log("library loaded: ", url);
                    break;
                default:
                    console.log("ERROR: library not loaded: ", url);
            }
        }
    };
    ajax.send(null);
}

 // initialize a single load 
load('plugins/script.js');

// initialize a full load of scripts
if (s.length > 0)
{
    for (i = 0; i < s.length; i++)
    {
        load(s[i]);
    }
}

This code is simply a short functional example that could require additional feature functionality for full support on any (or given) platform.

Adding elements to a C# array

If you really won't (or can't) use a generic collection instead of your array, Array.Resize is c#'s version of redim preserve:

var  oldA = new [] {1,2,3,4};
Array.Resize(ref oldA,10);
foreach(var i in oldA) Console.WriteLine(i); //1 2 3 4 0 0 0 0 0 0

Select distinct values from a list using LINQ in C#

Try,

var newList = 
(
from x in empCollection
select new {Loc = x.empLoc, PL = x.empPL, Shift = x.empShift}
).Distinct();

Does C have a string type?

First, you don't need to do all that. In particular, the strcpy is redundant - you don't need to copy a string just to printf it. Your message can be defined with that string in place.

Second, you've not allowed enough space for that "Hello, World!" string (message needs to be at least 14 characters, allowing the extra one for the null terminator).

On the why, though, it's history. In assembler, there are no strings, only bytes, words etc. Pascal had strings, but there were problems with static typing because of that - string[20] was a different type that string[40]. There were languages even in the early days that avoided this issue, but that caused indirection and dynamic allocation overheads which were much more of an efficiency problem back then.

C simply chose to avoid the overheads and stay very low level. Strings are character arrays. Arrays are very closely related to pointers that point to their first item. When array types "decay" to pointer types, the buffer-size information is lost from the static type, so you don't get the old Pascal string issues.

In C++, there's the std::string class which avoids a lot of these issues - and has the dynamic allocation overheads, but these days we usually don't care about that. And in any case, std::string is a library class - there's C-style character-array handling underneath.

jQuery position DIV fixed at top on scroll

instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0; once your window has scrolled pass a certain height:

jQuery

  $(window).scroll(function(){
      if ($(this).scrollTop() > 135) {
          $('#task_flyout').addClass('fixed');
      } else {
          $('#task_flyout').removeClass('fixed');
      }
  });

css

.fixed {position:fixed; top:0; left:0;}

Example

How do I convert NSMutableArray to NSArray?

In objective-c :

NSArray *myArray = [myMutableArray copy];

In swift :

 var arr = myMutableArray as NSArray

using "if" and "else" Stored Procedures MySQL

The problem is you either haven't closed your if or you need an elseif:

create procedure checando(
    in nombrecillo varchar(30),
    in contrilla varchar(30), 
    out resultado int)
begin 

    if exists (select * from compas where nombre = nombrecillo and contrasenia = contrilla) then
        set resultado = 0;
    elseif exists (select * from compas where nombre = nombrecillo) then
        set resultado = -1;
    else 
        set resultado = -2;
    end if;
end;

How can I account for period (AM/PM) using strftime?

You used %H (24 hour format) instead of %I (12 hour format).

C# : assign data to properties via constructor vs. instantiating

Second approach is object initializer in C#

Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor.

The first approach

var albumData = new Album("Albumius", "Artistus", 2013);

explicitly calls the constructor, whereas in second approach constructor call is implicit. With object initializer you can leave out some properties as well. Like:

 var albumData = new Album
        {
            Name = "Albumius",
        };

Object initializer would translate into something like:

var albumData; 
var temp = new Album();
temp.Name = "Albumius";
temp.Artist = "Artistus";
temp.Year = 2013;
albumData = temp;

Why it uses a temporary object (in debug mode) is answered here by Jon Skeet.

As far as advantages for both approaches are concerned, IMO, object initializer would be easier to use specially if you don't want to initialize all the fields. As far as performance difference is concerned, I don't think there would any since object initializer calls the parameter less constructor and then assign the properties. Even if there is going to be performance difference it should be negligible.

'Missing contentDescription attribute on image' in XML

This warning tries to improve accessibility of your application.

To disable missing content description warning in the whole project, you can add this to your application module build.gradle

android {

    ...

    lintOptions {
        disable 'ContentDescription'
    }
}

How to initialize array to 0 in C?

If you'd like to initialize the array to values other than 0, with gcc you can do:

int array[1024] = { [ 0 ... 1023 ] = -1 };

This is a GNU extension of C99 Designated Initializers. In older GCC, you may need to use -std=gnu99 to compile your code.

jQuery get textarea text

Normally, it's the value property

testArea.value

Or is there something I'm missing in what you need?

apply drop shadow to border-top only?

Multiple box shadows did it for me.

box-shadow:
        inset 0 -8px 4px 4px rgb(255,255,255),
        inset 0 2px 4px 0px rgba(50, 50, 50, 0.75);

http://jsfiddle.net/kk66f/

How to format a java.sql Timestamp for displaying?

For this particular question, the standard suggestion of java.text.SimpleDateFormat works, but has the unfortunate side effect that SimpleDateFormat is not thread-safe and can be the source of particularly nasty problems since it'll corrupt your output in multi-threaded scenarios, and you won't get any exceptions!

I would strongly recommend looking at Joda for anything like this. Why ? It's a much richer and more intuitive time/date library for Java than the current library (and the basis of the up-and-coming new standard Java date/time library, so you'll be learning a soon-to-be-standard API).

How to Delete node_modules - Deep Nested Folder in Windows

Please save yourself the need to read most of these answers and just use npx rather than trying to install rimraf globally. You can run a single command and always have the most recent version with none of the issues seen here.

npx rimraf ./**/node_modules

Write lines of text to a file in R

You could do that in a single statement

cat("hello","world",file="output.txt",sep="\n",append=TRUE)

How to check if the docker engine and a docker container are running?

container status: true/false

# docker inspect --format '{{json .State.Running}}' container-name
true
#

How to hide elements without having them take space on the page?

use style instead like

<div style="display:none;"></div>

How to create an empty array in PHP with predefined size?

You can't predefine a size of an array in php. A good way to acheive your goal is the following:

// Create a new array.
$array = array(); 

// Add an item while $i < yourWantedItemQuantity
for ($i = 0; $i < $number_of_items; $i++)
{
    array_push($array, $some_data);
    //or $array[] = $some_data; for single items.
}

Note that it is way faster to use array_fill() to fill an Array :

$array = array_fill(0,$number_of_items, $some_data);

If you want to verify if a value has been set at an index, you should use the following: array_key_exists("key", $array) or isset($array["key"])

See array_key_exists , isset and array_fill

Redirect from asp.net web api post action

You can check this

[Route("Report/MyReport")]
public IHttpActionResult GetReport()
{

   string url = "https://localhost:44305/Templates/ReportPage.html";

   System.Uri uri = new System.Uri(url);

   return Redirect(uri);
}

Python - Move and overwrite files and folders

Since none of the above worked for me, so I wrote my own recursive function. Call Function copyTree(dir1, dir2) to merge directories. Run on multi-platforms Linux and Windows.

def forceMergeFlatDir(srcDir, dstDir):
    if not os.path.exists(dstDir):
        os.makedirs(dstDir)
    for item in os.listdir(srcDir):
        srcFile = os.path.join(srcDir, item)
        dstFile = os.path.join(dstDir, item)
        forceCopyFile(srcFile, dstFile)

def forceCopyFile (sfile, dfile):
    if os.path.isfile(sfile):
        shutil.copy2(sfile, dfile)

def isAFlatDir(sDir):
    for item in os.listdir(sDir):
        sItem = os.path.join(sDir, item)
        if os.path.isdir(sItem):
            return False
    return True


def copyTree(src, dst):
    for item in os.listdir(src):
        s = os.path.join(src, item)
        d = os.path.join(dst, item)
        if os.path.isfile(s):
            if not os.path.exists(dst):
                os.makedirs(dst)
            forceCopyFile(s,d)
        if os.path.isdir(s):
            isRecursive = not isAFlatDir(s)
            if isRecursive:
                copyTree(s, d)
            else:
                forceMergeFlatDir(s, d)

Do the parentheses after the type name make a difference with new?

The rules for new are analogous to what happens when you initialize an object with automatic storage duration (although, because of vexing parse, the syntax can be slightly different).

If I say:

int my_int; // default-initialize ? indeterminate (non-class type)

Then my_int has an indeterminate value, since it is a non-class type. Alternatively, I can value-initialize my_int (which, for non-class types, zero-initializes) like this:

int my_int{}; // value-initialize ? zero-initialize (non-class type)

(Of course, I can't use () because that would be a function declaration, but int() works the same as int{} to construct a temporary.)

Whereas, for class types:

Thing my_thing; // default-initialize ? default ctor (class type)
Thing my_thing{}; // value-initialize ? default-initialize ? default ctor (class type)

The default constructor is called to create a Thing, no exceptions.

So, the rules are more or less:

  • Is it a class type?
    • YES: The default constructor is called, regardless of whether it is value-initialized (with {}) or default-initialized (without {}). (There is some additional prior zeroing behavior with value-initialization, but the default constructor is always given the final say.)
    • NO: Were {} used?
      • YES: The object is value-initialized, which, for non-class types, more or less just zero-initializes.
      • NO: The object is default-initialized, which, for non-class types, leaves it with an indeterminate value (it effectively isn't initialized).

These rules translate precisely to new syntax, with the added rule that () can be substituted for {} because new is never parsed as a function declaration. So:

int* my_new_int = new int; // default-initialize ? indeterminate (non-class type)
Thing* my_new_thing = new Thing; // default-initialize ? default ctor (class type)
int* my_new_zeroed_int = new int(); // value-initialize ? zero-initialize (non-class type)
     my_new_zeroed_int = new int{}; // ditto
       my_new_thing = new Thing(); // value-initialize ? default-initialize ? default ctor (class type)

(This answer incorporates conceptual changes in C++11 that the top answer currently does not; notably, a new scalar or POD instance that would end up an with indeterminate value is now technically now default-initialized (which, for POD types, technically calls a trivial default constructor). While this does not cause much practical change in behavior, it does simplify the rules somewhat.)

npm ERR! network getaddrinfo ENOTFOUND

I got the exact same error and this is what i did.

npm config get proxy

and it returned "null"

Opened "C:\Users\Myname.npmrc" in a notepad and made some changes. This is how my .npmrc file looks now

http-proxy=http://proxyhost/:proxyport
strict-ssl=false
registry=http://registry.npmjs.org/

Where can I find "make" program for Mac OS X Lion?

If you installed xcode and upgraded to mountain lion, or you don't have the latest command line tools installed, or you have zsh or other shells, you can shortcut to some of the embedded tools in the developer directory with:

xcrun make

Error Code 1292 - Truncated incorrect DOUBLE value - Mysql

Had this issue with ES6 and TypeORM while trying to pass .where("order.id IN (:orders)", { orders }), where orders was a comma separated string of numbers. When I converted to a template literal, the problem was resolved.

.where(`order.id IN (${orders})`);

Node.js throws "btoa is not defined" error

Here's a concise universal solution for base64 encoding:

const nodeBtoa = (b) => Buffer.from(b).toString('base64');
export const base64encode = typeof btoa !== 'undefined' ? btoa : nodeBtoa;

IF EXISTS, THEN SELECT ELSE INSERT AND THEN SELECT

create schema tableName authorization dbo
go
IF OBJECT_ID ('tableName.put_fieldValue', 'P' ) IS NOT NULL 
drop proc tableName.put_fieldValue
go
create proc tableName.put_fieldValue(@fieldValue int) as
declare @tableid int = 0
select @tableid = tableid from table where fieldValue=''
if @tableid = 0 begin
   insert into table(fieldValue) values('')
   select @tableid = scope_identity()
end
return @tableid
go
declare @tablid int = 0
exec @tableid = tableName.put_fieldValue('')

How to discard uncommitted changes in SourceTree?

Its Ctrl + Shift + r

For me, there was only one option to discard all.

enter image description here

Fill an array with random numbers

I tried to make this as simple as possible in Java. This makes an integer array of 100 variables and fill it with integers between 0 and 10 using only three lines of code. You can easily change the bounds of the random number too!

int RandNumbers[]=new int[100];
for (int i=0;i<RandNumbers.length;i++)
    RandNumbers[i]=ThreadLocalRandom.current().nextInt(0,10);

Import Android volley to Android Studio

The "compile project(':volley')" line was giving me this error:

Error:Execution failed for task ':volley:processDebugResources'. > com.android.ide.common.process.ProcessException: Failed to execute aapt

It was caused because the compileSdk and buildTools versions of module volley were currently on"22" and "22.0.1" and I my project was working with newer ones ("24" and "24.0.1").

SOLUTION:

Open your build.gradle (Module:volley) file and change the version of "compileSdk" and "buildTools", for example I changed this:

android {
    compileSdkVersion 22
    buildToolsVersion = '22.0.1'
}

for this:

android {
    compileSdkVersion 24
    buildToolsVersion = '24.0.1'
}

You should no longer have this error, I hope it helps:)

Bootstrap 3: How do you align column content to bottom of row

When working with bootsrap usually face three main problems:

  1. How to place the content of the column to the bottom?
  2. How to create a multi-row gallery of columns of equal height in one .row?
  3. How to center columns horizontally if their total width is less than 12 and the remaining width is odd?

To solve first two problems download this small plugin https://github.com/codekipple/conformity

The third problem is solved here http://www.minimit.com/articles/solutions-tutorials/bootstrap-3-responsive-centered-columns

Common code

<style>
    [class*=col-] {position: relative}
    .row-conformity .to-bottom {position:absolute; bottom:0; left:0; right:0}
    .row-centered {text-align:center}   
    .row-centered [class*=col-] {display:inline-block; float:none; text-align:left; margin-right:-4px; vertical-align:top} 
</style>

<script src="assets/conformity/conformity.js"></script>
<script>
    $(document).ready(function () {
        $('.row-conformity > [class*=col-]').conformity();
        $(window).on('resize', function() {
            $('.row-conformity > [class*=col-]').conformity();
        });
    });
</script>

1. Aligning content of the column to the bottom

<div class="row row-conformity">
    <div class="col-sm-3">
        I<br>create<br>highest<br>column
    </div>
    <div class="col-sm-3">
        <div class="to-bottom">
            I am on the bottom
        </div>
    </div>
</div>

2. Gallery of columns of equal height

<div class="row row-conformity">
    <div class="col-sm-4">We all have equal height</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
</div>

3. Horizontal alignment of columns to the center (less than 12 col units)

<div class="row row-centered">
    <div class="col-sm-3">...</div>
    <div class="col-sm-4">...</div>
</div>

All classes can work together

<div class="row row-conformity row-centered">
    ...
</div>

Windows batch: echo without new line

I made a function out of @arnep 's idea:

echo|set /p="Hello World"

here it is:

:SL (sameline)
echo|set /p=%1
exit /b

Use it with call :SL "Hello There"
I know this is nothing special but it took me so long to think of it I figured I'd post it here.

What's the best practice to "git clone" into an existing folder?

To clone a git repo into an empty existing directory do the following:

cd myfolder
git clone https://myrepo.com/git.git . 

Notice the . at the end of your git clone command. That will download the repo into the current working directory.

Font Awesome icon inside text input element

Output:

enter image description here

HTML:

<input name="txtName" id="txtName">

<span class="fa fa-info-circle errspan"></span>

CSS:

<style type="text/css">
    .errspan {
        float: right;
        margin-right: 6px;
        margin-top: -20px;
        position: relative;
        z-index: 2;
        color: red;
    }
</style>

(Or)

Output:

enter image description here

HTML:

<div class="input-wrapper">
     <input type="text" />
 </div>

CSS:

<style type="text/css">
    .input-wrapper {
        display:inline-block;
        position: relative
    }
    .input-wrapper:after {
        font-family: 'FontAwesome';
        content: '\f274';
        position: absolute;
        right: 6px;
    }
</style>

Java ByteBuffer to String

private String convertFrom(String lines, String from, String to) {
    ByteBuffer bb = ByteBuffer.wrap(lines.getBytes());
    CharBuffer cb = Charset.forName(to).decode(bb);
    return new String(Charset.forName(from).encode(cb).array());
};
public Doit(){
    String concatenatedLines = convertFrom(concatenatedLines, "CP1252", "UTF-8");
};

PHP get domain name

Similar question has been asked in stackoverflow before.

See here: PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

Also see this article: http://shiflett.org/blog/2006/mar/server-name-versus-http-host

Recommended using HTTP_HOST, and falling back on SERVER_NAME only if HTTP_HOST was not set. He said that SERVER_NAME could be unreliable on the server for a variety of reasons, including:

  • no DNS support
  • misconfigured
  • behind load balancing software

Source: http://discussion.dreamhost.com/thread-4388.html

Set date input field's max date to today

toISOString() will give current UTC Date. So to get the current local time we have to get getTimezoneOffset() and subtract it from current time

_x000D_
_x000D_
document.getElementById('dt').max = new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60000).toISOString().split("T")[0];
_x000D_
<input type="date" min='1899-01-01' id="dt" />
_x000D_
_x000D_
_x000D_

How to resize a VirtualBox vmdk file

As mentioned in the answer by Luca the required steps are:

  1. Clone the VMDK image to VDI format

    VBoxManage clonehd "source.vmdk" "cloned.vdi" --format vdi

  2. Resize the VDI image

    VBoxManage modifyhd "cloned.vdi" --resize 51200

  3. Clone back to VMDK format

    VBoxManage clonehd "cloned.vdi" "resized.vmdk" --format vmdk

Step 3 is optional if you can use a VDI image instead.

All these steps can be carried out in the VirtualBox graphical user interface as well, under File -> Virtual Media Manager. Select the drive you want to clone, and then choose Copy. A dialog opens that allows you to choose the disk format and options. To resize a VDI image, just use the slider in the bottom (click on Properties if it's not visible).

Finally, you may need to change the disk size in the guest OS as well:

  1. Run the guest OS and resize the disk partition(s). If you are running Linux, you can use gparted or kparted.

Convert Promise to Observable

1 Direct Execution / Conversion

Use from to directly convert a previously created Promise to an Observable.

import { from } from 'rxjs';

// getPromise() is called once, the promise is passed to the Observable
const observable$ = from(getPromise());

observable$ will be a hot Observable that effectively replays the Promises value to Subscribers.

It's a hot Observable because the producer (in this case the Promise) is created outside of the Observable. Multiple subscribers will share the same Promise. If the inner Promise has been resolved a new subscriber to the Observable will get its value immediately.

2 Deferred Execution On Every Subscribe

Use defer with a Promise factory function as input to defer the creation and conversion of a Promise to an Observable.

import { defer } from 'rxjs';

// getPromise() is called every time someone subscribes to the observable$
const observable$ = defer(() => getPromise());

observable$ will be a cold Observable.

It's a cold Observable because the producer (the Promise) is created inside of the Observable. Each subscriber will create a new Promise by calling the given Promise factory function.

This allows you to create an observable$ without creating and thus executing a Promise right away and without sharing this Promise with multiple subscribers. Each subscriber to observable$ effectively calls from(promiseFactory()).subscribe(subscriber). So each subscriber creates and converts its own new Promise to a new Observable and attaches itself to this new Observable.

3 Many Operators Accept Promises Directly

Most RxJS operators that combine (e.g. merge, concat, forkJoin, combineLatest ...) or transform observables (e.g. switchMap, mergeMap, concatMap, catchError ...) accept promises directly. If you're using one of them anyway you don't have to use from to wrap a promise first (but to create a cold observable you still might have to use defer).

// Execute two promises simultaneously
forkJoin(getPromise(1), getPromise(2)).pipe(
  switchMap(([v1, v2]) => v1.getPromise(v2)) // map to nested Promise
)

Check the documentation or implementation to see if the operator you're using accepts ObservableInput or SubscribableOrPromise.

type ObservableInput<T> = SubscribableOrPromise<T> | ArrayLike<T> | Iterable<T>;
// Note the PromiseLike ----------------------------------------------------v
type SubscribableOrPromise<T> = Subscribable<T> | Subscribable<never> | PromiseLike<T> | InteropObservable<T>;

The difference between from and defer in an example: https://stackblitz.com/edit/rxjs-6rb7vf

const getPromise = val => new Promise(resolve => {
  console.log('Promise created for', val);
  setTimeout(() => resolve(`Promise Resolved: ${val}`), 5000);
});

// the execution of getPromise('FROM') starts here, when you create the promise inside from
const fromPromise$ = from(getPromise('FROM'));
const deferPromise$ = defer(() => getPromise('DEFER'));

fromPromise$.subscribe(console.log);
// the execution of getPromise('DEFER') starts here, when you subscribe to deferPromise$
deferPromise$.subscribe(console.log);

How to get index using LINQ?

myCars.Select((v, i) => new {car = v, index = i}).First(myCondition).index;

or the slightly shorter

myCars.Select((car, index) => new {car, index}).First(myCondition).index;

Detect element content changes with jQuery

These are mutation events.

I have not used mutation event APIs in jQuery, but a cursory search led me to this project on GitHub. I am unaware of the project's maturity.

Jenkins not executing jobs (pending - waiting for next executor)

In my case it is similar to @Michael Easter: I got a problem in a job due to lack of disk space. I cleared some space, restarted Jenkins but still the problem persisted.

The solution was to go to Jenkins -> Manage Jenkins -> Manage Nodes and just Click on the button to update the status.

how to sort an ArrayList in ascending order using Collections and Comparator

Use the default version:

Collections.sort(myarrayList);

Of course this requires that your Elements implement Comparable, but the same holds true for the version you mentioned.

BTW: you should use generics in your code, that way you get compile-time errors if your class doesn't implement Comparable. And compile-time errors are much better than the runtime errors you'll get otherwise.

List<MyClass> list = new ArrayList<MyClass>();
// now fill up the list

// compile error here unless MyClass implements Comparable
Collections.sort(list); 

How can I add an item to a IEnumerable<T> collection?

Sure, you can (I am leaving your T-business aside):

public IEnumerable<string> tryAdd(IEnumerable<string> items)
{
    List<string> list = items.ToList();
    string obj = "";
    list.Add(obj);

    return list.Select(i => i);
}

How to find all the dependencies of a table in sql server

In SQL Server 2008 there are two new Dynamic Management Functions introduced to keep track of object dependencies: sys.dm_sql_referenced_entities and sys.dm_sql_referencing_entities:

1/ Returning the entities that refer to a given entity:

SELECT
        referencing_schema_name, referencing_entity_name, 
        referencing_class_desc, is_caller_dependent
FROM sys.dm_sql_referencing_entities ('<TableName>', 'OBJECT')

2/ Returning entities that are referenced by an object:

SELECT
        referenced_schema_name, referenced_entity_name, referenced_minor_name, 
        referenced_class_desc, is_caller_dependent, is_ambiguous
FROM sys.dm_sql_referenced_entities ('<StoredProcedureName>', 'OBJECT');

Alternatively, you can use sp_depends:

EXEC sp_depends '<TableName>'

Another option is to use a pretty useful tool called SQL Dependency Tracker from Red Gate.

Stop an input field in a form from being submitted

Add disabled="disabled" in input and while jquery remove the attribute disabled when you want to submit it using .removeAttr('disabled')

HTML:

<input type="hidden" name="test" value="test" disabled='disabled'/>

jquery:

$("input[name='test']").removeAttr('disabled');

Difference between frontend, backend, and middleware in web development

Generally speaking, people refer to an application's presentation layer as its front end, its persistence layer (database, usually) as the back end, and anything between as middle tier. This set of ideas is often referred to as 3-tier architecture. They let you separate your application into more easily comprehensible (and testable!) chunks; you can also reuse lower-tier code more easily in higher tiers.

Which code is part of which tier is somewhat subjective; graphic designers tend to think of everything that isn't presentation as the back end, database people think of everything in front of the database as the front end, and so on.

Not all applications need to be separated out this way, though. It's certainly more work to have 3 separate sub-projects than it is to just open index.php and get cracking; depending on (1) how long you expect to have to maintain the app (2) how complex you expect the app to get, you may want to forgo the complexity.

MySQL COUNT DISTINCT

Overall

SELECT
       COUNT(DISTINCT `site_id`) as distinct_sites
  FROM `cp_visits`
 WHERE ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)

Or per site

  SELECT
         `site_id` as site,
         COUNT(DISTINCT `user_id`) as distinct_users_per_site
    FROM `cp_visits`
   WHERE ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
GROUP BY `site_id`

Having the time column in the result doesn't make sense - since you are aggregating the rows, showing one particular time is irrelevant, unless it is the min or max you are after.

How to fully delete a git repository created with init?

I tried:

rm -rf .git and also

Git keeps all of its files in the .git directory. Just remove that one and init again.

Neither worked for me. Here's what did:

  • Delete all files except for .git
  • git add . -A
  • git commit -m "deleted entire project"
  • git push

Then create / restore the project from backup:

  • Create new project files (or copy paste a backup)
  • git add . -A
  • git commit -m "recreated project"
  • git push

Allowed memory size of 536870912 bytes exhausted in Laravel

While using Laravel on apache server there is another php.ini

 /etc/php/7.2/apache2/php.ini

Modify the memory limit value in this file

 memory_limit=1024M

and restart the apache server

 sudo service apache2 restart

Access Control Request Headers, is added to header in AJAX request with jQuery

And that is why you can't create a bot with JavaScript, because your options are limited to what the browser allows you to do. You can't just order a browser that follows the CORS policy, which most browsers follow, to send random requests to other origins and allow you to get the response that simply!

Additionally, if you tried to edit some request headers manually, like origin-header from the developers tools that come with the browsers, the browser will refuse your edit and may send a preflight OPTIONS request.

Export MySQL data to Excel in PHP

Try the Following Code Please. just only update two values.
1.your_database_name 2.table_name

 <?php
    $host="localhost";
    $username="root";
    $password="";
    $dbname="your_database_name";
    $con = new mysqli($host, $username, $password,$dbname); 

        $sql_data="select * from table_name";
        $result_data=$con->query($sql_data);
        $results=array();
    filename = "Webinfopen.xls"; // File Name
    // Download file
    header("Content-Disposition: attachment; filename=\"$filename\"");
    header("Content-Type: application/vnd.ms-excel");

    $flag = false;
    while ($row = mysqli_fetch_assoc($result_data)) {
        if (!$flag) {
            // display field/column names as first row
            echo implode("\t", array_keys($row)) . "\r\n";
            $flag = true;
        }
        echo implode("\t", array_values($row)) . "\r\n";
    }
    ?>

How to check if a column exists in a datatable

Base on accepted answer, I made an extension method to check column exist in table as

I shared for whom concern.

 public static class DatatableHelper
 {
        public static bool ContainColumn(this DataTable table, string columnName)
        {
            DataColumnCollection columns = table.Columns;
            if (columns.Contains(columnName))
            {
                return true;
            }

            return false;
        }
}

And use as dtTagData.ContainColumn("SystemName")

Android: How to get a custom View's height and width?

You can use the following method to get the width and height of the view, For example,

int height = yourView.getLayoutParams().height;
int width = yourView.getLayoutParams().width;

This gives the converted value of the view which specified in the XML layout.

Say if the specified value for height is 53dp in XML, you will get the converted value in integer as 80.

How to declare std::unique_ptr and what is the use of it?

Unique pointers are guaranteed to destroy the object they manage when they go out of scope. http://en.cppreference.com/w/cpp/memory/unique_ptr

In this case:

unique_ptr<double> uptr2 (pd);

pd will be destroyed when uptr2 goes out of scope. This facilitates memory management by automatic deletion.

The case of unique_ptr<int> uptr (new int(3)); is not different, except that the raw pointer is not assigned to any variable here.

How do I make a comment in a Dockerfile?

Dockerfile comments start with '#', just like Python. Here is a good example (kstaken/dockerfile-examples):

# Install a more-up-to date version of MongoDB than what is included in the default Ubuntu repositories.

FROM ubuntu
MAINTAINER Kimbro Staken

RUN apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10
RUN echo "deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen" | tee -a /etc/apt/sources.list.d/10gen.list
RUN apt-get update
RUN apt-get -y install apt-utils
RUN apt-get -y install mongodb-10gen

#RUN echo "" >> /etc/mongodb.conf

CMD ["/usr/bin/mongod", "--config", "/etc/mongodb.conf"] 

Checking for multiple conditions using "when" on single task in ansible

You can use like this.

when: condition1 == "condition1" or condition2 == "condition2"

Link to official docs: The When Statement.

Also Please refer to this gist: https://gist.github.com/marcusphi/6791404

Batch file script to zip files

I know its too late but if you still wanna try

for /d %%X in (*) do (for /d %%a in (%%X) do ( "C:\Program Files\7-Zip\7z.exe" a -tzip "%%X.zip" ".\%%a\" ))

here * is the current folder. for more options try this link

How can I make SQL case sensitive string comparison on MySQL?

Following is for MySQL versions equal to or higher than 5.5.

Add to /etc/mysql/my.cnf

  [mysqld]
  ...
  character-set-server=utf8
  collation-server=utf8_bin
  ...

All other collations I tried seemed to be case-insensitive, only "utf8_bin" worked.

Do not forget to restart mysql after this:

   sudo service mysql restart

According to http://dev.mysql.com/doc/refman/5.0/en/case-sensitivity.html there is also a "latin1_bin".

The "utf8_general_cs" was not accepted by mysql startup. (I read "_cs" as "case-sensitive" - ???).

How to check type of object in Python?

What type() means:

I think your question is a bit more general than I originally thought. type() with one argument returns the type or class of the object. So if you have a = 'abc' and use type(a) this returns str because the variable a is a string. If b = 10, type(b) returns int.

See also python documentation on type().


For comparisons:

If you want a comparison you could use: if type(v) == h5py.h5r.Reference (to check if it is a h5py.h5r.Reference instance).

But it is recommended that one uses if isinstance(v, h5py.h5r.Reference) but then also subclasses will evaluate to True.

If you want to print the class use print v.__class__.__name__.

More generally: You can compare if two instances have the same class by using type(v) is type(other_v) or isinstance(v, other_v.__class__).

When do I use the PHP constant "PHP_EOL"?

When jumi (joomla plugin for PHP) compiles your code for some reason it removes all backslashes from your code. Such that something like $csv_output .= "\n"; becomes $csv_output .= "n";

Very annoying bug!

Use PHP_EOL instead to get the result you were after.

What does 'killed' mean when a processing of a huge CSV with Python, which suddenly stops?

I just had the same happen on me when I tried to run a python script from a shared folder in VirtualBox within the new Ubuntu 20.04 LTS. Python bailed with Killed while loading my own personal library. When I moved the folder to a local directory, the issue went away. It appears that the Killed stop happened during the initial imports of my library as I got messages of missing libraries once I moved the folder over.

The issue went away after I restarted my computer.

Therefore, people may want to try moving the program to a local directory if its over a share of some kind or it could be a transient problem that just requires a reboot of the OS.

How to save LogCat contents to file?

You are not getting the answer you are looking for, are you.

Two ways to do what you want:

  1. Right-click in the logcat messages window, choose select all. Then your save will be all logcat messages in that window (including the ones scrolled out of view).
  2. When focus is in logcat messages window, type control-A, this will select all messages. Then save etc. etc.

Cannot change column used in a foreign key constraint

You can turn off foreign key checks:

SET FOREIGN_KEY_CHECKS = 0;

/* DO WHAT YOU NEED HERE */

SET FOREIGN_KEY_CHECKS = 1;

Please make sure to NOT use this on production and have a backup.

Turning off some legends in a ggplot

You can use guide=FALSE in scale_..._...() to suppress legend.

For your example you should use scale_colour_continuous() because length is continuous variable (not discrete).

(p3 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
   scale_colour_continuous(guide = FALSE) +
   geom_point()
)

Or using function guides() you should set FALSE for that element/aesthetic that you don't want to appear as legend, for example, fill, shape, colour.

p0 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
  geom_point()    
p0+guides(colour=FALSE)

UPDATE

Both provided solutions work in new ggplot2 version 2.0.0 but movies dataset is no longer present in this library. Instead you have to use new package ggplot2movies to check those solutions.

library(ggplot2movies)
data(movies)
mov <- subset(movies, length != "")

Android ListView with Checkbox and all clickable

this code works on my proyect and i can select the listview item and checkbox

<?xml version="1.0" encoding="utf-8"?>
<!-- Single List Item Design -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:clickable="true" >

    <TextView
        android:id="@+id/label"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="4" />

    <CheckBox
        android:id="@+id/check"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:focusable="false"
        android:text="" >
    </CheckBox>

</LinearLayout>

How to check whether a Storage item is set?

You should check for the type of the item in the localStorage

if(localStorage.token !== null) {
   // this will only work if the token is set in the localStorage
}

if(typeof localStorage.token !== 'undefined') {
  // do something with token
}

if(typeof localStorage.token === 'undefined') {
  // token doesn't exist in the localStorage, maybe set it?
}

MessageBodyWriter not found for media type=application/json

To overcome this issue try the following. Worked for me.

Add following dependency in the pom.xml

<dependency>
  <groupId>org.glassfish.jersey.media</groupId>
  <artifactId>jersey-media-json-jackson</artifactId>
  <version>2.25</version>
</dependency>

And make sure Model class contains no arg constructor

 public Student()
    {
    }

.aspx vs .ashx MAIN difference

.aspx uses a full lifecycle (Init, Load, PreRender) and can respond to button clicks etc.
An .ashx has just a single ProcessRequest method.

How can I access each element of a pair in a pair list?

Use tuple unpacking:

>>> pairs = [("a", 1), ("b", 2), ("c", 3)]
>>> for a, b in pairs:
...    print a, b
... 
a 1
b 2
c 3

See also: Tuple unpacking in for loops.

How to find the privileges and roles granted to a user in Oracle?

Combining the earlier suggestions to determine your personal permissions (ie 'USER' permissions), then use this:

-- your permissions
select * from USER_ROLE_PRIVS where USERNAME= USER;
select * from USER_TAB_PRIVS where Grantee = USER;
select * from USER_SYS_PRIVS where USERNAME = USER;

-- granted role permissions
select * from ROLE_ROLE_PRIVS where ROLE IN (select granted_role from USER_ROLE_PRIVS where USERNAME= USER);
select * from ROLE_TAB_PRIVS  where ROLE IN (select granted_role from USER_ROLE_PRIVS where USERNAME= USER);
select * from ROLE_SYS_PRIVS  where ROLE IN (select granted_role from USER_ROLE_PRIVS where USERNAME= USER);

VBA vlookup reference in different sheet

Your code work fine, provided the value in Sheet2!D2 exists in Sheet1!A:A. If it does not then error 1004 is raised.

To handle this case, try

Sub Demo()
    Dim MyStringVar1 As Variant
    On Error Resume Next
    MyStringVar1 = Application.WorksheetFunction.VLookup(Range("D2"), _
      Worksheets("Sheet1").Range("A:C"), 1, False)
    On Error GoTo 0
    If IsEmpty(MyStringVar1) Then
        MsgBox "Value not found!"
    End If

    Range("E2") = MyStringVar1

End Sub

pythonw.exe or python.exe?

If you're going to call a python script from some other process (say, from the command line), use pythonw.exe. Otherwise, your user will continuously see a cmd window launching the python process. It'll still run your script just the same, but it won't intrude on the user experience.

An example might be sending an email; python.exe will pop up a CLI window, send the email, then close the window. It'll appear as a quick flash, and can be considered somewhat annoying. pythonw.exe avoids this, but still sends the email.

How can I extract the folder path from file path in Python?

Anyone trying to do this in the ESRI GIS Table field calculator interface can do this with the Python parser:

PathToContainingFolder =

"\\".join(!FullFilePathWithFileName!.split("\\")[0:-1])

so that

\Users\me\Desktop\New folder\file.txt

becomes

\Users\me\Desktop\New folder

How to handle login pop up window using Selenium WebDriver?

Use the approach where you send username and password in URL Request:

http://username:[email protected]

So just to make it more clear. The username is username password is password and the rest is usual URL of your test web

Works for me without needing any tweaks.

Sample Java code:

public static final String TEST_ENVIRONMENT = "the-site.com";
private WebDriver driver;

public void login(String uname, String pwd){
  String URL = "http://" + uname + ":" + pwd + "@" + TEST_ENVIRONMENT;
  driver.get(URL);
}

@Test
public void testLogin(){
   driver = new FirefoxDriver();
   login("Pavel", "UltraSecretPassword");
   //Assert...
}

JavaScript - cannot set property of undefined

i'd just do a simple check to see if d[a] exists and if not initialize it...

var a = "1",
    b = "hello",
    c = { "100" : "some important data" },
    d = {};

    if (d[a] === undefined) {
        d[a] = {}
    };
    d[a]["greeting"] = b;
    d[a]["data"] = c;

    console.debug (d);

toBe(true) vs toBeTruthy() vs toBeTrue()

There are a lot many good answers out there, i just wanted to add a scenario where the usage of these expectations might be helpful. Using element.all(xxx), if i need to check if all elements are displayed at a single run, i can perform -

expect(element.all(xxx).isDisplayed()).toBeTruthy(); //Expectation passes
expect(element.all(xxx).isDisplayed()).toBe(true); //Expectation fails
expect(element.all(xxx).isDisplayed()).toBeTrue(); //Expectation fails

Reason being .all() returns an array of values and so all kinds of expectations(getText, isPresent, etc...) can be performed with toBeTruthy() when .all() comes into picture. Hope this helps.

to remove first and last element in array

You used Fruits.shift() method to first element remove . Fruits.pop() method used for last element remove one by one if you used button click. Fruits.slice( start position, delete element)You also used slice method for remove element in middle start.

XAMPP Start automatically on Windows 7 startup

You can put in this directory your Xampp control panel shortcut it will work fine (it will automatically start after windows startup) as @wajahat-hashmi answered above:

C:\Users\User-Name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

About aditional windows script or programs that we need to run automatically...

I needed to create some additional scripts to initialize some windows services. If someone has the same need you can put in that same directory, they will all run right after windows startup.

For me, Xampp auto start and other scripts and shortcuts worked fine in windows 8.1, I think it will work fine in any windows version.

I hope it works well for anyone who has the same need.

Get image data url in JavaScript?

Note: This only works if the image is from the same domain as the page, or has the crossOrigin="anonymous" attribute and the server supports CORS. It's also not going to give you the original file, but a re-encoded version. If you need the result to be identical to the original, see Kaiido's answer.


You will need to create a canvas element with the correct dimensions and copy the image data with the drawImage function. Then you can use the toDataURL function to get a data: url that has the base-64 encoded image. Note that the image must be fully loaded, or you'll just get back an empty (black, transparent) image.

It would be something like this. I've never written a Greasemonkey script, so you might need to adjust the code to run in that environment.

function getBase64Image(img) {
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    // Get the data-URL formatted image
    // Firefox supports PNG and JPEG. You could check img.src to
    // guess the original format, but be aware the using "image/jpg"
    // will re-encode the image.
    var dataURL = canvas.toDataURL("image/png");

    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

Getting a JPEG-formatted image doesn't work on older versions (around 3.5) of Firefox, so if you want to support that, you'll need to check the compatibility. If the encoding is not supported, it will default to "image/png".

MySQL pivot table query with dynamic columns

Here's stored procedure, which will generate the table based on data from one table and column and data from other table and column.

The function 'sum(if(col = value, 1,0)) as value ' is used. You can choose from different functions like MAX(if()) etc.

delimiter //

  create procedure myPivot(
    in tableA varchar(255),
    in columnA varchar(255),
    in tableB varchar(255),
    in columnB varchar(255)
)
begin
  set @sql = NULL;
    set @sql = CONCAT('select group_concat(distinct concat(
            \'SUM(IF(', 
        columnA, 
        ' = \'\'\',',
        columnA,
        ',\'\'\', 1, 0)) AS \'\'\',',
        columnA, 
            ',\'\'\'\') separator \', \') from ',
        tableA, ' into @sql');
    -- select @sql;

    PREPARE stmt FROM @sql;
    EXECUTE stmt;

    DEALLOCATE PREPARE stmt;
    -- select @sql;

    SET @sql = CONCAT('SELECT p.', 
        columnB, 
        ', ', 
        @sql, 
        ' FROM ', tableB, ' p GROUP BY p.',
        columnB,'');

    -- select @sql;

    /* */
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    /* */
    DEALLOCATE PREPARE stmt;
end//

delimiter ;

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

Solution 1:

Extract P12 from jks

keytool -importkeystore -srckeystore MyRootCA.jks -destkeystore MyRootCA.p12 -deststoretype PKCS12

Extract PEM from P12 and Edit file and pem from crt file

openssl pkcs12 -in MyRootCA.p12 -clcerts -nokeys -out MyRootCA.crt

Extract key from jks

openssl pkcs12 -in MyRootCA.p12 -nocerts -out encryptedPrivateKey.pem
openssl rsa -in encryptedPrivateKey.pem -out decryptedPrivateKey.key

Solution 2:

Extract PEM and encryptedPrivateKey to txt file```

openssl pkcs12 -in MyRootCA.p12 -out keys_out.txt

Decrypt privateKey

openssl rsa -in encryptedPrivateKey.key [-outform PEM] -out decryptedPrivateKey.key

"pip install unroll": "python setup.py egg_info" failed with error code 1

I faced the same problem with the same error message but on Ubuntu 16.04 LTS (Xenial Xerus) instead:

Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-w71uo1rg/poster/

I tested all the solutions provided above and none of them worked for me. I read the full TraceBack and found out I had to create the virtual environment with Python version 2.7 instead (the default one uses Python 3.5 instead):

virtualenv --python=/usr/bin/python2.7 my_venv

Once I activated it, I run pip install unirest successfully.

Windows equivalent to UNIX pwd

cd without any parameters is equivalent to pwd on Unix/Linux.

From the console output of typing cd /?:

Displays the name of or changes the current directory.

[...]

Type CD without parameters to display the current drive and directory.

Headers and client library minor version mismatch

The same works for MySQL:

sudo apt-get install php5-mysqlnd

I've read this thread trying to find the solution for MySQL, and I've also seen ken's answer, but I ignored the solution for MariaDB, wasting a few hours that way. It wasn't clear for me that the same may apply to MySQL. This post is just to spare you the few hours I lost.

How to format a float in javascript?

There are functions to round numbers. For example:

var x = 5.0364342423;
print(x.toFixed(2));

will print 5.04.

EDIT: Fiddle

Changing precision of numeric column in Oracle

By setting the scale, you decrease the precision. Try NUMBER(16,2).

How to determine programmatically the current active profile using Spring boot

It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment to your bean.

@Autowired
private Environment environment;
....

this.environment.getActiveProfiles();

How to listen for 'props' changes

The watch function should place in Child component. Not parent.

How to format font style and color in echo

foreach($months as $key => $month){
  if(strpos($filename,$month)!==false){
        echo "<div style ='font:11px/21px Arial,tahoma,sans-serif;color:#ff0000'> Movie List for $key 2013</div>";
    }
}

Check if $_POST exists

The proper way of checking if array key exists is function array_key_exists()

The difference is that when you have $_POST['variable'] = null it means that key exists and was send but value was null

The other option is isset() which which will check if array key exists and if it was set

The last option is to use empty() which will check if array key exists if is set and if value is not considered empty.

Examples:

$arr = [
  'a' => null,
  'b' => '',
  'c' => 1
];

array_key_exists('a', $arr); // true
isset($arr['a']); // false
empty($arr['a']); // true


array_key_exists('b', $arr); // true
isset($arr['b']); // true
empty($arr['b']); // true


array_key_exists('c', $arr); // true
isset($arr['c']); // true
empty($arr['c']); // false

Regarding your question

The proper way to check if value was send is to use array_key_exists() with check of request method

if ($_SERVER['REQUEST_METHOD'] == 'POST' && array_key_exists('fromPerson', $_POST)    
{
   // logic
}

But there are some cases depends on your logic where isset() and empty() can be good as well.

How to request Google to re-crawl my website?

There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:

  1. Go to: https://www.google.com/webmasters/tools/ and log in
  2. If you haven't already, add and verify the site with the "Add a Site" button
  3. Click on the site name for the one you want to manage
  4. Click Crawl -> Fetch as Google
  5. Optional: if you want to do a specific page only, type in the URL
  6. Click Fetch
  7. Click Submit to Index
  8. Select either "URL" or "URL and its direct links"
  9. Click OK and you're done.

With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.

Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/

Update 2019:

  1. Login to - Google Search Console
  2. Add a site and verify it with the available methods.
  3. After verification from the console, click on URL Inspection.
  4. In the Search bar on top, enter your website URL or custom URLs for inspection and enter.
  5. After Inspection, it'll show an option to Request Indexing
  6. Click on it and GoogleBot will add your website in a Queue for crawling.

How to create a Date in SQL Server given the Day, Month and Year as Integers

select convert(varchar(11), transfer_date, 106)

got me my desired result of date formatted as 07 Mar 2018

My column 'transfer_date' is a datetime type column and I am using SQL Server 2017 on azure

Change Default branch in gitlab

In the latest GitLab Community Edition version 9.2.2.:

  1. You have to click on 'Settings' tab located at right most on tabs panel after opening the project.
  2. Under 'Settings' you will get section 'Default Branch' dropdown which will give you all branches for the repository. Select the desired branch.
  3. Scroll down to hit green colored 'Save changes' button located just after 'Project Avatar'.

Please refer image below:

enter image description here

How to create checkbox inside dropdown?

Simply use bootstrap-multiselect where you can populate dropdown with multiselect option and many more feaatures.

For doc and tutorials you may visit below link

https://www.npmjs.com/package/bootstrap-multiselect

http://davidstutz.de/bootstrap-multiselect/

How to do IF NOT EXISTS in SQLite

If you want to ignore the insertion of existing value, there must be a Key field in your Table. Just create a table With Primary Key Field Like:

CREATE TABLE IF NOT EXISTS TblUsers (UserId INTEGER PRIMARY KEY, UserName varchar(100), ContactName varchar(100),Password varchar(100));

And Then Insert Or Replace / Insert Or Ignore Query on the Table Like:

INSERT OR REPLACE INTO TblUsers (UserId, UserName, ContactName ,Password) VALUES('1','UserName','ContactName','Password');

It Will Not Let it Re-Enter The Existing Primary key Value... This Is how you can Check Whether a Value exists in the table or not.

How to read a Parquet file into Pandas DataFrame?

pandas 0.21 introduces new functions for Parquet:

pd.read_parquet('example_pa.parquet', engine='pyarrow')

or

pd.read_parquet('example_fp.parquet', engine='fastparquet')

The above link explains:

These engines are very similar and should read/write nearly identical parquet format files. These libraries differ by having different underlying dependencies (fastparquet by using numba, while pyarrow uses a c-library).

iOS 7 UIBarButton back button arrow color

You have to set the tintColor of the entire app.

self.window.tintColor = [UIColor redColor];

Or in Swift 3:

self.window?.tintColor = UIColor.blue

Source: iOS 7 UI Transition Guide

Why do I need 'b' to encode a string with Base64?

If the data to be encoded contains "exotic" characters, I think you have to encode in "UTF-8"

encoded = base64.b64encode (bytes('data to be encoded', "utf-8"))

How to deal with bad_alloc in C++?

You can catch it like any other exception:

try {
  foo();
}
catch (const std::bad_alloc&) {
  return -1;
}

Quite what you can usefully do from this point is up to you, but it's definitely feasible technically.



In general you cannot, and should not try, to respond to this error. bad_alloc indicates that a resource cannot be allocated because not enough memory is available. In most scenarios your program cannot hope to cope with that, and terminating soon is the only meaningful behaviour.

Worse, modern operating systems often over-allocate: on such systems, malloc and new can return a valid pointer even if there is not enough free memory left – std::bad_alloc will never be thrown, or is at least not a reliable sign of memory exhaustion. Instead, attempts to access the allocated memory will then result in a segmentation fault, which is not catchable (you can handle the segmentation fault signal, but you cannot resume the program afterwards).

The only thing you could do when catching std::bad_alloc is to perhaps log the error, and try to ensure a safe program termination by freeing outstanding resources (but this is done automatically in the normal course of stack unwinding after the error gets thrown if the program uses RAII appropriately).

In certain cases, the program may attempt to free some memory and try again, or use secondary memory (= disk) instead of RAM but these opportunities only exist in very specific scenarios with strict conditions:

  1. The application must ensure that it runs on a system that does not overcommit memory, i.e. it signals failure upon allocation rather than later.
  2. The application must be able to free memory immediately, without any further accidental allocations in the meantime.

It’s exceedingly rare that applications have control over point 1 — userspace applications never do, it’s a system-wide setting that requires root permissions to change.1

OK, so let’s assume you’ve fixed point 1. What you can now do is for instance use a LRU cache for some of your data (probably some particularly large business objects that can be regenerated or reloaded on demand). Next, you need to put the actual logic that may fail into a function that supports retry — in other words, if it gets aborted, you can just relaunch it:

lru_cache<widget> widget_cache;

double perform_operation(int widget_id) {
    std::optional<widget> maybe_widget = widget_cache.find_by_id(widget_id);
    if (not maybe_widget) {
        maybe_widget = widget_cache.store(widget_id, load_widget_from_disk(widget_id));
    }
    return maybe_widget->frobnicate();
}

…

for (int num_attempts = 0; num_attempts < MAX_NUM_ATTEMPTS; ++num_attempts) {
    try {
        return perform_operation(widget_id);
    } catch (std::bad_alloc const&) {
        if (widget_cache.empty()) throw; // memory error elsewhere.
        widget_cache.remove_oldest();
    }
}

// Handle too many failed attempts here.

But even here, using std::set_new_handler instead of handling std::bad_alloc provides the same benefit and would be much simpler.


1 If you’re creating an application that does control point 1, and you’re reading this answer, please shoot me an email, I’m genuinely curious about your circumstances.


What is the C++ Standard specified behavior of new in c++?

The usual notion is that if new operator cannot allocate dynamic memory of the requested size, then it should throw an exception of type std::bad_alloc.
However, something more happens even before a bad_alloc exception is thrown:

C++03 Section 3.7.4.1.3: says

An allocation function that fails to allocate storage can invoke the currently installed new_handler(18.4.2.2), if any. [Note: A program-supplied allocation function can obtain the address of the currently installed new_handler using the set_new_handler function (18.4.2.3).] If an allocation function declared with an empty exception-specification (15.4), throw(), fails to allocate storage, it shall return a null pointer. Any other allocation function that fails to allocate storage shall only indicate failure by throw-ing an exception of class std::bad_alloc (18.4.2.1) or a class derived from std::bad_alloc.

Consider the following code sample:

#include <iostream>
#include <cstdlib>

// function to call if operator new can't allocate enough memory or error arises
void outOfMemHandler()
{
    std::cerr << "Unable to satisfy request for memory\n";

    std::abort();
}

int main()
{
    //set the new_handler
    std::set_new_handler(outOfMemHandler);

    //Request huge memory size, that will cause ::operator new to fail
    int *pBigDataArray = new int[100000000L];

    return 0;
}

In the above example, operator new (most likely) will be unable to allocate space for 100,000,000 integers, and the function outOfMemHandler() will be called, and the program will abort after issuing an error message.

As seen here the default behavior of new operator when unable to fulfill a memory request, is to call the new-handler function repeatedly until it can find enough memory or there is no more new handlers. In the above example, unless we call std::abort(), outOfMemHandler() would be called repeatedly. Therefore, the handler should either ensure that the next allocation succeeds, or register another handler, or register no handler, or not return (i.e. terminate the program). If there is no new handler and the allocation fails, the operator will throw an exception.

What is the new_handler and set_new_handler?

new_handler is a typedef for a pointer to a function that takes and returns nothing, and set_new_handler is a function that takes and returns a new_handler.

Something like:

typedef void (*new_handler)();
new_handler set_new_handler(new_handler p) throw();

set_new_handler's parameter is a pointer to the function operator new should call if it can't allocate the requested memory. Its return value is a pointer to the previously registered handler function, or null if there was no previous handler.

How to handle out of memory conditions in C++?

Given the behavior of newa well designed user program should handle out of memory conditions by providing a proper new_handlerwhich does one of the following:

Make more memory available: This may allow the next memory allocation attempt inside operator new's loop to succeed. One way to implement this is to allocate a large block of memory at program start-up, then release it for use in the program the first time the new-handler is invoked.

Install a different new-handler: If the current new-handler can't make any more memory available, and of there is another new-handler that can, then the current new-handler can install the other new-handler in its place (by calling set_new_handler). The next time operator new calls the new-handler function, it will get the one most recently installed.

(A variation on this theme is for a new-handler to modify its own behavior, so the next time it's invoked, it does something different. One way to achieve this is to have the new-handler modify static, namespace-specific, or global data that affects the new-handler's behavior.)

Uninstall the new-handler: This is done by passing a null pointer to set_new_handler. With no new-handler installed, operator new will throw an exception ((convertible to) std::bad_alloc) when memory allocation is unsuccessful.

Throw an exception convertible to std::bad_alloc. Such exceptions are not be caught by operator new, but will propagate to the site originating the request for memory.

Not return: By calling abort or exit.

How to use ADB to send touch events to device using sendevent command?

In order to do a particular action (for example to open the web browser), you need to first figure out where to tap. To do that, you can first run:

adb shell getevent -l

Once you press on the device, at the location that you want, you will see this output:

<...>
/dev/input/event3: EV_KEY       BTN_TOUCH            DOWN
/dev/input/event3: EV_ABS       ABS_MT_POSITION_X    000002f5
/dev/input/event3: EV_ABS       ABS_MT_POSITION_Y    0000069e

adb is telling you that a key was pressed (button down) at position 2f5, 69e in hex which is 757 and 1694 in decimal.

If you now want to generate the same event, you can use the input tap command at the same position:

adb shell input tap 757 1694

More info can be found at:

https://source.android.com/devices/input/touch-devices.html http://source.android.com/devices/input/getevent.html

Passing multiple parameters to pool.map() function in Python

You could use a map function that allows multiple arguments, as does the fork of multiprocessing found in pathos.

>>> from pathos.multiprocessing import ProcessingPool as Pool
>>> 
>>> def add_and_subtract(x,y):
...   return x+y, x-y
... 
>>> res = Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))
>>> res
[(-5, 5), (-2, 6), (1, 7), (4, 8), (7, 9), (10, 10), (13, 11), (16, 12), (19, 13), (22, 14)]
>>> Pool().map(add_and_subtract, *zip(*res))
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

pathos enables you to easily nest hierarchical parallel maps with multiple inputs, so we can extend our example to demonstrate that.

>>> from pathos.multiprocessing import ThreadingPool as TPool
>>> 
>>> res = TPool().amap(add_and_subtract, *zip(*Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))))
>>> res.get()
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

Even more fun, is to build a nested function that we can pass into the Pool. This is possible because pathos uses dill, which can serialize almost anything in python.

>>> def build_fun_things(f, g):
...   def do_fun_things(x, y):
...     return f(x,y), g(x,y)
...   return do_fun_things
... 
>>> def add(x,y):
...   return x+y
... 
>>> def sub(x,y):
...   return x-y
... 
>>> neato = build_fun_things(add, sub)
>>> 
>>> res = TPool().imap(neato, *zip(*Pool().map(neato, range(0,20,2), range(-5,5,1))))
>>> list(res)
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

If you are not able to go outside of the standard library, however, you will have to do this another way. Your best bet in that case is to use multiprocessing.starmap as seen here: Python multiprocessing pool.map for multiple arguments (noted by @Roberto in the comments on the OP's post)

Get pathos here: https://github.com/uqfoundation

How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte"

Finally I got it:

as3:/usr/local/lib/python2.7/site-packages# cat sitecustomize.py
# encoding=utf8  
import sys  

reload(sys)  
sys.setdefaultencoding('utf8')

Let me check:

as3:~/ngokevin-site# python
Python 2.7.6 (default, Dec  6 2013, 14:49:02)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> reload(sys)
<module 'sys' (built-in)>
>>> sys.getdefaultencoding()
'utf8'
>>>

The above shows the default encoding of python is utf8. Then the error is no more.

How can I change from SQL Server Windows mode to mixed mode (SQL Server 2008)?

  1. Open up SQL Server Management Studio and connect to your database server.
  2. Right Click The Database Server and click Properties.
  3. Set the Server Authentication to SQL Server and Windows Authentication Mode.

Select mysql query between date?

You can use now() like:

Select data from tablename where datetime >= "01-01-2009 00:00:00" and datetime <= now();

What is the MySQL JDBC driver connection string?

It is very simple :

  1. Go to MySQL workbench and lookup for Database > Manage Connections
  2. you will see a list of connections. Click on the connection you wish to connect to.
  3. You will see a tabs around connection, remote management, system profile. Click on connection tab.
  4. your url is jdbc:mysql://<hostname>:<port>/<dbname>?prop1 etc. where <hostname> and <port> are given in the connection tab.It will mostly be localhost : 3306. <dbname> will be found under System Profile tab in Windows Service Name. Default will mostly be MySQL5<x> where x is the version number eg. 56 for MySQL5.6 and 55 for MySQL5.5 etc.You can specify ur own Windows Service name to connect too.
  5. Construct the url accordingly and set the url to connect.

Check if value exists in the array (AngularJS)

You can use indexOf(). Like:

var Color = ["blue", "black", "brown", "gold"];
var a = Color.indexOf("brown");
alert(a);

The indexOf() method searches the array for the specified item, and returns its position. And return -1 if the item is not found.


If you want to search from end to start, use the lastIndexOf() method:

    var Color = ["blue", "black", "brown", "gold"];
    var a = Color.lastIndexOf("brown");
    alert(a);

The search will start at the specified position, or at the end if no start position is specified, and end the search at the beginning of the array.

Returns -1 if the item is not found.

How best to determine if an argument is not sent to the JavaScript function

There are significant differences. Let's set up some test cases:

var unused; // value will be undefined
Test("test1", "some value");
Test("test2");
Test("test3", unused);
Test("test4", null);
Test("test5", 0);
Test("test6", "");

With the first method you describe, only the second test will use the default value. The second method will default all but the first (as JS will convert undefined, null, 0, and "" into the boolean false. And if you were to use Tom's method, only the fourth test will use the default!

Which method you choose really depends on your intended behavior. If values other than undefined are allowable for argument2, then you'll probably want some variation on the first; if a non-zero, non-null, non-empty value is desired, then the second method is ideal - indeed, it is often used to quickly eliminate such a wide range of values from consideration.

Why is Visual Studio 2010 not able to find/open PDB files?

I had the same problem. Debugging does not work with the stuff that comes with the OpenCV executable. you have to build your own binarys.
Then enable Microsoft Symbol Servers in Debug->options and settings->debug->symbols

What is the equivalent of Java static methods in Kotlin?

There are 2 ways you can apply static in Kotlin

First make a companion object under class

For ex:

class Test{
    companion object{
          fun isCheck(a:Int):Boolean{
             if(a==0) true else false
          }
     }
}

you can call this function as

Test.Companion.isCheck(2)

Another way we can use is to make an object class

object Test{
       fun isCheck(a:Int):Boolean{
            if(a==0) true else false
       }
}

Happy Coding!

How to reset / remove chrome's input highlighting / focus border?

You should be able to remove it using

outline: none;

but keep in mind this is potentially bad for usability: It will be hard to tell whether an element is focused, which can suck when you walk through all a form's elements using the Tab key - you should reflect somehow when an element is focused.

How to get the Mongo database specified in connection string in C#

With version 1.7 of the official 10gen driver, this is the current (non-obsolete) API:

const string uri = "mongodb://localhost/mydb";
var client = new MongoClient(uri);
var db = client.GetServer().GetDatabase(new MongoUrl(uri).DatabaseName);
var collection = db.GetCollection("mycollection");

How to specify line breaks in a multi-line flexbox layout?

I just want to throw this answer in the mix, intended as a reminder that – given the right conditions – you sometimes don't need to overthink the issue at hand. What you want might be achievable with flex: wrap and max-width instead of :nth-child.

_x000D_
_x000D_
ul {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  max-width: 420px;
  list-style-type: none;
  background-color: tomato;
  margin: 0 auto;
  padding: 0;
}

li {
  display: inline-block;
  background-color: #ccc;
  border: 1px solid #333;
  width: 23px;
  height: 23px;
  text-align: center;
  font-size: 1rem;
  line-height: 1.5;
  margin: 0.2rem;
  flex-shrink: 0;
}
_x000D_
<div class="root">
  <ul>
    <li>A</li>
    <li>B</li>
    <li>C</li>
    <li>D</li>
    <li>E</li>
    <li>F</li>
    <li>G</li>
    <li>H</li>
    <li>I</li>
    <li>J</li>
    <li>K</li>
    <li>L</li>
    <li>M</li>
    <li>N</li>
    <li>O</li>
    <li>P</li>
    <li>Q</li>
    <li>R</li>
    <li>S</li>
    <li>T</li>
    <li>U</li>
    <li>V</li>
    <li>W</li>
    <li>X</li>
    <li>Y</li>
    <li>Z</li>
  </ul>
</div>
_x000D_
_x000D_
_x000D_

https://jsfiddle.net/age3qp4d/

How to delete and update a record in Hive

Once you have installed and configured Hive , create simple table :

hive>create table testTable(id int,name string)row format delimited fields terminated by ',';

Then, try to insert few rowsin test table.

hive>insert into table testTable values (1,'row1'),(2,'row2');

Now try to delete records , you just inserted in table.

hive>delete from testTable where id = 1;

Error! FAILED: SemanticException [Error 10294]: Attempt to do update or delete using transaction manager that does not support these operations.

By default transactions are configured to be off. It is been said that update is not supported with the delete operation used in the conversion manager. To support update/delete , you must change following configuration.

cd  $HIVE_HOME
vi conf/hive-site.xml

Add below properties to file

<property>
  <name>hive.support.concurrency</name>
  <value>true</value>
 </property>
 <property>
  <name>hive.enforce.bucketing</name>
  <value>true</value>
 </property>
 <property>
  <name>hive.exec.dynamic.partition.mode</name>
  <value>nonstrict</value>
 </property>
 <property>
  <name>hive.txn.manager</name>
  <value>org.apache.hadoop.hive.ql.lockmgr.DbTxnManager</value>
 </property>
 <property>
  <name>hive.compactor.initiator.on</name>
  <value>true</value>
 </property>
 <property>
  <name>hive.compactor.worker.threads</name>
  <value>2</value>
 </property>

Restart the service and then try delete command again :

Error!

FAILED: LockException [Error 10280]: Error communicating with the metastore.

There is problem with metastore. In order to use insert/update/delete operation, You need to change following configuration in conf/hive-site.xml as feature is currently in development.

<property>
  <name>hive.in.test</name>
  <value>true</value>
 </property>

Restart the service and then delete command again :

hive>delete from testTable where id = 1;

Error!

FAILED: SemanticException [Error 10297]: Attempt to do update or delete on table default.testTable that does not use an AcidOutputFormat or is not bucketed.

Only ORC file format is supported in this first release. The feature has been built such that transactions can be used by any storage format that can determine how updates or deletes apply to base records (basically, that has an explicit or implicit row id), but so far the integration work has only been done for ORC.

Tables must be bucketed to make use of these features. Tables in the same system not using transactions and ACID do not need to be bucketed.

See below built table example with ORCFileformat, bucket enabled and ('transactional'='true').

hive>create table testTableNew(id int ,name string ) clustered by (id) into 2 buckets stored as orc TBLPROPERTIES('transactional'='true');

Insert :

hive>insert into table testTableNew values (1,'row1'),(2,'row2'),(3,'row3');

Update :

hive>update testTableNew set name = 'updateRow2' where id = 2;

Delete :

hive>delete from testTableNew where id = 1;

Test :

hive>select * from testTableNew ;

how to remove untracked files in Git?

For deleting untracked files:

git clean -f

For deleting untracked directories as well, use:

git clean -f -d

For preventing any cardiac arrest, use

git clean -n -f -d

JQuery string contains check

You can use javascript's indexOf function.

_x000D_
_x000D_
var str1 = "ABCDEFGHIJKLMNOP";_x000D_
var str2 = "DEFG";_x000D_
if(str1.indexOf(str2) != -1){_x000D_
    console.log(str2 + " found");_x000D_
}
_x000D_
_x000D_
_x000D_

Scanf/Printf double variable C

When a float is passed to printf, it is automatically converted to a double. This is part of the default argument promotions, which apply to functions that have a variable parameter list (containing ...), largely for historical reasons. Therefore, the “natural” specifier for a float, %f, must work with a double argument. So the %f and %lf specifiers for printf are the same; they both take a double value.

When scanf is called, pointers are passed, not direct values. A pointer to float is not converted to a pointer to double (this could not work since the pointed-to object cannot change when you change the pointer type). So, for scanf, the argument for %f must be a pointer to float, and the argument for %lf must be a pointer to double.

Http Get using Android HttpURLConnection

I have created with callBack(delegate) response to Activity class.

public class WebService extends AsyncTask<String, Void, String> {

    private Context mContext;
    private OnTaskDoneListener onTaskDoneListener;
    private String urlStr = "";

    public WebService(Context context, String url, OnTaskDoneListener onTaskDoneListener) {
        this.mContext = context;
        this.urlStr = url;
        this.onTaskDoneListener = onTaskDoneListener;
    }

    @Override
    protected String doInBackground(String... params) {
        try {

            URL mUrl = new URL(urlStr);
            HttpURLConnection httpConnection = (HttpURLConnection) mUrl.openConnection();
            httpConnection.setRequestMethod("GET");
            httpConnection.setRequestProperty("Content-length", "0");
            httpConnection.setUseCaches(false);
            httpConnection.setAllowUserInteraction(false);
            httpConnection.setConnectTimeout(100000);
            httpConnection.setReadTimeout(100000);

            httpConnection.connect();

            int responseCode = httpConnection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                br.close();
                return sb.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        if (onTaskDoneListener != null && s != null) {
            onTaskDoneListener.onTaskDone(s);
        } else
            onTaskDoneListener.onError();
    }
}

where

public interface OnTaskDoneListener {
    void onTaskDone(String responseData);

    void onError();
}

You can modify according to your needs. It's for get

add onclick function to a submit button

  1. Create a hidden button with id="hiddenBtn" and type="submit" that do the submit
  2. Change current button to type="button"
  3. set onclick of the current button call a function look like below:

    function foo() { // do something before submit ... // trigger click event of the hidden button $('#hinddenBtn').trigger("click"); }

Git Bash doesn't see my PATH

I've run into a stupid mistake on my part. I had a systems wide and a user variable path set for my golang workspace on my windows 10 machine. When I removed the redundant systems variable pathway and logged off and back on, I was able to call .exe files in bash and call go env with success.

Although OP has been answered this is another problem that could keep bash from seeing your pathways. I just tested bash again with this problem and it does seem to give a conflict of some sort that blocks bash from following either of the paths.

How to drop all tables in a SQL Server database?

Spot on!!

You can use below query to remove all the tables from database

EXEC sp_MSforeachtable @command1 = "DROP TABLE ?"

Happy coding !

How to Decrease Image Brightness in CSS

If you have a background-image, you can do this : Set a rgba() gradient on the background-image.

_x000D_
_x000D_
.img_container {_x000D_
  float: left;_x000D_
  width: 300px;_x000D_
  height: 300px;_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
  border : 1px solid #fff;_x000D_
}_x000D_
_x000D_
.image_original {_x000D_
  background: url(https://i.ibb.co/GkDXWYW/demo-img.jpg);_x000D_
}_x000D_
_x000D_
.image_brighness {_x000D_
  background: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), /* the gradient on top, adjust color and opacity to your taste */_x000D_
  url(https://i.ibb.co/GkDXWYW/demo-img.jpg);_x000D_
}_x000D_
_x000D_
.img_container p {_x000D_
  color: #fff;_x000D_
  font-size: 28px;_x000D_
}
_x000D_
<div class="img_container image_original">_x000D_
  <p>normal</p>_x000D_
</div>_x000D_
<div class="img_container image_brighness ">_x000D_
  <p>less brightness</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Hosting a Maven repository on github

Another alternative is to use any web hosting with webdav support. You will need some space for this somewhere of course but it is straightforward to set up and a good alternative to running a full blown nexus server.

add this to your build section

     <extensions>
        <extension>
        <artifactId>wagon-webdav-jackrabbit</artifactId>
        <groupId>org.apache.maven.wagon</groupId>
        <version>2.2</version>
        </extension>
    </extensions>

Add something like this to your distributionManagement section

<repository>
    <id>release.repo</id>
    <url>dav:http://repo.jillesvangurp.com/releases/</url>
</repository>

Finally make sure to setup the repository access in your settings.xml

add this to your servers section

    <server>
        <id>release.repo</id>
        <username>xxxx</username>
        <password>xxxx</password>
    </server>

and a definition to your repositories section

            <repository>
                <id>release.repo</id>
                <url>http://repo.jillesvangurp.com/releases</url>
                <releases>
                    <enabled>true</enabled>
                </releases>
                <snapshots>
                    <enabled>false</enabled>
                </snapshots>
            </repository>

Finally, if you have any standard php hosting, you can use something like sabredav to add webdav capabilities.

Advantages: you have your own maven repository Downsides: you don't have any of the management capabilities in nexus; you need some webdav setup somewhere

How to rotate a 3D object on axis three.js?

In Three.js R66, this is what I use (CoffeeScript version):

THREE.Object3D.prototype.rotateAroundWorldAxis = (axis, radians) ->
  rotWorldMatrix = new THREE.Matrix4()
  rotWorldMatrix.makeRotationAxis axis.normalize(), radians
  rotWorldMatrix.multiply this.matrix
  this.matrix = rotWorldMatrix
  this.rotation.setFromRotationMatrix this.matrix

How to send email via Django?

For Django version 1.7, if above solutions dont work then try the following

in settings.py add

#For email
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

EMAIL_USE_TLS = True

EMAIL_HOST = 'smtp.gmail.com'

EMAIL_HOST_USER = '[email protected]'

#Must generate specific password for your app in [gmail settings][1]
EMAIL_HOST_PASSWORD = 'app_specific_password'

EMAIL_PORT = 587

#This did the trick
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

The last line did the trick for django 1.7

How to exit when back button is pressed?

To exit from an Android app, just simply use. in your Main Activity, or you can use Android manifest file to set

android:noHistory="true"

How to add a constant column in a Spark DataFrame?

As the other answers have described, lit and typedLit are how to add constant columns to DataFrames. lit is an important Spark function that you will use frequently, but not for adding constant columns to DataFrames.

You'll commonly be using lit to create org.apache.spark.sql.Column objects because that's the column type required by most of the org.apache.spark.sql.functions.

Suppose you have a DataFrame with a some_date DateType column and would like to add a column with the days between December 31, 2020 and some_date.

Here's your DataFrame:

+----------+
| some_date|
+----------+
|2020-09-23|
|2020-01-05|
|2020-04-12|
+----------+

Here's how to calculate the days till the year end:

val diff = datediff(lit(Date.valueOf("2020-12-31")), col("some_date"))
df
  .withColumn("days_till_yearend", diff)
  .show()
+----------+-----------------+
| some_date|days_till_yearend|
+----------+-----------------+
|2020-09-23|               99|
|2020-01-05|              361|
|2020-04-12|              263|
+----------+-----------------+

You could also use lit to create a year_end column and compute the days_till_yearend like so:

import java.sql.Date

df
  .withColumn("yearend", lit(Date.valueOf("2020-12-31")))
  .withColumn("days_till_yearend", datediff(col("yearend"), col("some_date")))
  .show()
+----------+----------+-----------------+
| some_date|   yearend|days_till_yearend|
+----------+----------+-----------------+
|2020-09-23|2020-12-31|               99|
|2020-01-05|2020-12-31|              361|
|2020-04-12|2020-12-31|              263|
+----------+----------+-----------------+

Most of the time, you don't need to use lit to append a constant column to a DataFrame. You just need to use lit to convert a Scala type to a org.apache.spark.sql.Column object because that's what's required by the function.

See the datediff function signature:

enter image description here

As you can see, datediff requires two Column arguments.

Find the 2nd largest element in an array with minimum number of comparisons

try this.

max1 = a[0].
max2.
for i = 0, until length:
  if a[i] > max:
     max2 = max1.
     max1 = a[i].
     #end IF
  #end FOR
return min2.

it should work like a charm. low in complexity.

here is a java code.

int secondlLargestValue(int[] secondMax){
int max1 = secondMax[0]; // assign the first element of the array, no matter what, sorted or not.
int max2 = 0; // anything really work, but zero is just fundamental.
   for(int n = 0; n < secondMax.length; n++){ // start at zero, end when larger than length, grow by 1. 
        if(secondMax[n] > max1){ // nth element of the array is larger than max1, if so.
           max2 = max1; // largest in now second largest,
           max1 = secondMax[n]; // and this nth element is now max.
        }//end IF
    }//end FOR
    return max2;
}//end secondLargestValue()

How to find unused/dead code in java projects

An Eclipse plugin that works reasonably well is Unused Code Detector.

It processes an entire project, or a specific file and shows various unused/dead code methods, as well as suggesting visibility changes (i.e. a public method that could be protected or private).

Reading JSON POST using PHP

you can put your json in a parameter and send it instead of put only your json in header:

$post_string= 'json_param=' . json_encode($data);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $post_string);
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/');  // Set the url path we want to call

//execute post
$result = curl_exec($curl);

//see the results
$json=json_decode($result,true);
curl_close($curl);
print_r($json);

on the service side you can get your json string as a parameter:

$json_string = $_POST['json_param'];
$obj = json_decode($json_string);

then you can use your converted data as object.

How to add results of two select commands in same query

UNION ALL once, aggregate once:

SELECT sum(hours) AS total_hours
FROM   (
   SELECT hours FROM resource
   UNION ALL
   SELECT hours FROM "projects-time" -- illegal name without quotes in most RDBMS
   ) x

How do I pass a variable by reference?

Effbot (aka Fredrik Lundh) has described Python's variable passing style as call-by-object: http://effbot.org/zone/call-by-object.htm

Objects are allocated on the heap and pointers to them can be passed around anywhere.

  • When you make an assignment such as x = 1000, a dictionary entry is created that maps the string "x" in the current namespace to a pointer to the integer object containing one thousand.

  • When you update "x" with x = 2000, a new integer object is created and the dictionary is updated to point at the new object. The old one thousand object is unchanged (and may or may not be alive depending on whether anything else refers to the object).

  • When you do a new assignment such as y = x, a new dictionary entry "y" is created that points to the same object as the entry for "x".

  • Objects like strings and integers are immutable. This simply means that there are no methods that can change the object after it has been created. For example, once the integer object one-thousand is created, it will never change. Math is done by creating new integer objects.

  • Objects like lists are mutable. This means that the contents of the object can be changed by anything pointing to the object. For example, x = []; y = x; x.append(10); print y will print [10]. The empty list was created. Both "x" and "y" point to the same list. The append method mutates (updates) the list object (like adding a record to a database) and the result is visible to both "x" and "y" (just as a database update would be visible to every connection to that database).

Hope that clarifies the issue for you.

position fixed is not working

you need to give width explicitly to header and footer

width: 100%;

Working fiddle

If you want the middle section not to be hidden then give position: absolute;width: 100%; and set top and bottom properties (related to header and footer heights) to it and give parent element position: relative. (ofcourse, remove height: 700px;.) and to make it scrollable, give overflow: auto.

How we can bold only the name in table td tag not the value

I would use to table header tag below for a text in a table to make it standout from the rest of the table content.

 <table>

    <tr>
     <th>Dimension:</th>
    <td>98cm x 71cm</td>
    </tr>
   </table

Show a leading zero if a number is less than 10

There's no built-in JavaScript function to do this, but you can write your own fairly easily:

function pad(n) {
    return (n < 10) ? ("0" + n) : n;
}

EDIT:

Meanwhile there is a native JS function that does that. See String#padStart

_x000D_
_x000D_
console.log(String(5).padStart(2, '0'));
_x000D_
_x000D_
_x000D_

Node update a specific package

Use npm outdated to see Current and Latest version of all packages.


Then npm i packageName@versionNumber to install specific version : example npm i [email protected].

Or npm i packageName@latest to install latest version : example npm i browser-sync@latest.

Converting PKCS#12 certificate into PEM using OpenSSL

I had a PFX file and needed to create KEY file for NGINX, so I did this:

openssl pkcs12 -in file.pfx -out file.key -nocerts -nodes

Then I had to edit the KEY file and remove all content up to -----BEGIN PRIVATE KEY-----. After that NGINX accepted the KEY file.

Eclipse plugin for generating a class diagram

Try Amateras. It is a very good plugin for generating UML diagrams including class diagram.

How do I get my solution in Visual Studio back online in TFS?

You will need to do two steps here for a complete solution

First click on the Solution that you have open and then go File-> Source Control -> Go Online Then uncheck all the files that are being shown as being modified while you were offline.

Don't do the Get Latest version from Source Control Explorer. That will result in a dialog potentially showing a bunch of files asking you to resolve conflicts. Instead do this

In source Control explorer right click on the folder you want to get latest of and then Advanced - Get Specific Version. In the dropdown for version type choose Latest and then choose the first check box that says Overwrite writable files that are not checked out. This will automatically bring your folder in sync with latest on the server

How to print colored text to the terminal?

An easier option would be to use the cprint function from the termcolor package.

color-print-python

It also supports %s, %d format of printing:

Enter image description here

SQL JOIN and different types of JOINs

What is SQL JOIN ?

SQL JOIN is a method to retrieve data from two or more database tables.

What are the different SQL JOINs ?

There are a total of five JOINs. They are :

  1. JOIN or INNER JOIN
  2. OUTER JOIN

     2.1 LEFT OUTER JOIN or LEFT JOIN
     2.2 RIGHT OUTER JOIN or RIGHT JOIN
     2.3 FULL OUTER JOIN or FULL JOIN

  3. NATURAL JOIN
  4. CROSS JOIN
  5. SELF JOIN

1. JOIN or INNER JOIN :

In this kind of a JOIN, we get all records that match the condition in both tables, and records in both tables that do not match are not reported.

In other words, INNER JOIN is based on the single fact that: ONLY the matching entries in BOTH the tables SHOULD be listed.

Note that a JOIN without any other JOIN keywords (like INNER, OUTER, LEFT, etc) is an INNER JOIN. In other words, JOIN is a Syntactic sugar for INNER JOIN (see: Difference between JOIN and INNER JOIN).

2. OUTER JOIN :

OUTER JOIN retrieves

Either, the matched rows from one table and all rows in the other table Or, all rows in all tables (it doesn't matter whether or not there is a match).

There are three kinds of Outer Join :

2.1 LEFT OUTER JOIN or LEFT JOIN

This join returns all the rows from the left table in conjunction with the matching rows from the right table. If there are no columns matching in the right table, it returns NULL values.

2.2 RIGHT OUTER JOIN or RIGHT JOIN

This JOIN returns all the rows from the right table in conjunction with the matching rows from the left table. If there are no columns matching in the left table, it returns NULL values.

2.3 FULL OUTER JOIN or FULL JOIN

This JOIN combines LEFT OUTER JOIN and RIGHT OUTER JOIN. It returns rows from either table when the conditions are met and returns NULL value when there is no match.

In other words, OUTER JOIN is based on the fact that: ONLY the matching entries in ONE OF the tables (RIGHT or LEFT) or BOTH of the tables(FULL) SHOULD be listed.

Note that `OUTER JOIN` is a loosened form of `INNER JOIN`.

3. NATURAL JOIN :

It is based on the two conditions :

  1. the JOIN is made on all the columns with the same name for equality.
  2. Removes duplicate columns from the result.

This seems to be more of theoretical in nature and as a result (probably) most DBMS don't even bother supporting this.

4. CROSS JOIN :

It is the Cartesian product of the two tables involved. The result of a CROSS JOIN will not make sense in most of the situations. Moreover, we won't need this at all (or needs the least, to be precise).

5. SELF JOIN :

It is not a different form of JOIN, rather it is a JOIN (INNER, OUTER, etc) of a table to itself.

JOINs based on Operators

Depending on the operator used for a JOIN clause, there can be two types of JOINs. They are

  1. Equi JOIN
  2. Theta JOIN

1. Equi JOIN :

For whatever JOIN type (INNER, OUTER, etc), if we use ONLY the equality operator (=), then we say that the JOIN is an EQUI JOIN.

2. Theta JOIN :

This is same as EQUI JOIN but it allows all other operators like >, <, >= etc.

Many consider both EQUI JOIN and Theta JOIN similar to INNER, OUTER etc JOINs. But I strongly believe that its a mistake and makes the ideas vague. Because INNER JOIN, OUTER JOIN etc are all connected with the tables and their data whereas EQUI JOIN and THETA JOIN are only connected with the operators we use in the former.

Again, there are many who consider NATURAL JOIN as some sort of "peculiar" EQUI JOIN. In fact, it is true, because of the first condition I mentioned for NATURAL JOIN. However, we don't have to restrict that simply to NATURAL JOINs alone. INNER JOINs, OUTER JOINs etc could be an EQUI JOIN too.

How can I parse a string with a comma thousand separator to a number?

Removing commas is potentially dangerous because, as others have mentioned in the comments, many locales use a comma to mean something different (like a decimal place).

I don't know where you got your string from, but in some places in the world "2,299.00" = 2.299

The Intl object could have been a nice way to tackle this problem, but somehow they managed to ship the spec with only a Intl.NumberFormat.format() API and no parse counterpart :(

The only way to parse a string with cultural numeric characters in it to a machine recognisable number in any i18n sane way is to use a library that leverages CLDR data to cover off all possible ways of formatting number strings http://cldr.unicode.org/

The two best JS options I've come across for this so far:

Is there a way to represent a directory tree in a Github README.md?

I just like to generate it with UTF-8 and link it to every file and folder to navigate really easily. Please take a look at the example here.

The denerated markdown file

FromBody string parameter is giving null

I just ran into this and was frustrating. My setup: The header was set to Content-Type: application/JSON and was passing the info from the body with JSON format, and was reading [FromBody] on the controller.

Everything was set up fine and I expect it to work, but the problem was with the JSON sent over. Since it was a complex structure, one of my classes which was defined 'Abstract' was not getting initialized and hence the values weren't assigned to the model properly. I removed the abstract keyword and it just worked..!!!

One tip, the way I could figure this out was to send data in parts to my controller and check when it becomes null... since it was a complex model I was appending one model at a time to my request params. Hope it helps someone who runs into this stupid issue.

How to make a div have a fixed size?

Thats the natural behavior of the buttons. You could try putting a max-width/max-height on the parent container, but I'm not sure if that would do it.

max-width:something px;
max-height:something px;

The other option would be to use the devlopr tools and see if you can remove the natural padding.

padding: 0;

How to set default values in Go structs

type Config struct {
    AWSRegion                               string `default:"us-west-2"`
}

How do I convert a factor into date format?

Take a look at the formats in ?strptime

R> foo <-  factor("1/15/2006 0:00:00")
R> foo <- as.Date(foo, format = "%m/%d/%Y %H:%M:%S")                                           
R> foo                                                                                       
 [1] "2006-01-15"                                                                             
R> class(foo)                                                                                
 [1] "Date"  

Note that this will work even if foo starts out as a character. It will also work if using other date formats (as.POSIXlt, as.POSIXct).

Eliminating duplicate values based on only one column of the table

From your example it seems reasonable to assume that the siteIP column is determined by the siteName column (that is, each site has only one siteIP). If this is indeed the case, then there is a simple solution using group by:

select
  sites.siteName,
  sites.siteIP,
  max(history.date)
from sites
inner join history on
  sites.siteName=history.siteName
group by
  sites.siteName,
  sites.siteIP
order by
  sites.siteName;

However, if my assumption is not correct (that is, it is possible for a site to have multiple siteIP), then it is not clear from you question which siteIP you want the query to return in the second column. If just any siteIP, then the following query will do:

select
  sites.siteName,
  min(sites.siteIP),
  max(history.date)
from sites
inner join history on
  sites.siteName=history.siteName
group by
  sites.siteName
order by
  sites.siteName;

Set Background cell color in PHPExcel

$sheet->getStyle('A1')->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => 'FF0000')
        )
    )
);

Source: http://bayu.freelancer.web.id/2010/07/16/phpexcel-advanced-read-write-excel-made-simple/

Select all from table with Laravel and Eloquent

 public function getAllPosts()
 {
   return  Blog::all();        
 }

Have a look at the docs this is probably the first thing they explain..

How do I load a file from resource folder?

The following class can be used to load a resource from the classpath and also receive a fitting error message in case there's a problem with the given filePath.

import java.io.InputStream;
import java.nio.file.NoSuchFileException;

public class ResourceLoader
{
    private String filePath;

    public ResourceLoader(String filePath)
    {
        this.filePath = filePath;

        if(filePath.startsWith("/"))
        {
            throw new IllegalArgumentException("Relative paths may not have a leading slash!");
        }
    }

    public InputStream getResource() throws NoSuchFileException
    {
        ClassLoader classLoader = this.getClass().getClassLoader();

        InputStream inputStream = classLoader.getResourceAsStream(filePath);

        if(inputStream == null)
        {
            throw new NoSuchFileException("Resource file not found. Note that the current directory is the source folder!");
        }

        return inputStream;
    }
}

Why my $.ajax showing "preflight is invalid redirect error"?

This answer goes over the exact same thing (although for angular) -- it is a CORS issue.

One quick fix is to modify each POST request by specifying one of the 'Content-Type' header values which will not trigger a "preflight". These types are:

  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

ANYTHING ELSE triggers a preflight.

For example:

$.ajax({
   url: 'http://api.example.com/users/get',
   type: 'POST',
   headers: {
      'name-api-key':'ewf45r4435trge',
      'Content-Type':'application/x-www-form-urlencoded'
   },
   data: {
      'uid':36,
   },
   success: function(data) {
      console.log(data);
   }
});

append new row to old csv file python

Are you opening the file with mode of 'a' instead of 'w'?

See Reading and Writing Files in the python docs

7.2. Reading and Writing Files

open() returns a file object, and is most commonly used with two arguments: open(filename, mode).

>>> f = open('workfile', 'w')
>>> print f <open file 'workfile', mode 'w' at 80a0960>

The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end. 'r+' opens the file for both reading and writing. The mode argument is optional; 'r' will be assumed if it’s omitted.

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

Path to MSBuild

On Windows 2003 and later, type this command in cmd:

cmd> where MSBuild
Sample result: C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe

If nothing appears, it means that .NET framework is not included in the system PATH. The MSBuild should be in the .NET installation folder, along with .NET compilers (vbc.exe, csc.exe)

Rails: Can't verify CSRF token authenticity when making a POST request

Another way to turn off CSRF that won't render a null session is to add:

skip_before_action :verify_authenticity_token

in your Rails Controller. This will ensure you still have access to session info.

Again, make sure you only do this in API controllers or in other places where CSRF protection doesn't quite apply.

Best timing method in C?

High resolution is relative... I was looking at the examples and they mostly cater for milliseconds. However for me it is important to measure microseconds. I have not seen a platform independant solution for microseconds and thought something like the code below will be usefull. I was timing on windows only for the time being and will most likely add a gettimeofday() implementation when doing the same on AIX/Linux.

    #ifdef WIN32
      #ifndef PERFTIME
        #include <windows.h>
        #include <winbase.h>
        #define PERFTIME_INIT unsigned __int64 freq;  QueryPerformanceFrequency((LARGE_INTEGER*)&freq); double timerFrequency = (1.0/freq);  unsigned __int64 startTime;  unsigned __int64 endTime;  double timeDifferenceInMilliseconds;
        #define PERFTIME_START QueryPerformanceCounter((LARGE_INTEGER *)&startTime);
        #define PERFTIME_END QueryPerformanceCounter((LARGE_INTEGER *)&endTime); timeDifferenceInMilliseconds = ((endTime-startTime) * timerFrequency);  printf("Timing %fms\n",timeDifferenceInMilliseconds);
    #define PERFTIME(funct) {unsigned __int64 freq;  QueryPerformanceFrequency((LARGE_INTEGER*)&freq);  double timerFrequency = (1.0/freq);  unsigned __int64 startTime;  QueryPerformanceCounter((LARGE_INTEGER *)&startTime);  unsigned __int64 endTime;  funct; QueryPerformanceCounter((LARGE_INTEGER *)&endTime);  double timeDifferenceInMilliseconds = ((endTime-startTime) * timerFrequency);  printf("Timing %fms\n",timeDifferenceInMilliseconds);}
      #endif
    #else
      //AIX/Linux gettimeofday() implementation here
    #endif

Usage:

PERFTIME(ProcessIntenseFunction());

or

PERFTIME_INIT
PERFTIME_START
ProcessIntenseFunction()
PERFTIME_END

Failed to load resource: net::ERR_FILE_NOT_FOUND loading json.js

Sometime when you downloading a project from other people, they might have some special customization. So, in my case I downloaded this project https://github.com/thecodercoder/fem-easybank

And got these errors: Failed to load resource: net::ERR_FILE_NOT_FOUND Errors That happed because the creator was using the /dist folder customization.

SOLUTION

https://youtu.be/aoQ6S1a32j8?t=309

SOLUTION: you open Notepad++ press: Ctrl + F for search find all folders that starts with / as in the picture and replace with norma ones like: /dist/ to dist

enter image description here

Array.sort() doesn't sort numbers correctly

I've tried different numbers, and it always acts as if the 0s aren't there and sorts the numbers correctly otherwise. Anyone know why?

You're getting a lexicographical sort (e.g. convert objects to strings, and sort them in dictionary order), which is the default sort behavior in Javascript:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort

array.sort([compareFunction])

Parameters

compareFunction

Specifies a function that defines the sort order. If omitted, the array is sorted lexicographically (in dictionary order) according to the string conversion of each element.

In the ECMAscript specification (the normative reference for the generic Javascript), ECMA-262, 3rd ed., section 15.4.4.11, the default sort order is lexicographical, although they don't come out and say it, instead giving the steps for a conceptual sort function that calls the given compare function if necessary, otherwise comparing the arguments when converted to strings:

13. If the argument comparefn is undefined, go to step 16.
14. Call comparefn with arguments x and y.
15. Return Result(14).
16. Call ToString(x).
17. Call ToString(y).
18. If Result(16) < Result(17), return -1.
19. If Result(16) > Result(17), return 1.
20. Return +0.