Programs & Examples On #Multiprocess

Mutex lock threads

A process consists of at least one thread (think of the main function). Multi threaded code will just spawn more threads. Mutexes are used to create locks around shared resources to avoid data corruption / unexpected / unwanted behaviour. Basically it provides for sequential execution in an asynchronous setup - the requirement for which stems from non-const non-atomic operations on shared data structures.

A vivid description of what mutexes would be the case of people (threads) queueing up to visit the restroom (shared resource). While one person (thread) is using the bathroom easing him/herself (non-const non-atomic operation), he/she should ensure the door is locked (mutex), otherwise it could lead to being caught in full monty (unwanted behaviour)

How to give ASP.NET access to a private key in a certificate in the certificate store?

If you are trying to load a cert from a .pfx file in IIS the solution may be as simple as enabling this option for the Application Pool.

Right click on the App Pool and select Advanced Settings.

Then enable Load User Profile


enter image description here

Where is the web server root directory in WAMP?

To check what is your root directory go to httpd.conf file of apache and search for "DocumentRoot".The location following it is your root directory

How to post ASP.NET MVC Ajax form using JavaScript rather than submit button

A simple example, where a change on a dropdown list triggers an ajax form-submit to reload a datagrid:

<div id="pnlSearch">

    <% using (Ajax.BeginForm("UserSearch", "Home", new AjaxOptions { UpdateTargetId = "pnlSearchResults" }, new { id="UserSearchForm" }))
    { %>

        UserType: <%: Html.DropDownList("FilterUserType", Model.UserTypes, "--", new { onchange = "$('#UserSearchForm').trigger('submit');" })%>

    <% } %>

</div>

The trigger('onsubmit') is the key thing: it calls the onsubmit function that MVC has grafted onto the form.

NB. The UserSearchResults controller returns a PartialView that renders a table using the supplied Model

<div id="pnlSearchResults">
    <% Html.RenderPartial("UserSearchResults", Model); %>
</div>

spacing between form fields

  <form>     
            <div class="form-group">
                <label for="nameLabel">Name</label>
                <input id="name" name="name" class="form-control" type="text" /> 
            </div>
            <div class="form-group">
                <label for="PhoneLabel">Phone</label>
                <input id="phone" name="phone" class="form-control" type="text" /> 
            </div>
            <div class="form-group">
                <label for="yearLabel">Year</label>
                <input id="year" name="year" class="form-control" type="text" />
            </div>
        </form>

Check if a varchar is a number (TSQL)

DECLARE @A nvarchar(100) = '12'
IF(ISNUMERIC(@A) = 1)
BEGIN
    PRINT 'YES NUMERIC'
END

$(this).val() not working to get text from span using jquery

To retrieve text of an auto generated span value just do this :

var al = $("#id-span-name").text();    
alert(al);

How to compare two tags with git?

For a side-by-side visual representation, I use git difftool with openDiff set to the default viewer.

Example usage:

git difftool tags/<FIRST TAG> tags/<SECOND TAG>

If you are only interested in a specific file, you can use:

git difftool tags/<FIRST TAG>:<FILE PATH> tags/<SECOND TAG>:<FILE PATH>

As a side-note, the tags/<TAG>s can be replaced with <BRANCH>es if you are interested in diffing branches.

Can not change UILabel text color

May be the better way is

UIColor *color = [UIColor greenColor];
[self.myLabel setTextColor:color];

Thus we have colored text

Extracting a parameter from a URL in WordPress

You can try this function

/**
 * Gets the request parameter.
 *
 * @param      string  $key      The query parameter
 * @param      string  $default  The default value to return if not found
 *
 * @return     string  The request parameter.
 */

function get_request_parameter( $key, $default = '' ) {
    // If not request set
    if ( ! isset( $_REQUEST[ $key ] ) || empty( $_REQUEST[ $key ] ) ) {
        return $default;
    }

    // Set so process it
    return strip_tags( (string) wp_unslash( $_REQUEST[ $key ] ) );
}

Here is what is happening in the function

Here three things are happening.

  • First we check if the request key is present or not. If not, then just return a default value.
  • If it is set, then we first remove slashes by doing wp_unslash. Read here why it is better than stripslashes_deep.
  • Then we sanitize the value by doing a simple strip_tags. If you expect rich text from parameter, then run it through wp_kses or similar functions.

All of this information plus more info on the thinking behind the function can be found on this link https://www.intechgrity.com/correct-way-get-url-parameter-values-wordpress/

Http Post request with content type application/x-www-form-urlencoded not working in Spring

You have to tell Spring what input content-type is supported by your service. You can do this with the "consumes" Annotation Element that corresponds to your request's "Content-Type" header.

@RequestMapping(value = "/", method = RequestMethod.POST, consumes = {"application/x-www-form-urlencoded"})

It would be helpful if you posted your code.

Joining pandas dataframes by column names

you can use the left_on and right_on options as follows:

pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')

I was not sure from the question if you only wanted to merge if the key was in the left hand dataframe. If that is the case then the following will do that (the above will in effect do a many to many merge)

pd.merge(frame_1, frame_2, how='left', left_on='county_ID', right_on='countyid')

How can I implement a theme from bootswatch or wrapbootstrap in an MVC 5 project?

First, if you are able to locate your

bootstrap.css file

and

bootstrap.min.js file

in your computer, then what you just do is

First download your favorite theme i.e. from http://bootswatch.com/

Copy the downloaded bootstrap.css and bootstrap.min.js files

Then in your computer locate the existing files and replace them with the new downloaded files.

NOTE: ensure your downloaded files are renamed to what is in your folder

i.e.

enter image description here

Then you are good to go.

sometimes result may not display immediately. your may need to run the css on your browser as a way of refreshing

Convert NVARCHAR to DATETIME in SQL Server 2008

alter table your_table
alter column LoginDate datetime;

SQLFiddle demo

Jquery Value match Regex

Change it to this:

var email = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;

This is a regular expression literal that is passed the i flag which means to be case insensitive.

Keep in mind that email address validation is hard (there is a 4 or 5 page regular expression at the end of Mastering Regular Expressions demonstrating this) and your expression certainly will not capture all valid e-mail addresses.

What is console.log?

Use console.log to add debugging information to your page.

Many people use alert(hasNinjas) for this purpose but console.log(hasNinjas) is easier to work with. Using an alert pop-ups up a modal dialog box that blocks the user interface.

Edit: I agree with Baptiste Pernet and Jan Hancic that it is a very good idea to check if window.console is defined first so that your code doesn't break if there is no console available.

What does this format means T00:00:00.000Z?

Please use DateTimeFormatter ISO_DATE_TIME = DateTimeFormatter.ISO_DATE_TIME; instead of DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss") or any pattern

This fixed my problem Below

java.time.format.DateTimeParseException: Text '2019-12-18T19:00:00.000Z' could not be parsed at index 10

Selenium IDE - Command to wait for 5 seconds

This will do what you are looking for in C# (WebDriver/Selenium 2.0)

var browser = new FirefoxDriver();
var overallTimeout = Timespan.FromSeconds(10);
var sleepCycle = TimeSpan.FromMiliseconds(50);
var wait = new WebDriverWait(new SystemClock(), browser, overallTimeout, sleepCycle);
var hasTimedOut = wait.Until(_ => /* here goes code that looks for the map */);

And never use Thread.Sleep because it makes your tests unreliable

Changing the maximum length of a varchar column?

Using Maria-DB and DB-Navigator tool inside IntelliJ, MODIFY Column worked for me instead of Alter Column

Determine the number of lines within a text file

Seriously belated edit: If you're using .NET 4.0 or later

The File class has a new ReadLines method which lazily enumerates lines rather than greedily reading them all into an array like ReadAllLines. So now you can have both efficiency and conciseness with:

var lineCount = File.ReadLines(@"C:\file.txt").Count();

Original Answer

If you're not too bothered about efficiency, you can simply write:

var lineCount = File.ReadAllLines(@"C:\file.txt").Length;

For a more efficient method you could do:

var lineCount = 0;
using (var reader = File.OpenText(@"C:\file.txt"))
{
    while (reader.ReadLine() != null)
    {
        lineCount++;
    }
}

Edit: In response to questions about efficiency

