Programs & Examples On #Library path

Change R default library path using .libPaths in Rprofile.site fails to work

I was looking into this because R was having issues installing into the default location and was instead just putting the packages into the temp folder. It turned out to be the latest update for Mcaffee Endpoint Security which apparently has issues with R. You can disable the threat protection while you install the packages and it will work properly.

Questions every good PHP Developer should be able to answer

What is wrong with the following code?

$a = 2;
function foo()
{
    $a = 3;
}
foo();
echo $a;

Is there a command to undo git init?

You can just delete .git. Typically:

rm -rf .git

Then, recreate as the right user.

How do I install cygwin components from the command line?

There is no tool specifically in the 'setup.exe' installer that offers the functionality of apt-get. There is, however, a command-line package installer for Cygwin that can be downloaded separately, but it is not entirely stable and relies on workarounds.

apt-cyg: http://github.com/transcode-open/apt-cyg

Check out the issues tab for the project to see the known problems.

Insert data through ajax into mysql database

Try this:

  $(document).on('click','#save',function(e) {
  var data = $("#form-search").serialize();
  $.ajax({
         data: data,
         type: "post",
         url: "insertmail.php",
         success: function(data){
              alert("Data Save: " + data);
         }
});
 });

and in insertmail.php:

<?php 
if(isset($_REQUEST))
{
        mysql_connect("localhost","root","");
mysql_select_db("eciticket_db");
error_reporting(E_ALL && ~E_NOTICE);

$email=$_POST['email'];
$sql="INSERT INTO newsletter_email(email) VALUES ('$email')";
$result=mysql_query($sql);
if($result){
echo "You have been successfully subscribed.";
}
}
?>

Don't use mysql_ it's deprecated.

another method:

Actually if your problem is null value inserted into the database then try this and here no need of ajax.

<?php
if($_POST['email']!="")
{
    mysql_connect("localhost","root","");
    mysql_select_db("eciticket_db");
    error_reporting(E_ALL && ~E_NOTICE);
    $email=$_POST['email'];
    $sql="INSERT INTO newsletter_email(email) VALUES ('$email')";
    $result=mysql_query($sql);
    if($result){
    //echo "You have been successfully subscribed.";
              setcookie("msg","You have been successfully subscribed.",time()+5,"/");
              header("location:yourphppage.php");
    }
     if(!$sql)
    die(mysql_error());
    mysql_close();
}
?>
    <?php if(isset($_COOKIE['msg'])){?>
       <span><?php echo $_COOKIE['msg'];setcookie("msg","",time()-5,"/");?></span> 
    <?php }?>
<form id="form-search" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
    <span><span class="style2">Enter you email here</span>:</span>
    <input name="email" type="email" id="email" required/>
    <input type="submit" value="subscribe" class="submit"/>
</form>

ng-repeat :filter by single field

If you want to filter on a grandchild (or deeper) of the given object, you can continue to build out your object hierarchy. For example, if you want to filter on 'thing.properties.title', you can do the following:

<div ng-repeat="thing in things | filter: { properties: { title: title_filter } }">

You can also filter on multiple properties of an object just by adding them to your filter object:

<div ng-repeat="thing in things | filter: { properties: { title: title_filter, id: id_filter } }">

Basic CSS - how to overlay a DIV with semi-transparent DIV on top

For a div-Element you could just set the opacity via a class to enable or disable the effect.

.mute-all {
   opacity: 0.4;
}

How can I find the product GUID of an installed MSI setup?

There is also a very helpful GUI tool called Product Browser which appears to be made by Microsoft or at least an employee of Microsoft.

It can be found on Github here Product Browser

I personally had a very easy time locating the GUID I needed with this.

creating triggers for After Insert, After Update and After Delete in SQL

(Update: overlooked a fault in the matter, I have corrected)

(Update2: I wrote from memory the code screwed up, repaired it)

(Update3: check on SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150)
    ,Questions nvarchar(100)
    ,Answer nvarchar(100)
    )

go

CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
        inner join deleted d on i.BusinessUnit = d.BusinessUnit
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
    FROM 
        deleted d
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

delete Derived_Values;

and then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


Record Count: 0;

BUSINESSUNIT    QUESTIONS   ANSWER
Updated Record -- After Update Trigger.BU1  Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1  Q11 A11
Updated Record -- After Update Trigger.BU1  Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1  Q12 A12
Updated Record -- After Update Trigger.BU2  Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2  Q21 A21
Updated Record -- After Update Trigger.BU2  Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2  Q22 A22

