Programs & Examples On #E71

Docker: Container keeps on restarting again on again

Try adding these params to your docker yml file

restart: "no"
  restart: always
  restart: on-failure
  restart: unless-stopped
  environment:
    POSTGRES_DB: "db_name"
    POSTGRES_HOST_AUTH_METHOD: "trust"

Final file should look something like this

postgres:
  restart: "no"
  restart: always
  restart: on-failure
  restart: unless-stopped
  image: postgres:latest
  volumes:
    - /data/postgresql:/var/lib/postgresql
  ports:
    - "5432:5432"
  environment:
    POSTGRES_DB: "db_name"
    POSTGRES_HOST_AUTH_METHOD: "trust"

Could not find method android() for arguments

My issue was inside of my app.gradle. I ran into this issue when I moved

apply plugin: "com.android.application"

from the top line to below a line with

apply from:

I switched the plugin back to the top and violá

My exact error was

Could not find method android() for arguments [dotenv_wke4apph61tdae6bfodqe7sj$_run_closure1@5d9d91a5] on project ':app' of type org.gradle.api.Project.

The top of my app.gradle now looks like this

project.ext.envConfigFiles = [
        debug: ".env",
        release: ".env",
        anothercustombuild: ".env",
]


apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"
apply plugin: "com.android.application"

How to convert an XML file to nice pandas dataframe?

You can also convert by creating a dictionary of elements and then directly converting to a data frame:

import xml.etree.ElementTree as ET
import pandas as pd

# Contents of test.xml
# <?xml version="1.0" encoding="utf-8"?> <tags>   <row Id="1" TagName="bayesian" Count="4699" ExcerptPostId="20258" WikiPostId="20257" />   <row Id="2" TagName="prior" Count="598" ExcerptPostId="62158" WikiPostId="62157" />   <row Id="3" TagName="elicitation" Count="10" />   <row Id="5" TagName="open-source" Count="16" /> </tags>

root = ET.parse('test.xml').getroot()

tags = {"tags":[]}
for elem in root:
    tag = {}
    tag["Id"] = elem.attrib['Id']
    tag["TagName"] = elem.attrib['TagName']
    tag["Count"] = elem.attrib['Count']
    tags["tags"]. append(tag)

df_users = pd.DataFrame(tags["tags"])
df_users.head()

How to download image from url

Most of the posts that I found will timeout after a second iteration. Particularly if you are looping through a bunch if images as I have been. So to improve the suggestions above here is the entire method:

public System.Drawing.Image DownloadImage(string imageUrl)
    {
        System.Drawing.Image image = null;

        try
        {
            System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(imageUrl);
            webRequest.AllowWriteStreamBuffering = true;
            webRequest.Timeout = 30000;
            webRequest.ServicePoint.ConnectionLeaseTimeout = 5000;
            webRequest.ServicePoint.MaxIdleTime = 5000;

            using (System.Net.WebResponse webResponse = webRequest.GetResponse())
            {

                using (System.IO.Stream stream = webResponse.GetResponseStream())
                {
                    image = System.Drawing.Image.FromStream(stream);
                }
            }

            webRequest.ServicePoint.CloseConnectionGroup(webRequest.ConnectionGroupName);
            webRequest = null; 
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message, ex);

        }


        return image;
    }

Saving binary data as file using JavaScript from a browser

Try

_x000D_
_x000D_
let bytes = [65,108,105,99,101,39,115,32,65,100,118,101,110,116,117,114,101];_x000D_
_x000D_
let base64data = btoa(String.fromCharCode.apply(null, bytes));_x000D_
_x000D_
let a = document.createElement('a');_x000D_
a.href = 'data:;base64,' + base64data;_x000D_
a.download = 'binFile.txt'; _x000D_
a.click();
_x000D_
_x000D_
_x000D_

I convert here binary data to base64 (for bigger data conversion use this) - during downloading browser decode it automatically and save raw data in file. 2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop working (probably due to sandbox security restrictions) - but JSFiddle version works - here

git status shows fatal: bad object HEAD

I solved this by doing git fetch. My error was because I moved my file from my main storage to my secondary storage on windows 10.

How to fix corrupted git repository?

If you have a remote configured and you have / don't care about losing some unpushed code, you can do :

git fetch && git reset --hard

Can't install via pip because of egg_info error

See this : What Python version can I use with Django?¶ https://docs.djangoproject.com/en/2.0/faq/install/

if you are using python27 you must to set django version :

try: $pip install django==1.9

You have not concluded your merge (MERGE_HEAD exists)

If you are sure that you already resolved all merge conflicts:

rm -rf .git/MERGE*

And the error will disappear.

Completely uninstall PostgreSQL 9.0.4 from Mac OSX Lion?

Incase you have multiple versions of Postgres installed on your machine. You can remove all via brew command as:

brew uninstall --force postgresql

Drop-down menu that opens up/upward with pure css

If we are use chosen dropdown list, then we can use below css(No JS/JQuery require)

<select chosen="{width: '100%'}" ng- 
   model="modelName" class="form-control input- 
   sm"
   ng- 
   options="persons.persons as 
   persons.persons for persons in 
   jsonData"
   ng- 
   change="anyFunction(anyParam)" 
   required>
   <option value=""> </option>
</select>
<style>   
.chosen-container .chosen-drop {
    border-bottom: 0;
    border-top: 1px solid #aaa;
    top: auto;
    bottom: 40px;
}

.chosen-container.chosen-with-drop .chosen-single {
    border-top-left-radius: 0px;
    border-top-right-radius: 0px;

    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;

    background-image: none;
}

.chosen-container.chosen-with-drop .chosen-drop {
    border-bottom-left-radius: 0px;
    border-bottom-right-radius: 0px;

    border-top-left-radius: 5px;
    border-top-right-radius: 5px;

    box-shadow: none;

    margin-bottom: -16px;
}
</style>

How to give a Blob uploaded as FormData a file name?

Haven't tested it, but that should alert the blobs data url:

var blob = event.clipboardData.items[0].getAsFile(), 
    form = new FormData(),
    request = new XMLHttpRequest();

var reader = new FileReader();
reader.onload = function(event) {
  alert(event.target.result); // <-- data url
};
reader.readAsDataURL(blob);

Write bytes to file

You convert the hex string to a byte array.

public static byte[] StringToByteArray(string hex) {
return Enumerable.Range(0, hex.Length)
                 .Where(x => x % 2 == 0)
                 .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                 .ToArray();
}

Credit: Jared Par

And then use WriteAllBytes to write to the file system.

How to replace a hash key with another key

For Ruby 2.5 or newer with transform_keys and delete_prefix / delete_suffix methods:

hash1 = { '_id' => 'random1' }
hash2 = { 'old_first' => '123456', 'old_second' => '234567' }
hash3 = { 'first_com' => 'google.com', 'second_com' => 'amazon.com' }

hash1.transform_keys { |key| key.delete_prefix('_') }
# => {"id"=>"random1"}
hash2.transform_keys { |key| key.delete_prefix('old_') }
# => {"first"=>"123456", "second"=>"234567"}
hash3.transform_keys { |key| key.delete_suffix('_com') }
# => {"first"=>"google.com", "second"=>"amazon.com"}

Replace forward slash "/ " character in JavaScript string?

Remove all forward slash occurrences with blank char in Javascript.