The reason I said the second was more efficient was regarding memory usage, not necessarily speed. The first one loads the entire contents of the file into an array which means it must allocate at least as much memory as the size of the file. The second merely loops one line at a time so it never has to allocate more than one line's worth of memory at a time. This isn't that important for small files, but for larger files it could be an issue (if you try and find the number of lines in a 4GB file on a 32-bit system, for example, where there simply isn't enough user-mode address space to allocate an array this large).

In terms of speed I wouldn't expect there to be a lot in it. It's possible that ReadAllLines has some internal optimisations, but on the other hand it may have to allocate a massive chunk of memory. I'd guess that ReadAllLines might be faster for small files, but significantly slower for large files; though the only way to tell would be to measure it with a Stopwatch or code profiler.

I can't find my git.exe file in my Github folder

I faced the same issue and was not able to find it out where git.exe is located. After spending so much time I fount that in my windows 8, it is located at

C:\Program Files (x86)\Git\bin

And for command line :

C:\Program Files (x86)\Git\cmd

Hope this helps someone facing the same issue.

The target principal name is incorrect. Cannot generate SSPI context

I received this error when connecting via SQL Server Management Studio using Windows Authentication. My password had expired but I had not yet changed it. Once changed, I then had to log out and log back in so that the machine was working using my new credentials.

getApplication() vs. getApplicationContext()

It seems to have to do with context wrapping. Most classes derived from Context are actually a ContextWrapper, which essentially delegates to another context, possibly with changes by the wrapper.

The context is a general abstraction that supports mocking and proxying. Since many contexts are bound to a limited-lifetime object such as an Activity, there needs to be a way to get a longer-lived context, for purposes such as registering for future notifications. That is achieved by Context.getApplicationContext(). A logical implementation is to return the global Application object, but nothing prevents a context implementation from returning a wrapper or proxy with a suitable lifetime instead.

Activities and services are more specifically associated with an Application object. The usefulness of this, I believe, is that you can create and register in the manifest a custom class derived from Application and be certain that Activity.getApplication() or Service.getApplication() will return that specific object of that specific type, which you can cast to your derived Application class and use for whatever custom purpose.

In other words, getApplication() is guaranteed to return an Application object, while getApplicationContext() is free to return a proxy instead.

How to Git stash pop specific stash in 1.8.3?

If none of the above work, quotation marks around the stash itself might work for you:

git stash pop "stash@{0}"

Remove all multiple spaces in Javascript and replace with single space

There are a lot of options for regular expressions you could use to accomplish this. One example that will perform well is:

str.replace( /\s\s+/g, ' ' )

See this question for a full discussion on this exact problem: Regex to replace multiple spaces with a single space

Call to a member function on a non-object

There's an easy way to produce this error:

    $joe = null;
    $joe->anything();

Will render the error:

Fatal error: Call to a member function anything() on a non-object in /Applications/XAMPP/xamppfiles/htdocs/casMail/dao/server.php on line 23

It would be a lot better if PHP would just say,

Fatal error: Call from Joe is not defined because (a) joe is null or (b) joe does not define anything() in on line <##>.

Usually you have build your class so that $joe is not defined in the constructor or

Callback when CSS3 transition finishes

There is an animationend Event that can be observed see documentation here, also for css transition animations you could use the transitionend event

There is no need for additional libraries these all work with vanilla JS

_x000D_
_x000D_
document.getElementById("myDIV").addEventListener("transitionend", myEndFunction);_x000D_
function myEndFunction() {_x000D_
 this.innerHTML = "transition event ended";_x000D_
}
_x000D_
#myDIV {transition: top 2s; position: relative; top: 0;}_x000D_
div {background: #ede;cursor: pointer;padding: 20px;}
_x000D_
<div id="myDIV" onclick="this.style.top = '55px';">Click me to start animation.</div>
_x000D_
_x000D_
_x000D_

Checking for empty queryset in Django

Since version 1.2, Django has QuerySet.exists() method which is the most efficient:

if orgs.exists():
    # Do this...
else:
    # Do that...

But if you are going to evaluate QuerySet anyway it's better to use:

if orgs:
   ...

For more information read QuerySet.exists() documentation.

How do I view executed queries within SQL Server Management Studio?

     SELECT *  FROM sys.dm_exec_sessions es
  INNER JOIN sys.dm_exec_connections ec
      ON es.session_id = ec.session_id
  CROSS APPLY sys.dm_exec_sql_text(ec.most_recent_sql_handle) where es.session_id=65 under see text contain...

How to install sklearn?

I would recommend you look at getting the anaconda package, it will install and configure Sklearn and its dependencies.

https://www.continuum.io

how to convert milliseconds to date format in android?

try this code might help, modify it suit your needs

SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date d = format.parse(fileDate);

How to do something before on submit?

If you have a form as such:

<form id="myform">
...
</form>

You can use the following jQuery code to do something before the form is submitted:

$('#myform').submit(function() {
    // DO STUFF...
    return true; // return false to cancel form action
});

Why use prefixes on member variables in C++ classes

Many of those conventions are from a time without sophisticated editors. I would recommend using a proper IDE that allows you to color every kind of variable. Color is by far easier to spot than any prefix.

If you need to get even more detail on a variable any modern IDE should be able to show it to you by moving the caret or cursor over it. And if you use a variable in a wrong way (for instance a pointer with the . operator) you will get an error, anyway.

Disable Proximity Sensor during call

If you have LineageOS 7.1.2 (and have root), try this solution from XDA.


After having tried all the solutions proposed here, none of which worked for my Nexus 4 (mako), I found one on XDA that solves the problem with the Android dialer (but not with other apps). Basically I downloaded a recompiled version of the Dialer.apk file, which simply ignores the proximity sensor and behaves in the same way as the stock dialer app does.

Rename /system/priv-app/Dialer/Dialer.apk to something, then place the downloaded file to that folder. After reboot, I had to install the new dialer manually (simply by clicking on it). So now the original app is replaced, and the calls should be handled by this new one.

[Downside: the new way to answer a call is by pulling down the status bar and clicking 'Answer' (or 'Dismiss'), the usual slider is missing. Also, you'll need to repeat this every time your Android updates to a newer version.]

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

Use os.path.join to combine the path to the Documents directory with the completeName (filename?) supplied by the user.

import os
with open(os.path.join('/path/to/Documents',completeName), "w") as file1:
    toFile = raw_input("Write what you want into the field")
    file1.write(toFile)

If you want the Documents directory to be relative to the user's home directory, you could use something like:

os.path.join(os.path.expanduser('~'),'Documents',completeName)

Others have proposed using os.path.abspath. Note that os.path.abspath does not resolve '~' to the user's home directory:

In [10]: cd /tmp
/tmp

In [11]: os.path.abspath("~")
Out[11]: '/tmp/~'

How do I add python3 kernel to jupyter (IPython)

Shortest and best solution from my side

conda create --name py3-ml python=3.6
conda install ipykernel

source activate py3-ml # or conda activate py3-ml
python -m ipykernel install --user --name py3-ml

Clicking a checkbox with ng-click does not update the model

The order in which ng-click and ng-model will be executed is ambiguous (since neither explicitly set their priority). The most stable solution to this would be to avoid using them on the same element.

Also, you probably do not want the behavior that the examples show; you want the checkbox to respond to clicks on the complete label text, not only the checkbox. Hence, the cleanest solution would be to wrap the input (with ng-model) inside a label (with ng-click):

<label ng-click="onCompleteTodo(todo)">
  <input type='checkbox' ng-model="todo.done">
  {{todo.text}}
</label>

Working example: http://jsfiddle.net/b3NLH/1/

how to install python distutils

you can use sudo apt-get install python3-distutils by root permission.

i believe it worked here

Undefined reference to vtable

The GNU C++ compiler has to make a decision where to put the vtable in case you have the definition of the virtual functions of an object spread across multiple compilations units (e.g. some of the objects virtual functions definitions are in a .cpp file others in another .cpp file, and so on).

The compiler chooses to put the vtable in the same place as where the first declared virtual function is defined.

Now if you for some reason forgot to provide a definition for that first virtual function declared in the object (or mistakenly forgot to add the compiled object at linking phase), you will get this error.

As a side effect, please note that only for this particular virtual function you won't get the traditional linker error like you are missing function foo.

How to remove folders with a certain name

Combining multiple answers, here's a command that works on both Linux and MacOS

rm -rf $(find . -type d -name __pycache__)

How to change line color in EditText

Programmatically, you can try:

editText.getBackground().mutate().setColorFilter(getResources().getColor(android.R.color.holo_red_light), PorterDuff.Mode.SRC_ATOP);

How to deploy a React App on Apache web server

As well described in React's official docs, If you use routers that use the HTML5 pushState history API under the hood, you just need to below content to .htaccess file in public directory of your react-app.

Options -MultiViews
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.html [QSA,L]

And if using relative path update the package.json like this:

"homepage": ".",

Note: If you are using react-router@^4, you can root <Link> using the basename prop on any <Router>.

import React from 'react';
import BrowserRouter as Router from 'react-router-dom';
...
<Router basename="/calendar"/>
<Link to="/today"/>

When to Redis? When to MongoDB?

Redis is an in memory data store, that can persist it's state to disk (to enable recovery after restart). However, being an in-memory data store means the size of the data store (on a single node) cannot exceed the total memory space on the system (physical RAM + swap space). In reality, it will be much less that this, as Redis is sharing that space with many other processes on the system, and if it exhausts the system memory space it will likely be killed off by the operating system.

Mongo is a disk based data store, that is most efficient when it's working set fits within physical RAM (like all software). Being a disk based data means there are no intrinsic limits on the size of a Mongo database, however configuration options, available disk space, and other concerns may mean that databases sizes over a certain limit may become impractical or inefficient.

Both Redis and Mongo can be clustered for high availability, backup and to increase the overall size of the datastore.

Importing a Maven project into Eclipse from Git

Can't you import it as a git project and then (if you have the m2eclipse installed) right click on the project in the Package Explorer > Maven > Enable Dependency Management?

Animation fade in and out

According to the documentation AnimationSet

Represents a group of Animations that should be played together. The transformation of each individual animation are composed together into a single transform. If AnimationSet sets any properties that its children also set (for example, duration or fillBefore), the values of AnimationSet override the child values

AnimationSet mAnimationSet = new AnimationSet(false); //false means don't share interpolators

Pass true if all of the animations in this set should use the interpolator associated with this AnimationSet. Pass false if each animation should use its own interpolator.

ImageView imageView= (ImageView)findViewById(R.id.imageView);
Animation fadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in);
Animation fadeOutAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out);
mAnimationSet.addAnimation(fadeInAnimation);
mAnimationSet.addAnimation(fadeOutAnimation);
imageView.startAnimation(mAnimationSet);

I hope this will help you.

Converting Varchar Value to Integer/Decimal Value in SQL Server

You are getting arithmetic overflow. this means you are trying to make a conversion impossible to be made. This error is thrown when you try to make a conversion and the destiny data type is not enough to convert the origin data. For example:

If you try to convert 100.52 to decimal(4,2) you will get this error. The number 100.52 requires 5 positions and 2 of them are decimal.

Try to change the decimal precision to something like 16,2 or higher. Try with few records first then use it to all your select.

If input field is empty, disable submit button

An easy way to do:

function toggleButton(ref,bttnID){
    document.getElementById(bttnID).disabled= ((ref.value !== ref.defaultValue) ? false : true);
}


<input ... onkeyup="toggleButton(this,'bttnsubmit');">
<input ... disabled='disabled' id='bttnsubmit' ... >

Jenkins fails when running "service start jenkins"

In my case, the issue was of unsupported java version

Check the file /etc/init.d/jenkins to find out which java versions are supported.

To find which java versions are supported, run

grep -m 1 "JAVA_ALLOWED_VERSIONS" /etc/init.d/jenkins

The output will be like this(your's might be different)

JAVA_ALLOWED_VERSIONS=( "1.8" "11" )

In my case version 1.8 and 11 are supported. I will be going with version 11.

Install the supported version of jre using command

For ubuntu/debian

sudo apt install openjdk-11-jre 

For centOS use

sudo yum install java-11-openjdk-devel

Find the path to newly installed jre

For ubuntu/debian path is

/usr/lib/jvm/java-11-openjdk-amd64/bin/java

You can find the path on centOS under /usr/lib/jvm/

Modify the file /etc/init.d/jenkins At line number 28, replace the JAVA=`type -p java` with JAVA='/usr/lib/jvm/java-11-openjdk-amd64/bin/java'

Now run command to reload the systemctl daemon

sudo systemctl daemon-reload

Start the jenkins service

sudo systemctl start jenkins

How to use hex color values

Hex with validation

Based on Eduardo answer

Details

  • Xcode 10.0, Swift 4.2
  • Xcode 10.2.1 (10E1001), Swift 5

Solution

import UIKit

extension UIColor {

    convenience init(r: UInt8, g: UInt8, b: UInt8, alpha: CGFloat = 1.0) {
        let divider: CGFloat = 255.0
        self.init(red: CGFloat(r)/divider, green: CGFloat(g)/divider, blue: CGFloat(b)/divider, alpha: alpha)
    }

    private convenience init(rgbWithoutValidation value: Int32, alpha: CGFloat = 1.0) {
        self.init(
            r: UInt8((value & 0xFF0000) >> 16),
            g: UInt8((value & 0x00FF00) >> 8),
            b: UInt8(value & 0x0000FF),
            alpha: alpha
        )
    }

    convenience init?(rgb: Int32, alpha: CGFloat = 1.0) {
        if rgb > 0xFFFFFF || rgb < 0 { return nil }
        self.init(rgbWithoutValidation: rgb, alpha: alpha)
    }

    convenience init?(hex: String, alpha: CGFloat = 1.0) {
        var charSet = CharacterSet.whitespacesAndNewlines
        charSet.insert("#")
        let _hex = hex.trimmingCharacters(in: charSet)
        guard _hex.range(of: "^[0-9A-Fa-f]{6}$", options: .regularExpression) != nil else { return nil }
        var rgb: UInt32 = 0
        Scanner(string: _hex).scanHexInt32(&rgb)
        self.init(rgbWithoutValidation: Int32(rgb), alpha: alpha)
    }
}

Usage

let alpha: CGFloat = 1.0

// Hex
print(UIColor(rgb: 0x4F9BF5) ?? "nil")
print(UIColor(rgb: 0x4F9BF5, alpha: alpha) ?? "nil")
print(UIColor(rgb: 5217269) ?? "nil")
print(UIColor(rgb: -5217269) ?? "nil")                  // = nil
print(UIColor(rgb: 0xFFFFFF1) ?? "nil")                 // = nil

// String
print(UIColor(hex: "4F9BF5") ?? "nil")
print(UIColor(hex: "4F9BF5", alpha: alpha) ?? "nil")
print(UIColor(hex: "#4F9BF5") ?? "nil")
print(UIColor(hex: "#4F9BF5", alpha: alpha) ?? "nil")
print(UIColor(hex: "#4F9BF56") ?? "nil")                // = nil
print(UIColor(hex: "#blabla") ?? "nil")                 // = nil

// RGB
print(UIColor(r: 79, g: 155, b: 245))
print(UIColor(r: 79, g: 155, b: 245, alpha: alpha))
//print(UIColor(r: 792, g: 155, b: 245, alpha: alpha))  // Compiler will throw an error, r,g,b = [0...255]

How to get a JavaScript object's class?

Agree with dfa, that's why i consider the prototye as the class when no named class found

Here is an upgraded function of the one posted by Eli Grey, to match my way of mind

function what(obj){
    if(typeof(obj)==="undefined")return "undefined";
    if(obj===null)return "Null";
    var res = Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1];
    if(res==="Object"){
        res = obj.constructor.name;
        if(typeof(res)!='string' || res.length==0){
            if(obj instanceof jQuery)return "jQuery";// jQuery build stranges Objects
            if(obj instanceof Array)return "Array";// Array prototype is very sneaky
            return "Object";
        }
    }
    return res;
}

Remove a folder from git tracking

This works for me:

git rm -r --cached --ignore-unmatch folder_name

--ignore-unmatch is important here, without that option git will exit with error on the first file not in the index.

Access denied for user 'homestead'@'localhost' (using password: YES)

TLDR: You need to stop the server Ctrl + c and start again using php artisan serve


Details:

If you are using Laravel, and have started local dev server already by php artisan serve

And after having above server already running, you change your database server related stuff in .env file. Like moving from MySQL to SQLite or something. You need to make sure that you stop above process i.e. Ctrcl C or anything which stop the process. And then restart Artisan Serve again i.e. y php artisan serve and refresh your browser and your issue related to database will be fixed. This is what worked for me for Laravel 5.3

What is “the inverse side of the association” in a bidirectional JPA OneToMany/ManyToOne association?

Simple rules of bidirectional relationships:

1.For many-to-one bidirectional relationships, the many side is always the owning side of the relationship. Example: 1 Room has many Person (a Person belongs one Room only) -> owning side is Person

2.For one-to-one bidirectional relationships, the owning side corresponds to the side that contains the corresponding foreign key.

3.For many-to-many bidirectional relationships, either side may be the owning side.

Hope can help you.

How to change HTML Object element data attribute value in javascript

document.getElementById("PdfContentArea").setAttribute('data', path);

OR

var objectEl = document.getElementById("PdfContentArea")

objectEl.outerHTML = objectEl.outerHTML.replace(/data="(.+?)"/, 'data="' + path + '"');

How to list files using dos commands?

Try dir /b, for bare format.

dir /? will show you documentation of what you can do with the dir command. Here is the output from my Windows 7 machine:

C:\>dir /?
Displays a list of files and subdirectories in a directory.

DIR [drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D] [/L] [/N]
  [/O[[:]sortorder]] [/P] [/Q] [/R] [/S] [/T[[:]timefield]] [/W] [/X] [/4]

  [drive:][path][filename]
              Specifies drive, directory, and/or files to list.

  /A          Displays files with specified attributes.
  attributes   D  Directories                R  Read-only files
               H  Hidden files               A  Files ready for archiving
               S  System files               I  Not content indexed files
               L  Reparse Points             -  Prefix meaning not
  /B          Uses bare format (no heading information or summary).
  /C          Display the thousand separator in file sizes.  This is the
              default.  Use /-C to disable display of separator.
  /D          Same as wide but files are list sorted by column.
  /L          Uses lowercase.
  /N          New long list format where filenames are on the far right.
  /O          List by files in sorted order.
  sortorder    N  By name (alphabetic)       S  By size (smallest first)
               E  By extension (alphabetic)  D  By date/time (oldest first)
               G  Group directories first    -  Prefix to reverse order
  /P          Pauses after each screenful of information.
  /Q          Display the owner of the file.
  /R          Display alternate data streams of the file.
  /S          Displays files in specified directory and all subdirectories.
  /T          Controls which time field displayed or used for sorting
  timefield   C  Creation
              A  Last Access
              W  Last Written
  /W          Uses wide list format.
  /X          This displays the short names generated for non-8dot3 file
              names.  The format is that of /N with the short name inserted
              before the long name. If no short name is present, blanks are
              displayed in its place.
  /4          Displays four-digit years

Switches may be preset in the DIRCMD environment variable.  Override
preset switches by prefixing any switch with - (hyphen)--for example, /-W.

NullPointerException in Java with no StackTrace

When you are using AspectJ in your project, it may happen that some aspect hides its portion of the stack trace. For example, today I had:

java.lang.NullPointerException:
  at com.company.product.MyTest.test(MyTest.java:37)

This stack trace was printed when running the test via Maven's surefire.

On the other hand, when running the test in IntelliJ, a different stack trace was printed:

java.lang.NullPointerException
  at com.company.product.library.ArgumentChecker.nonNull(ArgumentChecker.java:67)
  at ...
  at com.company.product.aspects.CheckArgumentsAspect.wrap(CheckArgumentsAspect.java:82)
  at ...
  at com.company.product.MyTest.test(MyTest.java:37)

Determining if Swift dictionary contains key and obtaining any of its values

Looks like you got what you need from @matt, but if you want a quick way to get a value for a key, or just the first value if that key doesn’t exist:

extension Dictionary {
    func keyedOrFirstValue(key: Key) -> Value? {
        // if key not found, replace the nil with 
        // the first element of the values collection
        return self[key] ?? first(self.values)
        // note, this is still an optional (because the
        // dictionary could be empty)
    }
}

let d = ["one":"red", "two":"blue"]

d.keyedOrFirstValue("one")  // {Some "red"}
d.keyedOrFirstValue("two")  // {Some "blue"}
d.keyedOrFirstValue("three")  // {Some "red”}

Note, no guarantees what you'll actually get as the first value, it just happens in this case to return “red”.

How do you replace all the occurrences of a certain character in a string?

You really should have multiple input, e.g. one for firstname, middle names, lastname and another one for age. If you want to have some fun though you could try:

>>> input_given="join smith 25"
>>> chars="".join([i for i in input_given if not i.isdigit()])
>>> age=input_given.translate(None,chars)
>>> age
'25'
>>> name=input_given.replace(age,"").strip()
>>> name
'join smith'

This would of course fail if there is multiple numbers in the input. a quick check would be:

assert(age in input_given)

and also:

assert(len(name)<len(input_given))

How do I find what Java version Tomcat6 is using?

To find it from Windows OS,

  1. Open command prompt and change the directory to tomcat/tomee /bin directory.
  2. Type catalina.bat version
  3. It should print jre version details along with other informative details.

    Using CATALINA_BASE: "C:\User\software\enterprise-server-tome...

    Using CATALINA_HOME: "C:\User\software\enterprise-server-tome...

    Using CATALINA_TMPDIR: "C:\User\software\enterprise-server-tome...

    Using JRE_HOME: "C:\Program Files\Java\jdk1.8.0_25"

    Using CLASSPATH: "C:\User\software\enterprise-server-tome...

    Server version: Apache Tomcat/8.5.11

    Server built: Jan 10 2017 21:02:52 UTC

    Server number: 8.5.11.0

    OS Name: Windows 7

    OS Version: 6.1

    Architecture: amd64

    JVM Version: 1.8.0_25-b18

    JVM Vendor: Oracle Corporation

Last non-empty cell in a column

This formula worked with me for office 2010:

=LOOKUP(2;1/(A1:A100<>"");A1:A100)

A1: the first cell A100: refer to the last cell in comparing

Convert a Python list with strings all to lowercase or uppercase

A much simpler version of the top answer is given here by @Amorpheuses.

With a list of values in val:

valsLower = [item.lower() for item in vals]

This worked well for me with an f = open() text source.

iCheck check if checkbox is checked

To know if the iCheck box is checked

var isChecked = $("#myicheckboxid").prop("checked");

Fire event on enter key press for a textbox

<asp:Panel ID="Panel2" runat="server" DefaultButton="bttxt">
    <telerik:RadNumericTextBox ID="txt" runat="server">
    </telerik:RadNumericTextBox>
    <asp:LinkButton ID="bttxt" runat="server" Style="display: none;" OnClick="bttxt_Click" />
</asp:Panel>

 

protected void txt_TextChanged(object sender, EventArgs e)
{
    //enter code here
}

Node.js: Python not found exception due to node-sass and node-gyp

I had to:

Delete node_modules
Uninstall/reinstall node
npm install [email protected]

worked fine after forcing it to the right sass version, according to the version said to be working with the right node.

NodeJS  Minimum node-sass version   Node Module
Node 12 4.12+   72
Node 11 4.10+   67
Node 10 4.9+    64
Node 8  4.5.3+  57

There was lots of other errors that seemed to be caused by the wrong sass version defined.

Remove duplicate rows in MySQL

I have this query snipet for SQLServer but I think It can be used in others DBMS with little changes:

DELETE
FROM Table
WHERE Table.idTable IN  (  
    SELECT MAX(idTable)
    FROM idTable
    GROUP BY field1, field2, field3
    HAVING COUNT(*) > 1)

I forgot to tell you that this query doesn't remove the row with the lowest id of the duplicated rows. If this works for you try this query:

DELETE
FROM jobs
WHERE jobs.id IN  (  
    SELECT MAX(id)
    FROM jobs
    GROUP BY site_id, company, title, location
    HAVING COUNT(*) > 1)

How to uninstall Ruby from /usr/local?

Create a symlink at /usr/bin named 'ruby' and point it to the latest installed ruby.

You can use something like ln -s /usr/bin/ruby /to/the/installed/ruby/binary

Hope this helps.

Java generics: multiple generic parameters?

Yes - it's possible (though not with your method signature) and yes, with your signature the types must be the same.

With the signature you have given, T must be associated to a single type (e.g. String or Integer) at the call-site. You can, however, declare method signatures which take multiple type parameters

public <S, T> void func(Set<S> s, Set<T> t)

Note in the above signature that I have declared the types S and T in the signature itself. These are therefore different to and independent of any generic types associated with the class or interface which contains the function.

public class MyClass<S, T> {
   public        void foo(Set<S> s, Set<T> t); //same type params as on class
   public <U, V> void bar(Set<U> s, Set<V> t); //type params independent of class
}

You might like to take a look at some of the method signatures of the collection classes in the java.util package. Generics is really rather a complicated subject, especially when wildcards (? extends and ? super) are considered. For example, it's often the case that a method which might take a Set<Number> as a parameter should also accept a Set<Integer>. In which case you'd see a signature like this:

public void baz(Set<? extends T> s);

There are plenty of questions already on SO for you to look at on the subject!

Not sure what the point of returning an int from the function is, although you could do that if you want!

Android, getting resource ID from string?

For getting Drawable id from String resource name I am using this code:

private int getResId(String resName) {
    int defId = -1;
    try {
        Field f = R.drawable.class.getDeclaredField(resName);
        Field def = R.drawable.class.getDeclaredField("transparent_flag");
        defId = def.getInt(null);
        return f.getInt(null);
    } catch (NoSuchFieldException | IllegalAccessException e) {
        return defId;
    }
}

How can I get form data with JavaScript/jQuery?

You are all not fully correct. You cannot write:

formObj[input.name] = input.value;

Because this way if you have multiselect list - its values will be overwritten with the last one, since it's transmitted as: "param1" : "value1", "param1" : "value2".

So, correct approach is:

if (formData[input.name] === undefined) {
    formData[input.name] = input.value;
}
else {
    var inputFieldArray = $.merge([], $.isArray(formData[input.name]) ? formData[input.name] : [formData[input.name]]);
    $.merge(inputFieldArray, [input.value]);
    formData[input.name] = $.merge([], inputFieldArray);
}

How to get all options in a drop-down list by Selenium WebDriver using C#?

 WebElement element = driver.findElement(By.id("inst_state"));
        Select s = new Select(element);
        List <WebElement> elementcount = s.getOptions();

        System.out.println(elementcount.size());
        for(int i=0 ;i<elementcount.size();i++)
        {
            String value = elementcount.get(i).getText();
            System.out.println(value);

        }

How to call a function in shell Scripting?

#!/bin/bash

process_install()
{
    commands... 
    commands... 
}

process_exit()
{
    commands... 
    commands... 
}


if [ "$choice" = "true" ] then
    process_install
else
    process_exit
fi

Throwing exceptions from constructors

Apart from the fact that you do not need to throw from the constructor in your specific case because pthread_mutex_lock actually returns an EINVAL if your mutex has not been initialized and you can throw after the call to lock as is done in std::mutex:

void
lock()
{
  int __e = __gthread_mutex_lock(&_M_mutex);

  // EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may)
  if (__e)
__throw_system_error(__e);
}

then in general throwing from constructors is ok for acquisition errors during construction, and in compliance with RAII ( Resource-acquisition-is-Initialization ) programming paradigm.

Check this example on RAII

void write_to_file (const std::string & message) {
    // mutex to protect file access (shared across threads)
    static std::mutex mutex;

    // lock mutex before accessing file
    std::lock_guard<std::mutex> lock(mutex);

    // try to open file
    std::ofstream file("example.txt");
    if (!file.is_open())
        throw std::runtime_error("unable to open file");

    // write message to file
    file << message << std::endl;

    // file will be closed 1st when leaving scope (regardless of exception)
    // mutex will be unlocked 2nd (from lock destructor) when leaving
    // scope (regardless of exception)
}

Focus on these statements:

  1. static std::mutex mutex
  2. std::lock_guard<std::mutex> lock(mutex);
  3. std::ofstream file("example.txt");

The first statement is RAII and noexcept. In (2) it is clear that RAII is applied on lock_guard and it actually can throw , whereas in (3) ofstream seems not to be RAII , since the objects state has to be checked by calling is_open() that checks the failbit flag.

At first glance it seems that it is undecided on what it the standard way and in the first case std::mutex does not throw in initialization , *in contrast to OP implementation * . In the second case it will throw whatever is thrown from std::mutex::lock, and in the third there is no throw at all.

Notice the differences:

(1) Can be declared static, and will actually be declared as a member variable (2) Will never actually be expected to be declared as a member variable (3) Is expected to be declared as a member variable, and the underlying resource may not always be available.

All these forms are RAII; to resolve this, one must analyse RAII.

  • Resource : your object
  • Acquisition ( allocation ) : you object being created
  • Initialization : your object is in its invariant state

This does not require you to initialize and connect everything on construction. For example when you would create a network client object you would not actually connect it to the server upon creation, since it is a slow operation with failures. You would instead write a connect function to do just that. On the other hand you could create the buffers or just set its state.

Therefore, your issue boils down to defining your initial state. If in your case your initial state is mutex must be initialized then you should throw from the constructor. In contrast it is just fine not to initialize then ( as is done in std::mutex ), and define your invariant state as mutex is created . At any rate the invariant is not compromized necessarily by the state of its member object, since the mutex_ object mutates between locked and unlocked through the Mutex public methods Mutex::lock() and Mutex::unlock().

class Mutex {
private:
  int e;
  pthread_mutex_t mutex_;

public:
  Mutex(): e(0) {
  e = pthread_mutex_init(&mutex_);
  }

  void lock() {

    e = pthread_mutex_lock(&mutex_);
    if( e == EINVAL ) 
    { 
      throw MutexInitException();
    }
    else (e ) {
      throw MutexLockException();
    }
  }

  // ... the rest of your class
};

Unable to merge dex

This may not be your problem, but I got this error when I accidentally included two identical (but differently named) libraries in the dependencies{} section of the project.

Running a single test from unittest.TestCase via the command line

If you organize your test cases, that is, follow the same organization like the actual code and also use relative imports for modules in the same package, you can also use the following command format:

python -m unittest mypkg.tests.test_module.TestClass.test_method

# In your case, this would be:
python -m unittest testMyCase.MyCase.testItIsHot

Python 3 documentation for this: Command-Line Interface

best way to get folder and file list in Javascript

I don't like adding new package into my project just to handle this simple task.

And also, I try my best to avoid RECURSIVE algorithm.... since, for most cases it is slower compared to non Recursive one.

So I made a function to get all the folder content (and its sub folder).... NON-Recursively

var getDirectoryContent = function(dirPath) {
    /* 
        get list of files and directories from given dirPath and all it's sub directories
        NON RECURSIVE ALGORITHM
        By. Dreamsavior
    */
    var RESULT = {'files':[], 'dirs':[]};

    var fs = fs||require('fs');
    if (Boolean(dirPath) == false) {
        return RESULT;
    }
    if (fs.existsSync(dirPath) == false) {
        console.warn("Path does not exist : ", dirPath);
        return RESULT;
    }

    var directoryList = []
    var DIRECTORY_SEPARATOR = "\\";
    if (dirPath[dirPath.length -1] !== DIRECTORY_SEPARATOR) dirPath = dirPath+DIRECTORY_SEPARATOR;

    directoryList.push(dirPath); // initial

    while (directoryList.length > 0) {
        var thisDir  = directoryList.shift(); 
        if (Boolean(fs.existsSync(thisDir) && fs.lstatSync(thisDir).isDirectory()) == false) continue;

        var thisDirContent = fs.readdirSync(thisDir);
        while (thisDirContent.length > 0) { 
            var thisFile  = thisDirContent.shift(); 
            var objPath = thisDir+thisFile

            if (fs.existsSync(objPath) == false) continue;
            if (fs.lstatSync(objPath).isDirectory()) { // is a directory
                let thisDirPath = objPath+DIRECTORY_SEPARATOR; 
                directoryList.push(thisDirPath);
                RESULT['dirs'].push(thisDirPath);

            } else  { // is a file
                RESULT['files'].push(objPath); 

            } 
        } 

    }
    return RESULT;
}

the only drawback of this function is that this is Synchronous function... You have been warned ;)