(Update4: If you want to sync: SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

CREATE TRIGGER trgAfterInsert ON  [Derived_Values]
FOR INSERT
AS  
begin
    insert
        [Derived_Values_Test]
        (BusinessUnit,Questions,Answer)
    SELECT 
        i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
end

go


CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    update
        [Derived_Values_Test]
    set
        --BusinessUnit = i.BusinessUnit
        --,Questions = i.Questions
        Answer = i.Answer
    from
        [Derived_Values]
        inner join inserted i 
    on
        [Derived_Values].BusinessUnit = i.BusinessUnit
        and
        [Derived_Values].Questions = i.Questions
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR DELETE
AS  
begin
    delete 
        [Derived_Values_Test]
    from
        [Derived_Values_Test]
        inner join deleted d 
    on
        [Derived_Values_Test].BusinessUnit = d.BusinessUnit
        and
        [Derived_Values_Test].Questions = d.Questions
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

--delete Derived_Values;

And then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

Getting "java.nio.file.AccessDeniedException" when trying to write to a folder

Delete .android folder cache files, Also delete the build folder manually from a directory and open android studio and run again.

enter image description here

'Class' does not contain a definition for 'Method'

I had the same problem. Turns out the project I was referencing did not get build. When I went to the build configuration manager in visual studio and enabled the reference project , the issue got resolved.

How to sort two lists (which reference each other) in the exact same way

You can use the zip() and sort() functions to accomplish this:

Python 2.6.5 (r265:79063, Jun 12 2010, 17:07:01)
[GCC 4.3.4 20090804 (release) 1] on cygwin
>>> list1 = [3,2,4,1,1]
>>> list2 = ['three', 'two', 'four', 'one', 'one2']
>>> zipped = zip(list1, list2)
>>> zipped.sort()
>>> slist1 = [i for (i, s) in zipped]
>>> slist1
[1, 1, 2, 3, 4]
>>> slist2 = [s for (i, s) in zipped]
>>> slist2
['one', 'one2', 'two', 'three', 'four']

Hope this helps

Why use deflate instead of gzip for text files served by Apache?

There shouldn't be any difference in gzip & deflate for decompression. Gzip is just deflate with a few dozen byte header wrapped around it including a checksum. The checksum is the reason for the slower compression. However when you're precompressing zillions of files you want those checksums as a sanity check in your filesystem. In addition you can utilize commandline tools to get stats on the file. For our site we are precompressing a ton of static data (the entire open directory, 13,000 games, autocomplete for millions of keywords, etc.) and we are ranked 95% faster than all websites by Alexa. Faxo Search. However, we do utilize a home grown proprietary web server. Apache/mod_deflate just didn't cut it. When those files are compressed into the filesystem not only do you take a hit for your file with the minimum filesystem block size but all the unnecessary overhead in managing the file in the filesystem that the webserver could care less about. Your concerns should be total disk footprint and access/decompression time and secondarily speed in being able to get this data precompressed. The footprint is important because even though disk space is cheap you want as much as possible to fit in the cache.

How to download Visual Studio Community Edition 2015 (not 2017)

The "official" way to get the vs2015 is to go to https://my.visualstudio.com/ ; join the " Visual Studio Dev Essentials" and then search the relevant file to download https://my.visualstudio.com/Downloads?q=Visual%20Studio%202015%20with%20Update%203

Wget output document and headers to STDOUT

This will not work:

wget -q -S -O - google.com 1>wget.txt 2>&1

since redirects are evaluated right to left, this sends html to wget.txt and the header to STDOUT:

wget -q -S -O - google.com 2>&1 1>wget.txt

What is managed or unmanaged code in programming?

Here is some text from MSDN about unmanaged code.

Some library code needs to call into unmanaged code (for example, native code APIs, such as Win32). Because this means going outside the security perimeter for managed code, due caution is required.

Here is some other complimentary explication about Managed code:

  • Code that is executed by the CLR.
  • Code that targets the common language runtime, the foundation of the .NET Framework, is known as managed code.
  • Managed code supplies the metadata necessary for the CLR to provide services such as memory management, cross-language integration, code access security, and automatic lifetime control of objects. All code based on IL executes as managed code.
  • Code that executes under the CLI execution environment.

For your problem:

I think it's because NUnit execute your code for UnitTesting and might have some part of it that is unmanaged. But I am not sure about it, so do not take this for gold. I am sure someone will be able to give you more information about it. Hope it helps!

Javascript for "Add to Home Screen" on iPhone?

The only way to add any book marks in MobileSafari (including ones on the home screen) is with the builtin UI, and that Apples does not provide anyway to do this from scripts within a page. In fact, I am pretty sure there is no mechanism for doing this on the desktop version of Safari either.

How to redirect page after click on Ok button on sweet alert?

_x000D_
_x000D_
setTimeout(function () { _x000D_
swal({_x000D_
  title: "Wow!",_x000D_
  text: "Message!",_x000D_
  type: "success",_x000D_
  confirmButtonText: "OK"_x000D_
},_x000D_
function(isConfirm){_x000D_
  if (isConfirm) {_x000D_
    window.location.href = "//stackoverflow.com";_x000D_
  }_x000D_
}); }, 1000);
_x000D_
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>_x000D_
  <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert-dev.js"></script>_x000D_
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.css">
_x000D_
_x000D_
_x000D_


Or you can use the build-in function timer, i.e.:

_x000D_
_x000D_
swal({_x000D_
  title: "Success!",_x000D_
  text: "Redirecting in 2 seconds.",_x000D_
  type: "success",_x000D_
  timer: 2000,_x000D_
  showConfirmButton: false_x000D_
}, function(){_x000D_
      window.location.href = "//stackoverflow.com";_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>_x000D_
  <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert-dev.js"></script>_x000D_
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.css">
_x000D_
_x000D_
_x000D_

Scale image to fit a bounding box

Another solution without background image and without the need for a container (though the max sizes of the bounding box must be known):

img{
  max-height: 100px;
  max-width: 100px;
  width: auto;    /* These two are added only for clarity, */
  height: auto;   /* as the default is auto anyway */
}


If a container's use is required, then the max-width and max-height can be set to 100%:

img {
    max-height: 100%;
    max-width: 100%;
    width: auto; /* These two are added only for clarity, */
    height: auto; /* as the default is auto anyway */
}

div.container {
    width: 100px;
    height: 100px;
}

For this you would have something like:

<table>
    <tr>
        <td>Lorem</td>
        <td>Ipsum<br />dolor</td>
        <td>
            <div class="container"><img src="image5.png" /></div>
        </td>
    </tr>
</table>

Android Studio - Unable to find valid certification path to requested target

For me it was my internet, I was working on restricted network

Working Copy Locked

I have experienced the same issues as you described. It appears to be a bug on Tortoise 1.7.3. I have reverted back to 1.7.2, executed a cleanup and an update. Now my SVN/Tortoise is working fine again

Does java.util.List.isEmpty() check if the list itself is null?

Invoking any method on any null reference will always result in an exception. Test if the object is null first:

List<Object> test = null;
if (test != null && !test.isEmpty()) {
    // ...
}

Alternatively, write a method to encapsulate this logic:

public static <T> boolean IsNullOrEmpty(Collection<T> list) {
    return list == null || list.isEmpty();
}

Then you can do:

List<Object> test = null;
if (!IsNullOrEmpty(test)) {
    // ...
}

Java String encoding (UTF-8)

This could be complicated way of doing

String newString = new String(oldString);

This shortens the String is the underlying char[] used is much longer.

However more specifically it will be checking that every character can be UTF-8 encoded.

There are some "characters" you can have in a String which cannot be encoded and these would be turned into ?

Any character between \uD800 and \uDFFF cannot be encoded and will be turned into '?'

String oldString = "\uD800";
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8");
System.out.println(newString.equals(oldString));

prints

false

What's a .sh file?

Typically a .sh file is a shell script which you can execute in a terminal. Specifically, the script you mentioned is a bash script, which you can see if you open the file and look in the first line of the file, which is called the shebang or magic line.

How to set some xlim and ylim in Seaborn lmplot facetgrid

You need to get hold of the axes themselves. Probably the cleanest way is to change your last row:

lm = sns.lmplot('X','Y',df,col='Z',sharex=False,sharey=False)

Then you can get hold of the axes objects (an array of axes):

axes = lm.axes

After that you can tweak the axes properties

axes[0,0].set_ylim(0,)
axes[0,1].set_ylim(0,)

creates:

enter image description here

Get the date (a day before current time) in Bash

You could do a simple calculation, pimped with an regex, if the chosen date format is 'YYYYMM':

echo $(($(date +"%Y%m") - 1)) | sed -e 's/99$/12/'

In January of 2020 it will return 201912 ;-) But, it's only a workaround, when date does not have calculation options and other dateinterpreter options (e.g. using perl) not available ;-)

ConvergenceWarning: Liblinear failed to converge, increase the number of iterations

I reached the point that I set, up to max_iter=1200000 on my LinearSVC classifier, but still the "ConvergenceWarning" was still present. I fix the issue by just setting dual=False and leaving max_iter to its default.

With LogisticRegression(solver='lbfgs') classifier, you should increase max_iter. Mine have reached max_iter=7600 before the "ConvergenceWarning" disappears when training with large dataset's features.

Microsoft Advertising SDK doesn't deliverer ads

I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.

Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled

Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is

  1. Remove the XAML for the ad
  2. Remove the xmlns declaration (usually at the top of the page, but sometimes will be declared in the ad itself)
  3. Remove the bad DLL (the one ending in .SDK )
  4. Do a Clean and then Build (clean out anything remaining from the DLL)
  5. Add the xmlns reference (actual reference is below)
  6. Add the ad to the page (example below)

Here is the xmlns reference:

xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI" 

Then the ad itself:

<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480"                    AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/> 

HTML image not showing in Gmail

My issue was similar. This is what my experience has been on testing the IMG tag on gmail (assuming most of the organization's would have a dev qa and prod server.)

I had to send emails to customers on their personal email id's and we could see that gmail would add something of its own like following to src attribute of img tag. Now when we were sending these images from our dev environment they would never render on gmail and we were always curious why?

https://ci7.googleusercontent.com/proxy/AEF54znasdUhUYhuHuHuhHkHfT7u2w5zsOnWJ7k1MwrKe8pP69hY9W9eo8_n6-tW0KdSIaG4qaBEbcXue74nbVBysdfqweAsNNmmmJyTB-JQzcgn1j=s0-d-e2-ft#https://www.prodserver.com/Folder1/Images/OurImage.PNG

so an image sent to my gmail id as following never worked for me

<img src="https://ci7.googleuser....Blah.Blah..https://devserver.com/Folder1/Images/OurImage.PNG">

and our dev server we can't render this image by hitting following URL on Chrome(or any browser).

https://www.devserver.com/folder1/folder2/myactualimage.jpg

now as long as the src has www on it worked all the time and we didnt had to add any other attributes.

<img src="https://www.**prodserver**.com/folder1/folder2/myactualimage.jpg">

SSH SCP Local file to Remote in Terminal Mac Os X

Just to clarify the answer given by JScoobyCed, the scp command cannot copy files to directories that require administrative permission. However, you can use the scp command to copy to directories that belong to the remote user.

So, to copy to a directory that requires root privileges, you must first copy that file to a directory belonging to the remote user using the scp command. Next, you must login to the remote account using ssh. Once logged in, you can then move the file to the directory of your choosing by using the sudo mv command. In short, the commands to use are as follows:

Using scp, copy file to a directory in the remote user's account, for example the Documents directory:

scp /path/to/your/local/file remoteUser@some_address:/home/remoteUser/Documents

Next, login to the remote user's account using ssh and then move the file to a restricted directory using sudo:

ssh remoteUser@some_address
sudo mv /home/remoteUser/Documents/file /var/www

How to programmatically set drawableLeft on Android button?

If you are using drawableStart, drawableEnd, drawableTop or drawableBottom; you must use "setCompoundDrawablesRelativeWithIntrinsicBounds"

edittext.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, R.drawable.anim_search_to_close, 0)

QR Code encoding and decoding using zxing

this is my working example Java code to encode QR code using ZXing with UTF-8 encoding, please note: you will need to change the path and utf8 data to your path and language characters

package com.mypackage.qr;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.Hashtable;

import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.*;

public class CreateQR {

public static void main(String[] args)
{
    Charset charset = Charset.forName("UTF-8");
    CharsetEncoder encoder = charset.newEncoder();
    byte[] b = null;
    try {
        // Convert a string to UTF-8 bytes in a ByteBuffer
        ByteBuffer bbuf = encoder.encode(CharBuffer.wrap("utf 8 characters - i used hebrew, but you should write some of your own language characters"));
        b = bbuf.array();
    } catch (CharacterCodingException e) {
        System.out.println(e.getMessage());
    }

    String data;
    try {
        data = new String(b, "UTF-8");
        // get a byte matrix for the data
        BitMatrix matrix = null;
        int h = 100;
        int w = 100;
        com.google.zxing.Writer writer = new MultiFormatWriter();
        try {
            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(2);
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            matrix = writer.encode(data,
            com.google.zxing.BarcodeFormat.QR_CODE, w, h, hints);
        } catch (com.google.zxing.WriterException e) {
            System.out.println(e.getMessage());
        }

        // change this path to match yours (this is my mac home folder, you can use: c:\\qr_png.png if you are on windows)
                String filePath = "/Users/shaybc/Desktop/OutlookQR/qr_png.png";
        File file = new File(filePath);
        try {
            MatrixToImageWriter.writeToFile(matrix, "PNG", file);
            System.out.println("printing to " + file.getAbsolutePath());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    } catch (UnsupportedEncodingException e) {
        System.out.println(e.getMessage());
    }
}

}

Java: Date from unix timestamp

tl;dr

Instant.ofEpochSecond( 1_280_512_800L )

2010-07-30T18:00:00Z

java.time

The new java.time framework built into Java 8 and later is the successor to Joda-Time.

These new classes include a handy factory method to convert a count of whole seconds from epoch. You get an Instant, a moment on the timeline in UTC with up to nanoseconds resolution.

Instant instant = Instant.ofEpochSecond( 1_280_512_800L );

instant.toString(): 2010-07-30T18:00:00Z

See that code run live at IdeOne.com.

Table of date-time types in Java, both modern and legacy

Asia/Kabul or Asia/Tehran time zones ?

You reported getting a time-of-day value of 22:30 instead of the 18:00 seen here. I suspect your PHP utility is implicitly applying a default time zone to adjust from UTC. My value here is UTC, signified by the Z (short for Zulu, means UTC). Any chance your machine OS or PHP is set to Asia/Kabul or Asia/Tehran time zones? I suppose so as you report IRST in your output which apparently means Iran time. Currently in 2017 those are the only zones operating with a summer time that is four and a half hours ahead of UTC.

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

If you want to see your moment through the lens of a particular region's time zone, apply a ZoneId to get a ZonedDateTime. Still the same simultaneous moment, but seen as a different wall-clock time.

ZoneId z = ZoneId.of( "Asia/Tehran" ) ;
ZonedDateTime zdt = instant.atZone( z );  // Same moment, same point on timeline, but seen as different wall-clock time.

2010-07-30T22:30+04:30[Asia/Tehran]

Converting from java.time to legacy classes

You should stick with the new java.time classes. But you can convert to old if required.

java.util.Date date = java.util.Date.from( instant );

Joda-Time

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

FYI, the constructor for a Joda-Time DateTime is similar: Multiply by a thousand to produce a long (not an int!).

DateTime dateTime = new DateTime( ( 1_280_512_800L * 1000_L ), DateTimeZone.forID( "Europe/Paris" ) );

Best to avoid the notoriously troublesome java.util.Date and .Calendar classes. But if you must use a Date, you can convert from Joda-Time.

java.util.Date date = dateTime.toDate();

About java.time

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

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

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

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

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to POST raw whole JSON in the body of a Retrofit request?

For more clarity on the answers given here, this is how you can use the extension functions. This is only if you are using Kotlin

If you are using com.squareup.okhttp3:okhttp:4.0.1 the older methods of creating objects of MediaType and RequestBody have been deprecated and cannot be used in Kotlin.

If you want to use the extension functions to get a MediaType object and a ResponseBody object from your strings, firstly add the following lines to the class in which you expect to use them.

import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody

You can now directly get an object of MediaType this way

val mediaType = "application/json; charset=utf-8".toMediaType()

To get an object of RequestBody first convert the JSONObject you want to send to a string this way. You have to pass the mediaType object to it.

val requestBody = myJSONObject.toString().toRequestBody(mediaType)

Hashing a string with Sha256

In the PHP version you can send 'true' in the last parameter, but the default is 'false'. The following algorithm is equivalent to the default PHP's hash function when passing 'sha256' as the first parameter:

public static string GetSha256FromString(string strData)
    {
        var message = Encoding.ASCII.GetBytes(strData);
        SHA256Managed hashString = new SHA256Managed();
        string hex = "";

        var hashValue = hashString.ComputeHash(message);
        foreach (byte x in hashValue)
        {
            hex += String.Format("{0:x2}", x);
        }
        return hex;
    }

How to get last inserted id?

There are all sorts of ways to get the Last Inserted ID but the easiest way I have found is by simply retrieving it from the TableAdapter in the DataSet like so:

<Your DataTable Class> tblData = new <Your DataTable Class>();
<Your Table Adapter Class> tblAdpt = new <Your Table Adapter Class>();

/*** Initialize and update Table Data Here ***/

/*** Make sure to call the EndEdit() method ***/
/*** of any Binding Sources before update ***/
<YourBindingSource>.EndEdit();

//Update the Dataset
tblAdpt.Update(tblData);

//Get the New ID from the Table Adapter
long newID = tblAdpt.Adapter.InsertCommand.LastInsertedId;

Hope this Helps ...

How do I log a Python error with debug information?

A little bit of decorator treatment (very loosely inspired by the Maybe monad and lifting). You can safely remove Python 3.6 type annotations and use an older message formatting style.

fallible.py

from functools import wraps
from typing import Callable, TypeVar, Optional
import logging


A = TypeVar('A')


def fallible(*exceptions, logger=None) \
        -> Callable[[Callable[..., A]], Callable[..., Optional[A]]]:
    """
    :param exceptions: a list of exceptions to catch
    :param logger: pass a custom logger; None means the default logger, 
                   False disables logging altogether.
    """
    def fwrap(f: Callable[..., A]) -> Callable[..., Optional[A]]:

        @wraps(f)
        def wrapped(*args, **kwargs):
            try:
                return f(*args, **kwargs)
            except exceptions:
                message = f'called {f} with *args={args} and **kwargs={kwargs}'
                if logger:
                    logger.exception(message)
                if logger is None:
                    logging.exception(message)
                return None

        return wrapped

    return fwrap

Demo:

In [1] from fallible import fallible

In [2]: @fallible(ArithmeticError)
    ...: def div(a, b):
    ...:     return a / b
    ...: 
    ...: 

In [3]: div(1, 2)
Out[3]: 0.5

In [4]: res = div(1, 0)
ERROR:root:called <function div at 0x10d3c6ae8> with *args=(1, 0) and **kwargs={}
Traceback (most recent call last):
  File "/Users/user/fallible.py", line 17, in wrapped
    return f(*args, **kwargs)
  File "<ipython-input-17-e056bd886b5c>", line 3, in div
    return a / b

In [5]: repr(res)
'None'

You can also modify this solution to return something a bit more meaningful than None from the except part (or even make the solution generic, by specifying this return value in fallible's arguments).

Could not open input file: artisan

If you project is at /home/forge/laravel-project/

You can properly execute your artisan like this

php /home/forge/laravel-project/artisan ...

what is the difference between GROUP BY and ORDER BY in sql

  1. GROUP BY will aggregate records by the specified column which allows you to perform aggregation functions on non-grouped columns (such as SUM, COUNT, AVG, etc.). ORDER BY alters the order in which items are returned.
  2. If you do SELECT IsActive, COUNT(*) FROM Customers GROUP BY IsActive you get a count of active and inactive customers. The group by aggregated the results based on the field you specified. If you do SELECT * FROM Customers ORDER BY Name then you get the result list sorted by the customer’s name.
  3. If you GROUP, the results are not necessarily sorted; although in many cases they may come out in an intuitive order, that's not guaranteed by the GROUP clause. If you want your groups sorted, always use an explicitly ORDER BY after the GROUP BY.
  4. Grouped data cannot be filtered by WHERE clause. Order data can be filtered by WHERE clause.

Select NOT IN multiple columns

You should probably use NOT EXISTS for multiple columns.

Can constructors throw exceptions in Java?

Yes, they can throw exceptions. If so, they will only be partially initialized and if non-final, subject to attack.

The following is from the Secure Coding Guidelines 2.0.

Partially initialized instances of a non-final class can be accessed via a finalizer attack. The attacker overrides the protected finalize method in a subclass, and attempts to create a new instance of that subclass. This attempt fails (in the above example, the SecurityManager check in ClassLoader's constructor throws a security exception), but the attacker simply ignores any exception and waits for the virtual machine to perform finalization on the partially initialized object. When that occurs the malicious finalize method implementation is invoked, giving the attacker access to this, a reference to the object being finalized. Although the object is only partially initialized, the attacker can still invoke methods on it (thereby circumventing the SecurityManager check).

How does Java import work?

The classes which you are importing have to be on the classpath. So either the users of your Applet have to have the libraries in the right place or you simply provide those libraries by including them in your jar file. For example like this: Easiest way to merge a release into one JAR file

T-SQL: Selecting rows to delete via joins

Yes you can. Example :

DELETE TableA 
FROM TableA AS a
INNER JOIN TableB AS b
ON a.BId = b.BId
WHERE [filter condition]

Java random numbers using a seed

If you're giving the same seed, that's normal. That's an important feature allowing tests.

Check this to understand pseudo random generation and seeds:

Pseudorandom number generator

A pseudorandom number generator (PRNG), also known as a deterministic random bit generator DRBG, is an algorithm for generating a sequence of numbers that approximates the properties of random numbers. The sequence is not truly random in that it is completely determined by a relatively small set of initial values, called the PRNG's state, which includes a truly random seed.

If you want to have different sequences (the usual case when not tuning or debugging the algorithm), you should call the zero argument constructor which uses the nanoTime to try to get a different seed every time. This Random instance should of course be kept outside of your method.

Your code should probably be like this:

private Random generator = new Random();
double randomGenerator() {
    return generator.nextDouble()*0.5;
}

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

The jersey-container-servlet actually uses the jersey-container-servlet-core dependency. But if you use maven, that does not really matter. If you just define the jersey-container-servlet usage, it will automatically download the dependency as well.

But for those who add jar files to their project manually (i.e. without maven) It is important to know that you actually need both jar files. The org.glassfish.jersey.servlet.ServletContainer class is actually part of the core dependency.

How to set image name in Dockerfile?

Here is another version if you have to reference a specific docker file:

version: "3"
services:
  nginx:
    container_name: nginx
    build:
      context: ../..
      dockerfile: ./docker/nginx/Dockerfile
    image: my_nginx:latest

Then you just run

docker-compose build

Find directory name with wildcard or similar to "like"

find supports wildcard matches, just add a *:

find / -type d -name "ora10*"

Webdriver Screenshot

Use driver.save_screenshot('/path/to/file') or driver.get_screenshot_as_file('/path/to/file'):

import selenium.webdriver as webdriver
import contextlib

@contextlib.contextmanager
def quitting(thing):
    yield thing
    thing.quit()

with quitting(webdriver.Firefox()) as driver:
    driver.implicitly_wait(10)
    driver.get('http://www.google.com')
    driver.get_screenshot_as_file('/tmp/google.png') 
    # driver.save_screenshot('/tmp/google.png')

Python FileNotFound

try block should be around open. Not around prompt.

while True:
    prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
    try:
        sudoku = open(prompt, 'r').readlines()
    except FileNotFoundError:
        print("Wrong file or file path")
    else:
        break

How to install "ifconfig" command in my ubuntu docker image?

Please use the below command to get the IP address of the running container.

$ ip addr

Example-:

root@4c712d05922b:/# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
247: eth0@if248: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 02:42:ac:11:00:06 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.17.0.6/16 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::42:acff:fe11:6/64 scope link
       valid_lft forever preferred_lft forever

How can a file be copied?

In Python, you can copy the files using


import os
import shutil
import subprocess

1) Copying files using shutil module

shutil.copyfile signature

shutil.copyfile(src_file, dest_file, *, follow_symlinks=True)

# example    
shutil.copyfile('source.txt', 'destination.txt')

shutil.copy signature

shutil.copy(src_file, dest_file, *, follow_symlinks=True)

# example
shutil.copy('source.txt', 'destination.txt')

shutil.copy2 signature

shutil.copy2(src_file, dest_file, *, follow_symlinks=True)

# example
shutil.copy2('source.txt', 'destination.txt')  

shutil.copyfileobj signature

shutil.copyfileobj(src_file_object, dest_file_object[, length])

# example
file_src = 'source.txt'  
f_src = open(file_src, 'rb')

file_dest = 'destination.txt'  
f_dest = open(file_dest, 'wb')

shutil.copyfileobj(f_src, f_dest)  

2) Copying files using os module

os.popen signature

os.popen(cmd[, mode[, bufsize]])

# example
# In Unix/Linux
os.popen('cp source.txt destination.txt') 

# In Windows
os.popen('copy source.txt destination.txt')

os.system signature

os.system(command)


# In Linux/Unix
os.system('cp source.txt destination.txt')  

# In Windows
os.system('copy source.txt destination.txt')

3) Copying files using subprocess module

subprocess.call signature

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

# example (WARNING: setting `shell=True` might be a security-risk)
# In Linux/Unix
status = subprocess.call('cp source.txt destination.txt', shell=True) 

# In Windows
status = subprocess.call('copy source.txt destination.txt', shell=True)

subprocess.check_output signature

subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)

# example (WARNING: setting `shell=True` might be a security-risk)
# In Linux/Unix
status = subprocess.check_output('cp source.txt destination.txt', shell=True)

# In Windows
status = subprocess.check_output('copy source.txt destination.txt', shell=True)

How can change width of dropdown list?

If you want to control the width of the list that drops down, you can do it as follows.

CSS

#wgtmsr option {
    width: 50px;
}