modelData = modelData.replace(/\//g, '');

How to force garbage collection in Java?

If you are running out of memory and getting an OutOfMemoryException you can try increasing the amount of heap space available to java by starting you program with java -Xms128m -Xmx512m instead of just java. This will give you an initial heap size of 128Mb and a maximum of 512Mb, which is far more than the standard 32Mb/128Mb.

Add onclick event to newly added element in JavaScript

Short answer: you want to set the handler to a function:

elemm.onclick = function() { alert('blah'); };

Slightly longer answer: you'll have to write a few more lines of code to get that to work consistently across browsers.

The fact is that even the sligthly-longer-code that might solve that particular problem across a set of common browsers will still come with problems of its own. So if you don't care about cross-browser support, go with the totally short one. If you care about it and absolutely only want to get this one single thing working, go with a combination of addEventListener and attachEvent. If you want to be able to extensively create objects and add and remove event listeners throughout your code, and want that to work across browsers, you definitely want to delegate that responsibility to a library such as jQuery.

SQL Server 2008 - Help writing simple INSERT Trigger

check this code:

CREATE TRIGGER trig_Update_Employee ON [EmployeeResult] FOR INSERT AS Begin   
    Insert into Employee (Name, Department)  
    Select Distinct i.Name, i.Department   
        from Inserted i
        Left Join Employee e on i.Name = e.Name and i.Department = e.Department
        where e.Name is null
End

Git Commit Messages: 50/72 Formatting

Regarding the “summary” line (the 50 in your formula), the Linux kernel documentation has this to say:

For these reasons, the "summary" must be no more than 70-75
characters, and it must describe both what the patch changes, as well
as why the patch might be necessary.  It is challenging to be both
succinct and descriptive, but that is what a well-written summary
should do.

That said, it seems like kernel maintainers do indeed try to keep things around 50. Here’s a histogram of the lengths of the summary lines in the git log for the kernel:

Lengths of Git summary lines (view full-sized)

There is a smattering of commits that have summary lines that are longer (some much longer) than this plot can hold without making the interesting part look like one single line. (There’s probably some fancy statistical technique for incorporating that data here but oh well… :-)

If you want to see the raw lengths:

cd /path/to/repo
git shortlog  | grep -e '^      ' | sed 's/[[:space:]]\+\(.*\)$/\1/' | awk '{print length($0)}'

or a text-based histogram:

cd /path/to/repo
git shortlog  | grep -e '^      ' | sed 's/[[:space:]]\+\(.*\)$/\1/' | awk '{lens[length($0)]++;} END {for (len in lens) print len, lens[len] }' | sort -n

Calculate row means on subset of columns

Using dplyr:

library(dplyr)

# exclude ID column then get mean
DF %>%
  transmute(ID,
            Mean = rowMeans(select(., -ID)))

Or

# select the columns to include in mean
DF %>%
  transmute(ID,
            Mean = rowMeans(select(., C1:C3)))

#   ID     Mean
# 1  A 3.666667
# 2  B 4.333333
# 3  C 3.333333
# 4  D 4.666667
# 5  E 4.333333

Correct mime type for .mp4

When uploading .mp4 file into Perl script, using CGI.pm I see it as video/mp when printing out Content-type for the uploaded file. I hope it will help someone.

When does System.getProperty("java.io.tmpdir") return "c:\temp"

On the one hand, when you call System.getProperty("java.io.tmpdir") instruction, Java calls the Win32 API's function GetTempPath. According to the MSDN :

The GetTempPath function checks for the existence of environment variables in the following order and uses the first path found:

  1. The path specified by the TMP environment variable.
  2. The path specified by the TEMP environment variable.
  3. The path specified by the USERPROFILE environment variable.
  4. The Windows directory.

On the other hand, please check the historical reasons on why TMP and TEMP coexist. It's really worth reading.

Java double.MAX_VALUE?

this states that Account.deposit(Double.MAX_VALUE); it is setting deposit value to MAX value of Double dataType.to procced for running tests.

Concatenating string and integer in python

Let's assume you want to concatenate string and integer in a situation like this:

for i in range(1,11):
   string="string"+i 

and you are getting type or concatenation error

The best way to go about it is to do something like this:

for i in range(1,11):
   print("string",i)    

This will give you concatenated results like string 1, string 2, string 3 ...etc

How to get a jqGrid cell value when editing

Try this, it will give you particular column's value

onSelectRow: function(id) {
    var rowData = jQuery(this).getRowData(id); 
    var temp= rowData['name'];//replace name with you column
    alert(temp);
}

How to split a list by comma not space

kent$  echo "Hello,World,Questions,Answers,bash shell,script"|awk -F, '{for (i=1;i<=NF;i++)print $i}'
Hello
World
Questions
Answers
bash shell
script

Can you find all classes in a package using reflection?

I put together a simple github project that solves this problem:

https://github.com/ddopson/java-class-enumerator

It should work for BOTH file-based classpaths AND for jar files.

If you run 'make' after checking out the project it will print this out:

 Cleaning...
rm -rf build/
 Building...
javac -d build/classes src/pro/ddopson/ClassEnumerator.java src/test/ClassIShouldFindOne.java src/test/ClassIShouldFindTwo.java src/test/subpkg/ClassIShouldFindThree.java src/test/TestClassEnumeration.java
 Making JAR Files...
jar cf build/ClassEnumerator_test.jar -C build/classes/ . 
jar cf build/ClassEnumerator.jar -C build/classes/ pro
 Running Filesystem Classpath Test...
java -classpath build/classes test.TestClassEnumeration
ClassDiscovery: Package: 'test' becomes Resource: 'file:/Users/Dopson/work/other/java-class-enumeration/build/classes/test'
ClassDiscovery: Reading Directory '/Users/Dopson/work/other/java-class-enumeration/build/classes/test'
ClassDiscovery: FileName 'ClassIShouldFindOne.class'  =>  class 'test.ClassIShouldFindOne'
ClassDiscovery: FileName 'ClassIShouldFindTwo.class'  =>  class 'test.ClassIShouldFindTwo'
ClassDiscovery: FileName 'subpkg'  =>  class 'null'
ClassDiscovery: Reading Directory '/Users/Dopson/work/other/java-class-enumeration/build/classes/test/subpkg'
ClassDiscovery: FileName 'ClassIShouldFindThree.class'  =>  class 'test.subpkg.ClassIShouldFindThree'
ClassDiscovery: FileName 'TestClassEnumeration.class'  =>  class 'test.TestClassEnumeration'
 Running JAR Classpath Test...
java -classpath build/ClassEnumerator_test.jar  test.TestClassEnumeration
ClassDiscovery: Package: 'test' becomes Resource: 'jar:file:/Users/Dopson/work/other/java-class-enumeration/build/ClassEnumerator_test.jar!/test'
ClassDiscovery: Reading JAR file: '/Users/Dopson/work/other/java-class-enumeration/build/ClassEnumerator_test.jar'
ClassDiscovery: JarEntry 'META-INF/'  =>  class 'null'
ClassDiscovery: JarEntry 'META-INF/MANIFEST.MF'  =>  class 'null'
ClassDiscovery: JarEntry 'pro/'  =>  class 'null'
ClassDiscovery: JarEntry 'pro/ddopson/'  =>  class 'null'
ClassDiscovery: JarEntry 'pro/ddopson/ClassEnumerator.class'  =>  class 'null'
ClassDiscovery: JarEntry 'test/'  =>  class 'null'
ClassDiscovery: JarEntry 'test/ClassIShouldFindOne.class'  =>  class 'test.ClassIShouldFindOne'
ClassDiscovery: JarEntry 'test/ClassIShouldFindTwo.class'  =>  class 'test.ClassIShouldFindTwo'
ClassDiscovery: JarEntry 'test/subpkg/'  =>  class 'null'
ClassDiscovery: JarEntry 'test/subpkg/ClassIShouldFindThree.class'  =>  class 'test.subpkg.ClassIShouldFindThree'
ClassDiscovery: JarEntry 'test/TestClassEnumeration.class'  =>  class 'test.TestClassEnumeration'
 Tests Passed. 

See also my other answer

Run Android studio emulator on AMD processor

I have a Ryzen 2600X and I am able to run the emulator without problems. Here are the tweaks I made:

*NOTE: You don't need the beta version of Android Studio or Android Emulator.

  1. Go to the MB bios and turn SVM on (CPU Virtualization).
  2. In Windows right click Windows Button => Select "Apps and Features" => "Programs and features" => "Turn Windows Features on and off"
  3. In the displayed list select Hyper-V checkbox == Make sure the subfolders are all selected. When prompted to restart, restart the PC.
  4. After restart and update instalation screen you are back in Windows and you should be able to run the Emulator.

**Note: I have selected x86_64 and plain x86 images(both API 28) from the x86 Images tab and they work just fine.

***Note: Might also check for Android Licenses if errors pop up, I had an issue because of this while using Flutter, maybe it's related to that.

How do I return a proper success/error message for JQuery .ajax() using PHP?

Some people recommend using HTTP status codes, but I rather despise that practice. e.g. If you're doing a search engine and the provided keywords have no results, the suggestion would be to return a 404 error.

However, I consider that wrong. HTTP status codes apply to the actual browser<->server connection. Everything about the connect went perfectly. The browser made a request, the server invoked your handler script. The script returned 'no rows'. Nothing in that signifies "404 page not found" - the page WAS found.

Instead, I favor divorcing the HTTP layer from the status of your server-side operations. Instead of simply returning some text in a json string, I always return a JSON data structure which encapsulates request status and request results.

e.g. in PHP you'd have

$results = array(
   'error' => false,
   'error_msg' => 'Everything A-OK',
   'data' => array(....results of request here ...)
);
echo json_encode($results);

Then in your client-side code you'd have

if (!data.error) {
   ... got data, do something with it ...
} else {
   ... invoke error handler ...
}

npm install Error: rollbackFailedOptional

I set two system environment variables -

  1. HTTP_PROXY = <_proxy_url_>
  2. HTTPS_PROXY = <_proxy_url_>

This actually worked for me.

How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?

System.setProperty("webdriver.chrome.driver",
         "D:\\Lib\\chrome_driver_latest\\chromedriver_win32\\chromedriver.exe");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--allow-running-insecure-content");
chromeOptions.addArguments("--window-size=1920x1080");
chromeOptions.addArguments("--disable-gpu"); 
chromeOptions.setHeadless(true);
ChromeDriver driver = new ChromeDriver(chromeOptions);

Why doesn't os.path.join() work in this case?

Try with new_sandbox only

os.path.join('/home/build/test/sandboxes/', todaystr, 'new_sandbox')

Put quotes around a variable string in JavaScript

You can add these single quotes with template literals:

_x000D_
_x000D_
var text = "http://example.com"_x000D_
var quoteText = `'${text}'`_x000D_
_x000D_
console.log(quoteText)
_x000D_
_x000D_
_x000D_

Docs are here. Browsers that support template literals listed here.

CSS / HTML Navigation and Logo on same line

You need to apply the logo class to the image...then float the ul

Codepen Demo

HTML

<img class="logo" src="http://i.imgur.com/hCrQkJi.png">

CSS

.navigation-bar ul {
  padding: 0px;
  margin: 0px;
  text-align: center;
  float: left;
  background: white;
}

With ng-bind-html-unsafe removed, how do I inject HTML?

You indicated that you're using Angular 1.2.0... as one of the other comments indicated, ng-bind-html-unsafe has been deprecated.

Instead, you'll want to do something like this:

<div ng-bind-html="preview_data.preview.embed.htmlSafe"></div>

In your controller, inject the $sce service, and mark the HTML as "trusted":

myApp.controller('myCtrl', ['$scope', '$sce', function($scope, $sce) {
  // ...
  $scope.preview_data.preview.embed.htmlSafe = 
     $sce.trustAsHtml(preview_data.preview.embed.html);
}

Note that you'll want to be using 1.2.0-rc3 or newer. (They fixed a bug in rc3 that prevented "watchers" from working properly on trusted HTML.)

Make iframe automatically adjust height according to the contents without using scrollbar?

I wanted to make an iframe behave like a normal page (I needed to make a fullscreen banner inside an iframe element), so here is my script:

    (function (window, undefined) {

    var frame,
        lastKnownFrameHeight = 0,
        maxFrameLoadedTries = 5,
        maxResizeCheckTries = 20;

    //Resize iframe on window resize
    addEvent(window, 'resize', resizeFrame);

    var iframeCheckInterval = window.setInterval(function () {
        maxFrameLoadedTries--;
        var frames = document.getElementsByTagName('iframe');
        if (maxFrameLoadedTries == 0 || frames.length) {
            clearInterval(iframeCheckInterval);
            frame = frames[0];
            addEvent(frame, 'load', resizeFrame);
            var resizeCheckInterval = setInterval(function () {
                resizeFrame();
                maxResizeCheckTries--;
                if (maxResizeCheckTries == 0) {
                    clearInterval(resizeCheckInterval);
                }
            }, 1000);
            resizeFrame();
        }
    }, 500);

    function resizeFrame() {
        if (frame) {
            var frameHeight = frame.contentWindow.document.body.scrollHeight;
            if (frameHeight !== lastKnownFrameHeight) {
                lastKnownFrameHeight = frameHeight;

                var viewportWidth = document.documentElement.clientWidth;
                if (document.compatMode && document.compatMode === 'BackCompat') {
                    viewportWidth = document.body.clientWidth;
                }

                frame.setAttribute('width', viewportWidth);
                frame.setAttribute('height', lastKnownFrameHeight);

                frame.style.width = viewportWidth + 'px';
                frame.style.height = frameHeight + 'px';
            }
        }
    }

    //--------------------------------------------------------------
    //  Cross-browser helpers
    //--------------------------------------------------------------

    function addEvent(elem, event, fn) {
        if (elem.addEventListener) {
            elem.addEventListener(event, fn, false);
        } else {
            elem.attachEvent("on" + event, function () {
                return (fn.call(elem, window.event));
            });
        }
    }

})(window);

The functions are self-explanatory and have comments to further explain their purpose.

Unable to open debugger port in IntelliJ IDEA

All the other solutions unfortunately did not work. This is what worked for me . I simply changed the debugger port to some other port number.

Intelij-> preferences->Build, execution, deployment ->Debugger-> Built in server->port(change value )

enter image description here

Open web in new tab Selenium + Python

The other solutions do not work for chrome driver v83.

Instead, it works as follows, suppose there is only 1 opening tab:

driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[1])
driver.get("https://www.example.com")

If there are already more than 1 opening tabs, you should first get the index of the last newly-created tab and switch to the tab before calling the url (Credit to tylerl) :

driver.execute_script("window.open('');")
driver.switch_to.window(len(driver.window_handles)-1)
driver.get("https://www.example.com")

Changing font size and direction of axes text in ggplot2

Use theme():

d <- data.frame(x=gl(10, 1, 10, labels=paste("long text label ", letters[1:10])), y=rnorm(10))
ggplot(d, aes(x=x, y=y)) + geom_point() +
theme(text = element_text(size=20))

Inline <style> tags vs. inline css properties

To answer your direct question: neither of these is the preferred method. Use a separate file.

Inline styles should only be used as a last resort, or set by Javascript code. Inline styles have the highest level of specificity, so override your actual stylesheets. This can make them hard to control (you should avoid !important as well for the same reason).

An embedded <style> block is not recommended, because you lose the browser's ability to cache the stylesheet across multiple pages on your site.

So in short, wherever possible, you should put your styles into a separate CSS file.

Django CSRF check failing with an Ajax POST request

Here's a less verbose solution provided by Django:

<script type="text/javascript">
// using jQuery
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
// set csrf header
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

// Ajax call here
$.ajax({
    url:"{% url 'members:saveAccount' %}",
    data: fd,
    processData: false,
    contentType: false,
    type: 'POST',
    success: function(data) {
        alert(data);
        }
    });
</script>

Source: https://docs.djangoproject.com/en/1.11/ref/csrf/

What's the meaning of exception code "EXC_I386_GPFLT"?

You can often get information from the header files. For example:

$ cd /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk
$ find usr -name \*.h -exec fgrep -l EXC_I386_GPFLT {} \;
usr/include/mach/i386/exception.h
^C
$ more usr/include/mach/i386/exception.h
....
#define EXC_I386_GPFLT          13      /* general protection fault     */

OK, so it's a general protection fault (as its name suggests anyway). Googling "i386 general protection fault" yields many hits, but this looks interesting:

Memory protection is also implemented using the segment descriptors. First, the processor checks whether a value loaded in a segment register references a valid descriptor. Then it checks that every linear address calculated actually lies within the segment. Also, the type of access (read, write, or execute) is checked against the information in the segment descriptor. Whenever one of these checks fails, exception (interrupt) 13 (hex 0D) is raised. This exception is called a General Protection Fault (GPF).

That 13 matches what we saw in the header files, so it looks like the same thing. However from the application programmer's point-of-view, it just means we're referencing memory we shouldn't be, and it's doesn't really matter how it's implemented on the hardware.

MySQL - select data from database between two dates

Another alternative is to use DATE() function on the left hand operand as shown below

SELECT users.* FROM users WHERE DATE(created_at) BETWEEN '2011-12-01' AND '2011-12-06'

 

AngularJS : Why ng-bind is better than {{}} in angular?

According to Angular Doc:
Since ngBind is an element attribute, it makes the bindings invisible to the user while the page is loading... it's the main difference...

Basically until every dom elements not loaded, we can not see them and because ngBind is attribute on the element, it waits until the doms come into play... more info below

ngBind
- directive in module ng

The ngBind attribute tells AngularJS to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes.

Typically, you don't use ngBind directly, but instead you use the double curly markup like {{ expression }} which is similar but less verbose.

It is preferable to use ngBind instead of {{ expression }} if a template is momentarily displayed by the browser in its raw state before AngularJS compiles it. Since ngBind is an element attribute, it makes the bindings invisible to the user while the page is loading.

An alternative solution to this problem would be using the ngCloak directive. visit here

for more info about the ngbind visit this page: https://docs.angularjs.org/api/ng/directive/ngBind

You could do something like this as attribute, ng-bind:

<div ng-bind="my.name"></div>

or do interpolation as below:

<div>{{my.name}}</div>

or this way with ng-cloak attributes in AngularJs:

<div id="my-name" ng-cloak>{{my.name}}</div>

ng-cloak avoid flashing on the dom and wait until all be ready! this is equal to ng-bind attribute...

How can I check if a command exists in a shell script?

Check if a program exists from a Bash script covers this very well. In any shell script, you're best off running command -v $command_name for testing if $command_name can be run. In bash you can use hash $command_name, which also hashes the result of any path lookup, or type -P $binary_name if you only want to see binaries (not functions etc.)

Clear a terminal screen for real

Use the following command to do a clear screen instead of merely adding new lines ...

printf "\033c"

yes that's a 'printf' on the bash prompt.

You will probably want to define an alias though...

alias cls='printf "\033c"'

Explanation

\033 == \x1B == 27 == ESC

So this becomes <ESC>c which is the VT100 escape code for resetting the terminal. Here is some more information on terminal escape codes.

Edit

Here are a few other ways of doing it...

printf "\ec" #\e is ESC in bash
echo -en "\ec" #thanks @Jonathon Reinhart.
# -e    Enable interpretation of of backslash escapes
# -n    Do not output a new line

KDE

The above does not work on the KDE console (called Konsole) but there is hope! Use the following sequence of commands to clear the screen and the scroll-back buffer...

clear && echo -en "\e[3J"

Or perhaps use the following alias on KDE...

alias cls='clear && echo -en "\e[3J"'

I got the scroll-back clearing command from here.

Convert integer to hex and hex to integer

Actually, the built-in function is named master.dbo.fn_varbintohexstr.

So, for example:

SELECT 100, master.dbo.fn_varbintohexstr(100)

Gives you

100 0x00000064

PHP: Split a string in to an array foreach char

you can convert a string to array with str_split and use foreach

$chars = str_split($str);
foreach($chars as $char){
    // your code
}

How to add a file to the last commit in git?

Yes, there's a command git commit --amend which is used to "fix" last commit.

In your case it would be called as:

git add the_left_out_file
git commit --amend --no-edit

The --no-edit flag allow to make amendment to commit without changing commit message.

EDIT: Warning You should never amend public commits, that you already pushed to public repository, because what amend does is actually removing from history last commit and creating new commit with combined changes from that commit and new added when amending.

Adding an assets folder in Android Studio

According to new Gradle based build system. We have to put assets under main folder.

Or simply right click on your project and create it like

File > New > folder > assets Folder

How do I get the Date & Time (VBS)

This is an old question but alot of the answers in here use VB or VBA. The tag says vbscript (which is how I got here).

The answers here got kind of muddled since VB is super broad where you can have so many applications of it. My answer is solely on vbscript and accomplishes my case of formatting in YYYYMMDD in vbscript

Sharing what I've learned:

  1. There are all the DateTime functions in vbscript defined here so you can mix-n-match to get the result that you want
  2. What I needed was to get the current date and format it in YYYYMMDD to do that I just needed to concat DatePart like so for the current Date: date = DatePart("yyyy",Date) & DatePart("m",Date) & DatePart("d",Date)

That's all, I hope this helps someone.

How to check ASP.NET Version loaded on a system?

You can use

<%
Response.Write("Version: " + System.Environment.Version.ToString());
%>

That will get the currently running version. You can check the registry for all installed versions at:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP

How to have Ellipsis effect on Text

Use the numberOfLines parameter on a Text component:

<Text numberOfLines={1}>long long long long text<Text>

Will produce:

long long long…

(Assuming you have short width container.)


Use the ellipsizeMode parameter to move the ellipsis to the head or middle. tail is the default value.

<Text numberOfLines={1} ellipsizeMode='head'>long long long long text<Text>

Will produce:

…long long text

NOTE: The Text component should also include style={{ flex: 1 }} when the ellipsis needs to be applied relative to the size of its container. Useful for row layouts, etc.

How to Set Selected value in Multi-Value Select in Jquery-Select2.?

no need to do so many things. for set value using multiple select2 var selectedvalue="1,2,3"; //if first 3 products are selected. $('#ddlProduct').val(selectedvalue);

Argument Exception "Item with Same Key has already been added"

As others have said, you are adding the same key more than once. If this is a NOT a valid scenario, then check Jdinklage Morgoone's answer (which only saves the first value found for a key), or, consider this workaround (which only saves the last value found for a key):

// This will always overwrite the existing value if one is already stored for this key
rct3Features[items[0]] = items[1];

Otherwise, if it is valid to have multiple values for a single key, then you should consider storing your values in a List<string> for each string key.

For example:

var rct3Features = new Dictionary<string, List<string>>();
var rct4Features = new Dictionary<string, List<string>>();

foreach (string line in rct3Lines)
{
    string[] items = line.Split(new String[] { " " }, 2, StringSplitOptions.None);

    if (!rct3Features.ContainsKey(items[0]))
    {
        // No items for this key have been added, so create a new list
        // for the value with item[1] as the only item in the list
        rct3Features.Add(items[0], new List<string> { items[1] });
    }
    else
    {
        // This key already exists, so add item[1] to the existing list value
        rct3Features[items[0]].Add(items[1]);
    }
}

// To display your keys and values (testing)
foreach (KeyValuePair<string, List<string>> item in rct3Features)
{
    Console.WriteLine("The Key: {0} has values:", item.Key);
    foreach (string value in item.Value)
    {
        Console.WriteLine(" - {0}", value);
    }
}

Object does not support item assignment error

Another way would be adding __getitem__, __setitem__ function

def __getitem__(self, key):
    return getattr(self, key)

You can use self[key] to access now.

How can I find WPF controls by name or type?

Try this

<TextBlock x:Name="txtblock" FontSize="24" >Hai Welcom to this page
</TextBlock>

Code Behind

var txtblock = sender as Textblock;
txtblock.Foreground = "Red"

How do I merge two dictionaries in a single expression (taking union of dictionaries)?

In a follow-up answer, you asked about the relative performance of these two alternatives:

z1 = dict(x.items() + y.items())
z2 = dict(x, **y)

On my machine, at least (a fairly ordinary x86_64 running Python 2.5.2), alternative z2 is not only shorter and simpler but also significantly faster. You can verify this for yourself using the timeit module that comes with Python.

Example 1: identical dictionaries mapping 20 consecutive integers to themselves:

% python -m timeit -s 'x=y=dict((i,i) for i in range(20))' 'z1=dict(x.items() + y.items())'
100000 loops, best of 3: 5.67 usec per loop
% python -m timeit -s 'x=y=dict((i,i) for i in range(20))' 'z2=dict(x, **y)' 
100000 loops, best of 3: 1.53 usec per loop

z2 wins by a factor of 3.5 or so. Different dictionaries seem to yield quite different results, but z2 always seems to come out ahead. (If you get inconsistent results for the same test, try passing in -r with a number larger than the default 3.)

Example 2: non-overlapping dictionaries mapping 252 short strings to integers and vice versa:

% python -m timeit -s 'from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z1=dict(x.items() + y.items())'
1000 loops, best of 3: 260 usec per loop
% python -m timeit -s 'from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z2=dict(x, **y)'               
10000 loops, best of 3: 26.9 usec per loop

z2 wins by about a factor of 10. That's a pretty big win in my book!

After comparing those two, I wondered if z1's poor performance could be attributed to the overhead of constructing the two item lists, which in turn led me to wonder if this variation might work better:

from itertools import chain
z3 = dict(chain(x.iteritems(), y.iteritems()))

A few quick tests, e.g.

% python -m timeit -s 'from itertools import chain; from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z3=dict(chain(x.iteritems(), y.iteritems()))'
10000 loops, best of 3: 66 usec per loop

lead me to conclude that z3 is somewhat faster than z1, but not nearly as fast as z2. Definitely not worth all the extra typing.

This discussion is still missing something important, which is a performance comparison of these alternatives with the "obvious" way of merging two lists: using the update method. To try to keep things on an equal footing with the expressions, none of which modify x or y, I'm going to make a copy of x instead of modifying it in-place, as follows:

z0 = dict(x)
z0.update(y)

A typical result:

% python -m timeit -s 'from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z0=dict(x); z0.update(y)'
10000 loops, best of 3: 26.9 usec per loop

In other words, z0 and z2 seem to have essentially identical performance. Do you think this might be a coincidence? I don't....

In fact, I'd go so far as to claim that it's impossible for pure Python code to do any better than this. And if you can do significantly better in a C extension module, I imagine the Python folks might well be interested in incorporating your code (or a variation on your approach) into the Python core. Python uses dict in lots of places; optimizing its operations is a big deal.

You could also write this as

z0 = x.copy()
z0.update(y)

as Tony does, but (not surprisingly) the difference in notation turns out not to have any measurable effect on performance. Use whichever looks right to you. Of course, he's absolutely correct to point out that the two-statement version is much easier to understand.

How can you flush a write using a file descriptor?

It sounds like what you are looking for is the fsync() function (or fdatasync()?), or you could use the O_SYNC flag in your open() call.

What is the optimal way to compare dates in Microsoft SQL server?

You could add a calculated column that includes only the date without the time. Between the two options, I'd go with the BETWEEN operator because it's 'cleaner' to me and should make better use of indexes. Comparing execution plans would seem to indicate that BETWEEN would be faster; however, in actual testing they performed the same.

CSS selector for text input fields?

I had input type text field in a table row field. I am targeting it with code

.admin_table input[type=text]:focus
{
    background-color: #FEE5AC;
}

PHP compare time

$ThatTime ="14:08:10";
if (time() >= strtotime($ThatTime)) {
  echo "ok";
}

A solution using DateTime (that also regards the timezone).

$dateTime = new DateTime($ThatTime);
if ($dateTime->diff(new DateTime)->format('%R') == '+') {
  echo "OK";
}

http://php.net/datetime.diff

Insert Picture into SQL Server 2005 Image Field using only SQL

CREATE TABLE Employees
(
    Id int,
    Name varchar(50) not null,
    Photo varbinary(max) not null
)


INSERT INTO Employees (Id, Name, Photo) 
SELECT 10, 'John', BulkColumn 
FROM Openrowset( Bulk 'C:\photo.bmp', Single_Blob) as EmployeePicture

Giving UIView rounded corners

As described in this blog post, here is a method to round the corners of a UIView:

+(void)roundView:(UIView *)view onCorner:(UIRectCorner)rectCorner radius:(float)radius
{
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds
                                                   byRoundingCorners:rectCorner
                                                         cornerRadii:CGSizeMake(radius, radius)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    [view.layer setMask:maskLayer];
    [maskLayer release];
}

The cool part about it is that you can select which corners you want rounded up.

Convert UTC Epoch to local date

Considering, you have epoch_time available,

// for eg. epoch_time = 1487086694.213
var date = new Date(epoch_time * 1000); // multiply by 1000 for milliseconds
var date_string = date.toLocaleString('en-GB');  // 24 hour format

How to style the UL list to a single line

HTML code:

<ul class="list">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

CSS code:

ul.list li{
  width: auto;
  float: left;
}

How to tell bash that the line continues on the next line

The character is a backslash \

From the bash manual:

The backslash character ‘\’ may be used to remove any special meaning for the next character read and for line continuation.

WCF - How to Increase Message Size Quota

You'll want something like this to increase the message size quotas, in the App.config or Web.config file:

<bindings>
    <basicHttpBinding>
        <binding name="basicHttp" allowCookies="true"
                 maxReceivedMessageSize="20000000" 
                 maxBufferSize="20000000"
                 maxBufferPoolSize="20000000">
            <readerQuotas maxDepth="32" 
                 maxArrayLength="200000000"
                 maxStringContentLength="200000000"/>
        </binding>
    </basicHttpBinding>
</bindings>

And use the binding name in your endpoint configuration e.g.

...
bindingConfiguration="basicHttp"
...

The justification for the values is simple, they are sufficiently large to accommodate most messages. You can tune that number to fit your needs. The low default value is basically there to prevent DOS type attacks. Making it 20000000 would allow for a distributed DOS attack to be effective, the default size of 64k would require a very large number of clients to overpower most servers these days.

How do I make a matrix from a list of vectors in R?

The built-in matrix function has the nice option to enter data byrow. Combine that with an unlist on your source list will give you a matrix. We also need to specify the number of rows so it can break up the unlisted data. That is:

> matrix(unlist(a), byrow=TRUE, nrow=length(a) )
      [,1] [,2] [,3] [,4] [,5] [,6]
 [1,]    1    1    2    3    4    5
 [2,]    2    1    2    3    4    5
 [3,]    3    1    2    3    4    5
 [4,]    4    1    2    3    4    5
 [5,]    5    1    2    3    4    5
 [6,]    6    1    2    3    4    5
 [7,]    7    1    2    3    4    5
 [8,]    8    1    2    3    4    5
 [9,]    9    1    2    3    4    5
[10,]   10    1    2    3    4    5

SQL Server command line backup statement

I am using SQL Server 2005 Express, and I had to enable Named Pipes connection to be able to backup from the Windows Command. My final script is this:

@echo off
set DB_NAME=Your_DB_Name
set BK_FILE=D:\DB_Backups\%DB_NAME%.bak
set DB_HOSTNAME=Your_DB_Hostname
echo.
echo.
echo Backing up %DB_NAME% to %BK_FILE%...
echo.
echo.
sqlcmd -E -S np:\\%DB_HOSTNAME%\pipe\MSSQL$SQLEXPRESS\sql\query -d master -Q "BACKUP DATABASE [%DB_NAME%] TO DISK = N'%BK_FILE%' WITH INIT , NOUNLOAD , NAME = N'%DB_NAME% backup', NOSKIP , STATS = 10, NOFORMAT"
echo.
echo Done!
echo.

It's working just fine here!!

"Undefined reference to" template class constructor

This link explains where you're going wrong:

[35.12] Why can't I separate the definition of my templates class from its declaration and put it inside a .cpp file?

Place the definition of your constructors, destructors methods and whatnot in your header file, and that will correct the problem.

This offers another solution:

How can I avoid linker errors with my template functions?

However this requires you to anticipate how your template will be used and, as a general solution, is counter-intuitive. It does solve the corner case though where you develop a template to be used by some internal mechanism, and you want to police the manner in which it is used.

Write a function that returns the longest palindrome in a given string

my solution is :

static string GetPolyndrom(string str)
{
    string Longest = "";

    for (int i = 0; i < str.Length; i++)
    {
        if ((str.Length - 1 - i) < Longest.Length)
        {
            break;
        }
        for (int j = str.Length - 1; j > i; j--)
        {
            string str2 = str.Substring(i, j - i + 1);
            if (str2.Length > Longest.Length)
            {
                if (str2 == str2.Reverse())
                {
                    Longest = str2;
                }
            }
            else
            {
                break;
            }
        }

    }
    return Longest;
}

Illegal Character when trying to compile java code

Even I was facing this issue as am using notepad++ to code. It is very convenient to type the code in notepad++. However after compiling I get an error " error: illegal character: '\u00bb'". Solution : Start writing the code in older version of notepad(which will be there by default in your PC) and save it. Later the modifications can be done using notepad++. It works!!!

php - push array into array - key issue

first convert your array too JSON

while($query->fetch()){
   $col[] = json_encode($row,JSON_UNESCAPED_UNICODE);
}

then vonvert back it to array

foreach($col as &$array){
   $array = json_decode($array,true);
}

good luck

Powershell: count members of a AD group

Every response has missed one detail. What if the group only has 1 user.

$count = @(get-adgroupmember $group).count

Put the command in the @() wrapper so that the result is an array no matter what, so even if it is 1 item, you get a count.

Parsing CSV / tab-delimited txt file with Python

Although there is nothing wrong with the other solutions presented, you could simplify and greatly escalate your solutions by using python's excellent library pandas.

Pandas is a library for handling data in Python, preferred by many Data Scientists.

Pandas has a simplified CSV interface to read and parse files, that can be used to return a list of dictionaries, each containing a single line of the file. The keys will be the column names, and the values will be the ones in each cell.

In your case:

    import pandas

    def create_dictionary(filename):
        my_data = pandas.DataFrame.from_csv(filename, sep='\t', index_col=False)
        # Here you can delete the dataframe columns you don't want!
        del my_data['B']
        del my_data['D']
        # ...
        # Now you transform the DataFrame to a list of dictionaries
        list_of_dicts = [item for item in my_data.T.to_dict().values()]
        return list_of_dicts

# Usage:
x = create_dictionary("myfile.csv")

Angular window resize event

I know this was asked a long time ago, but there is a better way to do this now! I'm not sure if anyone will see this answer though. Obviously your imports:

import { fromEvent, Observable, Subscription } from "rxjs";

Then in your component:

resizeObservable$: Observable<Event>
resizeSubscription$: Subscription

ngOnInit() {
    this.resizeObservable$ = fromEvent(window, 'resize')
    this.resizeSubscription$ = this.resizeObservable$.subscribe( evt => {
      console.log('event: ', evt)
    })
}

Then be sure to unsubscribe on destroy!

ngOnDestroy() {
    this.resizeSubscription$.unsubscribe()
}

mongoError: Topology was destroyed

I was struggling with this for some time - As you can see from other answers, the issue can be very different.

The easiest way to find out whats causing is this is to turn on loggerLevel: 'info' in the options

Simplest way to detect keypresses in javascript

Use event.key and modern JS!

No number codes anymore. You can use "Enter", "ArrowLeft", "r", or any key name directly, making your code far more readable.

NOTE: The old alternatives (.keyCode and .which) are Deprecated.

document.addEventListener("keypress", function onEvent(event) {
    if (event.key === "ArrowLeft") {
        // Move Left
    }
    else if (event.key === "Enter") {
        // Open Menu...
    }
});

Mozilla Docs

Supported Browsers

How do you create a UIImage View Programmatically - Swift

First create UIImageView then add image in UIImageView .

    var imageView : UIImageView
    imageView  = UIImageView(frame:CGRectMake(10, 50, 100, 300));
    imageView.image = UIImage(named:"image.jpg")
    self.view.addSubview(imageView)

Converting unix timestamp string to readable date

For a human readable timestamp from a UNIX timestamp, I have used this in scripts before:

import os, datetime

datetime.datetime.fromtimestamp(float(os.path.getmtime("FILE"))).strftime("%B %d, %Y")

Output:

'December 26, 2012'

Printing Lists as Tabular Data

I would try to loop through the list and use a CSV formatter to represent the data you want.

You can specify tabs, commas, or any other char as the delimiter.

Otherwise, just loop through the list and print "\t" after each element

http://docs.python.org/library/csv.html

How to fix homebrew permissions?

In my case, I has having problems removing and reinstalling SaltStack.

After running:

ls -lah /usr/local/Cellar/salt/

I noticed that the group owner was "staff". (BTW, I'm running macOS Mojave version 10.14.3.) The staff group could be related to my workplace configuration, but I don't really know. Regardless, I preserved the group to prevent myself from breaking anything further.

I then ran:

sudo chown -R "$USER":staff /usr/local/Cellar/salt/

After that, I was successfully able to remove it with this command (not as root):

brew uninstall --force salt

How to shrink temp tablespace in oracle?

You should have written what version of Oracle you use. You most likely use something else than Oracle 11g, that's why you can't shrink a temp tablespace.

Alternatives:

1) alter database tempfile '[your_file]' resize 128M; which will probably fail
2) Drop and recreate the tablespace. If the temporary tablespace you want to shrink is your default temporary tablespace, you may have to first create a new temporary tablespace, set it as the default temporary tablespace then drop your old default temporary tablespace and recreate it. Afterwards drop the second temporary table created. 3) For Oracle 9i and higher you could just drop the tempfile(s) and add a new one(s)