How can I make a JPA OneToOne relation lazy

As already perfectly explained by ChssPly76, Hibernate's proxies don't help with unconstrained (nullable) one-to-one associations, BUT there is a trick explained here to avoid to set up instrumentation. The idea is to fool Hibernate that the entity class which we want to use has been already instrumented: you instrument it manually in the source code. It's easy! I've implemented it with CGLib as bytecode provider and it works (ensure that you configure lazy="no-proxy" and fetch="select", not "join", in your HBM).

I think this is a good alternative to real (I mean automatic) instrumentation when you have just one one-to-one nullable relation that you want to make lazy. The main drawback is that the solution depends on the bytecode provider you are using, so comment your class accurately because you could have to change the bytecode provider in the future; of course, you are also modifying your model bean for a technical reason and this is not fine.

Adding List<t>.add() another list

List<T>.Add adds a single element. Instead, use List<T>.AddRange to add multiple values.

Additionally, List<T>.AddRange takes an IEnumerable<T>, so you don't need to convert tripDetails into a List<TripDetails>, you can pass it directly, e.g.:

tripDetailsCollection.AddRange(tripDetails);

Dynamic WHERE clause in LINQ

alt text
(source: scottgu.com)

You need something like this? Use the Linq Dynamic Query Library (download includes examples).

