Programs & Examples On #Ucma

Unified Communications Managed API (UCMA)

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

Similar situation. It was working. Then, I started to include pytables. At first view, no reason to errors. I decided to use another function, that has a domain constraint (elipse) and received the following error:

TypeError: 'numpy.float64' object cannot be interpreted as an integer

or

TypeError: 'numpy.float64' object is not iterable

The crazy thing: the previous function I was using, no code changed, started to return the same error. My intermediary function, already used was:

def MinMax(x, mini=0, maxi=1)
    return max(min(x,mini), maxi)

The solution was avoid numpy or math:

def MinMax(x, mini=0, maxi=1)
    x = [x_aux if x_aux > mini else mini for x_aux in x]
    x = [x_aux if x_aux < maxi else maxi for x_aux in x]
    return max(min(x,mini), maxi)

Then, everything calm again. It was like one library possessed max and min!

jQuery Ajax calls and the Html.AntiForgeryToken()

I'm using a ajax post to run a delete method (happens to be from a visjs timeline but that's not relelvant). This is what I sis:

This is my Index.cshtml

@Scripts.Render("~/bundles/schedule")
@Styles.Render("~/bundles/visjs")
@Html.AntiForgeryToken()

<!-- div to attach schedule to -->
<div id='schedule'></div>

<!-- div to attach popups to -->
<div id='dialog-popup'></div>

All I added here was @Html.AntiForgeryToken() to make the token appear in the page

Then in my ajax post I used:

$.ajax(
    {
        type: 'POST',
        url: '/ScheduleWorks/Delete/' + item.id,
        data: {
            '__RequestVerificationToken': 
            $("input[name='__RequestVerificationToken']").val()
              }
     }
);

Which adds the token value, scraped off the page, to the fields posted

Before this I tried putting the value in the headers but I got the same error

Feel free to post improvements. This certainly seems to be a simple approach that I can understand

Can a website detect when you are using Selenium with chromedriver?

Basically, the way the Selenium detection works, is that they test for predefined JavaScript variables which appear when running with Selenium. The bot detection scripts usually look anything containing word "selenium" / "webdriver" in any of the variables (on window object), and also document variables called $cdc_ and $wdc_. Of course, all of this depends on which browser you are on. All the different browsers expose different things.

For me, I used Chrome, so, all that I had to do was to ensure that $cdc_ didn't exist anymore as a document variable, and voilà (download chromedriver source code, modify chromedriver and re-compile $cdc_ under different name.)

This is the function I modified in chromedriver:

File call_function.js:

function getPageCache(opt_doc) {
  var doc = opt_doc || document;
  //var key = '$cdc_asdjflasutopfhvcZLmcfl_';
  var key = 'randomblabla_';
  if (!(key in doc))
    doc[key] = new Cache();
  return doc[key];
}

(Note the comment. All I did I turned $cdc_ to randomblabla_.)

Here is pseudocode which demonstrates some of the techniques that bot networks might use:

runBotDetection = function () {
    var documentDetectionKeys = [
        "__webdriver_evaluate",
        "__selenium_evaluate",
        "__webdriver_script_function",
        "__webdriver_script_func",
        "__webdriver_script_fn",
        "__fxdriver_evaluate",
        "__driver_unwrapped",
        "__webdriver_unwrapped",
        "__driver_evaluate",
        "__selenium_unwrapped",
        "__fxdriver_unwrapped",
    ];

    var windowDetectionKeys = [
        "_phantom",
        "__nightmare",
        "_selenium",
        "callPhantom",
        "callSelenium",
        "_Selenium_IDE_Recorder",
    ];

    for (const windowDetectionKey in windowDetectionKeys) {
        const windowDetectionKeyValue = windowDetectionKeys[windowDetectionKey];
        if (window[windowDetectionKeyValue]) {
            return true;
        }
    };
    for (const documentDetectionKey in documentDetectionKeys) {
        const documentDetectionKeyValue = documentDetectionKeys[documentDetectionKey];
        if (window['document'][documentDetectionKeyValue]) {
            return true;
        }
    };

    for (const documentKey in window['document']) {
        if (documentKey.match(/\$[a-z]dc_/) && window['document'][documentKey]['cache_']) {
            return true;
        }
    }

    if (window['external'] && window['external'].toString() && (window['external'].toString()['indexOf']('Sequentum') != -1)) return true;

    if (window['document']['documentElement']['getAttribute']('selenium')) return true;
    if (window['document']['documentElement']['getAttribute']('webdriver')) return true;
    if (window['document']['documentElement']['getAttribute']('driver')) return true;

    return false;
};

According to user szx, it is also possible to simply open chromedriver.exe in a hex editor, and just do the replacement manually, without actually doing any compiling.

How can the error 'Client found response content type of 'text/html'.. be interpreted

I had this happen as a result of a configuration error in web.config. Checking the connection string etc might be the answer for the time out.

I cannot access tomcat admin console?

Your tomcat-users.xml looks good.

Make sure you have the manager/ application inside your $CATALINA_BASE/webapps/

  • Linux:

You have to install tomcat-admin package: sudo apt-get install tomcat8-admin (for version 8)

  • Windows:

I am using Eclipse. I had to copy the manager/ folder from C:\Program Files\apache-tomcat-8.5.20\webapps to my Eclipse workspace (~\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\webapps\).

pip install returning invalid syntax

Try:

pip3 install bs4

If you have python2 installed you typically have to make sure you are using the correct version of pip.

Detecting when user scrolls to bottom of div with jQuery

If you need to use this on a div that has overflow-y as hidden or scroll, something like this may be what you need.

if ($('#element').prop('scrollHeight') - $('#element').scrollTop() <= Math.ceil($('#element').height())) {
    at_bottom = true;
}

I found ceil was needed because prop scrollHeight seems to round, or perhaps some other reason causing this to be off by less than 1.

Reporting Services export to Excel with Multiple Worksheets

Put the tab name on the page header or group TableRow1 in your report so that it will appear in the "A1" position on each Excel sheet. Then run this macro in your Excel workbook.

Sub SelectSheet()
        For i = 1 To ThisWorkbook.Sheets.Count
        mysheet = "Sheet" & i
        On Error GoTo 10
        Sheets(mysheet).Select
        Set Target = Range("A1")
        If Target = "" Then Exit Sub
        On Error GoTo Badname
        ActiveSheet.Name = Left(Target, 31)
        GoTo 10
Badname:
        MsgBox "Please revise the entry in A1." & Chr(13) _
        & "It appears to contain one or more " & Chr(13) _
        & "illegal characters." & Chr(13)
        Range("A1").Activate
10
        Next i
End Sub

How to change the default background color white to something else in twitter bootstrap

I would not recommend changing the actual bootstrap CSS files. If you do not want to use Jako's first solution you can create a custom bootstrap style sheet with one of the available Bootstrap theme generator (Bootstrap theme generators). That way you can use 1 style sheet with all of the default Bootstrap CSS with just the one change to it that you want. With a Bootstrap theme generator you do not need to write any CSS. You only need to set the hex values for the color you want for the body (Scaffolding; bodyBackground).

How to add local jar files to a Maven project?

To install third party jar, Please call the command like below

mvn install:install-file -DgroupId= -DartifactId= -Dversion= -Dpackaging=jar -Dfile=path

How to set proper codeigniter base url?

Check

config > config

codeigniter file structure

replace

$config['base_url'] = "your Website url";

with

$config['base_url']  =  "http://".$_SERVER['HTTP_HOST'];

$config['base_url'] .= preg_replace('@/+$@', '', dirname($_SERVER['SCRIPT_NAME'])).'/';

Regular expression for decimal number

There is an alternative approach, which does not have I18n problems (allowing ',' or '.' but not both): Decimal.TryParse.

Just try converting, ignoring the value.

bool IsDecimalFormat(string input) {
  Decimal dummy;
  return Decimal.TryParse(input, out dummy);
}

This is significantly faster than using a regular expression, see below.

(The overload of Decimal.TryParse can be used for finer control.)


Performance test results: Decimal.TryParse: 0.10277ms, Regex: 0.49143ms

Code (PerformanceHelper.Run is a helper than runs the delegate for passed iteration count and returns the average TimeSpan.):

using System;
using System.Text.RegularExpressions;
using DotNetUtils.Diagnostics;

class Program {
    static private readonly string[] TestData = new string[] {
        "10.0",
        "10,0",
        "0.1",
        ".1",
        "Snafu",
        new string('x', 10000),
        new string('2', 10000),
        new string('0', 10000)
    };

    static void Main(string[] args) {
        Action parser = () => {
            int n = TestData.Length;
            int count = 0;
            for (int i = 0; i < n; ++i) {
                decimal dummy;
                count += Decimal.TryParse(TestData[i], out dummy) ? 1 : 0;
            }
        };
        Regex decimalRegex = new Regex(@"^[0-9]([\.\,][0-9]{1,3})?$");
        Action regex = () => {
            int n = TestData.Length;
            int count = 0;
            for (int i = 0; i < n; ++i) {
                count += decimalRegex.IsMatch(TestData[i]) ? 1 : 0;
            }
        };

        var paserTotal = 0.0;
        var regexTotal = 0.0;
        var runCount = 10;
        for (int run = 1; run <= runCount; ++run) {
            var parserTime = PerformanceHelper.Run(10000, parser);
            var regexTime = PerformanceHelper.Run(10000, regex);

            Console.WriteLine("Run #{2}: Decimal.TryParse: {0}ms, Regex: {1}ms",
                              parserTime.TotalMilliseconds, 
                              regexTime.TotalMilliseconds,
                              run);
            paserTotal += parserTime.TotalMilliseconds;
            regexTotal += regexTime.TotalMilliseconds;
        }

        Console.WriteLine("Overall averages: Decimal.TryParse: {0}ms, Regex: {1}ms",
                          paserTotal/runCount,
                          regexTotal/runCount);
    }
}

Access-Control-Allow-Origin wildcard subdomains, ports and protocols

The CORS spec is all-or-nothing. It only supports *, null or the exact protocol + domain + port: http://www.w3.org/TR/cors/#access-control-allow-origin-response-header

Your server will need to validate the origin header using the regex, and then you can echo the origin value in the Access-Control-Allow-Origin response header.

What is the best way to remove the first element from an array?

The size of arrays in Java cannot be changed. So, technically you cannot remove any elements from the array.

One way to simulate removing an element from the array is to create a new, smaller array, and then copy all of the elements from the original array into the new, smaller array.

String[] yourArray = Arrays.copyOfRange(oldArr, 1, oldArr.length);

However, I would not suggest the above method. You should really be using a List<String>. Lists allow you to add and remove items from any index. That would look similar to the following:

List<String> list = new ArrayList<String>(); // or LinkedList<String>();
list.add("Stuff");
// add lots of stuff
list.remove(0); // removes the first item

Usage of @see in JavaDoc?

@see is useful for information about related methods/classes in an API. It will produce a link to the referenced method/code on the documentation. Use it when there is related code that might help the user understand how to use the API.

ReactJS: Warning: setState(...): Cannot update during an existing state transition

This same warning will be emitted on any state changes done in a render() call.

An example of a tricky to find case: When rendering a multi-select GUI component based on state data, if state has nothing to display, a call to resetOptions() is considered state change for that component.

The obvious fix is to do resetOptions() in componentDidUpdate() instead of render().

Twitter Bootstrap Button Text Word Wrap

FWIW, in Boostrap 4.4, you can add .text-wrap style to things like buttons:

   <a href="#" class="btn btn-primary text-wrap">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</a>

https://getbootstrap.com/docs/4.4/utilities/text/#text-wrapping-and-overflow

AngularJs event to call after content is loaded

If you're getting a $digest already in progress error, this might help:

return {
        restrict: 'A',
        link: function( $scope, elem, attrs ) {
            elem.ready(function(){

                if(!$scope.$$phase) {
                    $scope.$apply(function(){
                        var func = $parse(attrs.elemReady);
                        func($scope);
                    })
                }
                else {

                    var func = $parse(attrs.elemReady);
                    func($scope);
                }

            })
        }
    }

Using LINQ to concatenate strings

I blogged about this a while ago, what I did seams to be exactly what you're looking for:

http://ondevelopment.blogspot.com/2009/02/string-concatenation-made-easy.html

In the blog post describe how to implement extension methods that works on IEnumerable and are named Concatenate, this will let you write things like:

var sequence = new string[] { "foo", "bar" };
string result = sequence.Concatenate();

Or more elaborate things like:

var methodNames = typeof(IFoo).GetMethods().Select(x => x.Name);
string result = methodNames.Concatenate(", ");

Google Chrome Printing Page Breaks

Have that issue. So long time pass... Without side-fields of page it's break normal, but when fields appears, page and "page break space" will scale. So, with a normal field, within a document, it was shown incorrect. I fix it with set

    width:100%

and use

div.page
  {
    page-break-before: always;
    page-break-inside: avoid;
  }

Use it on first line.

How to generate UL Li list from string array using jquery?

    <script type="text/javascript" >
        function aa()
        {
            var YourArray = ['United States', 'Canada', 'Argentina', 'Armenia'];
            var ObjUl = $('<ul></ul>');
            for (i = 0; i < YourArray.length; i++)
            {
                var Objli = $('<li></li>');
                var Obja = $('<a></a>');

                ObjUl.addClass("ui-menu-item");
                ObjUl.attr("role", "menuitem");

                Obja.addClass("ui-all");
                Obja.attr("tabindex", "-1");

                Obja.text(YourArray[i]);
                Objli.append(Obja);

                ObjUl.append(Objli);
            }
            $('.DivSai').append(ObjUl);
        }
    </script>
</head>
<body onload="aa()">
    <form id="form1" runat="server">
    <div class="DivSai" >

    </div>
    </form>
</body>

How do I manage MongoDB connections in a Node.js web application?

I have implemented below code in my project to implement connection pooling in my code so it will create a minimum connection in my project and reuse available connection

/* Mongo.js*/

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/yourdatabasename"; 
var assert = require('assert');

var connection=[];
// Create the database connection
establishConnection = function(callback){

                MongoClient.connect(url, { poolSize: 10 },function(err, db) {
                    assert.equal(null, err);

                        connection = db
                        if(typeof callback === 'function' && callback())
                            callback(connection)

                    }

                )



}

function getconnection(){
    return connection
}

module.exports = {

    establishConnection:establishConnection,
    getconnection:getconnection
}

/*app.js*/
// establish one connection with all other routes will use.
var db = require('./routes/mongo')

db.establishConnection();

//you can also call with callback if you wanna create any collection at starting
/*
db.establishConnection(function(conn){
  conn.createCollection("collectionName", function(err, res) {
    if (err) throw err;
    console.log("Collection created!");
  });
};
*/

// anyother route.js

var db = require('./mongo')

router.get('/', function(req, res, next) {
    var connection = db.getconnection()
    res.send("Hello");

});

Performing user authentication in Java EE / JSF using j_security_check

The issue HttpServletRequest.login does not set authentication state in session has been fixed in 3.0.1. Update glassfish to the latest version and you're done.

Updating is quite straightforward:

glassfishv3/bin/pkg set-authority -P dev.glassfish.org
glassfishv3/bin/pkg image-update

Android Fastboot devices not returning device

For Windows:

  • Open device manager
  • Find Unknown "Android" device (likely listed under Other devices with an exclamation mark)
  • Update driver
  • Browse my computer for driver software
  • Let me pick from a list of devices, select List All Devices
  • Under "Android device" or "Google Inc", you will find "Android Bootloader Interface"
  • Choose "Android Bootloader Interface"
  • Click "yes" when it says that driver might not be compatible

How to make a simple image upload using Javascript/HTML

<li class="list-group-item active"><h5>Feaured Image</h5></li>
            <li class="list-group-item">
                <div class="input-group mb-3">
                    <div class="custom-file ">
                        <input type="file"  class="custom-file-input" name="thumbnail" id="thumbnail">
                        <label class="custom-file-label" for="thumbnail">Choose file</label>
                    </div>
                </div>
                <div class="img-thumbnail  text-center">
                    <img src="@if(isset($product)) {{asset('storage/'.$product->thumbnail)}} @else {{asset('images/no-thumbnail.jpeg')}} @endif" id="imgthumbnail" class="img-fluid" alt="">
                </div>
            </li>