Everything is described here in great detail.


See this link: http://databaseguide.blogspot.com/2008/06/resizing-temporary-tablespace.html
It was already linked, but maybe you missed it, so here it is again.

Regex Letters, Numbers, Dashes, and Underscores

Depending on your regex variant, you might be able to do simply this:

([\w-]+)

Also, you probably don't need the parentheses unless this is part of a larger expression.

Debugging with command-line parameters in Visual Studio

Microsoft Visual Studio Ultima 2013.

You can just go to the DEBUG menu ? Main Properties ? Configuration properties ? Debugging and then you will see the box for the command line arguments.

Actually, you can set the same input arguments for all the different configurations and not only for debugging.

From the pull down menu of configuration select: All Configurations and insert the input arguments (each argument separated by space).

Now, you can execute your program in different modes without having to change the input arguments every time.

Is there a way to delete created variables, functions, etc from the memory of the interpreter?

Yes. There is a simple way to remove everything in iPython. In iPython console, just type:

%reset

Then system will ask you to confirm. Press y. If you don't want to see this prompt, simply type:

%reset -f

This should work..

SQL-Server: The backup set holds a backup of a database other than the existing

Same issue with me.The solution for me is:

  1. Right click on the database.
  2. Select tasks, select restore database.
  3. Click options on the left hand side.
  4. Check first option OverWrite the existing database(WITH REPLACE).
  5. Go to General, select source and destination database.
  6. Click OK, that's it

Build fails with "Command failed with a nonzero exit code"

I got the same error when linking separate storyboards. The error, "Command CompileSwiftSources failed with a nonzero exit code." is shown because I simply forgot to set the view controller inside the second storyboard that I am linking as 'an initial view controller'.

How do I read configuration settings from Symfony2 config.yml?

I have to add to the answer of douglas, you can access the global config, but symfony translates some parameters, for example:

# config.yml
... 
framework:
    session:
        domain: 'localhost'
...

are

$this->container->parameters['session.storage.options']['domain'];

You can use var_dump to search an specified key or value.

Should I use PATCH or PUT in my REST API?

The PATCH method is the correct choice here as you're updating an existing resource - the group ID. PUT should only be used if you're replacing a resource in its entirety.

Further information on partial resource modification is available in RFC 5789. Specifically, the PUT method is described as follows:

Several applications extending the Hypertext Transfer Protocol (HTTP) require a feature to do partial resource modification. The existing HTTP PUT method only allows a complete replacement of a document. This proposal adds a new HTTP method, PATCH, to modify an existing HTTP resource.

Invalid column count in CSV input on line 1 Error

The final column of my database (it's column F in the spreadsheet) is not used and therefore empty. When I imported the excel CSV file I got the "column count" error.

This is because excel was only saving the columns I use. A-E

Adding a 0 to the first row in F solved the problem, then I deleted it after upload was successful.

Hope this helps and saves someone else time and loss of hair :)

Running an outside program (executable) in Python?

If using Python 2.7 or higher (especially prior to Python 3.5) you can use the following:

import subprocess
  • subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False) Runs the command described by args. Waits for command to complete, then returns the returncode attribute.
  • subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False) Runs command with arguments. Waits for command to complete. If the return code was zero then returns, otherwise raises CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute

Example: subprocess.check_call([r"C:\pathToYourProgram\yourProgram.exe", "your", "arguments", "comma", "separated"])

In regular Python strings, the \U character combination signals a extended Unicode code point escape.

Here is the link to the documentation: http://docs.python.org/3.2/library/subprocess.html

For Python 3.5+ you can now use run() in many cases: https://docs.python.org/3.5/library/subprocess.html#subprocess.run

NoClassDefFoundError on Maven dependency

By default, Maven doesn't bundle dependencies in the JAR file it builds, and you're not providing them on the classpath when you're trying to execute your JAR file at the command-line. This is why the Java VM can't find the library class files when trying to execute your code.

You could manually specify the libraries on the classpath with the -cp parameter, but that quickly becomes tiresome.

A better solution is to "shade" the library code into your output JAR file. There is a Maven plugin called the maven-shade-plugin to do this. You need to register it in your POM, and it will automatically build an "uber-JAR" containing your classes and the classes for your library code too when you run mvn package.

To simply bundle all required libraries, add the following to your POM:

<project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>3.2.4</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  ...
</project>

Once this is done, you can rerun the commands you used above:

$ mvn package
$ java -cp target/bil138_4-0.0.1-SNAPSHOT.jar tr.edu.hacettepe.cs.b21127113.bil138_4.App

If you want to do further configuration of the shade plugin in terms of what JARs should be included, specifying a Main-Class for an executable JAR file, and so on, see the "Examples" section on the maven-shade-plugin site.

Localhost : 404 not found

I had the same problem and here is how it worked for me :

1) Open XAMPP control panel.

2)On the right top corner go to config > Service and Port setting and change the port (I did 81 from 80).

3)Open config in Apache just right(next) to Apache admin Option and click on that and select first one (httpd.conf) it will open in the notepad.

4) There you find port listen 80 and replace it with 81 in all place and save the file.

5) Now restart Apache and MYSql

6) Now type following in Browser : http://localhost:81/phpmyadmin/

I hope this works.

HttpListener Access Denied

Can I make it run without admin mode? if yes how? If not how can I make the app change to admin mode after start running?

You can't, it has to start with elevated privileges. You can restart it with the runas verb, which will prompt the user to switch to admin mode

static void RestartAsAdmin()
{
    var startInfo = new ProcessStartInfo("yourApp.exe") { Verb = "runas" };
    Process.Start(startInfo);
    Environment.Exit(0);
}

EDIT: actually, that's not true; HttpListener can run without elevated privileges, but you need to give permission for the URL on which you want to listen. See Darrel Miller's answer for details.

In practice, what are the main uses for the new "yield from" syntax in Python 3.3?

Let's get one thing out of the way first. The explanation that yield from g is equivalent to for v in g: yield v does not even begin to do justice to what yield from is all about. Because, let's face it, if all yield from does is expand the for loop, then it does not warrant adding yield from to the language and preclude a whole bunch of new features from being implemented in Python 2.x.

What yield from does is it establishes a transparent bidirectional connection between the caller and the sub-generator:

  • The connection is "transparent" in the sense that it will propagate everything correctly too, not just the elements being generated (e.g. exceptions are propagated).

  • The connection is "bidirectional" in the sense that data can be both sent from and to a generator.

(If we were talking about TCP, yield from g might mean "now temporarily disconnect my client's socket and reconnect it to this other server socket".)

BTW, if you are not sure what sending data to a generator even means, you need to drop everything and read about coroutines first—they're very useful (contrast them with subroutines), but unfortunately lesser-known in Python. Dave Beazley's Curious Course on Coroutines is an excellent start. Read slides 24-33 for a quick primer.

Reading data from a generator using yield from

def reader():
    """A generator that fakes a read from a file, socket, etc."""
    for i in range(4):
        yield '<< %s' % i

def reader_wrapper(g):
    # Manually iterate over data produced by reader
    for v in g:
        yield v

wrap = reader_wrapper(reader())
for i in wrap:
    print(i)

# Result
<< 0
<< 1
<< 2
<< 3

Instead of manually iterating over reader(), we can just yield from it.

def reader_wrapper(g):
    yield from g

That works, and we eliminated one line of code. And probably the intent is a little bit clearer (or not). But nothing life changing.

Sending data to a generator (coroutine) using yield from - Part 1

Now let's do something more interesting. Let's create a coroutine called writer that accepts data sent to it and writes to a socket, fd, etc.

def writer():
    """A coroutine that writes data *sent* to it to fd, socket, etc."""
    while True:
        w = (yield)
        print('>> ', w)

Now the question is, how should the wrapper function handle sending data to the writer, so that any data that is sent to the wrapper is transparently sent to the writer()?

def writer_wrapper(coro):
    # TBD
    pass

w = writer()
wrap = writer_wrapper(w)
wrap.send(None)  # "prime" the coroutine
for i in range(4):
    wrap.send(i)

# Expected result
>>  0
>>  1
>>  2
>>  3

The wrapper needs to accept the data that is sent to it (obviously) and should also handle the StopIteration when the for loop is exhausted. Evidently just doing for x in coro: yield x won't do. Here is a version that works.

def writer_wrapper(coro):
    coro.send(None)  # prime the coro
    while True:
        try:
            x = (yield)  # Capture the value that's sent
            coro.send(x)  # and pass it to the writer
        except StopIteration:
            pass

Or, we could do this.

def writer_wrapper(coro):
    yield from coro

That saves 6 lines of code, make it much much more readable and it just works. Magic!

Sending data to a generator yield from - Part 2 - Exception handling

Let's make it more complicated. What if our writer needs to handle exceptions? Let's say the writer handles a SpamException and it prints *** if it encounters one.

class SpamException(Exception):
    pass

def writer():
    while True:
        try:
            w = (yield)
        except SpamException:
            print('***')
        else:
            print('>> ', w)

What if we don't change writer_wrapper? Does it work? Let's try

# writer_wrapper same as above

w = writer()
wrap = writer_wrapper(w)
wrap.send(None)  # "prime" the coroutine
for i in [0, 1, 2, 'spam', 4]:
    if i == 'spam':
        wrap.throw(SpamException)
    else:
        wrap.send(i)

# Expected Result
>>  0
>>  1
>>  2
***
>>  4

# Actual Result
>>  0
>>  1
>>  2
Traceback (most recent call last):
  ... redacted ...
  File ... in writer_wrapper
    x = (yield)
__main__.SpamException

Um, it's not working because x = (yield) just raises the exception and everything comes to a crashing halt. Let's make it work, but manually handling exceptions and sending them or throwing them into the sub-generator (writer)

def writer_wrapper(coro):
    """Works. Manually catches exceptions and throws them"""
    coro.send(None)  # prime the coro
    while True:
        try:
            try:
                x = (yield)
            except Exception as e:   # This catches the SpamException
                coro.throw(e)
            else:
                coro.send(x)
        except StopIteration:
            pass

This works.

# Result
>>  0
>>  1
>>  2
***
>>  4

But so does this!

def writer_wrapper(coro):
    yield from coro

The yield from transparently handles sending the values or throwing values into the sub-generator.

This still does not cover all the corner cases though. What happens if the outer generator is closed? What about the case when the sub-generator returns a value (yes, in Python 3.3+, generators can return values), how should the return value be propagated? That yield from transparently handles all the corner cases is really impressive. yield from just magically works and handles all those cases.

I personally feel yield from is a poor keyword choice because it does not make the two-way nature apparent. There were other keywords proposed (like delegate but were rejected because adding a new keyword to the language is much more difficult than combining existing ones.

In summary, it's best to think of yield from as a transparent two way channel between the caller and the sub-generator.

References:

  1. PEP 380 - Syntax for delegating to a sub-generator (Ewing) [v3.3, 2009-02-13]
  2. PEP 342 - Coroutines via Enhanced Generators (GvR, Eby) [v2.5, 2005-05-10]

`ui-router` $stateParams vs. $state.params

EDIT: This answer is correct for version 0.2.10. As @Alexander Vasilyev pointed out it doesn't work in version 0.2.14.

Another reason to use $state.params is when you need to extract query parameters like this:

$stateProvider.state('a', {
  url: 'path/:id/:anotherParam/?yetAnotherParam',
  controller: 'ACtrl',
});

module.controller('ACtrl', function($stateParams, $state) {
  $state.params; // has id, anotherParam, and yetAnotherParam
  $stateParams;  // has id and anotherParam
}

Downloading a file from spring controllers

This can be a useful answer.

Is it ok to export data as pdf format in frontend?

Extending to this, adding content-disposition as an attachment(default) will download the file. If you want to view it, you need to set it to inline.

jQuery event handlers always execute in order they were bound - any way around this?

I'm assuming you are talking about the event bubbling aspect of it. It would be helpful to see your HTML for the said span elements as well. I can't see why you'd want to change the core behavior like this, I don't find it at all annoying. I suggest going with your second block of code:

$('span').click(function (){
  doStuff2();
  doStuff1();
});

Most importantly I think you'll find it more organized if you manage all the events for a given element in the same block like you've illustrated. Can you explain why you find this annoying?

JQuery show and hide div on mouse click (animate)

<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $(".click-header").click(function(){
            $(this).next(".hidden-content").slideToggle("slow");
            $(this).toggleClass("expanded-header");
        });
    });
</script>
.demo-container {
    margin:0 auto;
    width: 600px;
    text-align:center;
}
.click-header {
    padding: 5px 10px 5px 60px;
    background: url(images/arrow-down.png) no-repeat 50% 50%;
}
.expanded-header {
    padding: 5px 10px 5px 60px;
    background: url(images/arrow-up.png) no-repeat 50% 50%;
}
.hidden-content {
    display:none;
    border: 1px solid #d7dbd8;
    padding: 20px;
    text-align: center;
}
<div class="demo-container">
    <div class="click-header">&nbsp;</div>
    <div class="hidden-content">Lorem Ipsum.</div>
</div>

How to convert dd/mm/yyyy string into JavaScript Date object?

Here is a way to transform a date string with a time of day to a date object. For example to convert "20/10/2020 18:11:25" ("DD/MM/YYYY HH:MI:SS" format) to a date object

    function newUYDate(pDate) {
      let dd = pDate.split("/")[0].padStart(2, "0");
      let mm = pDate.split("/")[1].padStart(2, "0");
      let yyyy = pDate.split("/")[2].split(" ")[0];
      let hh = pDate.split("/")[2].split(" ")[1].split(":")[0].padStart(2, "0");
      let mi = pDate.split("/")[2].split(" ")[1].split(":")[1].padStart(2, "0");
      let secs = pDate.split("/")[2].split(" ")[1].split(":")[2].padStart(2, "0");
    
      mm = (parseInt(mm) - 1).toString(); // January is 0
    
      return new Date(yyyy, mm, dd, hh, mi, secs);
    }

Sending data through POST request from a node.js server to a node.js server

You can also use Requestify, a really cool and very simple HTTP client I wrote for nodeJS + it supports caching.

Just do the following for executing a POST request:

var requestify = require('requestify');

requestify.post('http://example.com', {
    hello: 'world'
})
.then(function(response) {
    // Get the response body (JSON parsed or jQuery object for XMLs)
    response.getBody();
});

How to change the default docker registry from docker.io to my private registry?

UPDATE: Following your comment, it is not currently possible to change the default registry, see this issue for more info.

You should be able to do this, substituting the host and port to your own:

docker pull localhost:5000/registry-demo

If the server is remote/has auth you may need to log into the server with:

docker login https://<YOUR-DOMAIN>:8080

Then running:

docker pull <YOUR-DOMAIN>:8080/test-image

Add item to Listview control

I have done it like this and it seems to work:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string[] row = { textBox1.Text, textBox2.Text, textBox3.Text };
        var listViewItem = new ListViewItem(row); 
        listView1.Items.Add(listViewItem);
    }
}

How do you test running time of VBA code?

We've used a solution based on timeGetTime in winmm.dll for millisecond accuracy for many years. See http://www.aboutvb.de/kom/artikel/komstopwatch.htm

The article is in German, but the code in the download (a VBA class wrapping the dll function call) is simple enough to use and understand without being able to read the article.

How to create new div dynamically, change it, move it, modify it in every way possible, in JavaScript?

This covers the basics of DOM manipulation. Remember, element addition to the body or a body-contained node is required for the newly created node to be visible within the document.

How to Use Sockets in JavaScript\HTML?

I think it is important to mention, now that this question is over 1 year old, that Socket.IO has since come out and seems to be the primary way to work with sockets in the browser now; it is also compatible with Node.js as far as I know.

$.ajax( type: "POST" POST method to php

You need to use data: {title: title} to POST it correctly.

In the PHP code you need to echo the value instead of returning it.

Disable submit button when form invalid with AngularJS

You need to use the name of your form, as well as ng-disabled: Here's a demo on Plunker

<form name="myForm">
    <input name="myText" type="text" ng-model="mytext" required />
    <button ng-disabled="myForm.$invalid">Save</button>
</form>

String.strip() in Python

If you can comment out code and your program still works, then yes, that code was optional.

.strip() with no arguments (or None as the first argument) removes all whitespace at the start and end, including spaces, tabs, newlines and carriage returns. Leaving it in doesn't do any harm, and allows your program to deal with unexpected extra whitespace inserted into the file.

For example, by using .strip(), the following two lines in a file would lead to the same end result:

 foo\tbar \n
foo\tbar\n

I'd say leave it in.

How exactly to use Notification.Builder

Notification Builder is strictly for Android API Level 11 and above (Android 3.0 and up).

Hence, if you are not targeting Honeycomb tablets, you should not be using the Notification Builder but rather follow older notification creation methods like the following example.

How to get process ID of background process?

this is what I have done. Check it out, hope it can help.

#!/bin/bash
#
# So something to show.
echo "UNO" >  UNO.txt
echo "DOS" >  DOS.txt
#
# Initialize Pid List
dPidLst=""
#
# Generate background processes
tail -f UNO.txt&
dPidLst="$dPidLst $!"
tail -f DOS.txt&
dPidLst="$dPidLst $!"
#
# Report process IDs
echo PID=$$
echo dPidLst=$dPidLst
#
# Show process on current shell
ps -f
#
# Start killing background processes from list
for dPid in $dPidLst
do
        echo killing $dPid. Process is still there.
        ps | grep $dPid
        kill $dPid
        ps | grep $dPid
        echo Just ran "'"ps"'" command, $dPid must not show again.
done

Then just run it as: ./bgkill.sh with proper permissions of course

root@umsstd22 [P]:~# ./bgkill.sh
PID=23757
dPidLst= 23758 23759
UNO
DOS
UID        PID  PPID  C STIME TTY          TIME CMD
root      3937  3935  0 11:07 pts/5    00:00:00 -bash
root     23757  3937  0 11:55 pts/5    00:00:00 /bin/bash ./bgkill.sh
root     23758 23757  0 11:55 pts/5    00:00:00 tail -f UNO.txt
root     23759 23757  0 11:55 pts/5    00:00:00 tail -f DOS.txt
root     23760 23757  0 11:55 pts/5    00:00:00 ps -f
killing 23758. Process is still there.
23758 pts/5    00:00:00 tail
./bgkill.sh: line 24: 23758 Terminated              tail -f UNO.txt
Just ran 'ps' command, 23758 must not show again.
killing 23759. Process is still there.
23759 pts/5    00:00:00 tail
./bgkill.sh: line 24: 23759 Terminated              tail -f DOS.txt
Just ran 'ps' command, 23759 must not show again.
root@umsstd22 [P]:~# ps -f
UID        PID  PPID  C STIME TTY          TIME CMD
root      3937  3935  0 11:07 pts/5    00:00:00 -bash
root     24200  3937  0 11:56 pts/5    00:00:00 ps -f

Reading and writing binary file

Here is a short example, the C++ way using rdbuf. I got this from the web. I can't find my original source on this:

#include <fstream>
#include <iostream>

int main () 
{
  std::ifstream f1 ("C:\\me.txt",std::fstream::binary);

  std::ofstream f2 ("C:\\me2.doc",std::fstream::trunc|std::fstream::binary);

  f2<<f1.rdbuf();

  return 0;
}

Run AVD Emulator without Android Studio

On MacOS

First list down the installed emulators

~/Library/Android/sdk/tools/emulator -list-avds

then run an emulator

~/Library/Android/sdk/tools/emulator -avd Nexus_5X_API_27

How to get the first and last date of the current year?

SELECT
   DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) AS StartOfYear,
   DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, -1) AS EndOfYear

