Programs & Examples On #Trove4j

The Trove library provides high speed regular and primitive collections for Java.

Remove Trailing Spaces and Update in Columns in SQL Server

Example:

SELECT TRIM('   Sample   ');

Result: 'Sample'

UPDATE TableName SET ColumnName = TRIM(ColumnName)

Most common C# bitwise operations on enums

C++ operations are: & | ^ ~ (for and, or, xor and not bitwise operations). Also of interest are >> and <<, which are bitshift operations.

So, to test for a bit being set in a flag, you would use: if (flags & 8) //tests bit 4 has been set

Is there any difference between DECIMAL and NUMERIC in SQL Server?

To my knowledge there is no difference between NUMERIC and DECIMAL data types. They are synonymous to each other and either one can be used. DECIMAL and NUMERIC data types are numeric data types with fixed precision and scale.

Edit:

Speaking to a few collegues maybe its has something to do with DECIMAL being the ANSI SQL standard and NUMERIC being one Mircosoft prefers as its more commonly found in programming languages. ...Maybe ;)

How to remove a file from the index in git?

Only use git rm --cached [file] to remove a file from the index.

git reset <filename> can be used to remove added files from the index given the files are never committed.

% git add First.txt
% git ls-files
First.txt
% git commit -m "First"   
% git ls-files            
First.txt
% git reset First.txt
% git ls-files              
First.txt

NOTE: git reset First.txt has no effect on index after the commit.

Which brings me to the topic of git restore --staged <file>. It can be used to (presumably after the first commit) remove added files from the index given the files are never committed.

% git add Second.txt              
% git status        
On branch master
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
    new file:   Second.txt
% git ls-files       
First.txt
Second.txt
% git restore --staged Second.txt
% git ls-files 
First.txt
% git add Second.txt 
% git commit -m "Second"
% git status            
On branch master
nothing to commit, working tree clean
% git ls-files 
First.txt         
Second.txt
Desktop/Test% git restore --staged .
Desktop/Test% git ls-files
First.txt                   
Second.txt
Desktop/Test% git reset .                    
Desktop/Test% git ls-files
First.txt
Second.txt
% git rm --cached -r .
rm 'First.txt'
rm 'Second.txt'
% git ls-files  

tl;dr Look at last 15 lines. If you don't want to be confused with first commit, second commit, before commit, after commit.... always use git rm --cached [file]

How to put sshpass command inside a bash script?

Do which sshpass in your command line to get the absolute path to sshpass and replace it in the bash script.

You should also probably do the same with the command you are trying to run.

The problem might be that it is not finding it.

URL for public Amazon S3 bucket

The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.


Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.


If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/ is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/ or http://s3-external-1.amazonaws.com/bucket/

The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].

S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.

If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.

However... the two endpoints do not offer the same functionality.

Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.

Choose the correct type of endpoint (REST or web site) for your application:

http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff


¹ s3-external-1.amazonaws.com has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2 had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1 so s3-external-2 appears to have no purpose except backwards-compatibility.

Accessing JPEG EXIF rotation data in JavaScript on the client side

I upload expansion code to show photo by android camera on html as normal on some img tag with right rotaion, especially for img tag whose width is wider than height. I know this code is ugly but you don't need to install any other packages. (I used above code to obtain exif rotation value, Thank you.)

function getOrientation(file, callback) {
  var reader = new FileReader();
  reader.onload = function(e) {

    var view = new DataView(e.target.result);
    if (view.getUint16(0, false) != 0xFFD8) return callback(-2);
    var length = view.byteLength, offset = 2;
    while (offset < length) {
      var marker = view.getUint16(offset, false);
      offset += 2;
      if (marker == 0xFFE1) {
        if (view.getUint32(offset += 2, false) != 0x45786966) return callback(-1);
        var little = view.getUint16(offset += 6, false) == 0x4949;
        offset += view.getUint32(offset + 4, little);
        var tags = view.getUint16(offset, little);
        offset += 2;
        for (var i = 0; i < tags; i++)
          if (view.getUint16(offset + (i * 12), little) == 0x0112)
            return callback(view.getUint16(offset + (i * 12) + 8, little));
      }
      else if ((marker & 0xFF00) != 0xFF00) break;
      else offset += view.getUint16(offset, false);
    }
    return callback(-1);
  };
  reader.readAsArrayBuffer(file);
}

var isChanged = false;
function rotate(elem, orientation) {
    if (isIPhone()) return;

    var degree = 0;
    switch (orientation) {
        case 1:
            degree = 0;
            break;
        case 2:
            degree = 0;
            break;
        case 3:
            degree = 180;
            break;
        case 4:
            degree = 180;
            break;
        case 5:
            degree = 90;
            break;
        case 6:
            degree = 90;
            break;
        case 7:
            degree = 270;
            break;
        case 8:
            degree = 270;
            break;
    }
    $(elem).css('transform', 'rotate('+ degree +'deg)')
    if(degree == 90 || degree == 270) {
        if (!isChanged) {
            changeWidthAndHeight(elem)
            isChanged = true
        }
    } else if ($(elem).css('height') > $(elem).css('width')) {
        if (!isChanged) {
            changeWidthAndHeightWithOutMargin(elem)
            isChanged = true
        } else if(degree == 180 || degree == 0) {
            changeWidthAndHeightWithOutMargin(elem)
            if (!isChanged)
                isChanged = true
            else
                isChanged = false
        }
    }
}


function changeWidthAndHeight(elem){
    var e = $(elem)
    var width = e.css('width')
    var height = e.css('height')
    e.css('width', height)
    e.css('height', width)
    e.css('margin-top', ((getPxInt(height) - getPxInt(width))/2).toString() + 'px')
    e.css('margin-left', ((getPxInt(width) - getPxInt(height))/2).toString() + 'px')
}

function changeWidthAndHeightWithOutMargin(elem){
    var e = $(elem)
    var width = e.css('width')
    var height = e.css('height')
    e.css('width', height)
    e.css('height', width)
    e.css('margin-top', '0')
    e.css('margin-left', '0')
}

function getPxInt(pxValue) {
    return parseInt(pxValue.trim("px"))
}

function isIPhone(){
    return (
        (navigator.platform.indexOf("iPhone") != -1) ||
        (navigator.platform.indexOf("iPod") != -1)
    );
}

and then use such as

$("#banner-img").change(function () {
    var reader = new FileReader();
    getOrientation(this.files[0], function(orientation) {
        rotate($('#banner-img-preview'), orientation, 1)
    });

    reader.onload = function (e) {
        $('#banner-img-preview').attr('src', e.target.result)
        $('#banner-img-preview').css('display', 'inherit')

    };

    // read the image file as a data URL.
    reader.readAsDataURL(this.files[0]);

});

Replace text inside td using jQuery having td containing other elements

How about:

function changeText() {
    $("#demoTable td").each(function () {
       $(this).html().replace("8: Tap on APN and Enter <B>www</B>", "");
    }
}

How do I automatically update a timestamp in PostgreSQL

Using 'now()' as default value automatically generates time-stamp.

Send value of submit button when form gets posted

The initial post mentioned buttons. You can also replace the input tags with buttons.

<button type="submit" name="product" value="Tea">Tea</button>
<button type="submit" name="product" value="Coffee">Coffee</button>

The name and value attributes are required to submit the value when the form is submitted (the id attribute is not necessary in this case). The attribute type=submit specifies that clicking on this button causes the form to be submitted.

When the server is handling the submitted form, $_POST['product'] will contain the value "Tea" or "Coffee" depending on which button was clicked.

If you want you can also require the user to confirm before submitting the form (useful when you are implementing a delete button for example).

<button type="submit" name="product" value="Tea" onclick="return confirm('Are you sure you want tea?');">Tea</button>
<button type="submit" name="product" value="Coffee" onclick="return confirm('Are you sure you want coffee?');">Coffee</button>

MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050

As already stated, it's a warning not an error, but (if like me) you want things to run without warnings, you can disable that warning, then re-enable it again when you're done.

SET sql_notes = 0;      -- Temporarily disable the "Table already exists" warning
CREATE TABLE IF NOT EXISTS ...
SET sql_notes = 1;      -- And then re-enable the warning again

Java 8 stream reverse order

ArrayDeque are faster in the stack than a Stack or LinkedList. "push()" inserts elements at the front of the Deque

 protected <T> Stream<T> reverse(Stream<T> stream) {
    ArrayDeque<T> stack = new ArrayDeque<>();
    stream.forEach(stack::push);
    return stack.stream();
}

What is the difference between XML and XSD?

XSD:
XSD (XML Schema Definition) specifies how to formally describe the elements in an Extensible Markup Language (XML) document.
Xml:
XML was designed to describe data.It is independent from software as well as hardware.
It enhances the following things.
-Data sharing.
-Platform independent.
-Increasing the availability of Data.

Differences:

  1. XSD is based and written on XML.

  2. XSD defines elements and structures that can appear in the document, while XML does not.

  3. XSD ensures that the data is properly interpreted, while XML does not.

  4. An XSD document is validated as XML, but the opposite may not always be true.

  5. XSD is better at catching errors than XML.

An XSD defines elements that can be used in the documents, relating to the actual data with which it is to be encoded.
for eg:
A date that is expressed as 1/12/2010 can either mean January 12 or December 1st. Declaring a date data type in an XSD document, ensures that it follows the format dictated by XSD.

Objective-C : BOOL vs bool

At the time of writing this is the most recent version of objc.h:

/// Type to represent a boolean value.
#if (TARGET_OS_IPHONE && __LP64__)  ||  TARGET_OS_WATCH
#define OBJC_BOOL_IS_BOOL 1
typedef bool BOOL;
#else
#define OBJC_BOOL_IS_CHAR 1
typedef signed char BOOL; 
// BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C" 
// even if -funsigned-char is used.
#endif

It means that on 64-bit iOS devices and on WatchOS BOOL is exactly the same thing as bool while on all other devices (OS X, 32-bit iOS) it is signed char and cannot even be overridden by compiler flag -funsigned-char

It also means that this example code will run differently on different platforms (tested it myself):

int myValue = 256;
BOOL myBool = myValue;
if (myBool) {
    printf("i'm 64-bit iOS");
} else {
    printf("i'm 32-bit iOS");
}

BTW never assign things like array.count to BOOL variable because about 0.4% of possible values will be negative.

How do I iterate through lines in an external file with shell?

You'll be wanting to use the 'read' command

while read name
do
    echo "$name"
done < names.txt

Note that "$name" is quoted -- if it's not, it will be split using the characters in $IFS as delimiters. This probably won't be noticed if you're just echoing the variable, but if your file contains a list of file names which you want to copy, those will get broken down by $IFS if the variable is unquoted, which is not what you want or expect.

If you want to use Mike Clark's approach (loading into a variable rather than using read), you can do it without the use of cat:

NAMES="$(< scripts/names.txt)" #names from names.txt file
for NAME in $NAMES; do
    echo "$NAME"
done

The problem with this is that it loads the whole file into $NAMES, when you read it back out, you can either get the whole file (if quoted) or the file broken down by $IFS, if not quoted. By default, this will give you individual words, not individual lines. So if the name "Mary Jane" appeared on a line, you would get "Mary" and "Jane" as two separate names. Using read will get around this... although you could also change the value of $IFS

Get the records of last month in SQL server

SQL query to get record of the present month only

SELECT * FROM CUSTOMER
WHERE MONTH(DATE) = MONTH(CURRENT_TIMESTAMP) AND YEAR(DATE) = YEAR(CURRENT_TIMESTAMP);

How to convert an xml string to a dictionary?

@dibrovsd: Solution will not work if the xml have more than one tag with same name

On your line of thought, I have modified the code a bit and written it for general node instead of root:

from collections import defaultdict
def xml2dict(node):
    d, count = defaultdict(list), 1
    for i in node:
        d[i.tag + "_" + str(count)]['text'] = i.findtext('.')[0]
        d[i.tag + "_" + str(count)]['attrib'] = i.attrib # attrib gives the list
        d[i.tag + "_" + str(count)]['children'] = xml2dict(i) # it gives dict
     return d

nodejs mongodb object id to string

I'm using mongojs, and i have this example:

db.users.findOne({'_id': db.ObjectId(user_id)  }, function(err, user) {
   if(err == null && user != null){
      user._id.toHexString(); // I convert the objectId Using toHexString function.
   }
})

I hope this help.

Compare two Byte Arrays? (Java)

In your example, you have:

if (new BigInteger("1111000011110001", 2).toByteArray() == array)

When dealing with objects, == in java compares reference values. You're checking to see if the reference to the array returned by toByteArray() is the same as the reference held in array, which of course can never be true. In addition, array classes don't override .equals() so the behavior is that of Object.equals() which also only compares the reference values.

To compare the contents of two arrays, static array comparison methods are provided by the Arrays class

byte[] array = new BigInteger("1111000011110001", 2).toByteArray();
byte[] secondArray = new BigInteger("1111000011110001", 2).toByteArray();
if (Arrays.equals(array, secondArray))
{
    System.out.println("Yup, they're the same!");
}

Perl read line by line

If you had use strict turned on, you would have found out that $++foo doesn't make any sense.

Here's how to do it:

use strict;
use warnings;

my $file = 'SnPmaster.txt';
open my $info, $file or die "Could not open $file: $!";

while( my $line = <$info>)  {   
    print $line;    
    last if $. == 2;
}

close $info;

This takes advantage of the special variable $. which keeps track of the line number in the current file. (See perlvar)

If you want to use a counter instead, use

my $count = 0;
while( my $line = <$info>)  {   
    print $line;    
    last if ++$count == 2;
}

Getting the class name of an instance?

To get instance classname:

type(instance).__name__

or

instance.__class__.__name__

both are the same

How to see remote tags?

You can list the tags on remote repository with ls-remote, and then check if it's there. Supposing the remote reference name is origin in the following.

git ls-remote --tags origin

And you can list tags local with tag.

git tag

You can compare the results manually or in script.

Gson: How to exclude specific fields from Serialization without annotations

I have Kotlin version

@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FIELD)
internal annotation class JsonSkip

