Programs & Examples On #Cygpath

Change the location of the ~ directory in a Windows install of Git Bash

So, $HOME is what I need to modify. However I have been unable to find where this mythical $HOME variable is set so I assumed it was a Linux system version of PATH or something. Anyway...**

Answer

Adding HOME at the top of the profile file worked.

HOME="c://path/to/custom/root/".

  #THE FIX WAS ADDING THE FOLLOWING LINE TO THE TOP OF THE PROFILE FILE

  HOME="c://path/to/custom/root/"

  # below are the original contents ===========
  # To the extent possible under law, ..blah blah

  # Some resources...
  # Customizing Your Shell: http://www.dsl.org/cookbook/cookbook_5.html#SEC69
  # Consistent BackSpace and Delete Configuration:
  #   http://www.ibb.net/~anne/keyboard.html
  # The Linux Documentation Project: http://www.tldp.org/
  # The Linux Cookbook: http://www.tldp.org/LDP/linuxcookbook/html/
  # Greg's Wiki http://mywiki.wooledge.org/

  # Setup some default paths. Note that this order will allow user installed
  # software to override 'system' software.
  # Modifying these default path settings can be done in different ways.
  # To learn more about startup files, refer to your shell's man page.

  MSYS2_PATH="/usr/local/bin:/usr/bin:/bin"
  MANPATH="/usr/local/man:/usr/share/man:/usr/man:/share/man:${MANPATH}"
  INFOPATH="/usr/local/info:/usr/share/info:/usr/info:/share/info:${INFOPATH}"
  MINGW_MOUNT_POINT=
  if [ -n "$MSYSTEM" ]
  then
    case "$MSYSTEM" in
      MINGW32)
        MINGW_MOUNT_POINT=/mingw32
        PATH="${MINGW_MOUNT_POINT}/bin:${MSYS2_PATH}:${PATH}"
        PKG_CONFIG_PATH="${MINGW_MOUNT_POINT}/lib/pkgconfig:${MINGW_MOUNT_POINT}/share/pkgconfig"
        ACLOCAL_PATH="${MINGW_MOUNT_POINT}/share/aclocal:/usr/share/aclocal"
        MANPATH="${MINGW_MOUNT_POINT}/share/man:${MANPATH}"
      ;;
      MINGW64)
        MINGW_MOUNT_POINT=/mingw64
        PATH="${MINGW_MOUNT_POINT}/bin:${MSYS2_PATH}:${PATH}"
        PKG_CONFIG_PATH="${MINGW_MOUNT_POINT}/lib/pkgconfig:${MINGW_MOUNT_POINT}/share/pkgconfig"
        ACLOCAL_PATH="${MINGW_MOUNT_POINT}/share/aclocal:/usr/share/aclocal"
        MANPATH="${MINGW_MOUNT_POINT}/share/man:${MANPATH}"
      ;;
      MSYS)
        PATH="${MSYS2_PATH}:/opt/bin:${PATH}"
        PKG_CONFIG_PATH="/usr/lib/pkgconfig:/usr/share/pkgconfig:/lib/pkgconfig"
      ;;
      *)
        PATH="${MSYS2_PATH}:${PATH}"
      ;;
    esac
  else
    PATH="${MSYS2_PATH}:${PATH}"
  fi

  MAYBE_FIRST_START=false
  SYSCONFDIR="${SYSCONFDIR:=/etc}"

  # TMP and TEMP as defined in the Windows environment must be kept
  # for windows apps, even if started from msys2. However, leaving
  # them set to the default Windows temporary directory or unset
  # can have unexpected consequences for msys2 apps, so we define
  # our own to match GNU/Linux behaviour.
  ORIGINAL_TMP=$TMP
  ORIGINAL_TEMP=$TEMP
  #unset TMP TEMP
  #tmp=$(cygpath -w "$ORIGINAL_TMP" 2> /dev/null)
  #temp=$(cygpath -w "$ORIGINAL_TEMP" 2> /dev/null)
  #TMP="/tmp"
  #TEMP="/tmp"
  case "$TMP" in *\\*) TMP="$(cygpath -m "$TMP")";; esac
  case "$TEMP" in *\\*) TEMP="$(cygpath -m "$TEMP")";; esac
  test -d "$TMPDIR" || test ! -d "$TMP" || {
    TMPDIR="$TMP"
    export TMPDIR
  }


  # Define default printer
  p='/proc/registry/HKEY_CURRENT_USER/Software/Microsoft/Windows NT/CurrentVersion/Windows/Device'
  if [ -e "${p}" ] ; then
    read -r PRINTER < "${p}"
    PRINTER=${PRINTER%%,*}
  fi
  unset p

  print_flags ()
  {
    (( $1 & 0x0002 )) && echo -n "binary" || echo -n "text"
    (( $1 & 0x0010 )) && echo -n ",exec"
    (( $1 & 0x0040 )) && echo -n ",cygexec"
    (( $1 & 0x0100 )) && echo -n ",notexec"
  }

  # Shell dependent settings
  profile_d ()
  {
    local file=
    for file in $(export LC_COLLATE=C; echo /etc/profile.d/*.$1); do
      [ -e "${file}" ] && . "${file}"
    done

    if [ -n ${MINGW_MOUNT_POINT} ]; then
      for file in $(export LC_COLLATE=C; echo ${MINGW_MOUNT_POINT}/etc/profile.d/*.$1); do
        [ -e "${file}" ] && . "${file}"
      done
    fi
  }

  for postinst in $(export LC_COLLATE=C; echo /etc/post-install/*.post); do
    [ -e "${postinst}" ] && . "${postinst}"
  done

  if [ ! "x${BASH_VERSION}" = "x" ]; then
    HOSTNAME="$(/usr/bin/hostname)"
    profile_d sh
    [ -f "/etc/bash.bashrc" ] && . "/etc/bash.bashrc"
  elif [ ! "x${KSH_VERSION}" = "x" ]; then
    typeset -l HOSTNAME="$(/usr/bin/hostname)"
    profile_d sh
    PS1=$(print '\033]0;${PWD}\n\033[32m${USER}@${HOSTNAME} \033[33m${PWD/${HOME}/~}\033[0m\n$ ')
  elif [ ! "x${ZSH_VERSION}" = "x" ]; then
    HOSTNAME="$(/usr/bin/hostname)"
    profile_d zsh
    PS1='(%n@%m)[%h] %~ %% '
  elif [ ! "x${POSH_VERSION}" = "x" ]; then
    HOSTNAME="$(/usr/bin/hostname)"
    PS1="$ "
  else
    HOSTNAME="$(/usr/bin/hostname)"
    profile_d sh
    PS1="$ "
  fi

  if [ -n "$ACLOCAL_PATH" ]
  then
    export ACLOCAL_PATH
  fi

  export PATH MANPATH INFOPATH PKG_CONFIG_PATH USER TMP TEMP PRINTER HOSTNAME PS1 SHELL tmp temp
  test -n "$TERM" || export TERM=xterm-256color

  if [ "$MAYBE_FIRST_START" = "true" ]; then
    sh /usr/bin/regen-info.sh

    if [ -f "/usr/bin/update-ca-trust" ]
    then
      sh /usr/bin/update-ca-trust
    fi

    clear
    echo
    echo
    echo "###################################################################"
    echo "#                                                                 #"
    echo "#                                                                 #"
    echo "#                   C   A   U   T   I   O   N                     #"
    echo "#                                                                 #"
    echo "#                  This is first start of MSYS2.                  #"
    echo "#       You MUST restart shell to apply necessary actions.        #"
    echo "#                                                                 #"
    echo "#                                                                 #"
    echo "###################################################################"
    echo
    echo
  fi
  unset MAYBE_FIRST_START

configure: error: C compiler cannot create executables

If anyone is coming here because RVM / Ruby is creating issues (Middleman/Grunt) I've solved my issue.

PS. The answer by steroscott fixed my issue a while back...this time around not the case.

In my case rvm is trying to use a downloaded gcc via homebrew. I ran a brew uninstall of gcc (gcc46 for me) and reran the code for the ruby installation (old project old ruby v)

$ brew uninstall gcc46

$ rvm install 1.9.3

during that process of checking for requirements it automatically fetched a newer gcc for me and boom, all is working now. Oh a big note, the gcc install from the rvm command can take around 10-15 minutes without throwing out any text, it's not frozen :) Good luck

How do I increase the capacity of the Eclipse output console?

Window > Preferences, go to the Run/Debug > Console section >> "Limit console output.>>Console buffer size(characters):" (This option can be seen in Eclipse Indigo ,but it limits buffer size at 1,000,000 )

Extract the first word of a string in a SQL Server query

Try This:

Select race_id, race_description
, Case patIndex ('%[ /-]%', LTrim (race_description))
    When 0 Then LTrim (race_description)
    Else substring (LTrim (race_description), 1, patIndex ('%[ /-]%', LTrim (race_description)) - 1)
End race_abbreviation

from tbl_races

Python datetime to string without microsecond component

I found this to be the simplest way.

>>> t = datetime.datetime.now()
>>> t
datetime.datetime(2018, 11, 30, 17, 21, 26, 606191)
>>> t = str(t).split('.')
>>> t
['2018-11-30 17:21:26', '606191']
>>> t = t[0]
>>> t
'2018-11-30 17:21:26'
>>> 

Can a variable number of arguments be passed to a function?

Adding to the other excellent posts.

Sometimes you don't want to specify the number of arguments and want to use keys for them (the compiler will complain if one argument passed in a dictionary is not used in the method).

def manyArgs1(args):
  print args.a, args.b #note args.c is not used here

def manyArgs2(args):
  print args.c #note args.b and .c are not used here

class Args: pass

args = Args()
args.a = 1
args.b = 2
args.c = 3

manyArgs1(args) #outputs 1 2
manyArgs2(args) #outputs 3

Then you can do things like

myfuns = [manyArgs1, manyArgs2]
for fun in myfuns:
  fun(args)

How do I display an alert dialog on Android?

AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("This is Title");
    builder.setMessage("This is message for Alert Dialog");
    builder.setPositiveButton("Positive Button", (dialog, which) -> onBackPressed());
    builder.setNegativeButton("Negative Button", (dialog, which) -> dialog.cancel());
    builder.show();

This is a way which alike to create the Alert dialog with some line of code.

Checking if a list is empty with LINQ

List<T> li = new List<T>();
(li.First().DefaultValue.HasValue) ? string.Format("{0:yyyy/MM/dd}", sender.First().DefaultValue.Value) : string.Empty;

Verifying that a string contains only letters in C#

bool result = input.All(Char.IsLetter);

bool result = input.All(Char.IsLetterOrDigit);

bool result = input.All(c=>Char.IsLetterOrDigit(c) || c=='_');

Create Hyperlink in Slack

I am not sure if this is still bothering you but take a look at this page for slack text formatting:

https://api.slack.com/docs/message-formatting#linking_to_urls

For example using Python and the slack API:

from slackclient import SlackClient
slack_client = SlackClient(your_slack_token)
link_as_text_example = '<http://www.hyperlinkcode.com/|Hyperlink Code>'
slack_client.api_call("chat.postMessage", channel=channel_to_post, text=link_as_text_example , as_user=True)

You can also send a more advance JSON following the link: https://api.slack.com/docs/message-attachments

What's the difference between identifying and non-identifying relationships?

Do attributes migrated from parent to child help identify1 the child?

  • If yes: the identification-dependence exists, the relationship is identifying and the child entity is "weak".
  • If not: the identification-dependence doesn't exists, the relationship is non-identifying and the child entity "strong".

Note that identification-dependence implies existence-dependence, but not the other way around. Every non-NULL FK means a child cannot exist without parent, but that alone doesn't make the relationship identifying.

For more on this (and some examples), take a look at the "Identifying Relationships" section of the ERwin Methods Guide.

P.S. I realize I'm (extremely) late to the party, but I feel other answers are either not entirely accurate (defining it in terms of existence-dependence instead of identification-dependence), or somewhat meandering. Hopefully this answer provides more clarity...


1 The child's FK is a part of child's PRIMARY KEY or (non-NULL) UNIQUE constraint.

Remove duplicate values from JS array

If you don't want to include a whole library, you can use this one off to add a method that any array can use:

Array.prototype.uniq = function uniq() {
  return this.reduce(function(accum, cur) { 
    if (accum.indexOf(cur) === -1) accum.push(cur); 
    return accum; 
  }, [] );
}

["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"].uniq()

Printing 1 to 1000 without loop or conditionals

Easy as pie:

int main(int argc, char* argv[])
{
    printf(argv[0]);
}

method of execution:

printer.exe "1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;18;19;20;21;22;23;24;25;26;27;28;29;30;31;32;33;34;35;36;37;38;39;40;41;42;43;44;45;46;47;48;49;50;51;52;53;54;55;56;57;58;59;60;61;62;63;64;65;66;67;68;69;70;71;72;73;74;75;76;77;78;79;80;81;82;83;84;85;86;87;88;89;90;91;92;93;94;95;96;97;98;99;100;101;102;103;104;105;106;107;108;109;110;111;112;113;114;115;116;117;118;119;120;121;122;123;124;125;126;127;128;129;130;131;132;133;134;135;136;137;138;139;140;141;142;143;144;145;146;147;148;149;150;151;152;153;154;155;156;157;158;159;160;161;162;163;164;165;166;167;168;169;170;171;172;173;174;175;176;177;178;179;180;181;182;183;184;185;186;187;188;189;190;191;192;193;194;195;196;197;198;199;200;201;202;203;204;205;206;207;208;209;210;211;212;213;214;215;216;217;218;219;220;221;222;223;224;225;226;227;228;229;230;231;232;233;234;235;236;237;238;239;240;241;242;243;244;245;246;247;248;249;250;251;252;253;254;255;256;257;258;259;260;261;262;263;264;265;266;267;268;269;270;271;272;273;274;275;276;277;278;279;280;281;282;283;284;285;286;287;288;289;290;291;292;293;294;295;296;297;298;299;300;301;302;303;304;305;306;307;308;309;310;311;312;313;314;315;316;317;318;319;320;321;322;323;324;325;326;327;328;329;330;331;332;333;334;335;336;337;338;339;340;341;342;343;344;345;346;347;348;349;350;351;352;353;354;355;356;357;358;359;360;361;362;363;364;365;366;367;368;369;370;371;372;373;374;375;376;377;378;379;380;381;382;383;384;385;386;387;388;389;390;391;392;393;394;395;396;397;398;399;400;401;402;403;404;405;406;407;408;409;410;411;412;413;414;415;416;417;418;419;420;421;422;423;424;425;426;427;428;429;430;431;432;433;434;435;436;437;438;439;440;441;442;443;444;445;446;447;448;449;450;451;452;453;454;455;456;457;458;459;460;461;462;463;464;465;466;467;468;469;470;471;472;473;474;475;476;477;478;479;480;481;482;483;484;485;486;487;488;489;490;491;492;493;494;495;496;497;498;499;500;501;502;503;504;505;506;507;508;509;510;511;512;513;514;515;516;517;518;519;520;521;522;523;524;525;526;527;528;529;530;531;532;533;534;535;536;537;538;539;540;541;542;543;544;545;546;547;548;549;550;551;552;553;554;555;556;557;558;559;560;561;562;563;564;565;566;567;568;569;570;571;572;573;574;575;576;577;578;579;580;581;582;583;584;585;586;587;588;589;590;591;592;593;594;595;596;597;598;599;600;601;602;603;604;605;606;607;608;609;610;611;612;613;614;615;616;617;618;619;620;621;622;623;624;625;626;627;628;629;630;631;632;633;634;635;636;637;638;639;640;641;642;643;644;645;646;647;648;649;650;651;652;653;654;655;656;657;658;659;660;661;662;663;664;665;666;667;668;669;670;671;672;673;674;675;676;677;678;679;680;681;682;683;684;685;686;687;688;689;690;691;692;693;694;695;696;697;698;699;700;701;702;703;704;705;706;707;708;709;710;711;712;713;714;715;716;717;718;719;720;721;722;723;724;725;726;727;728;729;730;731;732;733;734;735;736;737;738;739;740;741;742;743;744;745;746;747;748;749;750;751;752;753;754;755;756;757;758;759;760;761;762;763;764;765;766;767;768;769;770;771;772;773;774;775;776;777;778;779;780;781;782;783;784;785;786;787;788;789;790;791;792;793;794;795;796;797;798;799;800;801;802;803;804;805;806;807;808;809;810;811;812;813;814;815;816;817;818;819;820;821;822;823;824;825;826;827;828;829;830;831;832;833;834;835;836;837;838;839;840;841;842;843;844;845;846;847;848;849;850;851;852;853;854;855;856;857;858;859;860;861;862;863;864;865;866;867;868;869;870;871;872;873;874;875;876;877;878;879;880;881;882;883;884;885;886;887;888;889;890;891;892;893;894;895;896;897;898;899;900;901;902;903;904;905;906;907;908;909;910;911;912;913;914;915;916;917;918;919;920;921;922;923;924;925;926;927;928;929;930;931;932;933;934;935;936;937;938;939;940;941;942;943;944;945;946;947;948;949;950;951;952;953;954;955;956;957;958;959;960;961;962;963;964;965;966;967;968;969;970;971;972;973;974;975;976;977;978;979;980;981;982;983;984;985;986;987;988;989;990;991;992;993;994;995;996;997;998;999;1000"

The specification does not say that the sequence must be generated inside the code :)

How to check undefined in Typescript

Adding this late answer to check for object.propertie that can help in some cases:

Using a juggling-check, you can test both null and undefined in one hit:

if (object.property == null) {

If you use a strict-check, it will only be true for values set to null and won't evaluate as true for undefined variables:

if (object.property === null) {

Typescript does NOT have a function to check if a variable is defined.

Update October 2020

You can now also use the nullish coallesing operator introduced in Typescript.

let neverNullOrUndefined = someValue ?? anotherValue;

Here, anotherValue will only be returned if someValue is null or undefined.

How to edit .csproj file

It is a built-in option .Net core and .Net standard projects

How can I get the IP address from NIC in Python?

It worked for me

 import subprocess
 my_ip = subprocess.Popen(['ifconfig eth0 | awk "/inet /" | cut -d":" -f 2 | cut -d" " -f1'], stdout=subprocess.PIPE, shell=True)
 (IP,errors) = my_ip.communicate()
 my_ip.stdout.close()
 print IP

How to change MySQL data directory?

Quick and easy to do:

# Create new directory for MySQL data
mkdir /new/dir/for/mysql

# Set ownership of new directory to match existing one
chown --reference=/var/lib/mysql /new/dir/for/mysql

# Set permissions on new directory to match existing one
chmod --reference=/var/lib/mysql /new/dir/for/mysql

# Stop MySQL before copying over files
service mysql stop

# Copy all files in default directory, to new one, retaining perms (-p)
cp -rp /var/lib/mysql/* /new/dir/for/mysql/

Edit the /etc/my.cnf file, and under [mysqld] add this line:

datadir=/new/dir/for/mysql/

If you are using CageFS (with or without CloudLinux) and want to change the MySQL directory, you MUST add the new directory to this file:

/etc/cagefs/cagefs.mp

And then run this command:

cagefsctl --remount-all

Remove directory which is not empty

I wish there was a way to do this without additional modules for something so minuscule and common, but this is the best I could come up with.

Update: Should now work on Windows (tested Windows 10), and should also work on Linux/Unix/BSD/Mac systems.

const
    execSync = require("child_process").execSync,
    fs = require("fs"),
    os = require("os");

let removeDirCmd, theDir;

removeDirCmd = os.platform() === 'win32' ? "rmdir /s /q " : "rm -rf ";

theDir = __dirname + "/../web-ui/css/";

// WARNING: Do not specify a single file as the windows rmdir command will error.
if (fs.existsSync(theDir)) {
    console.log(' removing the ' + theDir + ' directory.');
    execSync(removeDirCmd + '"' + theDir + '"', function (err) {
        console.log(err);
    });
}

Rails and PostgreSQL: Role postgres does not exist

I met this issue right on when I first install the Heroku's POSTGRES.app thing. After one morning trial and error i think this one line of code solved problem. As describe earlier, this is because postgresql does not have default role the first time it is set up. And we need to set that.

sovanlandy=# CREATE ROLE postgres LOGIN;

You must log in to your respective psql console to use this psql command.

Also noted that, if you already created the role 'postgre' but still get permission errors, you need to alter with command:

sovanlandy=# ALTER ROLE postgres LOGIN;

Hope it helps!

Detect when an HTML5 video finishes

Have a look at this Everything You Need to Know About HTML5 Video and Audio post at the Opera Dev site under the "I want to roll my own controls" section.

This is the pertinent section:

<video src="video.ogv">
     video not supported
</video>

then you can use:

<script>
    var video = document.getElementsByTagName('video')[0];

    video.onended = function(e) {
      /*Do things here!*/
    };
</script>

onended is a HTML5 standard event on all media elements, see the HTML5 media element (video/audio) events documentation.

Where is android studio building my .apk file?

YourApplication\app\build\outputs\apk

HTML colspan in CSS

You could trying using a grid system like http://960.gs/

Your code would be something like this, assuming you're using a "12 column" layout:

<div class="container_12">
<div class="grid_4">1</div><div class="grid_4">2</div><div class="grid_4">3</div>
<div class="clear"></div>
<div class="grid_12">123</div>
</div>

Turn off auto formatting in Visual Studio

Disable pretty listing. It is the option that re-formats what you are doing. I had the same discomfort with it and after doing it, my code stays how i want and it doesn't go back to previous settings.

enter image description here

How can I disable the bootstrap hover color for links?

if anyone cares i ended up with:

a {
    color: inherit;
}

Screenshot sizes for publishing android app on Google Play

You can upload up to 8 screenshots. Those screenshots must be one of the dimensions (sizes) you listed; you can have multiple screenshots of the same dimensions.

Where does flask look for image files?

for importing the image in flask you want a sub folder named static into the folder keep your img

and go into your html file and write

"Are you missing an assembly reference?" compile error - Visual Studio

Delete 'Web.Debug.config' and 'Web.Release.config' file for your solution directory,it should remove all errors

Adding placeholder text to textbox

Attached properties to the rescue:

public static class TextboxExtensions
{
    public static readonly DependencyProperty PlaceholderProperty = 
        DependencyProperty.RegisterAttached(
            "Placeholder", 
            typeof(string), 
            typeof(TextboxExtensions), 
            new PropertyMetadata(default(string), propertyChangedCallback: PlaceholderChanged)
            );

    private static void PlaceholderChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
    {
        var tb = dependencyObject as TextBox;

        if (tb == null)
            return;

        tb.LostFocus -= OnLostFocus;
        tb.GotFocus -= OnGotFocus;

        if (args.NewValue != null)
        {
            tb.GotFocus += OnGotFocus;
            tb.LostFocus += OnLostFocus;
        }

        SetPlaceholder(dependencyObject, args.NewValue as string);

        if (!tb.IsFocused)
            ShowPlaceholder(tb);
    }

    private static void OnLostFocus(object sender, RoutedEventArgs routedEventArgs)
    {
        ShowPlaceholder(sender as TextBox);
    }

    private static void OnGotFocus(object sender, RoutedEventArgs routedEventArgs)
    {
        HidePlaceholder(sender as TextBox);
    }

    [AttachedPropertyBrowsableForType(typeof(TextBox))]
    public static void SetPlaceholder(DependencyObject element, string value)
    {
        element.SetValue(PlaceholderProperty, value);
    }

    [AttachedPropertyBrowsableForType(typeof(TextBox))]
    public static string GetPlaceholder(DependencyObject element)
    {
        return (string)element.GetValue(PlaceholderProperty);
    }

    private static void ShowPlaceholder(TextBox textBox)
    {
        if (string.IsNullOrWhiteSpace(textBox.Text))
        {
            textBox.Text = GetPlaceholder(textBox);
        }
    }

    private static void HidePlaceholder(TextBox textBox)
    {
        string placeholderText = GetPlaceholder(textBox);

        if (textBox.Text == placeholderText)
            textBox.Text = string.Empty;
    }
}

Usage:

<TextBox Text="hi" local:TextboxExtensions.Placeholder="Hello there"></TextBox>

PHP Sort a multidimensional array by element containing date

For 'd/m/Y' dates:

usort($array, function ($a, $b, $i = 'datetime') { 
    $t1 = strtotime(str_replace('/', '-', $a[$i]));
    $t2 = strtotime(str_replace('/', '-', $b[$i]));

    return $t1 > $t2;
});

where $i is the array index

SQL JOIN and different types of JOINs

I'm going to push my pet peeve: the USING keyword.

If both tables on both sides of the JOIN have their foreign keys properly named (ie, same name, not just "id) then this can be used:

SELECT ...
FROM customers JOIN orders USING (customer_id)

I find this very practical, readable, and not used often enough.

How to update fields in a model without creating a new record in django?

Sometimes it may be required to execute the update atomically that is using one update request to the database without reading it first.

Also get-set attribute-save may cause problems if such updates may be done concurrently or if you need to set the new value based on the old field value.

In such cases query expressions together with update may by useful:

TemperatureData.objects.filter(id=1).update(value=F('value') + 1)

Split List into Sublists with LINQ

System.Interactive provides Buffer() for this purpose. Some quick testing shows performance is similar to Sam's solution.

Changing Fonts Size in Matlab Plots

If anyone was wondering how to change the font sizes without messing around with the Matlab default fonts, and change every font in a figure, I found this thread where suggests this:

set(findall(fig, '-property', 'FontSize'), 'FontSize', 10, 'fontWeight', 'bold')

findall is a pretty handy command and in the case above it really finds all the children who have a 'FontSize' property: axes lables, axes titles, pushbuttons, etc.

Hope it helps.

fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected?

The first line of every source file of your project must be the following:

#include <stdafx.h>

Visit here to understand Precompiled Headers

How to calculate probability in a normal distribution given mean & standard deviation?

In case you would like to find the area between 2 values of x mean = 1; standard deviation = 2; the probability of x between [0.5,2]

import scipy.stats
scipy.stats.norm(1, 2).cdf(2) - scipy.stats.norm(1,2).cdf(0.5)

How do I iterate and modify Java Sets?

You can do what you want if you use an iterator object to go over the elements in your set. You can remove them on the go an it's ok. However removing them while in a for loop (either "standard", of the for each kind) will get you in trouble:

Set<Integer> set = new TreeSet<Integer>();
    set.add(1);
    set.add(2);
    set.add(3);

    //good way:
    Iterator<Integer> iterator = set.iterator();
    while(iterator.hasNext()) {
        Integer setElement = iterator.next();
        if(setElement==2) {
            iterator.remove();
        }
    }

    //bad way:
    for(Integer setElement:set) {
        if(setElement==2) {
            //might work or might throw exception, Java calls it indefined behaviour:
            set.remove(setElement);
        } 
    }

As per @mrgloom's comment, here are more details as to why the "bad" way described above is, well... bad :

Without getting into too much details about how Java implements this, at a high level, we can say that the "bad" way is bad because it is clearly stipulated as such in the Java docs:

https://docs.oracle.com/javase/8/docs/api/java/util/ConcurrentModificationException.html

stipulate, amongst others, that (emphasis mine):

"For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected" (...)

"Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception."

To go more into details: an object that can be used in a forEach loop needs to implement the "java.lang.Iterable" interface (javadoc here). This produces an Iterator (via the "Iterator" method found in this interface), which is instantiated on demand, and will contain internally a reference to the Iterable object from which it was created. However, when an Iterable object is used in a forEach loop, the instance of this iterator is hidden to the user (you cannot access it yourself in any way).

This, coupled with the fact that an Iterator is pretty stateful, i.e. in order to do its magic and have coherent responses for its "next" and "hasNext" methods it needs that the backing object is not changed by something else than the iterator itself while it's iterating, makes it so that it will throw an exception as soon as it detects that something changed in the backing object while it is iterating over it.

Java calls this "fail-fast" iteration: i.e. there are some actions, usually those that modify an Iterable instance (while an Iterator is iterating over it). The "fail" part of the "fail-fast" notion refers to the ability of an Iterator to detect when such "fail" actions happen. The "fast" part of the "fail-fast" (and, which in my opinion should be called "best-effort-fast"), will terminate the iteration via ConcurrentModificationException as soon as it can detect that a "fail" action has happen.

how to get all markers on google-maps-v3

For an specific cluster use: getMarkers() Gets the array of markers in the clusterer.

For all the markers in the map use: getTotalMarkers() Gets the array of markers in the clusterer.

Returning a promise in an async function in TypeScript

It's complicated.

First of all, in this code

const p = new Promise((resolve) => {
    resolve(4);
});

the type of p is inferred as Promise<{}>. There is open issue about this on typescript github, so arguably this is a bug, because obviously (for a human), p should be Promise<number>.

Then, Promise<{}> is compatible with Promise<number>, because basically the only property a promise has is then method, and then is compatible in these two promise types in accordance with typescript rules for function types compatibility. That's why there is no error in whatever1.

But the purpose of async is to pretend that you are dealing with actual values, not promises, and then you get the error in whatever2 because {} is obvioulsy not compatible with number.

So the async behavior is the same, but currently some workaround is necessary to make typescript compile it. You could simply provide explicit generic argument when creating a promise like this:

const whatever2 = async (): Promise<number> => {
    return new Promise<number>((resolve) => {
        resolve(4);
    });
};

How can I get the name of an html page in Javascript?

Try this

location.pathname.substring(location.pathname.lastIndexOf("/") + 1);

location.pathname gives the part (domain not included) of the page URL. To get only the filename you have to extract it using the substring method.

How to set the color of an icon in Angular Material?

In the component.css or app.css add Icon Color styles

.material-icons.color_green { color: #00FF00; }
.material-icons.color_white { color: #FFFFFF; }

In the component.html set the icon class

<mat-icon class="material-icons color_green">games</mat-icon>
<mat-icon class="material-icons color_white">cloud</mat-icon>

ng build

sql query distinct with Row_Number

Use this:

SELECT *, ROW_NUMBER() OVER (ORDER BY id) AS RowNum FROM
    (SELECT DISTINCT id FROM table WHERE fid = 64) Base

and put the "output" of a query as the "input" of another.

Using CTE:

; WITH Base AS (
    SELECT DISTINCT id FROM table WHERE fid = 64
)

SELECT *, ROW_NUMBER() OVER (ORDER BY id) AS RowNum FROM Base

The two queries should be equivalent.

Technically you could

SELECT DISTINCT id, ROW_NUMBER() OVER (PARTITION BY id ORDER BY id) AS RowNum 
    FROM table
    WHERE fid = 64

but if you increase the number of DISTINCT fields, you have to put all these fields in the PARTITION BY, so for example

SELECT DISTINCT id, description,
    ROW_NUMBER() OVER (PARTITION BY id, description ORDER BY id) AS RowNum 
    FROM table
    WHERE fid = 64

I even hope you comprehend that you are going against standard naming conventions here, id should probably be a primary key, so unique by definition, so a DISTINCT would be useless on it, unless you coupled the query with some JOINs/UNION ALL...

Get ID from URL with jQuery

try this javascript

Snippet for getting the parameters from URL. Use javascript to get the URL parameters either from current window location or static URL into the argument for the function call.

javascript

function getUrlParameters(parameter, staticURL, decode){

       var currLocation = (staticURL.length)? staticURL : window.location.search,
           parArr = currLocation.split("?")[1].split("&"),
           returnBool = true;

       for(var i = 0; i < parArr.length; i++){
            parr = parArr[i].split("=");
            if(parr[0] == parameter){
                return (decode) ? decodeURIComponent(parr[1]) : parr[1];
                returnBool = true;
            }else{
                returnBool = false;            
            }
       }

       if(!returnBool) return false;  
    }

To get the parameter “id” from above static URL, use the following:

var idParameter = getUrlParameters("id", "http://www.example.com?id=1234&auth=true", true);

or

var idParameter = getUrlParameters("id", "", true);

How can I wrap or break long text/word in a fixed width span?

You can use the CSS property word-wrap:break-word;, which will break words if they are too long for your span width.

_x000D_
_x000D_
span { _x000D_
    display:block;_x000D_
    width:150px;_x000D_
    word-wrap:break-word;_x000D_
}
_x000D_
<span>VeryLongLongLongLongLongLongLongLongLongLongLongLongExample</span>
_x000D_
_x000D_
_x000D_

Google Maps v3 - limit viewable area and zoom level

To limit the zoom on v.3+. in your map setting add default zoom level and minZoom or maxZoom (or both if required) zoom levels are 0 to 19. You must declare deafult zoom level if limitation is required. all are case sensitive!

function initialize() {
   var mapOptions = {
      maxZoom:17,
      minZoom:15,
      zoom:15,
      ....

Could not resolve Spring property placeholder

It's definitely not a problem with propeties file not being found, since in that case another exception is thrown.

Make sure that you actually have a value with key idm.url in your idm.properties.

Difference between using "chmod a+x" and "chmod 755"

Yes - different

chmod a+x will add the exec bits to the file but will not touch other bits. For example file might be still unreadable to others and group.

chmod 755 will always make the file with perms 755 no matter what initial permissions were.

This may or may not matter for your script.

Understanding the order() function

(I thought it might be helpful to lay out the ideas very simply here to summarize the good material posted by @doug, & linked by @duffymo; +1 to each,btw.)

?order tells you which element of the original vector needs to be put first, second, etc., so as to sort the original vector, whereas ?rank tell you which element has the lowest, second lowest, etc., value. For example:

> a <- c(45, 50, 10, 96)
> order(a)  
[1] 3 1 2 4  
> rank(a)  
[1] 2 3 1 4  

So order(a) is saying, 'put the third element first when you sort... ', whereas rank(a) is saying, 'the first element is the second lowest... '. (Note that they both agree on which element is lowest, etc.; they just present the information differently.) Thus we see that we can use order() to sort, but we can't use rank() that way:

> a[order(a)]  
[1] 10 45 50 96  
> sort(a)  
[1] 10 45 50 96  
> a[rank(a)]  
[1] 50 10 45 96  

In general, order() will not equal rank() unless the vector has been sorted already:

> b <- sort(a)  
> order(b)==rank(b)  
[1] TRUE TRUE TRUE TRUE  

Also, since order() is (essentially) operating over ranks of the data, you could compose them without affecting the information, but the other way around produces gibberish:

> order(rank(a))==order(a)  
[1] TRUE TRUE TRUE TRUE  
> rank(order(a))==rank(a)  
[1] FALSE FALSE FALSE  TRUE  

ReDim Preserve to a Multi-Dimensional Array in Visual Basic 6

This is more compact and respect the intial first position in array and just use the inital bound to add old value.

Public Sub ReDimPreserve(ByRef arr, ByVal size1 As Long, ByVal size2 As Long)
Dim arr2 As Variant
Dim x As Long, y As Long

'Check if it's an array first
If Not IsArray(arr) Then Exit Sub

'create new array with initial start
ReDim arr2(LBound(arr, 1) To size1, LBound(arr, 2) To size2)

'loop through first
For x = LBound(arr, 1) To UBound(arr, 1)
    For y = LBound(arr, 2) To UBound(arr, 2)
        'if its in range, then append to new array the same way
        arr2(x, y) = arr(x, y)
    Next
Next
'return byref
arr = arr2
End Sub

I call this sub with this line to resize the first dimension

ReDimPreserve arr2, UBound(arr2, 1) + 1, UBound(arr2, 2)

You can add an other test to verify if the initial size is not upper than new array. In my case it's not necessary

Print Pdf in C#

Open, import, edit, merge, convert Acrobat PDF documents with a few lines of code using the intuitive API of Ultimate PDF. By using 100% managed code written in C#, the component takes advantage of the numerous built-in features of the .NET Framework to enhance performance. Moreover, the library is CLS compliant, and it does not use any unsafe blocks for minimal permission requirements. The classes are fully documented with detailed example code which helps shorten your learning curve. If your development environment is Visual Studio, enjoy the full integration of the online documentation. Just mark or select a keyword and press F1 in your Visual Studio IDE, and the online documentation is represented instantly. A high-performance and reliable PDF library which lets you add PDF functionality to your .NET applications easily with a few lines of code.

PDF Component for NET

Change column type in pandas

pandas >= 1.0

Here's a chart that summarises some of the most important conversions in pandas.

enter image description here

Conversions to string are trivial .astype(str) and are not shown in the figure.

"Hard" versus "Soft" conversions

Note that "conversions" in this context could either refer to converting text data into their actual data type (hard conversion), or inferring more appropriate data types for data in object columns (soft conversion). To illustrate the difference, take a look at

df = pd.DataFrame({'a': ['1', '2', '3'], 'b': [4, 5, 6]}, dtype=object)
df.dtypes                                                                  

a    object
b    object
dtype: object

# Actually converts string to numeric - hard conversion
df.apply(pd.to_numeric).dtypes                                             

a    int64
b    int64
dtype: object

# Infers better data types for object data - soft conversion
df.infer_objects().dtypes                                                  

a    object  # no change
b     int64
dtype: object

# Same as infer_objects, but converts to equivalent ExtensionType
df.convert_dtypes().dtypes                                                     

How to clear jQuery validation error messages?

I just did

$('.input-validation-error').removeClass('input-validation-error');

to remove red border on the input error fields.

How to persist a property of type List<String> in JPA?

My fix for this issue was to separate the primary key with the foreign key. If you are using eclipse and made the above changes please remember to refresh the database explorer. Then recreate the entities from the tables.

How to add a downloaded .box file to Vagrant?

Try to change directory to where the .box is saved

Run vagrant box add my-box downloaded.box, this may work as it avoids absolute path (on Windows?).

What is the non-jQuery equivalent of '$(document).ready()'?

The body onLoad could be an alternative too:

<html>
<head><title>Body onLoad Exmaple</title>

<script type="text/javascript">
    function window_onload() {
        //do something
    }
</script>

</head>
<body onLoad="window_onload()">

</body>
</html>

SQL query, store result of SELECT in local variable

I came here with a similar question/problem, but I only needed a single value to be stored from the query, not an array/table of results as in the orig post. I was able to use the table method above for a single value, however I have stumbled upon an easier way to store a single value.

declare @myVal int; set @myVal = isnull((select a from table1), 0);

Make sure to default the value in the isnull statement to a valid type for your variable, in my example the value in table1 that we're storing is an int.

How to tell if a JavaScript function is defined

typeof(callback) == "function"

Can iterators be reset in Python?

This is perhaps orthogonal to the original question, but one could wrap the iterator in a function that returns the iterator.

def get_iter():
    return iterator

To reset the iterator just call the function again. This is of course trivial if the function when the said function takes no arguments.

In the case that the function requires some arguments, use functools.partial to create a closure that can be passed instead of the original iterator.

def get_iter(arg1, arg2):
   return iterator
from functools import partial
iter_clos = partial(get_iter, a1, a2)

This seems to avoid the caching that tee (n copies) or list (1 copy) would need to do

how to remove the first two columns in a file using shell (awk, sed, whatever)

Thanks for posting the question. I'd also like to add the script that helped me.

awk '{ $1=""; print $0 }' file

Visual Studio displaying errors even if projects build

Following solution worked for me

1 - Close VS

2 - Delete .vs folder

3 - Open VS

4 - Build solution

Convert byte to string in Java

You have to construct a new string out of a byte array. The first element in your byteArray should be 0x63. If you want to add any more letters, make the byteArray longer and add them to the next indices.

byte[] byteArray = new byte[1];
byteArray[0] = 0x63;

try {
    System.out.println("string " + new String(byteArray, "US-ASCII"));
} catch (UnsupportedEncodingException e) {
    // TODO: Handle exception.
    e.printStackTrace();
}

Note that specifying the encoding will eventually throw an UnsupportedEncodingException and you must handle that accordingly.

clear cache of browser by command line

You can run Rundll32.exe for IE Options control panel applet and achieve following tasks.


Deletes ALL History - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255

Deletes History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1

Deletes Cookies Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2

Deletes Temporary Internet Files Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8

Deletes Form Data Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16

Deletes Password History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32

Extracting the last n characters from a string in R

Use stri_sub function from stringi package. To get substring from the end, use negative numbers. Look below for the examples:

stri_sub("abcde",1,3)
[1] "abc"
stri_sub("abcde",1,1)
[1] "a"
stri_sub("abcde",-3,-1)
[1] "cde"

You can install this package from github: https://github.com/Rexamine/stringi

It is available on CRAN now, simply type

install.packages("stringi")

to install this package.

How to completely uninstall Android Studio from windows(v10)?

Firstly uninstall Android Studio from control panel using program and features. Later you also need to enable displaying of hidden files and folders and delete the following:

users/${yourUserName}/appData/Local/Android

Convert javascript array to string

Use join() and the separator.

Working example

_x000D_
_x000D_
var arr = ['a', 'b', 'c', 1, 2, '3'];_x000D_
_x000D_
// using toString method_x000D_
var rslt = arr.toString(); _x000D_
console.log(rslt);_x000D_
_x000D_
// using join method. With a separator '-'_x000D_
rslt = arr.join('-');_x000D_
console.log(rslt);_x000D_
_x000D_
// using join method. without a separator _x000D_
rslt = arr.join('');_x000D_
console.log(rslt);
_x000D_
_x000D_
_x000D_

"Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP

When dealing with files, a proper enctype and a POST method are required, which will trigger an undefined index notice if either are not included in the form.

The manual states the following basic syntax:

HTML

<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
    <!-- MAX_FILE_SIZE must precede the file input field -->
    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
    <!-- Name of input element determines name in $_FILES array -->
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>

PHP

<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.

$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    echo "File is valid, and was successfully uploaded.\n";
} else {
    echo "Possible file upload attack!\n";
}

echo 'Here is some more debugging info:';
print_r($_FILES);

print "</pre>";

?>

Reference:

What does "hard coded" mean?

"hard coding" means putting something into your source code. If you are not hard coding, then you do something like prompting the user for the data, or allow the user to put the data on the command line, or something like that.

So, to hard code the location of the file as being on the C: drive, you would just put the pathname of the file all together in your source code.

Here is an example.

int main()
{
    const char *filename = "C:\\myfile.txt";

    printf("Filename is: %s\n", filename);
}

The file name is "hard coded" as: C:\myfile.txt

The reason the backslash is doubled is because backslashes are special in C strings.

Moment JS start and end of given month

Don't really think there is some direct method to get the last day but you could do something like this:

var dateInst = new moment();
/**
 * adding 1 month from the present month and then subtracting 1 day, 
 * So you would get the last day of this month 
 */
dateInst.add(1, 'months').date(1).subtract(1, 'days');
/* printing the last day of this month's date */
console.log(dateInst.format('YYYY MM DD'));

Relative imports - ModuleNotFoundError: No module named x

Declare correct sys.path list before you call module:

import os, sys

#'/home/user/example/parent/child'
current_path = os.path.abspath('.')

#'/home/user/example/parent'
parent_path = os.path.dirname(current_path)

sys.path.append(parent_path)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'child.settings')

How to add LocalDB to Visual Studio 2015 Community's SQL Server Object Explorer?

I tried to install only LocalDB, which was missed in my VS 2015 installation. Followed below URL & selectively download the LocalDB (2012) installer which is only 33mb in size :)

https://www.microsoft.com/en-us/download/details.aspx?id=29062

If you are looking for the SQL Server Data Tool for Visual Studio 2015 Integration, then Please download that from :

https://msdn.microsoft.com/en-us/mt186501

How do I retrieve query parameters in Spring Boot?

I was interested in this as well and came across some examples on the Spring Boot site.

   // get with query string parameters e.g. /system/resource?id="rtze1cd2"&person="sam smith" 
// so below the first query parameter id is the variable and name is the variable
// id is shown below as a RequestParam
    @GetMapping("/system/resource")
    // this is for swagger docs
    @ApiOperation(value = "Get the resource identified by id and person")
    ResponseEntity<?> getSomeResourceWithParameters(@RequestParam String id, @RequestParam("person") String name) {

        InterestingResource resource = getMyInterestingResourc(id, name);
        logger.info("Request to get an id of "+id+" with a name of person: "+name);

        return new ResponseEntity<Object>(resource, HttpStatus.OK);
    }

See here also

Moving from one activity to another Activity in Android

It is mainly due to unregistered activity in manifest file as "NextActivity" Firstly register NextActivity in Manifest like

<activity android:name=".NextActivity">

then use the code in the where you want

Intent intent=new Intent(MainActivity.this,NextActivity.class);
startActivity(intent);

where you have to call the NextActivity..

How to use HTTP GET in PowerShell?

In PowerShell v3, have a look at the Invoke-WebRequest and Invoke-RestMethod e.g.:

$msg = Read-Host -Prompt "Enter message"
$encmsg = [System.Web.HttpUtility]::UrlEncode($msg)
Invoke-WebRequest -Uri "http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$encmsg&encoding=windows-1255"

JQuery: detect change in input field

Same functionality i recently achieved using below function.

I wanted to enable SAVE button on edit.

  1. Change event is NOT advisable as it will ONLY be fired if after editing, mouse is clicked somewhere else on the page before clicking SAVE button.
  2. Key Press doesnt handle Backspace, Delete and Paste options.
  3. Key Up handles everything including tab, Shift key.

Hence i wrote below function combining keypress, keyup (for backspace, delete) and paste event for text fields.

Hope it helps you.

function checkAnyFormFieldEdited() {
    /*
     * If any field is edited,then only it will enable Save button
     */
    $(':text').keypress(function(e) { // text written
        enableSaveBtn();
    });

    $(':text').keyup(function(e) {
        if (e.keyCode == 8 || e.keyCode == 46) { //backspace and delete key
            enableSaveBtn();
        } else { // rest ignore
            e.preventDefault();
        }
    });
    $(':text').bind('paste', function(e) { // text pasted
        enableSaveBtn();
    });

    $('select').change(function(e) { // select element changed
        enableSaveBtn();
    });

    $(':radio').change(function(e) { // radio changed
        enableSaveBtn();
    });

    $(':password').keypress(function(e) { // password written
        enableSaveBtn();
    });
    $(':password').bind('paste', function(e) { // password pasted
        enableSaveBtn();
    });


}

How to compare datetime with only date in SQL Server

DON'T be tempted to do things like this:

Select * from [User] U where convert(varchar(10),U.DateCreated, 120) = '2014-02-07'

This is a better way:

Select * from [User] U 
where U.DateCreated >= '2014-02-07' and U.DateCreated < dateadd(day,1,'2014-02-07')

see: What does the word “SARGable” really mean?

EDIT + There are 2 fundamental reasons for avoiding use of functions on data in the where clause (or in join conditions).

  1. In most cases using a function on data to filter or join removes the ability of the optimizer to access an index on that field, hence making the query slower (or more "costly")
  2. The other is, for every row of data involved there is at least one calculation being performed. That could be adding hundreds, thousands or many millions of calculations to the query so that we can compare to a single criteria like 2014-02-07. It is far more efficient to alter the criteria to suit the data instead.

"Amending the criteria to suit the data" is my way of describing "use SARGABLE predicates"


And do not use between either.

the best practice with date and time ranges is to avoid BETWEEN and to always use the form:

WHERE col >= '20120101' AND col < '20120201' This form works with all types and all precisions, regardless of whether the time part is applicable.

http://sqlmag.com/t-sql/t-sql-best-practices-part-2 (Itzik Ben-Gan)

Why .NET String is immutable?

Just to throw this in, an often forgotten view is of security, picture this scenario if strings were mutable:

string dir = "C:\SomePlainFolder";

//Kick off another thread
GetDirectoryContents(dir);

void GetDirectoryContents(string directory)
{
  if(HasAccess(directory) {
    //Here the other thread changed the string to "C:\AllYourPasswords\"
    return Contents(directory);
  }
  return null;
}

You see how it could be very, very bad if you were allowed to mutate strings once they were passed.

Java: Get first item from a collection

Functional way:

public static <T> Optional<T> findFirst(List<T> result) {
    return Optional.ofNullable(result)
            .map(List::stream)
            .flatMap(Stream::findFirst);
}

above code snippet preserve from NullPointerException and IndexOutOfBoundsException

How to get Latitude and Longitude of the mobile device in android?

Here is the class LocationFinder to find the GPS location. This class will call MyLocation, which will do the business.

LocationFinder

public class LocationFinder extends Activity {

    int increment = 4;
    MyLocation myLocation = new MyLocation();

    // private ProgressDialog dialog;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.intermediat);
        myLocation.getLocation(getApplicationContext(), locationResult);

        boolean r = myLocation.getLocation(getApplicationContext(),
            locationResult);

        startActivity(new Intent(LocationFinder.this,
        // Nearbyhotelfinder.class));
            GPSMyListView.class));
        finish();
    }

    public LocationResult locationResult = new LocationResult() {

        @Override
        public void gotLocation(Location location) {
            // TODO Auto-generated method stub
            double Longitude = location.getLongitude();
            double Latitude = location.getLatitude();

            Toast.makeText(getApplicationContext(), "Got Location",
                Toast.LENGTH_LONG).show();

            try {
                SharedPreferences locationpref = getApplication()
                    .getSharedPreferences("location", MODE_WORLD_READABLE);
                SharedPreferences.Editor prefsEditor = locationpref.edit();
                prefsEditor.putString("Longitude", Longitude + "");
                prefsEditor.putString("Latitude", Latitude + "");
                prefsEditor.commit();
                System.out.println("SHARE PREFERENCE ME PUT KAR DIYA.");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };

    // handler for the background updating

}

MyLocation

public class MyLocation {

    Timer timer1;
    LocationManager lm;
    LocationResult locationResult;
    boolean gps_enabled=false;
    boolean network_enabled=false;

    public boolean getLocation(Context context, LocationResult result)
    {
        //I use LocationResult callback class to pass location value from MyLocation to user code.
        locationResult=result;
        if(lm==null)
            lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        //exceptions will be thrown if provider is not permitted.
        try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
        try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}

        //Toast.makeText(context, gps_enabled+" "+network_enabled,     Toast.LENGTH_LONG).show();

        //don't start listeners if no provider is enabled
        if(!gps_enabled && !network_enabled)
            return false;

        if(gps_enabled)
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
        if(network_enabled)
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
        timer1=new Timer();


        timer1.schedule(new GetLastLocation(), 10000);
    //    Toast.makeText(context, " Yaha Tak AAya", Toast.LENGTH_LONG).show();
        return true;
    }

    LocationListener locationListenerGps = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerNetwork);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    LocationListener locationListenerNetwork = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerGps);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    class GetLastLocation extends TimerTask {
        @Override

        public void run() {

            //Context context = getClass().getgetApplicationContext();
             Location net_loc=null, gps_loc=null;
             if(gps_enabled)
                 gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
             if(network_enabled)
                 net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

             //if there are both values use the latest one
             if(gps_loc!=null && net_loc!=null){
                 if(gps_loc.getTime()>net_loc.getTime())
                     locationResult.gotLocation(gps_loc);
                 else
                     locationResult.gotLocation(net_loc);
                 return;
             }

             if(gps_loc!=null){
                 locationResult.gotLocation(gps_loc);
                 return;
             }
             if(net_loc!=null){
                 locationResult.gotLocation(net_loc);
                 return;
             }
             locationResult.gotLocation(null);
        }
    }

    public static abstract class LocationResult{
        public abstract void gotLocation(Location location);
    }
}

$.focus() not working

I realize this is old, but came across it today. None of the answers worked for me, what I did find that worked was setTimeout. I wanted my focus to be placed on the input filed of a modal, using the setTimeout worked. Hope this helps!

How to change value of object which is inside an array using JavaScript or jQuery?

Assuming you wanted to run a bit more complicated codes during the modification, you might reach for an if-else statement over the ternary operator approach

// original 'projects' array;
var projects = [
    {
        value: "jquery",
        label: "jQuery",
        desc: "the write less, do more, JavaScript library",
        icon: "jquery_32x32.png"
    },
    {
        value: "jquery-ui",
        label: "jQuery UI",
        desc: "the official user interface library for jQuery",
        icon: "jqueryui_32x32.png"
    },
    {
        value: "sizzlejs",
        label: "Sizzle JS",
        desc: "a pure-JavaScript CSS selector engine",
        icon: "sizzlejs_32x32.png"
    }
];
// modify original 'projects' array, and save modified array into 'projects' variable
projects = projects.map(project => {
// When there's an object where key 'value' has value 'jquery-ui'
    if (project.value == 'jquery-ui') {

// do stuff and set a new value for where object's key is 'value'
        project.value = 'updated value';

// do more stuff and also set a new value for where the object's key is 'label', etc.
        project.label = 'updated label';

// now return modified object
        return project;
    } else {
// just return object as is
        return project;
    }
});

// log modified 'projects' array
console.log(projects);

How to delete specific characters from a string in Ruby?

Here is an even shorter way of achieving this:

1) using Negative character class pattern matching

irb(main)> "((String1))"[/[^()]+/]
=> "String1"

^ - Matches anything NOT in the character class. Inside the charachter class, we have ( and )

Or with global substitution "AKA: gsub" like others have mentioned.

irb(main)> "((String1))".gsub(/[)(]/, '')
=> "String1"

Spring mvc @PathVariable

It is one of the annotation used to map/handle dynamic URIs. You can even specify a regular expression for URI dynamic parameter to accept only specific type of input.

For example, if the URL to retrieve a book using a unique number would be:

URL:http://localhost:8080/book/9783827319333

The number denoted at the last of the URL can be fetched using @PathVariable as shown:

@RequestMapping(value="/book/{ISBN}", method= RequestMethod.GET)

public String showBookDetails(@PathVariable("ISBN") String id,

Model model){

model.addAttribute("ISBN", id);

return "bookDetails";

}

In short it is just another was to extract data from HTTP requests in Spring.

How to check if a string contains a specific text

If you need to know if a word exists in a string you can use this. As it is not clear from your question if you just want to know if the variable is a string or not. Where 'word' is the word you are searching in the string.

if (strpos($a,'word') !== false) {
echo 'true';
}

or use the is_string method. Whichs returns true or false on the given variable.

<?php
$a = '';
is_string($a);
?>

In WPF, what are the differences between the x:Name and Name attributes?

x:Name and Name are referencing different namespaces.

x:name is a reference to the x namespace defined by default at the top of the Xaml file.

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Just saying Name uses the default below namespace.

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

x:Name is saying use the namespace that has the x alias. x is the default and most people leave it but you can change it to whatever you like

xmlns:foo="http://schemas.microsoft.com/winfx/2006/xaml"

so your reference would be foo:name

Define and Use Namespaces in WPF


OK lets look at this a different way. Say you drag and drop an button onto your Xaml page. You can reference this 2 ways x:name and name. All xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" and xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" are is references to multiple namespaces. Since xaml holds the Control namespace(not 100% on that) and presentation holds the FrameworkElement AND the Button class has a inheritance pattern of:

Button : ButtonBase
ButtonBase : ContentControl, ICommandSource
ContentControl : Control, IAddChild
Control : FrameworkElement
FrameworkElement : UIElement, IFrameworkInputElement, 
                    IInputElement, ISupportInitialize, IHaveResources

So as one would expect anything that inherits from FrameworkElement would have access to all its public attributes. so in the case of Button it is getting its Name attribute from FrameworkElement, at the very top of the hierarchy tree. So you can say x:Name or Name and they will both be accessing the getter/setter from the FrameworkElement.

MSDN Reference

WPF defines a CLR attribute that is consumed by XAML processors in order to map multiple CLR namespaces to a single XML namespace. The XmlnsDefinitionAttribute attribute is placed at the assembly level in the source code that produces the assembly. The WPF assembly source code uses this attribute to map the various common namespaces, such as System.Windows and System.Windows.Controls, to the http://schemas.microsoft.com/winfx/2006/xaml/presentation namespace.

So the assembly attributes will look something like:

PresentationFramework.dll - XmlnsDefinitionAttribute:

[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows")]

[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows.Data")]

[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows.Navigation")]

[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows.Shapes")]

[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows.Documents")]

[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows.Controls")]  

Python class returning value

I think you are very confused about what is occurring.

In Python, everything is an object:

  • [] (a list) is an object
  • 'abcde' (a string) is an object
  • 1 (an integer) is an object
  • MyClass() (an instance) is an object
  • MyClass (a class) is also an object
  • list (a type--much like a class) is also an object

They are all "values" in the sense that they are a thing and not a name which refers to a thing. (Variables are names which refer to values.) A value is not something different from an object in Python.

When you call a class object (like MyClass() or list()), it returns an instance of that class. (list is really a type and not a class, but I am simplifying a bit here.)

When you print an object (i.e. get a string representation of an object), that object's __str__ or __repr__ magic method is called and the returned value printed.

For example:

>>> class MyClass(object):
...     def __str__(self):
...             return "MyClass([])"
...     def __repr__(self):
...             return "I am an instance of MyClass at address "+hex(id(self))
... 
>>> m = MyClass()
>>> print m
MyClass([])
>>> m
I am an instance of MyClass at address 0x108ed5a10
>>> 

So what you are asking for, "I need that MyClass return a list, like list(), not the instance info," does not make any sense. list() returns a list instance. MyClass() returns a MyClass instance. If you want a list instance, just get a list instance. If the issue instead is what do these objects look like when you print them or look at them in the console, then create a __str__ and __repr__ method which represents them as you want them to be represented.

Update for new question about equality

Once again, __str__ and __repr__ are only for printing, and do not affect the object in any other way. Just because two objects have the same __repr__ value does not mean they are equal!

MyClass() != MyClass() because your class does not define how these would be equal, so it falls back to the default behavior (of the object type), which is that objects are only equal to themselves:

>>> m = MyClass()
>>> m1 = m
>>> m2 = m
>>> m1 == m2
True
>>> m3 = MyClass()
>>> m1 == m3
False

If you want to change this, use one of the comparison magic methods

For example, you can have an object that is equal to everything:

>>> class MyClass(object):
...     def __eq__(self, other):
...             return True
... 
>>> m1 = MyClass()
>>> m2 = MyClass()
>>> m1 == m2
True
>>> m1 == m1
True
>>> m1 == 1
True
>>> m1 == None
True
>>> m1 == []
True

I think you should do two things:

  1. Take a look at this guide to magic method use in Python.
  2. Justify why you are not subclassing list if what you want is very list-like. If subclassing is not appropriate, you can delegate to a wrapped list instance instead:

    class MyClass(object):
        def __init__(self):
            self._list = []
        def __getattr__(self, name):
            return getattr(self._list, name)
    
        # __repr__ and __str__ methods are automatically created
        # for every class, so if we want to delegate these we must
        # do so explicitly
        def __repr__(self):
            return "MyClass(%s)" % repr(self._list)
        def __str__(self):
            return "MyClass(%s)" % str(self._list)
    

    This will now act like a list without being a list (i.e., without subclassing list).

    >>> c = MyClass()
    >>> c.append(1)
    >>> c
    MyClass([1])
    

Check if element is visible on screen

Could you use jQuery, since it's cross-browser compatible?

function isOnScreen(element)
{
    var curPos = element.offset();
    var curTop = curPos.top;
    var screenHeight = $(window).height();
    return (curTop > screenHeight) ? false : true;
}

And then call the function using something like:

if(isOnScreen($('#myDivId'))) { /* Code here... */ };

Set cursor position on contentEditable <div>

After playing around I've modified eyelidlessness' answer above and made it a jQuery plugin so you can just do one of these:

var html = "The quick brown fox";
$div.html(html);

// Select at the text "quick":
$div.setContentEditableSelection(4, 5);

// Select at the beginning of the contenteditable div:
$div.setContentEditableSelection(0);

// Select at the end of the contenteditable div:
$div.setContentEditableSelection(html.length);

Excuse the long code post, but it may help someone:

$.fn.setContentEditableSelection = function(position, length) {
    if (typeof(length) == "undefined") {
        length = 0;
    }

    return this.each(function() {
        var $this = $(this);
        var editable = this;
        var selection;
        var range;

        var html = $this.html();
        html = html.substring(0, position) +
            '<a id="cursorStart"></a>' +
            html.substring(position, position + length) +
            '<a id="cursorEnd"></a>' +
            html.substring(position + length, html.length);
        console.log(html);
        $this.html(html);

        // Populates selection and range variables
        var captureSelection = function(e) {
            // Don't capture selection outside editable region
            var isOrContainsAnchor = false,
                isOrContainsFocus = false,
                sel = window.getSelection(),
                parentAnchor = sel.anchorNode,
                parentFocus = sel.focusNode;

            while (parentAnchor && parentAnchor != document.documentElement) {
                if (parentAnchor == editable) {
                    isOrContainsAnchor = true;
                }
                parentAnchor = parentAnchor.parentNode;
            }

            while (parentFocus && parentFocus != document.documentElement) {
                if (parentFocus == editable) {
                    isOrContainsFocus = true;
                }
                parentFocus = parentFocus.parentNode;
            }

            if (!isOrContainsAnchor || !isOrContainsFocus) {
                return;
            }

            selection = window.getSelection();

            // Get range (standards)
            if (selection.getRangeAt !== undefined) {
                range = selection.getRangeAt(0);

                // Get range (Safari 2)
            } else if (
                document.createRange &&
                selection.anchorNode &&
                selection.anchorOffset &&
                selection.focusNode &&
                selection.focusOffset
            ) {
                range = document.createRange();
                range.setStart(selection.anchorNode, selection.anchorOffset);
                range.setEnd(selection.focusNode, selection.focusOffset);
            } else {
                // Failure here, not handled by the rest of the script.
                // Probably IE or some older browser
            }
        };

        // Slight delay will avoid the initial selection
        // (at start or of contents depending on browser) being mistaken
        setTimeout(function() {
            var cursorStart = document.getElementById('cursorStart');
            var cursorEnd = document.getElementById('cursorEnd');

            // Don't do anything if user is creating a new selection
            if (editable.className.match(/\sselecting(\s|$)/)) {
                if (cursorStart) {
                    cursorStart.parentNode.removeChild(cursorStart);
                }
                if (cursorEnd) {
                    cursorEnd.parentNode.removeChild(cursorEnd);
                }
            } else if (cursorStart) {
                captureSelection();
                range = document.createRange();

                if (cursorEnd) {
                    range.setStartAfter(cursorStart);
                    range.setEndBefore(cursorEnd);

                    // Delete cursor markers
                    cursorStart.parentNode.removeChild(cursorStart);
                    cursorEnd.parentNode.removeChild(cursorEnd);

                    // Select range
                    selection.removeAllRanges();
                    selection.addRange(range);
                } else {
                    range.selectNode(cursorStart);

                    // Select range
                    selection.removeAllRanges();
                    selection.addRange(range);

                    // Delete cursor marker
                    document.execCommand('delete', false, null);
                }
            }

            // Register selection again
            captureSelection();
        }, 10);
    });
};

How to run a cron job on every Monday, Wednesday and Friday?

Use this command to add job

crontab -e

In this format:

0 19 * * 1,3,5 /path to your file/file.php

android : Error converting byte to dex

This problem is mainly in gradle or in misversioned libraries, including, from libraries, when both define the same class. Expand and check, imported external libraries...

You cannot have two same classes to be exported to one place, or code, therefore, dexer does not know which one should be used...

Can't open config file: /usr/local/ssl/openssl.cnf on Windows

Simply install Win64 OpenSSL v1.0.2a or Win32 OpenSSL v1.0.2a, you can download these from http://slproweb.com/products/Win32OpenSSL.html. Works out of the box, no configuration needed.

Can I force a UITableView to hide the separator between empty cells?

Swift Version

The easiest method is to set the tableFooterView property:

override func viewDidLoad() {
    super.viewDidLoad()
    // This will remove extra separators from tableview
    self.tableView.tableFooterView = UIView(frame: CGRectZero)
}

How to flatten only some dimensions of a numpy array

Take a look at numpy.reshape .

>>> arr = numpy.zeros((50,100,25))
>>> arr.shape
# (50, 100, 25)

>>> new_arr = arr.reshape(5000,25)
>>> new_arr.shape   
# (5000, 25)

# One shape dimension can be -1. 
# In this case, the value is inferred from 
# the length of the array and remaining dimensions.
>>> another_arr = arr.reshape(-1, arr.shape[-1])
>>> another_arr.shape
# (5000, 25)

Qt. get part of QString

Use the left function:

QString yourString = "This is a string";
QString leftSide = yourString.left(5);
qDebug() << leftSide; // output "This "

Also have a look at mid() if you want more control.

vi/vim editor, copy a block (not usual action)

It sounds like you want to place marks in the file.

mx places a mark named x under the cursor

y'x yanks everything between the cursor's current position and the line containing mark x.

You can use 'x to simply move the cursor to the line with your mark.

You can use `x (a back-tick) to move to the exact location of the mark.


One thing I do all the time is yank everything between the cursor and mark x into the clipboard.

You can do that like this:

"+y'x

NOTE: In some environments the clipboard buffer is represented by a * in stead of a +.


Similar questions with some good answers:

How to read/write arbitrary bits in C/C++

To read bytes use std::bitset

const int bits_in_byte = 8;

char myChar = 's';
cout << bitset<sizeof(myChar) * bits_in_byte>(myChar);

To write you need to use bit-wise operators such as & ^ | & << >>. make sure to learn what they do.

For example to have 00100100 you need to set the first bit to 1, and shift it with the << >> operators 5 times. if you want to continue writing you just continue to set the first bit and shift it. it's very much like an old typewriter: you write, and shift the paper.

For 00100100: set the first bit to 1, shift 5 times, set the first bit to 1, and shift 2 times:

const int bits_in_byte = 8;

char myChar = 0;
myChar = myChar | (0x1 << 5 | 0x1 << 2);
cout << bitset<sizeof(myChar) * bits_in_byte>(myChar);

Fixed positioning in Mobile Safari

You could try using touch-scroll, a jQuery plugin that mimics scrolling with fixed elements on mobile Safari: https://github.com/neave/touch-scroll

View an example with your iOS device at http://neave.github.com/touch-scroll/

Or an alternative is iScroll: http://cubiq.org/iscroll

Anaconda Navigator won't launch (windows 10)

You need to run the cmd prompt from the Scripts directory of Anaconda where ever you have the Anaconda parent folder installed. I happen to have in the root directory of the C drive on my Windows machine. If you are not familiar there are two ways to do that:

A) Use the key combination Win-key + R then type cmd and hit return to launch the terminal window and then type: cd C:\Anaconda\Scripts (or whatever directory path yours is).

B) Navigate using windows explorer to that Scripts directory then type cmd in the address bar of that window and hit return (that will launch the terminal already set to that directory).

Next type the follow commands waiting in between for each to complete:

activate root
conda update -n root conda
conda update --all

When complete type the following and Navigator hopefully should launch:

anaconda-navigator

ASP.NET Setting width of DataBound column in GridView

hey recently i figured it out how to set width if your gridview databound with sql dataset.first set these control RowStyle-Wrap="false" HeaderStyle-Wrap="false" and then you can set the column width as much as you like. ex : ItemStyle-Width="150px" HeaderStyle-Width="150px"

Print debugging info from stored procedure in MySQL

Option 1: Put this in your procedure to print 'comment' to stdout when it runs.

SELECT 'Comment';

Option 2: Put this in your procedure to print a variable with it to stdout:

declare myvar INT default 0;
SET myvar = 5;
SELECT concat('myvar is ', myvar);

This prints myvar is 5 to stdout when the procedure runs.

Option 3, Create a table with one text column called tmptable, and push messages to it:

declare myvar INT default 0;
SET myvar = 5;
insert into tmptable select concat('myvar is ', myvar);

You could put the above in a stored procedure, so all you would have to write is this:

CALL log(concat('the value is', myvar));

Which saves a few keystrokes.

Option 4, Log messages to file

select "penguin" as log into outfile '/tmp/result.txt';

There is very heavy restrictions on this command. You can only write the outfile to areas on disk that give the 'others' group create and write permissions. It should work saving it out to /tmp directory.

Also once you write the outfile, you can't overwrite it. This is to prevent crackers from rooting your box just because they have SQL injected your website and can run arbitrary commands in MySQL.

Chrome dev tools fails to show response even the content returned has header Content-Type:text/html; charset=UTF-8

One workaround is to use Postman with same request url, headers and payload.

It will give response for sure.

ImportError: No module named matplotlib.pyplot

If you are using Python 2, just run

sudo apt-get install python-matplotlib

The best way to get matplotlib is :

pip install matplotlib

cause the previous way may give you a old version of matplotlib

Access to the requested object is only available from the local network phpmyadmin

I newer version of xampp you may use another method first open your httpd-xampp.conf file and find the string "phpmyadmin" using ctrl+F command (Windows). and then replace this code

Alias /phpmyadmin "D:/server/phpMyAdmin/"
<Directory "D:/server/phpMyAdmin">
    AllowOverride AuthConfig
    Require local
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>

with this

Alias /phpmyadmin "D:/server/phpMyAdmin/"
<Directory "D:/server/phpMyAdmin">
    AllowOverride AuthConfig
    Require all granted
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>

Don't Forget to Restart your Xampp.

JQuery datepicker language

This is for the dutch people.

$.datepicker.regional['nl'] = {clearText: 'Effacer', clearStatus: '',
    closeText: 'sluiten', closeStatus: 'Onveranderd sluiten ',
    prevText: '<vorige', prevStatus: 'Zie de vorige maand',
    nextText: 'volgende>', nextStatus: 'Zie de volgende maand',
    currentText: 'Huidige', currentStatus: 'Bekijk de huidige maand',
    monthNames: ['januari','februari','maart','april','mei','juni',
    'juli','augustus','september','oktober','november','december'],
    monthNamesShort: ['jan','feb','mrt','apr','mei','jun',
    'jul','aug','sep','okt','nov','dec'],
    monthStatus: 'Bekijk een andere maand', yearStatus: 'Bekijk nog een jaar',
    weekHeader: 'Sm', weekStatus: '',
    dayNames: ['zondag','maandag','dinsdag','woensdag','donderdag','vrijdag','zaterdag'],
    dayNamesShort: ['zo', 'ma','di','wo','do','vr','za'],
    dayNamesMin: ['zo', 'ma','di','wo','do','vr','za'],
    dayStatus: 'Gebruik DD als de eerste dag van de week', dateStatus: 'Kies DD, MM d',
    dateFormat: 'dd/mm/yy', firstDay: 1, 
    initStatus: 'Kies een datum', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['nl']);

Best Timer for using in a Windows service

I know this thread is a little old but it came in handy for a specific scenario I had and I thought it worth while to note that there is another reason why System.Threading.Timer might be a good approach. When you have to periodically execute a Job that might take a long time and you want to ensure that the entire waiting period is used between jobs or if you don't want the job to run again before the previous job has finished in the case where the job takes longer than the timer period. You could use the following:

using System;
using System.ServiceProcess;
using System.Threading;

    public partial class TimerExampleService : ServiceBase
    {
        private AutoResetEvent AutoEventInstance { get; set; }
        private StatusChecker StatusCheckerInstance { get; set; }
        private Timer StateTimer { get; set; }
        public int TimerInterval { get; set; }

        public CaseIndexingService()
        {
            InitializeComponent();
            TimerInterval = 300000;
        }

        protected override void OnStart(string[] args)
        {
            AutoEventInstance = new AutoResetEvent(false);
            StatusCheckerInstance = new StatusChecker();

            // Create the delegate that invokes methods for the timer.
            TimerCallback timerDelegate =
                new TimerCallback(StatusCheckerInstance.CheckStatus);

            // Create a timer that signals the delegate to invoke 
            // 1.CheckStatus immediately, 
            // 2.Wait until the job is finished,
            // 3.then wait 5 minutes before executing again. 
            // 4.Repeat from point 2.
            Console.WriteLine("{0} Creating timer.\n",
                DateTime.Now.ToString("h:mm:ss.fff"));
            //Start Immediately but don't run again.
            StateTimer = new Timer(timerDelegate, AutoEventInstance, 0, Timeout.Infinite);
            while (StateTimer != null)
            {
                //Wait until the job is done
                AutoEventInstance.WaitOne();
                //Wait for 5 minutes before starting the job again.
                StateTimer.Change(TimerInterval, Timeout.Infinite);
            }
            //If the Job somehow takes longer than 5 minutes to complete then it wont matter because we will always wait another 5 minutes before running again.
        }

        protected override void OnStop()
        {
            StateTimer.Dispose();
        }
    }

    class StatusChecker
        {

            public StatusChecker()
            {
            }

            // This method is called by the timer delegate.
            public void CheckStatus(Object stateInfo)
            {
                AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
                Console.WriteLine("{0} Start Checking status.",
                    DateTime.Now.ToString("h:mm:ss.fff"));
                //This job takes time to run. For example purposes, I put a delay in here.
                int milliseconds = 5000;
                Thread.Sleep(milliseconds);
                //Job is now done running and the timer can now be reset to wait for the next interval
                Console.WriteLine("{0} Done Checking status.",
                    DateTime.Now.ToString("h:mm:ss.fff"));
                autoEvent.Set();
            }
        }

Conda: Installing / upgrading directly from github

I found a reference to this in condas issues. The following should now work.

name: sample_env
channels:
dependencies:
   - requests
   - bokeh>=0.10.0
   - pip:
     - git+https://github.com/pythonforfacebook/facebook-sdk.git

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    console.log(call)
    
    var a = call['a'], b = call['b']
     
    if(a == null || b == null) {
        result = false
        break
    }
}

Changing background colour of tr element on mouseover

its easy . Just add !important at the end of your css line :

tr:hover {    background: #000 !important; }

Vagrant shared and synced folders

shared folders VS synced folders

Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf between host and guest (there is known performance issues if there are large numbers of files/directories).

Vagrantfile directory mounted as /vagrant in guest

Vagrant is mounting the current working directory (where Vagrantfile resides) as /vagrant in the guest, this is the default behaviour.

See docs

NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.

You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true in your Vagrantfile.

Why synced folder is not working

Based on the output /tmp on host was NOT mounted during up time.

Use VAGRANT_INFO=debug vagrant up or VAGRANT_INFO=debug vagrant reload to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp on host should be drwxrwxrwt).

I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)

config.vm.synced_folder "/tmp", "/tmp/src"

output

$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src

Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw).

Bootstrap Accordion button toggle "data-parent" not working

If found this alteration to Krzysztof answer helped my issue

$('#' + parentId + ' .collapse').on('show.bs.collapse', function (e) {            
    var all = $('#' + parentId).find('.collapse');
    var actives = $('#' + parentId).find('.in, .collapsing');
    all.each(function (index, element) {
      $(element).collapse('hide');
    })
    actives.each(function (index, element) {                
      $(element).collapse('show');                
    })
})    

if you have nested panels then you may also need to specify which ones by adding another class name to distinguish between them and add this to the a selector in the above JavaScript

Why is Spring's ApplicationContext.getBean considered bad?

Using @Autowired or ApplicationContext.getBean() is really the same thing. In both ways you get the bean that is configured in your context and in both ways your code depends on spring. The only thing you should avoid is instantiating your ApplicationContext. Do this only once! In other words, a line like

ApplicationContext context = new ClassPathXmlApplicationContext("AppContext.xml");

should only be used once in your application.

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

What does template <unsigned int N> mean?

You templatize your class based on an 'unsigned int'.

Example:

template <unsigned int N>
class MyArray
{
    public:
    private:
        double    data[N]; // Use N as the size of the array
};

int main()
{
    MyArray<2>     a1;
    MyArray<2>     a2;

    MyArray<4>     b1;

    a1 = a2;  // OK The arrays are the same size.
    a1 = b1;  // FAIL because the size of the array is part of the
              //      template and thus the type, a1 and b1 are different types.
              //      Thus this is a COMPILE time failure.
 }

Byte Array and Int conversion in Java

You're swapping endianness between your two methods. You have intToByteArray(int a) assigning the low-order bits into ret[0], but then byteArrayToInt(byte[] b) assigns b[0] to the high-order bits of the result. You need to invert one or the other, like:

public static byte[] intToByteArray(int a)
{
    byte[] ret = new byte[4];
    ret[3] = (byte) (a & 0xFF);   
    ret[2] = (byte) ((a >> 8) & 0xFF);   
    ret[1] = (byte) ((a >> 16) & 0xFF);   
    ret[0] = (byte) ((a >> 24) & 0xFF);
    return ret;
}

Difference between matches() and find() in Java Regex

find() will consider the sub-string against the regular expression where as matches() will consider complete expression.

find() will returns true only if the sub-string of the expression matches the pattern.

public static void main(String[] args) {
        Pattern p = Pattern.compile("\\d");
        String candidate = "Java123";
        Matcher m = p.matcher(candidate);

        if (m != null){
            System.out.println(m.find());//true
            System.out.println(m.matches());//false
        }
    }

Django - filtering on foreign key properties

Asset.objects.filter( project__name__contains="Foo" )

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

You need to start by understanding that the target of a symlink is a pathname. And it can be absolute or relative to the directory which contains the symlink

Assuming you have foo.conf in sites-available

Try

cd sites-enabled
sudo ln -s ../sites-available/foo.conf .
ls -l

Now you will have a symlink in sites-enabled called foo.conf which has a target ../sites-available/foo.conf

Just to be clear, the normal configuration for Apache is that the config files for potential sites live in sites-available and the symlinks for the enabled sites live in sites-enabled, pointing at targets in sites-available. That doesn't quite seem to be the case the way you describe your setup, but that is not your primary problem.

If you want a symlink to ALWAYS point at the same file, regardless of the where the symlink is located, then the target should be the full path.

ln -s /etc/apache2/sites-available/foo.conf mysimlink-whatever.conf

Here is (line 1 of) the output of my ls -l /etc/apache2/sites-enabled:

lrwxrwxrwx 1 root root  26 Jun 24 21:06 000-default -> ../sites-available/default

See how the target of the symlink is relative to the directory that contains the symlink (it starts with ".." meaning go up one directory).

Hardlinks are totally different because the target of a hardlink is not a directory entry but a filing system Inode.

How to change font of UIButton with Swift

Example: button.titleLabel?.font = UIFont(name: "HelveticaNeue-Bold", size: 12)

  • If you want to use defaul font from it's own family, use for example: "HelveticaNeue"
  • If you want to specify family font, use for example: "HelveticaNeue-Bold"

How can I center <ul> <li> into div

Steps :

  1. Write style="text-align:center;" to parent div of ul
  2. Write style="display:inline-table;" to ul
  3. Write style="display:inline;" to li

or use

<div class="menu">
 <ul>
   <li>item 1 </li>
   <li>item 2 </li>
   <li>item 3 </li>
 </ul>
</div>

<style>
 .menu { text-align: center; }
 .menu ul { display:inline-table; }
 .menu li { display:inline; }
</style>

Importing json file in TypeScript

The import form and the module declaration need to agree about the shape of the module, about what it exports.

When you write (a suboptimal practice for importing JSON since TypeScript 2.9 when targeting compatible module formatssee note)

declare module "*.json" {
  const value: any;
  export default value;
}

You are stating that all modules that have a specifier ending in .json have a single export named default.

There are several ways you can correctly consume such a module including

import a from "a.json";
a.primaryMain

and

import * as a from "a.json";
a.default.primaryMain

and

import {default as a} from "a.json";
a.primaryMain

and

import a = require("a.json");
a.default.primaryMain

The first form is the best and the syntactic sugar it leverages is the very reason JavaScript has default exports.

However I mentioned the other forms to give you a hint about what's going wrong. Pay special attention to the last one. require gives you an object representing the module itself and not its exported bindings.

So why the error? Because you wrote

import a = require("a.json");
a.primaryMain

And yet there is no export named primaryMain declared by your "*.json".

All of this assumes that your module loader is providing the JSON as the default export as suggested by your original declaration.

Note: Since TypeScript 2.9, you can use the --resolveJsonModule compiler flag to have TypeScript analyze imported .json files and provide correct information regarding their shape obviating the need for a wildcard module declaration and validating the presence of the file. This is not supported for certain target module formats.

How to set the holo dark theme in a Android app?

change parent="android:Theme.Holo.Dark" to parent="android:Theme.Holo"

The holo dark theme is called Holo

List of special characters for SQL LIKE clause

You should add that you have to add an extra ' to escape an exising ' in SQL Server:

smith's -> smith''s

How to delete directory content in Java?

for(File f : files) {
    f.delete();
}    
files.delete(); // will work

ActionBarActivity: cannot be resolved to a type

UPDATE:

Since the version 22.1.0, the class ActionBarActivity is deprecated, so instead use AppCompatActivity. For more details see here

Using ActionBarActivity:

In Eclipse:

1 - Make sure library project(appcompat_v7) is open & is proper referenced (added as library) in your application project.

2 - Delete android-support-v4.jar from your project's libs folder(if jar is present).

3 - Appcompat_v7 must have android-support-v4.jar & android-support-v7-appcompat.jar inside it's libs folder. (If jars are not present copy them from /sdk/extras/android/support/v7/appcompat/libs folder of your installed android sdk location)

4- Check whether ActionBarActivity is properly imported.

import android.support.v7.app.ActionBarActivity;

In Android Studio

Just add compile dependencies to app's build.gradle

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.1.1'
}

How to share my Docker-Image without using the Docker-Hub?

Sending a docker image to a remote server can be done in 3 simple steps:

  1. Locally, save docker image as a .tar:
docker save -o <path for created tar file> <image name>
  1. Locally, use scp to transfer .tar to remote

  2. On remote server, load image into docker:

docker load -i <path to docker image tar file>

How to select where ID in Array Rails ActiveRecord without exception

Now .find and .find_by_id methods are deprecated in rails 4. So instead we can use below:

Comment.where(id: [2, 3, 5])

It will work even if some of the ids don't exist. This works in the

user.comments.where(id: avoided_ids_array)

Also for excluding ID's

Comment.where.not(id: [2, 3, 5])

How can I decrypt a password hash in PHP?

Use the password_verify() function

if (password_vertify($inputpassword, $row['password'])) {
  print "Logged in";
else {
    print "Password Incorrect";
}

Why compile Python code?

The .pyc file is Python that has already been compiled to byte-code. Python automatically runs a .pyc file if it finds one with the same name as a .py file you invoke.

"An Introduction to Python" says this about compiled Python files:

A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded.

The advantage of running a .pyc file is that Python doesn't have to incur the overhead of compiling it before running it. Since Python would compile to byte-code before running a .py file anyway, there shouldn't be any performance improvement aside from that.

How much improvement can you get from using compiled .pyc files? That depends on what the script does. For a very brief script that simply prints "Hello World," compiling could constitute a large percentage of the total startup-and-run time. But the cost of compiling a script relative to the total run time diminishes for longer-running scripts.

The script you name on the command-line is never saved to a .pyc file. Only modules loaded by that "main" script are saved in that way.

Changing an AIX password via script?

You can try :

echo -e "newpasswd123\nnnewpasswd123" | passwd user

How do I drop a MongoDB database from the command line?

Eventhough there are several methods, The best way (most efficient and easiest) is using db.dropDatabase()

Specified cast is not valid?

htmlStr is string then You need to Date and Time variables to string

while (reader.Read())
                {
                    DateTime Date = reader.GetDateTime(0);
                    DateTime Time = reader.GetDateTime(1);
                    htmlStr += "<tr><td>" + Date.ToString() + "</td><td>"  + 
                    Time.ToString() + "</td></tr>";                  
                }

Java String import

Java compiler imports 3 packages by default. 1. The package without name 2. The java.lang package(That's why you can declare String, Integer, System classes without import) 3. The current package (current file's package)

That's why you don't need to declare import statement for the java.lang package.

Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done?

No it doesn't wait and the way you are doing it in that sample is not good practice.

dispatch_async is always asynchronous. It's just that you are enqueueing all the UI blocks to the same queue so the different blocks will run in sequence but parallel with your data processing code.

If you want the update to wait you can use dispatch_sync instead.

// This will wait to finish
dispatch_sync(dispatch_get_main_queue(), ^{
    // Update the UI on the main thread.
});

Another approach would be to nest enqueueing the block. I wouldn't recommend it for multiple levels though.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // Background work

    dispatch_async(dispatch_get_main_queue(), ^{
        // Update UI

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            // Background work

            dispatch_async(dispatch_get_main_queue(), ^{
                // Update UI
            });
        });
    });
});

If you need the UI updated to wait then you should use the synchronous versions. It's quite okay to have a background thread wait for the main thread. UI updates should be very quick.

How to disable keypad popup when on edittext?

You have to create a view, above the EditText, that takes a 'fake' focus:

Something like :

<!-- Stop auto focussing the EditText -->
<LinearLayout
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:background="@android:color/transparent"
    android:focusable="true"
    android:focusableInTouchMode="true">
</LinearLayout>

<EditText
    android:id="@+id/searchAutoCompleteTextView_feed"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:inputType="text" />

In this case, I used a LinearLayout to request the focus. Hope this helps.

This worked perfectly...thanks to Zaggo0

Plotting using a CSV file

This should get you started:

set datafile separator ","
plot 'infile' using 0:1

Exclude all transitive dependencies of a single dependency

I use the following workaround : instead of trying to exclude the artifact in all appropriate dependencies, I draw the dependency as "provided" at top level. For example, to avoid shipping xml-apis "whatever version" :

    <dependency>
        <groupId>xml-apis</groupId>
        <artifactId>xml-apis</artifactId>
        <version>[1.0,]</version>
        <scope>provided</scope>
    </dependency>

Git: Recover deleted (remote) branch

If your organization uses JIRA or another similar system that is tied into git, you can find the commits listed on the ticket itself and click the links to the code changes. Github deletes the branch but still has the commits available for cherry-picking.

Bootstrap's JavaScript requires jQuery version 1.9.1 or higher

in my case the fix was replacing

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

with

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

How to get input field value using PHP

Example of using PHP to get a value from a form:

Put this in foobar.php:

<html>
<body>
  <form action="foobar_submit.php" method="post">
    <input name="my_html_input_tag"  value="PILLS HERE"/>

    <input type="submit" name="my_form_submit_button" 
           value="Click here for penguins"/>

    </form>
</body>
</html>

Read the above code so you understand what it is doing:

"foobar.php is an HTML document containing an HTML form. When the user presses the submit button inside the form, the form's action property is run: foobar_submit.php. The form will be submitted as a POST request. Inside the form is an input tag with the name "my_html_input_tag". It's default value is "PILLS HERE". That causes a text box to appear with text: 'PILLS HERE' on the browser. To the right is a submit button, when you click it, the browser url changes to foobar_submit.php and the below code is run.

Put this code in foobar_submit.php in the same directory as foobar.php:

<?php
  echo $_POST['my_html_input_tag'];
  echo "<br><br>";
  print_r($_POST); 
?>

Read the above code so you know what its doing:

The HTML form from above populated the $_POST superglobal with key/value pairs representing the html elements inside the form. The echo prints out the value by key: 'my_html_input_tag'. If the key is found, which it is, its value is returned: "PILLS HERE".

Then print_r prints out all the keys and values from $_POST so you can peek as to what else is in there.

The value of the input tag with name=my_html_input_tag was put into the $_POST and you retrieved it inside another PHP file.

Check if two unordered lists are equal

Python has a built-in datatype for an unordered collection of (hashable) things, called a set. If you convert both lists to sets, the comparison will be unordered.

set(x) == set(y)

Documentation on set


EDIT: @mdwhatcott points out that you want to check for duplicates. set ignores these, so you need a similar data structure that also keeps track of the number of items in each list. This is called a multiset; the best approximation in the standard library is a collections.Counter:

>>> import collections
>>> compare = lambda x, y: collections.Counter(x) == collections.Counter(y)
>>> 
>>> compare([1,2,3], [1,2,3,3])
False
>>> compare([1,2,3], [1,2,3])
True
>>> compare([1,2,3,3], [1,2,2,3])
False
>>> 

List files recursively in Linux CLI with path relative to the current directory

You could create a shell function, e.g. in your .zshrc or .bashrc:

filepath() {
    echo $PWD/$1
}

filepath2() {
    for i in $@; do
        echo $PWD/$i
    done
}

The first one would work on single files only, obviously.

How does MySQL CASE work?

CASE in MySQL is both a statement and an expression, where each usage is slightly different.

As a statement, CASE works much like a switch statement and is useful in stored procedures, as shown in this example from the documentation (linked above):

DELIMITER |

CREATE PROCEDURE p()
  BEGIN
    DECLARE v INT DEFAULT 1;

    CASE v
      WHEN 2 THEN SELECT v;
      WHEN 3 THEN SELECT 0;
      ELSE
        BEGIN -- Do other stuff
        END;
    END CASE;
  END;
  |

However, as an expression it can be used in clauses:

SELECT *
  FROM employees
  ORDER BY
    CASE title
      WHEN "President" THEN 1
      WHEN "Manager" THEN 2
      ELSE 3
    END, surname

Additionally, both as a statement and as an expression, the first argument can be omitted and each WHEN must take a condition.

SELECT *
  FROM employees
  ORDER BY
    CASE 
      WHEN title = "President" THEN 1
      WHEN title = "Manager" THEN 2
      ELSE 3
    END, surname

I provided this answer because the other answer fails to mention that CASE can function both as a statement and as an expression. The major difference between them is that the statement form ends with END CASE and the expression form ends with just END.

How to use enums as flags in C++?

The C++ standard explicitly talks about this, see section "17.5.2.1.3 Bitmask types":

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3485.pdf

Given this "template" you get:

enum AnimalFlags : unsigned int
{
    HasClaws = 1,
    CanFly = 2,
    EatsFish = 4,
    Endangered = 8
};

constexpr AnimalFlags operator|(AnimalFlags X, AnimalFlags Y) {
    return static_cast<AnimalFlags>(
        static_cast<unsigned int>(X) | static_cast<unsigned int>(Y));
}

AnimalFlags& operator|=(AnimalFlags& X, AnimalFlags Y) {
    X = X | Y; return X;
}

And similar for the other operators. Also note the "constexpr", it is needed if you want the compiler to be able to execute the operators compile time.

If you are using C++/CLI and want to able assign to enum members of ref classes you need to use tracking references instead:

AnimalFlags% operator|=(AnimalFlags% X, AnimalFlags Y) {
    X = X | Y; return X;
}

NOTE: This sample is not complete, see section "17.5.2.1.3 Bitmask types" for a complete set of operators.

How to left align a fixed width string?

This one worked in my python script:

print "\t%-5s %-10s %-10s %-10s %-10s %-10s %-20s"  % (thread[0],thread[1],thread[2],thread[3],thread[4],thread[5],thread[6])

z-index not working with position absolute

z-index only applies to elements that have been given an explicit position. Add position:relative to #popupContent and you should be good to go.

Load a Bootstrap popover content with AJAX. Is this possible?

There are way too many answers here but I also found none of them to be what I wanted. I've extended Ivan Klass's answer to be both Bootstrap 4 appropriate and intelligently cached.

Note that the snippet won't actually load the remote address due to Stackoverflow's CORS policy.

_x000D_
_x000D_
var popoverRemoteContents = function(element) {_x000D_
  if ($(element).data('loaded') !== true) {_x000D_
    var div_id = 'tmp-id-' + $.now();_x000D_
    $.ajax({_x000D_
      url: $(element).data('popover-remote'),_x000D_
      success: function(response) {_x000D_
        $('#' + div_id).html(response);_x000D_
        $(element).attr("data-loaded", true);_x000D_
        $(element).attr("data-content", response);_x000D_
        return $(element).popover('update');_x000D_
      }_x000D_
    });_x000D_
    return '<div id="' + div_id + '">Loading...</div>';_x000D_
  } else {_x000D_
    return $(element).data('content');_x000D_
  }_x000D_
};_x000D_
_x000D_
$('[data-popover-remote]').popover({_x000D_
  html: true,_x000D_
  trigger: 'hover',_x000D_
  content: function() {_x000D_
    return popoverRemoteContents(this);_x000D_
  }_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<span data-popover-remote="http://example.com/">Remote Popover test with caching</span>
_x000D_
_x000D_
_x000D_

connecting to MySQL from the command line

See here http://dev.mysql.com/doc/refman/5.0/en/connecting.html

mysql -u USERNAME -pPASSWORD -h HOSTNAMEORIP DATABASENAME 

The options above means:

-u: username
-p: password (**no space between -p and the password text**)
-h: host
last one is name of the database that you wanted to connect. 

Look into the link, it's detailed there!


As already mentioned by Rick, you can avoid passing the password as the part of the command by not passing the password like this:

mysql -u USERNAME -h HOSTNAMEORIP DATABASENAME -p

People editing this answer: PLEASE DONOT ADD A SPACE between -p and PASSWORD

TimeStamp on file name using PowerShell

You can insert arbitrary PowerShell script code in a double-quoted string by using a subexpression, for example, $() like so:

"C:\temp\mybackup $(get-date -f yyyy-MM-dd).zip"

And if you are getting the path from somewhere else - already as a string:

$dirName  = [io.path]::GetDirectoryName($path)
$filename = [io.path]::GetFileNameWithoutExtension($path)
$ext      = [io.path]::GetExtension($path)
$newPath  = "$dirName\$filename $(get-date -f yyyy-MM-dd)$ext"

And if the path happens to be coming from the output of Get-ChildItem:

Get-ChildItem *.zip | Foreach {
  "$($_.DirectoryName)\$($_.BaseName) $(get-date -f yyyy-MM-dd)$($_.extension)"}

How to read the RGB value of a given pixel in Python?

If you are looking to have three digits in the form of an RGB colour code, the following code should do just that.

i = Image.open(path)
pixels = i.load() # this is not a list, nor is it list()'able
width, height = i.size

all_pixels = []
for x in range(width):
    for y in range(height):
        cpixel = pixels[x, y]
        all_pixels.append(cpixel)

This may work for you.

How to make a JFrame Modal in Swing java

Your best bet is to use a JDialog instead of a JFrame if you want to make the window modal. Check out details on the introduction of the Modality API in Java 6 for info. There is also a tutorial.

Here is some sample code which will display a JPanel panel in a JDialog which is modal to Frame parentFrame. Except for the constructor, this follows the same pattern as opening a JFrame.

final JDialog frame = new JDialog(parentFrame, frameTitle, true);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);

Edit: updated Modality API link & added tutorial link (nod to @spork for the bump).

setting min date in jquery datepicker

basically if you already specify the year range there is no need to use mindate and maxdate if only year is required

Remove a fixed prefix/suffix from a string in Bash

Using sed:

$ echo "$string" | sed -e "s/^$prefix//" -e "s/$suffix$//"
o-wor

Within the sed command, the ^ character matches text beginning with $prefix, and the trailing $ matches text ending with $suffix.

Adrian Frühwirth makes some good points in the comments below, but sed for this purpose can be very useful. The fact that the contents of $prefix and $suffix are interpreted by sed can be either good OR bad- as long as you pay attention, you should be fine. The beauty is, you can do something like this:

$ prefix='^.*ll'
$ suffix='ld$'
$ echo "$string" | sed -e "s/^$prefix//" -e "s/$suffix$//"
o-wor

which may be what you want, and is both fancier and more powerful than bash variable substitution. If you remember that with great power comes great responsibility (as Spiderman says), you should be fine.

A quick introduction to sed can be found at http://evc-cit.info/cit052/sed_tutorial.html

A note regarding the shell and its use of strings:

For the particular example given, the following would work as well:

$ echo $string | sed -e s/^$prefix// -e s/$suffix$//

...but only because:

  1. echo doesn't care how many strings are in its argument list, and
  2. There are no spaces in $prefix and $suffix

It's generally good practice to quote a string on the command line because even if it contains spaces it will be presented to the command as a single argument. We quote $prefix and $suffix for the same reason: each edit command to sed will be passed as one string. We use double quotes because they allow for variable interpolation; had we used single quotes the sed command would have gotten a literal $prefix and $suffix which is certainly not what we wanted.

Notice, too, my use of single quotes when setting the variables prefix and suffix. We certainly don't want anything in the strings to be interpreted, so we single quote them so no interpolation takes place. Again, it may not be necessary in this example but it's a very good habit to get into.

Logcat not displaying my log calls

I've had the same problem using Android Studio and managed to get around by selecting No Filters in the select box in the top right corner of LogCat. By doing this I started receiving everything Android logs in the background into LogCat including my missing Log calls.

enter image description here

How to modify values of JsonObject / JsonArray directly?

Strangely, the answer is to keep adding back the property. I was half expecting a setter method. :S

System.out.println("Before: " + obj.get("DebugLogId")); // original "02352"

obj.addProperty("DebugLogId", "YYY");

System.out.println("After: " + obj.get("DebugLogId")); // now "YYY"

Failed to load resource: the server responded with a status of 404 (Not Found) error in server

It just means that the server cannot find your image.

Remember The image path must be relative to the CSS file location

Check the path and if the image file exist.

Parsing command-line arguments in C

Okay, that's the start of long story - made short abort parsing a command line in C ...

/**
* Helper function to parse the command line
* @param argc Argument Counter
* @param argv Argument Vector
* @param prog Program Instance Reference to fill with options
*/
bool parseCommandLine(int argc, char* argv[], DuplicateFileHardLinker* prog) {
  bool pathAdded = false;

  // Iterate over all arguments...
  for (int i = 1; i<argc; i++) {

    // Is argv a command line option?
    if (argv[i][0] == '-' || argv[i][0] == '/') {

      // ~~~~~~ Optionally Cut that part vvvvvvvvvvvvv for sake of simplicity ~~~~~~~
      // Check for longer options
      if (stricmp( &argv[i][1], "NoFileName") == 0  ||
          strcmp( &argv[i][1], "q1"         ) == 0 ) {

        boNoFileNameLog = true;

      } else if (strcmp( &argv[i][1], "HowAreYou?") == 0 ) {
          logInfo( "SECRET FOUND: Well - wow I'm glad ya ask me.");
      } else {


        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        // Now here comes the main thing:
        //

        // Check for one-character options
        while (char option = *++argv[i]) {

          switch (option) {
          case '?':
            // Show program usage

            logInfo(L"Options:");
            logInfo(L"  /q\t>Quite mode");
            logInfo(L"  /v\t>Verbose mode");
            logInfo(L"  /d\t>Debug mode");
            return false;

            // Log options
          case 'q':
            setLogLevel(LOG_ERROR);
            break;

          case 'v':
            setLogLevel(LOG_VERBOSE);
            break;

          case 'd':
            setLogLevel(LOG_DEBUG);
            break;

          default:
            logError(L"'%s' is an illegal command line option!"
                      "  Use /? to see valid options!", option);
            return false;
          } // switch one-char-option
        } // while one-char-options
      }  // else one vs longer options
    } // if isArgAnOption

    //
    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^  So that's it! ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    // What follows now is are some useful extras...
    //
    else {

      // The command line options seems to be a path...
      WCHAR tmpPath[MAX_PATH_LENGTH];
      mbstowcs(tmpPath, argv[i], sizeof(tmpPath));

      // Check if the path is existing!
      //...

      prog->addPath(tmpPath); // Comment or remove to get a working example
      pathAdded = true;
    }
  }

  // Check for parameters
  if (!pathAdded) {
    logError("You need to specify at least one folder to process!\n"
             "Use /? to see valid options!");
    return false;
  }

  return true;
}


int main(int argc, char* argv[]) {

  try {
    // Parse the command line
    if ( !parseCommandLine(argc, argv, prog) ) {
      return 1;
    }

    // I know that sample is just to show how the nicely parse command-line arguments
    // So Please excuse more nice useful C-glatter that follows now...

  }
  catch ( LPCWSTR err ) {
    DWORD dwError = GetLastError();
    if ( wcslen(err) > 0 ) {
      if ( dwError != 0 ) {
        logError(dwError, err);
      }
      else {
        logError(err);
      }
    }
    return 2;
  }
}

#define LOG_ERROR                1
#define LOG_INFO                 0
#define LOG_VERBOSE             -1
#define LOG_DEBUG               -2

/** Logging level for the console output */
int logLevel = LOG_INFO;

void logError(LPCWSTR message, ...) {
  va_list argp;
  fwprintf(stderr, L"ERROR: ");
  va_start(argp, message);
  vfwprintf(stderr, message, argp);
  va_end(argp);
  fwprintf(stderr, L"\n");
}


void logInfo(LPCWSTR message, ...) {
  if ( logLevel <= LOG_INFO ) {
    va_list argp;
    va_start(argp, message);
    vwprintf(message, argp);
    va_end(argp);
    wprintf(L"\n");
  }
}

Note that this version will also support combining arguments: So instead of writing /h /s -> /hs will also work.

Sorry for being the n-th person posting here - however I wasn't really satisfied with all the stand-alone-versions I saw here. Well, the library ones are quiet nice. So I would prefer the libUCW option parser, Arg or Getopt over a home-made ones.

Note you may change:

*++argv[i] -> (++argv*)[0]

It is longer and less cryptic, but still cryptic.

Okay, let's break it down:

  1. argv[i]-> access i-th element in the argv-char pointer field

  2. ++*... -> will forward the argv-pointer by one char

  3. ... [0]-> will follow the pointer read the char

  4. ++(...) -> bracket are there so we'll increase the pointer and not the char value itself.

It is so nice that in C#, the pointers 'died' - long live the pointers!!

mysql: get record count between two date-time

select * from yourtable 
   where created < now() 
     and created > concat(curdate(),' 4:30:00 AM') 

How to override equals method in Java

I'm not sure of the details as you haven't posted the whole code, but:

  • remember to override hashCode() as well
  • the equals method should have Object, not People as its argument type. At the moment you are overloading, not overriding, the equals method, which probably isn't what you want, especially given that you check its type later.
  • you can use instanceof to check it is a People object e.g. if (!(other instanceof People)) { result = false;}
  • equals is used for all objects, but not primitives. I think you mean age is an int (primitive), in which case just use ==. Note that an Integer (with a capital 'I') is an Object which should be compared with equals.

See What issues should be considered when overriding equals and hashCode in Java? for more details.

String concatenation with Groovy

def my_string = "some string"
println "here: " + my_string 

Not quite sure why the answer above needs to go into benchmarks, string buffers, tests, etc.

How to compare strings in Bash

Or, if you don't need else clause:

[ "$x" == "valid" ] && echo "x has the value 'valid'"

How do I create a WPF Rounded Corner container?

VB.Net code based implementation of kobusb's Border control solution. I used it to populate a ListBox of Button controls. The Button controls are created from MEF extensions. Each extension uses MEF's ExportMetaData attribute for a Description of the extension. The extensions are VisiFire charting objects. The user pushes a button, selected from the list of buttons, to execute the desired chart.

        ' Create a ListBox of Buttons, one button for each MEF charting component. 
    For Each c As Lazy(Of ICharts, IDictionary(Of String, Object)) In ext.ChartDescriptions
        Dim brdr As New Border
        brdr.BorderBrush = Brushes.Black
        brdr.BorderThickness = New Thickness(2, 2, 2, 2)
        brdr.CornerRadius = New CornerRadius(8, 8, 8, 8)
        Dim btn As New Button
        AddHandler btn.Click, AddressOf GenericButtonClick
        brdr.Child = btn
        brdr.Background = btn.Background
        btn.Margin = brdr.BorderThickness
        btn.Width = ChartsLBx.ActualWidth - 22
        btn.BorderThickness = New Thickness(0, 0, 0, 0)
        btn.Height = 22
        btn.Content = c.Metadata("Description")
        btn.Tag = c
        btn.ToolTip = "Push button to see " & c.Metadata("Description").ToString & " chart"
        Dim lbi As New ListBoxItem
        lbi.Content = brdr
        ChartsLBx.Items.Add(lbi)
    Next

Public Event Click As RoutedEventHandler

Private Sub GenericButtonClick(sender As Object, e As RoutedEventArgs)
    Dim btn As Button = DirectCast(sender, Button)
    Dim c As Lazy(Of ICharts, IDictionary(Of String, Object)) = DirectCast(btn.Tag, Lazy(Of ICharts, IDictionary(Of String, Object)))
    Dim w As Window = DirectCast(c.Value, Window)
    Dim cc As ICharts = DirectCast(c.Value, ICharts)
    c.Value.CreateChart()
    w.Show()
End Sub

<System.ComponentModel.Composition.Export(GetType(ICharts))> _
<System.ComponentModel.Composition.ExportMetadata("Description", "Data vs. Time")> _
Public Class DataTimeChart
    Implements ICharts

    Public Sub CreateChart() Implements ICharts.CreateChart
    End Sub
End Class

Public Interface ICharts
    Sub CreateChart()
End Interface

Public Class Extensibility
    Public Sub New()
        Dim catalog As New AggregateCatalog()

        catalog.Catalogs.Add(New AssemblyCatalog(GetType(Extensibility).Assembly))

        'Create the CompositionContainer with the parts in the catalog
        ChartContainer = New CompositionContainer(catalog)

        Try
            ChartContainer.ComposeParts(Me)
        Catch ex As Exception
            Console.WriteLine(ex.ToString)
        End Try
    End Sub

    ' must use Lazy otherwise instantiation of Window will hold open app. Otherwise must specify Shutdown Mode of "Shutdown on Main Window".
    <ImportMany()> _
    Public Property ChartDescriptions As IEnumerable(Of Lazy(Of ICharts, IDictionary(Of String, Object)))

End Class

Practical uses of git reset --soft?

git reset is all about moving HEAD, and generally the branch ref.
Question: what about the working tree and index?
When employed with --soft, moves HEAD, most often updating the branch ref, and only the HEAD.
This differ from commit --amend as:

  • it doesn't create a new commit.
  • it can actually move HEAD to any commit (as commit --amend is only about not moving HEAD, while allowing to redo the current commit)

Just found this example of combining:

  • a classic merge
  • a subtree merge

all into one (octopus, since there is more than two branches merged) commit merge.

Tomas "wereHamster" Carnecky explains in his "Subtree Octopus merge" article:

  • The subtree merge strategy can be used if you want to merge one project into a subdirectory of another project, and the subsequently keep the subproject up to date. It is an alternative to git submodules.
  • The octopus merge strategy can be used to merge three or more branches. The normal strategy can merge only two branches and if you try to merge more than that, git automatically falls back to the octopus strategy.

The problem is that you can choose only one strategy. But I wanted to combine the two in order to get a clean history in which the whole repository is atomically updated to a new version.

I have a superproject, let's call it projectA, and a subproject, projectB, that I merged into a subdirectory of projectA.

(that's the subtree merge part)

I'm also maintaining a few local commits.
ProjectA is regularly updated, projectB has a new version every couple days or weeks and usually depends on a particular version of projectA.

When I decide to update both projects, I don't simply pull from projectA and projectB as that would create two commits for what should be an atomic update of the whole project.
Instead, I create a single merge commit which combines projectA, projectB and my local commits.
The tricky part here is that this is an octopus merge (three heads), but projectB needs to be merged with the subtree strategy. So this is what I do:

# Merge projectA with the default strategy:
git merge projectA/master

# Merge projectB with the subtree strategy:
git merge -s subtree projectB/master

Here the author used a reset --hard, and then read-tree to restore what the first two merges had done to the working tree and index, but that is where reset --soft can help:
How to I redo those two merges, which have worked, i.e. my working tree and index are fine, but without having to record those two commits?

# Move the HEAD, and just the HEAD, two commits back!
git reset --soft HEAD@{2}

Now, we can resume Tomas's solution:

# Pretend that we just did an octopus merge with three heads:
echo $(git rev-parse projectA/master) > .git/MERGE_HEAD
echo $(git rev-parse projectB/master) >> .git/MERGE_HEAD

# And finally do the commit:
git commit

So, each time:

  • you are satisfied with what you end up with (in term of working tree and index)
  • you are not satisfied with all the commits that took you to get there:

git reset --soft is the answer.

Having links relative to root?

To give a URL to an image tag which locates images/ directory in the root like

`logo.png`

you should give src URL starting with / as follows:

<img src="/images/logo.png"/>

This code works in any directories without any troubles even if you are in branches/europe/about.php still the logo can be seen right there.

Select query with date condition

The semicolon character is used to terminate the SQL statement.

You can either use # signs around a date value or use Access's (ACE, Jet, whatever) cast to DATETIME function CDATE(). As its name suggests, DATETIME always includes a time element so your literal values should reflect this fact. The ISO date format is understood perfectly by the SQL engine.

Best not to use BETWEEN for DATETIME in Access: it's modelled using a floating point type and anyhow time is a continuum ;)

DATE and TABLE are reserved words in the SQL Standards, ODBC and Jet 4.0 (and probably beyond) so are best avoided for a data element names:

Your predicates suggest open-open representation of periods (where neither its start date or the end date is included in the period), which is arguably the least popular choice. It makes me wonder if you meant to use closed-open representation (where neither its start date is included but the period ends immediately prior to the end date):

SELECT my_date
  FROM MyTable
 WHERE my_date >= #2008-09-01 00:00:00#
       AND my_date < #2010-09-01 00:00:00#;

Alternatively:

SELECT my_date
  FROM MyTable
 WHERE my_date >= CDate('2008-09-01 00:00:00')
       AND my_date < CDate('2010-09-01 00:00:00'); 

How to restart a rails server on Heroku?

Go into your application directory on terminal and run following command:

heroku restart

HTTPS connection Python

To check for ssl support in Python 2.6+:

try:
    import ssl
except ImportError:
    print "error: no ssl support"

To connect via https:

import urllib2

try:
    response = urllib2.urlopen('https://example.com') 
    print 'response headers: "%s"' % response.info()
except IOError, e:
    if hasattr(e, 'code'): # HTTPError
        print 'http error code: ', e.code
    elif hasattr(e, 'reason'): # URLError
        print "can't connect, reason: ", e.reason
    else:
        raise

How do CORS and Access-Control-Allow-Headers work?

Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000 or Access-Control-Allow-Origin: * on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true on the POST response as well.

Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept to match the requested header.

Maven artifact and groupId naming

Your convention seems to be reasonable. If I were searching for your framework in the Maven repo, I would look for awesome-inhouse-framework-x.y.jar in com.mycompany.awesomeinhouseframework group directory. And I would find it there according to your convention.

Two simple rules work for me:

  • reverse-domain-packages for groupId (since such are quite unique) with all the constrains regarding Java packages names
  • project name as artifactId (keeping in mind that it should be jar-name friendly i.e. not contain characters that maybe invalid for a file name or just look weird)

Where is SQLite database stored on disk?

If you are running Rails (its the default db in Rails) check the {RAILS_ROOT}/config/database.yml file and you will see something like:

database: db/development.sqlite3

This means that it will be in the {RAILS_ROOT}/db directory.

Include in SELECT a column that isn't actually in the database

You may want to use:

SELECT Name, 'Unpaid' AS Status FROM table;

The SELECT clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:

SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ] 
<select_list> 

Where the expression can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.

How to vertical align an inline-block in a line of text?

_x000D_
_x000D_
code {_x000D_
    background: black;_x000D_
    color: white;_x000D_
    display: inline-block;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<p>Some text <code>A<br />B<br />C<br />D</code> continues afterward.</p>
_x000D_
_x000D_
_x000D_

Tested and works in Safari 5 and IE6+.

Retrieving data from a POST method in ASP.NET

You need to examine (put a breakpoint on / Quick Watch) the Request object in the Page_Load method of your Test.aspx.cs file.

Draw an X in CSS

Yet another pure CSS solution (i.e. without the use of images, characters or additional fonts), based on @Bansoa is the answer's answer .

I've simplified it and added a bit of Flexbox magic to make it responsive.

Cross in this example automatically scales to any square container, and to change the thickness of its lines one have just to tune height: 4px; (to make a cross truly responsive, you may want to set the height in percents or other relative units).

_x000D_
_x000D_
div {_x000D_
    position: relative;_x000D_
    height: 150px; /* this can be anything */_x000D_
    width: 150px;  /* ...but maintain 1:1 aspect ratio */_x000D_
    display: flex;_x000D_
    flex-direction: column;_x000D_
    justify-content: center;_x000D_
    border: 1px solid pink; /* not required, added for better visibility */_x000D_
}_x000D_
_x000D_
div::before,_x000D_
div::after {_x000D_
    position: absolute;_x000D_
    content: '';_x000D_
    width: 100%;_x000D_
    height: 4px; /* cross thickness */_x000D_
    background-color: black;_x000D_
}_x000D_
_x000D_
div::before {_x000D_
    transform: rotate(45deg);_x000D_
}_x000D_
_x000D_
div::after {_x000D_
    transform: rotate(-45deg);_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

There are no primary or candidate keys in the referenced table that match the referencing column list in the foreign key

You need either

  • A unique index on Title in BookTitle
  • An ISBN column in BookCopy and the FK is on both columns

A foreign key needs to uniquely identify the parent row: you currently have no way to do that because Title is not unique.

How to find the index of an element in an int array?

Another option if you are using Guava Collections is Ints.indexOf

// Perfect storm:
final int needle = 42;
final int[] haystack = [1, 2, 3, 42];

// Spoiler alert: index == 3
final int index = Ints.indexOf(haystack, needle);

This is a great choice when space, time and code reuse are at a premium. It is also very terse.

Use index in pandas to plot data

Also,

monthly_mean.plot(x=df.index, y='A')

C++11 rvalues and move semantics confusion (return statement)

First example

std::vector<int> return_vector(void)
{
    std::vector<int> tmp {1,2,3,4,5};
    return tmp;
}

std::vector<int> &&rval_ref = return_vector();

The first example returns a temporary which is caught by rval_ref. That temporary will have its life extended beyond the rval_ref definition and you can use it as if you had caught it by value. This is very similar to the following:

const std::vector<int>& rval_ref = return_vector();

except that in my rewrite you obviously can't use rval_ref in a non-const manner.

Second example

std::vector<int>&& return_vector(void)
{
    std::vector<int> tmp {1,2,3,4,5};
    return std::move(tmp);
}

std::vector<int> &&rval_ref = return_vector();

In the second example you have created a run time error. rval_ref now holds a reference to the destructed tmp inside the function. With any luck, this code would immediately crash.

Third example

std::vector<int> return_vector(void)
{
    std::vector<int> tmp {1,2,3,4,5};
    return std::move(tmp);
}

std::vector<int> &&rval_ref = return_vector();

Your third example is roughly equivalent to your first. The std::move on tmp is unnecessary and can actually be a performance pessimization as it will inhibit return value optimization.

The best way to code what you're doing is:

Best practice

std::vector<int> return_vector(void)
{
    std::vector<int> tmp {1,2,3,4,5};
    return tmp;
}

std::vector<int> rval_ref = return_vector();

I.e. just as you would in C++03. tmp is implicitly treated as an rvalue in the return statement. It will either be returned via return-value-optimization (no copy, no move), or if the compiler decides it can not perform RVO, then it will use vector's move constructor to do the return. Only if RVO is not performed, and if the returned type did not have a move constructor would the copy constructor be used for the return.

react-native: command not found

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew install yarn
brew install node
brew install watchman
brew tap AdoptOpenJDK/openjdk
brew cask install adoptopenjdk8
npm install -g react-native-cli

How do you run a command as an administrator from the Windows command line?

I would set up a shortcut, either to CMD or to the thing you want to run, then set the properties of the shortcut to require admin, and then run the shortcut from your batch file. I haven't tested to confirm it will respect the properties, but I think it's more elegant and doesn't require activating the Administrator account.

Also if you do it as a scheduled task (which can be set up from code) there is an option to run it elevated there.

C++ Returning reference to local variable

This code snippet:

int& func1()
{
    int i;
    i = 1;
    return i;
}

will not work because you're returning an alias (a reference) to an object with a lifetime limited to the scope of the function call. That means once func1() returns, int i dies, making the reference returned from the function worthless because it now refers to an object that doesn't exist.

int main()
{
    int& p = func1();
    /* p is garbage */
}

The second version does work because the variable is allocated on the free store, which is not bound to the lifetime of the function call. However, you are responsible for deleteing the allocated int.

int* func2()
{
    int* p;
    p = new int;
    *p = 1;
    return p;
}

int main()
{
    int* p = func2();
    /* pointee still exists */
    delete p; // get rid of it
}

Typically you would wrap the pointer in some RAII class and/or a factory function so you don't have to delete it yourself.

In either case, you can just return the value itself (although I realize the example you provided was probably contrived):

int func3()
{
    return 1;
}

int main()
{
    int v = func3();
    // do whatever you want with the returned value
}

Note that it's perfectly fine to return big objects the same way func3() returns primitive values because just about every compiler nowadays implements some form of return value optimization:

class big_object 
{ 
public:
    big_object(/* constructor arguments */);
    ~big_object();
    big_object(const big_object& rhs);
    big_object& operator=(const big_object& rhs);
    /* public methods */
private:
    /* data members */
};

big_object func4()
{
    return big_object(/* constructor arguments */);
}

int main()
{
     // no copy is actually made, if your compiler supports RVO
    big_object o = func4();    
}

Interestingly, binding a temporary to a const reference is perfectly legal C++.

int main()
{
    // This works! The returned temporary will last as long as the reference exists
    const big_object& o = func4();    
    // This does *not* work! It's not legal C++ because reference is not const.
    // big_object& o = func4();  
}

Android changing Floating Action Button color

for Material design, I just changed the floating action button color like this, Add the below two lines in your Floating action button xml. And done,

 android:backgroundTint="@color/colorPrimaryDark"
 app:borderWidth="0dp"

Is returning out of a switch statement considered a better practice than using break?

Neither, because both are quite verbose for a very simple task. You can just do:

let result = ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[opt] ?? 'Default'    // opt can be 1, 2, 3 or anything (default)

This, of course, also works with strings, a mix of both or without a default case:

let result = ({
  'first': 'One',
  'second': 'Two',
  3: 'Three'
})[opt]                // opt can be 'first', 'second' or 3

Explanation:

It works by creating an object where the options/cases are the keys and the results are the values. By putting the option into the brackets you access the value of the key that matches the expression via the bracket notation.

This returns undefined if the expression inside the brackets is not a valid key. We can detect this undefined-case by using the nullish coalescing operator ?? and return a default value.

Example:

_x000D_
_x000D_
console.log('Using a valid case:', ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[1] ?? 'Default')

console.log('Using an invalid case/defaulting:', ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[7] ?? 'Default')
_x000D_
.as-console-wrapper {max-height: 100% !important;top: 0;}
_x000D_
_x000D_
_x000D_

How to force Hibernate to return dates as java.util.Date instead of Timestamp?

There are some classes in the Java platform libraries that do extend an instantiable class and add a value component. For example, java.sql.Timestamp extends java.util.Date and adds a nanoseconds field. The equals implementation for Timestamp does violate symmetry and can cause erratic behavior if Timestamp and Date objects are used in the same collection or are otherwise intermixed. The Timestamp class has a disclaimer cautioning programmers against mixing dates and timestamps. While you won’t get into trouble as long as you keep them separate, there’s nothing to prevent you from mixing them, and the resulting errors can be hard to debug. This behavior of the Timestamp class was a mistake and should not be emulated.

check out this link

http://blogs.sourceallies.com/2012/02/hibernate-date-vs-timestamp/

Convert JsonNode into POJO

In Jackson 2.4, you can convert as follows:

MyClass newJsonNode = jsonObjectMapper.treeToValue(someJsonNode, MyClass.class);

where jsonObjectMapper is a Jackson ObjectMapper.


In older versions of Jackson, it would be

MyClass newJsonNode = jsonObjectMapper.readValue(someJsonNode, MyClass.class);

Swipe ListView item From right to left show delete button

see there link was very nice and simple. its working fine... u don't want any library its working fine. click here

OnTouchListener gestureListener = new View.OnTouchListener() {
    private int padding = 0;
    private int initialx = 0;
    private int currentx = 0;
    private  ViewHolder viewHolder;

    public boolean onTouch(View v, MotionEvent event) {
        if ( event.getAction() == MotionEvent.ACTION_DOWN) {
            padding = 0;
            initialx = (int) event.getX();
            currentx = (int) event.getX();
            viewHolder = ((ViewHolder) v.getTag());
        }
        if ( event.getAction() == MotionEvent.ACTION_MOVE) {
            currentx = (int) event.getX();
            padding = currentx - initialx;
        }       
        if ( event.getAction() == MotionEvent.ACTION_UP || 
                     event.getAction() == MotionEvent.ACTION_CANCEL) {
            padding = 0;
            initialx = 0;
            currentx = 0;
        }
        if(viewHolder != null) {
            if(padding == 0) {
                v.setBackgroundColor(0xFF000000 );  
                if(viewHolder.running)
                    v.setBackgroundColor(0xFF058805);
            }
            if(padding > 75) {
                viewHolder.running = true;
                v.setBackgroundColor(0xFF00FF00 );  
                viewHolder.icon.setImageResource(R.drawable.clock_running);
            }
            if(padding < -75) {
                viewHolder.running = false;
                v.setBackgroundColor(0xFFFF0000 );  
            }

            v.setPadding(padding, 0,0, 0);
        }

        return true;
    }
};

Running Google Maps v2 on the Android emulator

I have already replied to this question in an answer to Stack Overflow question Trouble using Google sign-in button in emulator. It only works for Android 4.2.2, but lets you use the "Intel Atom (x86)" in AVD.

I think that it is easy to make it work for other versions of Android. Just find the correct files.

Android: how to convert whole ImageView to Bitmap?

It works in Kotlin after buildDrawingCache() being deprecated

 // convert imageView to bitmap
val bitmap = (imageViewId.getDrawable() as BitmapDrawable).getBitmap()

Expanding a parent <div> to the height of its children

_x000D_
_x000D_
#parent{_x000D_
  background-color:green;_x000D_
  height:auto;_x000D_
  width:300px;_x000D_
  overflow:hidden;_x000D_
}_x000D_
_x000D_
#childRightCol{_x000D_
  color:gray;_x000D_
  background-color:yellow;_x000D_
  margin:10px;_x000D_
  padding:10px;_x000D_
}
_x000D_
<div id="parent">_x000D_
    <div id="childRightCol">_x000D_
        <p>_x000D_
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vulputate sit amet neque ac consequat._x000D_
        </p>_x000D_
    </div>_x000D_
  </div>
_x000D_
_x000D_
_x000D_

you are manage by using overflow:hidden; property in css

Giving UIView rounded corners

ON Xcode 6 Your try

     self.layer.layer.cornerRadius = 5.0f;

or

    self.layer.layer.cornerRadius = 5.0f;
    self.layer.clipsToBounds = YES;

How to convert timestamps to dates in Bash?

I have written a script that does this myself:

#!/bin/bash
LANG=C
if [ -z "$1" ]; then
    if [  "$(tty)" = "not a tty" ]; then
            p=`cat`;
    else
            echo "No timestamp given."
            exit
    fi
else
    p=$1
fi
echo $p | gawk '{ print strftime("%c", $0); }'

C# Convert List<string> to Dictionary<string, string>

By using ToDictionary:

var dictionary = list.ToDictionary(s => s);

If it is possible that any string could be repeated, either do a Distinct call first on the list (to remove duplicates), or use ToLookup which allows for multiple values per key.

How do I run SSH commands on remote system using Java?

Below is the easiest way to SSh in java. Download any of the file in the below link and extract, then add the jar file from the extracted file and add to your build path of the project http://www.ganymed.ethz.ch/ssh2/ and use the below method

public void SSHClient(String serverIp,String command, String usernameString,String password) throws IOException{
        System.out.println("inside the ssh function");
        try
        {
            Connection conn = new Connection(serverIp);
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(usernameString, password);
            if (isAuthenticated == false)
                throw new IOException("Authentication failed.");        
            ch.ethz.ssh2.Session sess = conn.openSession();
            sess.execCommand(command);  
            InputStream stdout = new StreamGobbler(sess.getStdout());
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
            System.out.println("the output of the command is");
            while (true)
            {
                String line = br.readLine();
                if (line == null)
                    break;
                System.out.println(line);
            }
            System.out.println("ExitCode: " + sess.getExitStatus());
            sess.close();
            conn.close();
        }
        catch (IOException e)
        {
            e.printStackTrace(System.err);

        }
    }

How to "set a breakpoint in malloc_error_break to debug"

I had the same problem with Xcode. I followed steps you gave and it didn't work. I became crazy because in every forum I saw, all clues for this problem are the one you gave. I finally saw I put a space after the malloc_error_break, I suppressed it and now it works. A dumb problem but if the solution doesn't work, be sure you haven't put any space before and after the malloc_error_break.

Hope this message will help..

How to call javascript function from asp.net button click event

You're already prepending the hash sign in your showDialog() function, and you're missing single quotes in your second code snippet. You should also return false from the handler to prevent a postback from occurring. Try:

<asp:Button ID="ButtonAdd" runat="server" Text="Add"
    OnClientClick="showDialog('<%=addPerson.ClientID %>'); return false;" />

React "after render" code?

I had weird situation when i need to print react component which receives big amount of data and paint in on canvas. I've tried all mentioned approaches, non of them worked reliably for me, with requestAnimationFrame inside setTimeout i get empty canvas in 20% of the time, so i did the following:

nRequest = n => range(0,n).reduce(
(acc,val) => () => requestAnimationFrame(acc), () => requestAnimationFrame(this.save)
);

Basically i made a chain of requestAnimationFrame's, not sure is this good idea or not but this works in 100% of the cases for me so far (i'm using 30 as a value for n variable).

PHP multidimensional array search by value

Looks array_filter will be suitable solution for this...

$userdb=Array
(
    (0) => Array
        (
            (uid) => '100',
            (name) => 'Sandra Shush',
            (url) => 'urlof100'
        ),

    (1) => Array
        (
            (uid) => '5465',
            (name) => 'Stefanie Mcmohn',
            (pic_square) => 'urlof100'
        ),

    (2) => Array
        (
            (uid) => '40489',
            (name) => 'Michael',
            (pic_square) => 'urlof40489'
        )
);

PHP Code

<?php 
$search = 5465;
$found = array_filter($userdb,function($v,$k) use ($search){
  return $v['uid'] == $search;
},ARRAY_FILTER_USE_BOTH) // With latest PHP third parameter is mandatory.. Available Values:- ARRAY_FILTER_USE_BOTH OR ARRAY_FILTER_USE_KEY  

$values= print_r(array_values($found));
$keys =  print_r(array_keys($found)); 

How to use greater than operator with date?

you have enlosed start_date with single quote causing it to become string, use backtick instead

SELECT * FROM `la_schedule` WHERE `start_date` > '2012-11-18';

Using SVG as background image

You can try removing the width and height attributes on the svg root element, adding preserveAspectRatio="none" viewBox="0 0 1024 800" instead. It makes a difference in Opera at least, assuming you wanted the svg to stretch to fill the entire region defined by the CSS styles.

How To Save Canvas As An Image With canvas.toDataURL()?

You cannot use the methods previously mentioned to download an image when running in Cordova. You will need to use the Cordova File Plugin. This will allow you to pick where to save it and leverage different persistence settings. Details here: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/

Alternatively, you can convert the image to base64 then store the string in localStorage but this will fill your quota pretty quickly if you have many images or high-res.

Querying date field in MongoDB with Mongoose

{ "date" : "1000000" } in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }

It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback) and if that works, you have a typing issue.

Create JSON object dynamically via JavaScript (Without concate strings)

This is what you need!

function onGeneratedRow(columnsResult)
{
    var jsonData = {};
    columnsResult.forEach(function(column) 
    {
        var columnName = column.metadata.colName;
        jsonData[columnName] = column.value;
    });
    viewData.employees.push(jsonData);
 }

T-SQL Subquery Max(Date) and Joins

In SQL Server 2005 and later use ROW_NUMBER():

SELECT * FROM 
    ( SELECT p.*,
        ROW_NUMBER() OVER(PARTITION BY Partid ORDER BY PriceDate DESC) AS rn
    FROM MyPrice AS p ) AS t
WHERE rn=1