<script>
$(function(){
$('#thumbnail').on('change', function() {
    var file = $(this).get(0).files;
    var reader = new FileReader();
    reader.readAsDataURL(file[0]);
    reader.addEventListener("load", function(e) {
    var image = e.target.result;
$("#imgthumbnail").attr('src', image);
});
});
}
</script>

Use a content script to access the page context variables and functions

I've also faced the problem of ordering of loaded scripts, which was solved through sequential loading of scripts. The loading is based on Rob W's answer.

function scriptFromFile(file) {
    var script = document.createElement("script");
    script.src = chrome.extension.getURL(file);
    return script;
}

function scriptFromSource(source) {
    var script = document.createElement("script");
    script.textContent = source;
    return script;
}

function inject(scripts) {
    if (scripts.length === 0)
        return;
    var otherScripts = scripts.slice(1);
    var script = scripts[0];
    var onload = function() {
        script.parentNode.removeChild(script);
        inject(otherScripts);
    };
    if (script.src != "") {
        script.onload = onload;
        document.head.appendChild(script);
    } else {
        document.head.appendChild(script);
        onload();
    }
}

The example of usage would be:

var formulaImageUrl = chrome.extension.getURL("formula.png");
var codeImageUrl = chrome.extension.getURL("code.png");

inject([
    scriptFromSource("var formulaImageUrl = '" + formulaImageUrl + "';"),
    scriptFromSource("var codeImageUrl = '" + codeImageUrl + "';"),
    scriptFromFile("EqEditor/eq_editor-lite-17.js"),
    scriptFromFile("EqEditor/eq_config.js"),
    scriptFromFile("highlight/highlight.pack.js"),
    scriptFromFile("injected.js")
]);

Actually, I'm kinda new to JS, so feel free to ping me to the better ways.

Plot size and resolution with R markdown, knitr, pandoc, beamer

I think that is a frequently asked question about the behavior of figures in beamer slides produced from Pandoc and markdown. The real problem is, R Markdown produces PNG images by default (from knitr), and it is hard to get the size of PNG images correct in LaTeX by default (I do not know why). It is fairly easy, however, to get the size of PDF images correct. One solution is to reset the default graphical device to PDF in your first chunk:

```{r setup, include=FALSE}
knitr::opts_chunk$set(dev = 'pdf')
```

Then all the images will be written as PDF files, and LaTeX will be happy.

Your second problem is you are mixing up the HTML units with LaTeX units in out.width / out.height. LaTeX and HTML are very different technologies. You should not expect \maxwidth to work in HTML, or 200px in LaTeX. Especially when you want to convert Markdown to LaTeX, you'd better not set out.width / out.height (use fig.width / fig.height and let LaTeX use the original size).

Running an Excel macro via Python?

Hmm i was having some trouble with that part (yes still xD):

xl.Application.Run("excelsheet.xlsm!macroname.macroname")

cos im not using excel often (same with vb or macros, but i need it to use femap with python) so i finaly resolved it checking macro list: Developer -> Macros: there i saw that: this macroname.macroname should be sheet_name.macroname like in "Macros" list.

(i spend something like 30min-1h trying to solve it, so it may be helpful for noobs like me in excel) xD

How to add data into ManyToMany field?

In case someone else ends up here struggling to customize admin form Many2Many saving behaviour, you can't call self.instance.my_m2m.add(obj) in your ModelForm.save override, as ModelForm.save later populates your m2m from self.cleaned_data['my_m2m'] which overwrites your changes. Instead call:

my_m2ms = list(self.cleaned_data['my_m2ms'])
my_m2ms.extend(my_custom_new_m2ms)
self.cleaned_data['my_m2ms'] = my_m2ms

(It is fine to convert the incoming QuerySet to a list - the ManyToManyField does that anyway.)

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

Following the logic behind @CoryM's answer above :

After trying EVERY solution google came up with on stack overflow, I found what my particular problem was. I had edited my hosts file a long time ago to allow me to access my localhost from my virtualbox.

Removing this entry solved it for me...

I had edited my hosts file too for Python Machine Learning setup 2 months ago. So instead of removing it because I still need it, I use 127.0.0.1 in place of localhost and it worked :

mongoose.connect('mongodb://127.0.0.1/testdb')

How do you append to a file?

You can also open the file in r+ mode and then set the file position to the end of the file.

import os

with open('text.txt', 'r+') as f:
    f.seek(0, os.SEEK_END)
    f.write("text to add")

Opening the file in r+ mode will let you write to other file positions besides the end, while a and a+ force writing to the end.

Markdown `native` text alignment

In Github You need to write:

<p align="justify">
  Lorem ipsum
</p>

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

In Microsoft SQL Server (T-SQL) this can be done as follows

--beginning of year
select '01/01/' + LTRIM(STR(YEAR(CURRENT_TIMESTAMP)))

--end of year
select '12/31/' + LTRIM(STR(YEAR(CURRENT_TIMESTAMP)))

CURRENT_TIMESTAMP - returns the sql server date at the time of execution of the query.

YEAR - gets the year part of the current time stamp.

STR , LTRIM - these two functions are applied so that we can convert this into a varchar that can be concatinated with our desired prefix (in this case it's either first date of the year or the last date of the year). For whatever reason the result generated by the YEAR function has prefixing spaces. To fix them we use the LTRIM function which is left trim.

How to extract duration time from ffmpeg output?

For those who want to perform the same calculations with no additional software in Windows, here is the script for command line script:

set input=video.ts

ffmpeg -i "%input%" 2> output.tmp

rem search "  Duration: HH:MM:SS.mm, start: NNNN.NNNN, bitrate: xxxx kb/s"
for /F "tokens=1,2,3,4,5,6 delims=:., " %%i in (output.tmp) do (
    if "%%i"=="Duration" call :calcLength %%j %%k %%l %%m
)
goto :EOF

:calcLength
set /A s=%3
set /A s=s+%2*60
set /A s=s+%1*60*60
set /A VIDEO_LENGTH_S = s
set /A VIDEO_LENGTH_MS = s*1000 + %4
echo Video duration %1:%2:%3.%4 = %VIDEO_LENGTH_MS%ms = %VIDEO_LENGTH_S%s

Same answer posted here: How to crop last N seconds from a TS video

How do I list all the columns in a table?

MS SQL Server:

sp_columns [tablename]

What is MVC and what are the advantages of it?

Jeff has a post about it, otherwise I found some useful documents on Apple's website, in Cocoa tutorials (this one for example).

Sending message through WhatsApp

this is much lengthy but surly working. enjoy your code:)

 //method used to show IMs
private void show_custom_chooser(String value) {
    List<ResolveInfo> list = null;
    final Intent email = new Intent(Intent.ACTION_SEND);
    email.setData(Uri.parse("sms:"));
    email.putExtra(Intent.EXTRA_TEXT, "" + value);
    email.setType("text/plain"); // vnd.android-dir/mms-sms

    WindowManager.LayoutParams WMLP = dialogCustomChooser.getWindow()
            .getAttributes();
    WMLP.gravity = Gravity.CENTER;
    dialogCustomChooser.getWindow().setAttributes(WMLP);
    dialogCustomChooser.getWindow().setBackgroundDrawable(
            new ColorDrawable(android.graphics.Color.TRANSPARENT));
    dialogCustomChooser.setCanceledOnTouchOutside(true);
    dialogCustomChooser.setContentView(R.layout.about_dialog);
    dialogCustomChooser.setCancelable(true);
    ListView lvOfIms = (ListView) dialogCustomChooser
            .findViewById(R.id.listView1);
    PackageManager pm = getPackageManager();
    List<ResolveInfo> launchables = pm.queryIntentActivities(email, 0);
    // ////////////new
    list = new ArrayList<ResolveInfo>();
    for (int i = 0; i < launchables.size(); i++) {
        String string = launchables.get(i).toString();
        Log.d("heh", string);
//check only messangers
        if (string.contains("whatsapp")) {
            list.add(launchables.get(i));
        }
    }
    Collections.sort(list, new ResolveInfo.DisplayNameComparator(pm));
    int size = launchables.size();
    adapter = new AppAdapter(pm, list, MainActivity.this);
    lvOfIms.setAdapter(adapter);
    lvOfIms.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1,
                int position, long arg3) {
            ResolveInfo launchable = adapter.getItem(position);
            ActivityInfo activity = launchable.activityInfo;
            ComponentName name = new ComponentName(
                    activity.applicationInfo.packageName, activity.name);
            email.addCategory(Intent.CATEGORY_LAUNCHER);
            email.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            email.setComponent(name);
            startActivity(email);
            dialogCustomChooser.dismiss();
        }
    });
    dialogCustomChooser.show();

}

Convert a Map<String, String> to a POJO

The answers provided so far using Jackson are so good, but still you could have a util function to help you convert different POJOs as follows:

    public static <T> T convert(Map<String, Object> aMap, Class<T> t) {
        try {
            return objectMapper
                    .convertValue(aMap, objectMapper.getTypeFactory().constructType(t));
        } catch (Exception e) {
            log.error("converting failed! aMap: {}, class: {}", getJsonString(aMap), t.getClass().getSimpleName(), e);
        }
        return null;
    }

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

I have the same exact error message while I was doing my unit test and throwing observable exception after mocking my services.

I resolved it by passing exact function and format inside Observable.throw.

Actual code which calls the service and subscribe to get data. notice that catch to handle the 400 error.

     this.search(event).catch((e: Response) => {
        if (e.status === 400) {
          console.log(e.json().message);
        } else if (e.url) {
          console.log('HTTP Error: ' + e.status + ' ' + e.statusText,
            'URL: ' + e.url, 'Info: ' + e.json().message));
        }
      }).finally(() => {
        this.loading = false;
      }).subscribe((bData) => {
        this.data = bData;
      });

The code inside the service

  search() {
    return this.someService.getData(request)
       .do((r) => {
          this.someService.defaultHeaders.delete('skipAlert');
          return r;
        })
      .map((r) => {
          return r.businessObjectDataElements.length && r.businessObjectDataElements || null;
        });
  }

Unit Testing

I have mocked the SomeService and returning observable data and its fine as it have all the required methods inside it.

 someServiceApi = fixture.debugElement.injector.get(SomeService);
 spyOn(someServiceApi, 'getData').and.returnValue(Observable.of({}));

The above code is okey but when when I was trying to test the catch/error condition by passing Observable.throw({}) it was showing me the error as it was expecting Response type return from the service.

So below service mocking return was giving me that error.

someServiceApi.getData
  .and.returnValue(Observable.throw(new Response({status: 400, body: [], message: 'not found error'})));

So I Corrected it by replicating the exact expected function in my return object rather passing a Response type value.

someServiceApi.getData
  .and.returnValue(Observable.throw({status: 400, json: () => { return {message: 'not found error'}}, body: []}));
// see `json: () => { return {message: 'not found error'}}` inside return value

How to resolve Value cannot be null. Parameter name: source in linq?

When you call a Linq statement like this:

// x = new List<string>();
var count = x.Count(s => s.StartsWith("x"));

You are actually using an extension method in the System.Linq namespace, so what the compiler translates this into is:

var count = Enumerable.Count(x, s => s.StartsWith("x"));

So the error you are getting above is because the first parameter, source (which would be x in the sample above) is null.

Git - Ignore files during merge

I ended up finding git attributes. Trying it. Working so far. Did not check all scenarios yet. But it should be the solution.

Merge Strategies - Git attributes

Format y axis as percent

Based on the answer of @erwanp, you can use the formatted string literals of Python 3,

x = '2'
percentage = f'{x}%' # 2%

inside the FuncFormatter() and combined with a lambda expression.

All wrapped:

ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: f'{y}%'))

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

You can configure an inputType for your EditText:

<EditText android:inputType="number" ... />

How to stop asynctask thread in android?

You can't just kill asynctask immediately. In order it to stop you should first cancel it:

task.cancel(true);

and than in asynctask's doInBackground() method check if it's already cancelled:

isCancelled()

and if it is, stop executing it manually.

Converting from hex to string

For Unicode support:

public class HexadecimalEncoding
{
    public static string ToHexString(string str)
    {
        var sb = new StringBuilder();

        var bytes = Encoding.Unicode.GetBytes(str);
        foreach (var t in bytes)
        {
            sb.Append(t.ToString("X2"));
        }

        return sb.ToString(); // returns: "48656C6C6F20776F726C64" for "Hello world"
    }

    public static string FromHexString(string hexString)
    {
        var bytes = new byte[hexString.Length / 2];
        for (var i = 0; i < bytes.Length; i++)
        {
            bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
        }

        return Encoding.Unicode.GetString(bytes); // returns: "Hello world" for "48656C6C6F20776F726C64"
    }
}

how to replace characters in hive?

select translate(description,'\\t','') from myTable;

Translates the input string by replacing the characters present in the from string with the corresponding characters in the to string. This is similar to the translate function in PostgreSQL. If any of the parameters to this UDF are NULL, the result is NULL as well. (Available as of Hive 0.10.0, for string types)

Char/varchar support added as of Hive 0.14.0

Any way (or shortcut) to auto import the classes in IntelliJ IDEA like in Eclipse?

Another option is to ask IDEA to behave like eclipse with eclipse shortcut keys. You can use all eclipse shortcuts by enabling this.

Here are the steps:

1- With IDEA open, press Control + `. Following options will be popped up.

enter image description here

2- Select Keymap. You will see another pop-up. Select Eclipse there.

enter image description here

3- Now press Ctrl + Shift + O. You are done!

How to install npm peer dependencies automatically?

Install yarn an then run

yarn global add install-peerdeps

Git Pull While Ignoring Local Changes?

git fetch --all && git reset --hard origin/master

Could not find method android() for arguments

This error appear because the compiler could not found "my-upload-key.keystore" file in your project

After you have generated the file you need to paste it into project's andorid/app folder

this worked for me!

Convert java.util.Date to String

public static void main(String[] args) 
{
    Date d = new Date();
    SimpleDateFormat form = new SimpleDateFormat("dd-mm-yyyy hh:mm:ss");
    System.out.println(form.format(d));
    String str = form.format(d); // or if you want to save it in String str
    System.out.println(str); // and print after that
}

Joining Spark dataframes on the key

From https://spark.apache.org/docs/1.5.1/api/java/org/apache/spark/sql/DataFrame.html, use join:

Inner equi-join with another DataFrame using the given column.

PersonDf.join(ProfileDf,$"personId")

OR

PersonDf.join(ProfileDf,PersonDf("personId") === ProfileDf("personId"))

Update:

You can also save the DFs as temp table using df.registerTempTable("tableName") and you can write sql queries using sqlContext.

Add content to a new open window

Here is what you can try

  • Write a function say init() inside mypage.html that do the html thing ( append or what ever)
  • instead of OpenWindow.document.write(output); call OpenWindow.init() when the dom is ready

So the parent window will have

    OpenWindow.onload = function(){
       OpenWindow.init('test');
    }

and in the child

    function init(txt){
        $('#test').text(txt);
    }

What is a web service endpoint?

A endpoint is a URL for web service.And Endpoints also is a distributed API.

The Simple Object Access Protocol (SOAP) endpoint is a URL. It identifies the location on the built-in HTTP service where the web services listener listens for incoming requests.

Reference: https://www.ibm.com/support/knowledgecenter/SSSHYH_7.1.0.4/com.ibm.netcoolimpact.doc/dsa/imdsa_web_netcool_impact_soap_endpoint_c.html

Does MS SQL Server's "between" include the range boundaries?

The BETWEEN operator is inclusive.

From Books Online:

BETWEEN returns TRUE if the value of test_expression is greater than or equal to the value of begin_expression and less than or equal to the value of end_expression.

DateTime Caveat

NB: With DateTimes you have to be careful; if only a date is given the value is taken as of midnight on that day; to avoid missing times within your end date, or repeating the capture of the following day's data at midnight in multiple ranges, your end date should be 3 milliseconds before midnight on of day following your to date. 3 milliseconds because any less than this and the value will be rounded up to midnight the next day.

e.g. to get all values within June 2016 you'd need to run:

where myDateTime between '20160601' and DATEADD(millisecond, -3, '20160701')

i.e.

where myDateTime between '20160601 00:00:00.000' and '20160630 23:59:59.997'

datetime2 and datetimeoffset

Subtracting 3 ms from a date will leave you vulnerable to missing rows from the 3 ms window. The correct solution is also the simplest one:

where myDateTime >= '20160601' AND myDateTime < '20160701'

"NoClassDefFoundError: Could not initialize class" error

I recently ran into this error on Windows 10. It turned out that windows was looking for .dll files necessary for my project and couldn't find them because it looks for them in the system path, PATH, rather than the CLASSPATH or -Djava.library.path

How to test an Oracle Stored Procedure with RefCursor return type?

Something like

create or replace procedure my_proc( p_rc OUT SYS_REFCURSOR )
as
begin
  open p_rc
   for select 1 col1
         from dual;
end;
/

variable rc refcursor;
exec my_proc( :rc );
print rc;

will work in SQL*Plus or SQL Developer. I don't have any experience with Embarcardero Rapid XE2 so I have no idea whether it supports SQL*Plus commands like this.

Difference between `Optional.orElse()` and `Optional.orElseGet()`

First of all check the declaration of both the methods.

1) OrElse: Execute logic and pass result as argument.

public T orElse(T other) {    
 return value != null ? value : other;
}

2) OrElseGet: Execute logic if value inside the optional is null

public T orElseGet(Supplier<? extends T> other) {
  return value != null ? value : other.get(); 
}

Some explanation on above declaration: The argument of “Optional.orElse” always gets executed irrespective of the value of the object in optional (null, empty or with value). Always consider the above-mentioned point in mind while using “Optional.orElse”, otherwise use of “Optional.orElse” can be very risky in the following situation.

Risk-1) Logging Issue: If content inside orElse contains any log statement: In this case, you will end up logging it every time.

Optional.of(getModel())
   .map(x -> {
      //some logic
   })
  .orElse(getDefaultAndLogError());

getDefaultAndLogError() {
  log.error("No Data found, Returning default");
  return defaultValue;
}

Risk-2) Performance Issue: If content inside orElse is time-intensive: Time intensive content can be any i/o operations DB call, API call, file reading. If we put such content in orElse(), the system will end up executing a code of no use.

Optional.of(getModel())
   .map(x -> //some logic)
   .orElse(getDefaultFromDb());

getDefaultFromDb() {
   return dataBaseServe.getDefaultValue(); //api call, db call.
}

Risk-3) Illegal State or Bug Issue: If content inside orElse is mutating some object state: We might be using the same object at another place let say inside Optional.map function and it can put us in a critical bug.

List<Model> list = new ArrayList<>();
Optional.of(getModel())
  .map(x -> {
  })
  .orElse(get(list));

get(List < String > list) {
   log.error("No Data found, Returning default");
   list.add(defaultValue);
   return defaultValue;
}

Then, When can we go with orElse()? Prefer using orElse when the default value is some constant object, enum. In all above cases we can go with Optional.orElseGet() (which only executes when Optional contains non empty value)instead of Optional.orElse(). Why?? In orElse, we pass default result value, but in orElseGet we pass Supplier and method of Supplier only executes if the value in Optional is null.

Key takeaways from this:

  1. Do not use “Optional.orElse” if it contains any log statement.
  2. Do not use “Optional.orElse” if it contains time-intensive logic.
  3. Do not use “Optional.orElse” if it is mutating some object state.
  4. Use “Optional.orElse” if we have to return a constant, enum.
  5. Prefer “Optional.orElseGet” in the situations mentioned in 1,2 and 3rd points.

I have explained this in point-2 (“Optional.map/Optional.orElse” != “if/else”) my medium blog. Use Java8 as a programmer not as a coder

How to forward declare a template class in namespace std?

I solved that problem.

I was implementing an OSI Layer (slider window, Level 2) for a network simulation in C++ (Eclipse Juno). I had frames (template <class T>) and its states (state pattern, forward declaration).

The solution is as follows:

In the *.cpp file, you must include the Header file that you forward, i.e.

ifndef STATE_H_
#define STATE_H_
#include <stdlib.h>
#include "Frame.h"

template <class T>
class LinkFrame;

using namespace std;

template <class T>
class State {

  protected:
    LinkFrame<int> *myFrame;

}

Its cpp:

#include "State.h"
#include "Frame.h"
#include  "LinkFrame.h"

template <class T>
bool State<T>::replace(Frame<T> *f){

And... another class.

Simplest way to restart service on a remote computer

This is what I do when I have restart a service remotely with different account

Open a CMD with different login

runas /noprofile /user:DOMAIN\USERNAME cmd

Use SC to stop and start

sc \\SERVERNAME query Tomcat8
sc \\SERVERNAME stop Tomcat8
sc \\SERVERNAME start Tomcat8

Execute php file from another php

This came across while working on a project on linux platform.

exec('wget http://<url to the php script>)

This runs as if you run the script from browser.

Hope this helps!!

PHP shorthand for isset()?

PHP 7.4+; with the null coalescing assignment operator

$var ??= '';

PHP 7.0+; with the null coalescing operator

$var = $var ?? '';

PHP 5.3+; with the ternary operator shorthand

isset($var) ?: $var = '';

Or for all/older versions with isset:

$var = isset($var) ? $var : '';

or

!isset($var) && $var = '';

How to make my layout able to scroll down?

Yes, it is very Simple. Just Put your Code Inside this:

<androidx.core.widget.NestedScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" 
    android:layout_height="match_parent">

//YOUR CODE

</androidx.core.widget.NestedScrollView>

How can I call PHP functions by JavaScript?

Void Function

<?php
function printMessage() {
    echo "Hello World!";
}
?>

<script>
    document.write("<?php printMessage() ?>");
</script>

Value Returning Function

<?php
function getMessage() {
    return "Hello World!";
}
?>

<script>
    var text = "<?php echo getMessage() ?>";
</script>

PHP mySQL - Insert new record into table with auto-increment on primary key

$query = "INSERT INTO myTable VALUES (NULL,'Fname', 'Lname', 'Website')";

Just leaving the value of the AI primary key NULL will assign an auto incremented value.

How do I redirect output to a variable in shell?

Create a function calling it as the command you want to invoke. In this case, I need to use the ruok command.

Then, call the function and assign its result into a variable. In this case, I am assigning the result to the variable health.

function ruok {
  echo ruok | nc *ip* 2181
}

health=echo ruok *ip*

get launchable activity name of package from adb

#!/bin/bash
#file getActivity.sh
package_name=$1
#launch app by package name
adb shell monkey -p ${package_name} -c android.intent.category.LAUNCHER 1;
sleep 1;
#get Activity name
adb shell logcat -d | grep 'START u0' | tail -n 1 | sed 's/.*cmp=\(.*\)} .*/\1/g'

sample:

getActivity.sh com.tencent.mm
com.tencent.mm/.ui.LauncherUI

What is "runtime"?

I found that the following folder structure makes a very insightful context for understanding what runtime is:

Runtimes of Mozilla XulRunner

You can see that there is the 'source', there is the 'SDK' or 'Software Development Kit' and then there is the Runtime, eg. the stuff that gets run - at runtime. It's contents are like:

runtimes' folder contents

The win32 zip contains .exe -s and .dll -s.

So eg. the C runtime would be the files like this -- C runtime libraries, .so-s or .dll -s -- you run at runtime, made special by their (or their contents' or purposes') inclusion in the definition of the C language (on 'paper'), then implemented by your C implementation of choice. And then you get the runtime of that implementation, to use it and to build upon it.

That is, with a little polarisation, the runnable files that the users of your new C-based program will need. As a developer of a C-based program, so do you, but you need the C compiler and the C library headers, too; the users don't need those.

Assigning out/ref parameters in Moq

Moq version 4.8 (or later) has much improved support for by-ref parameters:

public interface IGobbler
{
    bool Gobble(ref int amount);
}

delegate void GobbleCallback(ref int amount);     // needed for Callback
delegate bool GobbleReturns(ref int amount);      // needed for Returns

var mock = new Mock<IGobbler>();
mock.Setup(m => m.Gobble(ref It.Ref<int>.IsAny))  // match any value passed by-ref
    .Callback(new GobbleCallback((ref int amount) =>
     {
         if (amount > 0)
         {
             Console.WriteLine("Gobbling...");
             amount -= 1;
         }
     }))
    .Returns(new GobbleReturns((ref int amount) => amount > 0));

int a = 5;
bool gobbleSomeMore = true;
while (gobbleSomeMore)
{
    gobbleSomeMore = mock.Object.Gobble(ref a);
}

The same pattern works for out parameters.

It.Ref<T>.IsAny also works for C# 7 in parameters (since they are also by-ref).

How to add fonts to create-react-app based projects?

There are two options:

Using Imports

This is the suggested option. It ensures your fonts go through the build pipeline, get hashes during compilation so that browser caching works correctly, and that you get compilation errors if the files are missing.

As described in “Adding Images, Fonts, and Files”, you need to have a CSS file imported from JS. For example, by default src/index.js imports src/index.css:

import './index.css';

A CSS file like this goes through the build pipeline, and can reference fonts and images. For example, if you put a font in src/fonts/MyFont.woff, your index.css might include this:

@font-face {
  font-family: 'MyFont';
  src: local('MyFont'), url(./fonts/MyFont.woff) format('woff');
}

Notice how we’re using a relative path starting with ./. This is a special notation that helps the build pipeline (powered by Webpack) discover this file.

Normally this should be enough.

Using public Folder

If for some reason you prefer not to use the build pipeline, and instead do it the “classic way”, you can use the public folder and put your fonts there.

The downside of this approach is that the files don’t get hashes when you compile for production so you’ll have to update their names every time you change them, or browsers will cache the old versions.

If you want to do it this way, put the fonts somewhere into the public folder, for example, into public/fonts/MyFont.woff. If you follow this approach, you should put CSS files into public folder as well and not import them from JS because mixing these approaches is going to be very confusing. So, if you still want to do it, you’d have a file like public/index.css. You would have to manually add <link> to this stylesheet from public/index.html:

<link rel="stylesheet" href="%PUBLIC_URL%/index.css">

And inside of it, you would use the regular CSS notation:

@font-face {
  font-family: 'MyFont';
  src: local('MyFont'), url(fonts/MyFont.woff) format('woff');
}

Notice how I’m using fonts/MyFont.woff as the path. This is because index.css is in the public folder so it will be served from the public path (usually it’s the server root, but if you deploy to GitHub Pages and set your homepage field to http://myuser.github.io/myproject, it will be served from /myproject). However fonts are also in the public folder, so they will be served from fonts relatively (either http://mywebsite.com/fonts or http://myuser.github.io/myproject/fonts). Therefore we use the relative path.

Note that since we’re avoiding the build pipeline in this example, it doesn’t verify that the file actually exists. This is why I don’t recommend this approach. Another problem is that our index.css file doesn’t get minified and doesn’t get a hash. So it’s going to be slower for the end users, and you risk the browsers caching old versions of the file.

 Which Way to Use?

Go with the first method (“Using Imports”). I only described the second one since that’s what you attempted to do (judging by your comment), but it has many problems and should only be the last resort when you’re working around some issue.

Convert the first element of an array to a string in PHP

Use the inbuilt function in PHP, implode(array, separator):

<?php
    $ar = array("parth","raja","nikhar");
    echo implode($ar,"/");
?>

Result: parth/raja/nikhar

Gradle to execute Java class (without modifying build.gradle)

Expanding on First Zero's answer, I'm guess you want something where you can also run gradle build without errors.

Both gradle build and gradle -PmainClass=foo runApp work with this:

task runApp(type:JavaExec) {
    classpath = sourceSets.main.runtimeClasspath

    main = project.hasProperty("mainClass") ? project.getProperty("mainClass") : "package.MyDefaultMain"
}

where you set your default main class.

Indirectly referenced from required .class file

This issue happen because of few jars are getting references from other jar and reference jar is missing .

Example : Spring framework

Description Resource    Path    Location    Type
The project was not built since its build path is incomplete. Cannot find the class file for org.springframework.beans.factory.annotation.Autowire. Fix the build path then try building this project   SpringBatch     Unknown Java Problem

In this case "org.springframework.beans.factory.annotation.Autowire" is missing.

Spring-bean.jar is missing

Once you add dependency in your class path issue will resolve.

Android Get Current timestamp?

The solution is :

Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();

Setting the value of checkbox to true or false with jQuery

UPDATED: Using prop instead of attr

 <input type="checkbox" name="vehicle" id="vehicleChkBox" value="FALSE"/>

 $('#vehicleChkBox').change(function(){
     cb = $(this);
     cb.val(cb.prop('checked'));
 });

OUT OF DATE:

Here is the jsfiddle

<input type="checkbox" name="vehicle" id="vehicleChkBox" value="FALSE" />

$('#vehicleChkBox').change(function(){
     if($(this).attr('checked')){
          $(this).val('TRUE');
     }else{
          $(this).val('FALSE');
     }
});

Get dates from a week number in T-SQL

DECLARE @dayval int,
 @monthval int,
 @yearval int

SET @dayval = 1
SET @monthval = 1
SET @yearval = 2011


DECLARE @dtDateSerial datetime

        SET @dtDateSerial = DATEADD(day, @dayval-1,
                                DATEADD(month, @monthval-1,
                                    DATEADD(year, @yearval-1900, 0)
                                )
                            )

DECLARE @weekno int
SET @weekno = 53


DECLARE @weekstart datetime
SET @weekstart = dateadd(day, 7 * (@weekno -1) - datepart (dw, @dtDateSerial), @dtDateSerial)

DECLARE @weekend datetime
SET @weekend = dateadd(day, 6, @weekstart)

SELECT @weekstart, @weekend

How to disable scrolling in UITableView table when the content fits on the screen

The default height is 44.0f for a tableview cell I believe. You must be having your datasource in hand in a Array? Then just check if [array count]*44.0f goes beyond the frame bounds and if so set tableview.scrollEnabled = NO, else set it to YES. Do it where you figure the datasource out for that particular tableview.

How to get history on react-router v4?

In the specific case of react-router, using context is a valid case scenario, e.g.

class MyComponent extends React.Component {
  props: PropsType;

  static contextTypes = {
    router: PropTypes.object
  };

  render () {
    this.context.router;
  }
}

You can access an instance of the history via the router context, e.g. this.context.router.history.

Merging multiple PDFs using iTextSharp in c#.net

Using iTextSharp.dll

protected void Page_Load(object sender, EventArgs e)
{
    String[] files = @"C:\ENROLLDOCS\A1.pdf,C:\ENROLLDOCS\A2.pdf".Split(',');
    MergeFiles(@"C:\ENROLLDOCS\New1.pdf", files);
}
public void MergeFiles(string destinationFile, string[] sourceFiles)
{
    if (System.IO.File.Exists(destinationFile))
        System.IO.File.Delete(destinationFile);

    string[] sSrcFile;
    sSrcFile = new string[2];

    string[] arr = new string[2];
    for (int i = 0; i <= sourceFiles.Length - 1; i++)
    {
        if (sourceFiles[i] != null)
        {
            if (sourceFiles[i].Trim() != "")
                arr[i] = sourceFiles[i].ToString();
        }
    }

    if (arr != null)
    {
        sSrcFile = new string[2];

        for (int ic = 0; ic <= arr.Length - 1; ic++)
        {
            sSrcFile[ic] = arr[ic].ToString();
        }
    }
    try
    {
        int f = 0;

        PdfReader reader = new PdfReader(sSrcFile[f]);
        int n = reader.NumberOfPages;
        Response.Write("There are " + n + " pages in the original file.");
        Document document = new Document(PageSize.A4);

        PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));

        document.Open();
        PdfContentByte cb = writer.DirectContent;
        PdfImportedPage page;

        int rotation;
        while (f < sSrcFile.Length)
        {
            int i = 0;
            while (i < n)
            {
                i++;

                document.SetPageSize(PageSize.A4);
                document.NewPage();
                page = writer.GetImportedPage(reader, i);

                rotation = reader.GetPageRotation(i);
                if (rotation == 90 || rotation == 270)
                {
                    cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                }
                else
                {
                    cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                }
                Response.Write("\n Processed page " + i);
            }

            f++;
            if (f < sSrcFile.Length)
            {
                reader = new PdfReader(sSrcFile[f]);
                n = reader.NumberOfPages;
                Response.Write("There are " + n + " pages in the original file.");
            }
        }
        Response.Write("Success");
        document.Close();
    }
    catch (Exception e)
    {
        Response.Write(e.Message);
    }


}

Gridview with two columns and auto resized images

Here's a relatively easy method to do this. Throw a GridView into your layout, setting the stretch mode to stretch the column widths, set the spacing to 0 (or whatever you want), and set the number of columns to 2:

res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <GridView
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:verticalSpacing="0dp"
        android:horizontalSpacing="0dp"
        android:stretchMode="columnWidth"
        android:numColumns="2"/>

</FrameLayout>

Make a custom ImageView that maintains its aspect ratio:

src/com/example/graphicstest/SquareImageView.java

public class SquareImageView extends ImageView {
    public SquareImageView(Context context) {
        super(context);
    }

    public SquareImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
    }
}

Make a layout for a grid item using this SquareImageView and set the scaleType to centerCrop:

res/layout/grid_item.xml

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="match_parent"
             android:layout_height="match_parent">

    <com.example.graphicstest.SquareImageView
        android:id="@+id/picture"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"/>

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="15dp"
        android:paddingBottom="15dp"
        android:layout_gravity="bottom"
        android:textColor="@android:color/white"
        android:background="#55000000"/>

</FrameLayout>

Now make some sort of adapter for your GridView:

src/com/example/graphicstest/MyAdapter.java

private final class MyAdapter extends BaseAdapter {
    private final List<Item> mItems = new ArrayList<Item>();
    private final LayoutInflater mInflater;

    public MyAdapter(Context context) {
        mInflater = LayoutInflater.from(context);

        mItems.add(new Item("Red",       R.drawable.red));
        mItems.add(new Item("Magenta",   R.drawable.magenta));
        mItems.add(new Item("Dark Gray", R.drawable.dark_gray));
        mItems.add(new Item("Gray",      R.drawable.gray));
        mItems.add(new Item("Green",     R.drawable.green));
        mItems.add(new Item("Cyan",      R.drawable.cyan));
    }

    @Override
    public int getCount() {
        return mItems.size();
    }

    @Override
    public Item getItem(int i) {
        return mItems.get(i);
    }

    @Override
    public long getItemId(int i) {
        return mItems.get(i).drawableId;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View v = view;
        ImageView picture;
        TextView name;

        if (v == null) {
            v = mInflater.inflate(R.layout.grid_item, viewGroup, false);
            v.setTag(R.id.picture, v.findViewById(R.id.picture));
            v.setTag(R.id.text, v.findViewById(R.id.text));
        }

        picture = (ImageView) v.getTag(R.id.picture);
        name = (TextView) v.getTag(R.id.text);

        Item item = getItem(i);

        picture.setImageResource(item.drawableId);
        name.setText(item.name);

        return v;
    }

    private static class Item {
        public final String name;
        public final int drawableId;

        Item(String name, int drawableId) {
            this.name = name;
            this.drawableId = drawableId;
        }
    }
}

Set that adapter to your GridView:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    GridView gridView = (GridView)findViewById(R.id.gridview);
    gridView.setAdapter(new MyAdapter(this));
}

And enjoy the results:

Example GridView

How do you specify the Java compiler version in a pom.xml file?

<plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.3</version>
            <configuration>
                <fork>true</fork>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin> 

How to fix 'Microsoft Excel cannot open or save any more documents'

After giving necessary permissions in DCOM configurations I also needed to change the identity of my application in the IIS to a custom account

Remove blank lines with grep

egrep -v "^\s\s+"

egrep already do regex, and the \s is white space.

The + duplicates current pattern.

The ^ is for the start

How to generate an openSSL key using a passphrase from the command line?

If you don't use a passphrase, then the private key is not encrypted with any symmetric cipher - it is output completely unprotected.

You can generate a keypair, supplying the password on the command-line using an invocation like (in this case, the password is foobar):

openssl genrsa -aes128 -passout pass:foobar 3072

However, note that this passphrase could be grabbed by any other process running on the machine at the time, since command-line arguments are generally visible to all processes.

A better alternative is to write the passphrase into a temporary file that is protected with file permissions, and specify that:

openssl genrsa -aes128 -passout file:passphrase.txt 3072

Or supply the passphrase on standard input:

openssl genrsa -aes128 -passout stdin 3072

You can also used a named pipe with the file: option, or a file descriptor.


To then obtain the matching public key, you need to use openssl rsa, supplying the same passphrase with the -passin parameter as was used to encrypt the private key:

openssl rsa -passin file:passphrase.txt -pubout

(This expects the encrypted private key on standard input - you can instead read it from a file using -in <file>).


Example of creating a 3072-bit private and public key pair in files, with the private key pair encrypted with password foobar:

openssl genrsa -aes128 -passout pass:foobar -out privkey.pem 3072
openssl rsa -in privkey.pem -passin pass:foobar -pubout -out privkey.pub

How do I get just the date when using MSSQL GetDate()?

SELECT CONVERT(DATETIME, CONVERT(varchar(10), GETDATE(), 101))

JavaScript: How do I print a message to the error console?

Visit https://developer.chrome.com/devtools/docs/console-api for a complete console api reference

    console.error(object[Obj,....])\

In this case, object would be your error string

Can't import Numpy in Python

To install it on Debian/Ubuntu:

sudo apt-get install python-numpy

What is the best method to merge two PHP objects?

I understand that using the generic objects [stdClass()] and casting them as arrays answers the question, but I thought the Compositor was a great answer. Yet I felt it could use some feature enhancements and might be useful for someone else.

Features:

  • Specify reference or clone
  • Specify first or last entry to take precedence
  • Multiple (more than two) object merging with syntax similarity to array_merge
  • Method linking: $obj->f1()->f2()->f3()...
  • Dynamic composites: $obj->merge(...) /* work here */ $obj->merge(...)

Code:

class Compositor {

    protected $composite = array();
    protected $use_reference;
    protected $first_precedence;

    /**
     * __construct, Constructor
     *
     * Used to set options.
     *
     * @param bool $use_reference whether to use a reference (TRUE) or to copy the object (FALSE) [default]
     * @param bool $first_precedence whether the first entry takes precedence (TRUE) or last entry takes precedence (FALSE) [default]
     */
    public function __construct($use_reference = FALSE, $first_precedence = FALSE) {
        // Use a reference
        $this->use_reference = $use_reference === TRUE ? TRUE : FALSE;
        $this->first_precedence = $first_precedence === TRUE ? TRUE : FALSE;

    }

    /**
     * Merge, used to merge multiple objects stored in an array
     *
     * This is used to *start* the merge or to merge an array of objects.
     * It is not needed to start the merge, but visually is nice.
     *
     * @param object[]|object $objects array of objects to merge or a single object
     * @return object the instance to enable linking
     */

    public function & merge() {
        $objects = func_get_args();
        // Each object
        foreach($objects as &$object) $this->with($object);
        // Garbage collection
        unset($object);

        // Return $this instance
        return $this;
    }

    /**
     * With, used to merge a singluar object
     *
     * Used to add an object to the composition
     *
     * @param object $object an object to merge
     * @return object the instance to enable linking
     */
    public function & with(&$object) {
        // An object
        if(is_object($object)) {
            // Reference
            if($this->use_reference) {
                if($this->first_precedence) array_push($this->composite, $object);
                else array_unshift($this->composite, $object);
            }
            // Clone
            else {
                if($this->first_precedence) array_push($this->composite, clone $object);
                else array_unshift($this->composite, clone $object);
            }
        }

        // Return $this instance
        return $this;
    }

    /**
     * __get, retrieves the psudo merged object
     *
     * @param string $name name of the variable in the object
     * @return mixed returns a reference to the requested variable
     *
     */
    public function & __get($name) {
        $return = NULL;
        foreach($this->composite as &$object) {
            if(isset($object->$name)) {
                $return =& $object->$name;
                break;
            }
        }
        // Garbage collection
        unset($object);

        return $return;
    }
}

Usage:

$obj = new Compositor(use_reference, first_precedence);
$obj->merge([object $object [, object $object [, object $...]]]);
$obj->with([object $object]);

Example:

$obj1 = new stdClass();
$obj1->a = 'obj1:a';
$obj1->b = 'obj1:b';
$obj1->c = 'obj1:c';

$obj2 = new stdClass();
$obj2->a = 'obj2:a';
$obj2->b = 'obj2:b';
$obj2->d = 'obj2:d';

$obj3 = new Compositor();
$obj3->merge($obj1, $obj2);
$obj1->c = '#obj1:c';
var_dump($obj3->a, $obj3->b, $obj3->c, $obj3->d);
// obj2:a, obj2:b, obj1:c, obj2:d
$obj1->c;

$obj3 = new Compositor(TRUE);
$obj3->merge($obj1)->with($obj2);
$obj1->c = '#obj1:c';
var_dump($obj3->a, $obj3->b, $obj3->c, $obj3->d);
// obj1:a, obj1:b, obj1:c, obj2:d
$obj1->c = 'obj1:c';

$obj3 = new Compositor(FALSE, TRUE);
$obj3->with($obj1)->with($obj2);
$obj1->c = '#obj1:c';
var_dump($obj3->a, $obj3->b, $obj3->c, $obj3->d);
// obj1:a, obj1:b, #obj1:c, obj2:d
$obj1->c = 'obj1:c';

Get the time difference between two datetimes

To get the difference between two-moment format dates or javascript Date format indifference of minutes the most optimum solution is

const timeDiff = moment.duration((moment(apptDetails.end_date_time).diff(moment(apptDetails.date_time)))).asMinutes()

you can change the difference format as you need by just replacing the asMinutes() function

How to use performSelector:withObject:afterDelay: with primitive types in Cocoa?

Just wrap the float, boolean, int or similar in an NSNumber.

For structs, I don't know of a handy solution, but you could make a separate ObjC class that owns such a struct.

How to ignore a particular directory or file for tslint?

Update for tslint v5.8.0

As mentioned by Saugat Acharya, you can now update tslint.json CLI Options:

{
  "extends": "tslint:latest",
  "linterOptions": {
      "exclude": [
          "bin",
          "lib/*generated.js"
      ]
  }
}

More information in this pull request.


This feature has been introduced with tslint 3.6

tslint \"src/**/*.ts\" -e \"**/__test__/**\"

You can now add --exclude (or -e) see PR here.

CLI

usage: tslint [options] file ...

Options:

-c, --config          configuration file
--force               return status code 0 even if there are lint errors
-h, --help            display detailed help
-i, --init            generate a tslint.json config file in the current working directory
-o, --out             output file
-r, --rules-dir       rules directory
-s, --formatters-dir  formatters directory
-e, --exclude         exclude globs from path expansion
-t, --format          output format (prose, json, verbose, pmd, msbuild, checkstyle)  [default: "prose"]
--test                test that tslint produces the correct output for the specified directory
-v, --version         current version

you are looking at using

-e, --exclude         exclude globs from path expansion

Check if object exists in JavaScript

If that's a global object, you can use if (!window.maybeObject)

How to check if a string is null in python

In python, bool(sequence) is False if the sequence is empty. Since strings are sequences, this will work:

cookie = ''
if cookie:
    print "Don't see this"
else:
    print "You'll see this"

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

I'm not totally satisfied with the other answers given. They've all got some kind of flaw to them.

Using keyPress with event.which is unreliable because you can't catch a backspace or a delete (as mentioned by Tarl). Using keyDown (as in Niva's and Tarl's answers) is a bit better, but the solution is flawed because it attempts to use event.keyCode with String.fromCharCode() (keyCode and charCode are not the same!).

However, what we DO have with the keydown or keyup event is the actual key that was pressed (event.key). As far as I can tell, any key with a length of 1 is a character (number or letter) regardless of which language keyboard you're using. Please correct me if that's not true!

Then there's that very long answer from asdf. That might work perfectly, but it seems like overkill.


So here's a simple solution that will catch all characters, backspace, and delete. (Note: either keyup or keydown will work here, but keypress will not)

$("input").keydown(function(event) {

    var isWordCharacter = event.key.length === 1;
    var isBackspaceOrDelete = event.keyCode === 8 || event.keyCode === 46;

    if (isWordCharacter || isBackspaceOrDelete) {
        // do something
    }
});

"query function not defined for Select2 undefined error"

This error message is too general. One of its other possible sources is that you're trying to call select2() method on already "select2ed" input.

Regular Expression to get a string between parentheses in Javascript

Ported Mr_Green's answer to a functional programming style to avoid use of temporary global variables.

var matches = string2.split('[')
  .filter(function(v){ return v.indexOf(']') > -1})
  .map( function(value) { 
    return value.split(']')[0]
  })

Convert pandas Series to DataFrame

Rather than create 2 temporary dfs you can just pass these as params within a dict using the DataFrame constructor:

pd.DataFrame({'email':sf.index, 'list':sf.values})

There are lots of ways to construct a df, see the docs

ValueError: setting an array element with a sequence

From the code you showed us, the only thing we can tell is that you are trying to create an array from a list that isn't shaped like a multi-dimensional array. For example

numpy.array([[1,2], [2, 3, 4]])

or

numpy.array([[1,2], [2, [3, 4]]])

will yield this error message, because the shape of the input list isn't a (generalised) "box" that can be turned into a multidimensional array. So probably UnFilteredDuringExSummaryOfMeansArray contains sequences of different lengths.

Edit: Another possible cause for this error message is trying to use a string as an element in an array of type float:

numpy.array([1.2, "abc"], dtype=float)

That is what you are trying according to your edit. If you really want to have a NumPy array containing both strings and floats, you could use the dtype object, which enables the array to hold arbitrary Python objects:

numpy.array([1.2, "abc"], dtype=object)

Without knowing what your code shall accomplish, I can't judge if this is what you want.

Hide strange unwanted Xcode logs

Please note that for iOS 14 Simulator, the OS_ACTIVITY_MODE=disable will not show any logs using the new Swift Logger. You will have to remove or enable it.

Reading from stdin

From the man read:

#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);

Input parameters:

  • int fd file descriptor is an integer and not a file pointer. The file descriptor for stdin is 0

  • void *buf pointer to buffer to store characters read by the read function

  • size_t count maximum number of characters to read

So you can read character by character with the following code:

char buf[1];

while(read(0, buf, sizeof(buf))>0) {
   // read() here read from stdin charachter by character
   // the buf[0] contains the character got by read()
   ....
}

How do I use WPF bindings with RelativeSource?

I created a library to simplify the binding syntax of WPF including making it easier to use RelativeSource. Here are some examples. Before:

{Binding Path=PathToProperty, RelativeSource={RelativeSource Self}}
{Binding Path=PathToProperty, RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}
{Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}}
{Binding Path=Text, ElementName=MyTextBox}

After:

{BindTo PathToProperty}
{BindTo Ancestor.typeOfAncestor.PathToProperty}
{BindTo Template.PathToProperty}
{BindTo #MyTextBox.Text}

Here is an example of how method binding is simplified. Before:

// C# code
private ICommand _saveCommand;
public ICommand SaveCommand {
 get {
  if (_saveCommand == null) {
   _saveCommand = new RelayCommand(x => this.SaveObject());
  }
  return _saveCommand;
 }
}

private void SaveObject() {
 // do something
}

// XAML
{Binding Path=SaveCommand}

After:

// C# code
private void SaveObject() {
 // do something
}

// XAML
{BindTo SaveObject()}

You can find the library here: http://www.simplygoodcode.com/2012/08/simpler-wpf-binding.html

Note in the 'BEFORE' example that I use for method binding that code was already optimized by using RelayCommand which last I checked is not a native part of WPF. Without that the 'BEFORE' example would have been even longer.

Understanding the difference between Object.create() and new SomeFunction()

Let me try to explain (more on Blog) :

  1. When you write Car constructor var Car = function(){}, this is how things are internally: A diagram of prototypal chains when creating javascript objects We have one {prototype} hidden link to Function.prototype which is not accessible and one prototype link to Car.prototype which is accessible and has an actual constructor of Car. Both Function.prototype and Car.prototype have hidden links to Object.prototype.
  2. When we want to create two equivalent objects by using the new operator and create method then we have to do it like this: Honda = new Car(); and Maruti = Object.create(Car.prototype).A diagram of prototypal chains for differing object creation methods What is happening?

    Honda = new Car(); — When you create an object like this then hidden {prototype} property is pointed to Car.prototype. So here, the {prototype} of the Honda object will always be Car.prototype — we don't have any option to change the {prototype} property of the object. What if I want to change the prototype of our newly created object?
    Maruti = Object.create(Car.prototype) — When you create an object like this you have an extra option to choose your object's {prototype} property. If you want Car.prototype as the {prototype} then pass it as a parameter in the function. If you don't want any {prototype} for your object then you can pass null like this: Maruti = Object.create(null).

Conclusion — By using the method Object.create you have the freedom to choose your object {prototype} property. In new Car();, you don't have that freedom.

Preferred way in OO JavaScript :

Suppose we have two objects a and b.

var a = new Object();
var b = new Object();

Now, suppose a has some methods which b also wants to access. For that, we require object inheritance (a should be the prototype of b only if we want access to those methods). If we check the prototypes of a and b then we will find out that they share the prototype Object.prototype.

Object.prototype.isPrototypeOf(b); //true
a.isPrototypeOf(b); //false (the problem comes into the picture here).

Problem — we want object a as the prototype of b, but here we created object b with the prototype Object.prototype. Solution — ECMAScript 5 introduced Object.create(), to achieve such inheritance easily. If we create object b like this:

var b = Object.create(a);

then,

a.isPrototypeOf(b);// true (problem solved, you included object a in the prototype chain of object b.)

So, if you are doing object oriented scripting then Object.create() is very useful for inheritance.

AWS CLI S3 A client error (403) occurred when calling the HeadObject operation: Forbidden

403 - means I know who you are but you are not authorized to do what you asking.

In my case, the problem was in a Policy - I didn't choose an object when specified the Policy in Visual Editor

enter image description here

How to use SharedPreferences in Android to store, fetch and edit values

Singleton Shared Preferences Class. it may help for others in future.

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

public class SharedPref
{
    private static SharedPreferences mSharedPref;
    public static final String NAME = "NAME";
    public static final String AGE = "AGE";
    public static final String IS_SELECT = "IS_SELECT";

    private SharedPref()
    {

    }

    public static void init(Context context)
    {
        if(mSharedPref == null)
            mSharedPref = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
    }

    public static String read(String key, String defValue) {
        return mSharedPref.getString(key, defValue);
    }

    public static void write(String key, String value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putString(key, value);
        prefsEditor.commit();
    }

    public static boolean read(String key, boolean defValue) {
        return mSharedPref.getBoolean(key, defValue);
    }

    public static void write(String key, boolean value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putBoolean(key, value);
        prefsEditor.commit();
    }

    public static Integer read(String key, int defValue) {
        return mSharedPref.getInt(key, defValue);
    }

    public static void write(String key, Integer value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putInt(key, value).commit();
    }
}

Simply call SharedPref.init() on MainActivity once

SharedPref.init(getApplicationContext());

To Write data

SharedPref.write(SharedPref.NAME, "XXXX");//save string in shared preference.
SharedPref.write(SharedPref.AGE, 25);//save int in shared preference.
SharedPref.write(SharedPref.IS_SELECT, true);//save boolean in shared preference.

To Read Data

String name = SharedPref.read(SharedPref.NAME, null);//read string in shared preference.
int age = SharedPref.read(SharedPref.AGE, 0);//read int in shared preference.
boolean isSelect = SharedPref.read(SharedPref.IS_SELECT, false);//read boolean in shared preference.

How to create JSON object using jQuery

I believe he is asking to write the new json to a directory. You will need some Javascript and PHP. So, to piggy back off the other answers:

script.js

var yourObject = {
  test:'test 1',
  testData: [ 
    {testName: 'do',testId:''}
   ],
   testRcd:'value'   
};
var myString = 'newData='+JSON.stringify(yourObject);  //converts json to string and prepends the POST variable name
$.ajax({
   type: "POST",
   url: "buildJson.php", //the name and location of your php file
   data: myString,      //add the converted json string to a document.
   success: function() {alert('sucess');} //just to make sure it got to this point.
});
return false;  //prevents the page from reloading. this helps if you want to bind this whole process to a click event.

buildJson.php

<?php
    $file = "data.json";  //name and location of json file. if the file doesn't exist, it   will be created with this name

    $fh = fopen($file, 'a');  //'a' will append the data to the end of the file. there are other arguemnts for fopen that might help you a little more. google 'fopen php'.

    $new_data = $_POST["newData"]; //put POST data from ajax request in a variable

    fwrite($fh, $new_data);  //write the data with fwrite

    fclose($fh);  //close the dile
?>

What's the difference between "Layers" and "Tiers"?

Read Scott Hanselman's post on the issue: http://www.hanselman.com/blog/AReminderOnThreeMultiTierLayerArchitectureDesignBroughtToYouByMyLateNightFrustrations.aspx

Remember though, that in "Scott World" (which is hopefully your world also :) ) a "Tier" is a unit of deployment, while a "Layer" is a logical separation of responsibility within code. You may say you have a "3-tier" system, but be running it on one laptop. You may say your have a "3-layer" system, but have only ASP.NET pages that talk to a database. There's power in precision, friends.

"No X11 DISPLAY variable" - what does it mean?

If you're on the main display, then

export DISPLAY=:0.0

or if you're using csh or tcsh

setenv DISPLAY :0.0

before running your app.

Actually, I'm surprised it isn't set automatically. Are you trying to start this application from a non-graphic terminal? If not, have you modified the default .profile, .login, .bashrc or .cshrc?

Note that setting the DISPLAY to :0.0 pre-supposes that you're sitting at the main display, as I said, or at least that the main display is logged on to your user id. If it's not logged on, or it's a different userid, this will fail.

If you're coming in from another machine, and you're at the main display of that machine and it's running X, then you can use "ssh -X hostname" to connect to that host, and ssh will forward the X display back. ssh will also make sure that the DISPLAY environment variable is set correctly (providing it isn't being messed with in the various dot files I mentioned above). In a "ssh -X" session, the DISPLAY environment variable will have a value like "localhost:11.0", which will point to the socket that ssh is tunnelling to your local box.

JPA: How to get entity based on field value other than ID?

Using CrudRepository and JPA query works for me:

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;

public interface TokenCrudRepository extends CrudRepository<Token, Integer> {

 /**
 * Finds a token by using the user as a search criteria.
 * @param user
 * @return  A token element matching with the given user.
 */
    @Query("SELECT t FROM Token t WHERE LOWER(t.user) = LOWER(:user)")
    public Token find(@Param("user") String user);

}

and you invoke the find custom method like this:

public void destroyCurrentToken(String user){
    AbstractApplicationContext context = getContext();

    repository = context.getBean(TokenCrudRepository.class);

    Token token = ((TokenCrudRepository) repository).find(user);

    int idToken = token.getId();

    repository.delete(idToken);

    context.close();
}

Why does 'git commit' not save my changes?

if you have a subfolder, which was cloned from other git-Repository, first you have to remove the $.git$ file from the child-Repository: rm -rf .git after that you can change to parent folder and use git add -A.

How to sort an ArrayList in Java

Try BeanComparator from Apache Commons.

import org.apache.commons.beanutils.BeanComparator;


BeanComparator fieldComparator = new BeanComparator("fruitName");
Collections.sort(fruits, fieldComparator);

Initialise a list to a specific length in Python

If the "default value" you want is immutable, @eduffy's suggestion, e.g. [0]*10, is good enough.

But if you want, say, a list of ten dicts, do not use [{}]*10 -- that would give you a list with the same initially-empty dict ten times, not ten distinct ones. Rather, use [{} for i in range(10)] or similar constructs, to construct ten separate dicts to make up your list.

Does Android keep the .apk files? if so where?

There is no standard location, however you can use the PackageManager to find out about packages and the ApplicationInfo class you can get from there has various information about a particular package: the path to its .apk, the path to its data directory, the path to a resource-only .apk (for forward locked apps), etc. Note that you may or may not have permission to read these directories depending on your relationship with the other app; however, all apps are able to read the resource .apk (which is also the real .apk for non-forward-locked app).

If you are just poking around in the shell, currently non-forward-locked apps are located in /data/app/.apk. The shell user can read a specific .apk, though it can't list the directory. In a future release the naming convention will be changed slightly, so don't count on it remaining the same, but if you get the path of the .apk from the package manager then you can use it in the shell.

How do I get the path of the assembly the code is in?

This is what I came up with. In between web projects, unit tests (nunit and resharper test runner); I found this worked for me.

I have been looking for code to detect what configuration the build is in, Debug/Release/CustomName. Alas, the #if DEBUG. So if someone can improve that!

Feel free to edit and improve.

Getting app folder. Useful for web roots, unittests to get the folder of test files.

public static string AppPath
{
    get
    {
        DirectoryInfo appPath = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);

        while (appPath.FullName.Contains(@"\bin\", StringComparison.CurrentCultureIgnoreCase)
                || appPath.FullName.EndsWith(@"\bin", StringComparison.CurrentCultureIgnoreCase))
        {
            appPath = appPath.Parent;
        }
        return appPath.FullName;
    }
}

Getting bin folder: Useful for executing assemblies using reflection. If files are copied there due to build properties.

public static string BinPath
{
    get
    {
        string binPath = AppDomain.CurrentDomain.BaseDirectory;

        if (!binPath.Contains(@"\bin\", StringComparison.CurrentCultureIgnoreCase)
            && !binPath.EndsWith(@"\bin", StringComparison.CurrentCultureIgnoreCase))
        {
            binPath = Path.Combine(binPath, "bin");
            //-- Please improve this if there is a better way
            //-- Also note that apps like webapps do not have a debug or release folder. So we would just return bin.
#if DEBUG
            if (Directory.Exists(Path.Combine(binPath, "Debug"))) 
                        binPath = Path.Combine(binPath, "Debug");
#else
            if (Directory.Exists(Path.Combine(binPath, "Release"))) 
                        binPath = Path.Combine(binPath, "Release");
#endif
        }
            return binPath;
    }
}

Tools to generate database tables diagram with Postgresql?

Inside Eclipse I've used the Clay plugin (ex Clay-Azurri). The free version allows to introspect ("reverse engineer") an existing DB schema (via JDBC) and make a diagram of some selected tables.

T-SQL How to select only Second row from a table?

Assuming SQL Server 2005+ an example of how to get just the second row (which I think you may be asking - and is the reason why top won't work for you?)

set statistics io on

;with cte as
(
  select *
    , ROW_NUMBER() over (order by number) as rn
  from master.dbo.spt_values
) 
select *
from cte
where rn = 2

/* Just to add in what I was running RE: Comments */
;with cte as
(
  select top 2 *
    , ROW_NUMBER() over (order by number) as rn
  from master.dbo.spt_values
) 
select *
from cte
where rn = 2

How to group by week in MySQL?

Just ad this in the select :

DATE_FORMAT($yourDate, \'%X %V\') as week

And

group_by(week);

Exact difference between CharSequence and String in java

From the Java API of CharSequence:

A CharSequence is a readable sequence of characters. This interface provides uniform, read-only access to many different kinds of character sequences.

This interface is then used by String, CharBuffer and StringBuffer to keep consistency for all method names.

Asking the user for input until they give a valid response

Yeah I'm 6 years late from the but this question deserves more up-to-date answer.

Separation of concerns

I am a big fan of Unix philosophy "Do one thing and do it well". In this type of problem, it is better practice to split the problem to

  • Ask input with get_input until the input is ok.
  • Validate in validator function. You could write different validators for different input queries.

Asking for input

It can be kept as simple as (Python 3+)

def myvalidator(value):
    try:
        value = int(value)
    except ValueError:
        return False
    return value >= 0

def get_input(prompt, validator, on_validationerror):
    while True:
        value = input(prompt)
        if validator(value):
            return value
        print(on_validationerror)

Example

In [2]: get_input('Give a positive number: ', myvalidator, 'Please, try again')
Give a positive number: foobar
Please, try again
Give a positive number: -10
Please, try again
Give a positive number: 42
Out[2]: '42'

Python 3.8+ Note

In Python 3.8+ you could use the walrus operator

def get_input(prompt, validator, on_validationerror):
    while not validator(value := input(prompt)):
        print(on_validationerror)
    return value 

Query to count the number of tables I have in MySQL

SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'dbName';

Source

This is mine:

USE databasename; 
SHOW TABLES; 
SELECT FOUND_ROWS();

Parse string to DateTime in C#

As I am explaining later, I would always favor the TryParse and TryParseExact methods. Because they are a bit bulky to use, I have written an extension method which makes parsing much easier:

var    dtStr = "2011-03-21 13:26";
DateTime? dt = dtStr.ToDate("yyyy-MM-dd HH:mm");

Or more simply, if you want to use the date patterns of your current culture implicitly, you can use it like:

 DateTime? dt = dtStr.ToDate();

In that case no specific pattern need to be specified.

Unlike Parse, ParseExact etc. it does not throw an exception, and allows you to check via

if (dt.HasValue) { // continue processing } else { // do error handling }

whether the conversion was successful (in this case dt has a value you can access via dt.Value) or not (in this case, it is null).

That even allows to use elegant shortcuts like the "Elvis"-operator ?., for example:

int? year = dtStr?.ToDate("yyyy-MM-dd HH:mm")?.Year;

Here you can also use year.HasValue to check if the conversion succeeded, and if it did not succeed then year will contain null, otherwise the year portion of the date. There is no exception thrown if the conversion failed.


Solution:  The   .ToDate()   extension method

Try it in .NetFiddle

public static class Extensions
{
    /// <summary>
    /// Extension method parsing a date string to a DateTime? <para/>
    /// </summary>
    /// <param name="dateTimeStr">The date string to parse</param>
    /// <param name="dateFmt">dateFmt is optional and allows to pass 
    /// a parsing pattern array or one or more patterns passed 
    /// as string parameters</param>
    /// <returns>Parsed DateTime or null</returns>
    public static DateTime? ToDate(this string dateTimeStr, params string[] dateFmt)
    {
      // example: var dt = "2011-03-21 13:26".ToDate(new string[]{"yyyy-MM-dd HH:mm", 
      //                                                  "M/d/yyyy h:mm:ss tt"});
      // or simpler: 
      // var dt = "2011-03-21 13:26".ToDate("yyyy-MM-dd HH:mm", "M/d/yyyy h:mm:ss tt");
      const DateTimeStyles style = DateTimeStyles.AllowWhiteSpaces;
      if (dateFmt == null)
      {
        var dateInfo = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat;
        dateFmt=dateInfo.GetAllDateTimePatterns();
      }
      var result = DateTime.TryParseExact(dateTimeStr, dateFmt, CultureInfo.InvariantCulture,
                   style, out var dt) ? dt : null as DateTime?;
      return result;
    }
}

Some information about the code

You might wonder, why I have used InvariantCulture calling TryParseExact: This is to force the function to treat format patterns always the same way (otherwise for example "." could be interpreted as decimal separator in English while it is a group separator or a date separator in German). Recall we have already queried the culture based format strings a few lines before so that is okay here.

Update: .ToDate() (without parameters) now defaults to all common date/time patterns of the thread's current culture.
Note that we need the result and dt together, because TryParseExact does not allow to use DateTime?, which we intend to return. In C# Version 7 you could simplify the ToDate function a bit as follows:

 // in C#7 only: "DateTime dt;" - no longer required, declare implicitly
 if (DateTime.TryParseExact(dateTimeStr, dateFmt,
     CultureInfo.InvariantCulture, style, out var dt)) result = dt;

or, if you like it even shorter:

 // in C#7 only: Declaration of result as a "one-liner" ;-)
 var result = DateTime.TryParseExact(dateTimeStr, dateFmt, CultureInfo.InvariantCulture,
              style, out var dt) ? dt : null as DateTime?;

in which case you don't need the two declarations DateTime? result = null; and DateTime dt; at all - you can do it in one line of code. (It would also be allowed to write out DateTime dt instead of out var dt if you prefer that).

The old style of C# would have required it the following way (I removed that from the code above):

  // DateTime? result = null;
  // DateTime dt;
  // if (DateTime.TryParseExact(dateTimeStr, dateFmt,
  //    CultureInfo.InvariantCulture, style, out dt)) result = dt;

I have simplified the code further by using the params keyword: Now you don't need the 2nd overloaded method any more.


Example of usage

var dtStr="2011-03-21 13:26";    
var dt=dtStr.ToDate("yyyy-MM-dd HH:mm");
if (dt.HasValue)
{
    Console.WriteLine("Successful!");
    // ... dt.Value now contains the converted DateTime ...
}
else
{
    Console.WriteLine("Invalid date format!");
}

As you can see, this example just queries dt.HasValue to see if the conversion was successful or not. As an extra bonus, TryParseExact allows to specify strict DateTimeStyles so you know exactly whether a proper date/time string has been passed or not.


More Examples of usage

The overloaded function allows you to pass an array of valid formats used for parsing/converting dates as shown here as well (TryParseExact directly supports this), e.g.

string[] dateFmt = {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
                     "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", 
                     "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", 
                     "M/d/yyyy h:mm", "M/d/yyyy h:mm", 
                     "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
var dtStr="5/1/2009 6:32 PM"; 
var dt=dtStr.ToDate(dateFmt);

If you have only a few template patterns, you can also write:

var dateStr = "2011-03-21 13:26";
var dt = dateStr.ToDate("yyyy-MM-dd HH:mm", "M/d/yyyy h:mm:ss tt");

Advanced examples

You can use the ?? operator to default to a fail-safe format, e.g.

var dtStr = "2017-12-30 11:37:00";
var dt = (dtStr.ToDate()) ?? dtStr.ToDate("yyyy-MM-dd HH:mm:ss");

In this case, the .ToDate() would use common local culture date formats, and if all these failed, it would try to use the ISO standard format "yyyy-MM-dd HH:mm:ss" as a fallback. This way, the extension function allows to "chain" different fallback formats easily.

You can even use the extension in LINQ, try this out (it's in the .NetFiddle above):

var strDateArray = new[] { "15-01-2019", "15.01.2021" };
var patterns=new[] { "dd-MM-yyyy", "dd.MM.yyyy" };
var dtRange = strDateArray.Select(s => s.ToDate(patterns));
dtRange.Dump(); 

which will convert the dates in the array on the fly by using the patterns and dump them to the console.


Some background about TryParseExact

Finally, Here are some comments about the background (i.e. the reason why I have written it this way):

I am preferring TryParseExact in this extension method, because you avoid exception handling - you can read in Eric Lippert's article about exceptions why you should use TryParse rather than Parse, I quote him about that topic:2)

This unfortunate design decision1) [annotation: to let the Parse method throw an exception] was so vexing that of course the frameworks team implemented TryParse shortly thereafter which does the right thing.

It does, but TryParse and TryParseExact both are still a lot less than comfortable to use: They force you to use an uninitialized variable as an out parameter which must not be nullable and while you're converting you need to evaluate the boolean return value - either you have to use an ifstatement immediately or you have to store the return value in an additional boolean variable so you're able to do the check later. And you can't just use the target variable without knowing if the conversion was successful or not.

In most cases you just want to know whether the conversion was successful or not (and of course the value if it was successful), so a nullable target variable which keeps all the information would be desirable and much more elegant - because the entire information is just stored in one place: That is consistent and easy to use, and much less error-prone.

The extension method I have written does exactly that (it also shows you what kind of code you would have to write every time if you're not going to use it).

I believe the benefit of .ToDate(strDateFormat) is that it looks simple and clean - as simple as the original DateTime.Parse was supposed to be - but with the ability to check if the conversion was successful, and without throwing exceptions.


1) What is meant here is that exception handling (i.e. a try { ... } catch(Exception ex) { ...} block) - which is necessary when you're using Parse because it will throw an exception if an invalid string is parsed - is not only unnecessary in this case but also annoying, and complicating your code. TryParse avoids all this as the code sample I've provided is showing.


2) Eric Lippert is a famous StackOverflow fellow and was working at Microsoft as principal developer on the C# compiler team for a couple of years.

Declaring variables in Excel Cells

You can name cells. This is done by clicking the Name Box (that thing next to the formula bar which says "A1" for example) and typing a name, such as, "myvar". Now you can use that name instead of the cell reference:

= myvar*25

How can I render HTML from another file in a React component?

You could do it if template is a react component.

Template.js

var React = require('react');

var Template = React.createClass({
    render: function(){
        return (<div>Mi HTML</div>);
    }
});

module.exports = Template;

MainComponent.js

var React = require('react');
var ReactDOM = require('react-dom');
var injectTapEventPlugin = require("react-tap-event-plugin");
var Template = require('./Template');

//Needed for React Developer Tools
window.React = React;

//Needed for onTouchTap
//Can go away when react 1.0 release
//Check this repo:
//https://github.com/zilverline/react-tap-event-plugin
injectTapEventPlugin();

var MainComponent = React.createClass({
    render: function() {
        return(
            <Template/>
        );
    }
});

// Render the main app react component into the app div.
// For more details see: https://facebook.github.io/react/docs/top-level-api.html#react.render
ReactDOM.render(
  <MainComponent />,
  document.getElementById('app')
 );

And if you are using Material-UI, for compatibility use Material-UI Components, no normal inputs.

What is the 'dynamic' type in C# 4.0 used for?

The best use case of 'dynamic' type variables for me was when, recently, I was writing a data access layer in ADO.NET (using SQLDataReader) and the code was invoking the already written legacy stored procedures. There are hundreds of those legacy stored procedures containing bulk of the business logic. My data access layer needed to return some sort of structured data to the business logic layer, C# based, to do some manipulations (although there are almost none). Every stored procedures returns different set of data (table columns). So instead of creating dozens of classes or structs to hold the returned data and pass it to the BLL, I wrote the below code which looks quite elegant and neat.

public static dynamic GetSomeData(ParameterDTO dto)
        {
            dynamic result = null;
            string SPName = "a_legacy_stored_procedure";
            using (SqlConnection connection = new SqlConnection(DataConnection.ConnectionString))
            {
                SqlCommand command = new SqlCommand(SPName, connection);
                command.CommandType = System.Data.CommandType.StoredProcedure;                
                command.Parameters.Add(new SqlParameter("@empid", dto.EmpID));
                command.Parameters.Add(new SqlParameter("@deptid", dto.DeptID));
                connection.Open();
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        dynamic row = new ExpandoObject();
                        row.EmpName = reader["EmpFullName"].ToString();
                        row.DeptName = reader["DeptName"].ToString();
                        row.AnotherColumn = reader["AnotherColumn"].ToString();                        
                        result = row;
                    }
                }
            }
            return result;
        }

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

As per the docs:

You can set annotation processor argument (room.schemaLocation) to tell Room to export the schema into a folder. Even though it is not mandatory, it is a good practice to have version history in your codebase and you should commit that file into your version control system (but don't ship it with your app!).

So if you don't need to check the schema and you want to get rid of the warning, just add exportSchema = false to your RoomDatabase, as follows.

@Database(entities = { YourEntity.class }, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
   //...
}

If you follow @mikejonesguy answer below, you will follow the good practice mentioned in the docs :). Basically you will get a .json file in your ../app/schemas/ folder. And it looks something like this:

{
  "formatVersion": 1,
  "database": {
    "version": 1,
    "identityHash": "53db508c5248423325bd5393a1c88c03",
    "entities": [
      {
        "tableName": "sms_table",
        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `message` TEXT, `date` INTEGER, `client_id` INTEGER)",
        "fields": [
          {
            "fieldPath": "id",
            "columnName": "id",
            "affinity": "INTEGER"
          },
          {
            "fieldPath": "message",
            "columnName": "message",
            "affinity": "TEXT"
          },
          {
            "fieldPath": "date",
            "columnName": "date",
            "affinity": "INTEGER"
          },
          {
            "fieldPath": "clientId",
            "columnName": "client_id",
            "affinity": "INTEGER"
          }
        ],
        "primaryKey": {
          "columnNames": [
            "id"
          ],
          "autoGenerate": true
        },
        "indices": [],
        "foreignKeys": []
      }
    ],
    "setupQueries": [
      "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
      "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"53db508c5248423325bd5393a1c88c03\")"
    ]
  }
}

If my understanding is correct, you will get such a file with every database version update, so that you can easily follow the history of your db.

Clear the cache in JavaScript

I found a solution to this problem recently. In my case, I was trying to update an html element using javascript; I had been using XHR to update text based on data retrieved from a GET request. Although the XHR request happened frequently, the cached HTML data remained frustratingly the same.

Recently, I discovered a cache busting method in the fetch api. The fetch api replaces XHR, and it is super simple to use. Here's an example:

        async function updateHTMLElement(t) {
            let res = await fetch(url, {cache: "no-store"});
            if(res.ok){
                let myTxt = await res.text();
                document.getElementById('myElement').innerHTML = myTxt;
            }
        }

Notice that {cache: "no-store"} argument? This causes the browser to bust the cache for that element, so that new data gets loaded properly. My goodness, this was a godsend for me. I hope this is helpful for you, too.

Tangentially, to bust the cache for an image that gets updated on the server side, but keeps the same src attribute, the simplest and oldest method is to simply use Date.now(), and append that number as a url variable to the src attribute for that image. This works reliably for images, but not for HTML elements. But between these two techniques, you can update any info you need to now :-)

com.microsoft.sqlserver.jdbc.SQLServerDriver not found error

For me it worked after manually copying the sqljdbc4-2.jar into WEB-INF/lib folder. So please have a try on this too.

JQuery Number Formatting

http://jquerypriceformat.com/#examples

https://github.com/flaviosilveira/Jquery-Price-Format

html input runing for live chance.

<input type="text" name="v7"  class="priceformat"/>
<input type="text" name="v8"  class="priceformat"/>


$('.priceformat').each(function( index ) {
    $(this).priceFormat({ prefix: '',  thousandsSeparator: '' });
});

//5000.00

//5.000,00

//5,000.00

How can I make a list of installed packages in a certain virtualenv?

list out the installed packages in the virtualenv

step 1:

workon envname

step 2:

pip freeze

it will display the all installed packages and installed packages and versions

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

There are subtle and not-so-subtle differences between generic and non-generic collections. They merely use different underlying data structures. For example, Hashtable guarantees one-writer-many-readers without sync. Dictionary does not.

How do I get the current time only in JavaScript

var d = new Date("2011-04-20T09:30:51.01");
d.getHours(); // => 9
d.getMinutes(); // =>  30
d.getSeconds(); // => 51

or

var d = new Date(); // for now
d.getHours(); // => 9
d.getMinutes(); // =>  30
d.getSeconds(); // => 51

Execution sequence of Group By, Having and Where clause in SQL Server?

SELECT
FROM
JOINs
WHERE
GROUP By
HAVING
ORDER BY

How do I navigate to another page when PHP script is done?

if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}

Fix Access denied for user 'root'@'localhost' for phpMyAdmin

What worked for me:

Go to config.inc.php.

Change

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

to

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

Change

$cfg['Servers'][$i]['password'] = '';

to

$cfg['Servers'][$i]['password'] = ' ';

Change

$cfg['Servers'][$i]['auth_type'] = 'config';

to

$cfg['Servers'][$i]['auth_type'] = 'http';

Reload the page http://localhost/phpmyadmin

Type : root
pass : (empty)

Now you have access to it. :)

UPDATE multiple tables in MySQL using LEFT JOIN

                DECLARE @cols VARCHAR(max),@colsUpd VARCHAR(max), @query VARCHAR(max),@queryUpd VARCHAR(max), @subQuery VARCHAR(max)
DECLARE @TableNameTest NVARCHAR(150)
SET @TableNameTest = @TableName+ '_Staging';
SELECT  @colsUpd = STUF  ((SELECT DISTINCT '], T1.[' + name,']=T2.['+name+'' FROM sys.columns
                 WHERE object_id = (
                                    SELECT top 1 object_id 
                                      FROM sys.objects
                                     WHERE name = ''+@TableNameTest+''
                                    )
                and name not in ('Action','Record_ID')
                FOR XML PATH('')
            ), 1, 2, ''
        ) + ']'


  Select @queryUpd ='Update T1
SET '+@colsUpd+'
FROM '+@TableName+' T1
INNER JOIN '+@TableNameTest+' T2
ON T1.Record_ID = T2.Record_Id
WHERE T2.[Action] = ''Modify'''
EXEC (@queryUpd)

Base64 encoding and decoding in client-side Javascript

I'd rather use the bas64 encode/decode methods from CryptoJS, the most popular library for standard and secure cryptographic algorithms implemented in JavaScript using best practices and patterns.

How can one create an overlay in css?

If you don't mind messing with z-index, but you want to avoid adding extra div for overlay, you can use the following approach

/* make sure ::before is positioned relative to .foo */
.foo { position: relative; }

/* overlay */
.foo::before {
    content: '';
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    z-index: 0;
}
/* make sure all elements inside .foo placed above overlay element */
.foo > * { z-index: 1; }

How can I fetch all items from a DynamoDB table without specifying the primary key?

I fetch all items from dynamodb with the following query. It works fine. i create these function generic in zend framework and access these functions over the project.

        public function getQuerydata($tablename, $filterKey, $filterValue){
            return $this->getQuerydataWithOp($tablename, $filterKey, $filterValue, 'EQ');
        }

        public function getQuerydataWithOp($tablename, $filterKey, $filterValue, $compOperator){
        $result = $this->getClientdb()->query(array(
                'TableName'     => $tablename,
                'IndexName'     => $filterKey,
                'Select'        => 'ALL_ATTRIBUTES',
                'KeyConditions' => array(
                    $filterKey => array(
                        'AttributeValueList' => array(
                            array('S' => $filterValue)
                        ),
                'ComparisonOperator' => $compOperator
            )
            )
        ));
            return $result['Items'];
        }

       //Below i Access these functions and get data.
       $accountsimg = $this->getQuerydataWithPrimary('accounts', 'accountID',$msgdata[0]['accountID']['S']);

AES Encryption for an NSString on the iPhone

@owlstead, regarding your request for "a cryptographically secure variant of one of the given answers," please see RNCryptor. It was designed to do exactly what you're requesting (and was built in response to the problems with the code listed here).

RNCryptor uses PBKDF2 with salt, provides a random IV, and attaches HMAC (also generated from PBKDF2 with its own salt. It support synchronous and asynchronous operation.

Programmatically go back to the previous fragment in the backstack

16 July 2020 - Kotlin Answer

  1. First, call Fragment Manager.
  2. After, to use onBackPressed() method.

Coding in Android Studio 4.0 with Kotlin:

fragmentManager?.popBackStack()

Happy coding!

@canerkaseler

How do you check "if not null" with Eloquent?

I see this question is a bit old but I ran across it looking for an answer. Although I did not have success with the answers here I think this might be because I'm on PHP 7.2 and Laravel 5.7. or possible because I was just playing around with some data on the CLI using Laravel Tinker.

I have some things I tried that worked for me and others that did not that I hope will help others out.


I did not have success running:

    MyModel::whereNotNull('deleted_by')->get()->all();             // []
    MyModel::where('deleted_by', '<>', null)->get()->all();        // []
    MyModel::where('deleted_by', '!=', null)->get()->all();        // []
    MyModel::where('deleted_by', '<>', '', 'and')->get()->all();   // []
    MyModel::where('deleted_by', '<>', null, 'and')->get()->all(); // []
    MyModel::where('deleted_by', 'IS NOT', null)->get()->all();    // []

All of the above returned an empty array for me


I did however have success running:

    DB::table('my_models')->whereNotNull('deleted_by')->get()->all(); // [ ... ]

This returned all the results in an array as I expected. Note: you can drop the all() and get back a Illuminate\Database\Eloquent\Collection instead of an array if you prefer.

How to check if a text field is empty or not in swift

Swift 4.2

You can use a general function for your every textField just add the following function in your base controller

// White space validation.
func checkTextFieldIsNotEmpty(text:String) -> Bool
{
    if (text.trimmingCharacters(in: .whitespaces).isEmpty)
    {
        return false

    }else{
        return true
    }
}

What is causing ImportError: No module named pkg_resources after upgrade of Python on os X?

Try this only if you are ok with uninstalling python.

I uninstalled python using

brew uninstall python

then later installed using

brew install python

then it worked!

socket.shutdown vs socket.close

Here's one explanation:

Once a socket is no longer required, the calling program can discard the socket by applying a close subroutine to the socket descriptor. If a reliable delivery socket has data associated with it when a close takes place, the system continues to attempt data transfer. However, if the data is still undelivered, the system discards the data. Should the application program have no use for any pending data, it can use the shutdown subroutine on the socket prior to closing it.

Check if application is installed - Android

Those who are looking for Kotlin solution can use this method,

Here I have shared full code, and also handled enabled status. Check If Application is Installed in Android Kotlin

fun isAppInstalled(packageName: String, context: Context): Boolean {
        return try {
            val packageManager = context.packageManager
            packageManager.getPackageInfo(packageName, 0)
            true
        } catch (e: PackageManager.NameNotFoundException) {
            false
        }
    }

Set default heap size in Windows

Setup JAVA_OPTS as a system variable with the following content:

JAVA_OPTS="-Xms256m -Xmx512m"

After that in a command prompt run the following commands:

SET JAVA_OPTS="-Xms256m -Xmx512m"

This can be explained as follows:

  • allocate at minimum 256MBs of heap
  • allocate at maximum 512MBs of heap

These values should be changed according to application requirements.

EDIT:

You can also try adding it through the Environment Properties menu which can be found at:

  1. From the Desktop, right-click My Computer and click Properties.
  2. Click Advanced System Settings link in the left column.
  3. In the System Properties window click the Environment Variables button.
  4. Click New to add a new variable name and value.
  5. For variable name enter JAVA_OPTS for variable value enter -Xms256m -Xmx512m
  6. Click ok and close the System Properties Tab.
  7. Restart any java applications.

EDIT 2:

JAVA_OPTS is a system variable that stores various settings/configurations for your local Java Virtual Machine. By having JAVA_OPTS set as a system variable all applications running on top of the JVM will take their settings from this parameter.

To setup a system variable you have to complete the steps listed above from 1 to 4.

What does "collect2: error: ld returned 1 exit status" mean?

The ld returned 1 exit status error is the consequence of previous errors. In your example there is an earlier error - undefined reference to 'clrscr' - and this is the real one. The exit status error just signals that the linking step in the build process encountered some errors. Normally exit status 0 means success, and exit status > 0 means errors.

When you build your program, multiple tools may be run as separate steps to create the final executable. In your case one of those tools is ld, which first reports the error it found (clrscr reference missing), and then it returns the exit status. Since the exit status is > 0, it means an error and is reported.

In many cases tools return as the exit status the number of errors they encountered. So if ld tool finds two errors, its exit status would be 2.

How to do a scatter plot with empty circles in Python?

Would these work?

plt.scatter(np.random.randn(100), np.random.randn(100), facecolors='none')

example image

or using plot()

plt.plot(np.random.randn(100), np.random.randn(100), 'o', mfc='none')

example image

How to check permissions of a specific directory?

$ ls -ld directory

ls is the list command.

- indicates the beginning of the command options.

l asks for a long list which includes the permissions.

d indicates that the list should concern the named directory itself; not its contents. If no directory name is given, the list output will pertain to the current directory.

What is the maximum length of a String in PHP?

To properly answer this qustion you need to consider PHP internals or the target that PHP is built for.

To answer this from a typical Linux perspective on x86...

Sizes of types in C: https://usrmisc.wordpress.com/2012/12/27/integer-sizes-in-c-on-32-bit-and-64-bit-linux/

Types used in PHP for variables: http://php.net/manual/en/internals2.variables.intro.php

Strings are always 2GB as the length is always 32bits and a bit is wasted because it uses int rather than uint. int is impractical for lengths over 2GB as it requires a cast to avoid breaking arithmetic or "than" comparisons. The extra bit is likely being used for overflow checks.

Strangely, hash keys might internally support 4GB as uint is used although I have never put this to the test. PHP hash keys have a +1 to the length for a trailing null byte which to my knowledge gets ignored so it may need to be unsigned for that edge case rather than to allow longer keys.

A 32bit system may impose more external limits.

How to populate/instantiate a C# array with a single value?

If you can invert your logic you can use the Array.Clear() method to set the boolean array to false.

        int upperLimit = 21;
        double optimizeMe = Math.Sqrt(upperLimit);

        bool[] seiveContainer = new bool[upperLimit];
        Array.Clear(seiveContainer, 0, upperLimit);

Play audio file from the assets directory

this works for me:

public static class eSound_Def
{
  private static Android.Media.MediaPlayer mpBeep;

  public static void InitSounds( Android.Content.Res.AssetManager Assets )
  {
    mpBeep = new Android.Media.MediaPlayer();

    InitSound_Beep( Assets );
  }

  private static void InitSound_Beep( Android.Content.Res.AssetManager Assets )
  {
    Android.Content.Res.AssetFileDescriptor AFD;

    AFD = Assets.OpenFd( "Sounds/beep-06.mp3" );
    mpBeep.SetDataSource( AFD.FileDescriptor, AFD.StartOffset, AFD.Length );
    AFD.Close();

    mpBeep.Prepare();
    mpBeep.SetVolume( 1f, 1f );
    mpBeep.Looping = false;
  }

  public static void PlaySound_Beep()
  {
    if (mpBeep.IsPlaying == true) 
    {
      mpBeep.Stop();
      mpBeep.Reset();
      InitSound_Beep(); 
    }
    mpBeep.Start();
  }
}

In main activity, on create:

protected override void OnCreate( Bundle savedInstanceState )
{
  base.OnCreate( savedInstanceState );
  SetContentView( Resource.Layout.lmain_activity );
  ...
  eSound_Def.InitSounds( Assets );
  ...
}

how to use in code (on button click):

private void bButton_Click( object sender, EventArgs e )
{
  eSound_Def.PlaySound_Beep();
}

How can I exclude one word with grep?

If your grep supports Perl regular expression with -P option you can do (if bash; if tcsh you'll need to escape the !):

grep -P '(?!.*unwanted_word)keyword' file

Demo:

$ cat file
foo1
foo2
foo3
foo4
bar
baz

Let us now list all foo except foo3

$ grep -P '(?!.*foo3)foo' file
foo1
foo2
foo4
$ 

' << ' operator in verilog

<< is the left-shift operator, as it is in many other languages.

Here RAM_DEPTH will be 1 left-shifted by 8 bits, which is equivalent to 2^8, or 256.

Android TextView Justify Text

On android, to left justify text and not have truncation of the background color, try this, it worked for me, producing consistent results on android, ff, ie & chrome but you have to measure out the space that's left in between for the text when calculating the padding.

<td style="font-family:Calibri,Arial;
    font-size:15px;
    font-weight:800;
    background-color:#f5d5fd;
    color:black;
    border-style:solid;
    border-width:1px;
    border-color:#bd07eb;
    padding-left:10px;
    padding-right:1000px;
    padding-top:3px;
    padding-bottom:3px;
>

The hack is the padding-right:1000px; that pushes the text to the extreme left.

Any attempt to to a left or justify code in css or html results in a background that's only half width.

How to implement a custom AlertDialog View

This worked for me:

dialog.setView(dialog.getLayoutInflater().inflate(R.layout.custom_dialog_layout, null));

Delete the last two characters of the String

You may also try the following code with exception handling. Here you have a method removeLast(String s, int n) (it is actually an modified version of masud.m's answer). You have to provide the String s and how many char you want to remove from the last to this removeLast(String s, int n) function. If the number of chars have to remove from the last is greater than the given String length then it throws a StringIndexOutOfBoundException with a custom message -

public String removeLast(String s, int n) throws StringIndexOutOfBoundsException{

        int strLength = s.length();

        if(n>strLength){
            throw new StringIndexOutOfBoundsException("Number of character to remove from end is greater than the length of the string");
        }

        else if(null!=s && !s.isEmpty()){

            s = s.substring(0, s.length()-n);
        }

        return s;

    }

sudo: npm: command not found

For CentOS users, this works for me:

sudo yum install npm

git commit error: pathspec 'commit' did not match any file(s) known to git

Had this happen to me when committing from Xcode 6, after I had added a directory of files and subdirectories to the project folder. The problem was that, in the Commit sheet, in the left sidebar, I had checkmarked not only the root directory that I had added, but all of its descendants too. To solve the problem, I checkmarked only the root directory. This also committed all of the descendants, as desired, with no error.

Mockito - NullpointerException when stubbing Method

The default return value of methods you haven't stubbed yet is false for boolean methods, an empty collection or map for methods returning collections or maps and null otherwise.

This also applies to method calls within when(...). In you're example when(myService.getListWithData(inputData).get()) will cause a NullPointerException because myService.getListWithData(inputData) is null - it has not been stubbed before.

One option is create mocks for all intermediate return values and stub them before use. For example:

ListWithData listWithData = mock(ListWithData.class);
when(listWithData.get()).thenReturn(item1);
when(myService.getListWithData()).thenReturn(listWithData);

Or alternatively, you can specify a different default answer when creating a mock, to make methods return a new mock instead of null: RETURNS_DEEP_STUBS

SomeService myService = mock(SomeService.class, Mockito.RETURNS_DEEP_STUBS);
when(myService.getListWithData().get()).thenReturn(item1);

You should read the Javadoc of Mockito.RETURNS_DEEP_STUBS which explains this in more detail and also has some warnings about its usage.

I hope this helps. Just note that your example code seems to have more issues, such as missing assert or verify statements and calling setters on mocks (which does not have any effect).

Angular ReactiveForms: Producing an array of checkbox values?

With the help of silentsod answer, I wrote a solution to get values instead of states in my formBuilder.

I use a method to add or remove values in the formArray. It may be a bad approch, but it works !

component.html

<div *ngFor="let choice of checks; let i=index" class="col-md-2">
  <label>
    <input type="checkbox" [value]="choice.value" (change)="onCheckChange($event)">
    {{choice.description}}
  </label>
</div>

component.ts

// For example, an array of choices
public checks: Array<ChoiceClass> = [
  {description: 'descr1', value: 'value1'},
  {description: "descr2", value: 'value2'},
  {description: "descr3", value: 'value3'}
];

initModelForm(): FormGroup{
  return this._fb.group({
    otherControls: [''],
    // The formArray, empty 
    myChoices: new FormArray([]),
  }
}

onCheckChange(event) {
  const formArray: FormArray = this.myForm.get('myChoices') as FormArray;

  /* Selected */
  if(event.target.checked){
    // Add a new control in the arrayForm
    formArray.push(new FormControl(event.target.value));
  }
  /* unselected */
  else{
    // find the unselected element
    let i: number = 0;

    formArray.controls.forEach((ctrl: FormControl) => {
      if(ctrl.value == event.target.value) {
        // Remove the unselected element from the arrayForm
        formArray.removeAt(i);
        return;
      }

      i++;
    });
  }
}

When I submit my form, for example my model looks like:

  otherControls : "foo",
  myChoices : ['value1', 'value2']

Only one thing is missing, a function to fill the formArray if your model already has checked values.

Best way to store time (hh:mm) in a database

I would convert them to an integer (HH*3600 + MM*60), and store it that way. Small storage size, and still easy enough to work with.

intellij idea - Error: java: invalid source release 1.9

For anyone struggling with this issue who tried DeanM's solution but to no avail, there's something else worth checking, which is the version of the JDK you have configured for your project. What I'm trying to say is that if you have configured JDK 8u191 (for example) for your project, but have the language level set to anything higher than 8, you're gonna get this error.

In this case, it's probably better to ask whoever's in charge of the project, which version of the JDK would be preferable to compile the sources.

how to change the dist-folder path in angular-cli after 'ng build'

for github pages I Use

ng build --prod --base-href "https://<username>.github.io/<RepoName>/" --output-path=docs

This is what that copies output into the docs folder : --output-path=docs

Get element by id - Angular2

Complate Angular Way ( Set/Get value by Id ):

// In Html tag

 <button (click) ="setValue()">Set Value</button>
 <input type="text"  #userNameId />

// In component .ts File

    export class testUserClass {
       @ViewChild('userNameId') userNameId: ElementRef;

      ngAfterViewInit(){
         console.log(this.userNameId.nativeElement.value );
       }

      setValue(){
        this.userNameId.nativeElement.value = "Sample user Name";
      }



   }

How to set 24-hours format for date on java?

tl;dr

The modern approach uses java.time classes.

Instant.now()                                        // Capture current moment in UTC.
       .truncatedTo( ChronoUnit.SECONDS )            // Lop off any fractional second.
       .plus( 8 , ChronoUnit.HOURS )                 // Add eight hours.
       .atZone( ZoneId.of( "America/Montreal" ) )    // Adjust from UTC to the wall-clock time used by the people of a certain region (a time zone). Returns a `ZonedDateTime` object.
       .format(                                      // Generate a `String` object representing textually the value of the `ZonedDateTime` object.
           DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss" )
                            .withLocale( Locale.US ) // Specify a `Locale` to determine the human language and cultural norms used in localizing the text being generated. 
       )                                             // Returns a `String` object.

23/01/2017 15:34:56

java.time

FYI, the old Calendar and Date classes are now legacy. Supplanted by the java.time classes. Much of java.time is back-ported to Java 6, Java 7, and Android (see below).

Instant

Capture the current moment in UTC with the Instant class.

Instant instantNow = Instant.now();

instant.toString(): 2017-01-23T12:34:56.789Z

If you want only whole seconds, without any fraction of a second, truncate.

Instant instant = instantNow.truncatedTo( ChronoUnit.SECONDS );

instant.toString(): 2017-01-23T12:34:56Z

Math

The Instant class can do math, adding an amount of time. Specify the amount of time to add by the ChronoUnit enum, an implementation of TemporalUnit.

instant = instant.plus( 8 , ChronoUnit.HOURS );

instant.toString(): 2017-01-23T20:34:56Z

ZonedDateTime

To see that same moment through the lens of a particular region’s wall-clock time, apply a ZoneId to get a ZonedDateTime.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

zdt.toString(): 2017-01-23T15:34:56-05:00[America/Montreal]

Generate string

You can generate a String in your desired format by specifying a formatting pattern in a DateTimeFormatter object.

Note that case matters in the letters of your formatting pattern. The Question’s code had hh which is for 12-hour time while uppercase HH is 24-hour time (0-23) in both java.time.DateTimeFormatter as well as the legacy java.text.SimpleDateFormat.

The formatting codes in java.time are similar to those in the legacy SimpleDateFormat but not exactly the same. Carefully study the class doc. Here, HH happens to work identically.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss" ).withLocale( Locale.US );
String output = zdt.format( f );

Automatic localization

Rather than hard-coding a formatting pattern, consider letting java.time fully localize the generation of the String text by calling DateTimeFormatter.ofLocalizedDateTime.

And, by the way, be aware that time zone and Locale have nothing to do with one another; orthogonal issues. One is about content, the meaning (the wall-clock time). The other is about presentation, determining the human language and cultural norms used in presenting that meaning to the user.

Instant instant = Instant.parse( "2017-01-23T12:34:56Z" );
ZoneId z = ZoneId.of( "Pacific/Auckland" );  // Notice that time zone is unrelated to the `Locale` used in localizing.
ZonedDateTime zdt = instant.atZone( z );

DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL )
                                       .withLocale( Locale.CANADA_FRENCH );  // The locale determines human language and cultural norms used in generating the text representing this date-time object.
String output = zdt.format( f );

instant.toString(): 2017-01-23T12:34:56Z

zdt.toString(): 2017-01-24T01:34:56+13:00[Pacific/Auckland]

output: mardi 24 janvier 2017 à 01:34:56 heure avancée de la Nouvelle-Zélande


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?


Joda-Time

Update: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.

Joda-Time makes this kind of work much easier.

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;

DateTime later = DateTime.now().plusHours( 8 );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd/MM/yyyy HH:mm:ss" );
String laterAsText = formatter.print( later );

System.out.println( "laterAsText: " + laterAsText );

When run…

laterAsText: 19/12/2013 02:50:18

Beware that this syntax uses default time zone. A better practice is to use an explicit DateTimeZone instance.

How to get the wsdl file from a webservice's URL

By postfixing the URL with ?WSDL

If the URL is for example:

http://webservice.example:1234/foo

You use:

http://webservice.example:1234/foo?WSDL

And the wsdl will be delivered.

"git rm --cached x" vs "git reset head --? x"?

Perhaps an example will help:

git rm --cached asd
git commit -m "the file asd is gone from the repository"

versus

git reset HEAD -- asd
git commit -m "the file asd remains in the repository"

Note that if you haven't changed anything else, the second commit won't actually do anything.

Android disable screen timeout while app is running

this is the best way to solve this

 getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

Cloning specific branch

I don't think you fully understand how git by default gives you all history of all branches.

git clone --branch master <URL> will give you what you want.

But in fact, in any of the other repos where you ended up with test_1 checked out, you could have just done git checkout master and it would have switched you to the master branch.

(What @CodeWizard says is all true, I just think it's more advanced than what you really need.)

Switch tabs using Selenium WebDriver with Java

Work around

Assumption : By Clicking something on your web page leads to open a new tab.

Use below logic to switch to second tab.

new Actions(driver).sendKeys(driver.findElement(By.tagName("html")), Keys.CONTROL).sendKeys(driver.findElement(By.tagName("html")),Keys.NUMPAD2).build().perform();

In the same manner you can switch back to first tab again.

new Actions(driver).sendKeys(driver.findElement(By.tagName("html")), Keys.CONTROL).sendKeys(driver.findElement(By.tagName("html")),Keys.NUMPAD1).build().perform();

Java project in Eclipse: The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files

No amount of cleaning, closing/reopening the project&IDE, removing/adding the JRE in build path worked for me.

The solution I found was to remove the project from Eclipse (not from disk), remove the project's Eclipse files from the disk, and import into Eclipse again. That worked.

It is even faster if you are using Maven:

  1. Close Eclipse (no need to remove the project)
  2. Run mvn clean eclipse:clean eclipse:eclipse
  3. Open Eclipse. Your project is still present and the problem should be gone.

Check if a list contains an item in Ansible

You do not need {{}} in when conditions. What you are searching for is:

- fail: msg="unsupported version"
  when: version not in acceptable_versions

SELECT DISTINCT on one column

The simplest solution would be to use a subquery for finding the minimum ID matching your query. In the subquery you use GROUP BY instead of DISTINCT:

SELECT * FROM [TestData] WHERE [ID] IN (
   SELECT MIN([ID]) FROM [TestData]
   WHERE [SKU] LIKE 'FOO-%'
   GROUP BY [PRODUCT]
)

How to get store information in Magento?

Magento Store Id : Mage::app()->getStore()->getStoreId();

Magento Store Name : Mage::app()->getStore()->getName();

Compress images on client side before uploading

I'm late to the party, but this solution worked for me quite well. Based on this library, you can use a function lik this - setting the image, quality, max-width, and output format (jepg,png):

function compress(source_img_obj, quality, maxWidth, output_format){
    var mime_type = "image/jpeg";
    if(typeof output_format !== "undefined" && output_format=="png"){
        mime_type = "image/png";
    }

    maxWidth = maxWidth || 1000;
    var natW = source_img_obj.naturalWidth;
    var natH = source_img_obj.naturalHeight;
    var ratio = natH / natW;
    if (natW > maxWidth) {
        natW = maxWidth;
        natH = ratio * maxWidth;
    }

    var cvs = document.createElement('canvas');
    cvs.width = natW;
    cvs.height = natH;

    var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0, natW, natH);
    var newImageData = cvs.toDataURL(mime_type, quality/100);
    var result_image_obj = new Image();
    result_image_obj.src = newImageData;
    return result_image_obj;
}

Simple state machine example in C#?

Some shameless self-promo here, but a while ago I created a library called YieldMachine which allows a limited-complexity state machine to be described in a very clean and simple way. For example, consider a lamp:

state machine of a lamp

Notice that this state machine has 2 triggers and 3 states. In YieldMachine code, we write a single method for all state-related behavior, in which we commit the horrible atrocity of using goto for each state. A trigger becomes a property or field of type Action, decorated with an attribute called Trigger. I've commented the code of the first state and its transitions below; the next states follow the same pattern.

public class Lamp : StateMachine
{
    // Triggers (or events, or actions, whatever) that our
    // state machine understands.
    [Trigger]
    public readonly Action PressSwitch;

    [Trigger]
    public readonly Action GotError;

    // Actual state machine logic
    protected override IEnumerable WalkStates()
    {
    off:                                       
        Console.WriteLine("off.");
        yield return null;

        if (Trigger == PressSwitch) goto on;
        InvalidTrigger();

    on:
        Console.WriteLine("*shiiine!*");
        yield return null;

        if (Trigger == GotError) goto error;
        if (Trigger == PressSwitch) goto off;
        InvalidTrigger();

    error:
        Console.WriteLine("-err-");
        yield return null;

        if (Trigger == PressSwitch) goto off;
        InvalidTrigger();
    }
}

Short and nice, eh!

This state machine is controlled simply by sending triggers to it:

var sm = new Lamp();
sm.PressSwitch(); //go on
sm.PressSwitch(); //go off

sm.PressSwitch(); //go on
sm.GotError();    //get error
sm.PressSwitch(); //go off

Just to clarify, I've added some comments to the first state to help you understand how to use this.

    protected override IEnumerable WalkStates()
    {
    off:                                       // Each goto label is a state

        Console.WriteLine("off.");             // State entry actions

        yield return null;                     // This means "Wait until a 
                                               // trigger is called"

                                               // Ah, we got triggered! 
                                               //   perform state exit actions 
                                               //   (none, in this case)

        if (Trigger == PressSwitch) goto on;   // Transitions go here: 
                                               // depending on the trigger 
                                               // that was called, go to
                                               // the right state

        InvalidTrigger();                      // Throw exception on 
                                               // invalid trigger

        ...

This works because the C# compiler actually created a state machine internally for each method that uses yield return. This construct is usually used to lazily create sequences of data, but in this case we're not actually interested in the returned sequence (which is all nulls anyway), but in the state behaviour that gets created under the hood.

The StateMachine base class does some reflection on construction to assign code to each [Trigger] action, which sets the Trigger member and moves the state machine forward.

But you don't really need to understand the internals to be able to use it.

Elasticsearch error: cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark exceeded

This happens when Elasticsearch thinks the disk is running low on space so it puts itself into read-only mode.

By default Elasticsearch's decision is based on the percentage of disk space that's free, so on big disks this can happen even if you have many gigabytes of free space.

The flood stage watermark is 95% by default, so on a 1TB drive you need at least 50GB of free space or Elasticsearch will put itself into read-only mode.

For docs about the flood stage watermark see https://www.elastic.co/guide/en/elasticsearch/reference/6.2/disk-allocator.html.

The right solution depends on the context - for example a production environment vs a development environment.

Solution 1: free up disk space

Freeing up enough disk space so that more than 5% of the disk is free will solve this problem. Elasticsearch won't automatically take itself out of read-only mode once enough disk is free though, you'll have to do something like this to unlock the indices:

$ curl -XPUT -H "Content-Type: application/json" https://[YOUR_ELASTICSEARCH_ENDPOINT]:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'

Solution 2: change the flood stage watermark setting

Change the "cluster.routing.allocation.disk.watermark.flood_stage" setting to something else. It can either be set to a lower percentage or to an absolute value. Here's an example of how to change the setting from the docs:

PUT _cluster/settings
{
  "transient": {
    "cluster.routing.allocation.disk.watermark.low": "100gb",
    "cluster.routing.allocation.disk.watermark.high": "50gb",
    "cluster.routing.allocation.disk.watermark.flood_stage": "10gb",
    "cluster.info.update.interval": "1m"
  }
}

Again, after doing this you'll have to use the curl command above to unlock the indices, but after that they should not go into read-only mode again.

Warning :-Presenting view controllers on detached view controllers is discouraged

The reason of this warning is i was presenting a view controller over a small view that is not full size view. Given below is the image of my project. where on click on four option above. User navigate to different childviewcontroller's view.(it works like tabViewcontroller). But the childviewcontroller contains view of small size. So if we present a view from childviewcontroller it gives this warning.

master detail view

And to avoid this, you can present a view on childviewcontroller's parent

  [self.parentViewController presentViewController:viewController animated:YES completion:nil];

Automating running command on Linux from Windows using PuTTY

There could be security issues with common methods for auto-login. One of the most easiest ways is documented below:

And as for the part the executes the command In putty UI, Connection>SSH> there's a field for remote command.

4.17 The SSH panel

The SSH panel allows you to configure options that only apply to SSH sessions.

4.17.1 Executing a specific command on the server

In SSH, you don't have to run a general shell session on the server. Instead, you can choose to run a single specific command (such as a mail user agent, for example). If you want to do this, enter the command in the "Remote command" box. http://the.earth.li/~sgtatham/putty/0.53/htmldoc/Chapter4.html

in short, your answers might just as well be similar to the text below:

In WPF, what are the differences between the x:Name and Name attributes?

Name:

  1. can be used only for descendants of FrameworkElement and FrameworkContentElement;
  2. can be set from code-behind via SetValue() and property-like.

x:Name:

  1. can be used for almost all XAML elements;
  2. can NOT be set from code-behind via SetValue(); it can only be set using attribute syntax on objects because it is a directive.

Using both directives in XAML for one FrameworkElement or FrameworkContentElement will cause an exception: if the XAML is markup compiled, the exception will occur on the markup compile, otherwise it occurs on load.

C++: Print out enum value as text

You can use a simpler pre-processor trick if you are willing to list your enum entries in an external file.

/* file: errors.def */
/* syntax: ERROR_DEF(name, value) */
ERROR_DEF(ErrorA, 0x1)
ERROR_DEF(ErrorB, 0x2)
ERROR_DEF(ErrorC, 0x4)

Then in a source file, you treat the file like an include file, but you define what you want the ERROR_DEF to do.

enum Errors {
#define ERROR_DEF(x,y) x = y,
#include "errors.def"
#undef ERROR_DEF
};

static inline std::ostream & operator << (std::ostream &o, Errors e) {
    switch (e) {
    #define ERROR_DEF(x,y) case y: return o << #x"[" << y << "]";
    #include "errors.def"
    #undef ERROR_DEF
    default: return o << "unknown[" << e << "]";
    }
}

If you use some source browsing tool (like cscope), you'll have to let it know about the external file.

Error :- java runtime environment JRE or java development kit must be available in order to run eclipse

I faced this issue and it get resolved by following steps.

  1. Open Eclipse.ini file in Notepad
  2. Search vm
  3. Delete non existing JRE path from this file as mention in below

    -vm C:/Program Files/Java/jre1.8.0_181/bin

  4. Save this file and run eclipse again.

Simple 'if' or logic statement in Python

If key isn't an int or float but a string, you need to convert it to an int first by doing

key = int(key)

or to a float by doing

key = float(key)

Otherwise, what you have in your question should work, but

if (key < 1) or (key > 34):

or

if not (1 <= key <= 34):

would be a bit clearer.

Link error "undefined reference to `__gxx_personality_v0'" and g++