Convert multidimensional array into single array

Multi dimensional array to single array with one line code !!! Enjoy the code.

$array=[1=>[2,5=>[4,2],[7,8=>[3,6]],5],4];
$arr=[];
array_walk_recursive($array, function($k){global $arr; $arr[]=$k;});
print_r($arr);

...Enjoy the code.

Getting JavaScript object key list

Using ES6, you can use forEach to iterate over the Keys of an Object. To get all the keys you can use Object.keys which returns all the keys in an Object

Object.keys(obj).forEach(function(keyValue, index, map) { 
  console.log(keyValue); 
});

Short hand of the above snippet would be, which only takes one parameter

Object.keys(obj).forEach(function(keyValue) { 
  console.log(keyValue); 
});

How to jquery alert confirm box "yes" & "no"

This plugin can help you,

craftpip/jquery-confirm

Its easy to setup and has great set of features.

$.confirm({
    title: 'Confirm!',
    content: 'Simple confirm!',
    buttons: {
        confirm: function () {
            $.alert('Confirmed!');
        },
        cancel: function () {
            $.alert('Canceled!');
        },
        somethingElse: {
            text: 'Something else',
            btnClass: 'btn-blue',
            keys: ['enter', 'shift'], // trigger when enter or shift is pressed
            action: function(){
                $.alert('Something else?');
            }
        }
    }
});

Other than this you can also load your content from a remote url.

$.confirm({
    content: 'url:hugedata.html' // location of your hugedata.html.
});

Read CSV file column by column

Finds all files in folder and write that data to ArrayList row.

Initialize

ArrayList<ArrayList<String>> row=new ArrayList<ArrayList<String>>();
BufferedReader br=null;

For Accessing row

for(ArrayList<String> data:row){
data.get(col no); 
}
or row.get(0).get(0) // getting first row first col

Functions that reads all files from folders and concatenate them row.

static void readData(){
String path="C:\\Users\\Galaxy Computers\\Desktop\\Java project\\Nasdaq\\";
File files=new File(path);
String[] list=files.list();

try {
        String sCurrentLine;
       char check;
       for(String filename:list){ 
        br = new BufferedReader(new FileReader(path+filename));
        br.readLine();//If file contains uneccessary first line.
        while ((sCurrentLine = br.readLine()) != null) {

           row.add(splitLine(sCurrentLine));
        }
        }
        }

    } catch (IOException e) {
        e.printStackTrace();
    } 
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }


   static ArrayList<String> splitLine(String line){
   String[] ar=line.split(",");
   ArrayList<String> d=new ArrayList<String>();
   for(String data:ar){
    d.add(data);
   }

   return d; 
   } 

Where is adb.exe in windows 10 located?

Got it to work go to the local.properties file under your build.gradle files to find out the PATH to your SDK, from the SDK location go into the platform-tools folder and look and see if you have adb.exe.

If not go to http://adbshell.com/downloads and download ADB KITS. Copy the zip folder's contents into the platform-tools folder and re-make your project.

I didn't need to update the PATH in the Extended Controls Settings section on the emulator, I left Use detected ADB location settings on. Hope this makes this faster for you !

Using .otf fonts on web browsers

You can implement your OTF font using @font-face like:

@font-face {
    font-family: GraublauWeb;
    src: url("path/GraublauWeb.otf") format("opentype");
}

@font-face {
    font-family: GraublauWeb;
    font-weight: bold;
    src: url("path/GraublauWebBold.otf") format("opentype");
}

// Edit: OTF now works in most browsers, see comments

However if you want to support a wide variety of browsers i would recommend you to switch to WOFF and TTF font types. WOFF type is implemented by every major desktop browser, while the TTF type is a fallback for older Safari, Android and iOS browsers. If your font is a free font, you could convert your font using for example a transfonter.

@font-face {
    font-family: GraublauWeb;
    src: url("path/GraublauWebBold.woff") format("woff"), url("path/GraublauWebBold.ttf")  format("truetype");
}

If you want to support nearly every browser that is still out there (not necessary anymore IMHO), you should add some more font-types like:

@font-face {
    font-family: GraublauWeb;
    src: url("webfont.eot"); /* IE9 Compat Modes */
    src: url("webfont.eot?#iefix") format("embedded-opentype"), /* IE6-IE8 */
         url("webfont.woff") format("woff"), /* Modern Browsers */
         url("webfont.ttf")  format("truetype"), /* Safari, Android, iOS */
         url("webfont.svg#svgFontName") format("svg"); /* Legacy iOS */
}

You can read more about why all these types are implemented and their hacks here. To get a detailed view of which file-types are supported by which browsers, see:

@font-face Browser Support

EOT Browser Support

WOFF Browser Support

TTF Browser Support

SVG-Fonts Browser Support

hope this helps

Combine multiple JavaScript files into one JS file

On linux you can use simple shell script https://github.com/dfsq/compressJS.sh to combine multiple javascript files into the single one. It makes use of the Closure Compiler online service so the resulting script is also effectively compressed.

$ ./compressJS.sh some-script.js another-sctipt.js onemore.js

How to add http:// if it doesn't exist in the URL

A modified version of @nickf code:

function addhttp($url) {
    if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
        $url = "http://" . $url;
    }
    return $url;
}

Recognizes ftp://, ftps://, http:// and https:// in a case insensitive way.

How to use a different version of python during NPM install?

for quick one time use this works, npm install --python="c:\python27"

error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)' -- Missing /var/run/mysqld/mysqld.sock

I would also check the mysql configuration. I was running into this problem with my own server but I was a bit too hasty and misconfigured the innodb_buffer_pool_size for my machine.

innodb_buffer_pool_size = 4096M

It usually runs fine up to 2048 but I guess I don't have the memory necessary to support 4 gigs.

I imagine this could also happen with other mysql configuration settings.

Javascript array search and remove string?

DEMO

You need to find the location of what you're looking for with .indexOf() then remove it with .splice()

function remove(arr, what) {
    var found = arr.indexOf(what);

    while (found !== -1) {
        arr.splice(found, 1);
        found = arr.indexOf(what);
    }
}

var array = new Array();
array.push("A");
array.push("B");
array.push("C");
 ?   
remove(array, 'B');
alert(array)????;

This will take care of all occurrences.

Android: Proper Way to use onBackPressed() with Toast

I would implement a dialog asking the user if they wanted to exit and then call super.onBackPressed() if they did.

@Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
        .setTitle("Really Exit?")
        .setMessage("Are you sure you want to exit?")
        .setNegativeButton(android.R.string.no, null)
        .setPositiveButton(android.R.string.yes, new OnClickListener() {

            public void onClick(DialogInterface arg0, int arg1) {
                WelcomeActivity.super.onBackPressed();
            }
        }).create().show();
}

In the above example, you'll need to replace WelcomeActivity with the name of your activity.

How can I print a quotation mark in C?

You have to use escaping of characters. It's a solution of this chicken-and-egg problem: how do I write a ", if I need it to terminate a string literal? So, the C creators decided to use a special character that changes treatment of the next char:

printf("this is a \"quoted string\"");

Also you can use '\' to input special symbols like "\n", "\t", "\a", to input '\' itself: "\\" and so on.

How do I run Google Chrome as root?

Just replace following line

exec -a "$0" "$HERE/chrome" "$@"

with

exec -a "$0" "$HERE/chrome" "$@" --user-data-dir 

all things will be right.

How to find EOF through fscanf?

while (fscanf(input,"%s",arr) != EOF && count!=7) {
  len=strlen(arr); 
  count++; 
}

How can I show/hide a specific alert with twitter bootstrap?

Use the id selector #

$('#passwordsNoMatchRegister').show();

nodejs get file name from absolute path?

For those interested in removing extension from filename, you can use https://nodejs.org/api/path.html#path_path_basename_path_ext

path.basename('/foo/bar/baz/asdf/quux.html', '.html');

Firebase FCM force onTokenRefresh() to be called

FirebaseMessaging.getInstance().getToken().addOnSuccessListener(new 
OnSuccessListener<String>() {
    @Override
    public void onSuccess(String newToken) {
        ....
    }
});

How to convert View Model into JSON object in ASP.NET MVC?

@Html.Raw(Json.Encode(object)) can be used to convert the View Modal Object to JSON

How do I access my SSH public key?

If you are using Windows PowerShell, the easiest way is to:

cat ~/.ssh/id_<key-type-here>.pub | clip

That will copy the key to your clipboard for easy pasting.

So, in my instance, I use ed25519 since RSA is now fairly hackable:

cat ~/.ssh/id_ed25519.pub | clip