The above query gives a datetime value for midnight at the beginning of December 31. This is about 24 hours short of the last moment of the year. If you want to include time that might occur on December 31, then you should compare to the first of the next year, with a < comparison. Or you can compare to the last few milliseconds of the current year, but this still leaves a gap if you are using something other than DATETIME (such as DATETIME2):

SELECT
   DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) AS StartOfYear,
   DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, -1) AS LastDayOfYear,
   DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, 0) AS FirstOfNextYear,
   DATEADD(ms, -3, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, 0)) AS LastTimeOfYear

Tech Details

This works by figuring out the number of years since 1900 with DATEDIFF(yy, 0, GETDATE()) and then adding that to a date of zero = Jan 1, 1900. This can be changed to work for an arbitrary date by replacing the GETDATE() portion or an arbitrary year by replacing the DATEDIFF(...) function with "Year - 1900."

 SELECT
   DATEADD(yy, DATEDIFF(yy, 0, '20150301'), 0) AS StartOfYearForMarch2015,
   DATEADD(yy, 2015 - 1900, 0) AS StartOfYearFor2015

The I/O operation has been aborted because of either a thread exit or an application request

What I do when it happens is Disable the COM port into the Device Manager and Enable it again.

It stop the communications with another program or thread and become free for you.

I hope this works for you. Regards.

IOError: [Errno 2] No such file or directory trying to open a file

I got this error and fixed by appending the directory path in the loop. script not in the same directory as the files. dr1 ="~/test" directory variable

 fileop=open(dr1+"/"+fil,"r")

Stacked Bar Plot in R

The dataset:

dat <- read.table(text = "A   B   C   D   E   F    G
1 480 780 431 295 670 360  190
2 720 350 377 255 340 615  345
3 460 480 179 560  60 735 1260
4 220 240 876 789 820 100   75", header = TRUE)

Now you can convert the data frame into a matrix and use the barplot function.

barplot(as.matrix(dat))

enter image description here

Input widths on Bootstrap 3

Bootstrap 3 I achieved a nice responsive form layout using the following:

<div class="row">
    <div class="form-group  col-sm-4">
        <label for=""> Date</label>
        <input type="date" class="form-control" id="date" name="date" placeholder=" date">
    </div>

    <div class="form-group  col-sm-4">
        <label for="hours">Hours</label>
        <input type="" class="form-control" id="hours" name="hours" placeholder="Total hours">
    </div>
</div>

Java Replace Character At Specific Position Of String?

Kay!

First of all, when dealing with strings you have to refer to their positions in 0 base convention. This means that if you have a string like this:

String str = "hi";
//str length is equal 2 but the character
//'h' is in the position 0 and character 'i' is in the postion 1


With that in mind, the best way to tackle this problem is creating a method to replace a character at a given position in a string like this:

Method:

public String changeCharInPosition(int position, char ch, String str){
    char[] charArray = str.toCharArray();
    charArray[position] = ch;
    return new String(charArray);
}

Then you should call the method 'changeCharInPosition' in this way:

String str = "hi";
str = changeCharInPosition(1, 'k', str);
System.out.print(str); //this will return "hk"

If you have any questions, don't hesitate, post something!

Make the image go behind the text and keep it in center using CSS

Well, put your image in the background of your website/container and put whatever you want on top of that.

Your container defined in HTML:

<div id="container">
   <input name="box" type="textbox" />
   <input name="box" type="textbox" />
   <input name="submit" type="submit" />
</div>

Your CSS would look like this:

#container {
    background-image:url(yourimage.jpg);
    background-position:center;
    width:700px;
    height:400px;
}

For this to work though, you must have height and width specified to certain values (i.e. no percentages). I could help you more specifically if you wanted, but I'd need more info.

How to enable SOAP on CentOS

On CentOS 7, the following works:

yum install php-soap

This will automatically create a soap.ini under /etc/php.d.

The extension itself for me lives in /usr/lib64/php/modules. You can confirm your extension directory by doing:

php -i | grep extension_dir

Once this has been installed, you can simply restart Apache using the new service manager like so:

systemctl restart httpd

Thanks to Matt Browne for the info about /etc/php.d.

How to Determine the Screen Height and Width in Flutter

You can use:

  • double width = MediaQuery.of(context).size.width;
  • double height = MediaQuery.of(context).size.height;

To get height just of SafeArea (for iOS 11 and above):

  • var padding = MediaQuery.of(context).padding;
  • double newheight = height - padding.top - padding.bottom;

Sum values in a column based on date

Use a column to let each date be shown as month number; another column for day number:

      A      B       C         D
   -----  ----- ----------- --------
1     8      6    8/6/2010   12.70
2     8      7    8/7/2010   10.50
3     8      7    8/7/2010    7.10
4     8      9    8/9/2010   10.50
5     8     10   8/10/2010   15.00

The formula for A1 is =Month(C1)

The formula for B1 is =Day(C1)

For Month sums, put the month number next to each month:

      E      F         G     
   -----  ----- -------------  
1     7    July   $1,000,010 
2     8     Aug   $1,200,300 

The formula for G1 is =SumIf($A$1:$A$100, E1, $D$1:$D$100). This is a portable formula; just copy it down.

Total for the day will be be a bit more complicated, but you can probably see how to do it.

C# LINQ select from list

The "in" in Linq-To-Sql uses a reverse logic compared to a SQL query.

Let's say you have a list of integers, and want to find the items that match those integers.

int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

var items = from p in context.Items
                 where numbers.Contains(p.ItemId)
                select p;

Anyway, the above works fine in linq-to-sql but not in EF 1.0. Haven't tried it in EF 4.0

How can I use UIColorFromRGB in Swift?

Nate Cook's answer is absolutely correct. Just for greater flexibility, I keep the following functions in my pack:

func getUIColorFromRGBThreeIntegers(red: Int, green: Int, blue: Int) -> UIColor {
    return UIColor(red: CGFloat(Float(red) / 255.0),
        green: CGFloat(Float(green) / 255.0),
        blue: CGFloat(Float(blue) / 255.0),
        alpha: CGFloat(1.0))
}

func getUIColorFromRGBHexValue(value: Int) -> UIColor {
    return getUIColorFromRGBThreeIntegers(red: (value & 0xFF0000) >> 16,
        green: (value & 0x00FF00) >> 8,
        blue: value & 0x0000FF)
}

func getUIColorFromRGBString(value: String) -> UIColor {
    let str = value.lowercased().replacingOccurrences(of: "#", with: "").
        replacingOccurrences(of: "0x", with: "");
        return getUIColorFromRGBHexValue(value: Int(str, radix: 16)!);
}

And this is how I use them:

// All three of them are identical:
let myColor1 = getUIColorFromRGBHexValue(value: 0xd5a637)
let myColor2 = getUIColorFromRGBString(value: "#D5A637")
let myColor3 = getUIColorFromRGBThreeIntegers(red: 213, green: 166, blue: 55)

Hope this will help. Everything is tested with Swift 3/Xcode 8.

What is the difference between absolute and relative xpaths? Which is preferred in Selenium automation testing?

Absolute Xpath: It uses Complete path from the Root Element to the desire element.

Relative Xpath: You can simply start by referencing the element you want and go from there.

Relative Xpaths are always preferred as they are not the complete paths from the root element. (//html//body). Because in future, if any webelement is added/removed, then the absolute Xpath changes. So Always use Relative Xpaths in your Automation.

Below are Some Links which you can Refer for more Information on them.

Viewing localhost website from mobile device

First of all open applicationhost.config file in visual studio. address>>C:\Users\Your User Name\Documents\IISExpress\config\applicationhost.config

Then find this codes:

<site name="Your Site_Name" id="24">
        <application path="/" applicationPool="Clr4IntegratedAppPool"
        <virtualDirectory path="/" physicalPath="C:\Users\Your User         Name\Documents\Visual Studio 2013\Projects\Your Site Name" />
        </application>
         <bindings>      
           <binding protocol="http" bindingInformation="*:Port_Number:*" />
         </bindings>
   </site>

*)Port_Number:While your site running in IIS express on your computer, port number will visible in address bar of your browser like this: localhost:port_number/... When edit this file save it.

In the Second step you must run cmd as administrator and type this code: netsh http add urlacl url=http://*:port_Number/ user=everyone and press enter

In Third step you must Enable port on firewall

Go to the “Control Panel\System and Security\Windows Firewall”

Click “Advanced settings”

Select “Inbound Rules”

Click on “New Rule …” button

Select “Port”, click “Next”

Fill your IIS Express listening port number, click “Next”

Select “Allow the connection”, click “Next”

Check where you would like allow connection to IIS Express (Domain,Private, Public), click “Next”

Fill rule name (e.g “IIS Express), click “Finish”

I hopeful this answer be useful for you

Update for Visual Studio 2015 in this link: https://johan.driessen.se/posts/Accessing-an-IIS-Express-site-from-a-remote-computer

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

Run ssh-add on the client machine, that will add the SSH key to the agent.

Confirm with ssh-add -l (again on the client) that it was indeed added.

Regular cast vs. static_cast vs. dynamic_cast

You should look at the article C++ Programming/Type Casting.

It contains a good description of all of the different cast types. The following taken from the above link:

const_cast

const_cast(expression) The const_cast<>() is used to add/remove const(ness) (or volatile-ness) of a variable.

static_cast

static_cast(expression) The static_cast<>() is used to cast between the integer types. 'e.g.' char->long, int->short etc.

Static cast is also used to cast pointers to related types, for example casting void* to the appropriate type.

dynamic_cast

Dynamic cast is used to convert pointers and references at run-time, generally for the purpose of casting a pointer or reference up or down an inheritance chain (inheritance hierarchy).

dynamic_cast(expression)

The target type must be a pointer or reference type, and the expression must evaluate to a pointer or reference. Dynamic cast works only when the type of object to which the expression refers is compatible with the target type and the base class has at least one virtual member function. If not, and the type of expression being cast is a pointer, NULL is returned, if a dynamic cast on a reference fails, a bad_cast exception is thrown. When it doesn't fail, dynamic cast returns a pointer or reference of the target type to the object to which expression referred.

reinterpret_cast

Reinterpret cast simply casts one type bitwise to another. Any pointer or integral type can be casted to any other with reinterpret cast, easily allowing for misuse. For instance, with reinterpret cast one might, unsafely, cast an integer pointer to a string pointer.

React.js: Wrapping one component into another

Using children

const Wrapper = ({children}) => (
  <div>
    <div>header</div>
    <div>{children}</div>
    <div>footer</div>
  </div>
);

const App = ({name}) => <div>Hello {name}</div>;

const WrappedApp = ({name}) => (
  <Wrapper>
    <App name={name}/>
  </Wrapper>
);

render(<WrappedApp name="toto"/>,node);

This is also known as transclusion in Angular.

children is a special prop in React and will contain what is inside your component's tags (here <App name={name}/> is inside Wrapper, so it is the children

Note that you don't necessarily need to use children, which is unique for a component, and you can use normal props too if you want, or mix props and children:

const AppLayout = ({header,footer,children}) => (
  <div className="app">
    <div className="header">{header}</div>
    <div className="body">{children}</div>
    <div className="footer">{footer}</div>
  </div>
);

const appElement = (
  <AppLayout 
    header={<div>header</div>}
    footer={<div>footer</div>}
  >
    <div>body</div>
  </AppLayout>
);

render(appElement,node);

This is simple and fine for many usecases, and I'd recommend this for most consumer apps.


render props

It is possible to pass render functions to a component, this pattern is generally called render prop, and the children prop is often used to provide that callback.

This pattern is not really meant for layout. The wrapper component is generally used to hold and manage some state and inject it in its render functions.

Counter example:

const Counter = () => (
  <State initial={0}>
    {(val, set) => (
      <div onClick={() => set(val + 1)}>  
        clicked {val} times
      </div>
    )}
  </State>
); 

You can get even more fancy and even provide an object

<Promise promise={somePromise}>
  {{
    loading: () => <div>...</div>,
    success: (data) => <div>{data.something}</div>,
    error: (e) => <div>{e.message}</div>,
  }}
</Promise>

Note you don't necessarily need to use children, it is a matter of taste/API.

<Promise 
  promise={somePromise}
  renderLoading={() => <div>...</div>}
  renderSuccess={(data) => <div>{data.something}</div>}
  renderError={(e) => <div>{e.message}</div>}
/>

As of today, many libraries are using render props (React context, React-motion, Apollo...) because people tend to find this API more easy than HOC's. react-powerplug is a collection of simple render-prop components. react-adopt helps you do composition.


Higher-Order Components (HOC).

const wrapHOC = (WrappedComponent) => {
  class Wrapper extends React.PureComponent {
    render() {
      return (
        <div>
          <div>header</div>
          <div><WrappedComponent {...this.props}/></div>
          <div>footer</div>
        </div>
      );
    }  
  }
  return Wrapper;
}

const App = ({name}) => <div>Hello {name}</div>;

const WrappedApp = wrapHOC(App);

render(<WrappedApp name="toto"/>,node);

An Higher-Order Component / HOC is generally a function that takes a component and returns a new component.

Using an Higher-Order Component can be more performant than using children or render props, because the wrapper can have the ability to short-circuit the rendering one step ahead with shouldComponentUpdate.

Here we are using PureComponent. When re-rendering the app, if the WrappedApp name prop does not change over time, the wrapper has the ability to say "I don't need to render because props (actually, the name) are the same as before". With the children based solution above, even if the wrapper is PureComponent, it is not the case because the children element is recreated everytime the parent renders, which means the wrapper will likely always re-render, even if the wrapped component is pure. There is a babel plugin that can help mitigate this and ensure a constant children element over time.


Conclusion

Higher-Order Components can give you better performance. It's not so complicated but it certainly looks unfriendly at first.

Don't migrate your whole codebase to HOC after reading this. Just remember that on critical paths of your app you might want to use HOCs instead of runtime wrappers for performance reasons, particularly if the same wrapper is used a lot of times it's worth considering making it an HOC.

Redux used at first a runtime wrapper <Connect> and switched later to an HOC connect(options)(Comp) for performance reasons (by default, the wrapper is pure and use shouldComponentUpdate). This is the perfect illustration of what I wanted to highlight in this answer.

Note if a component has a render-prop API, it is generally easy to create a HOC on top of it, so if you are a lib author, you should write a render prop API first, and eventually offer an HOC version. This is what Apollo does with <Query> render-prop component, and the graphql HOC using it.

Personally, I use both, but when in doubt I prefer HOCs because:

  • It's more idiomatic to compose them (compose(hoc1,hoc2)(Comp)) compared to render props
  • It can give me better performances
  • I'm familiar with this style of programming

I don't hesitate to use/create HOC versions of my favorite tools:

  • React's Context.Consumer comp
  • Unstated's Subscribe
  • using graphql HOC of Apollo instead of Query render prop

In my opinion, sometimes render props make the code more readable, sometimes less... I try to use the most pragmatic solution according to the constraints I have. Sometimes readability is more important than performances, sometimes not. Choose wisely and don't bindly follow the 2018 trend of converting everything to render-props.

PHP new line break in emails

if you are outputting the code as html - change /n -->
and do echo $message;

Time comparison

package javaapplication4;

import java.text.*;
import java.util.*;

/**
 *
 * @author Stefan Wendelmann
 */
public class JavaApplication4
{
    private static SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");