If g++ still gives error Try using:

g++ file.c -lstdc++

Look at this post: What is __gxx_personality_v0 for?

Make sure -lstdc++ is at the end of the command. If you place it at the beginning (i.e. before file.c), you still can get this same error.

How to git clone a specific tag

Use --single-branch option to only clone history leading to tip of the tag. This saves a lot of unnecessary code from being cloned.

git clone <repo_url> --branch <tag_name> --single-branch

Gets byte array from a ByteBuffer in java

If one does not know anything about the internal state of the given (Direct)ByteBuffer and wants to retrieve the whole content of the buffer, this can be used:

ByteBuffer byteBuffer = ...;
byte[] data = new byte[byteBuffer.capacity()];
((ByteBuffer) byteBuffer.duplicate().clear()).get(data);

How to use orderby with 2 fields in linq?

If you have two or more field to order try this:

var soterdList = initialList.OrderBy(x => x.Priority).
                                    ThenBy(x => x.ArrivalDate).
                                    ThenBy(x => x.ShipDate);

You can add other fields with clasole "ThenBy"

What is thread safe or non-thread safe in PHP?

Apache MPM prefork with modphp is used because it is easy to configure/install. Performance-wise it is fairly inefficient. My preferred way to do the stack, FastCGI/PHP-FPM. That way you can use the much faster MPM Worker. The whole PHP remains non-threaded, but Apache serves threaded (like it should).