Check out ScottGu's blog for more examples.

Simple Popup by using Angular JS

Built a modal popup example using syarul's jsFiddle link. Here is the updated fiddle.

Created an angular directive called modal and used in html. Explanation:-

HTML

<div ng-controller="MainCtrl" class="container">
  <button ng-click="toggleModal('Success')" class="btn btn-default">Success</button>
  <button ng-click="toggleModal('Remove')" class="btn btn-default">Remove</button>
  <button ng-click="toggleModal('Deny')" class="btn btn-default">Deny</button>
  <button ng-click="toggleModal('Cancel')" class="btn btn-default">Cancel</button>
  <modal visible="showModal">
      Any additional data / buttons
  </modal>
</div>

On button click toggleModal() function is called with the button message as parameter. This function toggles the visibility of popup. Any tags that you put inside will show up in the popup as content since ng-transclude is placed on modal-body in the directive template.

JS

var mymodal = angular.module('mymodal', []);

mymodal.controller('MainCtrl', function ($scope) {
    $scope.showModal = false;
    $scope.buttonClicked = "";
    $scope.toggleModal = function(btnClicked){
        $scope.buttonClicked = btnClicked;
        $scope.showModal = !$scope.showModal;
    };
  });

mymodal.directive('modal', function () {
    return {
      template: '<div class="modal fade">' + 
          '<div class="modal-dialog">' + 
            '<div class="modal-content">' + 
              '<div class="modal-header">' + 
                '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' + 
                '<h4 class="modal-title">{{ buttonClicked }} clicked!!</h4>' + 
              '</div>' + 
              '<div class="modal-body" ng-transclude></div>' + 
            '</div>' + 
          '</div>' + 
        '</div>',
      restrict: 'E',
      transclude: true,
      replace:true,
      scope:true,
      link: function postLink(scope, element, attrs) {
        scope.title = attrs.title;

        scope.$watch(attrs.visible, function(value){
          if(value == true)
            $(element).modal('show');
          else
            $(element).modal('hide');
        });

        $(element).on('shown.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = true;
          });
        });

        $(element).on('hidden.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = false;
          });
        });
      }
    };
  });

UPDATE

<!doctype html>
<html ng-app="mymodal">


<body>

<div ng-controller="MainCtrl" class="container">
  <button ng-click="toggleModal('Success')" class="btn btn-default">Success</button>
  <button ng-click="toggleModal('Remove')" class="btn btn-default">Remove</button>
  <button ng-click="toggleModal('Deny')" class="btn btn-default">Deny</button>
  <button ng-click="toggleModal('Cancel')" class="btn btn-default">Cancel</button>
  <modal visible="showModal">
      Any additional data / buttons
  </modal>
</div>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
        <!-- Scripts -->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>

    <!-- App -->
    <script>
        var mymodal = angular.module('mymodal', []);

mymodal.controller('MainCtrl', function ($scope) {
    $scope.showModal = false;
    $scope.buttonClicked = "";
    $scope.toggleModal = function(btnClicked){
        $scope.buttonClicked = btnClicked;
        $scope.showModal = !$scope.showModal;
    };
  });

mymodal.directive('modal', function () {
    return {
      template: '<div class="modal fade">' + 
          '<div class="modal-dialog">' + 
            '<div class="modal-content">' + 
              '<div class="modal-header">' + 
                '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' + 
                '<h4 class="modal-title">{{ buttonClicked }} clicked!!</h4>' + 
              '</div>' + 
              '<div class="modal-body" ng-transclude></div>' + 
            '</div>' + 
          '</div>' + 
        '</div>',
      restrict: 'E',
      transclude: true,
      replace:true,
      scope:true,
      link: function postLink(scope, element, attrs) {
          scope.$watch(attrs.visible, function(value){
          if(value == true)
            $(element).modal('show');
          else
            $(element).modal('hide');
        });

        $(element).on('shown.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = true;
          });
        });

        $(element).on('hidden.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = false;
          });
        });
      }
    };
  });

    </script>
</body>
</html>

UPDATE 2 restrict : 'E' : directive to be used as an HTML tag (element). Example in our case is

<modal>

Other values are 'A' for attribute

<div modal>

'C' for class (not preferable in our case because modal is already a class in bootstrap.css)

<div class="modal">

INSTALL_FAILED_USER_RESTRICTED : android studio using redmi 4 device

Reference

The same trouble with the same device has been here.

So, it's Xiaomi trouble, and here is a solution to this problem:

  • Go to the "Security" application and tap "Options" at top right corner

  • Scroll down to "Feature Settings" group, and look for "Permissions"

  • At there switch off "Install via USB" option, which manages the installation of the apps via USB and doesn't allow it.

On Latest Redmi Device:

Settings > Additional Settings > Developer Options > Developer options: Check the Install via USB option.

enter image description here

Use dynamic (variable) string as regex pattern in JavaScript

I found this thread useful - so I thought I would add the answer to my own problem.

I wanted to edit a database configuration file (datastax cassandra) from a node application in javascript and for one of the settings in the file I needed to match on a string and then replace the line following it.

This was my solution.

dse_cassandra_yaml='/etc/dse/cassandra/cassandra.yaml'

// a) find the searchString and grab all text on the following line to it
// b) replace all next line text with a newString supplied to function
// note - leaves searchString text untouched
function replaceStringNextLine(file, searchString, newString) {
fs.readFile(file, 'utf-8', function(err, data){
if (err) throw err;
    // need to use double escape '\\' when putting regex in strings !
    var re = "\\s+(\\-\\s(.*)?)(?:\\s|$)";
    var myRegExp = new RegExp(searchString + re, "g");
    var match = myRegExp.exec(data);
    var replaceThis = match[1];
    var writeString = data.replace(replaceThis, newString);
    fs.writeFile(file, writeString, 'utf-8', function (err) {
    if (err) throw err;
        console.log(file + ' updated');
    });
});
}

searchString = "data_file_directories:"
newString = "- /mnt/cassandra/data"

replaceStringNextLine(dse_cassandra_yaml, searchString, newString );

After running, it will change the existing data directory setting to the new one:

config file before:

data_file_directories:  
   - /var/lib/cassandra/data

config file after:

data_file_directories:  
- /mnt/cassandra/data

Android: How to Enable/Disable Wifi or Internet Connection Programmatically

It is possible to enable/disable wifi on pre Android 10 devices using the following code:

WifiManager wifiManager = 
(WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);

wifiManager.setWifiEnabled(status);

But note that it is not possible to do this anymore on Android 10 and probably going ahead as well.
https://issuetracker.google.com/issues/141011684

How do I check if an array includes a value in JavaScript?

_x000D_
_x000D_
    function countArray(originalArray) {_x000D_
     _x000D_
     var compressed = [];_x000D_
     // make a copy of the input array_x000D_
     var copyArray = originalArray.slice(0);_x000D_
     _x000D_
     // first loop goes over every element_x000D_
     for (var i = 0; i < originalArray.length; i++) {_x000D_
     _x000D_
      var count = 0; _x000D_
      // loop over every element in the copy and see if it's the same_x000D_
      for (var w = 0; w < copyArray.length; w++) {_x000D_
       if (originalArray[i] == copyArray[w]) {_x000D_
        // increase amount of times duplicate is found_x000D_
        count++;_x000D_
        // sets item to undefined_x000D_
        delete copyArray[w];_x000D_
       }_x000D_
      }_x000D_
     _x000D_
      if (count > 0) {_x000D_
       var a = new Object();_x000D_
       a.value = originalArray[i];_x000D_
       a.count = count;_x000D_
       compressed.push(a);_x000D_
      }_x000D_
     }_x000D_
     _x000D_
     return compressed;_x000D_
    };_x000D_
    _x000D_
    // It should go something like this:_x000D_
    _x000D_
    var testArray = new Array("dog", "dog", "cat", "buffalo", "wolf", "cat", "tiger", "cat");_x000D_
    var newArray = countArray(testArray);_x000D_
    console.log(newArray);
_x000D_
_x000D_
_x000D_

jQuery checkbox change and click event

Try this:

    let checkbox = document.getElementById('checkboxId');
    if (checkbox.checked != true)
    {
        alert("select checkbox");
    }

get basic SQL Server table structure information

Name and datatype:

USE OurDatabaseName
GO

SELECT 
    sc.name AS [Columne Name], 
    st1.name AS [User Type],
    st2.name AS [Base Type]
FROM dbo.syscolumns sc
    INNER JOIN dbo.systypes st1 ON st1.xusertype = sc.xusertype
    INNER JOIN dbo.systypes st2 ON st2.xusertype = sc.xtype
-- STEP TWO: Change OurTableName to the table name
WHERE sc.id = OBJECT_ID('OurTableName')
ORDER BY sc.colid

Or:

SELECT COLUMN_NAME AS ColumnName, DATA_TYPE AS DataType, CHARACTER_MAXIMUM_LENGTH AS CharacterLength
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'OurTableName'

MySQL "NOT IN" query

The subquery option has already been answered, but note that in many cases a LEFT JOIN can be a faster way to do this:

SELECT table1.*
FROM table1 LEFT JOIN table2 ON table2.principal=table1.principal
WHERE table2.principal IS NULL

If you want to check multiple tables to make sure it's not present in any of the tables (like in SRKR's comment), you can use this:

SELECT table1.*
FROM table1
LEFT JOIN table2 ON table2.name=table1.name
LEFT JOIN table3 ON table3.name=table1.name
WHERE table2.name IS NULL AND table3.name IS NULL

UICollectionView current visible cell index

converting @Anthony's answer to Swift 3.0 worked perfectly for me:

func scrollViewDidScroll(_ scrollView: UIScrollView) {

    var visibleRect = CGRect()
    visibleRect.origin = yourCollectionView.contentOffset
    visibleRect.size = yourCollectionView.bounds.size
    let visiblePoint = CGPoint(x: CGFloat(visibleRect.midX), y: CGFloat(visibleRect.midY))
    let visibleIndexPath: IndexPath? = yourCollectionView.indexPathForItem(at: visiblePoint)
    print("Visible cell's index is : \(visibleIndexPath?.row)!")
}

PHP: How do you determine every Nth iteration of a loop?

Going off of @Powerlord's answer,

"There is one catch: 0 % 3 is equal to 0. This could result in unexpected results if your counter starts at 0."

You can still start your counter at 0 (arrays, querys), but offset it

if (($counter + 1) % 3 == 0) {
  echo 'image file';
}

Using boolean values in C

If you are using C99 then you can use the _Bool type. No #includes are necessary. You do need to treat it like an integer, though, where 1 is true and 0 is false.

You can then define TRUE and FALSE.

_Bool this_is_a_Boolean_var = 1;


//or using it with true and false
#define TRUE 1
#define FALSE 0
_Bool var = TRUE;

Sublime Text 2 Code Formatting

Maybe this answer is not quite what you're looking for, but it will fomat any language with the same keyboard shortcut. The solution are language specific keyboard shortcuts.

For every language you want to format, you must find and download a plugin for that, for example a html formatter and a C# formatter. And then you map the command for every plugin to the same key, but with a differnt context (see the link).

Greets

How to compile a 64-bit application using Visual C++ 2010 Express?

Note that Visual C++ compilers are removed when you upgrade Visual Studio 2010 Professional or Visual Studio 2010 Express to Visual Studio 2010 SP1 if Windows SDK v7.1 is installed.

For instructions on resolving this, see KB2519277 on the Microsoft Support site.

Using media breakpoints in Bootstrap 4-alpha

I answered a similar question here

As @Syden said, the mixins will work. Another option is using SASS map-get like this..

@media (min-width: map-get($grid-breakpoints, sm)){
  .something {
    padding: 10px;
   }
}

@media (min-width: map-get($grid-breakpoints, md)){
  .something {
    padding: 20px;
   }
}

http://www.codeply.com/go/0TU586QNlV


Bootstrap 4 Breakpoints demo

Updating Anaconda fails: Environment Not Writable Error

If you face this issue in Linux, one of the common reasons can be that the folder "anaconda3" or "anaconda2" has root ownership. This prevents other users from writing into the folder. This can be resolved by changing the ownership of the folder from root to "USER" by running the command:

sudo chown -R $USER:$USER anaconda3

or sudo chown -R $USER:$USER <path of anaconda 3/2 folder>

Note: How to figure out whether a folder has root ownership? -- There will be a lock symbol on the top right corner of the respective folder. Or right-click on the folder->properties and you will be able to see the owner details

The -R argument lets the $USER access all the folders and files within the folder anaconda3 or anaconda2 or any respective folder. It stands for "recursive".

add id to dynamically created <div>

If I got you correctly, it is as easy as

cartDiv.id = "someID";

No need for jQuery.

Have a look at the properties of a DOM Element.

For classes it is the same:

cartDiv.className = "classes here";

But note that this will overwrite already existing class names. If you want to add and remove classes dynamically, you either have to use jQuery or write your own function that does some string replacement.

The real difference between "int" and "unsigned int"

He is asking about the real difference. When you are talking about undefined behavior you are on the level of guarantee provided by language specification - it's far from reality. To understand the real difference please check this snippet (of course this is UB but it's perfectly defined on your favorite compiler):

#include <stdio.h>

int main()
{
    int i1 = ~0;
    int i2 = i1 >> 1;
    unsigned u1 = ~0;
    unsigned u2 = u1 >> 1;
    printf("int         : %X -> %X\n", i1, i2);
    printf("unsigned int: %X -> %X\n", u1, u2);
}