class SkipFieldsStrategy : ExclusionStrategy {

    override fun shouldSkipClass(clazz: Class<*>): Boolean {
        return false
    }

    override fun shouldSkipField(f: FieldAttributes): Boolean {
        return f.getAnnotation(JsonSkip::class.java) != null
    }
}

and how You can add this to Retrofit GSONConverterFactory:

val gson = GsonBuilder()
                .setExclusionStrategies(SkipFieldsStrategy())
                //.serializeNulls()
                //.setDateFormat(DateFormat.LONG)
                //.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
                //.setPrettyPrinting()
                //.registerTypeAdapter(Id.class, IdTypeAdapter())
                .create()
        return GsonConverterFactory.create(gson)

How can I make an "are you sure" prompt in a Windows batchfile?

try the CHOICE command, e.g.

CHOICE /C YNC /M "Press Y for Yes, N for No or C for Cancel."

The imported project "C:\Microsoft.CSharp.targets" was not found

For errors with Microsoft.WebApplications.targets, you can:

  1. Install Visual Studio 2010 (or the same version as in development machine) in your TFS server.
  2. Copy the “Microsoft.WebApplication.targets” from development machine file to TFS build machine.

Here's the post.

How do I get the path of the Python script I am running in?

os.path.realpath(__file__) will give you the path of the current file, resolving any symlinks in the path. This works fine on my mac.

Get Base64 encode file-data from Input Form

My solution was use readAsBinaryString() and btoa() on its result.

uploadFileToServer(event) {
    var file = event.srcElement.files[0];
    console.log(file);
    var reader = new FileReader();
    reader.readAsBinaryString(file);

    reader.onload = function() {
        console.log(btoa(reader.result));
    };
    reader.onerror = function() {
        console.log('there are some problems');
    };
}

What does $ mean before a string?

It signifies string interpolation.

It will protect you because it is adding compilation time protection on the string evaluation.

You will no longer get an exception with string.Format("{0}{1}",secondParamIsMissing)

Pandas Replace NaN with blank/empty string

import numpy as np
df1 = df.replace(np.nan, '', regex=True)

This might help. It will replace all NaNs with an empty string.

Alternative to the HTML Bold tag

Use the <strong> tag because it's more semantic. <b> has been depreciated so it's best not to use it. Also bold text is given more Search Engine Optimisation (SEO) weight so it's always best to use a real <strong> rather than making a <p> or <span> bold using CSS.

The shortest possible output from git log containing author and date

I use these two .gitconfig settings:

[log]
  date = relative
[format]
  pretty = format:%h %Cblue%ad%Creset %ae %Cgreen%s%Creset

%ad is the author date, which can be overidden by --date or the option specified in the [log] stanza in .gitconfig. I like the relative date because it gives an immediate feeling of when stuff was comitted. Output looks like this:

6c3e1a2 2 hours ago [email protected] lsof is a dependency now.
0754f18 11 hours ago [email protected] Properly unmount, so detaching works.
336a3ac 13 hours ago [email protected] Show ami registration command if auto register fails
be2ad45 17 hours ago [email protected] Fixes #6. Sao Paolo region is included as well.
5aed68e 17 hours ago [email protected] Shorten while loops

This is all of course in color, so it is easy to distinguish the various parts of a log line. Also it is the default when typing git log because of the [format] section.

2014 UPDATE: Since git now supports padding I have a nice amendment to the version above:

pretty = format:%C(yellow)%h %Cblue%>(12)%ad %Cgreen%<(7)%aN%Cred%d %Creset%s

This right aligns the relative dates and left aligns committer names, meaning you get a column-like look that is easy on the eyes.

Screenshot

  ss#1

2016 UPDATE: Since GPG commit signing is becoming a thing, I thought I'd update this post with a version that includes signature verification (in the screenshot it's the magenta letter right after the commit). A short explanation of the flag:

%G?: show "G" for a good (valid) signature, "B" for a bad signature, "U" for a good signature with unknown validity and "N" for no signature

Other changes include:

  • colors are now removed if the output is to something other than the tty (which is useful for grepping etc.)
  • git log -g now contains the reflog selector.
  • Save 2 parens on refnames and put them at the end (to preserve column alignment)
  • Truncate relative dates if they are too long (e.g. 3 years, 4..)
  • Truncate commiter names (might be a little short for some ppl, just change the %<(7,trunc) or check out the git .mailmap feature to shorten commiter names)

Here's the config:

pretty = format:%C(auto,yellow)%h%C(auto,magenta)% G? %C(auto,blue)%>(12,trunc)%ad %C(auto,green)%<(7,trunc)%aN%C(auto,reset)%s%C(auto,red)% gD% D

All in all column alignment is now preserved a lot better at the expense of some (hopefully) useless characters. Feel free to edit if you have any improvements, I'd love to make the message color depend on whether a commit is signed, but it doesn't seem like that is possible atm.

Screenshot

Screenshot of git log

Exception: There is already an open DataReader associated with this Connection which must be closed first

Always, always, always put disposable objects inside of using statements. I can't see how you've instantiated your DataReader but you should do it like this:

using (Connection c = ...)
{
    using (DataReader dr = ...)
    {
        //Work with dr in here.
    }
}
//Now the connection and reader have been closed and disposed.

Now, to answer your question, the reader is using the same connection as the command you're trying to ExecuteNonQuery on. You need to use a separate connection since the DataReader keeps the connection open and reads data as you need it.

How to handle screen orientation change when progress dialog and background thread active?

I've tried EVERYTHING. Spent days experimenting. I didn't want to block the activity from rotating. My scenario was:

  1. A progress dialog showing dynamic information to the user. E.g.: "Connecting to server...", "Downloading data...", etc.
  2. A thread doing the heavy stuff and updating the dialog
  3. Updating the UI with the results at the end.

The problem was, when rotating the screen, every solution on the book failed. Even with the AsyncTask class, which is the correct Android way of dealing with this situations. When rotating the screen, the current Context that the starting thread is working with, is gone, and that messes up with the dialog that is showing. The problem was always the Dialog, no matter how many tricks I added to the code (passing new contexts to running threads, retaining thread states through rotations, etc...). The code complexity at the end was always huge and there was always something that could go wrong.

The only solution that worked for me was the Activity/Dialog trick. It's simple and genius and it's all rotation proof:

  1. Instead of creating a Dialog and ask to show it, create an Activity that has been set in the manifest with android:theme="@android:style/Theme.Dialog". So, it just looks like a dialog.

  2. Replace showDialog(DIALOG_ID) with startActivityForResult(yourActivityDialog, yourCode);

  3. Use onActivityResult in the calling Activity to get the results from the executing thread (even the errors) and update the UI.

  4. On your 'ActivityDialog', use threads or AsyncTask to execute long tasks and onRetainNonConfigurationInstance to save "dialog" state when rotating the screen.

This is fast and works fine. I still use dialogs for other tasks and the AsyncTask for something that doesn't require a constant dialog on screen. But with this scenario, I always go for the Activity/Dialog pattern.

And, I didn't try it, but it's even possible to block that Activity/Dialog from rotating, when the thread is running, speeding things up, while allowing the calling Activity to rotate.

Check if list contains element that contains a string and get that element

It is possible to combine Any, Where, First and FirstOrDefault; or just place the predicate in any of those methods depending on what is needed.

You should probably avoid using First unless you want to have an exception thrown when no match is found. FirstOrDefault is usually the better option as long as you know it will return the type's default if no match is found (string's default is null, int is 0, bool is false, etc).

using System.Collections.Generic;
using System.Linq;


bool exists;
string firstMatch;
IEnumerable<string> matchingList;

var myList = new List<string>() { "foo", "bar", "foobar" };

exists = myList.Any(x => x.Contains("o"));
// exists => true

firstMatch = myList.FirstOrDefault(x => x.Contains("o"));
firstMatch = myList.First(x => x.Contains("o"));
// firstMatch => "foo"

firstMatch = myList.First(x => x.Contains("dark side"));
// throws exception because no element contains "dark side"

firstMatch = myList.FirstOrDefault(x => x.Contains("dark side"));
// firstMatch => null

matchingList = myList.Where(x => x.Contains("o")); 
// matchingList => { "foo", "foobar" }

Test this code @ https://rextester.com/TXDL57489

Where's my JSON data in my incoming Django request?

Using Angular you should add header to request or add it to module config headers: {'Content-Type': 'application/x-www-form-urlencoded'}

$http({
    url: url,
    method: method,
    timeout: timeout,
    data: data,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

matching query does not exist Error in Django

try:
    user = UniversityDetails.objects.get(email=email)
except UniversityDetails.DoesNotExist:
    user = None

I also see you're storing your passwords in plaintext (a big security no-no!). Consider using the built-in auth system instead.

Return array in a function

Here's a full example of this kind of problem to solve

#include <bits/stdc++.h>
using namespace std;
int* solve(int brr[],int n)
{
sort(brr,brr+n);
return brr;
}

int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
    cin>>arr[i];
}
int *a=solve(arr,n);
for(int i=0;i<n;i++)
{
    cout<<a[i]<<endl;
}

return 0;
}

How to get all Windows service names starting with a common word?

Save it as a .ps1 file and then execute

powershell -file "path\to your\start stop nation service command file.ps1"

C# Return Different Types?

My post here is strictly related to Blazor v5 but should work in 3.x as well. Additionally, I'm using these methods with bootstrap 4.5 and 5.0 beta 1 but you could easily adapt it to use style's instead of classes or use your own classes.

To those recommending dynamic, I thank you. The dynamic type seems like it can be very valuable when used correctly. Most of the time you'll probably use an interface but this wasn't plausible for me. I went ahead and updated my project with a dynamic return type and it's working great while being the quickest, cleanest solution.

I previously added the following extension methods to boolean types to help me avoid long ternary operators in razor page code. Here are the 3 main extension methods I use to accomplish it:

public static T Then<T>(this bool value, T result) => value ? result : default;    
public static T Then<T>(this bool value, T thenResult, T elseResult) => value ? thenResult : elseResult;
public static T Else<T>(this bool value, T result) => !value ? result : default;

The following are examples of that implementation:

<div class="@Hidden.Then("d-none")">
    Hidden content...
</div>

Note: ErrorOrWarning would hide the content if there was no error/warning so I could default it to yellow/italic but this is an example so please use your imagination:

<div class="@ErrorOrWarning.Else("d-none")" style="@Error.Then("color:red;font-weight:bold;","color:yellow;font-style:italic;")">
    Error/Warning content...
</div>

This is the typical implementation without the extension methods. It's common to see this technique in Blazor guides/tutorials/videos online. There are cleaner ways to handle it but this is the basic idea:

<div class="@(ErrorOrWarning ? "" : "d-none")" style="@(Error ? "color:red;font-weight:bold;" : "color:yellow;font-style:italic;")">
    Error/Warning content...
</div>

While this might not seem like too big a difference, if you have a lot of dynamic content/styles driving your page, it can get really messy. With those 3 lines of code you can enhance the readability and cleanliness and it really does reduce risk of typos. Adding two more extension methods, you can reduce the risk even further Note: Again, this is using bootstrap class "d-none" for the style "display:none!important" but you could just as easily replace with your own usage:

public static string ThenShow(this bool value) => value ? "" : "d-none";
public static string ThenHide(this bool value) => value ? "d-none" : "";

The limitation I previously faced was when using the overloaded Then(thenResult, elseResult), each of the parameters must be of the same type. 99% of the time this is fine. Actually, another 0.5% of the time it's still okay because you can probably solve it quickly with a .ToString() or an explicit cast.

What I ran into, and what took me to this post was: I have a control you can imagine as a button. There is an Enum property allowing the user to select an icon to display. The selected Enum dynamically populates a readonly MarkupString property. As an alternative option, they can use the ChildContent (or IconContent in my example) of type RenderFragment. This will let them manually add anything they want (maybe an iFrame to stackoverflow haha) but my intention is for them to add style, most likely in the form of an icon.

I know I can cast/convert one to the other however my existing extension method is so clean and simple, it would be great to be able to use pass the MarkupString and RenderFragment together as parameters, conditionally output to the razor page. So, thanks to this post, I changed my Then(thenResult, elseResult) extension methods to use unique generic parameter types and return a dynamic type like so:

public static dynamic Then<T,E>(this bool value, T thenResult, E elseResult) => value ? thenResult : elseResult;

Now in my razor page I have a very simple line for the icon output. Note: IconContent is a RenderFragment and IconMarkup is a MarkupString.

@((@IconContent == null).Then(IconMarkup, IconContent))

And because I love extension methods and I'm typing this up, I took it a step further with another extension method:

public static bool IsNull(this RenderFragment value) => value == null;

Which enables the extremely clean and simple:

@IconContent.IsNull().Then(IconMarkup, IconContent)

Here's the extra extension method I mentioned above which converts a string to a MarkupString. It might be overkill but I like it.

public static MarkupString ToMarkup(this string value) => (MarkupString)value;

Let me know if you have a better recommendation or if you think I'm doing something wrong. I'm sure this post makes it seem like I overuse extension methods but I really don't. I keep their use limited to outcomes such as I've outlined in this post.

Understanding dispatch_async

All of the DISPATCH_QUEUE_PRIORITY_X queues are concurrent queues (meaning they can execute multiple tasks at once), and are FIFO in the sense that tasks within a given queue will begin executing using "first in, first out" order. This is in comparison to the main queue (from dispatch_get_main_queue()), which is a serial queue (tasks will begin executing and finish executing in the order in which they are received).

So, if you send 1000 dispatch_async() blocks to DISPATCH_QUEUE_PRIORITY_DEFAULT, those tasks will start executing in the order you sent them into the queue. Likewise for the HIGH, LOW, and BACKGROUND queues. Anything you send into any of these queues is executed in the background on alternate threads, away from your main application thread. Therefore, these queues are suitable for executing tasks such as background downloading, compression, computation, etc.

Note that the order of execution is FIFO on a per-queue basis. So if you send 1000 dispatch_async() tasks to the four different concurrent queues, evenly splitting them and sending them to BACKGROUND, LOW, DEFAULT and HIGH in order (ie you schedule the last 250 tasks on the HIGH queue), it's very likely that the first tasks you see starting will be on that HIGH queue as the system has taken your implication that those tasks need to get to the CPU as quickly as possible.

Note also that I say "will begin executing in order", but keep in mind that as concurrent queues things won't necessarily FINISH executing in order depending on length of time for each task.

As per Apple:

https://developer.apple.com/library/content/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html

A concurrent dispatch queue is useful when you have multiple tasks that can run in parallel. A concurrent queue is still a queue in that it dequeues tasks in a first-in, first-out order; however, a concurrent queue may dequeue additional tasks before any previous tasks finish. The actual number of tasks executed by a concurrent queue at any given moment is variable and can change dynamically as conditions in your application change. Many factors affect the number of tasks executed by the concurrent queues, including the number of available cores, the amount of work being done by other processes, and the number and priority of tasks in other serial dispatch queues.

Basically, if you send those 1000 dispatch_async() blocks to a DEFAULT, HIGH, LOW, or BACKGROUND queue they will all start executing in the order you send them. However, shorter tasks may finish before longer ones. Reasons behind this are if there are available CPU cores or if the current queue tasks are performing computationally non-intensive work (thus making the system think it can dispatch additional tasks in parallel regardless of core count).

The level of concurrency is handled entirely by the system and is based on system load and other internally determined factors. This is the beauty of Grand Central Dispatch (the dispatch_async() system) - you just make your work units as code blocks, set a priority for them (based on the queue you choose) and let the system handle the rest.

So to answer your above question: you are partially correct. You are "asking that code" to perform concurrent tasks on a global concurrent queue at the specified priority level. The code in the block will execute in the background and any additional (similar) code will execute potentially in parallel depending on the system's assessment of available resources.

The "main" queue on the other hand (from dispatch_get_main_queue()) is a serial queue (not concurrent). Tasks sent to the main queue will always execute in order and will always finish in order. These tasks will also be executed on the UI Thread so it's suitable for updating your UI with progress messages, completion notifications, etc.

KeyListener, keyPressed versus keyTyped

Neither. You should NOT use a KeyLIstener.

Swing was designed to be used with Key Bindings. Read the section from the Swing tutorial on How to Use Key Bindings.

How to do an array of hashmaps?

The Java Language Specification, section 15.10, states:

An array creation expression creates an object that is a new array whose elements are of the type specified by the PrimitiveType or ClassOrInterfaceType. It is a compile-time error if the ClassOrInterfaceType does not denote a reifiable type (§4.7).

and

The rules above imply that the element type in an array creation expression cannot be a parameterized type, other than an unbounded wildcard.

The closest you can do is use an unchecked cast, either from the raw type, as you have done, or from an unbounded wildcard:

 HashMap<String, String>[] responseArray = (Map<String, String>[]) new HashMap<?,?>[games.size()];

Your version is clearly better :-)

How to make certain text not selectable with CSS

The CSS below stops users from being able to select text.

-webkit-user-select: none; /* Safari */        
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* IE10+/Edge */
user-select: none; /* Standard */

To target IE9 downwards the html attribute unselectable must be used instead:

<p unselectable="on">Test Text</p>

Reloading the page gives wrong GET request with AngularJS HTML5 mode

There are few things to set up so your link in the browser will look like http://yourdomain.com/path and these are your angular config + server side

1) AngularJS

$routeProvider
  .when('/path', {
    templateUrl: 'path.html',
  });
$locationProvider
  .html5Mode(true);

2) server side, just put .htaccess inside your root folder and paste this

RewriteEngine On 
Options FollowSymLinks

RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /#/$1 [L]

More interesting stuff to read about html5 mode in angularjs and the configuration required per different environment https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode Also this question might help you $location / switching between html5 and hashbang mode / link rewriting

SQL subquery with COUNT help

This is probably the easiest way, not the prettiest though:

SELECT *,
    (SELECT Count(*) FROM eventsTable WHERE columnName = 'Business') as RowCount
    FROM eventsTable
    WHERE columnName = 'Business'

This will also work without having to use a group by

SELECT *, COUNT(*) OVER () as RowCount
    FROM eventsTables
    WHERE columnName = 'Business'

Android Room - simple select query - Cannot access database on the main thread

Just do the database operations in a separate Thread. Like this (Kotlin):

Thread {
   //Do your database´s operations here
}.start()

How to search for a part of a word with ElasticSearch

Nevermind.

I had to look at the Lucene documentation. Seems I can use wildcards! :-)

curl http://localhost:9200/my_idx/my_type/_search?q=*Doe*

does the trick!

How do I parse a string to a float or int?

Users codelogic and harley are correct, but keep in mind if you know the string is an integer (for example, 545) you can call int("545") without first casting to float.

If your strings are in a list, you could use the map function as well.

>>> x = ["545.0", "545.6", "999.2"]
>>> map(float, x)
[545.0, 545.60000000000002, 999.20000000000005]
>>>

It is only good if they're all the same type.

htaccess redirect to https://www

To first force HTTPS, you must check the correct environment variable %{HTTPS} off, but your rule above then prepends the www. Since you have a second rule to enforce www., don't use it in the first rule.

RewriteEngine On
RewriteCond %{HTTPS} off
# First rewrite to HTTPS:
# Don't put www. here. If it is already there it will be included, if not
# the subsequent rule will catch it.
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Now, rewrite any request to the wrong domain to use www.
# [NC] is a case-insensitive match
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

About proxying

When behind some forms of proxying, whereby the client is connecting via HTTPS to a proxy, load balancer, Passenger application, etc., the %{HTTPS} variable may never be on and cause a rewrite loop. This is because your application is actually receiving plain HTTP traffic even though the client and the proxy/load balancer are using HTTPS. In these cases, check the X-Forwarded-Proto header instead of the %{HTTPS} variable. This answer shows the appropriate process

'Static readonly' vs. 'const'

One thing to note is const is restricted to primitive/value types (the exception being strings).

Maximum execution time in phpMyadmin

ini_set('max_execution_time', 0); or create file name called php.ini and enter the first line max_execution_time=0 then save it and put the file in your root folder of your application.

That's it. Good luck.

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.

Loop through array of values with Arrow Function

One statement can be written as such:

someValues.forEach(x => console.log(x));

or multiple statements can be enclosed in {} like this:

someValues.forEach(x => { let a = 2 + x; console.log(a); });

AngularJS dynamic routing

I think the easiest way to do such thing is to resolve the routes later, you could ask the routes via json, for example. Check out that I make a factory out of the $routeProvider during config phase, via $provide, so I can keep using the $routeProvider object in the run phase, and even in controllers.

'use strict';

angular.module('myapp', []).config(function($provide, $routeProvider) {
    $provide.factory('$routeProvider', function () {
        return $routeProvider;
    });
}).run(function($routeProvider, $http) {
    $routeProvider.when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
    }).otherwise({
        redirectTo: '/'
    });

    $http.get('/dynamic-routes.json').success(function(data) {
        $routeProvider.when('/', {
            templateUrl: 'views/main.html',
            controller: 'MainCtrl'
        });
        // you might need to call $route.reload() if the route changed
        $route.reload();
    });
});

run program in Python shell

It depends on what is in test.py. The following is an appropriate structure:

# suppose this is your 'test.py' file
def main():
 """This function runs the core of your program"""
 print("running main")

if __name__ == "__main__":
 # if you call this script from the command line (the shell) it will
 # run the 'main' function
 main()

If you keep this structure, you can run it like this in the command line (assume that $ is your command-line prompt):

$ python test.py
$ # it will print "running main"

If you want to run it from the Python shell, then you simply do the following:

>>> import test
>>> test.main() # this calls the main part of your program

There is no necessity to use the subprocess module if you are already using Python. Instead, try to structure your Python files in such a way that they can be run both from the command line and the Python interpreter.

Pretty-Printing JSON with PHP

You could do it like below.

$array = array(
   "a" => "apple",
   "b" => "banana",
   "c" => "catnip"
);

foreach ($array as $a_key => $a_val) {
   $json .= "\"{$a_key}\" : \"{$a_val}\",\n";
}

header('Content-Type: application/json');
echo "{\n"  .rtrim($json, ",\n") . "\n}";

Above would output kind of like Facebook.

{
"a" : "apple",
"b" : "banana",
"c" : "catnip"
}

Transform char array into String

Visit https://www.arduino.cc/en/Reference/StringConstructor to solve the problem easily.

This worked for me:

char yyy[6];

String xxx;

yyy[0]='h';

yyy[1]='e';

yyy[2]='l';

yyy[3]='l';

yyy[4]='o';

yyy[5]='\0';

xxx=String(yyy);

Ternary operator ?: vs if...else

No, they are converted to exactly the same executable code.

Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html

The correct way to use LOCK TABLES and UNLOCK TABLES with transactional tables, such as InnoDB tables, is to begin a transaction with SET autocommit = 0 (not START TRANSACTION) followed by LOCK TABLES, and to not call UNLOCK TABLES until you commit the transaction explicitly. For example, if you need to write to table t1 and read from table t2, you can do this:

SET autocommit=0;
LOCK TABLES t1 WRITE, t2 READ, ...;... do something with tables t1 and t2 here ...
COMMIT;
UNLOCK TABLES;

How to display hexadecimal numbers in C?

You can use the following snippet code:

#include<stdio.h>
int main(int argc, char *argv[]){
    unsigned int i;
    printf("decimal  hexadecimal\n");
    for (i = 0; i <= 256; i+=16)
        printf("%04d     0x%04X\n", i, i);
    return 0;
}

It prints both decimal and hexadecimal numbers in 4 places with zero padding.

Regex to match string containing two names in any order

The expression in this answer does that for one jack and one james in any order.

Here, we'd explore other scenarios.

METHOD 1: One jack and One james

Just in case, two jack or two james would not be allowed, only one jack and one james would be valid, we can likely design an expression similar to:

^(?!.*\bjack\b.*\bjack\b)(?!.*\bjames\b.*\bjames\b)(?=.*\bjames\b)(?=.*\bjack\b).*$

Here, we would exclude those instances using these statements:

(?!.*\bjack\b.*\bjack\b)

and,

(?!.*\bjames\b.*\bjames\b)

RegEx Demo 1

We can also simplify that to:

^(?!.*\bjack\b.*\bjack\b|.*\bjames\b.*\bjames\b)(?=.*\bjames\b|.*\bjack\b).*$

RegEx Demo 2


If you wish to simplify/update/explore the expression, it's been explained on the top right panel of regex101.com. You can watch the matching steps or modify them in this debugger link, if you'd be interested. The debugger demonstrates that how a RegEx engine might step by step consume some sample input strings and would perform the matching process.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Test

_x000D_
_x000D_
const regex = /^(?!.*\bjack\b.*\bjack\b|.*\bjames\b.*\bjames\b)(?=.*\bjames\b|.*\bjack\b).*$/gm;
const str = `hi jack here is james
hi james here is jack
hi james jack here is jack james
hi jack james here is james jack
hi jack jack here is jack james
hi james james here is james jack
hi jack jack jack here is james
`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}
_x000D_
_x000D_
_x000D_


METHOD 2: One jack and One james in a specific order

The expression can be also designed for first a james then a jack, similar to the following one:

^(?!.*\bjack\b.*\bjack\b|.*\bjames\b.*\bjames\b)(?=.*\bjames\b.*\bjack\b).*$

RegEx Demo 3

and vice versa:

^(?!.*\bjack\b.*\bjack\b|.*\bjames\b.*\bjames\b)(?=.*\bjack\b.*\bjames\b).*$

RegEx Demo 4

Event listener for when element becomes visible?