So basically, from bottom to top

Linux

Apache + MPM Worker + ModFastCGI (NOT FCGI) |(or)| Cherokee |(or)| Nginx

PHP-FPM + APC

ModFCGI does not correctly support PHP-FPM, or any external FastCGI applications. It only supports non-process managed FastCGI scripts. PHP-FPM is the PHP FastCGI process manager.

How can I get terminal output in python?

The recommended way in Python 3.5 and above is to use subprocess.run():

from subprocess import run
output = run("pwd", capture_output=True).stdout

How can I generate an MD5 hash?

MD5 is perfectly fine if you don't need the best security, and if you're doing something like checking file integrity then security is not a consideration. In such as case you might want to consider something simpler and faster, such as Adler32, which is also supported by the Java libraries.

How to mount a single file in a volume

I have same issue on my Windows 8.1

It turned out that it was due to case-sensitivity of path. I called docker-compose up from directory cd /c/users/alex/ and inside container a file was turned into directory.

But when I did cd /c/Users/alex/ (not Users capitalized) and called docker-compose up from there, it worked.

In my system both Users dir and Alex dir are capitalized, though it seems like only Users dir matter.

How to create streams from string in Node.Js?

Edit: Garth's answer is probably better.

My old answer text is preserved below.


To convert a string to a stream, you can use a paused through stream:

through().pause().queue('your string').end()

Example:

var through = require('through')

// Create a paused stream and buffer some data into it:
var stream = through().pause().queue('your string').end()

// Pass stream around:
callback(null, stream)

// Now that a consumer has attached, remember to resume the stream:
stream.resume()

logger configuration to log to file and print to stdout

For 2.7, try the following:

fh = logging.handlers.RotatingFileHandler(LOGFILE, maxBytes=(1048576*5), backupCount=7)

Python glob multiple filetypes

To glob multiple file types, you need to call glob() function several times in a loop. Since this function returns a list, you need to concatenate the lists.

For instance, this function do the job:

import glob
import os


def glob_filetypes(root_dir, *patterns):
    return [path
            for pattern in patterns
            for path in glob.glob(os.path.join(root_dir, pattern))]

Simple usage:

project_dir = "path/to/project/dir"
for path in sorted(glob_filetypes(project_dir, '*.txt', '*.mdown', '*.markdown')):
    print(path)

You can also use glob.iglob() to have an iterator:

Return an iterator which yields the same values as glob() without actually storing them all simultaneously.

def iglob_filetypes(root_dir, *patterns):
    return (path
            for pattern in patterns
            for path in glob.iglob(os.path.join(root_dir, pattern)))

How can I check a C# variable is an empty string "" or null?

if the variable is a string

bool result = string.IsNullOrEmpty(variableToTest);

if you only have an object which may or may not contain a string then

bool result = string.IsNullOrEmpty(variableToTest as string);

Reading rows from a CSV file in Python

Example:

import pandas as pd

data = pd.read_csv('data.csv')

# read row line by line
for d in data.values:
  # read column by index
  print(d[2])