How do I perform an IF...THEN in an SQL SELECT?

If you're inserting results into a table for the first time, rather than transferring results from one table to another, this works in Oracle 11.2g:

INSERT INTO customers (last_name, first_name, city)
    SELECT 'Doe', 'John', 'Chicago' FROM dual
    WHERE NOT EXISTS 
        (SELECT '1' from customers 
            where last_name = 'Doe' 
            and first_name = 'John'
            and city = 'Chicago');

Push local Git repo to new remote including all branches and tags

To push branches and tags (but not remotes):

git push origin 'refs/tags/*' 'refs/heads/*'

This would be equivalent to combining the --tags and --all options for git push, which git does not seem to allow.

Read/Parse text file line by line in VBA

For completeness; working with the data loaded into memory;

dim hf As integer: hf = freefile
dim lines() as string, i as long

open "c:\bla\bla.bla" for input as #hf
    lines = Split(input$(LOF(hf), #hf), vbnewline)
close #hf

for i = 0 to ubound(lines)
    debug.? "Line"; i; "="; lines(i)
next

What is the Linux equivalent to DOS pause?

read -n1 is not portable. A portable way to do the same might be:

(   trap "stty $(stty -g;stty -icanon)" EXIT
    LC_ALL=C dd bs=1 count=1 >/dev/null 2>&1
)   </dev/tty

Besides using read, for just a press ENTER to continue prompt you could do:

sed -n q </dev/tty

Get UserDetails object from Security Context in Spring MVC controller

Let Spring 3 injection take care of this.

Thanks to tsunade21 the easiest way is:

 @RequestMapping(method = RequestMethod.GET)   
 public ModelAndView anyMethodNameGoesHere(Principal principal) {
        final String loggedInUserName = principal.getName();

 }

How to install a Mac application using Terminal

Probably not exactly your issue..

Do you have any spaces in your package path? You should wrap it up in double quotes to be safe, otherwise it can be taken as two separate arguments

sudo installer -store -pkg "/User/MyName/Desktop/helloWorld.pkg" -target /

jQuery AJAX cross domain

I had to load webpage from local disk "file:///C:/test/htmlpage.html", call "http://localhost/getxml.php" url, and do this in IE8+ and Firefox12+ browsers, use jQuery v1.7.2 lib to minimize boilerplate code. After reading dozens of articles finally figured it out. Here is my summary.

  • server script (.php, .jsp, ...) must return http response header Access-Control-Allow-Origin: *
  • before using jQuery ajax set this flag in javascript: jQuery.support.cors = true;
  • you may set flag once or everytime before using jQuery ajax function
  • now I can read .xml document in IE and Firefox. Other browsers I did not test.
  • response document can be plain/text, xml, json or anything else

Here is an example jQuery ajax call with some debug sysouts.

jQuery.support.cors = true;
$.ajax({
    url: "http://localhost/getxml.php",
    data: { "id":"doc1", "rows":"100" },
    type: "GET",
    timeout: 30000,
    dataType: "text", // "xml", "json"
    success: function(data) {
        // show text reply as-is (debug)
        alert(data);

        // show xml field values (debug)
        //alert( $(data).find("title").text() );

        // loop JSON array (debug)
        //var str="";
        //$.each(data.items, function(i,item) {
        //  str += item.title + "\n";
        //});
        //alert(str);
    },
    error: function(jqXHR, textStatus, ex) {
        alert(textStatus + "," + ex + "," + jqXHR.responseText);
    }
});

JPA - Persisting a One to Many relationship

You have to set the associatedEmployee on the Vehicle before persisting the Employee.

Employee newEmployee = new Employee("matt");
vehicle1.setAssociatedEmployee(newEmployee);
vehicles.add(vehicle1);

newEmployee.setVehicles(vehicles);

Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);

Returning multiple values from a C++ function

The OO solution for this is to create a ratio class. It wouldn't take any extra code (would save some), would be significantly cleaner/clearer, and would give you some extra refactorings letting you clean up code outside this class as well.

Actually I think someone recommended returning a structure, which is close enough but hides the intent that this needs to be a fully thought-out class with constructor and a few methods, in fact, the "method" that you originally mentioned (as returning the pair) should most likely be a member of this class returning an instance of itself.

I know your example was just an "Example", but the fact is that unless your function is doing way more than any function should be doing, if you want it to return multiple values you are almost certainly missing an object.

Don't be afraid to create these tiny classes to do little pieces of work--that's the magic of OO--you end up breaking it down until every method is very small and simple and every class small and understandable.

Another thing that should have been an indicator that something was wrong: in OO you have essentially no data--OO isn't about passing around data, a class needs to manage and manipulate it's own data internally, any data passing (including accessors) is a sign that you may need to rethink something..

Android SharedPreferences in Fragment

This did the trick for me

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());

Check here https://developer.android.com/guide/topics/ui/settings.html#ReadingPrefs

Node.js request CERT_HAS_EXPIRED

I think the strictSSL: false should (should have worked, even in 2013) work. So in short are three possible ways:

  1. (obvious) Get your CA to renew the certificate, and put it on your server!
  2. Change the default settings of your request object:

    const myRequest = require('request').defaults({strictSSL: false})

    Many modules that use node-request internally also allow a request-object to be injected, so you can make them use your modified instance.
  3. (not recommended) Override all certificate checks for all HTTP(S) agent connections by setting the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 for the Node.js process.

generating variable names on fly in python

Another example, which is really a variation of another answer, in that it uses a dictionary too:

>>> vr={} 
... for num in range(1,4): 
...     vr[str(num)] = 5 + num
...     
>>> print vr["3"]
8
>>> 

MySQL limit from descending order

Let's say we have a table with a column time and you want the last 5 entries, but you want them returned to you in asc order, not desc, this is how you do it:

select * from ( select * from `table` order by `time` desc limit 5 ) t order by `time` asc

Implementing INotifyPropertyChanged - does a better way exist?

I have just found ActiveSharp - Automatic INotifyPropertyChanged, I have yet to use it, but it looks good.

To quote from it's web site...


Send property change notifications without specifying property name as a string.

Instead, write properties like this:

public int Foo
{
    get { return _foo; }
    set { SetValue(ref _foo, value); }  // <-- no property name here
}

Note that there is no need to include the name of the property as a string. ActiveSharp reliably and correctly figures that out for itself. It works based on the fact that your property implementation passes the backing field (_foo) by ref. (ActiveSharp uses that "by ref" call to identify which backing field was passed, and from the field it identifies the property).

Standard Android Button with a different color

I like the color filter suggestion in previous answers from @conjugatedirection and @Tomasz; However, I found that the code provided so far wasn't as easily applied as I expected.

First, it wasn't mentioned where to apply and clear the color filter. It's possible that there are other good places to do this, but what came to mind for me was an OnTouchListener.

From my reading of the original question, the ideal solution would be one that does not involve any images. The accepted answer using custom_button.xml from @emmby is probably a better fit than color filters if that's your goal. In my case, I'm starting with a png image from a UI designer of what the button is supposed to look like. If I set the button background to this image, the default highlight feedback is lost completely. This code replaces that behavior with a programmatic darkening effect.

button.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // 0x6D6D6D sets how much to darken - tweak as desired
                setColorFilter(v, 0x6D6D6D);
                break;
            // remove the filter when moving off the button
            // the same way a selector implementation would 
            case MotionEvent.ACTION_MOVE:
                Rect r = new Rect();
                v.getLocalVisibleRect(r);
                if (!r.contains((int) event.getX(), (int) event.getY())) {
                    setColorFilter(v, null);
                }
                break;
            case MotionEvent.ACTION_OUTSIDE:
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                setColorFilter(v, null);
                break;
        }
        return false;
    }

    private void setColorFilter(View v, Integer filter) {
        if (filter == null) v.getBackground().clearColorFilter();
        else {
            // To lighten instead of darken, try this:
            // LightingColorFilter lighten = new LightingColorFilter(0xFFFFFF, filter);
            LightingColorFilter darken = new LightingColorFilter(filter, 0x000000);
            v.getBackground().setColorFilter(darken);
        }
        // required on Android 2.3.7 for filter change to take effect (but not on 4.0.4)
        v.getBackground().invalidateSelf();
    }
});

I extracted this as a separate class for application to multiple buttons - shown as anonymous inner class just to get the idea.

HTTP Status 405 - Method Not Allowed Error for Rest API

Add

@Produces({"image/jpeg,image/png"})

to

@POST
@Path("/pdf")
@Consumes({ MediaType.MULTIPART_FORM_DATA })
@Produces({"image/jpeg,image/png"})
//@Produces("text/plain")
public Response uploadPdfFile(@FormDataParam("file") InputStream fileInputStream,@FormDataParam("file") FormDataContentDisposition fileMetaData) throws Exception {
    ...
}

Problem with converting int to string in Linq to entities

With EF v4 you can use SqlFunctions.StringConvert. There is no overload for int so you need to cast to a double or a decimal. Your code ends up looking like this:

var items = from c in contacts
            select new ListItem
            {
                Value = SqlFunctions.StringConvert((double)c.ContactId).Trim(),
                Text = c.Name
            };

Black transparent overlay on image hover with only CSS?

See what I've done here: http://jsfiddle.net/dyarbrough93/c8wEC/

First off, you never set the dimensions of the overlay, meaning it wasn't showing up in the first place. Secondly, I recommend just changing the z-index of the overlay when you hover over the image. Change the opacity / color of the overlay to suit your needs.

.image { position: relative; width: 200px; height: 200px;}
.image img { max-width: 100%; max-height: 100%; }
.overlay { position: absolute; top: 0; left: 0; background-color: gray; z-index: -10; width: 200px; height: 200px; opacity: 0.5}
.image:hover .overlay { z-index: 10}

Sockets: Discover port availability using Java

If you're not too concerned with performance, you could always try listening on a port using the ServerSocket class. If it throws an exception odds are it's being used.

public static boolean isAvailable(int portNr) {
  boolean portFree;
  try (var ignored = new ServerSocket(portNr)) {
      portFree = true;
  } catch (IOException e) {
      portFree = false;
  }
  return portFree;
}

EDIT: If all you're trying to do is select a free port then new ServerSocket(0) will find one for you.

Google Chrome "window.open" workaround?

This worked for me:

newwindow = window.open(url, "_blank", "resizable=yes, scrollbars=yes, titlebar=yes, width=800, height=900, top=10, left=10");

Get the cell value of a GridView row

I suggest you use a HiddenField inside template field use FindControl to find this field.

ie:

ASPX

                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:HiddenField ID="hfFname" runat="server" Value='<%# Eval("FileName") %>' />
                    </ItemTemplate>
                </asp:TemplateField>

Code behind

protected void gvAttachments_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        GridView gv1 = (GridView)sender;
        GridViewRow gvr1 = (GridViewRow)gv1.Rows[e.RowIndex];

        //get hidden field value and not directly from the GridviewRow, as that will be null or empty!
        HiddenField hf1 = (HiddenField)gvr1.FindControl("hfFname");
        if (hf1 != null)
        {
           ..
        }
    }

Visual Studio "Could not copy" .... during build

I managed to get around the issue by running the Visual Studio as administrator.

Is there StartsWith or Contains in t sql with variables?

I would use

like 'Express Edition%'

Example:

DECLARE @edition varchar(50); 
set @edition = cast((select SERVERPROPERTY ('edition')) as varchar)

DECLARE @isExpress bit
if @edition like 'Express Edition%'
    set @isExpress = 1;
else
    set @isExpress = 0;

print @isExpress

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

I had a similar issue and based on above suggestions I first added "super.setIntegerProperty("loadUrlTimeoutValue", 70000);" but that did not help. So I tried Project -> Clean, that worked and I can launch the app now !

Avinash...

Access host database from a docker container

From the 18.03 docs:

I want to connect from a container to a service on the host

The host has a changing IP address (or none if you have no network access). From 18.03 onwards our recommendation is to connect to the special DNS name host.docker.internal, which resolves to the internal IP address used by the host.

The gateway is also reachable as gateway.docker.internal.

EXAMPLE: Here's what I use for my MySQL connection string inside my container to access the MySQL instance on my host:

mysql://host.docker.internal:3306/my_awesome_database

SQL injection that gets around mysql_real_escape_string()

The short answer is yes, yes there is a way to get around mysql_real_escape_string(). #For Very OBSCURE EDGE CASES!!!

The long answer isn't so easy. It's based off an attack demonstrated here.

The Attack

So, let's start off by showing the attack...

mysql_query('SET NAMES gbk');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");