Javascript events deal with User Interaction, if your code is organised enough you should be able to call the initialising function in the same place where the visibility changes (i.e. you shouldn't change myElement.style.display on many places, instead, call a function/method that does this and anything else you might want).

MySQL Event Scheduler on a specific time everyday

CREATE EVENT test_event_03
ON SCHEDULE EVERY 1 MINUTE
STARTS CURRENT_TIMESTAMP
ENDS CURRENT_TIMESTAMP + INTERVAL 1 HOUR
DO
   INSERT INTO messages(message,created_at)
   VALUES('Test MySQL recurring Event',NOW());

ERROR: Sonar server 'http://localhost:9000' can not be reached

For me the issue was that the maven sonar plugin was using proxy servers defined in the maven settings.xml. I was trying to access the sonarque on another (not localhost alias) and so it was trying to use the proxy server to access it. Just added my alias to nonProxyHosts in settings.xml and it is working now. I did not face this issue in maven sonar plugin 3.2, only after i upgraded it.

<proxy>
  <id>proxy_id</id>
  <active>true</active>
  <protocol>http</protocol>
  <host>your-proxy-host/host>
  <port>your-proxy-host</port>
  <nonProxyHosts>localhost|127.0.*|other-non-proxy-hosts</nonProxyHosts>
</proxy>enter code here

How to Correctly handle Weak Self in Swift Blocks with Arguments

**EDITED for Swift 4.2:

As @Koen commented, swift 4.2 allows:

guard let self = self else {
   return // Could not get a strong reference for self :`(
}

// Now self is a strong reference
self.doSomething()

P.S.: Since I am having some up-votes, I would like to recommend the reading about escaping closures.

EDITED: As @tim-vermeulen has commented, Chris Lattner said on Fri Jan 22 19:51:29 CST 2016, this trick should not be used on self, so please don't use it. Check the non escaping closures info and the capture list answer from @gbk.**

For those who use [weak self] in capture list, note that self could be nil, so the first thing I do is check that with a guard statement

guard let `self` = self else {
   return
}
self.doSomething()

If you are wondering what the quote marks are around self is a pro trick to use self inside the closure without needing to change the name to this, weakSelf or whatever.

port forwarding in windows

nginx is useful for forwarding HTTP on many platforms including Windows. It's easy to setup and extend with more advanced configuration. A basic configuration could look something like this:

events {}

http {
     server {

        listen 192.168.1.111:4422;

        location / {
            proxy_pass http://192.168.2.33:80/;
        }
     }
}

"VT-x is not available" when I start my Virtual machine

You might try reducing your base memory under settings to around 3175MB and reduce your cores to 1. That should work given that your BIOS is set for virtualization. Use the f12 key, security, virtualization to make sure that it is enabled. If it doesn't say VT-x that is ok, it should say VT-d or the like.

Calling Oracle stored procedure from C#?

Connecting to Oracle is ugly. Here is some cleaner code with a using statement. A lot of the other samples don't call the IDisposable Methods on the objects they create.

using (OracleConnection connection = new OracleConnection("ConnectionString"))
    using (OracleCommand command = new OracleCommand("ProcName", connection))             
    {
          command.CommandType = CommandType.StoredProcedure;
          command.Parameters.Add("ParameterName", OracleDbType.Varchar2).Value = "Your Data Here";
          command.Parameters.Add("SomeOutVar", OracleDbType.Varchar2, 120);
          command.Parameters["return_out"].Direction = ParameterDirection.Output;
          command.Parameters.Add("SomeOutVar1", OracleDbType.Varchar2, 120);
          command.Parameters["return_out2"].Direction = ParameterDirection.Output;
          connection.Open();
          command.ExecuteNonQuery();
          string SomeOutVar = command.Parameters["SomeOutVar"].Value.ToString();
          string SomeOutVar1 = command.Parameters["SomeOutVar1"].Value.ToString();
    }

Difference between List, List<?>, List<T>, List<E>, and List<Object>

1) Correct

2) You can think of that one as "read only" list, where you don't care about the type of the items.Could e.g. be used by a method that is returning the length of the list.

3) T, E and U are the same, but people tend to use e.g. T for type, E for Element, V for value and K for key. The method that compiles says that it took an array of a certain type, and returns an array of the same type.

4) You can't mix oranges and apples. You would be able to add an Object to your String list if you could pass a string list to a method that expects object lists. (And not all objects are strings)

How to get script of SQL Server data?

Check out SSMS Tool Pack. It works in Management Studio 2005 and 2008. There is an option to generate insert statements which I've found helpful moving small amounts of data from one system to another.

With this option you will have to script out the DDL separately.

Is there a simple way to convert C++ enum to string?

This question is a duplicate of,

However, in none of the questions, I could find good answers.

After delving into the topic, I found two great open source solutions:

wise_enum

  • Standalone smart enum library for C++11/14/17. It supports all of the standard functionality that you would expect from a smart enum class in C++.
  • Limitations: requires at least C++11.

Better Enums

  • Reflective compile-time enum library with clean syntax, in a single header file, and without dependencies.
  • Limitations: based on macros, can't be used inside a class.

Note: I am repeating the recommendation here. This question has a lot of traffic/views and really requires listing the solutions above.

Why use Select Top 100 Percent?

It was used for "intermediate materialization (Google search)"

Good article: Adam Machanic: Exploring the secrets of intermediate materialization

He even raised an MS Connect so it can be done in a cleaner fashion

My view is "not inherently bad", but don't use it unless 100% sure. The problem is, it works only at the time you do it and probably not later (patch level, schema, index, row counts etc)...

Worked example

This may fail because you don't know in which order things are evaluated

SELECT foo From MyTable WHERE ISNUMERIC (foo) = 1 AND CAST(foo AS int) > 100

And this may also fail because

SELECT foo
FROM
    (SELECT foo From MyTable WHERE ISNUMERIC (foo) = 1) bar
WHERE
    CAST(foo AS int) > 100

However, this did not in SQL Server 2000. The inner query is evaluated and spooled:

SELECT foo
FROM
    (SELECT TOP 100 PERCENT foo From MyTable WHERE ISNUMERIC (foo) = 1 ORDER BY foo) bar
WHERE
    CAST(foo AS int) > 100

Note, this still works in SQL Server 2005

SELECT TOP 2000000000 ... ORDER BY...

Bootstrap - Uncaught TypeError: Cannot read property 'fn' of undefined

My way is importing the jquery library.

<script
  src="https://code.jquery.com/jquery-3.3.1.js"
  integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
  crossorigin="anonymous"></script>

What does it mean when the size of a VARCHAR2 in Oracle is declared as 1 byte?

it means ONLY one byte will be allocated per character - so if you're using multi-byte charsets, your 1 character won't fit

if you know you have to have at least room enough for 1 character, don't use the BYTE syntax unless you know exactly how much room you'll need to store that byte

when in doubt, use VARCHAR2(1 CHAR)

same thing answered here Difference between BYTE and CHAR in column datatypes

Also, in 12c the max for varchar2 is now 32k, not 4000. If you need more than that, use CLOB

in Oracle, don't use VARCHAR

How do I clear only a few specific objects from the workspace?

A useful way to remove a whole set of named-alike objects:

rm(list = ls()[grep("^tmp", ls())])

thereby removing all objects whose name begins with the string "tmp".

Edit: Following Gsee's comment, making use of the pattern argument:

rm(list = ls(pattern = "^tmp"))

Edit: Answering Rafael comment, one way to retain only a subset of objects is to name the data you want to retain with a specific pattern. For example if you wanted to remove all objects whose name do not start with paper you would issue the following command:

rm(list = grep("^paper", ls(), value = TRUE, invert = TRUE))

PHP create key => value pairs within a foreach

Create key value pairs on the phpsh commandline like this:

php> $keyvalues = array();
php> $keyvalues['foo'] = "bar";
php> $keyvalues['pyramid'] = "power";
php> print_r($keyvalues);
Array
(
    [foo] => bar
    [pyramid] => power
)

Get the count of key value pairs:

php> echo count($offerarray);
2

Get the keys as an array:

php> echo implode(array_keys($offerarray));
foopyramid

How to select rows for a specific date, ignoring time in SQL Server

I know it's been a while on this question, but I was just looking for the same answer and found this seems to be the simplest solution:

select * from sales where datediff(dd, salesDate, '20101111') = 0

I actually use it more to find things within the last day or two, so my version looks like this:

select * from sales where datediff(dd, salesDate, getdate()) = 0

And by changing the 0 for today to a 1 I get yesterday's transactions, 2 is the day before that, and so on. And if you want everything for the last week, just change the equals to a less-than-or-equal-to:

select * from sales where datediff(dd, salesDate, getdate()) <= 7

Angularjs - ng-cloak/ng-show elements blink

We ran into this problem at our company and solved it by adding "display: none" to the CSS styling for those flickering ng-show elements. We didn't have to use ng-cloak at all. Unlike others in this thread, we experienced this issue in Safari but not Firefox or Chrome -- possibly due to Safari's lazy repaint bug in iOS7.

getCurrentPosition() and watchPosition() are deprecated on insecure origins

I know that the geoLocation API is better but for people whom can't use an SSL, you can still use some sort of services such as geopluginService.

as specified in the documentation you simply send a request with the ip to the service url http://www.geoplugin.net/php.gp?ip=xx.xx.xx.xx the output is a serialized array so you must need to unserialize it before using it.

Remember this service is not very accurate as the geoLocation is, but it is still an easy and fast solution.

Creating a Shopping Cart using only HTML/JavaScript

For a project this size, you should stop writing pure JavaScript and turn to some of the libraries available. I'd recommend jQuery (http://jquery.com/), which allows you to select elements by css-selectors, which I recon should speed up your development quite a bit.

Example of your code then becomes;

function AddtoCart() {
  var len = $("#Items tr").length, $row, $inp1, $inp2, $cells;

  $row = $("#Items td:first").clone(true);
  $cells = $row.find("td");

  $cells.get(0).html( len );

  $inp1 = $cells.get(1).find("input:first");
  $inp1.attr("id", $inp1.attr("id") + len).val("");

  $inp2 = $cells.get(2).find("input:first");
  $inp2.attr("id", $inp2.attr("id") + len).val("");

  $("#Items").append($row);
    }

I can see that you might not understand that code yet, but take a look at jQuery, it's easy to learn and will make this development way faster.

I would use the libraries already created specifically for js shopping carts if I were you though.

To your problem; If i look at your jsFiddle, it doesn't even seem like you have defined a table with the id Items? Maybe that's why it doesn't work?

How do I get the current date and current time only respectively in Django?

For the date, you can use datetime.date.today() or datetime.datetime.now().date().

For the time, you can use datetime.datetime.now().time().


However, why have separate fields for these in the first place? Why not use a single DateTimeField?

You can always define helper functions on the model that return the .date() or .time() later if you only want one or the other.

How do I format a date with Dart?

You can use the intl package (installer) to format dates.

For en_US formats, it's quite simple:

import 'package:intl/intl.dart';

main() {
  final DateTime now = DateTime.now();
  final DateFormat formatter = DateFormat('yyyy-MM-dd');
  final String formatted = formatter.format(now);
  print(formatted); // something like 2013-04-20
}

There are many options for formatting. From the docs:

ICU Name                   Skeleton
--------                   --------
DAY                          d
ABBR_WEEKDAY                 E
WEEKDAY                      EEEE
ABBR_STANDALONE_MONTH        LLL
STANDALONE_MONTH             LLLL
NUM_MONTH                    M
NUM_MONTH_DAY                Md
NUM_MONTH_WEEKDAY_DAY        MEd
ABBR_MONTH                   MMM
ABBR_MONTH_DAY               MMMd
ABBR_MONTH_WEEKDAY_DAY       MMMEd
MONTH                        MMMM
MONTH_DAY                    MMMMd
MONTH_WEEKDAY_DAY            MMMMEEEEd
ABBR_QUARTER                 QQQ
QUARTER                      QQQQ
YEAR                         y
YEAR_NUM_MONTH               yM
YEAR_NUM_MONTH_DAY           yMd
YEAR_NUM_MONTH_WEEKDAY_DAY   yMEd
YEAR_ABBR_MONTH              yMMM
YEAR_ABBR_MONTH_DAY          yMMMd
YEAR_ABBR_MONTH_WEEKDAY_DAY  yMMMEd
YEAR_MONTH                   yMMMM
YEAR_MONTH_DAY               yMMMMd
YEAR_MONTH_WEEKDAY_DAY       yMMMMEEEEd
YEAR_ABBR_QUARTER            yQQQ
YEAR_QUARTER                 yQQQQ
HOUR24                       H
HOUR24_MINUTE                Hm
HOUR24_MINUTE_SECOND         Hms
HOUR                         j
HOUR_MINUTE                  jm
HOUR_MINUTE_SECOND           jms
HOUR_MINUTE_GENERIC_TZ       jmv
HOUR_MINUTE_TZ               jmz
HOUR_GENERIC_TZ              jv
HOUR_TZ                      jz
MINUTE                       m
MINUTE_SECOND                ms
SECOND                       s

For non-en_US dates, you need to explicitly load in the locale. See the DateFormat docs for more info. The date_symbol_data_local.dart contains all of the formats for each country/language, if you would like a more in-depth look.

Use of *args and **kwargs

Just imagine you have a function but you don't want to restrict the number of parameter it takes. Example:

>>> import operator
>>> def multiply(*args):
...  return reduce(operator.mul, args)

Then you use this function like:

>>> multiply(1,2,3)
6

or

>>> numbers = [1,2,3]
>>> multiply(*numbers)
6

How to copy a file to another path?

File.Move(@"c:\filename", @"c:\filenamet\filename.txt");

Best way to incorporate Volley (or other library) into Android Studio project