  /**
   * @param args the command line arguments
   */
  public static void main(String[] args) throws ParseException
  {
    SimpleDateFormat parser = new SimpleDateFormat("dd.MM.YYYY HH:mm:ss.SSS");
    Date before = parser.parse("01.10.1990 07:00:00.000");
    Date base = parser.parse("01.10.1990 08:00:00.000");
    Date after = parser.parse("01.10.1990 09:00:00.000");

    printCompare(base, base, "==");
    printCompare(base, before, "==");
    printCompare(base, before, "<");
    printCompare(base, after, "<");
    printCompare(base, after, ">");
    printCompare(base, before, ">");
    printCompare(base, before, "<=");
    printCompare(base, base, "<=");
    printCompare(base, after, "<=");
    printCompare(base, after, ">=");
    printCompare(base, base, ">=");
    printCompare(base, before, ">=");

  }

  private static void printCompare (Date a, Date b, String operator){
    System.out.println(sdf.format(b)+"\t"+operator+"\t"+sdf.format(a)+"\t"+compareTime(a, b, operator));
  }

  protected static boolean compareTime(Date a, Date b, String operator)
  {
    if (a == null)
    {
      return false;
    }
    try
    {
      //Zeit aus Datum holen
// The Magic happens here i only get the Time out of the Date Object
      SimpleDateFormat parser = new SimpleDateFormat("HH:mm:ss.SSS");
      a = parser.parse(parser.format(a));
      b = parser.parse(parser.format(b));
    }
    catch (ParseException ex)
    {
      System.err.println(ex);
    }
    switch (operator)
    {
      case "==":
        return b.compareTo(a) == 0;
      case "<":
        return b.compareTo(a) < 0;
      case ">":
        return b.compareTo(a) > 0;
      case "<=":
        return b.compareTo(a) <= 0;
      case ">=":
        return b.compareTo(a) >= 0;
      default:
        throw new IllegalArgumentException("Operator " + operator + " wird für Feldart Time nicht unterstützt!");

    }
  }

}



run:
08:00:00.000    ==  08:00:00.000    true
07:00:00.000    ==  08:00:00.000    false
07:00:00.000    <   08:00:00.000    true
09:00:00.000    <   08:00:00.000    false
09:00:00.000    >   08:00:00.000    true
07:00:00.000    >   08:00:00.000    false
07:00:00.000    <=  08:00:00.000    true
08:00:00.000    <=  08:00:00.000    true
09:00:00.000    <=  08:00:00.000    false
09:00:00.000    >=  08:00:00.000    true
08:00:00.000    >=  08:00:00.000    true
07:00:00.000    >=  08:00:00.000    false
BUILD SUCCESSFUL (total time: 0 seconds)

Default Xmxsize in Java 8 (max heap size)

As of 8, May, 2019:

JVM heap size depends on system configuration, meaning:

a) client jvm vs server jvm

b) 32bit vs 64bit.

Links:

1) updation from J2SE5.0: https://docs.oracle.com/javase/6/docs/technotes/guides/vm/gc-ergonomics.html
2) brief answer: https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/ergonomics.html
3) detailed answer: https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/parallel.html#default_heap_size
4) client vs server: https://www.javacodegeeks.com/2011/07/jvm-options-client-vs-server.html

Summary: (Its tough to understand from the above links. So summarizing them here)

1) Default maximum heap size for Client jvm is 256mb (there is an exception, read from links above).

2) Default maximum heap size for Server jvm of 32bit is 1gb and of 64 bit is 32gb (again there are exceptions here too. Kindly read that from the links).

So default maximum jvm heap size is: 256mb or 1gb or 32gb depending on VM, above.

jquery: get value of custom attribute

You need some form of iteration here, as val (except when called with a function) only works on the first element:

$("input[placeholder]").val($("input[placeholder]").attr("placeholder"));

should be:

$("input[placeholder]").each( function () {
    $(this).val( $(this).attr("placeholder") );
});

or

$("input[placeholder]").val(function() {
    return $(this).attr("placeholder");
});

VB.NET Empty String Array

Another way of doing this:

Dim strings() As String = {}

Testing that it is an empty string array:

MessageBox.Show("count: " + strings.Count.ToString)

Will show a message box saying "count: 0".

Remove grid, background color, and top and right borders from ggplot2

Recent updates to ggplot (0.9.2+) have overhauled the syntax for themes. Most notably, opts() is now deprecated, having been replaced by theme(). Sandy's answer will still (as of Jan '12) generates a chart, but causes R to throw a bunch of warnings.

Here's updated code reflecting current ggplot syntax:

library(ggplot2)
a <- seq(1,20)
b <- a^0.25
df <- as.data.frame(cbind(a,b))

#base ggplot object
p <- ggplot(df, aes(x = a, y = b))

p +
  #plots the points
  geom_point() +

  #theme with white background
  theme_bw() +

  #eliminates background, gridlines, and chart border
  theme(
    plot.background = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.border = element_blank()
  ) +

  #draws x and y axis line
  theme(axis.line = element_line(color = 'black'))

generates:

plot output

Select columns based on string match - dplyr::select

Within the dplyr world, try:

select(iris,contains("Sepal"))

See the Selection section in ?select for numerous other helpers like starts_with, ends_with, etc.

How to mute an html5 video player using jQuery