In certain circumstances, that will return more than 1 row. Let's dissect what's going on here:

  1. Selecting a Character Set

    mysql_query('SET NAMES gbk');
    

    For this attack to work, we need the encoding that the server's expecting on the connection both to encode ' as in ASCII i.e. 0x27 and to have some character whose final byte is an ASCII \ i.e. 0x5c. As it turns out, there are 5 such encodings supported in MySQL 5.6 by default: big5, cp932, gb2312, gbk and sjis. We'll select gbk here.

    Now, it's very important to note the use of SET NAMES here. This sets the character set ON THE SERVER. If we used the call to the C API function mysql_set_charset(), we'd be fine (on MySQL releases since 2006). But more on why in a minute...

  2. The Payload

    The payload we're going to use for this injection starts with the byte sequence 0xbf27. In gbk, that's an invalid multibyte character; in latin1, it's the string ¿'. Note that in latin1 and gbk, 0x27 on its own is a literal ' character.

    We have chosen this payload because, if we called addslashes() on it, we'd insert an ASCII \ i.e. 0x5c, before the ' character. So we'd wind up with 0xbf5c27, which in gbk is a two character sequence: 0xbf5c followed by 0x27. Or in other words, a valid character followed by an unescaped '. But we're not using addslashes(). So on to the next step...

  3. mysql_real_escape_string()

    The C API call to mysql_real_escape_string() differs from addslashes() in that it knows the connection character set. So it can perform the escaping properly for the character set that the server is expecting. However, up to this point, the client thinks that we're still using latin1 for the connection, because we never told it otherwise. We did tell the server we're using gbk, but the client still thinks it's latin1.

    Therefore the call to mysql_real_escape_string() inserts the backslash, and we have a free hanging ' character in our "escaped" content! In fact, if we were to look at $var in the gbk character set, we'd see:

    ?' OR 1=1 /*

    Which is exactly what the attack requires.

  4. The Query

    This part is just a formality, but here's the rendered query:

    SELECT * FROM test WHERE name = '?' OR 1=1 /*' LIMIT 1
    

Congratulations, you just successfully attacked a program using mysql_real_escape_string()...

The Bad

It gets worse. PDO defaults to emulating prepared statements with MySQL. That means that on the client side, it basically does a sprintf through mysql_real_escape_string() (in the C library), which means the following will result in a successful injection:

$pdo->query('SET NAMES gbk');
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));

Now, it's worth noting that you can prevent this by disabling emulated prepared statements:

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

This will usually result in a true prepared statement (i.e. the data being sent over in a separate packet from the query). However, be aware that PDO will silently fallback to emulating statements that MySQL can't prepare natively: those that it can are listed in the manual, but beware to select the appropriate server version).

The Ugly

I said at the very beginning that we could have prevented all of this if we had used mysql_set_charset('gbk') instead of SET NAMES gbk. And that's true provided you are using a MySQL release since 2006.

If you're using an earlier MySQL release, then a bug in mysql_real_escape_string() meant that invalid multibyte characters such as those in our payload were treated as single bytes for escaping purposes even if the client had been correctly informed of the connection encoding and so this attack would still succeed. The bug was fixed in MySQL 4.1.20, 5.0.22 and 5.1.11.

But the worst part is that PDO didn't expose the C API for mysql_set_charset() until 5.3.6, so in prior versions it cannot prevent this attack for every possible command! It's now exposed as a DSN parameter.

The Saving Grace

As we said at the outset, for this attack to work the database connection must be encoded using a vulnerable character set. utf8mb4 is not vulnerable and yet can support every Unicode character: so you could elect to use that instead—but it has only been available since MySQL 5.5.3. An alternative is utf8, which is also not vulnerable and can support the whole of the Unicode Basic Multilingual Plane.

Alternatively, you can enable the NO_BACKSLASH_ESCAPES SQL mode, which (amongst other things) alters the operation of mysql_real_escape_string(). With this mode enabled, 0x27 will be replaced with 0x2727 rather than 0x5c27 and thus the escaping process cannot create valid characters in any of the vulnerable encodings where they did not exist previously (i.e. 0xbf27 is still 0xbf27 etc.)—so the server will still reject the string as invalid. However, see @eggyal's answer for a different vulnerability that can arise from using this SQL mode.

Safe Examples

The following examples are safe:

mysql_query('SET NAMES utf8');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");

Because the server's expecting utf8...

mysql_set_charset('gbk');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");

Because we've properly set the character set so the client and the server match.

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->query('SET NAMES gbk');
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));

Because we've turned off emulated prepared statements.

$pdo = new PDO('mysql:host=localhost;dbname=testdb;charset=gbk', $user, $password);
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));

Because we've set the character set properly.

$mysqli->query('SET NAMES gbk');
$stmt = $mysqli->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$param = "\xbf\x27 OR 1=1 /*";
$stmt->bind_param('s', $param);
$stmt->execute();

Because MySQLi does true prepared statements all the time.

Wrapping Up

If you:

  • Use Modern Versions of MySQL (late 5.1, all 5.5, 5.6, etc) AND mysql_set_charset() / $mysqli->set_charset() / PDO's DSN charset parameter (in PHP = 5.3.6)

OR

  • Don't use a vulnerable character set for connection encoding (you only use utf8 / latin1 / ascii / etc)

You're 100% safe.

Otherwise, you're vulnerable even though you're using mysql_real_escape_string()...

How do I run a program with a different working directory from current, from Linux shell?

Call the program like this:

(cd /c; /a/helloworld)

The parentheses cause a sub-shell to be spawned. This sub-shell then changes its working directory to /c, then executes helloworld from /a. After the program exits, the sub-shell terminates, returning you to your prompt of the parent shell, in the directory you started from.

Error handling: To avoid running the program without having changed the directory, e.g. when having misspelled /c, make the execution of helloworld conditional:

(cd /c && /a/helloworld)

Reducing memory usage: To avoid having the subshell waste memory while hello world executes, call helloworld via exec:

(cd /c && exec /a/helloworld)

[Thanks to Josh and Juliano for giving tips on improving this answer!]

Transform hexadecimal information to binary using a Linux command

As @user786653 suggested, use the xxd(1) program:

xxd -r -p input.txt output.bin

How do I convert the date from one format to another date object in another format without using any deprecated classes?

Since Java 8, we can achieve this as follows:

private static String convertDate(String strDate) 
{
    //for strdate = 2017 July 25

    DateTimeFormatter f = new DateTimeFormatterBuilder().appendPattern("yyyy MMMM dd")
                                        .toFormatter();

    LocalDate parsedDate = LocalDate.parse(strDate, f);
    DateTimeFormatter f2 = DateTimeFormatter.ofPattern("MM/d/yyyy");

    String newDate = parsedDate.format(f2);

    return newDate;
}

The output will be : "07/25/2017"

Line Break in XML?

In the XML: use literal line-breaks, nothing else needed there.

The newlines will be preserved for Javascript to read them [1]. Note that any indentation-spaces and preceding or trailing line-breaks are preserved too (the reason you weren't seeing them is that HTML/CSS collapses whitespace into single space-characters by default).

Then the easiest way is: In the HTML: do nothing, just use CSS to preserve the line-breaks

.msg_body {
    white-space: pre-line;
}

But this also preserves your extra lines from the XML document, and doesn't work in IE 6 or 7 [2].

So clean up the whitespace yourself; this is one way to do it (linebreaks for clarity - Javascript is happy with or without them [3]) [4]

[get lyric...].nodeValue
    .replace(/^[\r\n\t ]+|[\r\n\t ]+$/g, '')
    .replace(/[ \t]+/g, ' ')
    .replace(/ ?([\r\n]) ?/g, '$1')

and then preserve those line-breaks with

.msg_body {
    white-space: pre; // for IE 6 and 7
    white-space: pre-wrap; // or pre-line
}

or, instead of that CSS, add a .replace(/\r?\n/g, '<br />') after the other JavaScript .replaces.

(Side note: Using document.write() like that is also not ideal and sometimes vulnerable to cross-site scripting attacks, but that's another subject. In relation to this answer, if you wanted to use the variation that replaces with <br>, you'd have to escape <,&(,>,",') before generating the <br>s.)

--

[1] reference: sections "Element White Space Handling" and "XML Schema White Space Control" http://www.usingxml.com/Basics/XmlSpace#ElementWhiteSpaceHandling

[2] http://www.quirksmode.org/css/whitespace.html

[3] except for a few places in Javascript's syntax where its semicolon insertion is particularly annoying.

[4] I wrote it and tested these regexps in Linux Node.js (which uses the same Javascript engine as Chrome, "V8"). There's a small risk some browser executes regexps differently. (My test string (in javascript syntax) "\n\nfoo bar baz\n\n\tmore lyrics \nare good\n\n")

Getting vertical gridlines to appear in line plot in matplotlib

maybe this can solve the problem: matplotlib, define size of a grid on a plot

ax.grid(True, which='both')

The truth is that the grid is working, but there's only one v-grid in 00:00 and no grid in others. I meet the same problem that there's only one grid in Nov 1 among many days.

Windows shell command to get the full path to the current directory?

Based on the follow up question (store the data in a variable) in the comments to the chdir post I'm betting he wants to store the current path to restore it after changeing directories.

The original user should look at "pushd", which changes directory and pushes the current one onto a stack that can be restored with a "popd". On any modern Windows cmd shell that is the way to go when making batch files.

If you really need to grab the current path then modern cmd shells also have a %CD% variable that you can easily stuff away in another variable for reference.

/etc/apt/sources.list" E212: Can't open file for writing

change the permission for the other user for that type setfacl -m u:username:rw filename

Android Text over image

There are many ways. You use RelativeLayout or AbsoluteLayout.

With relative, you can have the image align with parent on the left side for example and also have the text align to the parent left too... then you can use margins and padding and gravity on the text view to get it lined where you want over the image.

Go to next item in ForEach-Object

You may want to use the Continue statement to continue with the innermost loop.

Excerpt from PowerShell help file:

In a script, the continue statement causes program flow to move immediately to the top of the innermost loop controlled by any of these statements:

  • for
  • foreach
  • while

CSS hexadecimal RGBA?

See here http://www.w3.org/TR/css3-color/#rgba-color

It is not possible, most probably because 0xFFFFFFFF is greater than the maximum value for 32bit integers

How to compare DateTime without time via LINQ?

Try

var q = db.Games.Where(t => t.StartDate.Date >= DateTime.Now.Date).OrderBy(d => d.StartDate);

How do I capture the output of a script if it is being ran by the task scheduler?

Example how to run program and write stdout and stderr to file with timestamp:

cmd /c ""C:\Program Files (x86)\program.exe" -param fooo >> "c:\dir space\Log_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt" 2>&1"

Key part is to double quote whole part behind cmd /c and inside it use double quotes as usual. Also note that date is locale dependent, this example works using US locale.

Simulate a button click in Jest

I needed to do a little bit of testing myself of a button component. These tests work for me ;-)

import { shallow } from "enzyme";
import * as React from "react";
import Button from "../button.component";

describe("Button Component Tests", () => {
    it("Renders correctly in DOM", () => {
        shallow(
            <Button text="Test" />
        );
    });
    it("Expects to find button HTML element in the DOM", () => {
        const wrapper = shallow(<Button text="test"/>)
        expect(wrapper.find('button')).toHaveLength(1);
    });

    it("Expects to find button HTML element with className test in the DOM", () => {
        const wrapper = shallow(<Button className="test" text="test"/>)
        expect(wrapper.find('button.test')).toHaveLength(1);
    });

    it("Expects to run onClick function when button is pressed in the DOM", () => {
        const mockCallBackClick = jest.fn();
        const wrapper = shallow(<Button onClick={mockCallBackClick} className="test" text="test"/>);
        wrapper.find('button').simulate('click');
        expect(mockCallBackClick.mock.calls.length).toEqual(1);
    });
});

Get specific objects from ArrayList when objects were added anonymously?

I would suggest overriding the equals(Object) of your Party class. It might look something like this:

public boolean equals(Object o){
    if(o == null)
        return false;
    if(o instanceof String)
        return name.equalsIgnoreCase((String)o);
    else if(o instanceof Party)
        return equals(((Party)o).name);
    return false;
}

After you do that, you could use the indexOf(Object) method to retrieve the index of the party specified by its name, as shown below:

int index = cave.parties.indexOf("SecondParty");

Would return the index of the Party with the name SecondParty.

Note: This only works because you are overriding the equals(Object) method.

Generate random numbers using C++11 random library

Stephan T. Lavavej (stl) from Microsoft did a talk at Going Native about how to use the new C++11 random functions and why not to use rand(). In it, he included a slide that basically solves your question. I've copied the code from that slide below.

You can see his full talk here: http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful

#include <random>
#include <iostream>

int main() {
    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_real_distribution<double> dist(1.0, 10.0);

    for (int i=0; i<16; ++i)
        std::cout << dist(mt) << "\n";
}

We use random_device once to seed the random number generator named mt. random_device() is slower than mt19937, but it does not need to be seeded because it requests random data from your operating system (which will source from various locations, like RdRand for example).


Looking at this question / answer, it appears that uniform_real_distribution returns a number in the range [a, b), where you want [a, b]. To do that, our uniform_real_distibution should actually look like:

std::uniform_real_distribution<double> dist(1, std::nextafter(10, DBL_MAX));

How to change the button color when it is active using bootstrap?

CSS has different pseudo selector by which you can achieve such effect. In your case you can use

:active : if you want background color only when the button is clicked and don't want to persist.

:focus: if you want background color untill the focus is on the button.

button:active{
    background:olive;
}

and

button:focus{
    background:olive;
}

JsFiddle Example

P.S.: Please don't give the number in Id attribute of html elements.

top nav bar blocking top content of the page

The best solution I've found so far, that does not involve hard coding heights and breakpoints is to add an extra <nav... tag to the markup.

<nav class="navbar navbar-expand-md" aria-hidden="true">
    <a class="navbar-brand" href="#">Navbar</a>
</nav>
<nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top">
    <a class="navbar-brand" href="#">Navbar</a>

By doing it this way the @media breakpoints are identical, the height is identical (provided your navbar-brand is the tallest object in the navbar but you can easily substitute another element in the non fixed-top navbar.

Where this fails is with screen readers which will now present 2 navbar-brand elements. This points at the need for a not-for-sr class to prevent that element from showing up for screen readers. However that class does not exist https://getbootstrap.com/docs/4.0/utilities/screenreaders/

I've tried to compensate for the screen reader issue with aria-hidden="true" but https://www.accessibility-developer-guide.com/examples/sensible-aria-usage/hidden/ seems to indicate this will probably not work when the screen reader is in focus mode which is of course the only time you actually need it to work...

Python: URLError: <urlopen error [Errno 10060]

This is because of the proxy settings. I also had the same problem, under which I could not use any of the modules which were fetching data from the internet. There are simple steps to follow:
1. open the control panel
2. open internet options
3. under connection tab open LAN settings
4. go to advance settings and unmark everything, delete every proxy in there. Or u can just unmark the checkbox in proxy server this will also do the same
5. save all the settings by clicking ok.
you are done. try to run the programme again, it must work it worked for me at least

What's the source of Error: getaddrinfo EAI_AGAIN?

If you are not get that at localhost either production, that means you must upgrade your plan due to the limitations of the free tier

Rendering a template variable as HTML

If you don't want the HTML to be escaped, look at the safe filter and the autoescape tag:

safe:

{{ myhtml |safe }}

autoescape:

{% autoescape off %}
    {{ myhtml }}
{% endautoescape %}

Static image src in Vue.js template

If you want to bind a string to the src attribute, you should wrap it on single quotes:

<img v-bind:src="'/static/img/clear.gif'">
<!-- or shorthand -->
<img :src="'/static/img/clear.gif'">

IMO you do not need to bind a string, you could use the simple way:

<img src="/static/img/clear.gif">

Check an example about the image preload here: http://codepen.io/pespantelis/pen/RWVZxL

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

Try

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

What are the parameters for the number Pipe - Angular 2

'1.0-0' will give you zero decimal places i.e. no decimals. e.g.$500

What is the difference between map and flatMap and a good use case for each?

Flatmap and Map both transforms the collection.

Difference:

map(func)
Return a new distributed dataset formed by passing each element of the source through a function func.

flatMap(func)
Similar to map, but each input item can be mapped to 0 or more output items (so func should return a Seq rather than a single item).

The transformation function:
map: One element in -> one element out.
flatMap: One element in -> 0 or more elements out (a collection).

What does ellipsize mean in android?

Set this property to edit text. Elipsize is working with disable edit text

android:lines="1"
android:scrollHorizontally="true"
android:ellipsize="end"
android:singleLine="true"
android:editable="false"

or setKeyListener(null);

Curl error: Operation timed out

In curl request add time out 0 so its infinite time set like CURLOPT_TIMEOUT set 0

What is the use of BindingResult interface in spring MVC?

It's important to note that the order of parameters is actually important to spring. The BindingResult needs to come right after the Form that is being validated. Likewise, the [optional] Model parameter needs to come after the BindingResult. Example:

Valid:

@RequestMapping(value = "/entry/updateQuantity", method = RequestMethod.POST)
public String updateEntryQuantity(@Valid final UpdateQuantityForm form,
                                  final BindingResult bindingResult,
                                  @RequestParam("pk") final long pk,
                                  final Model model) {
}

Not Valid:

RequestMapping(value = "/entry/updateQuantity", method = RequestMethod.POST)
public String updateEntryQuantity(@Valid final UpdateQuantityForm form,
                                  @RequestParam("pk") final long pk,
                                  final BindingResult bindingResult,
                                  final Model model) {
}

Match two strings in one line with grep

I think this is what you were looking for:

grep -E "string1|string2" filename

I think that answers like this:

grep 'string1.*string2\|string2.*string1' filename

only match the case where both are present, not one or the other or both.

Run command on the Ansible host

I'd like to share that Ansible can be run on localhost via shell:

ansible all -i "localhost," -c local -m shell -a 'echo hello world'

This could be helpful for simple tasks or for some hands-on learning of Ansible.

The example of code is taken from this good article:

Running ansible playbook in localhost

Remove a fixed prefix/suffix from a string in Bash

I would make use of capture groups in regex:

$ string="hello-world"
$ prefix="hell"
$ suffix="ld"
$ set +H # Disables history substitution, can be omitted in scripts.
$ perl -pe "s/${prefix}((?:(?!(${suffix})).)*)${suffix}/\1/" <<< $string
o-wor
$ string1=$string$string
$ perl -pe "s/${prefix}((?:(?!(${suffix})).)*)${suffix}/\1/g" <<< $string1
o-woro-wor

((?:(?!(${suffix})).)*) makes sure that the content of ${suffix} will be excluded from the capture group. In terms of example, it's the string equivalent to [^A-Z]*. Otherwise you will get:

$ perl -pe "s/${prefix}(.*)${suffix}/\1/g" <<< $string1
o-worldhello-wor

Change navbar text color Bootstrap

The syntax is :

.nav navbar-nav .navbar-right > li > a {
   color: blue;
}

CSS disable hover effect

Here is way to to unset the hover effect.

.table-hover > tbody > tr.hidden-table:hover > td {
    background-color: unset !important;
    color: unset !important;
}

html div onclick event

The problem was that clicking the anchor still triggered a click in your <div>. That's called "event bubbling".

In fact, there are multiple solutions:

  • Checking in the DIV click event handler whether the actual target element was the anchor
    → jsFiddle

    $('.expandable-panel-heading').click(function (evt) {
        if (evt.target.tagName != "A") {
            alert('123');
        }
    
        // Also possible if conditions:
        // - evt.target.id != "ancherComplaint"
        // - !$(evt.target).is("#ancherComplaint")
    });
    
    $("#ancherComplaint").click(function () {
        alert($(this).attr("id"));
    });
    
  • Stopping the event propagation from the anchor click listener
    → jsFiddle

    $("#ancherComplaint").click(function (evt) {
        evt.stopPropagation();
        alert($(this).attr("id"));
    });
    


As you may have noticed, I have removed the following selector part from my examples:

:not(#ancherComplaint)

This was unnecessary because there is no element with the class .expandable-panel-heading which also have #ancherComplaint as its ID.

I assume that you wanted to suppress the event for the anchor. That cannot work in that manner because both selectors (yours and mine) select the exact same DIV. The selector has no influence on the listener when it is called; it only sets the list of elements to which the listeners should be registered. Since this list is the same in both versions, there exists no difference.

Finding local IP addresses using Python's stdlib

Socket API method

see https://stackoverflow.com/a/28950776/711085

Downsides:

  • Not cross-platform.
  • Requires more fallback code, tied to existence of particular addresses on the internet
  • This will also not work if you're behind a NAT
  • Probably creates a UDP connection, not independent of (usually ISP's) DNS availability (see other answers for ideas like using 8.8.8.8: Google's (coincidentally also DNS) server)
  • Make sure you make the destination address UNREACHABLE, like a numeric IP address that is spec-guaranteed to be unused. Do NOT use some domain like fakesubdomain.google.com or somefakewebsite.com; you'll still be spamming that party (now or in the future), and spamming your own network boxes as well in the process.

Reflector method

(Do note that this does not answer the OP's question of the local IP address, e.g. 192.168...; it gives you your public IP address, which might be more desirable depending on use case.)

You can query some site like whatismyip.com (but with an API), such as:

from urllib.request import urlopen
import re
def getPublicIp():
    data = str(urlopen('http://checkip.dyndns.com/').read())
    # data = '<html><head><title>Current IP Check</title></head><body>Current IP Address: 65.96.168.198</body></html>\r\n'

    return re.compile(r'Address: (\d+\.\d+\.\d+\.\d+)').search(data).group(1)

or if using python2:

from urllib import urlopen
import re
def getPublicIp():
    data = str(urlopen('http://checkip.dyndns.com/').read())
    # data = '<html><head><title>Current IP Check</title></head><body>Current IP Address: 65.96.168.198</body></html>\r\n'

    return re.compile(r'Address: (\d+\.\d+\.\d+\.\d+)').search(data).group(1)

Advantages:

  • One upside of this method is it's cross-platform
  • It works from behind ugly NATs (e.g. your home router).

Disadvantages (and workarounds):

  • Requires this website to be up, the format to not change (almost certainly won't), and your DNS servers to be working. One can mitigate this issue by also querying other third-party IP address reflectors in case of failure.
  • Possible attack vector if you don't query multiple reflectors (to prevent a compromised reflector from telling you that your address is something it's not), or if you don't use HTTPS (to prevent a man-in-the-middle attack pretending to be the server)

edit: Though initially I thought these methods were really bad (unless you use many fallbacks, the code may be irrelevant many years from now), it does pose the question "what is the internet?". A computer may have many interfaces pointing to many different networks. For a more thorough description of the topic, google for gateways and routes. A computer may be able to access an internal network via an internal gateway, or access the world-wide web via a gateway on for example a router (usually the case). The local IP address that the OP asks about is only well-defined with respect to a single link layer, so you have to specify that ("is it the network card, or the ethernet cable, which we're talking about?"). There may be multiple non-unique answers to this question as posed. However the global IP address on the world-wide web is probably well-defined (in the absence of massive network fragmentation): probably the return path via the gateway which can access the TLDs.

How do I update a formula with Homebrew?

You can update all outdated packages like so:

brew install `brew outdated`

or

brew outdated | xargs brew install

or

brew upgrade

This is from the brew site..

for upgrading individual formula:

brew install formula-name && brew cleanup formula-name

How is TeamViewer so fast?

A bit late answer, but I suggest you have a look at a not well known project on codeplex called ConferenceXP

ConferenceXP is an open source research platform that provides simple, flexible, and extensible conferencing and collaboration using high-bandwidth networks and the advanced multimedia capabilities of Microsoft Windows. ConferenceXP helps researchers and educators develop innovative applications and solutions that feature broadcast-quality audio and video in support of real-time distributed collaboration and distance learning environments.

Full source (it's huge!) is provided. It implements the RTP protocol.

Hiding a password in a python script (insecure obfuscation only)

A way that I have done this is as follows:

At the python shell:

>>> from cryptography.fernet import Fernet
>>> key = Fernet.generate_key()
>>> print(key)
b'B8XBLJDiroM3N2nCBuUlzPL06AmfV4XkPJ5OKsPZbC4='
>>> cipher = Fernet(key)
>>> password = "thepassword".encode('utf-8')
>>> token = cipher.encrypt(password)
>>> print(token)
b'gAAAAABe_TUP82q1zMR9SZw1LpawRLHjgNLdUOmW31RApwASzeo4qWSZ52ZBYpSrb1kUeXNFoX0tyhe7kWuudNs2Iy7vUwaY7Q=='

Then, create a module with the following code:

from cryptography.fernet import Fernet

# you store the key and the token
key = b'B8XBLJDiroM3N2nCBuUlzPL06AmfV4XkPJ5OKsPZbC4='
token = b'gAAAAABe_TUP82q1zMR9SZw1LpawRLHjgNLdUOmW31RApwASzeo4qWSZ52ZBYpSrb1kUeXNFoX0tyhe7kWuudNs2Iy7vUwaY7Q=='

# create a cipher and decrypt when you need your password
cipher = Fernet(key)

mypassword = cipher.decrypt(token).decode('utf-8')

Once you've done this, you can either import mypassword directly or you can import the token and cipher to decrypt as needed.

Obviously, there are some shortcomings to this approach. If someone has both the token and the key (as they would if they have the script), they can decrypt easily. However it does obfuscate, and if you compile the code (with something like Nuitka) at least your password won't appear as plain text in a hex editor.

How to parse JSON data with jQuery / JavaScript?

Here's how you would do this in JavaScript, this is a really efficient way to do it!

let data = "{ "name": "mark"}"
let object = JSON.parse(data);
console.log(object.name);

this would print mark

GoogleTest: How to skip a test?

If more than one test are needed be skipped

--gtest_filter=-TestName.*:TestName.*TestCase

std::cin input with spaces?

You want to use the .getline function in cin.

#include <iostream>
using namespace std;

int main () {
  char name[256], title[256];

  cout << "Enter your name: ";
  cin.getline (name,256);

  cout << "Enter your favourite movie: ";
  cin.getline (title,256);

  cout << name << "'s favourite movie is " << title;

  return 0;
}

Took the example from here. Check it out for more info and examples.

Parsing jQuery AJAX response

 $.ajax({     
     type: "POST",
     url: '/admin/systemgoalssystemgoalupdate?format=html',
     data: formdata,
     success: function (data) {
         console.log(data);
     },
     dataType: "json"
 });

how to get the last character of a string?

var firstName = "Ada";
var lastLetterOfFirstName = firstName[firstName.length - 1];

What is the incentive for curl to release the library for free?

I'm Daniel Stenberg.

I made curl

I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.

I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.

Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.

Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.

Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.

At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.

Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.

Why do I still work on curl?

Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?

  1. I can't speak for my fellow project team members. We all participate in this for our own reasons.
  2. I think it's still the right thing to do. I'm proud of what we've accomplished and I truly want to make the world a better place and I think curl does its little part in this.
  3. There are still bugs to fix and features to add!
  4. curl is free but my time is not. I still have a job and someone still has to pay someone for me to get paid every month so that I can put food on the table for my family. I charge customers and companies to help them with curl. You too can get my help for a fee, which then indirectly helps making sure that curl continues to evolve, remain free and the kick-ass product it is.
  5. curl was my spare time project for twenty years before I started working with it full time. I've had great jobs and worked on awesome projects. I've been in a position of luxury where I could continue to work on curl on my spare time and keep shipping a quality product for free. My work on curl has given me friends, boosted my career and taken me to places I would not have been at otherwise.
  6. I would not do it differently if I could back and do it again.

Am I proud of what we've done?

Yes. So insanely much.

But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.

We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.

Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.

For real?

Yeah. For real.

Do I ever get tired? Is it ever done?

Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.

But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.

curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.

SecurityException during executing jnlp file (Missing required Permissions manifest attribute in main jar)

If you'd like to set this globally for all users of a machine, you can create the following directory and file structures:

mkdir %windir%\Sun\Java\Deployment

Create a file deployment.config with the content:

deployment.system.config=file:///c:/windows/Sun/Java/Deployment/deployment.properties
deployment.system.config.mandatory=TRUE

Create a file deployment.properties

deployment.user.security.exception.sites=C\:/WINDOWS/Sun/Java/Deployment/exception.sites

Create a file exception.sites

http://example1.com
http://example2.com/path/to/specific/directory/

Reference https://blogs.oracle.com/java-platform-group/entry/upcoming_exception_site_list_in

static const vs #define

If this is a C++ question and it mentions #define as an alternative, then it is about "global" (i.e. file-scope) constants, not about class members. When it comes to such constants in C++ static const is redundant. In C++ const have internal linkage by default and there's no point in declaring them static. So it is really about const vs. #define.

And, finally, in C++ const is preferable. At least because such constants are typed and scoped. There are simply no reasons to prefer #define over const, aside from few exceptions.

String constants, BTW, are one example of such an exception. With #defined string constants one can use compile-time concatenation feature of C/C++ compilers, as in

#define OUT_NAME "output"
#define LOG_EXT ".log"
#define TEXT_EXT ".txt"

const char *const log_file_name = OUT_NAME LOG_EXT;
const char *const text_file_name = OUT_NAME TEXT_EXT;

P.S. Again, just in case, when someone mentions static const as an alternative to #define, it usually means that they are talking about C, not about C++. I wonder whether this question is tagged properly...

Get key and value of object in JavaScript?

Change your object.

var top_brands = [ 
  { key: 'Adidas', value: 100 }, 
  { key: 'Nike', value: 50 }
];

var $brand_options = $("#top-brands");

$.each(top_brands, function(brand) {
  $brand_options.append(
    $("<option />").val(brand.key).text(brand.key + " " + brand.value)
  );
});

As a rule of thumb:

  • An object has data and structure.
  • 'Adidas', 'Nike', 100 and 50 are data.
  • Object keys are structure. Using data as the object key is semantically wrong. Avoid it.

There are no semantics in {Nike: 50}. What's "Nike"? What's 50?

{key: 'Nike', value: 50} is a little better, since now you can iterate an array of these objects and values are at predictable places. This makes it easy to write code that handles them.

Better still would be {vendor: 'Nike', itemsSold: 50}, because now values are not only at predictable places, they also have meaningful names. Technically that's the same thing as above, but now a person would also understand what the values are supposed to mean.

Load json from local file with http.get() in angular 2

For Angular 5+ only preform steps 1 and 4


In order to access your file locally in Angular 2+ you should do the following (4 steps):

[1] Inside your assets folder create a .json file, example: data.json

[2] Go to your angular.cli.json (angular.json in Angular 6+) inside your project and inside the assets array put another object (after the package.json object) like this:

{ "glob": "data.json", "input": "./", "output": "./assets/" }

full example from angular.cli.json

"apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico",
        { "glob": "package.json", "input": "../", "output": "./assets/" },
        { "glob": "data.json", "input": "./", "output": "./assets/" }
      ],

Remember, data.json is just the example file we've previously added in the assets folder (you can name your file whatever you want to)

[3] Try to access your file via localhost. It should be visible within this address, http://localhost:your_port/assets/data.json

If it's not visible then you've done something incorrectly. Make sure you can access it by typing it in the URL field in your browser before proceeding to step #4.

[4] Now preform a GET request to retrieve your .json file (you've got your full path .json URL and it should be simple)

 constructor(private http: HttpClient) {}
        // Make the HTTP request:
        this.http.get('http://localhost:port/assets/data.json')
                 .subscribe(data => console.log(data));

How to randomly select an item from a list?

foo = ['a', 'b', 'c', 'd', 'e']
number_of_samples = 1

In python 2:

random_items = random.sample(population=foo, k=number_of_samples)

In python 3:

random_items = random.choices(population=foo, k=number_of_samples)

"cannot resolve symbol R" in Android Studio

I was facing this problem when I imported google-services.json file to implement Analytics. I already had global_tracker.xml file in the xml folder. During build, while merging contents from google-services.json file, the error was started occurring.

The error is resolved after removing the goolgle-services.json file.

How to stop VBA code running?

Or, if you want to avoid the use of a global variable you could use the rarely used .Tag property of the userform:

Private Sub CommandButton1_Click()
    Me.CommandButton1.Enabled = False 'Disabling button so user cannot push it
                                      'multiple times
    Me.CommandButton1.caption = "Wait..." 'Jamie's suggestion
    Me.Tag = "Cancel"
End Sub

Private Sub SomeVBASub
    If LCase(UserForm1.Tag) = "cancel" Then
        GoTo StopProcess
    Else
        'DoStuff
    End If

Exit Sub
StopProcess:
    'Here you can do some steps to be able to cancel process adequately
    'i.e. setting collections to "Nothing" deleting some files...
End Sub

ImportError: No module named BeautifulSoup

Try this from bs4 import BeautifulSoup

This might be a problem with Beautiful Soup, version 4, and the beta days. I just read this from the homepage.

Virtual network interface in Mac OS X

Here's a good guide: https://web.archive.org/web/20160301104014/http://gerrydevstory.com/2012/08/20/how-to-create-virtual-network-interface-on-mac-os-x/

Basically you select a network adapter in the Networks pane of system preferences, then click the gear to "Duplicate Service". After the service is duplicated, you manually assign an IP in one of the private address ranges. Then ping it to make sure ;)

How to create a signed APK file using Cordova command line interface?

On Mac (osx), I generated two .sh files, one for the first publication and another one for updating :

#!/bin/sh
echo "Ionic to Signed APK ---- [email protected] // Benjamin Rathelot\n"
printf "Project dir : "
read DIR
printf "Project key alias : "
read ALIAS
cd $DIR/
cordova build --release android
cd platforms/android/build/outputs/apk/
keytool -genkey -v -keystore my-release-key.keystore -alias $ALIAS -keyalg RSA -keysize 2048 -validity 10000
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore android-release-unsigned.apk $ALIAS
zipalign -v 4 android-release-unsigned.apk signedApk.apk

And to update your app:

#!/bin/sh
echo "Ionic to Signed APK ---- [email protected] // Benjamin Rathelot\n"
printf "Project dir : "
read DIR
printf "Project key alias : "
read ALIAS
cd $DIR/
cordova build --release android
cd platforms/android/build/outputs/apk/
rm signedApk.apk
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore android-release-unsigned.apk $ALIAS
zipalign -v 4 android-release-unsigned.apk signedApk.apk

Assuming you're in your home folder or a folder topping your apps folders. Make sure to set correctly chmod to use this script. Then :

./ionicToApk.sh # or whatever depending of the name of your file, in CLI

Your signed apk will be in Your App folder/platforms/android/build/outputs/apk/ as SignedApk.apk Make sure to use the correct key alias and password defined with the first script

How do I install the yaml package for Python?

There are three YAML capable packages. Syck (pip install syck) which implements the YAML 1.0 specification from 2002; PyYAML (pip install pyyaml) which follows the YAML 1.1 specification from 2004; and ruamel.yaml which follows the latest (YAML 1.2, from 2009) specification.

You can install the YAML 1.2 compatible package with pip install ruamel.yaml or if you are running a modern version of Debian/Ubuntu (or derivative) with:

sudo apt-get install python-ruamel.yaml

Count elements with jQuery

use the .size() method or .length attribute

Searching in a ArrayList with custom objects for certain strings

Use Apache CollectionUtils:

CollectionUtils.find(myList, new Predicate() {
   public boolean evaluate(Object o) {
      return name.equals(((MyClass) o).getName());
   }
}

GDB: Listing all mapped memory regions for a crashed process

You can also use info files to list all the sections of all the binaries loaded in process binary.

JavaScript equivalent to printf/String.Format

Not the most recommended function in the world, but it works.

If you need sprintf, just copy & paste this same function and change return console.log(sb) to just return sb.

_x000D_
_x000D_
printf = function(s, /*args...*/) {
    a = arguments;
    al = a.length;
    
    if (al <= 1) return -2;
    if (al >= 2 && s.toLowerCase().search(/%[a-z]/) == -1) return -1;

    sb = s;
    for (i = 1; i <= al - 1; i++) {
        sb = sb.replace(/%[a-z]/, a[i]);
    }

    return console.log(sb);
}