As of today, there is an official Android-hosted copy of Volley available on JCenter:

compile 'com.android.volley:volley:1.0.0'

This was compiled from the AOSP volley source code.

Insert NULL value into INT column

Just use the insert query and put the NULL keyword without quotes. That will work-

INSERT INTO `myDatabase`.`myTable` (`myColumn`) VALUES (NULL);

How to do a SQL NOT NULL with a DateTime?

Just to rule out a possibility - it doesn't appear to have anything to do with the ANSI_NULLS option, because that controls comparing to NULL with the = and <> operators. IS [NOT] NULL works whether ANSI_NULLS is ON or OFF.

I've also tried this against SQL Server 2005 with isql, because ANSI_NULLS defaults to OFF when using DB-Library.

How to use clock() in C++

On Windows at least, the only practically accurate measurement mechanism is QueryPerformanceCounter (QPC). std::chrono is implemented using it (since VS2015, if you use that), but it is not accurate to the same degree as using QueryPerformanceCounter directly. In particular it's claim to report at 1 nanosecond granularity is absolutely not correct. So, if you're measuring something that takes a very short amount of time (and your case might just be such a case), then you should use QPC, or the equivalent for your OS. I came up against this when measuring cache latencies, and I jotted down some notes that you might find useful, here; https://github.com/jarlostensen/notesandcomments/blob/master/stdchronovsqcp.md

Loop over html table and get checked checkboxes (JQuery)

The following code snippet enables/disables a button depending on whether at least one checkbox on the page has been checked.
$('input[type=checkbox]').change(function () {
    $('#test > tbody  tr').each(function () {
        if ($('input[type=checkbox]').is(':checked')) {
            $('#btnexcellSelect').removeAttr('disabled');
        } else {
            $('#btnexcellSelect').attr('disabled', 'disabled');
        }
        if ($(this).is(':checked')){
            console.log( $(this).attr('id'));
         }else{
             console.log($(this).attr('id'));
         }
     });
});

Here is demo in JSFiddle.

How to push changes to github after jenkins build completes?

Once you set your Global Jenkins credentials, you can apply this step:

stage('Update GIT') {
  steps {
    script {
      catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
        withCredentials([usernamePassword(credentialsId: 'example-secure', passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
            def encodedPassword = URLEncoder.encode("$GIT_PASSWORD",'UTF-8')
            sh "git config user.email [email protected]"
            sh "git config user.name example"
            sh "git add ."
            sh "git commit -m 'Triggered Build: ${env.BUILD_NUMBER}'"
            sh "git push https://${GIT_USERNAME}:${encodedPassword}@github.com/${GIT_USERNAME}/example.git"
        }
      }
    }
  }
}

Send Email Intent

This works for me:

Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:"));
intent.putExtra(Intent.EXTRA_EMAIL  , new String[] { "[email protected]" });
intent.putExtra(Intent.EXTRA_SUBJECT, "My subject");

startActivity(Intent.createChooser(intent, "Email via..."));

i.e. use the ACTION_SENDTO action rather than the ACTION_SEND action. I've tried it on a couple of Android 4.4 devices and it limits the chooser pop-up to only display email applications (Email, Gmail, Yahoo Mail etc) and it correctly inserts the email address and subject into the email.

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

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

should work.

From the manual:

auth_type = 'cookie' prompts for a MySQL username and password in a friendly HTML form. This is also the only way by which one can log in to an arbitrary server (if $cfg['AllowArbitraryServer'] is enabled). Cookie is good for most installations (default in pma 3.1+), it provides security over config and allows multiple users to use the same phpMyAdmin installation. For IIS users, cookie is often easier to configure than http.

Visual studio code CSS indentation and formatting

Go to Files menu -> Preference -> Extentions Then type CSS Formatter wait for it to load and click install

Update row values where certain condition is met in pandas

I think you can use loc if you need update two columns to same value:

df1.loc[df1['stream'] == 2, ['feat','another_feat']] = 'aaaa'
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2        aaaa         aaaa
c       2        aaaa         aaaa
d       3  some_value   some_value

If you need update separate, one option is use:

df1.loc[df1['stream'] == 2, 'feat'] = 10
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2          10   some_value
c       2          10   some_value
d       3  some_value   some_value

Another common option is use numpy.where:

df1['feat'] = np.where(df1['stream'] == 2, 10,20)
print df1
   stream  feat another_feat
a       1    20   some_value
b       2    10   some_value
c       2    10   some_value
d       3    20   some_value

EDIT: If you need divide all columns without stream where condition is True, use:

print df1
   stream  feat  another_feat
a       1     4             5
b       2     4             5
c       2     2             9
d       3     1             7

#filter columns all without stream
cols = [col for col in df1.columns if col != 'stream']
print cols
['feat', 'another_feat']

df1.loc[df1['stream'] == 2, cols ] = df1 / 2
print df1
   stream  feat  another_feat
a       1   4.0           5.0
b       2   2.0           2.5
c       2   1.0           4.5
d       3   1.0           7.0

If working with multiple conditions is possible use multiple numpy.where or numpy.select:

df0 = pd.DataFrame({'Col':[5,0,-6]})

df0['New Col1'] = np.where((df0['Col'] > 0), 'Increasing', 
                          np.where((df0['Col'] < 0), 'Decreasing', 'No Change'))

df0['New Col2'] = np.select([df0['Col'] > 0, df0['Col'] < 0],
                            ['Increasing',  'Decreasing'], 
                            default='No Change')

print (df0)
   Col    New Col1    New Col2
0    5  Increasing  Increasing
1    0   No Change   No Change
2   -6  Decreasing  Decreasing

how to add script inside a php code?

One way to avoid accidentally including the same script twice is to implement a script management module in your templating system. The typical way to include a script is to use the SCRIPT tag in your HTML page.

  <script type="text/javascript" src="menu_1.0.17.js"></script>

An alternative in PHP would be to create a function called insertScript.

  <?php insertScript("menu.js") ?>

What's the difference between Instant and LocalDateTime?

You are wrong about LocalDateTime: it does not store any time-zone information and it has nanosecond precision. Quoting the Javadoc (emphasis mine):

A date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30.

LocalDateTime is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second. Other date and time fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. Time is represented to nanosecond precision. For example, the value "2nd October 2007 at 13:45.30.123456789" can be stored in a LocalDateTime.

The difference between the two is that Instant represents an offset from the Epoch (01-01-1970) and, as such, represents a particular instant on the time-line. Two Instant objects created at the same moment in two different places of the Earth will have exactly the same value.

WCFTestClient The HTTP request is unauthorized with client authentication scheme 'Anonymous'

Here's what I had to do to get this working. This means:

  1. Custom UserNamePasswordValidator (no need for a Windows account, SQLServer or ActiveDirectory -- your UserNamePasswordValidator could have username & password hardcoded, or read it from a text file, MySQL or whatever).
  2. https
  3. IIS7
  4. .net 4.0

My site is managed through DotNetPanel. It has 3 security options for virtual directories:

  1. Allow Anonymous Access
  2. Enable Basic Authentication
  3. Enable Integrated Windows Authentication

Only "Allow Anonymous Access" is needed (although, that, by itself wasn't enough).

Setting

proxy.ClientCredentials.Windows.AllowedImpersonationLevel =  System.Security.Principal.TokenImpersonationLevel.Impersonation;

Didn't make a difference in my case.

However, using this binding worked:

      <security mode="TransportWithMessageCredential">
        <transport clientCredentialType="Windows" />
        <message clientCredentialType="UserName" />
      </security>        

Apply global variable to Vuejs

If the global variable should not be written to by anything, including Vuejs, you can use Object.freeze to freeze your object. Adding it to Vue's viewmodel won't unfreeze it. Another option is to provide Vuejs with a frozen copy of the object, if the object is intended to be written globally but just not by Vue: var frozenCopy = Object.freeze(Object.assign({}, globalObject))

CreateProcess: No such file or directory

So this is a stupid error message because it doesn't tell you what file it can't find.

Run the command again with the verbose flag gcc -v to see what gcc is up to.

In my case, it happened it was trying to call cc1plus. I checked, I don't have that. Installed mingw's C++ compiler and then I did.

How to debug Angular JavaScript Code

You can debug using browsers built in developer tools.

  1. open developer tools in browser and go to source tab.

  2. open the file do you want to debug using Ctrl+P and search file name

  3. add break point on a line ny clicking on left side of the code.

  4. refresh the page.

There are lot of plugin available for debugging you can refer for using chrome plugin Debug Angular Application using "Debugger for chrome" plugin

How to convert text column to datetime in SQL

In SQL Server , cast text as datetime

select cast('5/21/2013 9:45:48' as datetime)

Why does .json() return a promise?

Why does response.json return a promise?

Because you receive the response as soon as all headers have arrived. Calling .json() gets you another promise for the body of the http response that is yet to be loaded. See also Why is the response object from JavaScript fetch API a promise?.

Why do I get the value if I return the promise from the then handler?

Because that's how promises work. The ability to return promises from the callback and get them adopted is their most relevant feature, it makes them chainable without nesting.

You can use

fetch(url).then(response => 
    response.json().then(data => ({
        data: data,
        status: response.status
    })
).then(res => {
    console.log(res.status, res.data.title)
}));

or any other of the approaches to access previous promise results in a .then() chain to get the response status after having awaited the json body.

CSS3 transform: rotate; in IE9

I know this is old, but I was having this same issue, found this post, and while it didn't explain exactly what was wrong, it helped me to the right answer - so hopefully my answer helps someone else who might be having a similar problem to mine.

I had an element I wanted rotated vertical, so naturally I added the filter: for IE8 and then the -ms-transform property for IE9. What I found is that having the -ms-transform property AND the filter applied to the same element causes IE9 to render the element very poorly. My solution:

  1. If you are using the transform-origin property, add one for MS too (-ms-transform-origin: left bottom;). If you don't see your element, it could be that it's rotating on it's middle axis and thus leaving the page somehow - so double check that.

  2. Move the filter: property for IE7&8 to a separate style sheet and use an IE conditional to insert that style sheet for browsers less than IE9. This way it doesn't affect the IE9 styles and all should work fine.

  3. Make sure to use the correct DOCTYPE tag as well; if you have it wrong IE9 will not work properly.

Login failed for user 'DOMAIN\MACHINENAME$'

In my case I had Identity="ApplicationPoolIdentity" for my IIS Application Pool.

After I added IIS APPPOOL\ApplicationName user to SQL Server it works.

Swap two variables without using a temporary variable

The simple way to swap 2 numbers in just one line:

a=(a+b)-(b=a);

eg: a=1, b=2

Step 1: a=(1+2) - (b=1)

Step 2: a=3-1

=> a=2 and b=1


Efficient way is to use:

C Programming: (x ^= y), (y ^= x), (x ^= y);

Java: x = x ^ y ^ (y = x);

Python: x, y = y, x

Note: Most common mistake people make: //Swap using bitwise XOR (Wrong Solution in C/C++)

x ^= y ^= x ^= y; 

Source: GeeksforGeek

Spring - download response as a file

It is possible to download a file using XHR request. You can use angular $http to load the file and then use Blob feature of HTML5 to make browser save it. There is a library that can help you with saving: FileSaver.js.

How to set default value to all keys of a dict object in python?

You can use the following class. Just change zero to any default value you like. The solution was tested in Python 2.7.

class cDefaultDict(dict):
    # dictionary that returns zero for missing keys
    # keys with zero values are not stored

    def __missing__(self,key):
        return 0

    def __setitem__(self, key, value):
        if value==0:
            if key in self:  # returns zero anyway, so no need to store it
                del self[key]
        else:
            dict.__setitem__(self, key, value)

How to return first 5 objects of Array in Swift?

The Prefix function is definitely the most efficient way of solving this problem, but you can also use for-in loops like the following:

let array = [1,2,3,4,5,6,7,8,9]
let maxNum = 5
var iterationNumber = 0
var firstNumbers = [Int()]
if array.count > maxNum{
  for i in array{
    iterationNumber += 1
    if iterationNumber <= maxNum{
      firstNumbers.append(i)
    }
  }
  firstNumbers.remove(at: 0)
  print(firstNumbers)
} else {
  print("There were not \(maxNum) items in the array.")
}

This solution takes up many lines of code but checks to see if there are enough items in the array to carry out the program, then continues and solves the problem. This solution uses many basic functions including array.count, which returns the amount of items in the array, not the position of last item in the array. It also uses array.append, which adds things onto the end of the array. Lastly, it uses array.remove, which removes the array's item that has a specified position.

I have tested it it and it works for at least swift 5.

Understanding The Modulus Operator %

Modulus operator gives you the result in 'reduced residue system'. For example for mod 5 there are 5 integers counted: 0,1,2,3,4. In fact 19=12=5=-2=-9 (mod 7). The main difference that the answer is given by programming languages by 'reduced residue system'.

select count(*) from select

You're missing a FROM and you need to give the subquery an alias.

SELECT COUNT(*) FROM 
(
  SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
   FROM dbo.Table_A AS a 
   INNER JOIN dbo.Table_B AS b 
   ON a.a_id = b.a_id
) AS subquery;

How to escape special characters in building a JSON string?

To allow single quotes within doubule quoted string for the purpose of json, you double the single quote. {"X": "What's the question"} ==> {"X": "What''s the question"}

https://codereview.stackexchange.com/questions/69266/json-conversion-to-single-quotes

The \' sequence is invalid.

How to create duplicate table with new name in SQL Server 2008

My SQL Server Management Studio keeps asking me how I can make it better, I have an idea! The ability to highlight a table and then, ctrl C, ctrl V! would be great and the answer to this question at the same time!

SELECT FOR UPDATE with SQL Server

Recently I had a deadlock problem because Sql Server locks more then necessary (page). You can't really do anything against it. Now we are catching deadlock exceptions... and I wish I had Oracle instead.

Edit: We are using snapshot isolation meanwhile, which solves many, but not all of the problems. Unfortunately, to be able to use snapshot isolation it must be allowed by the database server, which may cause unnecessary problems at customers site. Now we are not only catching deadlock exceptions (which still can occur, of course) but also snapshot concurrency problems to repeat transactions from background processes (which cannot be repeated by the user). But this still performs much better than before.

How to convert between bytes and strings in Python 3?

TRY THIS:

StringVariable=ByteVariable.decode('UTF-8','ignore')

TO TEST TYPE:

print(type(StringVariable))

Here 'StringVariable' represented as a string. 'ByteVariable' represent as Byte. Its not relevent to question Variables..

Open terminal here in Mac OS finder

If like me you turn off the Finder toolbar, this Service adds an item to every folder's contextual menu: http://blog.leenarts.net/2009/09/03/open-service-here/

This also allows you to open any folder you see in Finder tree view.

Sql Server equivalent of a COUNTIF aggregate function

Not product-specific, but the SQL standard provides

SELECT COUNT() FILTER WHERE <condition-1>, COUNT() FILTER WHERE <condition-2>, ... FROM ...

for this purpose. Or something that closely resembles it, I don't know off the top of my hat.

And of course vendors will prefer to stick with their proprietary solutions.

Adding items to a JComboBox

create a new class called ComboKeyValue.java

    public class ComboKeyValue {
        private String key;
        private String value;
    
        public ComboKeyValue(String key, String value) {
            this.key = key;
            this.value = value;
        }
        
        @Override
        public String toString(){
            return key;
        }
    
        public String getKey() {
            return key;
        }
    
        public String getValue() {
            return value;
        }
}

when you want to add a new item, just write the code as below

 DefaultComboBoxModel model = new DefaultComboBoxModel();
    model.addElement(new ComboKeyValue("key", "value"));
    properties.setModel(model);

ActiveMQ connection refused

I encountered a similar problem when I was using the below to obtain connection factory ConnectionFactory factory = new
ActiveMQConnectionFactory("admin","admin","tcp://:61616");

Its resolved when I changed it to the below

ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://:61616");

The below then showed that my Q size was increasing.. http://:8161/admin/queues.jsp

Initializing default values in a struct

An explicit default initialization can help:

struct foo {
    bool a {};
    bool b {};
    bool c {};
 } bar;

Behavior bool a {} is same as bool b = bool(); and return false.

Compilation error: stray ‘\302’ in program etc

This problem comes when you have copied some text from html or you have done modification in windows environment and trying to compile in Unix/Solaris environment.

Please do "dos2unix" to remove the special characters from the file:

dos2unix fileName.ext fileName.ext

Why is the minidlna database not being refreshed?

There is a patch for the sourcecode of minidlna at sourceforge available that does not make a full rescan, but a kind of incremental scan. That worked fine, but with some later version, the patch is broken. See here Link to SF

Regards Gerry

Mysql SELECT CASE WHEN something then return field

You are mixing the 2 different CASE syntaxes inappropriately.

Use this style (Searched)

  CASE  
  WHEN u.nnmu ='0' THEN mu.naziv_mesta
  WHEN u.nnmu ='1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

Or this style (Simple)

  CASE u.nnmu 
  WHEN '0' THEN mu.naziv_mesta
  WHEN '1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

Not This (Simple but with boolean search predicates)

  CASE u.nnmu 
  WHEN u.nnmu ='0' THEN mu.naziv_mesta
  WHEN u.nnmu ='1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

In MySQL this will end up testing whether u.nnmu is equal to the value of the boolean expression u.nnmu ='0' itself. Regardless of whether u.nnmu is 1 or 0 the result of the case expression itself will be 1

For example if nmu = '0' then (nnmu ='0') evaluates as true (1) and (nnmu ='1') evaluates as false (0). Substituting these into the case expression gives

 SELECT CASE  '0'
  WHEN 1 THEN '0'
  WHEN 0 THEN '1'
 ELSE 'GRESKA'
 END as mesto_utovara

if nmu = '1' then (nnmu ='0') evaluates as false (0) and (nnmu ='1') evaluates as true (1). Substituting these into the case expression gives

 SELECT CASE  '1'
  WHEN 0 THEN '0'
  WHEN 1 THEN '1'
 ELSE 'GRESKA'
 END as mesto_utovara

Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

Try to find the product of numbers from 1 to 50:

Let product, P1 = 1 x 2 x 3 x ............. 50

When you take out numbers one by one, multiply them so that you get the product P2. But two numbers are missing here, hence P2 < P1.

The product of the two mising terms, a x b = P1 - P2.

You already know the sum, a + b = S1.

From the above two equations, solve for a and b through a quadratic equation. a and b are your missing numbers.

ImportError: No module named enum

Please use --user at end of this, it is working fine for me.

pip install enum34 --user

How to check if an array element exists?

You can also use array_keys for number of occurrences

<?php
$array=array('1','2','6','6','6','5');
$i=count(array_keys($array, 6));
if($i>0)
 echo "Element exists in Array";
?>

Bootstrap: Collapse other sections when one is expanded

Using data-parent, first solution is to stick to the example selector architecture

<div id="myGroup">
    <button class="btn dropdown" data-toggle="collapse" data-target="#keys" data-parent="#myGroup"><i class="icon-chevron-right"></i> Keys  <span class="badge badge-info pull-right">X</span></button>
    <button class="btn dropdown" data-toggle="collapse" data-target="#attrs" data-parent="#myGroup"><i class="icon-chevron-right"></i> Attributes</button>
    <button class="btn dropdown" data-toggle="collapse" data-target="#edit" data-parent="#myGroup"><i class="icon-chevron-right"></i> Edit Details</button>

    <div class="accordion-group">
        <div class="collapse indent" id="keys">
            keys
        </div>

        <div class="collapse indent" id="attrs">
            attrs
        </div>

        <div class="collapse" id="edit">
            edit
        </div>
    </div>
</div>

Demo (jsfiddle)

Second solution is to bind on the events and hide the other collapsible elements yourself.

var $myGroup = $('#myGroup');
$myGroup.on('show.bs.collapse','.collapse', function() {
    $myGroup.find('.collapse.in').collapse('hide');
});

Demo (jsfiddle)

PS: the strange effect in the demos is caused by the min-height set for the example, just ignore that.


Edit: changed the JS event from show to show.bs.collapse as specified in Bootstrap documentation.

Changing precision of numeric column in Oracle

If the table is compressed this will work:

alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);

update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;

update EVAPP_FEES set AMOUNT = null;

alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);