Because I find myself doing this a lot, I created a function and set a simple alias I could remember in my PowerShell profile (learn more about PowerShell profiles here. Just add this to your Microsoft.PowerShell_profile.ps1:

function Copy-SSHKey {
    Get-Content ~/.ssh/id_ed25519.pub | clip
}

Set_Alias -Name sshkey -Value Copy-SSHKey

Then, in a PowerShell console, run . $profile to load the functions. Then from now on all you will need to do is run sshkey, and then paste the key into wherever you need via the clipboard.

Moving up one directory in Python

Although this is not exactly what OP meant as this is not super simple, however, when running scripts from Notepad++ the os.getcwd() method doesn't work as expected. This is what I would do:

import os

# get real current directory (determined by the file location)
curDir, _ = os.path.split(os.path.abspath(__file__))

print(curDir) # print current directory

Define a function like this:

def dir_up(path,n): # here 'path' is your path, 'n' is number of dirs up you want to go
    for _ in range(n):
        path = dir_up(path.rpartition("\\")[0], 0) # second argument equal '0' ensures that 
                                                        # the function iterates proper number of times
    return(path)

The use of this function is fairly simple - all you need is your path and number of directories up.

print(dir_up(curDir,3)) # print 3 directories above the current one

The only minus is that it doesn't stop on drive letter, it just will show you empty string.

jQuery: Uncheck other checkbox on one checked

you could use class for all your checkboxes, and do:

$(".check_class").click(function() {
  $(".check_class").attr("checked", false); //uncheck all checkboxes
  $(this).attr("checked", true);  //check the clicked one
});

Android: remove left margin from actionbar's custom layout

Just Modify your styles.xml

<!-- ActionBar styles -->
    <style name="MyActionBar" parent="Widget.AppCompat.ActionBar">
        <item name="contentInsetStart">0dp</item>
        <item name="contentInsetEnd">0dp</item>
    </style>

How to get device make and model on iOS?

Kotlin Native:

memScoped {
            val q = alloc<utsname>()
            uname(q.ptr)
            val identifier = NSString.stringWithCString(q.machine, encoding = NSUTF8StringEncoding)
        }

Clicking submit button of an HTML form by a Javascript code

You can do :

document.forms["loginForm"].submit()

But this won't call the onclick action of your button, so you will need to call it by hand.

Be aware that you must use the name of your form and not the id to access it.

Counting unique / distinct values by group in a data frame

This is a simple solution with the function aggregate:

aggregate(order_no ~ name, myvec, function(x) length(unique(x)))

Including external jar-files in a new jar-file build with Ant

Two options, either reference the new jars in your classpath or unpack all classes in the enclosing jars and re-jar the whole lot! As far as I know packaging jars within jars is not recommeneded and you'll forever have the class not found exception!

Get a random item from a JavaScript array

If you really must use jQuery to solve this problem (NB: you shouldn't):

(function($) {
    $.rand = function(arg) {
        if ($.isArray(arg)) {
            return arg[$.rand(arg.length)];
        } else if (typeof arg === "number") {
            return Math.floor(Math.random() * arg);
        } else {
            return 4;  // chosen by fair dice roll
        }
    };
})(jQuery);

var items = [523, 3452, 334, 31, ..., 5346];
var item = jQuery.rand(items);

This plugin will return a random element if given an array, or a value from [0 .. n) given a number, or given anything else, a guaranteed random value!

For extra fun, the array return is generated by calling the function recursively based on the array's length :)

Working demo at http://jsfiddle.net/2eyQX/

Vertical dividers on horizontal UL menu

.last { border-right: none

.last { border-right: none !important; }

How to resize JLabel ImageIcon?

Resizing the icon is not straightforward. You need to use Java's graphics 2D to scale the image. The first parameter is a Image class which you can easily get from ImageIcon class. You can use ImageIcon class to load your image file and then simply call getter method to get the image.

private Image getScaledImage(Image srcImg, int w, int h){
    BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = resizedImg.createGraphics();

    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(srcImg, 0, 0, w, h, null);
    g2.dispose();

    return resizedImg;
}

PHP to write Tab Characters inside a file?

The tab character is \t. Notice the use of " instead of '.

$chunk = "abc\tdef\tghi";

PHP Strings - Double quoted

If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:

...

\t horizontal tab (HT or 0x09 (9) in ASCII)


Also, let me recommend the fputcsv() function which is for the purpose of writing CSV files.

How to use double or single brackets, parentheses, curly braces

The difference between test, [ and [[ is explained in great details in the BashFAQ.

To cut a long story short: test implements the old, portable syntax of the command. In almost all shells (the oldest Bourne shells are the exception), [ is a synonym for test (but requires a final argument of ]). Although all modern shells have built-in implementations of [, there usually still is an external executable of that name, e.g. /bin/[.

[[ is a new improved version of it, which is a keyword, not a program. This has beneficial effects on the ease of use, as shown below. [[ is understood by KornShell and BASH (e.g. 2.03), but not by the older POSIX or BourneShell.

And the conclusion:

When should the new test command [[ be used, and when the old one [? If portability to the BourneShell is a concern, the old syntax should be used. If on the other hand the script requires BASH or KornShell, the new syntax is much more flexible.

Mysql Compare two datetime fields

The query you want to show as an example is:

SELECT * FROM temp WHERE mydate > '2009-06-29 16:00:44';

04:00:00 is 4AM, so all the results you're displaying come after that, which is correct.

If you want to show everything after 4PM, you need to use the correct (24hr) notation in your query.

To make things a bit clearer, try this:

SELECT mydate, DATE_FORMAT(mydate, '%r') FROM temp;

That will show you the date, and its 12hr time.

Multiple FROMs - what it means

The first answer is too complex, historic, and uninformative for my tastes.


It's actually rather simple. Docker provides for a functionality called multi-stage builds the basic idea here is to,

  • Free you from having to manually remove what you don't want, by forcing you to whitelist what you do want,
  • Free resources that would otherwise be taken up because of Docker's implementation.

Let's start with the first. Very often with something like Debian you'll see.

RUN apt-get update \ 
  && apt-get dist-upgrade \
  && apt-get install <whatever> \
  && apt-get clean

We can explain all of this in terms of the above. The above command is chained together so it represents a single change with no intermediate Images required. If it was written like this,

RUN apt-get update ;
RUN apt-get dist-upgrade;
RUN apt-get install <whatever>;
RUN apt-get clean;

It would result in 3 more temporary intermediate Images. Having it reduced to one image, there is one remaining problem: apt-get clean doesn't clean up artifacts used in the install. If a Debian maintainer includes in his install a script that modifies the system that modification will also be present in the final solution (see something like pepperflashplugin-nonfree for an example of that).

By using a multi-stage build you get all the benefits of a single changed action, but it will require you to manually whitelist and copy over files that were introduced in the temporary image using the COPY --from syntax documented here. Moreover, it's a great solution where there is no alternative (like an apt-get clean), and you would otherwise have lots of un-needed files in your final image.

See also

React : difference between <Route exact path="/" /> and <Route path="/" />

Take a look here: https://reacttraining.com/react-router/core/api/Route/exact-bool

exact: bool

When true, will only match if the path matches the location.pathname exactly.

**path**    **location.pathname**   **exact**   **matches?**

/one        /one/two                true        no
/one        /one/two                false       yes

Automatically accept all SDK licences

Turns out if you didn't install any SDK, Android Studio also shown "you haven't accept the license"...Such deceiving message, normal people would assume it implied SDK were already installed but anyway. In the Studio's SDK manager, you can just manually select the missing sdk to download and install and it handles license too. You just need to restart the Android Studio.

Here is a YT video showing your where SDK manager is.

A general tree implementation?

anytree

I recommend https://pypi.python.org/pypi/anytree

Example

from anytree import Node, RenderTree

udo = Node("Udo")
marc = Node("Marc", parent=udo)
lian = Node("Lian", parent=marc)
dan = Node("Dan", parent=udo)
jet = Node("Jet", parent=dan)
jan = Node("Jan", parent=dan)
joe = Node("Joe", parent=dan)

print(udo)
Node('/Udo')
print(joe)
Node('/Udo/Dan/Joe')

for pre, fill, node in RenderTree(udo):
    print("%s%s" % (pre, node.name))
Udo
+-- Marc
¦   +-- Lian
+-- Dan
    +-- Jet
    +-- Jan
    +-- Joe

print(dan.children)
(Node('/Udo/Dan/Jet'), Node('/Udo/Dan/Jan'), Node('/Udo/Dan/Joe'))

Features

anytree has also a powerful API with:

  • simple tree creation
  • simple tree modification
  • pre-order tree iteration
  • post-order tree iteration
  • resolve relative and absolute node paths
  • walking from one node to an other.
  • tree rendering (see example above)
  • node attach/detach hookups

How can I set Image source with base64

Your problem are the cr (carriage return)

http://jsfiddle.net/NT9KB/210/

you can use:

document.getElementById("img").src = "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="

Running SSH Agent when starting Git Bash on Windows

In a git bash session, you can add a script to ~/.profile or ~/.bashrc (with ~ being usually set to %USERPROFILE%), in order for said session to launch automatically the ssh-agent. If the file doesn't exist, just create it.

This is what GitHub describes in "Working with SSH key passphrases".

The "Auto-launching ssh-agent on Git for Windows" section of that article has a robust script that checks if the agent is running or not. Below is just a snippet, see the GitHub article for the full solution.

# This is just a snippet. See the article above.
if ! agent_is_running; then
    agent_start
    ssh-add
elif ! agent_has_keys; then
    ssh-add
fi

Other Resources:

"Getting ssh-agent to work with git run from windows command shell" has a similar script, but I'd refer to the GitHub article above primarily, which is more robust and up to date.

Casting string to enum

As an extra, you can take the Enum.Parse answers already provided and put them in an easy-to-use static method in a helper class.

public static T ParseEnum<T>(string value)
{
    return (T)Enum.Parse(typeof(T), value, ignoreCase: true);
}

And use it like so:

{
   Content = ParseEnum<ContentEnum>(fileContentMessage);
};

Especially helpful if you have lots of (different) Enums to parse.

Using Git, show all commits that are in one branch, but not the other(s)

You can use this simple script to see commits that are not merged

#!/bin/bash
# Show commits that exists only on branch and not in current
# Usage:
#   git branch-notmerge <branchname>
#
# Setup git alias
#   git config alias.branch-notmerge [path/to/this/script]
grep -Fvf <(git log --pretty=format:'%H - %s') <(git log $1 --pretty=format:'%H - %s')

You can use also tool git-wtf that will display state of branches

Can an html element have multiple ids?

No. From the XHTML 1.0 Spec

In XML, fragment identifiers are of type ID, and there can only be a single attribute of type ID per element. Therefore, in XHTML 1.0 the id attribute is defined to be of type ID. In order to ensure that XHTML 1.0 documents are well-structured XML documents, XHTML 1.0 documents MUST use the id attribute when defining fragment identifiers on the elements listed above. See the HTML Compatibility Guidelines for information on ensuring such anchors are backward compatible when serving XHTML documents as media type text/html.

How to convert a set to a list in python?

Whenever you are stuck in such type of problems, try to find the datatype of the element you want to convert first by using :

type(my_set)

Then, Use:

  list(my_set) 

to convert it to a list. You can use the newly built list like any normal list in python now.

Determine path of the executing script

If rather than the script, foo.R, knowing its path location, if you can change your code to always reference all source'd paths from a common root then these may be a great help:

Given

  • /app/deeply/nested/foo.R
  • /app/other.R

This will work

#!/usr/bin/env Rscript
library(here)
source(here("other.R"))

See https://rprojroot.r-lib.org/ for how to define project roots.

JSON to pandas DataFrame

billmanH's solution helped me but didn't work until i switched from:

n = data.loc[row,'json_column']

to:

n = data.iloc[[row]]['json_column']

here's the rest of it, converting to a dictionary is helpful for working with json data.

import json

for row in range(len(data)):
    n = data.iloc[[row]]['json_column'].item()
    jsonDict = json.loads(n)
    if ('mykey' in jsonDict):
        display(jsonDict['mykey'])

Pass a PHP string to a JavaScript variable (and escape newlines)

The paranoid version: Escaping every single character.

function javascript_escape($str) {
  $new_str = '';

  $str_len = strlen($str);
  for($i = 0; $i < $str_len; $i++) {
    $new_str .= '\\x' . sprintf('%02x', ord(substr($str, $i, 1)));
  }

  return $new_str;
}

EDIT: The reason why json_encode() may not be appropriate is that sometimes, you need to prevent " to be generated, e.g.

<div onclick="alert(???)" />

Is there a max size for POST parameter content?

There is no defined maximum size for HTTP POST requests. If you notice such a limit then it's an arbitrary limitation of your HTTP Server/Client.

You might get a better answer if you tell how big the XML is.

How to ignore a property in class if null, using json.net

var settings = new JsonSerializerSettings();
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
settings.NullValueHandling = NullValueHandling.Ignore;
//you can add multiple settings and then use it
var bodyAsJson = JsonConvert.SerializeObject(body, Formatting.Indented, settings);

What is Domain Driven Design?

I believe the following pdf will give you the bigger picture. Domain Driven Design by Eric Evans

NOTE: Think of a project you can work on, apply the little things you understood and see best practices. It will help you to grow your ability to the micro service architecture design approach too.

Ignore invalid self-signed ssl certificate in node.js with https.request?

Add the following environment variable:

NODE_TLS_REJECT_UNAUTHORIZED=0

e.g. with export:

export NODE_TLS_REJECT_UNAUTHORIZED=0

(with great thanks to Juanra)

How to start working with GTest and CMake

You can get the best of both worlds. It is possible to use ExternalProject to download the gtest source and then use add_subdirectory() to add it to your build. This has the following advantages:

  • gtest is built as part of your main build, so it uses the same compiler flags, etc. and hence avoids problems like the ones described in the question.
  • There's no need to add the gtest sources to your own source tree.

Used in the normal way, ExternalProject won't do the download and unpacking at configure time (i.e. when CMake is run), but you can get it to do so with just a little bit of work. I've written a blog post on how to do this which also includes a generalised implementation which works for any external project which uses CMake as its build system, not just gtest. You can find them here:

Update: This approach is now also part of the googletest documentation.

Oracle - how to remove white spaces?

I have used below command to remove white space in Oracle

My Table Name is - NG_CAP_SENDER_INFO_MTR

My Column Name is - SENINFO_FROM

UPDATE NG_CAP_SENDER_INFO_MTR SET SENINFO_FROM = TRIM(SENINFO_FROM); 

Already Answer on StackOverflow LTRIM RTRIM

And its working fine

Replace line break characters with <br /> in ASP.NET MVC Razor view

Applying the DRY principle to Omar's solution, here's an HTML Helper extension:

using System.Web.Mvc;
using System.Text.RegularExpressions;

namespace System.Web.Mvc.Html {
    public static class MyHtmlHelpers {
        public static MvcHtmlString EncodedReplace(this HtmlHelper helper, string input, string pattern, string replacement) {
            return new MvcHtmlString(Regex.Replace(helper.Encode(input), pattern, replacement));
        }
    }
}

Usage (with improved regex):

@Html.EncodedReplace(Model.CommentText, "[\n\r]+", "<br />")

This also has the added benefit of putting less onus on the Razor View developer to ensure security from XSS vulnerabilities.


My concern with Jacob's solution is that rendering the line breaks with CSS breaks the HTML semantics.

How to use a class from one C# project with another C# project

All too often a new developer asks this simple question which is a common problem specifically with Visual Studio IDE's. Few people answer the specific question and often critique the question or give "guesses" for solutions which don't answer the common problems. The first common problem is the IDE leads you to create new projects rather than add new files (.java, .py, .cpp, .c) to the existing solution (by default it creates a new solution) unless you change the project name and add to the current solution. This problem occurs for Python, java, c#, C++ and C project folders.

The new developer selecting "new>project>project name and changing the solution directory to "use same solution" still creates a new "project" in the same solution space, but not in the same directory space as the current user interface file or command line file which still leads to problems with "package not found" errors when building and running the project or solution. This is why the above coding suggestions to importing packages, classes, methods and functions only work (and thus don't answer the question) when the "library" file or "separate behavior" file is not only in the same solution directory path, but also in the same "user interface" or "command shell" application directory space. This does does not happen when you add another project using the new>project>project type commands of the IDE. The problem here is the new project is stored in a different directory than the existing Client or User interface code files. To create a new "file" in the same project space rather than new project the beginner needs to do the following that Microsoft won't do for you and even misleads you away from the intuitively obvious by default.

  1. Select the "application" you want to import the new behavior into (from another file)
  2. Select project>add new item
  3. Select the "program file template type" such as filetype.py, filetype.java, filetype.c, filetype.cpp, filetype.C#, etc. or a library class file type (something other than startup file options you see when you create a new application project or create a new library project).
  4. A new file name with default name is created in your project.
  5. Change the default name of the file to something like library.py or façade.java, etc.

NOW the code recommendations to import libraries or using namespaces will work as described in the comments above and you don't have to change path statements or change solutions paths and solution names that Microsoft won't let you change easily (i.e. you can change the filenames or project names but the IDE won't automatically change the project path or the solution path names).

The following is a Python example but works similar for C#, java, or C/C++ using the includes, namespaces or using code commands appropriate to each language to find code in other classes/projects in the SAME DIRECTORY SPACE.

The application file "hello world" importing from other code files in the same directory.

Note the python white space delimiters are not going to space correctly in this stackoverflow comment editor:

print ("test")

from CIXMPythonFacade import ClassA

c1=ClassA
c1.methodA()

from CIXMPythonFacade import functionA 

functionA()


class ClassName(object): 
         def __init__(object, parameter):
         object.parameter = value

The library file or "façade" file containing classes, methods or functions you want to import.

class class1(object):
    """description of class"""

class ClassA(object):
    print ("test2")
    def methodA():
        print ("test3")

def functionA ():
    print ("test4")
    return (0)


pass

NOW how do you actually solve the mess that the IDE leads you into? To import code from another file in the same directory space you add a reference to it.

  1. Select the application file
  2. Select Project>add reference
  3. Choose the filename visible with the right directory path (check it)
  4. The reference is now available to the interpreter, the code checker and/or the compiler.

OK so now that you have this problem solved, how do you really link two separate projects together in the same solution space?

  1. You have to go to both the indexer or "intellisense" options and the compiler/interpreter and physically check or change/add the directory path statements if they are something other than what points to your "second" project or solution space. When you do the path changes or change the path variables to your workspace and to the specific locations of the projects which are different directory spaces the compiler and the code analyzer can then find these libraries, headers.h, namespaces, project or file locations.
  2. To remove old projects you created by mistake it is even worse. You have to exit the Visual Studio IDE, open windows explorer, go to the workspace directory ...documents\visualstudio xxx\solutionname\packagename select the file or folder, right click and "delete" file or folder.
  3. When you re-enter the IDE and select open solution or open package/solution, the old files and solution/package names are gone as are their misleading path statements which fools the compiler and code analyzer to look at the old directory even though you changed the filename and changed the project name, it does not change the directory path with it.

Microsoft really, really needs to fix these problem so you can intuitively create what most people want to create as new files in the same directories and remove solutions by selecting them and deleting them from the IDE. Beginners get so frustrated with directory path statements so flexible for seasoned developers, but so unfair to new developers in their defaults.

Hope this really helps you new guys and stops seasoned developers from giving you the wrong answers that don't work for you. They assume you already understand path statements and just want to type the right code...which is also why the tunnel in on trying to correct your code but does not help you fix the problem. This is probably the most common problem continually described on stackoverflow with wrong answers that don't work for new programmers.

What does 'COLLATE SQL_Latin1_General_CP1_CI_AS' do?

It sets how the database server sorts (compares pieces of text). in this case:

SQL_Latin1_General_CP1_CI_AS

breaks up into interesting parts:

  1. latin1 makes the server treat strings using charset latin 1, basically ascii
  2. CP1 stands for Code Page 1252
  3. CI case insensitive comparisons so 'ABC' would equal 'abc'
  4. AS accent sensitive, so 'ü' does not equal 'u'

P.S. For more detailed information be sure to read @solomon-rutzky's answer.

What is the .idea folder?

It contains your local IntelliJ IDE configs. I recommend adding this folder to your .gitignore file:

# intellij configs
.idea/

Can a relative sitemap url be used in a robots.txt?

Google crawlers are not smart enough, they can't crawl relative URLs, that's why it's always recommended to use absolute URL's for better crawlability and indexability.

Therefore, you can not use this variation

> sitemap: /sitemap.xml

Recommended syntax is

Sitemap: https://www.yourdomain.com/sitemap.xml

Note:

  • Don't forgot to capitalise the first letter in "sitemap"
  • Don't forgot to put space after "Sitemap:"

I want to remove double quotes from a String

If you only want to remove quotes from the beginning or the end, use the following regular expression:

'"Hello"'.replace(/(^"|"$)/g, '');

Forking / Multi-Threaded Processes | Bash

In bash scripts (non-interactive) by default JOB CONTROL is disabled so you can't do the the commands: job, fg, and bg.

Here is what works well for me:

#!/bin/sh

set -m # Enable Job Control

for i in `seq 30`; do # start 30 jobs in parallel
  sleep 3 &
done

# Wait for all parallel jobs to finish
while [ 1 ]; do fg 2> /dev/null; [ $? == 1 ] && break; done

The last line uses "fg" to bring a background job into the foreground. It does this in a loop until fg returns 1 ($? == 1), which it does when there are no longer any more background jobs.

How to change the color of a SwitchCompat from AppCompat library

Be carreful of the know bug with SwitchCompat

It's a bug with corrupt file in drawable-hdpi on AppCompat https://code.google.com/p/android/issues/detail?id=78262

To fix it, juste override it with this 2 files https://github.com/lopespm/quick-fix-switchcompat-resources Add it on your directory drawable-hdpi

XML

<android.support.v7.widget.SwitchCompat
android:id="@+id/dev_switch_show_dev_only"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

And nothing was necessary on Java

What's the difference between a mock & stub?

A test subject performs actions in response to certain prompts (function calls) or other stimuli. Here are concrete examples of test situations.

Scenario -- EMT student exam

A student has studied to be an Emergency Medical Technician. Go watch Ian Gallagher in Shameless Season 6, Episode 10 if you are unfamiliar with this test situation.

It is too expensive to find patients with various illnesses for test purposes. Instead we use actors. We ask the test subject (Ian) "you arrive on the scene and the patient is immobilized and unconscious what do you do first?" Ian responds "I check if the scene is safe". And the test instructor says "the scene is safe".

The instructor (and actor) are able to inject arbitrary answers to the test subject's queries.

Here, the instructor (and actor) are a mock. Medical training uses this terminology (e.g. mock code simulation) the same as computer scientists.

Scenario -- register for a website

You are testing Yahoo, a new email service you heard about. In order to sign up, you must provide your birthday and answers to other intrusive questions.

The website requires that you are 21 years or older. So you enter in the value January 1, 1970. It meets the requirements and it saves you from the laborious process of implementing a remember-my-birthday-and-type-it-in workflow.

This date is a stub. This word usage is specific to computer science.

React PropTypes : Allow different types of PropTypes for one prop

import React from 'react';              <--as normal
import PropTypes from 'prop-types';     <--add this as a second line

    App.propTypes = {
        monkey: PropTypes.string,           <--omit "React."
        cat: PropTypes.number.isRequired    <--omit "React."
    };

    Wrong:  React.PropTypes.string
    Right:  PropTypes.string

How to convert int to float in python?

You can literally convert it into float using:


float_value = float(integer_value)

Likewise, you can convert an integer back to float datatype with:


integer_value = int(float_value)

Hope it helped. I advice you to read "Build-In Functions of Python" at this link: https://docs.python.org/2/library/functions.html

Hibernate: hbm2ddl.auto=update in production?

Check out LiquiBase XML for keeping a changelog of updates. I had never used it until this year, but I found that it's very easy to learn and make DB revision control/migration/change management very foolproof. I work on a Groovy/Grails project, and Grails uses Hibernate underneath for all its ORM (called "GORM"). We use Liquibase to manage all SQL schema changes, which we do fairly often as our app evolves with new features.

Basically, you keep an XML file of changesets that you continue to add to as your application evolves. This file is kept in git (or whatever you are using) with the rest of your project. When your app is deployed, Liquibase checks it's changelog table in the DB you are connecting to so it will know what has already been applied, then it intelligently just applies whatever changesets have not been applied yet from the file. It works absolutely great in practice, and if you use it for all your schema changes, then you can be 100% confident that code you checkout and deploy will always be able to connect to a fully compatible database schema.

The awesome thing is that I can take a totally blank slate mysql database on my laptop, fire up the app, and right away the schema is set up for me. It also makes it easy to test schema changes by applying these to a local-dev or staging db first.

The easiest way to get started with it would probably be to take your existing DB and then use Liquibase to generate an initial baseline.xml file. Then in the future you can just append to it and let liquibase take over managing schema changes.

http://www.liquibase.org/

How to allow CORS in react.js?

I deal with this issue for some hours. Let's consider the request is Reactjs (javascript) and backend (API) is Asp .Net Core.

in the request, you must set in header Content-Type:

Axios({
            method: 'post',
            headers: { 'Content-Type': 'application/json'},
            url: 'https://localhost:44346/Order/Order/GiveOrder',
            data: order,
          }).then(function (response) {
            console.log(response);
          });

and in backend (Asp .net core API) u must have some setting:

1. in Startup --> ConfigureServices:

#region Allow-Orgin
            services.AddCors(c =>
            {
                c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
            });
            #endregion

2. in Startup --> Configure before app.UseMvc() :

app.UseCors(builder => builder
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());

3. in controller before action:

[EnableCors("AllowOrigin")]

Landscape printing from HTML

Quoted from CSS-Discuss Wiki

The @page rule has been cut down in scope from CSS2 to CSS2.1. The full CSS2 @page rule was reportedly implemented only in Opera (and buggily even then). My own testing shows that IE and Firefox don't support @page at all. According to the now-obsolescent CSS2 spec section 13.2.2 it is possible to override the user's setting of orientation and (for example) force printing in Landscape but the relevant "size" property has been dropped from CSS2.1, consistent with the fact that no current browser supports it. It has been reinstated in the CSS3 Paged Media module but note that this is only a Working Draft (as at July 2009).

Conclusion: forget about @page for the present. If you feel your document needs to be printed in Landscape orientation, ask yourself if you can instead make your design more fluid. If you really can't (perhaps because the document contains data tables with many columns, for example), you will need to advise the user to set the orientation to Landscape and perhaps outline how to do it in the most common browsers. Of course, some browsers have a print fit-to-width (shrink-to-fit) feature (e.g. Opera, Firefox, IE7) but it's inadvisable to rely on users having this facility or having it switched on.

Extract data from log file in specified range of time

I used this command to find last 5 minutes logs for particular event "DHCPACK", try below:

$ grep "DHCPACK" /var/log/messages | grep "$(date +%h\ %d) [$(date --date='5 min ago' %H)-$(date +%H)]:*:*"

Finding index of character in Swift String

In swift 2.0

var stringMe="Something In this.World"
var needle="."
if let idx = stringMe.characters.indexOf(needle) {
    let pos=stringMe.substringFromIndex(idx)
    print("Found \(needle) at position \(pos)")
}
else {
    print("Not found")
}

Swift Error: Editor placeholder in source file

If you have this error while you create segues with the view controllers not with the UI elements you have to change sender: Any? to this

@IBAction func backButtonPressed(_ sender: Any) {
        performSegue(withIdentifier: "goToMainScreen", sender: self)

    }

It will work.

SQL Server CASE .. WHEN .. IN statement

It might be easier to read when written out in longhand using the 'simple case' e.g.

CASE DeviceID 
   WHEN '7  ' THEN '01'
   WHEN '10 ' THEN '01'
   WHEN '62 ' THEN '01'
   WHEN '58 ' THEN '01'
   WHEN '60 ' THEN '01'
   WHEN '46 ' THEN '01'
   WHEN '48 ' THEN '01'
   WHEN '50 ' THEN '01'
   WHEN '137' THEN '01'
   WHEN '139' THEN '01'
   WHEN '142' THEN '01'
   WHEN '143' THEN '01'
   WHEN '164' THEN '01'
   WHEN '8  ' THEN '02'
   WHEN '9  ' THEN '02'
   WHEN '63 ' THEN '02'
   WHEN '59 ' THEN '02'
   WHEN '61 ' THEN '02'
   WHEN '47 ' THEN '02'
   WHEN '49 ' THEN '02'
   WHEN '51 ' THEN '02'
   WHEN '138' THEN '02'
   WHEN '140' THEN '02'
   WHEN '141' THEN '02'
   WHEN '144' THEN '02'
   WHEN '165' THEN '02'
   ELSE 'NA' 
END AS clocking

...which kind makes me thing that perhaps you could benefit from a lookup table to which you can JOIN to eliminate the CASE expression entirely.

Update OpenSSL on OS X with Homebrew

I had this issue and found that the installation of the newer openssl did actually work, but my PATH was setup incorrectly for it -- my $PATH had the ports path placed before my brew path so it always found the older version of openssl.

The fix for me was to put the path to brew (/usr/local/bin) at the front of my $PATH.

To find out where you're loading openssl from, run which openssl and note the output. It will be the location of the version your system is using when you run openssl. Its going to be somewhere other than the brewpath of "/usr/local/bin". Change your $PATH, close that terminal tab and open a new one, and run which openssl. You should see a different path now, probably under /usr/local/bin. Now run openssl version and you should see the new version you installed "OpenSSL 1.0.1e 11 Feb 2013".

Why does flexbox stretch my image rather than retaining aspect ratio?

It is stretching because align-self default value is stretch. there is two solution for this case : 1. set img align-self : center OR 2. set parent align-items : center

img {

   align-self: center
}

OR

.parent {
  align-items: center
}

How to count number of records per day?

This one is like the answer above which uses the MySql DATE_FORMAT() function. I also selected just one specific week in Jan.

SELECT 
    DatePart(day, DateAdded) AS date, 
    COUNT(entryhash) AS count 
FROM Responses 
    where DateAdded > '2020-01-25' and DateAdded < '2020-02-01' 
GROUP BY 
    DatePart(day, DateAdded )

How do I link to a library with Code::Blocks?

At a guess, you used Code::Blocks to create a Console Application project. Such a project does not link in the GDI stuff, because console applications are generally not intended to do graphics, and TextOut is a graphics function. If you want to use the features of the GDI, you should create a Win32 Gui Project, which will be set up to link in the GDI for you.

Import a custom class in Java

I see the picture, and all your classes are in the same package. So you don't have to import, you can create a new instance without the import sentence.

Convert int (number) to string with leading zeros? (4 digits)

Use the ToString() method - standard and custom numeric format strings. Have a look at the MSDN article How to: Pad a Number with Leading Zeros.

string text = no.ToString("0000");

Remove privileges from MySQL database

As a side note, the reason revoke usage on *.* from 'phpmyadmin'@'localhost'; does not work is quite simple : There is no grant called USAGE.

The actual named grants are in the MySQL Documentation

The grant USAGE is a logical grant. How? 'phpmyadmin'@'localhost' has an entry in mysql.user where user='phpmyadmin' and host='localhost'. Any row in mysql.user semantically means USAGE. Running DROP USER 'phpmyadmin'@'localhost'; should work just fine. Under the hood, it's really doing this:

DELETE FROM mysql.user WHERE user='phpmyadmin' and host='localhost';
DELETE FROM mysql.db   WHERE user='phpmyadmin' and host='localhost';
FLUSH PRIVILEGES;

Therefore, the removal of a row from mysql.user constitutes running REVOKE USAGE, even though REVOKE USAGE cannot literally be executed.

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

For Swift 3 and Xcode 8:

      var dataTask: URLSessionDataTask?

      if  let url = URL(string: urlString) {
            self.dataTask = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in

                if let error = error {
                    print(error.localizedDescription)
                } else if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
                     // You can use data received.
                    self.process(data: data as Data?)
                }
            })
        }
     }

//Note: You can always use debugger to check error

RedirectToAction with parameter

//How to use RedirectToAction in MVC

return RedirectToAction("actionName", "ControllerName", routevalue);

example

return RedirectToAction("Index", "Home", new { id = 2});

Home does not contain an export named Home

We also can use

import { Home } from './layouts/Home'; 

using export keyword before class keyword.

export class Home extends React.Component{
    render(){
        ........
    }
}

For default

 import Home from './layouts/Home'; 

Default export class

 export default class Home extends React.Component{
    render(){
        ........
    }
 }

Both case don't need to write

export default Home;

after class.

How to use class from other files in C# with visual studio?

According to your example here it seems that they both reside in the same namespace, i conclude that they are both part of the same project ( if you haven't created another project with the same namespace) and all class by default are defined as internal to the project they are defined in, if haven't declared otherwise, therefore i guess the problem is that your file is not included in your project. You can include it by right clicking the file in the solution explorer window => Include in project, if you cannot see the file inside the project files in the solution explorer then click the show the upper menu button of the solution explorer called show all files ( just hove your mouse cursor over the button there and you'll see the names of the buttons)

Just for basic knowledge: If the file resides in a different project\ assembly then it has to be defined, otherwise it has to be define at least as internal or public. in case your class is inheriting from that class that it can be protected as well.

How to get names of classes inside a jar file?

You can try:

jar tvf jarfile.jar 

This will be helpful only if your jar is executable i.e. in manifest you have defined some class as main class

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". in a Maven Project

The message you mention is quite clear:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

SLF4J API could not find a binding, and decided to default to a NOP implementation. In your case slf4j-log4j12.jar was somehow not visible when the LoggerFactory class was loaded into memory, which is admittedly very strange. What does "mvn dependency:tree" tell you?

The various dependency declarations may not even be directly at cause here. I strongly suspect that a pre-1.6 version of slf4j-api.jar is being deployed without your knowledge.

TypeError: window.initMap is not a function

This may seem obvious but just in case: If someone placed the JS code inside $(document).ready like this:

     $(document).ready(function() {
       ... Google Maps JS code ...
      }

Then that's the problem because using async defer when loading the Google Maps API library, it will load asynchronously, and when it finishes loading, will look for the callback function, which needs to be available by then.

So, you just need to put the code outside $(document).ready, and:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
    async defer></script>

at the very bottom, so your page loads FAST :-)

SQL: parse the first, middle and last name from a fullname field

Check this query in Athena for only one-space separated string (e.g. first name and middle name combination):

SELECT name, REVERSE( SUBSTR( REVERSE(name), 1, STRPOS(REVERSE(name), ' ') ) ) AS middle_name FROM name_table

If you expect to have two or more spaces, you can easily extend the above query.

WebView and HTML5 <video>

After long research, I got this thing working. See the following code:

Test.java

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;

public class Test extends Activity {

    HTML5WebView mWebView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mWebView = new HTML5WebView(this);

        if (savedInstanceState != null) {
            mWebView.restoreState(savedInstanceState);
        } else {    
            mWebView.loadUrl("http://192.168.1.18/xxxxxxxxxxxxxxxx/");
        }

        setContentView(mWebView.getLayout());
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mWebView.saveState(outState);
    }

    @Override
    public void onStop() {
        super.onStop();
        mWebView.stopLoading();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mWebView.inCustomView()) {
                mWebView.hideCustomView();
            //  mWebView.goBack();
                //mWebView.goBack();
                return true;
            }

        }
        return super.onKeyDown(keyCode, event);
    }
}

HTML%VIDEO.java

package com.ivz.idemandtest;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

public class HTML5WebView extends WebView {

    private Context                             mContext;
    private MyWebChromeClient                   mWebChromeClient;
    private View                                mCustomView;
    private FrameLayout                         mCustomViewContainer;
    private WebChromeClient.CustomViewCallback  mCustomViewCallback;

    private FrameLayout                         mContentView;
    private FrameLayout                         mBrowserFrameLayout;
    private FrameLayout                         mLayout;

    static final String LOGTAG = "HTML5WebView";

    private void init(Context context) {
        mContext = context;     
        Activity a = (Activity) mContext;

        mLayout = new FrameLayout(context);

        mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(a).inflate(R.layout.custom_screen, null);
        mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(R.id.main_content);
        mCustomViewContainer = (FrameLayout) mBrowserFrameLayout.findViewById(R.id.fullscreen_custom_content);

        mLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);

        // Configure the webview
        WebSettings s = getSettings();
        s.setBuiltInZoomControls(true);
        s.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        s.setUseWideViewPort(true);
        s.setLoadWithOverviewMode(true);
      //  s.setSavePassword(true);
        s.setSaveFormData(true);
        s.setJavaScriptEnabled(true);
        mWebChromeClient = new MyWebChromeClient();
        setWebChromeClient(mWebChromeClient);

        setWebViewClient(new WebViewClient());

setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

        // enable navigator.geolocation 
       // s.setGeolocationEnabled(true);
       // s.setGeolocationDatabasePath("/data/data/org.itri.html5webview/databases/");

        // enable Web Storage: localStorage, sessionStorage
        s.setDomStorageEnabled(true);

        mContentView.addView(this);
    }

    public HTML5WebView(Context context) {
        super(context);
        init(context);
    }

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

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

    public FrameLayout getLayout() {
        return mLayout;
    }

    public boolean inCustomView() {
        return (mCustomView != null);
    }

    public void hideCustomView() {
        mWebChromeClient.onHideCustomView();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((mCustomView == null) && canGoBack()){
                goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private class MyWebChromeClient extends WebChromeClient {
        private Bitmap      mDefaultVideoPoster;
        private View        mVideoProgressView;

        @Override
        public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback)
        {
            //Log.i(LOGTAG, "here in on ShowCustomView");
            HTML5WebView.this.setVisibility(View.GONE);

            // if a view already exists then immediately terminate the new one
            if (mCustomView != null) {
                callback.onCustomViewHidden();
                return;
            }

            mCustomViewContainer.addView(view);
            mCustomView = view;
            mCustomViewCallback = callback;
            mCustomViewContainer.setVisibility(View.VISIBLE);
        }

        @Override
        public void onHideCustomView() {
            System.out.println("customview hideeeeeeeeeeeeeeeeeeeeeeeeeee");
            if (mCustomView == null)
                return;        

            // Hide the custom view.
            mCustomView.setVisibility(View.GONE);

            // Remove the custom view from its container.
            mCustomViewContainer.removeView(mCustomView);
            mCustomView = null;
            mCustomViewContainer.setVisibility(View.GONE);
            mCustomViewCallback.onCustomViewHidden();

            HTML5WebView.this.setVisibility(View.VISIBLE);
            HTML5WebView.this.goBack();
            //Log.i(LOGTAG, "set it to webVew");
        }


        @Override
        public View getVideoLoadingProgressView() {
            //Log.i(LOGTAG, "here in on getVideoLoadingPregressView");

            if (mVideoProgressView == null) {
                LayoutInflater inflater = LayoutInflater.from(mContext);
                mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null);
            }
            return mVideoProgressView; 
        }

         @Override
         public void onReceivedTitle(WebView view, String title) {
            ((Activity) mContext).setTitle(title);
         }

         @Override
         public void onProgressChanged(WebView view, int newProgress) {
             ((Activity) mContext).getWindow().setFeatureInt(Window.FEATURE_PROGRESS, newProgress*100);
         }

         @Override
         public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
             callback.invoke(origin, true, false);
         }
    }


    static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
        new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}

custom_screen.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2009 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android">
    <FrameLayout android:id="@+id/fullscreen_custom_content"
        android:visibility="gone"
        android:background="@color/black"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
    />
    <LinearLayout android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout android:id="@+id/error_console"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
        />

        <FrameLayout android:id="@+id/main_content"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
        />
    </LinearLayout>
</FrameLayout>

video_loading_progress.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2009 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
         android:id="@+id/progress_indicator"
         android:orientation="vertical"
         android:layout_centerInParent="true"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content">

       <ProgressBar android:id="@android:id/progress"
           style="?android:attr/progressBarStyleLarge"
           android:layout_gravity="center"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content" />

       <TextView android:paddingTop="5dip"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_gravity="center"
           android:text="@string/loading_video" android:textSize="14sp"
           android:textColor="?android:attr/textColorPrimary" />
 </LinearLayout>

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<!--
/* //device/apps/common/assets/res/any/http_authentication_colors.xml
**
** Copyright 2006, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License"); 
** you may not use this file except in compliance with the License. 
** You may obtain a copy of the License at 
**
**     http://www.apache.org/licenses/LICENSE-2.0 
**
** Unless required by applicable law or agreed to in writing, software 
** distributed under the License is distributed on an "AS IS" BASIS, 
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
** See the License for the specific language governing permissions and 
** limitations under the License.
*/
-->
<!-- FIXME: Change the name of this file!  It is now being used generically
    for the browser -->
<resources>
    <color name="username_text">#ffffffff</color>
    <color name="username_edit">#ff000000</color>

    <color name="password_text">#ffffffff</color>
    <color name="password_edit">#ff000000</color>

    <color name="ssl_text_label">#ffffffff</color>
    <color name="ssl_text_value">#ffffffff</color>

    <color name="white">#ffffffff</color>
    <color name="black">#ff000000</color>



    <color name="geolocation_permissions_prompt_background">#ffdddddd</color>
</resources>

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.test"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="7" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Test"
                  android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
            android:configChanges="orientation|keyboardHidden|keyboard">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>  
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
</manifest>

Expecting rest of things you can understand.

How do I import a specific version of a package using go get?

That worked for me

GO111MODULE=on go get -u github.com/segmentio/[email protected]

How do I horizontally center an absolute positioned element inside a 100% width div?

In my experience, the best way is right:0;, left:0; and margin:0 auto. This way if the div is wide then you aren't hindered by the left: 50%; that will offset your div which results in adding negative margins etc.

DEMO http://jsfiddle.net/kevinPHPkevin/DeTJH/4/

#logo {
    background:red;
    height:50px;
    position:absolute;
    width:50px;
    margin:0 auto;
    right:0;
    left:0;
}

How to create a fixed sidebar layout with Bootstrap 4?

I'm using the J.S. to fix a sidebar menu. I've tried a lot of solutions with CSS but it's the simplest way to solve it, just add J.S. adding and removing a native BootStrap class: "position-fixed".

The J.S.:

var lateral = false;
function fixar() {

            var element, name, arr;
            element = document.getElementById("minhasidebar");

            if (lateral) {
                element.className = element.className.replace(
                        /\bposition-fixed\b/g, "");
                lateral = false;
            } else {

                name = "position-fixed";
                arr = element.className.split(" ");
                if (arr.indexOf(name) == -1) {
                    element.className += " " + name;
                }
                lateral = true;
            }

        }

The HTML:

Sidebar:

<aside>
        <nav class="sidebar ">
             <div id="minhasidebar">
                 <ul class="nav nav-pills">
                     <li class="nav-item"><a class="nav-link active" 
                     th:href="@{/hoje/inicial}"> <i class="oi oi-clipboard"></i> 
                     <span>Hoje</span>
                     </a></li>
                 </ul>
             </div>
        </nav>            
</aside>

Good examples of python-memcache (memcached) being used in Python?

It's fairly simple. You write values using keys and expiry times. You get values using keys. You can expire keys from the system.

Most clients follow the same rules. You can read the generic instructions and best practices on the memcached homepage.

If you really want to dig into it, I'd look at the source. Here's the header comment:

"""
client module for memcached (memory cache daemon)

Overview
========

See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.

Usage summary
=============

This should give you a feel for how this module operates::

    import memcache
    mc = memcache.Client(['127.0.0.1:11211'], debug=0)

    mc.set("some_key", "Some value")
    value = mc.get("some_key")

    mc.set("another_key", 3)
    mc.delete("another_key")

    mc.set("key", "1")   # note that the key used for incr/decr must be a string.
    mc.incr("key")
    mc.decr("key")

The standard way to use memcache with a database is like this::

    key = derive_key(obj)
    obj = mc.get(key)
    if not obj:
        obj = backend_api.get(...)
        mc.set(key, obj)

    # we now have obj, and future passes through this code
    # will use the object from the cache.

Detailed Documentation
======================

More detailed documentation is available in the L{Client} class.
"""

Spring boot - configure EntityManager

With Spring Boot its not necessary to have any config file like persistence.xml. You can configure with annotations Just configure your DB config for JPA in the

application.properties

spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@DB...
spring.datasource.username=username
spring.datasource.password=pass

spring.jpa.database-platform=org.hibernate.dialect....
spring.jpa.show-sql=true

Then you can use CrudRepository provided by Spring where you have standard CRUD transaction methods. There you can also implement your own SQL's like JPQL.

@Transactional
public interface ObjectRepository extends CrudRepository<Object, Long> {
...
}

And if you still need to use the Entity Manager you can create another class.

public class ObjectRepositoryImpl implements ObjectCustomMethods{

    @PersistenceContext
    private EntityManager em;

}

This should be in your pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.5.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.11.Final</version>
    </dependency>
</dependencies>

Pass in an array of Deferreds to $.when()

I had a case very similar where I was posting in an each loop and then setting the html markup in some fields from numbers received from the ajax. I then needed to do a sum of the (now-updated) values of these fields and place in a total field.

Thus the problem was that I was trying to do a sum on all of the numbers but no data had arrived back yet from the async ajax calls. I needed to complete this functionality in a few functions to be able to reuse the code. My outer function awaits the data before I then go and do some stuff with the fully updated DOM.

    // 1st
    function Outer() {
        var deferreds = GetAllData();

        $.when.apply($, deferreds).done(function () {
            // now you can do whatever you want with the updated page
        });
    }

    // 2nd
    function GetAllData() {
        var deferreds = [];
        $('.calculatedField').each(function (data) {
            deferreds.push(GetIndividualData($(this)));
        });
        return deferreds;
    }

    // 3rd
    function GetIndividualData(item) {
        var def = new $.Deferred();
        $.post('@Url.Action("GetData")', function (data) {
            item.html(data.valueFromAjax);
            def.resolve(data);
        });
        return def;
    }

How to modify memory contents using GDB?

The easiest is setting a program variable (see GDB: assignment):

(gdb) l
6       {
7           int i;
8           struct file *f, *ftmp;
9
(gdb) set variable i = 10
(gdb) p i
$1 = 10

Or you can just update arbitrary (writable) location by address:

(gdb) set {int}0x83040 = 4

There's more. Read the manual.

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

the problem is in url pattern of servlet-mapping.

 <url-pattern>/DispatcherServlet</url-pattern>

let's say our controller is

@Controller
public class HomeController {
    @RequestMapping("/home")
    public String home(){
        return "home";
    }
}

when we hit some URL on our browser. the dispatcher servlet will try to map this url.

the url pattern of our serlvet currently is /Dispatcher which means resources are served from {contextpath}/Dispatcher

but when we request http://localhost:8080/home we are actually asking resources from / which is not available. so either we need to say dispatcher servlet to serve from / by doing

<url-pattern>/</url-pattern>

our make it serve from /Dispatcher by doing /Dispatcher/*

E.g

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" 
version="3.1">
  <display-name>springsecuritydemo</display-name>

  <servlet>
    <description></description>
    <display-name>offers</display-name>
    <servlet-name>offers</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>offers</servlet-name>
    <url-pattern>/Dispatcher/*</url-pattern>
  </servlet-mapping>

</web-app>

and request it with http://localhost:8080/Dispatcher/home or put just / to request like

http://localhost:8080/home

PHPMyAdmin Default login password

I just installed Fedora 16 (yea, I know it's old and not supported but, I had the CD burnt :) )

Anyway, coming to the solution, this is what I was required to do:

su -
gedit /etc/phpMyAdmin/config.inc.php

if not found... try phpmyadmin - all small caps.

gedit /etc/phpmyadmin/config.inc.php

Locate

$cfg['Servers'][$i]['AllowNoPassword']

and set it to:

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

Save it.

What is the best open-source java charting library? (other than jfreechart)

EasyCharts is commercial so i couldn't use it for my project. I used the GRAL graphing library instead. I found it very easy to customize and it's licensed under LGPL just like JFreeChart, so you can use it for free:

http://trac.erichseifert.de/gral

Android - Adding at least one Activity with an ACTION-VIEW intent-filter after Updating SDK version 23

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.app"
tools:ignore="GoogleAppIndexingWarning">

You can remove the warning by adding xmlns:tools="http://schemas.android.com/tools" and tools:ignore="GoogleAppIndexingWarning" to the <manifest> tag.

Iterate through Nested JavaScript Objects

Here is a concise breadth-first iterative solution, which I prefer to recursion:

const findCar = function(car) {
    const carSearch = [cars];

      while(carSearch.length) {
          let item = carSearch.shift();
          if (item.label === car) return true;
          carSearch.push(...item.subs);
      }

      return false;
}

Android Layout Animations from bottom to top and top to bottom on ImageView click

I have solved my issue and now my animation works fine :) if anyone needed just copy my code and xml file and have a happy coding :)

My Activity MainActivity:

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class MainActivity extends Activity {

RelativeLayout rl_footer;
ImageView iv_header;
boolean isBottom = true;
Button btn1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    rl_footer = (RelativeLayout) findViewById(R.id.rl_footer);
    iv_header = (ImageView) findViewById(R.id.iv_up_arrow);
    iv_header.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            iv_header.setImageResource(R.drawable.down_arrow);
            iv_header.setPadding(0, 10, 0, 0); 
            rl_footer.setBackgroundResource(R.drawable.up_manu_bar);
            if (isBottom) {
                SlideToAbove();
                isBottom = false;
            } else {
                iv_header.setImageResource(R.drawable.up_arrow);
                iv_header.setPadding(0, 0, 0, 10);
                rl_footer.setBackgroundResource(R.drawable.down_manu_bar1);
                SlideToDown();
                isBottom = true;
            }

        }
    });

}

public void SlideToAbove() {
    Animation slide = null;
    slide = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
            0.0f, Animation.RELATIVE_TO_SELF, -5.0f);

    slide.setDuration(400);
    slide.setFillAfter(true);
    slide.setFillEnabled(true);
    rl_footer.startAnimation(slide);

    slide.setAnimationListener(new AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {

            rl_footer.clearAnimation();

            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    rl_footer.getWidth(), rl_footer.getHeight());
            // lp.setMargins(0, 0, 0, 0);
            lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
            rl_footer.setLayoutParams(lp);

        }

    });

}

public void SlideToDown() {
    Animation slide = null;
    slide = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
            0.0f, Animation.RELATIVE_TO_SELF, 5.2f);

    slide.setDuration(400);
    slide.setFillAfter(true);
    slide.setFillEnabled(true);
    rl_footer.startAnimation(slide);

    slide.setAnimationListener(new AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {

            rl_footer.clearAnimation();

            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    rl_footer.getWidth(), rl_footer.getHeight());
            lp.setMargins(0, rl_footer.getWidth(), 0, 0);
            lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            rl_footer.setLayoutParams(lp);

        }

    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

 }

and my Xml activity_main:

 <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/rl_main"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="@drawable/autograph_bg" >

 <RelativeLayout
    android:id="@+id/rl_footer"
    android:layout_width="fill_parent"
    android:layout_height="70dp"
    android:layout_alignParentBottom="true"
    android:background="@drawable/down_manu_bar1" >

    <ImageView
        android:id="@+id/iv_new_file"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="18dp"
        android:onClick="onNewFileClick"
        android:src="@drawable/file_icon" />

    <TextView
        android:id="@+id/tv_new_file"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/iv_new_file"
        android:layout_below="@+id/iv_new_file"
        android:text="New"
        android:textColor="#ffffff" />

    <ImageView
        android:id="@+id/iv_insert"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignTop="@+id/iv_new_file"
        android:layout_marginLeft="30dp"
        android:layout_toRightOf="@+id/iv_new_file"
        android:src="@drawable/insert_icon" />

    <TextView
        android:id="@+id/tv_insert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/iv_insert"
        android:layout_below="@+id/iv_insert"
        android:text="Insert"
        android:textColor="#ffffff" />

    <ImageView
        android:id="@+id/iv_up_arrow"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:paddingBottom="10dp"
        android:src="@drawable/up_arrow" />

    <ImageView
        android:id="@+id/iv_down_arrow"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:background="@drawable/down_arrow"
        android:paddingBottom="10dp"
        android:visibility="gone" />

    <ImageView
        android:id="@+id/iv_save"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignTop="@+id/iv_insert"
        android:layout_marginLeft="30dp"
        android:layout_toRightOf="@+id/iv_up_arrow"
        android:src="@drawable/save" />

    <TextView
        android:id="@+id/tv_save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/iv_save"
        android:layout_alignParentBottom="true"
        android:text="Save"
        android:textColor="#ffffff" />

    <ImageView
        android:id="@+id/iv_settings"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignTop="@+id/iv_save"
        android:layout_marginLeft="27dp"
        android:layout_toRightOf="@+id/tv_save"
        android:paddingTop="2dp"
        android:src="@drawable/icon_settings" />

    <TextView
        android:id="@+id/tv_settings"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginLeft="260dp"
        android:text="Settings"
        android:textColor="#ffffff" />
 </RelativeLayout>

 </RelativeLayout>

just create new android project and copy paste my code and have fun! :) also remember in xml i have image view and his background images replace with yout own images thanks..

How to read the content of a file to a string in C?

If you are reading special files like stdin or a pipe, you are not going to be able to use fstat to get the file size beforehand. Also, if you are reading a binary file fgets is going to lose the string size information because of embedded '\0' characters. Best way to read a file then is to use read and realloc:

#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

int main () {
    char buf[4096];
    ssize_t n;
    char *str = NULL;
    size_t len = 0;
    while (n = read(STDIN_FILENO, buf, sizeof buf)) {
        if (n < 0) {
            if (errno == EAGAIN)
                continue;
            perror("read");
            break;
        }
        str = realloc(str, len + n + 1);
        memcpy(str + len, buf, n);
        len += n;
        str[len] = '\0';
    }
    printf("%.*s\n", len, str);
    return 0;
}

How to run a SQL query on an Excel table?

You can experiment with the native DB driver for Excel in language/platform of your choice. In Java world, you can try with http://code.google.com/p/sqlsheet/ which provides a JDBC driver for working with Excel sheets directly. Similarly, you can get drivers for the DB technology for other platforms.

However, I can guarantee that you will soon hit a wall with the number of features these wrapper libraries provide. Better way will be to use Apache HSSF/POI or similar level of library but it will need more coding effort.

How to use Java property files?

Here is another way to iterate over the properties:

Enumeration eProps = properties.propertyNames();
while (eProps.hasMoreElements()) { 
    String key = (String) eProps.nextElement(); 
    String value = properties.getProperty(key); 
    System.out.println(key + " => " + value); 
}

Example of Mockito's argumentCaptor

Here I am giving you a proper example of one callback method . so suppose we have a method like method login() :

 public void login() {
    loginService = new LoginService();
    loginService.login(loginProvider, new LoginListener() {
        @Override
        public void onLoginSuccess() {
            loginService.getresult(true);
        }

        @Override
        public void onLoginFaliure() {
            loginService.getresult(false);

        }
    });
    System.out.print("@@##### get called");
}

I also put all the helper class here to make the example more clear: loginService class

public class LoginService implements Login.getresult{
public void login(LoginProvider loginProvider,LoginListener callback){

    String username  = loginProvider.getUsername();
    String pwd  = loginProvider.getPassword();
    if(username != null && pwd != null){
        callback.onLoginSuccess();
    }else{
        callback.onLoginFaliure();
    }

}

@Override
public void getresult(boolean value) {
    System.out.print("login success"+value);
}}

and we have listener LoginListener as :

interface LoginListener {
void onLoginSuccess();

void onLoginFaliure();

}

now I just wanted to test the method login() of class Login

 @Test
public void loginTest() throws Exception {
    LoginService service = mock(LoginService.class);
    LoginProvider provider = mock(LoginProvider.class);
    whenNew(LoginProvider.class).withNoArguments().thenReturn(provider);
    whenNew(LoginService.class).withNoArguments().thenReturn(service);
    when(provider.getPassword()).thenReturn("pwd");
    when(provider.getUsername()).thenReturn("username");
    login.getLoginDetail("username","password");

    verify(provider).setPassword("password");
    verify(provider).setUsername("username");

    verify(service).login(eq(provider),captor.capture());

    LoginListener listener = captor.getValue();

    listener.onLoginSuccess();

    verify(service).getresult(true);

also dont forget to add annotation above the test class as

@RunWith(PowerMockRunner.class)
@PrepareForTest(Login.class)

Replace whole line containing a string using Sed

cat find_replace | while read pattern replacement ; do
sed -i "/${pattern}/c ${replacement}" file    
done 

find_replace file contains 2 columns, c1 with pattern to match, c2 with replacement, the sed loop replaces each line conatining one of the pattern of variable 1

How can you use php in a javascript function

you use script in php..

<?php

        $num = 1;
        echo $num;

    echo '<input type="button"
           name="lol" 
           value="Click to increment"
           onclick="Inc()" />
    <br>
    <script>
        function Inc()
        {';
            $num = 2;
            echo $num;

        echo '}
    </script>';
?>

How do you use bcrypt for hashing passwords in PHP?

You can create a one-way hash with bcrypt using PHP's crypt() function and passing in an appropriate Blowfish salt. The most important of the whole equation is that A) the algorithm hasn't been compromised and B) you properly salt each password. Don't use an application-wide salt; that opens up your entire application to attack from a single set of Rainbow tables.

PHP - Crypt Function

How to make the window full screen with Javascript (stretching all over the screen)

This will works to show your window in full screen

Note: For this to work, you need Query from http://code.jquery.com/jquery-2.1.1.min.js

Or make have javascript link like this.

<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>

   <div id="demo-element">
        <span>Full Screen Mode Disabled</span>
        <button id="go-button">Enable Full Screen</button>
    </div>
    <script>
    function GoInFullscreen(element) {
        if(element.requestFullscreen)
            element.requestFullscreen();
        else if(element.mozRequestFullScreen)
            element.mozRequestFullScreen();
        else if(element.webkitRequestFullscreen)
            element.webkitRequestFullscreen();
        else if(element.msRequestFullscreen)
            element.msRequestFullscreen();
    }

    function GoOutFullscreen() {
        if(document.exitFullscreen)
            document.exitFullscreen();
        else if(document.mozCancelFullScreen)
            document.mozCancelFullScreen();
        else if(document.webkitExitFullscreen)
            document.webkitExitFullscreen();
        else if(document.msExitFullscreen)
            document.msExitFullscreen();
    }

    function IsFullScreenCurrently() {
        var full_screen_element = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement || null;

        if(full_screen_element === null)
            return false;
        else
            return true;
    }

    $("#go-button").on('click', function() {
        if(IsFullScreenCurrently())
            GoOutFullscreen();
        else
            GoInFullscreen($("#demo-element").get(0));
    });

    $(document).on('fullscreenchange webkitfullscreenchange mozfullscreenchange MSFullscreenChange', function() {
        if(IsFullScreenCurrently()) {
            $("#demo-element span").text('Full Screen Mode Enabled');
            $("#go-button").text('Disable Full Screen');
        }
        else {
            $("#demo-element span").text('Full Screen Mode Disabled');
            $("#go-button").text('Enable Full Screen');
        }
    });</script>

android - setting LayoutParams programmatically

Just replace from bottom and add this

tv.setLayoutParams(new ViewGroup.LayoutParams(
    ViewGroup.LayoutParams.WRAP_CONTENT,
    ViewGroup.LayoutParams.WRAP_CONTENT));

before

llview.addView(tv);

Can iterators be reset in Python?

One possible option is to use itertools.cycle(), which will allow you to iterate indefinitely without any trick like .seek(0).

iterDic = itertools.cycle(csv.DictReader(open('file.csv')))

Can't Load URL: The domain of this URL isn't included in the app's domains

Adding my localhost on Valid OAuth redirect URIs at https://developers.facebook.com/apps/YOUR_APP_ID/fb-login/ solved the problem!

And pay attention for one detail here:

In this case http://localhost:3000 is not the same of http://0.0.0.0:3000 or http://127.0.0.1:3000

Make sure you are using exactly the running url of you sandbox server. I spend some time to discover that...

enter image description here

How to show all privileges from a user in oracle?

There are various scripts floating around that will do that depending on how crazy you want to get. I would personally use Pete Finnigan's find_all_privs script.

If you want to write it yourself, the query gets rather challenging. Users can be granted system privileges which are visible in DBA_SYS_PRIVS. They can be granted object privileges which are visible in DBA_TAB_PRIVS. And they can be granted roles which are visible in DBA_ROLE_PRIVS (roles can be default or non-default and can require a password as well, so just because a user has been granted a role doesn't mean that the user can necessarily use the privileges he acquired through the role by default). But those roles can, in turn, be granted system privileges, object privileges, and additional roles which can be viewed by looking at ROLE_SYS_PRIVS, ROLE_TAB_PRIVS, and ROLE_ROLE_PRIVS. Pete's script walks through those relationships to show all the privileges that end up flowing to a user.

Multiple submit buttons in the same form calling different Servlets

In addition to the previous response, the best option to submit a form with different buttons without language problems is actually using a button tag.

<form>
    ...
    <button type="submit" name="submit" value="servlet1">Go to 1st Servlet</button>
    <button type="submit" name="submit" value="servlet2">Go to 2nd Servlet</button>
</form>

Android Gradle Apache HttpClient does not exist?

I cloned the following: https://github.com/google/play-licensing

Then I imported that into my project.

Excel formula to remove space between words in a cell

Steps (1) Just Select your range, rows or column or array , (2) Press ctrl+H , (3 a) then in the find type a space (3 b) in the replace do not enter anything, (4)then just click on replace all..... you are done.

How to insert strings containing slashes with sed?

add \ before special characters:

s/\?page=one&/page\/one\//g

etc.

Get Excel sheet name and use as variable in macro

in a Visual Basic Macro you would use

pName = ActiveWorkbook.Path      ' the path of the currently active file
wbName = ActiveWorkbook.Name     ' the file name of the currently active file
shtName = ActiveSheet.Name       ' the name of the currently selected worksheet

The first sheet in a workbook can be referenced by

ActiveWorkbook.Worksheets(1)

so after deleting the [Report] tab you would use

ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name

to "work on that sheet later on" you can create a range object like

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]

and continue working on MySheet(rowNum, colNum) etc. ...

shortcut creation of a range object without defining shtName:

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]

Add Keypair to existing EC2 instance

Once an instance has been started, there is no way to change the keypair associated with the instance at a meta data level, but you can change what ssh key you use to connect to the instance.

stackoverflow.com/questions/7881469/change-key-pair-for-ec2-instance

JSON response parsing in Javascript to get key/value pair

There are two ways to access properties of objects:

var obj = {a: 'foo', b: 'bar'};

obj.a //foo
obj['b'] //bar

Or, if you need to dynamically do it:

var key = 'b';
obj[key] //bar

If you don't already have it as an object, you'll need to convert it.

For a more complex example, let's assume you have an array of objects that represent users:

var users = [{name: 'Corbin', age: 20, favoriteFoods: ['ice cream', 'pizza']},
             {name: 'John', age: 25, favoriteFoods: ['ice cream', 'skittle']}];

To access the age property of the second user, you would use users[1].age. To access the second "favoriteFood" of the first user, you'd use users[0].favoriteFoods[2].

Another example: obj[2].key[3]["some key"]

That would access the 3rd element of an array named 2. Then, it would access 'key' in that array, go to the third element of that, and then access the property name some key.


As Amadan noted, it might be worth also discussing how to loop over different structures.

To loop over an array, you can use a simple for loop:

var arr = ['a', 'b', 'c'],
    i;
for (i = 0; i < arr.length; ++i) {
    console.log(arr[i]);
}

To loop over an object is a bit more complicated. In the case that you're absolutely positive that the object is a plain object, you can use a plain for (x in obj) { } loop, but it's a lot safer to add in a hasOwnProperty check. This is necessary in situations where you cannot verify that the object does not have inherited properties. (It also future proofs the code a bit.)

var user = {name: 'Corbin', age: 20, location: 'USA'},
    key;

for (key in user) {
    if (user.hasOwnProperty(key)) {
        console.log(key + " = " + user[key]);
    }
}    

(Note that I've assumed whatever JS implementation you're using has console.log. If not, you could use alert or some kind of DOM manipulation instead.)

How do I "decompile" Java class files?

Update February 2016:

www.javadecompilers.com lists JAD as being:

the most popular Java decompiler, but primarily of this age only. Written in C++, so very fast.
Outdated, unsupported and does not decompile correctly Java 5 and later

So your mileage may vary with recent jdk (7, 8).

The same site list other tools.

And javadecompiler, as noted by Salvador Valencia in the comments (Sept 2017), offers a SaaS where you upload the .class file to the cloud and it returns you the decompiled code.


Original answer: Oct. 2008

  • The final release of JSR 176, defining the major features of J2SE 5.0 (Java SE 5), has been published on September 30, 2004.
  • The lastest Java version supported by JAD, the famous Java decompiler written by Mr. Pavel Kouznetsov, is JDK 1.3.
  • Most of the Java decompilers downloadable today from the Internet, such as “DJ Java Decompiler” or “Cavaj Java Decompiler”, are powered by JAD: they can not display Java 5 sources.

Java Decompiler (Yet another Fast Java decompiler) has:

  • Explicit support for decompiling and analyzing Java 5+ “.class” files.
  • A nice GUI:

screenshot

It works with compilers from JDK 1.1.8 up to JDK 1.7.0, and others (Jikes, JRockit, etc.).

It features an online live demo version that is actually fully functional! You can just drop a jar file on the page and see the decompiled source code without installing anything.

How to update an "array of objects" with Firestore?

We can use arrayUnion({}) method to achive this.

Try this:

collectionRef.doc(ID).update({
    sharedWith: admin.firestore.FieldValue.arrayUnion({
       who: "[email protected]",
       when: new Date()
    })
});

Documentation can find here: https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array

Jenkins pipeline if else not working

your first try is using declarative pipelines, and the second working one is using scripted pipelines. you need to enclose steps in a steps declaration, and you can't use if as a top-level step in declarative, so you need to wrap it in a script step. here's a working declarative version:

pipeline {
    agent any

    stages {
        stage('test') {
            steps {
                sh 'echo hello'
            }
        }
        stage('test1') {
            steps {
                sh 'echo $TEST'
            }
        }
        stage('test3') {
            steps {
                script {
                    if (env.BRANCH_NAME == 'master') {
                        echo 'I only execute on the master branch'
                    } else {
                        echo 'I execute elsewhere'
                    }
                }
            }
        }
    }
}

you can simplify this and potentially avoid the if statement (as long as you don't need the else) by using "when". See "when directive" at https://jenkins.io/doc/book/pipeline/syntax/. you can also validate jenkinsfiles using the jenkins rest api. it's super sweet. have fun with declarative pipelines in jenkins!

mysqli_select_db() expects parameter 1 to be mysqli, string given

Your arguments are in the wrong order. The connection comes first according to the docs

<?php
require("constants.php");

// 1. Create a database connection
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS);

if (!$connection) {
    error_log("Failed to connect to MySQL: " . mysqli_error($connection));
    die('Internal server error');
}

// 2. Select a database to use 
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
    error_log("Database selection failed: " . mysqli_error($connection));
    die('Internal server error');
}

?>

sqlalchemy filter multiple columns

A generic piece of code that will work for multiple columns. This can also be used if there is a need to conditionally implement search functionality in the application.

search_key = "abc"
search_args = [col.ilike('%%%s%%' % search_key) for col in ['col1', 'col2', 'col3']]
query = Query(table).filter(or_(*search_args))
session.execute(query).fetchall()

Note: the %% are important to skip % formatting the query.

can't access mysql from command line mac

On mac, open the terminal and type:

cd /usr/local/mysql/bin

then type:

./mysql -u root -p

It will ask you for the mysql root password. Enter your password and use mysql database in the terminal.

Function names in C++: Capitalize or not?

Most code I've seen is camelCase functions (lower case initial letter), and ProperCase/PascalCase class names, and (most usually), snake_case variables.

But, to be honest, this is all just guidance. The single most important thing is to be consistent across your code base. Pick what seems natural / works for you, and stick to it. If you're joining a project in progress, follow their standards.

Sql Server equivalent of a COUNTIF aggregate function

I would use this syntax. It achives the same as Josh and Chris's suggestions, but with the advantage it is ANSI complient and not tied to a particular database vendor.

select count(case when myColumn = 1 then 1 else null end)
from   AD_CurrentView

How do I determine height and scrolling position of window in jQuery?

from http://api.jquery.com/height/ (Note: The difference between the use for the window and the document object)

$(window).height();   // returns height of browser viewport
$(document).height(); // returns height of HTML document

from http://api.jquery.com/scrollTop/

$(window).scrollTop() // return the number of pixels scrolled vertically

Spring data jpa- No bean named 'entityManagerFactory' is defined; Injection of autowired dependencies failed

I had the same problem and got it resolved by deleting .m2 maven repo (C:\Users\user\ .m2)

TypeError: Invalid dimensions for image data when plotting array with imshow()

There is a (somewhat) related question on StackOverflow:

Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeezed or sliced into a 2D array.

More generally, the reason for the Exception

TypeError: Invalid dimensions for image data

is shown here: matplotlib.pyplot.imshow() needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!

You can easily check this with (these checks are done by imshow, this function is only meant to give a more specific message in case it's not a valid input):

from __future__ import print_function
import numpy as np

def valid_imshow_data(data):
    data = np.asarray(data)
    if data.ndim == 2:
        return True
    elif data.ndim == 3:
        if 3 <= data.shape[2] <= 4:
            return True
        else:
            print('The "data" has 3 dimensions but the last dimension '
                  'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
                  ''.format(data.shape[2]))
            return False
    else:
        print('To visualize an image the data must be 2 dimensional or '
              '3 dimensional, not "{}".'
              ''.format(data.ndim))
        return False

In your case:

>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False

The np.asarray is what is done internally by matplotlib.pyplot.imshow so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list) it's necessary.


In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()

import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0)  # or axis=1
plt.imshow(a)
plt.show()

enter image description here

or just use something that accepts 1D arrays like plot:

a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()

enter image description here

Count number of occurrences by month

I would add another column on the data sheet with equation =month(A2), then run the countif on that column... If you still wanted to use text month('APRIL'), you would need a lookup table to reference the name to the month number. Otherwise, just use 4 instead of April on your metric sheet.

Regular expression to match a line that doesn't contain a word

Through PCRE verb (*SKIP)(*F)

^hede$(*SKIP)(*F)|^.*$

This would completely skips the line which contains the exact string hede and matches all the remaining lines.

DEMO

Execution of the parts:

Let us consider the above regex by splitting it into two parts.

  1. Part before the | symbol. Part shouldn't be matched.

    ^hede$(*SKIP)(*F)
    
  2. Part after the | symbol. Part should be matched.

    ^.*$
    

PART 1

Regex engine will start its execution from the first part.

^hede$(*SKIP)(*F)

Explanation:

  • ^ Asserts that we are at the start.
  • hede Matches the string hede
  • $ Asserts that we are at the line end.

So the line which contains the string hede would be matched. Once the regex engine sees the following (*SKIP)(*F) (Note: You could write (*F) as (*FAIL)) verb, it skips and make the match to fail. | called alteration or logical OR operator added next to the PCRE verb which inturn matches all the boundaries exists between each and every character on all the lines except the line contains the exact string hede. See the demo here. That is, it tries to match the characters from the remaining string. Now the regex in the second part would be executed.

PART 2

^.*$

Explanation:

  • ^ Asserts that we are at the start. ie, it matches all the line starts except the one in the hede line. See the demo here.
  • .* In the Multiline mode, . would match any character except newline or carriage return characters. And * would repeat the previous character zero or more times. So .* would match the whole line. See the demo here.

    Hey why you added .* instead of .+ ?

    Because .* would match a blank line but .+ won't match a blank. We want to match all the lines except hede , there may be a possibility of blank lines also in the input . so you must use .* instead of .+ . .+ would repeat the previous character one or more times. See .* matches a blank line here.

  • $ End of the line anchor is not necessary here.

How can I convert tabs to spaces in every file of a directory?

Download and run the following script to recursively convert hard tabs to soft tabs in plain text files.

Execute the script from inside the folder which contains the plain text files.

#!/bin/bash

find . -type f -and -not -path './.git/*' -exec grep -Iq . {} \; -and -print | while read -r file; do {
    echo "Converting... "$file"";
    data=$(expand --initial -t 4 "$file");
    rm "$file";
    echo "$data" > "$file";
}; done;

Method with a bool return

Use this code:

public bool roomSelected()
{
    foreach (RadioButton rb in GroupBox1.Controls)
    {
        if (rb.Checked == true)
        {
            return true;
        }
    }
    return false;
}

What is best way to start and stop hadoop ecosystem, with command line?

From Hadoop page,

start-all.sh 

This will startup a Namenode, Datanode, Jobtracker and a Tasktracker on your machine.

start-dfs.sh

This will bring up HDFS with the Namenode running on the machine you ran the command on. On such a machine you would need start-mapred.sh to separately start the job tracker

start-all.sh/stop-all.sh has to be run on the master node

You would use start-all.sh on a single node cluster (i.e. where you would have all the services on the same node.The namenode is also the datanode and is the master node).

In multi-node setup,

You will use start-all.sh on the master node and would start what is necessary on the slaves as well.

Alternatively,

Use start-dfs.sh on the node you want the Namenode to run on. This will bring up HDFS with the Namenode running on the machine you ran the command on and Datanodes on the machines listed in the slaves file.

Use start-mapred.sh on the machine you plan to run the Jobtracker on. This will bring up the Map/Reduce cluster with Jobtracker running on the machine you ran the command on and Tasktrackers running on machines listed in the slaves file.

hadoop-daemon.sh as stated by Tariq is used on each individual node. The master node will not start the services on the slaves.In a single node setup this will act same as start-all.sh.In a multi-node setup you will have to access each node (master as well as slaves) and execute on each of them.

Have a look at this start-all.sh it call config followed by dfs and mapred

Jmeter - Run .jmx file through command line and get the summary report in a excel

You can run JMeter from the command line using the -n parameter for 'Non-GUI' and the -t parameter for the test plan file.

    jmeter -n -t "PATHTOJMXFILE"        

If you want to further customize the command line experience, I would direct you to the 'Getting Started' section of their documentation.

xampp MySQL does not start

You already have a version of mySQL installed on this machine that is using port 3306. Go into the most recent my.ini file and change the port to 3307. Restart the mySQL service and see if it comes up.

You also need to change port 3306 to 3307 in xampp\php\php.ini

Sort a list of lists with a custom compare function

Also, your compare function is incorrect. It needs to return -1, 0, or 1, not a boolean as you have it. The correct compare function would be:

def compare(item1, item2):
    if fitness(item1) < fitness(item2):
        return -1
    elif fitness(item1) > fitness(item2):
        return 1
    else:
        return 0

# Calling
list.sort(key=compare)

how to pass parameter from @Url.Action to controller function

Try this

public ActionResult CreatePerson(string Enc)

 window.location = '@Url.Action("CreatePerson", "Person", new { Enc = "id", actionType = "Disable" })'.replace("id", id).replace("&amp;", "&");

you will get the id inside the Enc string.

How to format strings in Java

public class StringFormat {

    public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            System.out.println("================================");
            for(int i=0;i<3;i++){
                String s1=sc.next();
                int x=sc.nextInt();
                System.out.println(String.format("%-15s%03d",s1,x));
            }
            System.out.println("================================");

    }
}

outpot "================================"
ved15space123 ved15space123 ved15space123 "================================

Java solution

  • The "-" is used to left indent

  • The "15" makes the String's minimum length it takes up be 15

  • The "s" (which is a few characters after %) will be substituted by our String
  • The 0 pads our integer with 0s on the left
  • The 3 makes our integer be a minimum length of 3

GCM with PHP (Google Cloud Messaging)

<?php

function sendMessageToPhone($deviceToken, $collapseKey, $messageText, $yourKey) {    
    echo "DeviceToken:".$deviceToken."Key:".$collapseKey."Message:".$messageText
            ."API Key:".$yourKey."Response"."<br/>";

    $headers = array('Authorization:key=' . $yourKey);    
    $data = array(    
        'registration_id' => $deviceToken,          
        'collapse_key' => $collapseKey,
        'data.message' => $messageText);  
    $ch = curl_init();    

    curl_setopt($ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send");    
    if ($headers)    
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);    
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);    
    curl_setopt($ch, CURLOPT_POST, true);    
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);    
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);    

    $response = curl_exec($ch);    
    var_dump($response);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);    
    if (curl_errno($ch)) {
        return false;
    }    
    if ($httpCode != 200) {
        return false;
    }    
    curl_close($ch);    
    return $response;    
}  

$yourKey = "YOURKEY";
$deviceToken = "REGISTERED_ID";
$collapseKey = "COLLAPSE_KEY";
$messageText = "MESSAGE";
echo sendMessageToPhone($deviceToken, $collapseKey, $messageText, $yourKey);
?>

In above script just change :

"YOURKEY" to API key to Server Key of API console.
"REGISTERED_ID" with your device's registration ID
"COLLAPSE_KEY" with key which you required
"MESSAGE" with message which you want to send

Let me know if you are getting any problem in this I am able to get notification successfully using the same script.

Search for a string in Enum and return the Enum

class EnumStringToInt // to search for a string in enum
{
    enum Numbers{one,two,hree};
    static void Main()
    {
        Numbers num = Numbers.one; // converting enum to string
        string str = num.ToString();
        //Console.WriteLine(str);
        string str1 = "four";
        string[] getnames = (string[])Enum.GetNames(typeof(Numbers));
        int[] getnum = (int[])Enum.GetValues(typeof(Numbers));
        try
        {
            for (int i = 0; i <= getnum.Length; i++)
            {
                if (str1.Equals(getnames[i]))
                {
                    Numbers num1 = (Numbers)Enum.Parse(typeof(Numbers), str1);
                    Console.WriteLine("string found:{0}", num1);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Value not found!", ex);
        }
    }
}

Package doesn't exist error in intelliJ

What happens here is the particular package is not available in the cache. Resetting will help solve the problem.

  1. File -> Invalidate Caches /Restart
  2. Goto terminal and build the project again

    ./gradlew build
    

This should download all the missing packages again

SameSite warning Chrome 77

I had to disable this in chrome://flags

enter image description here

What is the equivalent of Java static methods in Kotlin?

For Java:

public class Constants {
public static final long MAX_CLICK_INTERVAL = 1000;}

Equivalent Kotlin code:

object  Constants {
const val MAX_CLICK_INTERVAL: Long = 1000}

So for the equivalent of Java static methods is object class in Kotlin.

How do I read and parse an XML file in C#?

You could use a DataSet to read XML strings.

var xmlString = File.ReadAllText(FILE_PATH);
var stringReader = new StringReader(xmlString);
var dsSet = new DataSet();
dsSet.ReadXml(stringReader);

Posting this for the sake of information.

ISO C++ forbids comparison between pointer and integer [-fpermissive]| [c++]

char a[2] defines an array of char's. a is a pointer to the memory at the beginning of the array and using == won't actually compare the contents of a with 'ab' because they aren't actually the same types, 'ab' is integer type. Also 'ab' should be "ab" otherwise you'll have problems here too. To compare arrays of char you'd want to use strcmp.

Something that might be illustrative is looking at the typeid of 'ab':

#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
    int some_int =5;
    std::cout << typeid('ab').name() << std::endl;
    std::cout << typeid(some_int).name() << std::endl;
    return 0;
}

on my system this returns:

i
i

showing that 'ab' is actually evaluated as an int.

If you were to do the same thing with a std::string then you would be dealing with a class and std::string has operator == overloaded and will do a comparison check when called this way.

If you wish to compare the input with the string "ab" in an idiomatic c++ way I suggest you do it like so:

#include <iostream>
#include <string>
using namespace std;
int main(){
    string a;
    cout<<"enter ab ";
    cin>>a;
    if(a=="ab"){
         cout<<"correct";
    }
    return 0;
}

This one is due to:

if(a=='ab') , here, a is const char* type (ie : array of char)

'ab' is a constant value,which isn't evaluated as string (because of single quote) but will be evaluated as integer.

Since char is a primitive type inherited from C, no operator == is defined.

the good code should be:

if(strcmp(a,"ab")==0) , then you'll compare a const char* to another const char* using strcmp.