var someString = "Hello %s\nIt's %s:%s %s now.\nThe day is %s\n";
printf(someString, "StackOverflowUser", "5", "48", "PM", "beautiful");
_x000D_
_x000D_
_x000D_

How would you count occurrences of a string (actually a char) within a string?

string s = "HOWLYH THIS ACTUALLY WORKSH WOWH";
int count = 0;
for (int i = 0; i < s.Length; i++)
   if (s[i] == 'H') count++;

It just checks every character in the string, if the character is the character you are searching for, add one to count.

Making HTML page zoom by default

A better solution is not to make your page dependable on zoom settings. If you set limits like the one you are proposing, you are limiting accessibility. If someone cannot read your text well, they just won't be able to change that. I would use proper CSS to make it look nice in any zoom.

If your really insist, take a look at this question on how to detect zoom level using JavaScript (nightmare!): How to detect page zoom level in all modern browsers?

How to check if element exists using a lambda expression?

Try to use anyMatch of Lambda Expression. It is much better approach.

 boolean idExists = tabPane.getTabs().stream()
            .anyMatch(t -> t.getId().equals(idToCheck));

Is it possible to create a File object from InputStream

If you are using Java version 7 or higher, you can use try-with-resources to properly close the FileOutputStream. The following code use IOUtils.copy() from commons-io.