update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;

alter table EVAPP_FEES move nocompress;

alter table EVAPP_FEES drop column AMOUNT_TEMP;

alter table EVAPP_FEES compress;

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed

This is due to using obsolete mysql-connection-java version, your MySQl is updated but not your MySQL jdbc Driver, you can update your connection jar from the official site Official MySQL Connector site. Good Luck.

Press TAB and then ENTER key in Selenium WebDriver

Be sure to include the Key in the imports...

const {Builder, By, logging, until, Key} = require('selenium-webdriver');

searchInput.sendKeys(Key.ENTER) worked great for me

How large is a DWORD with 32- and 64-bit code?

It is defined as:

typedef unsigned long       DWORD;

However, according to the MSDN:

On 32-bit platforms, long is synonymous with int.

Therefore, DWORD is 32bit on a 32bit operating system. There is a separate define for a 64bit DWORD:

typdef unsigned _int64 DWORD64;

Hope that helps.

Set up a scheduled job?

Interesting new pluggable Django app: django-chronograph

You only have to add one cron entry which acts as a timer, and you have a very nice Django admin interface into the scripts to run.

.m2 , settings.xml in Ubuntu

As per Where is Maven Installed on Ubuntu it will first create your settings.xml on /usr/share/maven2/, then you can copy to your home folder as jens mentioned

$ cp /usr/share/maven3/conf/settings.xml ~/.m2/settings.xml

How do I deal with "signed/unsigned mismatch" warnings (C4018)?

Ideally, I would use a construct like this instead:

for (std::vector<your_type>::const_iterator i = things.begin(); i != things.end(); ++i)
{
  // if you ever need the distance, you may call std::distance
  // it won't cause any overhead because the compiler will likely optimize the call
  size_t distance = std::distance(things.begin(), i);
}

This a has the neat advantage that your code suddenly becomes container agnostic.

And regarding your problem, if some library you use requires you to use int where an unsigned int would better fit, their API is messy. Anyway, if you are sure that those int are always positive, you may just do:

int int_distance = static_cast<int>(distance);

Which will specify clearly your intent to the compiler: it won't bug you with warnings anymore.

How do you fix a bad merge, and replay your good commits onto a fixed merge?

Definitely, git filter-branch is the way to go.

Sadly, this will not suffice to completely remove filename.orig from your repo, as it can be still be referenced by tags, reflog entries, remotes and so on.

I recommend removing all these references as well, and then calling the garbage collector. You can use the git forget-blob script from this website to do all this in one step.

git forget-blob filename.orig

Call jQuery Ajax Request Each X Minutes

A bit late but I used jQuery ajax method. But I did not want to send a request every second if I haven't got the response back from the last request, so I did this.

function request(){
            if(response == true){
                // This makes it unable to send a new request 
                // unless you get response from last request
                response = false;
                var req = $.ajax({
                    type:"post",
                    url:"request-handler.php",
                    data:{data:"Hello World"}
                });

                req.done(function(){
                    console.log("Request successful!");

                    // This makes it able to send new request on the next interval
                    response = true;
                });
            }

            setTimeout(request(),1000);
        }

        request();

Run function in script from command line (Node JS)

Try make-runnable.

In db.js, add require('make-runnable'); to the end.

Now you can do:

node db.js init

Any further args would get passed to the init method.

Matplotlib - global legend and title aside subplots

In addition to the orbeckst answer one might also want to shift the subplots down. Here's an MWE in OOP style:

import matplotlib.pyplot as plt

fig = plt.figure()
st = fig.suptitle("suptitle", fontsize="x-large")

ax1 = fig.add_subplot(311)
ax1.plot([1,2,3])
ax1.set_title("ax1")

ax2 = fig.add_subplot(312)
ax2.plot([1,2,3])
ax2.set_title("ax2")

ax3 = fig.add_subplot(313)
ax3.plot([1,2,3])
ax3.set_title("ax3")

fig.tight_layout()

# shift subplots down:
st.set_y(0.95)
fig.subplots_adjust(top=0.85)

fig.savefig("test.png")

gives:

enter image description here

Could not resolve this reference. Could not locate the assembly

You most likely get this message when the project points to an old location of the assembly where it no longer exists. Since you were able to build it once, the assembly has already been copied into your bin\Debug / bin\Release folders so your project can still find a copy.

If you open the references node of the project in your solution explorer, there should be a yellow icon next to the reference. Remove the reference and add it again from the correct location.

If you want to know the location it was referenced from, you'd have to open the .csproj file in a text editor and look for the HintPath for that assembly - the IDE for some reason does not show this information.

Docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock

I have Jenkins running in Docker and connected Jenkins is using Docker socket from host machine Ubuntu 16.04 via volume to /var/run/docker.sock.

For me solution was:

1) Inside Docker container of Jenkins (docker exec -it jenkins bash on host machine)

usermod -a -G docker jenkins
chmod 664 /var/run/docker.sock
service jenkins restart (or systemctl restart jenkins.service)
su jenkins

2) On host machine:

sudo service docker restart

664 means - read and write(but not execute) for owner and users from group.

How to use BeginInvoke C#

Action is a Type of Delegate provided by the .NET framework. The Action points to a method with no parameters and does not return a value.

() => is lambda expression syntax. Lambda expressions are not of Type Delegate. Invoke requires Delegate so Action can be used to wrap the lambda expression and provide the expected Type to Invoke()

Invoke causes said Action to execute on the thread that created the Control's window handle. Changing threads is often necessary to avoid Exceptions. For example, if one tries to set the Rtf property on a RichTextBox when an Invoke is necessary, without first calling Invoke, then a Cross-thread operation not valid exception will be thrown. Check Control.InvokeRequired before calling Invoke.

BeginInvoke is the Asynchronous version of Invoke. Asynchronous means the thread will not block the caller as opposed to a synchronous call which is blocking.

Nginx 403 forbidden for all files

If you're using SELinux, just type:

sudo chcon -v -R --type=httpd_sys_content_t /path/to/www/

This will fix permission issue.

PHP - Get key name of array value

If you have a value and want to find the key, use array_search() like this:

$arr = array ('first' => 'a', 'second' => 'b', );
$key = array_search ('a', $arr);

$key will now contain the key for value 'a' (that is, 'first').

Binary search (bisection) in Python

Why not look at the code for bisect_left/right and adapt it to suit your purpose.

like this:

def binary_search(a, x, lo=0, hi=None):
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        midval = a[mid]
        if midval < x:
            lo = mid+1
        elif midval > x: 
            hi = mid
        else:
            return mid
    return -1