Are you using the default controls boolean attribute on the video tag? If so, I believe all the supporting browsers have mute buttons. If you need to wire it up, set .muted to true on the element in javascript (use .prop for jquery because it's an IDL attribute.) The speaker icon on the volume control is the mute button on chrome,ff, safari, and opera for example

How to clear react-native cache?

If you are using WebStorm, press configuration selection drop down button left of the run button and select edit configurations:

edit configurations

Double click on Start React Native Bundler at bottom in Before launch section:

before launch

Enter --reset-cache to Arguments section:

arguments

Android Debug Bridge (adb) device - no permissions

I have a similar problem:

$ adb devices
List of devices attached 
4df15d6e02a55f15    device
????????????    no permissions

Investigation

If I run lsusb, I can see which devices I have connected, and where:

$ lsusb
...
Bus 002 Device 050: ID 04e8:6860 Samsung Electronics Co., Ltd GT-I9100 Phone ...
Bus 002 Device 049: ID 18d1:4e42 Google Inc. 

This is showing my Samsung Galaxy S3 and my Nexus 7 (2012) connected.

Checking the permissions on those:

$ ls -l /dev/bus/usb/002/{049,050}
crw-rw-r--  1 root root    189, 176 Oct 10 10:09 /dev/bus/usb/002/049
crw-rw-r--+ 1 root plugdev 189, 177 Oct 10 10:12 /dev/bus/usb/002/050

Wait. What? Where did that "plugdev" group come from?

$ cd /lib/udev/rules.d/
$ grep -R "6860.*plugdev" .
./40-libgphoto2-2.rules:ATTRS{idVendor}=="0bb4", ATTRS{idProduct}=="6860", \
  ENV{ID_GPHOTO2}="1", ENV{GPHOTO2_DRIVER}="proprietary", \
  ENV{ID_MEDIA_PLAYER}="1", MODE="0664", GROUP="plugdev"
./40-libgphoto2-2.rules:ATTRS{idVendor}=="04e8", ATTRS{idProduct}=="6860", \
  ENV{ID_GPHOTO2}="1", ENV{GPHOTO2_DRIVER}="proprietary", \
  ENV{ID_MEDIA_PLAYER}="1", MODE="0664", GROUP="plugdev"

(I've wrapped those lines)

Note the GROUP="plugdev" lines. Also note that this doesn't work for the other device ID:

$ grep -Ri "4e42.*plugdev" .

(nothing is returned)

Fixing it

OK. So what's the fix?

Add a rule

Create a file /etc/udev/rules.d/99-adb.rules containing the following line:

ATTRS{idVendor}=="18d1", ATTRS{idProduct}=="4e42", ENV{ID_GPHOTO2}="1",
  ENV{GPHOTO2_DRIVER}="proprietary", ENV{ID_MEDIA_PLAYER}="1",
  MODE="0664", GROUP="plugdev"

This should be a single line, I've wrapped it here for readability

Restart udev

$ sudo udevadm control --reload-rules
$ sudo service udev restart

That's it

Unplug/replug your device.

Try it

$ adb devices
List of devices attached 
4df15d6e02a55f15    device
015d2109ce67fa0c    device

How to get a Char from an ASCII Character Code in c#

You can simply write:

char c = (char) 2;

or

char c = Convert.ToChar(2);

or more complex option for ASCII encoding only

char[] characters = System.Text.Encoding.ASCII.GetChars(new byte[]{2});
char c = characters[0];

How to set focus on an input field after rendering?

Ben Carp solution in typescript

React 16.8 + Functional component - useFocus hook

export const useFocus = (): [React.MutableRefObject<HTMLInputElement>, VoidFunction] => {
  const htmlElRef = React.useRef<HTMLInputElement>(null);
  const setFocus = React.useCallback(() => {
    if (htmlElRef.current) htmlElRef.current.focus();
  }, [htmlElRef]);

  return React.useMemo(() => [htmlElRef, setFocus], [htmlElRef, setFocus]);
};

How do I create an Android Spinner as a popup?

If you want to show it as a full screen popup, then you don't even need an xml layout. Here's how do do it in Kotlin.

 val inputArray: Array<String> = arrayOf("Item 1","Item 2")
                val alt_bld =  AlertDialog.Builder(context);
                alt_bld.setTitle("Items:")
                alt_bld.setSingleChoiceItems(inputArray, -1) { dialog, which ->
                    if(which == 0){
                        //Item 1 Selected
                    }
                    else if(which == 1){
                        //Item 2 Selected
                    }
                    dialog.dismiss();

                }

                val alert11 = alt_bld.create()
                alert11.show()

error: unknown type name ‘bool’

C90 does not support the boolean data type.

C99 does include it with this include:

#include <stdbool.h>

Java heap terminology: young, old and permanent generations?

Memory in SunHotSpot JVM is organized into three generations: young generation, old generation and permanent generation.

  • Young Generation : the newly created objects are allocated to the young gen.
  • Old Generation : If the new object requests for a larger heap space, it gets allocated directly into the old gen. Also objects which have survived a few GC cycles gets promoted to the old gen i.e long lived objects house in old gen.
  • Permanent Generation : The permanent generation holds objects that the JVM finds convenient to have the garbage collector manage, such as objects describing classes and methods, as well as the classes and methods themselves.

FYI: The permanent gen is not considered a part of the Java heap.

How does the three generations interact/relate to each other? Objects(except the large ones) are first allocated to the young generation. If an object remain alive after x no. of garbage collection cycles it gets promoted to the old/tenured gen. Hence we can say that the young gen contains the short lived objects while the old gen contains the objects having a long life. The permanent gen does not interact with the other two generations.

Detect rotation of Android phone in the browser with JavaScript

two-bit-fool's excellent answer provides all the background, but let me attempt a concise, pragmatic summary of how to handle orientation changes across iOS and Android:

  • If you only care about window dimensions (the typical scenario) - and not about the specific orientation:
    • Handle the resize event only.
    • In your handler, act on window.innerWidth and window.InnerHeight only.
    • Do NOT use window.orientation - it won't be current on iOS.
  • If you DO care about the specific orientation:
    • Handle only the resize event on Android, and only the orientationchange event on iOS.
    • In your handler, act on window.orientation (and window.innerWidth and window.InnerHeight)

These approaches offer slight benefits over remembering the previous orientation and comparing:

  • the dimensions-only approach also works while developing on desktop browsers that can otherwise simulate mobile devices, e.g., Chrome 23. (window.orientation is not available on desktop browsers).
  • no need for a global/anonymous-file-level-function-wrapper-level variable.

Huge performance difference when using group by vs distinct

The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct approach is executed like:

  • Copy all business_key values to a temporary table
  • Sort the temporary table
  • Scan the temporary table, returning each item that is different from the one before it

The group by could be executed like:

  • Scan the full table, storing each value of business key in a hashtable
  • Return the keys of the hashtable

The first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.

Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.

java.util.zip.ZipException: duplicate entry during packageAllDebugClassesForMultiDex

I have faced this issue as i have manually copied the jar in libs as well as mentioned the dependency in gradle file. You also check in your project structure, whether the same jar file is copied in any other folder like libs or in project folder.

How to have Android Service communicate with Activity

As mentioned by Madhur, you can use a bus for communication.

In case of using a Bus you have some options:

Otto event Bus library (deprecated in favor of RxJava)

http://square.github.io/otto/

Green Robot’s EventBus

http://greenrobot.org/eventbus/

NYBus (RxBus, implemented using RxJava. very similar to the EventBus)

https://github.com/MindorksOpenSource/NYBus

Oracle date difference to get number of years

If you just want the difference in years, there's:

SELECT EXTRACT(YEAR FROM date1) - EXTRACT(YEAR FROM date2) FROM mytable

Or do you want fractional years as well?

SELECT (date1 - date2) / 365.242199 FROM mytable

365.242199 is 1 year in days, according to Google.

C/C++ check if one bit is set in, i.e. int variable

You could "simulate" shifting and masking: if((0x5e/(2*2*2))%2) ...

ActionController::InvalidAuthenticityToken

Problem solved by downgrading to 2.3.5 from 2.3.8. (as well as infamous 'You are being redirected.' issue)

How do I get textual contents from BLOB in Oracle SQL

You can try this:

SELECT TO_CHAR(dbms_lob.substr(BLOB_FIELD, 3900)) FROM TABLE_WITH_BLOB;

However, It would be limited to 4000 byte

How can I check if two segments intersect?

Here's a solution using dot products:

# assumes line segments are stored in the format [(x0,y0),(x1,y1)]
def intersects(s0,s1):
    dx0 = s0[1][0]-s0[0][0]
    dx1 = s1[1][0]-s1[0][0]
    dy0 = s0[1][1]-s0[0][1]
    dy1 = s1[1][1]-s1[0][1]
    p0 = dy1*(s1[1][0]-s0[0][0]) - dx1*(s1[1][1]-s0[0][1])
    p1 = dy1*(s1[1][0]-s0[1][0]) - dx1*(s1[1][1]-s0[1][1])
    p2 = dy0*(s0[1][0]-s1[0][0]) - dx0*(s0[1][1]-s1[0][1])
    p3 = dy0*(s0[1][0]-s1[1][0]) - dx0*(s0[1][1]-s1[1][1])
    return (p0*p1<=0) & (p2*p3<=0)

Here's a visualization in Desmos: Line Segment Intersection

#1227 - Access denied; you need (at least one of) the SUPER privilege(s) for this operation

In case you are uploading an sql file on cpanel, then try and replace root with your cpanel username in your sql file.

in the case above you could write

CREATE DEFINER = control_panel_username@localhost FUNCTION fnc_calcWalkedDistance

then upload the file. Hope it helps

How do I analyze a .hprof file?

If you want to do a custom analysis of your heapdump then there's:

This library is fast but you will need to write your analysis code in Java.

From the docs:

  • Does not create any temporary files on disk to process heap dump
  • Can work directly GZ compressed heap dumps
  • HeapPath notation

How do I change the select box arrow

You can skip the container or background image with pure css arrow:

select {

  /* make arrow and background */

  background:
    linear-gradient(45deg, transparent 50%, blue 50%),
    linear-gradient(135deg, blue 50%, transparent 50%),
    linear-gradient(to right, skyblue, skyblue);
  background-position:
    calc(100% - 21px) calc(1em + 2px),
    calc(100% - 16px) calc(1em + 2px),
    100% 0;
  background-size:
    5px 5px,
    5px 5px,
    2.5em 2.5em;
  background-repeat: no-repeat;

  /* styling and reset */

  border: thin solid blue;
  font: 300 1em/100% "Helvetica Neue", Arial, sans-serif;
  line-height: 1.5em;
  padding: 0.5em 3.5em 0.5em 1em;

  /* reset */

  border-radius: 0;
  margin: 0;      
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  -webkit-appearance:none;
  -moz-appearance:none;
}

Sample here

How to get ASCII value of string in C#

byte[] asciiBytes = Encoding.ASCII.GetBytes("Y");
foreach (byte b in asciiBytes)
{
    MessageBox.Show("" + b);
}

Difference between IsNullOrEmpty and IsNullOrWhiteSpace in C#

If your string (In your case the variable text) could be null this would make a big Difference:

1-string.IsNullOrEmpty(text.Trim()) --> EXCEPTION since your calling a mthode of a null object

2-string.IsNullOrWhiteSpace(text) This would work fine since the null issue is beeing checked internally

To provide the same behaviour using the 1st Option you would have to check somehow if its not null first then use the trim() method

if ((text != null) && string.IsNullOrEmpty(text.Trim())) { ... }

How to avoid the "Circular view path" exception with Spring MVC test

I solved this problem by using @ResponseBody like below:

@RequestMapping(value = "/resturl", method = RequestMethod.GET, produces = {"application/json"})
    @ResponseStatus(HttpStatus.OK)
    @Transactional(value = "jpaTransactionManager")
    public @ResponseBody List<DomainObject> findByResourceID(@PathParam("resourceID") String resourceID) {

Binary Search Tree - Java Implementation

According to Collections Framework Overview you have two balanced tree implementations:

Pass variables to Ruby script via command line

Unfortunately, Ruby does not support such passing mechanism as e.g. AWK:

> awk -v a=1 'BEGIN {print a}'
> 1

It means you cannot pass named values into your script directly.

Using cmd options may help:

> ruby script.rb val_0 val_1 val_2

# script.rb
puts ARGV[0] # => val_0
puts ARGV[1] # => val_1
puts ARGV[2] # => val_2

Ruby stores all cmd arguments in the ARGV array, the scriptname itself can be captured using the $PROGRAM_NAME variable.

The obvious disadvantage is that you depend on the order of values.

If you need only Boolean switches use the option -s of the Ruby interpreter:

> ruby -s -e 'puts "So do I!" if $agreed' -- -agreed
> So do I!

Please note the -- switch, otherwise Ruby will complain about a nonexistent option -agreed, so pass it as a switch to your cmd invokation. You don't need it in the following case:

> ruby -s script_with_switches.rb -agreed
> So do I!

The disadvantage is that you mess with global variables and have only logical true/false values.

You can access values from environment variables:

> FIRST_NAME='Andy Warhol' ruby -e 'puts ENV["FIRST_NAME"]'
> Andy Warhol

Drawbacks are present here to, you have to set all the variables before the script invocation (only for your ruby process) or to export them (shells like BASH):

> export FIRST_NAME='Andy Warhol'
> ruby -e 'puts ENV["FIRST_NAME"]'

In the latter case, your data will be readable for everybody in the same shell session and for all subprocesses, which can be a serious security implication.

And at least you can implement an option parser using getoptlong and optparse.

Happy hacking!

Countdown timer using Moment js

You're not using react native or react so forgive me this isn't a solution for you. - since this is a 7 year old post I'm pretty sure you figured it out by now ;)

But I was looking for something similar for react-native and it led me to this SO question. Incase anyone else winds up down the same road I thought I'd share my use-moment-countdown hook for react or react native: https://github.com/BrooklinJazz/use-moment-countdown.

For example you can make a 10 minute timer like so:

import React from 'react'

import  { useCountdown } from 'use-moment-countdown'

const App = () => {
  const {start, time} = useCountdown({m: 10})
  return (
    <div onClick={start}>
      {time.format("hh:mm:ss")}
    </div>
  )
}

export default App

Command to escape a string in bash

It may not be quite what you want, since it's not a standard command on anyone's systems, but since my program should work fine on POSIX systems (if compiled), I'll mention it anyway. If you have the ability to compile or add programs on the machine in question, it should work.

I've used it without issue for about a year now, but it could be that it won't handle some edge cases. Most specifically, I have no idea what it would do with newlines in strings; a case for \\n might need to be added. This list of characters is not authoritative, but I believe it covers everything else.

I wrote this specifically as a 'helper' program so I could make a wrapper for things like scp commands.

It can likely be implemented as a shell function as well

I therefore present escapify.c. I use it like so:

scp user@host:"$(escapify "/this/path/needs to be escaped/file.c")" destination_file.c

PLEASE NOTE: I made this program for my own personal use. It also will (probably wrongly) assume that if it is given more than one argument that it should just print an unescaped space and continue on. This means that it can be used to pass multiple escaped arguments correctly, but could be seen as unwanted behavior by some.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
  char c='\0';
  int i=0;
  int j=1;
  /* do not care if no args passed; escaped nothing is still nothing. */
  if(argc < 2)
  {
    return 0;
  }
  while(j<argc)
  {
    while(i<strlen(argv[j]))
    {
      c=argv[j][i];
      /* this switch has no breaks on purpose. */
      switch(c)
      {
      case ';':
      case '\'':
      case ' ':
      case '!':
      case '"':
      case '#':
      case '$':
      case '&':
      case '(':
      case ')':
      case '|':
      case '*':
      case ',':
      case '<':
      case '>':
      case '[':
      case ']':
      case '\\':
      case '^':
      case '`':
      case '{':
      case '}':
        putchar('\\');
      default:
        putchar(c);
      }
      i++;
    }
    j++;
    if(j<argc) {
      putchar(' ');
    }
    i=0;
  }
  /* newline at end */
  putchar ('\n');
  return 0;
}

Why when I transfer a file through SFTP, it takes longer than FTP?

There are all sorts of things which can do this. One possiblity is "Traffic Shaping". This is commonly done in office environments to reserve bandwidth for business critical activities. It may also be done by the web hosting company, or by your ISP, for very similar reasons.

You can also set it up at home very simply.

For example there may be a rule reserving minimum bandwidth for FTP, while SFTP might be falling under an "everything else" rule. Or there might be a rule capping bandwidth for SFTP, but someone else is also using SFTP at the same time as you.

So: Where are you tranferring the file from and to?

Accessing SQL Database in Excel-VBA

I've added the Initial Catalog to your connection string. I've also abandonded the ADODB.Command syntax in favor of simply creating my own SQL statement and open the recordset on that variable.

Hope this helps.

Sub GetDataFromADO()
    'Declare variables'
        Set objMyConn = New ADODB.Connection
        Set objMyRecordset = New ADODB.Recordset
        Dim strSQL As String

    'Open Connection'
        objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=MyDatabase;User ID=abc;Password=abc;"
        objMyConn.Open

    'Set and Excecute SQL Command'
        strSQL = "select * from myTable"

    'Open Recordset'
        Set objMyRecordset.ActiveConnection = objMyConn
        objMyRecordset.Open strSQL            

    'Copy Data to Excel'
        ActiveSheet.Range("A1").CopyFromRecordset (objMyRecordset)

End Sub

Remove plot axis values

@Richie Cotton has a pretty good answer above. I can only add that this page provides some examples. Try the following:

x <- 1:20
y <- runif(20)
plot(x,y,xaxt = "n")
axis(side = 1, at = x, labels = FALSE, tck = -0.01)

Position Absolute + Scrolling

So gaiour is right, but if you're looking for a full height item that doesn't scroll with the content, but is actually the height of the container, here's the fix. Have a parent with a height that causes overflow, a content container that has a 100% height and overflow: scroll, and a sibling then can be positioned according to the parent size, not the scroll element size. Here is the fiddle: http://jsfiddle.net/M5cTN/196/

and the relevant code:

html:

<div class="container">
  <div class="inner">
    Lorem ipsum ...
  </div>
  <div class="full-height"></div>
</div>

css:

.container{
  height: 256px;
  position: relative;
}
.inner{
  height: 100%;
  overflow: scroll;
}
.full-height{
  position: absolute;
  left: 0;
  width: 20%;
  top: 0;
  height: 100%;
}

Receiving login prompt using integrated windows authentication

I got the same issue and it was resolved by changing the Application pool identity of the application pool under which the web application is running to NetworkService enter image description here

How to determine whether a substring is in a different string

with in: substring in string:

>>> substring = "please help me out"
>>> string = "please help me out so that I could solve this"
>>> substring in string
True

Converting an object to a string

It appears JSON accept the second parameter that could help with functions - replacer, this solves the issue of converting in the most elegant way:

JSON.stringify(object, (key, val) => {
    if (typeof val === 'function') {
      return String(val);
    }
    return val;
  });

What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim?

One difference is that:

  • :map does nvo == normal + (visual + select) + operator pending
  • :map! does ic == insert + command-line mode

as stated on help map-modes tables.

So: map does not map to all modes.

To map to all modes you need both :map and :map!.

How to get just the parent directory name of a specific file

From java 7 I would prefer to use Path. You only need to put path into:

Path dddDirectoryPath = Paths.get("C:/aaa/bbb/ccc/ddd/test.java");

and create some get method:

public String getLastDirectoryName(Path directoryPath) {
   int nameCount = directoryPath.getNameCount();
   return directoryPath.getName(nameCount - 1);
}

Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

Add this 3 file for runtime support as well`

As per snapshot the main reason for error is that you are not defining c.tld in lib folder causes such error.

This lib content information about taglib

How return error message in spring mvc @Controller

Evaluating the error response from another service invocated...

This was my solution for evaluating the error:

try {
        return authenticationFeign.signIn(userDto, dataRequest);
    }catch(FeignException ex){

        //ex.status();

        if(ex.status() == HttpStatus.UNAUTHORIZED.value()){
            System.out.println("is a error 401");
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }
        return new ResponseEntity<>(HttpStatus.OK);

    }

Remove duplicated rows

just isolate your data frame to the columns you need, then use the unique function :D

# in the above example, you only need the first three columns
deduped.data <- unique( yourdata[ , 1:3 ] )
# the fourth column no longer 'distinguishes' them, 
# so they're duplicates and thrown out.

How can change width of dropdown list?

The dropdown width itself cannot be set. It's width depend on the option-values. See also here ( jsfiddle.net/LgS3C/ )

How the select box looks like is also depending on your browser.

You can build your own control or use Select2 https://select2.org

How do I use a 32-bit ODBC driver on 64-bit Server 2008 when the installer doesn't create a standard DSN?

A lot of these answers are pretty old, so I thought I would update with a solution that I think is helpful.

Our issue was similar to OP's, we upgraded 32 bit XP machines to 64 bit windows 7 and our application software that uses a 32 bit ODBC driver stopped being able to write to our database.

Turns out, there are two ODBC Data Source Managers, one for 32 bit and one for 64 bit. So I had to run the 32 bit version which is found in C:\Windows\SysWOW64\odbcad32.exe. Inside the ODBC Data Source Manager, I was able to go to the System DSN tab and Add my driver to the list using the Add button. (You can check the Drivers tab to see a list of the drivers you can add, if your driver isn't in this list then you may need to install it).

The next issue was the software that we ran was compiled to use 'Any CPU'. This would see the operating system was 64 bit, so it would look at the 64 bit ODBC Data Sources. So I had to force the program to compile as an x86 program, which then tells it to look at the 32 bit ODBC Data Sources. To set your program to x86, in Visual Studio go to your project properties and under the build tab at the top there is a platform drop down list, and choose x86. If you don't have the source code and can't compile the program as x86, you might be able to right click the program .exe and go to the compatibility tab and choose a compatibility that works for you.

Once I had the drivers added and the program pointing to the right drivers, everything worked like it use to. Hopefully this helps anyone working with older software.

How to ignore whitespace in a regular expression subject string?

This approach can be used to automate this (the following exemplary solution is in python, although obviously it can be ported to any language):

you can strip the whitespace beforehand AND save the positions of non-whitespace characters so you can use them later to find out the matched string boundary positions in the original string like the following:

def regex_search_ignore_space(regex, string):
    no_spaces = ''
    char_positions = []

    for pos, char in enumerate(string):
        if re.match(r'\S', char):  # upper \S matches non-whitespace chars
            no_spaces += char
            char_positions.append(pos)

    match = re.search(regex, no_spaces)
    if not match:
        return match

    # match.start() and match.end() are indices of start and end
    # of the found string in the spaceless string
    # (as we have searched in it).
    start = char_positions[match.start()]  # in the original string
    end = char_positions[match.end()]  # in the original string
    matched_string = string[start:end]  # see

    # the match WITH spaces is returned.
    return matched_string

with_spaces = 'a li on and a cat'
print(regex_search_ignore_space('lion', with_spaces))
# prints 'li on'

If you want to go further you can construct the match object and return it instead, so the use of this helper will be more handy.

And the performance of this function can of course also be optimized, this example is just to show the path to a solution.

Does Ruby have a string.startswith("abc") built in method?

Your question title and your question body are different. Ruby does not have a starts_with? method. Rails, which is a Ruby framework, however, does, as sepp2k states. See his comment on his answer for the link to the documentation for it.

You could always use a regular expression though:

if SomeString.match(/^abc/) 
   # SomeString starts with abc

^ means "start of string" in regular expressions

How to find files modified in last x minutes (find -mmin does not work as expected)

To search for files in /target_directory and all its sub-directories, that have been modified in the last 60 minutes:

$ find /target_directory -type f -mmin -60

To find the most recently modified files, sorted in the reverse order of update time (i.e., the most recently updated files first):

$ find /etc -type f -printf '%TY-%Tm-%Td %TT %p\n' | sort -r

Android 6.0 Marshmallow. Cannot write to SD Card

Android changed how permissions work with Android 6.0 that's the reason for your errors. You have to actually request and check if the permission was granted by user to use. So permissions in manifest file will only work for api below 21. Check this link for a snippet of how permissions are requested in api23 http://android-developers.blogspot.nl/2015/09/google-play-services-81-and-android-60.html?m=1

Code:-

If (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
                PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_RC);
            return;
        }`


` @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == STORAGE_PERMISSION_RC) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //permission granted  start reading
            } else {
                Toast.makeText(this, "No permission to read external storage.", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

How do I extract text that lies between parentheses (round brackets)?

Here is a general purpose readable function that avoids using regex:

// Returns the text between 'start' and 'end'.
string ExtractBetween(string text, string start, string end)
{
  int iStart = text.IndexOf(start);
  iStart = (iStart == -1) ? 0 : iStart + start.Length;
  int iEnd = text.LastIndexOf(end);
  if(iEnd == -1)
  {
    iEnd = text.Length;
  }
  int len = iEnd - iStart;

  return text.Substring(iStart, len);
}

To call it in your particular example you can do:

string result = ExtractBetween("User name (sales)", "(", ")");

How can I obfuscate (protect) JavaScript?

I can recommend JavaScript Utility by Patrick J. O'Neil. It can obfuscate/compact and compress and it seems to be pretty good at these. That said, I never tried integrating it in a build script of any kind.

As for obfuscating vs. minifying - I am not a big fan of the former. It makes debugging impossible (Error at line 1... "wait, there is only one line") and they always take time to unpack. But if you need to... well.

Safest way to convert float to integer in python?

That this works is not trivial at all! It's a property of the IEEE floating point representation that int°floor = ?·? if the magnitude of the numbers in question is small enough, but different representations are possible where int(floor(2.3)) might be 1.

This post explains why it works in that range.

In a double, you can represent 32bit integers without any problems. There cannot be any rounding issues. More precisely, doubles can represent all integers between and including 253 and -253.

Short explanation: A double can store up to 53 binary digits. When you require more, the number is padded with zeroes on the right.

It follows that 53 ones is the largest number that can be stored without padding. Naturally, all (integer) numbers requiring less digits can be stored accurately.

Adding one to 111(omitted)111 (53 ones) yields 100...000, (53 zeroes). As we know, we can store 53 digits, that makes the rightmost zero padding.

This is where 253 comes from.


More detail: We need to consider how IEEE-754 floating point works.

  1 bit    11 / 8     52 / 23      # bits double/single precision
[ sign |  exponent | mantissa ]

The number is then calculated as follows (excluding special cases that are irrelevant here):

-1sign × 1.mantissa ×2exponent - bias

where bias = 2exponent - 1 - 1, i.e. 1023 and 127 for double/single precision respectively.

Knowing that multiplying by 2X simply shifts all bits X places to the left, it's easy to see that any integer must have all bits in the mantissa that end up right of the decimal point to zero.

Any integer except zero has the following form in binary:

1x...x where the x-es represent the bits to the right of the MSB (most significant bit).

Because we excluded zero, there will always be a MSB that is one—which is why it's not stored. To store the integer, we must bring it into the aforementioned form: -1sign × 1.mantissa ×2exponent - bias.

That's saying the same as shifting the bits over the decimal point until there's only the MSB towards the left of the MSB. All the bits right of the decimal point are then stored in the mantissa.

From this, we can see that we can store at most 52 binary digits apart from the MSB.

It follows that the highest number where all bits are explicitly stored is

111(omitted)111.   that's 53 ones (52 + implicit 1) in the case of doubles.

For this, we need to set the exponent, such that the decimal point will be shifted 52 places. If we were to increase the exponent by one, we cannot know the digit right to the left after the decimal point.

111(omitted)111x.

By convention, it's 0. Setting the entire mantissa to zero, we receive the following number:

100(omitted)00x. = 100(omitted)000.

That's a 1 followed by 53 zeroes, 52 stored and 1 added due to the exponent.

It represents 253, which marks the boundary (both negative and positive) between which we can accurately represent all integers. If we wanted to add one to 253, we would have to set the implicit zero (denoted by the x) to one, but that's impossible.

Maximum call stack size exceeded on npm install

I'm not a Windows user, so if you are, try to check Rene Knop comment.

For Unix/OSX users, I've removed the root .npmrc file ~/.npmrc.
Before you're going to try it, please, check if there is nothing necessary over there you can use this command to bring all content into your terminal: cat ~/.npmrc .

If you have got something like:

cat: /Users/$USER/.npmrc: No such file or directory

to save a copy:

cp ~/.npmrc ~/.npmrc_copy

Now, try to remove it (Works for bash users: Unix / Ubuntu / OSX ...):

rm -f ~/.npmrc

This worked for me.
Hope this will be helpful for others.

TypeError: 'module' object is not callable

When configuring an console_scripts entrypoint in setup.py I found this issue existed when the endpoint was a module or package rather than a function within the module.

Traceback (most recent call last):
   File "/Users/ubuntu/.virtualenvs/virtualenv/bin/mycli", line 11, in <module>
load_entry_point('my-package', 'console_scripts', 'mycli')()
TypeError: 'module' object is not callable

For example

from setuptools import setup
setup (
# ...
    entry_points = {
        'console_scripts': [mycli=package.module.submodule]
    },
# ...
)

Should have been

from setuptools import setup
setup (
# ...
    entry_points = {
        'console_scripts': [mycli=package.module.submodule:main]
    },
# ...
)

So that it would refer to a callable function rather than the module itself. It seems to make no difference if the module has a if __name__ == '__main__': block. This will not make the module callable.

How to get table list in database, using MS SQL 2008?

Answering the question in your title, you can query sys.tables or sys.objects where type = 'U' to check for the existence of a table. You can also use OBJECT_ID('table_name', 'U'). If it returns a non-null value then the table exists:

IF (OBJECT_ID('dbo.My_Table', 'U') IS NULL)
BEGIN
    CREATE TABLE dbo.My_Table (...)
END

You can do the same for databases with DB_ID():

IF (DB_ID('My_Database') IS NULL)
BEGIN
    CREATE DATABASE My_Database
END

If you want to create the database and then start using it, that needs to be done in separate batches. I don't know the specifics of your case, but there shouldn't be many cases where this isn't possible. In a SQL script you can use GO statements. In an application it's easy enough to send across a new command after the database is created.

The only place that you might have an issue is if you were trying to do this in a stored procedure and creating databases on the fly like that is usually a bad idea.

If you really need to do this in one batch, you can get around the issue by using EXEC to get around the parsing error of the database not existing:

CREATE DATABASE Test_DB2

IF (OBJECT_ID('Test_DB2.dbo.My_Table', 'U') IS NULL)
BEGIN
    EXEC('CREATE TABLE Test_DB2.dbo.My_Table (my_id INT)')
END

EDIT: As others have suggested, the INFORMATION_SCHEMA.TABLES system view is probably preferable since it is supposedly a standard going forward and possibly between RDBMSs.

Kubernetes how to make Deployment to update image

UPDATE 2019-06-24

Based on the @Jodiug comment if you have a 1.15 version you can use the command:

kubectl rollout restart deployment/demo

Read more on the issue:

https://github.com/kubernetes/kubernetes/issues/13488


Well there is an interesting discussion about this subject on the kubernetes GitHub project. See the issue: https://github.com/kubernetes/kubernetes/issues/33664

From the solutions described there, I would suggest one of two.

First

1.Prepare deployment

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: demo
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: demo
    spec:
      containers:
      - name: demo
        image: registry.example.com/apps/demo:master
        imagePullPolicy: Always
        env:
        - name: FOR_GODS_SAKE_PLEASE_REDEPLOY
          value: 'THIS_STRING_IS_REPLACED_DURING_BUILD'

2.Deploy

sed -ie "s/THIS_STRING_IS_REPLACED_DURING_BUILD/$(date)/g" deployment.yml
kubectl apply -f deployment.yml

Second (one liner):

kubectl patch deployment web -p \
  "{\"spec\":{\"template\":{\"metadata\":{\"labels\":{\"date\":\"`date +'%s'`\"}}}}}"

Of course the imagePullPolicy: Always is required on both cases.

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);
}

Getting the encoding of a Postgres database

If you want to get database encodings:

psql  -U postgres -h somehost --list

You'll see something like:

List of databases
           Name         |  Owner   | Encoding
------------------------+----------+----------
db1                     | postgres | UTF8

Non greedy (reluctant) regex matching in sed?

sed 's|\(http:\/\/www\.[a-z.0-9]*\/\).*|\1| works too

PHP ternary operator vs null coalescing operator

Ran the below on php interactive mode (php -a on terminal). The comment on each line shows the result.

var_export (false ?? 'value2');   // false
var_export (true  ?? 'value2');   // true
var_export (null  ?? 'value2');   // value2
var_export (''    ?? 'value2');   // ""
var_export (0     ?? 'value2');   // 0

var_export (false ?: 'value2');   // value2
var_export (true  ?: 'value2');   // true
var_export (null  ?: 'value2');   // value2
var_export (''    ?: 'value2');   // value2
var_export (0     ?: 'value2');   // value2

The Null Coalescing Operator ??

  • ?? is like a "gate" that only lets NULL through.
  • So, it always returns first parameter, unless first parameter happens to be NULL.
  • This means ?? is same as ( !isset() || is_null() )

Use of ??

  • shorten !isset() || is_null() check
  • e.g $object = $object ?? new objClassName();

Stacking Null Coalese Operator

        $v = $x ?? $y ?? $z; 

        // This is a sequence of "SET && NOT NULL"s:

        if( $x  &&  !is_null($x) ){ 
            return $x; 
        } else if( $y && !is_null($y) ){ 
            return $y; 
        } else { 
            return $z; 
        }

The Ternary Operator ?:

  • ?: is like a gate that lets anything falsy through - including NULL
  • Anything falsy: 0, empty string, NULL, false, !isset(), empty()
  • Same like old ternary operator: X ? Y : Z
  • Note: ?: will throw PHP NOTICE on undefined (unset or !isset()) variables

Use of ?:

  • checking empty(), !isset(), is_null() etc
  • shorten ternary operation like !empty($x) ? $x : $y to $x ?: $y
  • shorten if(!$x) { echo $x; } else { echo $y; } to echo $x ?: $y

Stacking Ternary Operator

        echo 0 ?: 1 ?: 2 ?: 3; //1
        echo 1 ?: 0 ?: 3 ?: 2; //1
        echo 2 ?: 1 ?: 0 ?: 3; //2
        echo 3 ?: 2 ?: 1 ?: 0; //3
    
        echo 0 ?: 1 ?: 2 ?: 3; //1
        echo 0 ?: 0 ?: 2 ?: 3; //2
        echo 0 ?: 0 ?: 0 ?: 3; //3

    
        // Source & Credit: http://php.net/manual/en/language.operators.comparison.php#95997
   
        // This is basically a sequence of:

 
        if( truthy ) {}
        else if(truthy ) {}
        else if(truthy ) {}
        ..
        else {}

Stacking both, we can shorten this:

        if( isset($_GET['name']) && !is_null($_GET['name'])) {
            $name = $_GET['name'];
        } else if( !empty($user_name) ) {
             $name = $user_name; 
        } else {
            $name = 'anonymous';
        }

To this:

        $name = $_GET['name'] ?? $user_name ?: 'anonymous';

Cool, right? :-)

How to get the Touch position in android?

@Override
    public boolean onTouch(View v, MotionEvent event) {
       float x = event.getX();
       float y = event.getY();
       return true;
    }

Convert `List<string>` to comma-separated string

In .NET 4 you don't need the ToArray() call - string.Join is overloaded to accept IEnumerable<T> or just IEnumerable<string>.

There are potentially more efficient ways of doing it before .NET 4, but do you really need them? Is this actually a bottleneck in your code?

You could iterate over the list, work out the final size, allocate a StringBuilder of exactly the right size, then do the join yourself. That would avoid the extra array being built for little reason - but it wouldn't save much time and it would be a lot more code.

CURRENT_DATE/CURDATE() not working as default DATE value

I came to this page with the same question in mind, but it worked for me!, Just thought to update here , may be helpful for someone later!!

MariaDB [niffdb]> desc invoice;
+---------+--------+------+-----+---------+----------------+
| Field   | Type   | Null | Key | Default | Extra          |
+---------+--------+------+-----+---------+----------------+
| inv_id  | int(4) | NO   | PRI | NULL    | auto_increment |
| cust_id | int(4) | NO   | MUL | NULL    |                |
| inv_dt  | date   | NO   |     | NULL    |                |
| smen_id | int(4) | NO   | MUL | NULL    |                |
+---------+--------+------+-----+---------+----------------+
4 rows in set (0.003 sec)

MariaDB [niffdb]> ALTER TABLE invoice MODIFY inv_dt DATE NOT NULL DEFAULT (CURRENT_DATE);
Query OK, 0 rows affected (0.003 sec)
Records: 0  Duplicates: 0  Warnings: 0

MariaDB [niffdb]> desc invoice;
+---------+--------+------+-----+-----------+----------------+
| Field   | Type   | Null | Key | Default   | Extra          |
+---------+--------+------+-----+-----------+----------------+
| inv_id  | int(4) | NO   | PRI | NULL      | auto_increment |
| cust_id | int(4) | NO   | MUL | NULL      |                |
| inv_dt  | date   | NO   |     | curdate() |                |
| smen_id | int(4) | NO   | MUL | NULL      |                |
+---------+--------+------+-----+-----------+----------------+
4 rows in set (0.002 sec)

MariaDB [niffdb]> SELECT VERSION();
+---------------------------+
| VERSION()                 |
+---------------------------+
| 10.3.18-MariaDB-0+deb10u1 |
+---------------------------+
1 row in set (0.010 sec)

MariaDB [niffdb]>

Count number of occurrences by month

Sooooo, I had this same question. here's my answer: COUNTIFS(sheet1!$A:$A,">="&D1,sheet1!$A:$A,"<="&D2)

you don't need to specify A2:A50, unless there are dates beyond row 50 that you wish to exclude. this is cleaner in the sense that you don't have to go back and adjust the rows as more PO data comes in on sheet1.

also, the reference to D1 and D2 are start and end dates (respectively) for each month. On sheet2, you could have a hidden column that translates April to 4/1/2014, May into 5/1/2014, etc. THen, D1 would reference the cell that contains 4/1/2014, and D2 would reference the cell that contains 5/1/2014.

if you want to sum, it works the same way, except that the first argument is the sum array (column or row) and then the rest of the ranges/arrays and arguments are the same as the countifs formula.

btw-this works in excel AND google sheets. cheers

How do I group Windows Form radio buttons?

If you cannot put them into one container, then you have to write code to change checked state of each RadioButton:

private void rbDataSourceFile_CheckedChanged(object sender, EventArgs e)
{
    rbDataSourceNet.Checked = !rbDataSourceFile.Checked;
}

private void rbDataSourceNet_CheckedChanged(object sender, EventArgs e)
{
  rbDataSourceFile.Checked = !rbDataSourceNet.Checked;
}

Replace Both Double and Single Quotes in Javascript String

You don't need to escape it inside. You can use the | character to delimit searches.

"\"foo\"\'bar\'".replace(/("|')/g, "")

How can we redirect a Java program console output to multiple files?

We can do this by setting out variable of System class in the following way

System.setOut(new PrintStream(new FileOutputStream("Path to output file"))). Also You need to close or flush 'out'(System.out.close() or System.out.flush()) variable so that you don't end up missing some output.

Source : http://xmodulo.com/how-to-save-console-output-to-file-in-eclipse.html

Convert UTF-8 to base64 string

It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==, the following should work:

byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);

This will output: YWJjZGVmPT0= which is abcdef== encoded in Base64.

Edit:

To decode a Base64 string, simply use Convert.FromBase64String(). E.g.

string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);

At this point, bytes will be a byte[] (not a string). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:

string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);

This will output the original input string, abcdef== in this case.

How to use patterns in a case statement?

I don't think you can use braces.

According to the Bash manual about case in Conditional Constructs.

Each pattern undergoes tilde expansion, parameter expansion, command substitution, and arithmetic expansion.

Nothing about Brace Expansion unfortunately.

So you'd have to do something like this:

case $1 in
    req*)
        ...
        ;;
    met*|meet*)
        ...
        ;;
    *)
        # You should have a default one too.
esac

Android Fragments and animation

To animate the transition between fragments, or to animate the process of showing or hiding a fragment you use the Fragment Manager to create a Fragment Transaction.

Within each Fragment Transaction you can specify in and out animations that will be used for show and hide respectively (or both when replace is used).

The following code shows how you would replace a fragment by sliding out one fragment and sliding the other one in it's place.

FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);

DetailsFragment newFragment = DetailsFragment.newInstance();

ft.replace(R.id.details_fragment_container, newFragment, "detailFragment");

// Start the animated transition.
ft.commit();

To achieve the same thing with hiding or showing a fragment you'd simply call ft.show or ft.hide, passing in the Fragment you wish to show or hide respectively.

For reference, the XML animation definitions would use the objectAnimator tag. An example of slide_in_left might look something like this:

<?xml version="1.0" encoding="utf-8"?>
<set>
  <objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
    android:propertyName="x" 
    android:valueType="floatType"
    android:valueFrom="-1280"
    android:valueTo="0" 
    android:duration="500"/>
</set>

Check whether a path is valid

private bool IsValidPath(string path)
{
    Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
    if (!driveCheck.IsMatch(path.Substring(0, 3))) return false;
    string strTheseAreInvalidFileNameChars = new string(Path.GetInvalidPathChars());
    strTheseAreInvalidFileNameChars += @":/?*" + "\"";
    Regex containsABadCharacter = new Regex("[" + Regex.Escape(strTheseAreInvalidFileNameChars) + "]");
    if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
        return false;

    DirectoryInfo dir = new DirectoryInfo(Path.GetFullPath(path));
    if (!dir.Exists)
        dir.Create();
    return true;
}

AngularJS $location not changing the path

I had to embed my $location.path() statement like this because my digest was still running:

       function routeMe(data) {                
            var waitForRender = function () {
                if ($http.pendingRequests.length > 0) {
                    $timeout(waitForRender);
                } else {
                    $location.path(data);
                }
            };
            $timeout(waitForRender);
        }

Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table

I've found this to work very well. It uses the .range property of the .autofilter object, which seems to be a rather obscure, but very handy, feature:

Sub copyfiltered()
    ' Copies the visible columns
    ' and the selected rows in an autofilter
    '
    ' Assumes that the filter was previously applied
    '
    Dim wsIn As Worksheet
    Dim wsOut As Worksheet

    Set wsIn = Worksheets("Sheet1")
    Set wsOut = Worksheets("Sheet2")

    ' Hide the columns you don't want to copy
    wsIn.Range("B:B,D:D").EntireColumn.Hidden = True

    'Copy the filtered rows from wsIn and and paste in wsOut
    wsIn.AutoFilter.Range.Copy Destination:=wsOut.Range("A1")
End Sub

OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow

I also met the error message in raspberry pi 3, but my solution is reload kernel of camera after search on google, hope it can help you.

sudo modprobe bcm2835-v4l2

BTW, for this error please check your camera and file path is workable or not

How can I add 1 day to current date?

To add one day to a date object:

var date = new Date();

// add a day
date.setDate(date.getDate() + 1);