public void copyToFile(InputStream inputStream, File file) throws IOException {
    try(OutputStream outputStream = new FileOutputStream(file)) {
        IOUtils.copy(inputStream, outputStream);
    }
}  

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

I solved this problem by removing --deploy-mode cluster from spark-submit code. By default , spark submit takes client mode which has following advantage :

1. It opens up Netty HTTP server and distributes all jars to the worker nodes.
2. Driver program runs on master node , which means dedicated resources to driver process.

While in cluster mode :

 1.  It runs on worker node.
 2. All the jars need to be placed in a common folder of the cluster so that it is accessible to all the worker nodes or in folder of each worker node.

Here it's not able to access hive metastore due to unavailability of hive jar to any of the nodes in cluster. enter image description here

Removing duplicates from rows based on specific columns in an RDD/Spark DataFrame

Agree with David. To add on, it may not be the case that we want to groupBy all columns other than the column(s) in aggregate function i.e, if we want to remove duplicates purely based on a subset of columns and retain all columns in the original dataframe. So the better way to do this could be using dropDuplicates Dataframe api available in Spark 1.4.0

For reference, see: https://spark.apache.org/docs/1.4.0/api/scala/index.html#org.apache.spark.sql.DataFrame

Convert string to number field

Within Crystal, you can do it by creating a formula that uses the ToNumber function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:

If NumericText ({field}) then ToNumber ({field}) else 0

Alternatively, you might find it easier to convert the field's datatype within the query used in the report.

How to convert ASCII code (0-255) to its corresponding character?

One can iterate from a to z like this

int asciiForLowerA = 97;
int asciiForLowerZ = 122;
for(int asciiCode = asciiForLowerA; asciiCode <= asciiForLowerZ; asciiCode++){
    search(sCurrentLine, searchKey + Character.toString ((char) asciiCode));
}

How can I download a file from a URL and save it in Rails?

If you're using PaperClip, downloading from a URL is now handled automatically.

Assuming you've got something like:

class MyModel < ActiveRecord::Base
  has_attached_file :image, ...
end

On your model, just specify the image as a URL, something like this (written in deliberate longhand):

@my_model = MyModel.new
image_url = params[:image_url]
@my_model.image = URI.parse(image_url)

You'll probably want to put this in a method in your model. This will also work just fine on Heroku's temporary filesystem.

Paperclip will take it from there.

source: paperclip documentation

How to paste text to end of every line? Sublime 2

Here's the workflow I use all the time, using the keyboard only

  1. Ctrl/Cmd + A Select All
  2. Ctrl/Cmd + Shift + L Split into Lines
  3. ' Surround every line with quotes

Note that this doesn't work if there are blank lines in the selection.

How to convert an array to a string in PHP?

PHP has a built-in function implode to assign array values to string. Use it like this:

$str = implode(",", $array);

Switch case on type c#

Here's an option that stays as true I could make it to the OP's requirement to be able to switch on type. If you squint hard enough it almost looks like a real switch statement.

The calling code looks like this:

var @switch = this.Switch(new []
{
    this.Case<WebControl>(x => { /* WebControl code here */ }),
    this.Case<TextBox>(x => { /* TextBox code here */ }),
    this.Case<ComboBox>(x => { /* ComboBox code here */ }),
});

@switch(obj);

The x in each lambda above is strongly-typed. No casting required.

And to make this magic work you need these two methods:

private Action<object> Switch(params Func<object, Action>[] tests)
{
    return o =>
    {
        var @case = tests
            .Select(f => f(o))
            .FirstOrDefault(a => a != null);

        if (@case != null)
        {
            @case();
        }
    };
}

private Func<object, Action> Case<T>(Action<T> action)
{
    return o => o is T ? (Action)(() => action((T)o)) : (Action)null;
}

Almost brings tears to your eyes, right?

Nonetheless, it works. Enjoy.

Fit background image to div

If what you need is the image to have the same dimensions of the div, I think this is the most elegant solution:

background-size: 100% 100%;

If not, the answer by @grc is the most appropriated one.

Source: http://www.w3schools.com/cssref/css3_pr_background-size.asp

Access denied for root user in MySQL command-line

You mustn't have a space character between -u and the username:

mysql -uroot -p
# or
mysql --user=root --password

python: how to identify if a variable is an array or a scalar

Simply use size instead of len!

>>> from numpy import size
>>> N = [2, 3, 5]
>>> size(N)
3
>>> N = array([2, 3, 5])
>>> size(N)
3
>>> P = 5
>>> size(P)
1

How to clear or stop timeInterval in angularjs?

When you want to create interval store promise to variable:

var p = $interval(function() { ... },1000);

And when you want to stop / clear the interval simply use:

$interval.cancel(p);

Find the most frequent number in a NumPy array

You can use the following approach:

x = np.array([[2, 5, 5, 2], [2, 7, 8, 5], [2, 5, 7, 9]])
u, c = np.unique(x, return_counts=True)
print(u[c == np.amax(c)])

This will give the answer: array([2, 5])

how to convert Lower case letters to upper case letters & and upper case letters to lower case letters

Methods description:

*toLowerCase()* Returns a new string with all characters converted to lowercase.

*toUpperCase()* Returns a new string with all characters converted to uppercase.

For example:

"Welcome".toLowerCase() returns a new string, welcome

"Welcome".toUpperCase() returns a new string, WELCOME