How to fix error Base table or view not found: 1146 Table laravel relationship table?

You should change/add in your PostController: (and change PostsController to PostController)

public function create()
{
    $categories = Category::all();
    return view('create',compact('categories'));
}

public function store(Request $request)
{
    $post = new Posts;
    $post->title = $request->get('title'); // CHANGE THIS
    $post->body = $request->get('body'); // CHANGE THIS
    $post->save(); // ADD THIS
    $post->categories()->attach($request->get('categories_id')); // CHANGE THIS

    return redirect()->route('posts.index'); // PS ON THIS ONE
}

PS: using route() means you have named your route as such

Route::get('example', 'ExampleController@getExample')->name('getExample');

UPDATE

The comments above are also right, change your 'Posts' Model to 'Post'

How to scroll to an element?

You could try this way:

 handleScrollToElement = e => {
    const elementTop = this.gate.offsetTop;
    window.scrollTo(0, elementTop);
 };

 render(){
  return(
      <h2 ref={elem => (this.gate = elem)}>Payment gate</h2>
 )}

Best way to check if object exists in Entity Framework?

Best way to do it

Regardless of what your object is and for what table in the database the only thing you need to have is the primary key in the object.

C# Code

var dbValue = EntityObject.Entry(obj).GetDatabaseValues();
if (dbValue == null)
{
   Don't exist
}

VB.NET Code

Dim dbValue = EntityObject.Entry(obj).GetDatabaseValues()
If dbValue Is Nothing Then
   Don't exist
End If

Python: split a list based on a condition?

Yet another solution to this problem. I needed a solution that is as fast as possible. That means only one iteration over the list and preferably O(1) for adding data to one of the resulting lists. This is very similar to the solution provided by sastanin, except much shorter:

from collections import deque

def split(iterable, function):
    dq_true = deque()
    dq_false = deque()

    # deque - the fastest way to consume an iterator and append items
    deque((
      (dq_true if function(item) else dq_false).append(item) for item in iterable
    ), maxlen=0)

    return dq_true, dq_false

Then, you can use the function in the following way:

lower, higher = split([0,1,2,3,4,5,6,7,8,9], lambda x: x < 5)

selected, other = split([0,1,2,3,4,5,6,7,8,9], lambda x: x in {0,4,9})

If you're not fine with the resulting deque object, you can easily convert it to list, set, whatever you like (for example list(lower)). The conversion is much faster, that construction of the lists directly.

This methods keeps order of the items, as well as any duplicates.

NoClassDefFoundError on Maven dependency

I was able to work around it by running mvn install:install-file with -Dpackaging=class. Then adding entry to POM as described here:

Delete entire row if cell contains the string X

I'd like to add to @MBK's answer. Although I found @MBK's answer to be very helpful in solving a similar problem, it'd be better if @MBK included a screenshot of how to filter a particular column.enter image description here

Hide div by default and show it on click with bootstrap

I realize this question is a bit dated and since it shows up on Google search for similar issue I thought I will expand a little bit more on top of @CowWarrior's answer. I was looking for somewhat similar solution, and after scouring through countless SO question/answers and Bootstrap documentations the solution was pretty simple. Again, this would be using inbuilt Bootstrap collapse class to show/hide divs and Bootstrap's "Collapse Event".

What I realized is that it is easy to do it using a Bootstrap Accordion, but most of the time even though the functionality required is "somewhat" similar to an Accordion, it's different in a way that one would want to show hide <div> based on, lets say, menu buttons on a navbar. Below is a simple solution to this. The anchor tags (<a>) could be navbar items and based on a collapse event the corresponding div will replace the existing div. It looks slightly sloppy in CodeSnippet, but it is pretty close to achieving the functionality-

All that the JavaScript does is makes all the other <div> hide using

$(".main-container.collapse").not($(this)).collapse('hide');

when the loaded <div> is displayed by checking the Collapse event shown.bs.collapse. Here's the Bootstrap documentation on Collapse Event.

Note: main-container is just a custom class.

Here it goes-

_x000D_
_x000D_
$(".main-container.collapse").on('shown.bs.collapse', function () {    _x000D_
//when a collapsed div is shown hide all other collapsible divs that are visible_x000D_
       $(".main-container.collapse").not($(this)).collapse('hide');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<a href="#Foo" class="btn btn-default" data-toggle="collapse">Toggle Foo</a>_x000D_
<a href="#Bar" class="btn btn-default" data-toggle="collapse">Toggle Bar</a>_x000D_
_x000D_
<div id="Bar" class="main-container collapse in">_x000D_
    This div (#Bar) is shown by default and can toggle_x000D_
</div>_x000D_
<div id="Foo" class="main-container collapse">_x000D_
    This div (#Foo) is hidden by default_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to send string from one activity to another?

Intents are intense.

Intents are useful for passing data around the android framework. You can communicate with your own Activities and even other processes. Check the developer guide and if you have specific questions (it's a lot to digest up front) come back.

Meaning of end='' in the statement print("\t",end='')?

See the documentation for the print function: print()

The content of end is printed after the thing you want to print. By default it contains a newline ("\n") but it can be changed to something else, like an empty string.

How do I restrict an input to only accept numbers?

Here is a Plunker handling any situation above proposition do not handle.
By using $formatters and $parsers pipeline and avoiding type="number"

And here is the explanation of problems/solutions (also available in the Plunker) :

/*
 *
 * Limit input text for floating numbers.
 * It does not display characters and can limit the Float value to X numbers of integers and X numbers of decimals.
 * min and max attributes can be added. They can be Integers as well as Floating values.
 *
 * value needed    |    directive
 * ------------------------------------
 * 55              |    max-integer="2"
 * 55.55           |    max-integer="4" decimal="2" (decimals are substracted from total length. Same logic as database NUMBER type)
 *
 *
 * Input type="number" (HTML5)
 *
 * Browser compatibility for input type="number" :
 * Chrome : - if first letter is a String : allows everything
 *          - if first letter is a Integer : allows [0-9] and "." and "e" (exponential)
 * Firefox : allows everything
 * Internet Explorer : allows everything
 *
 * Why you should not use input type="number" :
 * When using input type="number" the $parser pipeline of ngModel controller won't be able to access NaN values.
 * For example : viewValue = '1e'  -> $parsers parameter value = "".
 * This is because undefined values are not allowes by default (which can be changed, but better not do it)
 * This makes it impossible to modify the view and model value; to get the view value, pop last character, apply to the view and return to the model.
 *
 * About the ngModel controller pipelines :
 * view value -> $parsers -> model value
 * model value -> $formatters -> view value
 *
 * About the $parsers pipeline :
 * It is an array of functions executed in ascending order.
 * When used with input type="number" :
 * This array has 2 default functions, one of them transforms the datatype of the value from String to Number.
 * To be able to change the value easier (substring), it is better to have access to a String rather than a Number.
 * To access a String, the custom function added to the $parsers pipeline should be unshifted rather than pushed.
 * Unshift gives the closest access to the view.
 *
 * About the $formatters pipeline :
 * It is executed in descending order
 * When used with input type="number"
 * Default function transforms the value datatype from Number to String.
 * To access a String, push to this pipeline. (push brings the function closest to the view value)
 *
 * The flow :
 * When changing ngModel where the directive stands : (In this case only the view has to be changed. $parsers returns the changed model)
 *     -When the value do not has to be modified :
 *     $parsers -> $render();
 *     -When the value has to be modified :
 *     $parsers(view value) --(does view needs to be changed?) -> $render();
 *       |                                  |
 *       |                     $setViewValue(changedViewValue)
 *       |                                  |
 *       --<-------<---------<--------<------
 *
 * When changing ngModel where the directive does not stand :
 *     - When the value does not has to be modified :
 *       -$formatters(model value)-->-- view value
 *     -When the value has to be changed
 *       -$formatters(model vale)-->--(does the value has to be modified) -- (when loop $parsers loop is finished, return modified value)-->view value
 *                                              |
 *                                  $setViewValue(notChangedValue) giving back the non changed value allows the $parsers handle the 'bad' value
 *                                               |                  and avoids it to think the value did not changed
 *                Changed the model <----(the above $parsers loop occurs)
 *
 */

Bootstrap 4 - Inline List?

Shouldn't it be just the .list-group? See below,

<ul class="list-group">
  <li class="list-group-item active">Cras justo odio</li>
  <li class="list-group-item">Dapibus ac facilisis in</li>
  <li class="list-group-item">Morbi leo risus</li>
  <li class="list-group-item">Porta ac consectetur ac</li>
  <li class="list-group-item">Vestibulum at eros</li>
</ul>

Reference: Bootstrap 4 Basic Example of a List group

How to search a string in multiple files and return the names of files in Powershell?

Get-ChildItem -r | ? {$_.psiscontainer -eq $false} | ? {gc $_.pspath |select-string -pattern "dummy"}

This will give you the full details of all files

Get an object's class name at runtime

You need to first cast the instance to any because Function's type definition does not have a name property.

class MyClass {
  getName() {
    return (<any>this).constructor.name;
    // OR return (this as any).constructor.name;
  }
}

// From outside the class:
var className = (<any>new MyClass()).constructor.name;
// OR var className = (new MyClass() as any).constructor.name;
console.log(className); // Should output "MyClass"

// From inside the class:
var instance = new MyClass();
console.log(instance.getName()); // Should output "MyClass"

Update:

With TypeScript 2.4 (and potentially earlier) the code can be even cleaner:

class MyClass {
  getName() {
    return this.constructor.name;
  }
}

// From outside the class:
var className = (new MyClass).constructor.name;
console.log(className); // Should output "MyClass"

// From inside the class:
var instance = new MyClass();
console.log(instance.getName()); // Should output "MyClass"

Signing a Windows EXE file

This is not a direct answer to the question, but it is closely related (and useful I hope) since sooner or later a programmer will have put his hand into the wallet:

So, prices for EV signature (OV doesn't help much):

1 Year 379 euro
en.sklep.certum.pl
(seems to be for Poland users only)

1 Year $350 + ($50 hidden fee)
2 Year $600
3 Year $750
(OV: $84 per year)
www.ksoftware.net
eToken sent as USB stick. No reader needed. You actually purchase from Comodo (Sectigo). They are veeeeerrry slow.

1 Year 364 euro+19%VAT
(OV 69+VAT)
www.leaderssl.de

1 Year $499 USD
3 Year $897 USD
sectigo.com

1 Year $410 total
2 Years $760 total
3 Years $950 total
www.globalsign.com

1 Year: $600 (it was $104)
3 Year: ?
www.digicert.com

1 Year: $700
3 Years: ridiculous expensive
[symantec.com]

More prices here:
cheapsslsecurity.com CodeSigning EV
cheapsslsecurity.com SSL only!


Swift - Remove " character from string

As Martin R says, your string "Optional("5")" looks like you did something wrong.

dasblinkenlight answers you so it is fine, but for future readers, I will try to add alternative code as:

if let realString = yourOriginalString {
    text2 = realString
} else {
    text2 = ""
}

text2 in your example looks like String and it is maybe already set to "" but it looks like you have an yourOriginalString of type Optional(String) somewhere that it wasn't cast or use correctly.

I hope this can help some reader.

Javascript / Chrome - How to copy an object from the webkit inspector as code

Right click on data which you want to store

  • Firstly, Right click on data which you want to store -> select "Store as global variable" And the new temp variable appear like bellow: (temp3 variable): New temp variable appear in console
  • Second use command copy(temp_variable_name) like picture: enter image description here After that, you can paste data to anywhere you want. hope useful/

A url resource that is a dot (%2E)

It is not possible. §2.3 says that "." is an unreserved character and that "URIs that differ in the replacement of an unreserved character with its corresponding percent-encoded US-ASCII octet are equivalent". Therefore, /%2E%2E/ is the same as /../, and that will get normalized away.

(This is a combination of an answer by bobince and a comment by slowpoison.)

How should I make my VBA code compatible with 64-bit Windows?

To write for all versions of Office use a combination of the newer VBA7 and Win64 conditional Compiler Constants.

VBA7 determines if code is running in version 7 of the VB editor (VBA version shipped in Office 2010+).

Win64 determines which version (32-bit or 64-bit) of Office is running.

#If VBA7 Then
'Code is running VBA7 (2010 or later).

     #If Win64 Then
     'Code is running in 64-bit version of Microsoft Office.
     #Else
     'Code is running in 32-bit version of Microsoft Office.
     #End If

#Else
'Code is running VBA6 (2007 or earlier).

#End If

See Microsoft Support Article for more details.

Can Keras with Tensorflow backend be forced to use CPU or GPU at will?

For people working on PyCharm, and for forcing CPU, you can add the following line in the Run/Debug configuration, under Environment variables:

<OTHER_ENVIRONMENT_VARIABLES>;CUDA_VISIBLE_DEVICES=-1

Get pixel color from canvas, on mousemove

@Wayne Burkett's answer is good. If you wanted to also extract the alpha value to get an rgba color, we could do this:

var r = p[0], g = p[1], b = p[2], a = p[3] / 255;
var rgba = "rgb(" + r + "," + g + "," + b + "," + a + ")";

I divided the alpha value by 255 because the ImageData object stores it as an integer between 0 - 255, but most applications (for example, CanvasRenderingContext2D.fillRect()) require colors to be in valid CSS format, where the alpha value is between 0 and 1.

(Also remember that if you extract a transparent color and then draw it back onto the canvas, it will overlay whatever color is there previously. So if you drew the color rgba(0,0,0,0.1) over the same spot 10 times, it would be black.)

Parsing JSON object in PHP using json_decode

This appears to work:

$url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710%22';
$content = file_get_contents($url);
$json = json_decode($content, true);

foreach($json['data']['weather'] as $item) {
    print $item['date'];
    print ' - ';
    print $item['weatherDesc'][0]['value'];
    print ' - ';
    print '<img src="' . $item['weatherIconUrl'][0]['value'] . '" border="0" alt="" />';
    print '<br>';
}

If you set the second parameter of json_decode to true, you get an array, so you cant use the -> syntax. I would also suggest you install the JSONview Firefox extension, so you can view generated json documents in a nice formatted tree view similiar to how Firefox displays XML structures. This makes things a lot easier.

Byte[] to InputStream or OutputStream

You create and use byte array I/O streams as follows:

byte[] source = ...;
ByteArrayInputStream bis = new ByteArrayInputStream(source);
// read bytes from bis ...

ByteArrayOutputStream bos = new ByteArrayOutputStream();
// write bytes to bos ...
byte[] sink = bos.toByteArray();

Assuming that you are using a JDBC driver that implements the standard JDBC Blob interface (not all do), you can also connect a InputStream or OutputStream to a blob using the getBinaryStream and setBinaryStream methods1, and you can also get and set the bytes directly.

(In general, you should take appropriate steps to handle any exceptions, and close streams. However, closing bis and bos in the example above is unnecessary, since they aren't associated with any external resources; e.g. file descriptors, sockets, database connections.)

1 - The setBinaryStream method is really a getter. Go figure.

How to embed HTML into IPython output?

This seems to work for me:

from IPython.core.display import display, HTML
display(HTML('<h1>Hello, world!</h1>'))

The trick is to wrap it in "display" as well.

Source: http://python.6.x6.nabble.com/Printing-HTML-within-IPython-Notebook-IPython-specific-prettyprint-tp5016624p5016631.html

C# SQL Server - Passing a list to a stored procedure

Make a datatable with one column instead of List and add strings to the table. You can pass this datatable as structured type and perform another join with title field of your table.

Using Intent in an Android application to show another activity

b1 = (Button) findViewById(R.id.click_me);
        b1.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                Intent i = new Intent(MainActivity.this, SecondActivity.class);
                startActivity(i);

            }
        });

illegal character in path

I usualy would enter the path like this ....

FileInfo fi = new FileInfo(@"C:\Program Files (x86)\test software\myapp\demo.exe"); 

Did you register the @ at the beginning of the string? ;-)

How to create an email form that can send email using html

As many answers in this thread already suggest it is not possible to send a mail from a static HTML page without using PHP or JS. I just wanted to add that there a some great solutions which will take your HTTP Post request generated by your form and create a mail from it. Those solutions are especially useful in case you do not want to add JS or PHP to your website.

Those servers basically can be configured with a mail-server which is responsible for then sending the email. The receiver, subject, body etc. is received by the server from your HTTP(S) post and then stuffed into the mail you want to send. So technically speaking it is still not possible to send mails from your HTML form but the outcome is the same.

Some of these solutions can be bought as SaaS solution or you can host them by yourself. I'll just name a few but I'm sure there are plenty in case anyone is interested in the technology or the service itself.

How to rename JSON key

Try this:

let jsonArr = [
    {
        "_id":"5078c3a803ff4197dc81fbfb",
        "email":"[email protected]",
        "image":"some_image_url",
        "name":"Name 1"
    },
    {
        "_id":"5078c3a803ff4197dc81fbfc",
        "email":"[email protected]",
        "image":"some_image_url",
        "name":"Name 2"
    }
]

let idModified = jsonArr.map(
    obj => {
        return {
            "id" : obj._id,
            "email":obj.email,
            "image":obj.image,
            "name":obj.name
        }
    }
);
console.log(idModified);

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.

Get a specific bit from byte

Using BitArray class and making an extension method as OP suggests:

public static bool GetBit(this byte b, int bitNumber)
{
    System.Collections.BitArray ba = new BitArray(new byte[]{b});
    return ba.Get(bitNumber);
}

'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel

I wrote this method to handle UTF8 arrays and JSON problems. It works fine with array (simple and multidimensional).

/**
 * Encode array from latin1 to utf8 recursively
 * @param $dat
 * @return array|string
 */
   public static function convert_from_latin1_to_utf8_recursively($dat)
   {
      if (is_string($dat)) {
         return utf8_encode($dat);
      } elseif (is_array($dat)) {
         $ret = [];
         foreach ($dat as $i => $d) $ret[ $i ] = self::convert_from_latin1_to_utf8_recursively($d);

         return $ret;
      } elseif (is_object($dat)) {
         foreach ($dat as $i => $d) $dat->$i = self::convert_from_latin1_to_utf8_recursively($d);

         return $dat;
      } else {
         return $dat;
      }
   }
// Sample use
// Just pass your array or string and the UTF8 encode will be fixed
$data = convert_from_latin1_to_utf8_recursively($data);

Spring Boot - Handle to Hibernate SessionFactory

Another way similar to the yglodt's

In application.properties:

spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext

And in your configuration class:

@Bean
public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf) {
    return hemf.getSessionFactory();
}

Then you can autowire the SessionFactory in your services as usual:

@Autowired
private SessionFactory sessionFactory;

string in namespace std does not name a type

You need to add:

#include <string>

In your header file.

How to use table variable in a dynamic sql statement?

Using Temp table solves the problem but I ran into issues using Exec so I went with the following solution of using sp_executesql:

Create TABLE #tempJoin ( Old_ID int, New_ID int);

declare @table_name varchar(128);

declare @strSQL nvarchar(3072);

set @table_name = 'Object';

--build sql sting to execute
set @strSQL='INSERT INTO '+@table_name+' SELECT '+@columns+' FROM #tempJoin CJ
                        Inner Join '+@table_name+' sourceTbl On CJ.Old_ID = sourceTbl.Object_ID'

**exec sp_executesql @strSQL;**

How to compare oldValues and newValues on React Hooks useEffect?

Incase anybody is looking for a TypeScript version of usePrevious:

In a .tsx module:

import { useEffect, useRef } from "react";

const usePrevious = <T extends unknown>(value: T): T | undefined => {
  const ref = useRef<T>();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
};

Or in a .ts module:

import { useEffect, useRef } from "react";

const usePrevious = <T>(value: T): T | undefined => {
  const ref = useRef<T>();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
};

How can I suppress all output from a command using Bash?

Try

: $(yourcommand)

: is short for "do nothing".

$() is just your command.

if (boolean condition) in Java

boolean state = "TURNED ON";

is not a Java valid code. boolean can receive only boolean values (true or false) and "TURNED ON"is a String.

EDIT:

now you are talking about a loop and your code does not contain any. your var state is false because the boolean default value and you execute the else clause.

CSS no text wrap

Use the css property overflow . For example:

  .item{
    width : 100px;
    overflow:hidden;
  }

The overflow property can have one of many values like ( hidden , scroll , visible ) .. you can als control the overflow in one direction only using overflow-x or overflow-y.

I hope this helps.

Remove useless zero digits from decimals in PHP

You can try the following:

rtrim(number_format($coin->current_price,6),'0.')

std::thread calling method of class

Not so hard:

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

If the result of the computation is still needed, use a future instead:

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

How to create JSON object Node.js

The other answers are helpful, but the JSON in your question isn't valid. I have formatted it to make it clearer below, note the missing single quote on line 24.

  1 {
  2     'Orientation Sensor':
  3     [
  4         {
  5             sampleTime: '1450632410296',
  6             data: '76.36731:3.4651554:0.5665419'
  7         },
  8         {
  9             sampleTime: '1450632410296',
 10             data: '78.15431:0.5247617:-0.20050584'
 11         }
 12     ],
 13     'Screen Orientation Sensor':
 14     [
 15         {
 16             sampleTime: '1450632410296',
 17             data: '255.0:-1.0:0.0'
 18         }
 19     ],
 20     'MPU6500 Gyroscope sensor UnCalibrated':
 21     [
 22         {
 23             sampleTime: '1450632410296',
 24             data: '-0.05006743:-0.013848438:-0.0063915867
 25         },
 26         {
 27             sampleTime: '1450632410296',
 28             data: '-0.051132694:-0.0127831735:-0.003325345'
 29         }
 30     ]
 31 }

There are a lot of great articles on how to manipulate objects in Javascript (whether using Node JS or a browser). I suggest here is a good place to start: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

How to cancel an $http request in AngularJS?

For some reason config.timeout doesn't work for me. I used this approach:

_x000D_
_x000D_
let cancelRequest = $q.defer();_x000D_
let cancelPromise = cancelRequest.promise;_x000D_
_x000D_
let httpPromise = $http.get(...);_x000D_
_x000D_
$q.race({ cancelPromise, httpPromise })_x000D_
    .then(function (result) {_x000D_
..._x000D_
});
_x000D_
_x000D_
_x000D_

And cancelRequest.resolve() to cancel. Actually it doesn't not cancel a request but you don't get unnecessary response at least.

Hope this helps.

C# Syntax - Split String into Array by Comma, Convert To Generic List, and Reverse Order

List<string> names = "Tom,Scott,Bob".Split(',').Reverse().ToList();

This one works.

Differences between Octave and MATLAB?

There is not much which I would like to add to Rody Oldenhuis answer. I usually follow the strategy that all functions which I write should run in Matlab.

Some specific functions I test on both systems, for the following use cases:

a) octave does not need a license server - e.g. if your institution does not support local licenses. I used it once in a situation where the system I used a script on had no connection to the internet and was going to run for a very long time (in a corner in the lab) and used by many different users. Remark: that is not about the license cost, but about the technical issues related.

b) Octave supports other platforms, for example, the Rasberry Pi (http://wiki.octave.org/Rasperry_Pi) - which may come in handy.

C programming in Visual Studio

Download visual studio c++ express version 2006,2010 etc. then goto create new project and create c++ project select cmd project check empty rename cc with c extension file name

How do I work with a git repository within another repository?

The key is git submodules.

Start reading the Submodules chapter of the Git Community Book or of the Users Manual

Say you have repository PROJECT1, PROJECT2, and MEDIA...

cd /path/to/PROJECT1
git submodule add ssh://path.to.repo/MEDIA
git commit -m "Added Media submodule"

Repeat on the other repo...

Now, the cool thing is, that any time you commit changes to MEDIA, you can do this:

cd /path/to/PROJECT2/MEDIA
git pull
cd ..
git add MEDIA
git commit -m "Upgraded media to version XYZ"

This just recorded the fact that the MEDIA submodule WITHIN PROJECT2 is now at version XYZ.

It gives you 100% control over what version of MEDIA each project uses. git submodules are great, but you need to experiment and learn about them.

With great power comes the great chance to get bitten in the rump.

Escaping Double Quotes in Batch Script

For example for Unreal engine Automation tool run from batch file - this worked for me

eg: -cmdline=" -Messaging" -device=device -addcmdline="-SessionId=session -SessionOwner='owner' -SessionName='Build' -dataProviderMode=local -LogCmds='LogCommodity OFF' -execcmds='automation list; runtests tests+separated+by+T1+T2; quit' " -run

Hope this helps someone, worked for me.

How to redirect to another page using PHP

You could use ob_start(); before you send any output. This will tell to PHP to keep all the output in a buffer until the script execution ends, so you still can change the header.

Usually I don't use output buffering, for simple projects I keep all the logic on the first part of my script, then I output all HTML.

ActionController::UnknownFormat

This problem happened with me and sovled by just add

 respond_to :html, :json

to ApplicationController file

You can Check Devise issues on Github: https://github.com/plataformatec/devise/issues/2667

How to define a circle shape in an Android XML drawable file?

I couldn't draw a circle inside my ConstraintLayout for some reason, I just couldn't use any of the answers above.

What did work perfectly is a simple TextView with the text that comes out, when you press "Alt+7":

 <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#0075bc"
            android:textSize="40dp"
            android:text="•"></TextView>

Attaching a Sass/SCSS to HTML docs

You can not "attach" a SASS/SCSS file to an HTML document.

SASS/SCSS is a CSS preprocessor that runs on the server and compiles to CSS code that your browser understands.

There are client-side alternatives to SASS that can be compiled in the browser using javascript such as LESS CSS, though I advise you compile to CSS for production use.

It's as simple as adding 2 lines of code to your HTML file.

<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="less.js" type="text/javascript"></script>

Check if Nullable Guid is empty in c#

SomeProperty.HasValue I think it's what you're looking for.

EDIT : btw, you can write System.Guid? instead of Nullable<System.Guid> ;)

Why can't I make a vector of references?

As other have mentioned, you will probably end up using a vector of pointers instead.

However, you may want to consider using a ptr_vector instead!

How to get current time with jQuery

You don't need to use jQuery for this!

The native JavaScript implementation is Date.now().

Date.now() and $.now() return the same value:

Date.now(); // 1421715573651
$.now();    // 1421715573651
new Date(Date.now())   // Mon Jan 19 2015 20:02:55 GMT-0500 (Eastern Standard Time)
new Date($.now());     // Mon Jan 19 2015 20:02:55 GMT-0500 (Eastern Standard Time)

..and if you want the time formatted in hh-mm-ss:

var now = new Date(Date.now());
var formatted = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
// 20:10:58