Programs & Examples On #Dozer

Dozer is a Java Bean to Java Bean mapper that recursively copies data from one object to another. Typically, these Java Beans will be of different complex types.

JUnit tests pass in Eclipse but fail in Maven Surefire

This doesn't exactly apply to your situation, but I had the same thing -- tests that would pass in Eclipse failed when the test goal from Maven was run.

It turned out to be a test earlier in my suite, in a different package. This took me a week to solve!

An earlier test was testing some Logback classes, and created a Logback context from a config file.

The later test was testing a subclass of Spring's SimpleRestTemplate, and somehow, the earlier Logback context was held, with DEBUG on. This caused extra calls to be made in RestTemplate to log HttpStatus, etc.

It's another thing to check if one ever gets into this situation. I fixed my problem by injecting some Mocks into my Logback test class, so that no real Logback contexts were created.

Java: recommended solution for deep cloning/copying an instance

For deep cloning (clones the entire object hierarchy):

  • commons-lang SerializationUtils - using serialization - if all classes are in your control and you can force implementing Serializable.

  • Java Deep Cloning Library - using reflection - in cases when the classes or the objects you want to clone are out of your control (a 3rd party library) and you can't make them implement Serializable, or in cases you don't want to implement Serializable.

For shallow cloning (clones only the first level properties):

I deliberately omitted the "do-it-yourself" option - the API's above provide a good control over what to and what not to clone (for example using transient, or String[] ignoreProperties), so reinventing the wheel isn't preferred.

Global variables in R

As Christian's answer with assign() shows, there is a way to assign in the global environment. A simpler, shorter (but not better ... stick with assign) way is to use the <<- operator, ie

    a <<- "new" 

inside the function.

Typescript input onchange event.target.value

as HTMLInputElement works for me

How do I change the ID of a HTML element with JavaScript?

You can modify the id without having to use getElementById

Example:

<div id = 'One' onclick = "One.id = 'Two'; return false;">One</div>

You can see it here: http://jsbin.com/elikaj/1/

Tested with Mozilla Firefox 22 and Google Chrome 60.0

Waiting till the async task finish its work

In your AsyncTask add one ProgressDialog like:

private final ProgressDialog dialog = new ProgressDialog(YourActivity.this);

you can setMessage in onPreExecute() method like:

this.dialog.setMessage("Processing..."); 
this.dialog.show();

and in your onPostExecute(Void result) method dismiss your ProgressDialog.

Different ways of adding to Dictionary

Yes, that is the difference, the Add method throws an exception if the key already exists.

The reason to use the Add method is exactly this. If the dictionary is not supposed to contain the key already, you usually want the exception so that you are made aware of the problem.

Is it possible to use pip to install a package from a private GitHub repository?

As an additional technique, if you have the private repository cloned locally, you can do:

pip install git+file://c:/repo/directory

More modernly, you can just do this (and the -e will mean you don't have to commit changes before they're reflected):

pip install -e C:\repo\directory

AngularJS ui-router login authentication

I have another solution: that solution works perfectly when you have only content you want to show when you are logged in. Define a rule where you checking if you are logged in and its not path of whitelist routes.

$urlRouterProvider.rule(function ($injector, $location) {
   var UserService = $injector.get('UserService');
   var path = $location.path(), normalized = path.toLowerCase();

   if (!UserService.isLoggedIn() && path.indexOf('login') === -1) {
     $location.path('/login/signin');
   }
});

In my example i ask if i am not logged in and the current route i want to route is not part of `/login', because my whitelist routes are the following

/login/signup // registering new user
/login/signin // login to app

so i have instant access to this two routes and every other route will be checked if you are online.

Here is my whole routing file for the login module

export default (
  $stateProvider,
  $locationProvider,
  $urlRouterProvider
) => {

  $stateProvider.state('login', {
    parent: 'app',
    url: '/login',
    abstract: true,
    template: '<ui-view></ui-view>'
  })

  $stateProvider.state('signin', {
    parent: 'login',
    url: '/signin',
    template: '<login-signin-directive></login-signin-directive>'
  });

  $stateProvider.state('lock', {
    parent: 'login',
    url: '/lock',
    template: '<login-lock-directive></login-lock-directive>'
  });

  $stateProvider.state('signup', {
    parent: 'login',
    url: '/signup',
    template: '<login-signup-directive></login-signup-directive>'
  });

  $urlRouterProvider.rule(function ($injector, $location) {
    var UserService = $injector.get('UserService');
    var path = $location.path();

    if (!UserService.isLoggedIn() && path.indexOf('login') === -1) {
         $location.path('/login/signin');
    }
  });

  $urlRouterProvider.otherwise('/error/not-found');
}

() => { /* code */ } is ES6 syntax, use instead function() { /* code */ }

Android - SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length

Check if you have any element such as button or text view duplicated (copied twice) in the screen where this encounters. I did this unnoticed and had to face the same issue.

How to open select file dialog via js?

_x000D_
_x000D_
function promptFile(contentType, multiple) {
  var input = document.createElement("input");
  input.type = "file";
  input.multiple = multiple;
  input.accept = contentType;
  return new Promise(function(resolve) {
    document.activeElement.onfocus = function() {
      document.activeElement.onfocus = null;
      setTimeout(resolve, 500);
    };
    input.onchange = function() {
      var files = Array.from(input.files);
      if (multiple)
        return resolve(files);
      resolve(files[0]);
    };
    input.click();
  });
}
function promptFilename() {
  promptFile().then(function(file) {
    document.querySelector("span").innerText = file && file.name || "no file selected";
  });
}
_x000D_
<button onclick="promptFilename()">Open</button>
<span></span>
_x000D_
_x000D_
_x000D_

git remote add with other SSH port

You need to edit your ~/.ssh/config file. Add something like the following:

Host example.com
    Port 1234

A quick google search shows a few different resources that explain it in more detail than me.

How to start color picker on Mac OS?

You can turn the color picker into an application by following the guide here:

http://hints.macworld.com/article.php?story=20060408050920158

From the guide:

Simply fire up AppleScript (Applications -> AppleScript Editor) and enter this text:

choose color

Now, save it as an application (File -> Save As, and set the File Format pop-up to Application), and you're done

Correct way to handle conditional styling in React

 <div style={{ visibility: this.state.driverDetails.firstName != undefined? 'visible': 'hidden'}}></div>

Checkout the above code. That will do the trick.

How schedule build in Jenkins?

This example is everyday, once around 9am and once around 5pm. (edited per comments).

H 9,17 * * * 

Editing dictionary values in a foreach loop

Call the ToList() in the foreach loop. This way we dont need a temp variable copy. It depends on Linq which is available since .Net 3.5.

using System.Linq;

foreach(string key in colStates.Keys.ToList())
{
  double  Percent = colStates[key] / TotalCount;

    if (Percent < 0.05)
    {
        OtherCount += colStates[key];
        colStates[key] = 0;
    }
}

Display Last Saved Date on worksheet

There is no built in function with this capability. The close would be to save the file in a folder named for the current date and use the =INFO("directory") function.

Why specify @charset "UTF-8"; in your CSS file?

One reason to always include a character set specification on every page containing text is to avoid cross site scripting vulnerabilities. In most cases the UTF-8 character set is the best choice for text, including HTML pages.

How to convert a UTF-8 string into Unicode?

If you have a UTF-8 string, where every byte is correct ('Ö' -> [195, 0] , [150, 0]), you can use the following:

public static string Utf8ToUtf16(string utf8String)
{
    /***************************************************************
     * Every .NET string will store text with the UTF-16 encoding, *
     * known as Encoding.Unicode. Other encodings may exist as     *
     * Byte-Array or incorrectly stored with the UTF-16 encoding.  *
     *                                                             *
     * UTF-8 = 1 bytes per char                                    *
     *    ["100" for the ansi 'd']                                 *
     *    ["206" and "186" for the russian '?']                    *
     *                                                             *
     * UTF-16 = 2 bytes per char                                   *
     *    ["100, 0" for the ansi 'd']                              *
     *    ["186, 3" for the russian '?']                           *
     *                                                             *
     * UTF-8 inside UTF-16                                         *
     *    ["100, 0" for the ansi 'd']                              *
     *    ["206, 0" and "186, 0" for the russian '?']              *
     *                                                             *
     * First we need to get the UTF-8 Byte-Array and remove all    *
     * 0 byte (binary 0) while doing so.                           *
     *                                                             *
     * Binary 0 means end of string on UTF-8 encoding while on     *
     * UTF-16 one binary 0 does not end the string. Only if there  *
     * are 2 binary 0, than the UTF-16 encoding will end the       *
     * string. Because of .NET we don't have to handle this.       *
     *                                                             *
     * After removing binary 0 and receiving the Byte-Array, we    *
     * can use the UTF-8 encoding to string method now to get a    *
     * UTF-16 string.                                              *
     *                                                             *
     ***************************************************************/

    // Get UTF-8 bytes and remove binary 0 bytes (filler)
    List<byte> utf8Bytes = new List<byte>(utf8String.Length);
    foreach (byte utf8Byte in utf8String)
    {
        // Remove binary 0 bytes (filler)
        if (utf8Byte > 0) {
            utf8Bytes.Add(utf8Byte);
        }
    }

    // Convert UTF-8 bytes to UTF-16 string
    return Encoding.UTF8.GetString(utf8Bytes.ToArray());
}

In my case the DLL result is a UTF-8 string too, but unfortunately the UTF-8 string is interpreted with UTF-16 encoding ('Ö' -> [195, 0], [19, 32]). So the ANSI '–' which is 150 was converted to the UTF-16 '–' which is 8211. If you have this case too, you can use the following instead:

public static string Utf8ToUtf16(string utf8String)
{
    // Get UTF-8 bytes by reading each byte with ANSI encoding
    byte[] utf8Bytes = Encoding.Default.GetBytes(utf8String);

    // Convert UTF-8 bytes to UTF-16 bytes
    byte[] utf16Bytes = Encoding.Convert(Encoding.UTF8, Encoding.Unicode, utf8Bytes);

    // Return UTF-16 bytes as UTF-16 string
    return Encoding.Unicode.GetString(utf16Bytes);
}

Or the Native-Method:

[DllImport("kernel32.dll")]
private static extern Int32 MultiByteToWideChar(UInt32 CodePage, UInt32 dwFlags, [MarshalAs(UnmanagedType.LPStr)] String lpMultiByteStr, Int32 cbMultiByte, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpWideCharStr, Int32 cchWideChar);

public static string Utf8ToUtf16(string utf8String)
{
    Int32 iNewDataLen = MultiByteToWideChar(Convert.ToUInt32(Encoding.UTF8.CodePage), 0, utf8String, -1, null, 0);
    if (iNewDataLen > 1)
    {
        StringBuilder utf16String = new StringBuilder(iNewDataLen);
        MultiByteToWideChar(Convert.ToUInt32(Encoding.UTF8.CodePage), 0, utf8String, -1, utf16String, utf16String.Capacity);

        return utf16String.ToString();
    }
    else
    {
        return String.Empty;
    }
}

If you need it the other way around, see Utf16ToUtf8. Hope I could be of help.

Check if value is in select list with JQuery

I know this is kind of an old question by this one works better.

if(!$('.dropdownName[data-dropdown="' + data["item"][i]["name"] + '"] option[value="'+data['item'][i]['id']+'"]')[0]){
  //Doesn't exist, so it isn't a repeat value being added. Go ahead and append.
  $('.dropdownName[data-dropdown="' + data["item"][i]["name"] + '"]').append(option);
}

As you can see in this example, I am searching by unique tags data-dropdown name and the value of the selected option. Of course you don't need these for these to work but I included them so that others could see you can search multi values, etc.

What is an instance variable in Java?

An instance variable is a variable that is a member of an instance of a class (i.e., associated with something created with a new), whereas a class variable is a member of the class itself.

Every instance of a class will have its own copy of an instance variable, whereas there is only one of each static (or class) variable, associated with the class itself.

What’s the difference between a class variable and an instance variable?

This test class illustrates the difference:

public class Test {
   
    public static String classVariable = "I am associated with the class";
    public String instanceVariable = "I am associated with the instance";
    
    public void setText(String string){
        this.instanceVariable = string;
    }
    
    public static void setClassText(String string){
        classVariable = string;
    }
    
    public static void main(String[] args) {
        Test test1 = new Test();
        Test test2 = new Test();
        
        // Change test1's instance variable
        test1.setText("Changed");
        System.out.println(test1.instanceVariable); // Prints "Changed"
        // test2 is unaffected
        System.out.println(test2.instanceVariable); // Prints "I am associated with the instance"
        
        // Change class variable (associated with the class itself)
        Test.setClassText("Changed class text");
        System.out.println(Test.classVariable); // Prints "Changed class text"
        
        // Can access static fields through an instance, but there still is only one
        // (not best practice to access static variables through instance)
        System.out.println(test1.classVariable); // Prints "Changed class text"
        System.out.println(test2.classVariable); // Prints "Changed class text"
    }
}

Time complexity of nested for-loop

First we'll consider loops where the number of iterations of the inner loop is independent of the value of the outer loop's index. For example:

 for (i = 0; i < N; i++) {
     for (j = 0; j < M; j++) {
         sequence of statements
      }
  }

The outer loop executes N times. Every time the outer loop executes, the inner loop executes M times. As a result, the statements in the inner loop execute a total of N * M times. Thus, the total complexity for the two loops is O(N2).

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

It depends on the kind of test double you want to interact with:

  • If you don't use doNothing and you mock an object, the real method is not called
  • If you don't use doNothing and you spy an object, the real method is called

In other words, with mocking the only useful interactions with a collaborator are the ones that you provide. By default functions will return null, void methods do nothing.

ORDER BY items must appear in the select list if SELECT DISTINCT is specified

Distinct and Group By generally do the same kind of thing, for different purposes... They both create a 'working" table in memory based on the columns being Grouped on, (or selected in the Select Distinct clause) - and then populate that working table as the query reads data, adding a new "row" only when the values indicate the need to do so...

The only difference is that in the Group By there are additional "columns" in the working table for any calculated aggregate fields, like Sum(), Count(), Avg(), etc. that need to updated for each original row read. Distinct doesn't have to do this... In the special case where you Group By only to get distinct values, (And there are no aggregate columns in output), then it is probably exactly the same query plan.... It would be interesting to review the query execution plan for the two options and see what it did...

Certainly Distinct is the way to go for readability if that is what you are doing (When your purpose is to eliminate duplicate rows, and you are not calculating any aggregate columns)

Getting Python error "from: can't read /var/mail/Bio"

I ran into a similar error

"from: can't read /var/mail/django.test.utils"

when trying to run a command

>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()

in the tutorial at https://docs.djangoproject.com/en/1.8/intro/tutorial05/

after reading the answer by Tamás I realized I was not trying this command in the python shell but in the termnial (this can happen to those new to linux)

solution was to first enter in the python shell with the command python and when you get these >>> then run any python commands

How can I backup a remote SQL Server database to a local drive?

You can use Copy database ... right click on the remote database ... select tasks and use copy database ... it will asks you about source server and destination server . that your source is the remote and destination is your local instance of sql server.

it's that easy

How to call multiple JavaScript functions in onclick event?

You can add multiple only by code even if you have the second onclick atribute in the html it gets ignored, and click2 triggered never gets printed, you could add one on action the mousedown but that is just an workaround.

So the best to do is add them by code as in:

_x000D_
_x000D_
var element = document.getElementById("multiple_onclicks");_x000D_
element.addEventListener("click", function(){console.log("click3 triggered")}, false);_x000D_
element.addEventListener("click", function(){console.log("click4 triggered")}, false);
_x000D_
<button id="multiple_onclicks" onclick='console.log("click1 triggered");' onclick='console.log("click2 triggered");' onmousedown='console.log("click mousedown triggered");'  > Click me</button>
_x000D_
_x000D_
_x000D_

You need to take care as the events can pile up, and if you would add many events you can loose count of the order they are ran.

jQuery not working with IE 11

The problem was caused because the page was an intranet site, & IE had compatibility mode set to default for this. IE11 does support addEventListener()

How to Populate a DataTable from a Stored Procedure

Use an SqlDataAdapter instead, it's much easier and you don't need to define the column names yourself, it will get the column names from the query results:

using (SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
{
    using (SqlCommand cmd = new SqlCommand("usp_GetABCD", sqlcon))
    {
        cmd.CommandType = CommandType.StoredProcedure;

        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
        {
            DataTable dt = new DataTable();

            da.Fill(dt);
        }
    }
}

How do you clear the SQL Server transaction log?

The SQL Server transaction log needs to be properly maintained in order to prevent its unwanted growth. This means running transaction log backups often enough. By not doing that, you risk the transaction log to become full and start to grow.

Besides the answers for this question I recommend reading and understanding the transaction log common myths. These readings may help understanding the transaction log and deciding what techniques to use to "clear" it:

From 10 most important SQL Server transaction log myths:

Myth: My SQL Server is too busy. I don’t want to make SQL Server transaction log backups

One of the biggest performance intensive operations in SQL Server is an auto-grow event of the online transaction log file. By not making transaction log backups often enough, the online transaction log will become full and will have to grow. The default growth size is 10%. The busier the database is, the quicker the online transaction log will grow if transaction log backups are not created Creating a SQL Server transaction log backup doesn’t block the online transaction log, but an auto-growth event does. It can block all activity in the online transaction log

From Transaction log myths:

Myth: Regular log shrinking is a good maintenance practice

FALSE. Log growth is very expensive because the new chunk must be zeroed-out. All write activity stops on that database until zeroing is finished, and if your disk write is slow or autogrowth size is big, that pause can be huge and users will notice. That’s one reason why you want to avoid growth. If you shrink the log, it will grow again and you are just wasting disk operation on needless shrink-and-grow-again game

How do I check particular attributes exist or not in XML?

You can use LINQ to XML,

XDocument doc = XDocument.Load(file);

var result = (from ele in doc.Descendants("section")
              select ele).ToList();

foreach (var t in result)
{
    if (t.Attributes("split").Count() != 0)
    {
        // Exist
    }

    // Suggestion from @UrbanEsc
    if(t.Attributes("split").Any())
    {

    }
}

OR

 XDocument doc = XDocument.Load(file);

 var result = (from ele in doc.Descendants("section").Attributes("split")
               select ele).ToList();

 foreach (var t in result)
 {
     // Response.Write("<br/>" +  t.Value);
 }

How to get the row number from a datatable?

Why don't you try this

for(int i=0; i < dt.Rows.Count; i++)
{
  // u can use here the i
}

mysql error 1364 Field doesn't have a default values

Its work and tested Copy to Config File: /etc/mysql/my.cnf OR /bin/mysql/my.ini

[mysqld]
port = 3306
sql-mode=""

then restart MySQL

Difference between Destroy and Delete

Basically "delete" sends a query directly to the database to delete the record. In that case Rails doesn't know what attributes are in the record it is deleting nor if there are any callbacks (such as before_destroy).

The "destroy" method takes the passed id, fetches the model from the database using the "find" method, then calls destroy on that. This means the callbacks are triggered.

You would want to use "delete" if you don't want the callbacks to be triggered or you want better performance. Otherwise (and most of the time) you will want to use "destroy".

Toggle visibility property of div

According to the jQuery docs, calling toggle() without parameters will toggle visibility.

$('#play-pause').click(function(){
   $('#video-over').toggle();
});

http://jsfiddle.net/Q47ya/

How can I change the color of a Google Maps marker?

Personally, I think the icons generated by the Google Charts API look great and are easy to customise dynamically.

See my answer on Google Maps API 3 - Custom marker color for default (dot) marker

How to unzip files programmatically in Android?

This is my unzip method, which I use:

private boolean unpackZip(String path, String zipname)
{       
     InputStream is;
     ZipInputStream zis;
     try 
     {
         is = new FileInputStream(path + zipname);
         zis = new ZipInputStream(new BufferedInputStream(is));          
         ZipEntry ze;

         while((ze = zis.getNextEntry()) != null) 
         {
             ByteArrayOutputStream baos = new ByteArrayOutputStream();
             byte[] buffer = new byte[1024];
             int count;

             String filename = ze.getName();
             FileOutputStream fout = new FileOutputStream(path + filename);

             // reading and writing
             while((count = zis.read(buffer)) != -1) 
             {
                 baos.write(buffer, 0, count);
                 byte[] bytes = baos.toByteArray();
                 fout.write(bytes);             
                 baos.reset();
             }

             fout.close();               
             zis.closeEntry();
         }

         zis.close();
     } 
     catch(IOException e)
     {
         e.printStackTrace();
         return false;
     }

    return true;
}

How add class='active' to html menu with php

             <ul>

                <li><a <?php echo ($page == "yourfilename") ? "class='active'" : ""; ?> href="user.php" ><span>Article</span></a></li>
                <li><a <?php echo ($page == "yourfilename") ? "class='active'" : ""; ?> href="newarticle.php"><span>New Articles</span></a></li>

                </ul>

Asp.net - Add blank item at top of dropdownlist

I think a better way is to insert the blank item first, then bind the data just as you have been doing. However you need to set the AppendDataBoundItems property of the list control.

We use the following method to bind any data source to any list control...

public static void BindList(ListControl list, IEnumerable datasource, string valueName, string textName)
{
    list.Items.Clear();
    list.Items.Add("", "");
    list.AppendDataBoundItems = true;
    list.DataValueField = valueName;
    list.DataTextField = textName;
    list.DataSource = datasource;
    list.DataBind();
}

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

Try this one (removes all elements in the list that equal i):

for (Object i : l) {
    if (condition(i)) {
        l = (l.stream().filter((a) -> a != i)).collect(Collectors.toList());
    }
}

Calculate correlation with cor(), only for numerical columns

I found an easier way by looking at the R script generated by Rattle. It looks like below:

correlations <- cor(mydata[,c(1,3,5:87,89:90,94:98)], use="pairwise", method="spearman")

How do I fix a NoSuchMethodError?

Why anybody doesn't mention dependency conflicts? This common problem can be related to included dependency jars with different versions. Detailed explanation and solution: https://dzone.com/articles/solving-dependency-conflicts-in-maven

Short answer;

Add this maven dependency;

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.0.0-M3</version>
<configuration>
    <rules>
        <dependencyConvergence />
    </rules>
</configuration>
</plugin>

Then run this command;

mvn enforcer:enforce

Maybe this is the cause your the issue you faced.

How to change the background color of a UIButton while it's highlighted?

Not sure if this sort of solves what you're after, or fits with your general development landscape but the first thing I would try would be to change the background colour of the button on the touchDown event.

Option 1:

You would need two events to be capture, UIControlEventTouchDown would be for when the user presses the button. UIControlEventTouchUpInside and UIControlEventTouchUpOutside will be for when they release the button to return it to the normal state

UIButton *myButton =  [UIButton buttonWithType:UIButtonTypeCustom];
[myButton setFrame:CGRectMake(10.0f, 10.0f, 100.0f, 20.f)];
[myButton setBackgroundColor:[UIColor blueColor]];
[myButton setTitle:@"click me:" forState:UIControlStateNormal];
[myButton setTitle:@"changed" forState:UIControlStateHighlighted];
[myButton addTarget:self action:@selector(buttonHighlight:) forControlEvents:UIControlEventTouchDown];
[myButton addTarget:self action:@selector(buttonNormal:) forControlEvents:UIControlEventTouchUpInside];

Option 2:

Return an image made from the highlight colour you want. This could also be a category.

+ (UIImage *)imageWithColor:(UIColor *)color {
   CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
   UIGraphicsBeginImageContext(rect.size);
   CGContextRef context = UIGraphicsGetCurrentContext();

   CGContextSetFillColorWithColor(context, [color CGColor]);
   CGContextFillRect(context, rect);

   UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();

   return image;
}

and then change the highlighted state of the button:

[myButton setBackgroundImage:[self imageWithColor:[UIColor greenColor]] forState:UIControlStateHighlighted];

Find the server name for an Oracle database

If you don't have access to the v$ views (as suggested by Quassnoi) there are two alternatives

select utl_inaddr.get_host_name from dual

and

select sys_context('USERENV','SERVER_HOST') from dual

Personally I'd tend towards the last as it doesn't require any grants/privileges which makes it easier from stored procedures.

How can I create a marquee effect?

With a small change of the markup, here's my approach (I've just inserted a span inside the paragraph):

_x000D_
_x000D_
.marquee {
  width: 450px;
  margin: 0 auto;
  overflow: hidden;
  box-sizing: border-box;
}

.marquee span {
  display: inline-block;
  width: max-content;

  padding-left: 100%;
  /* show the marquee just outside the paragraph */
  will-change: transform;
  animation: marquee 15s linear infinite;
}

.marquee span:hover {
  animation-play-state: paused
}


@keyframes marquee {
  0% { transform: translate(0, 0); }
  100% { transform: translate(-100%, 0); }
}


/* Respect user preferences about animations */

@media (prefers-reduced-motion: reduce) {
  .marquee span {
    animation-iteration-count: 1;
    animation-duration: 0.01; 
    /* instead of animation: none, so an animationend event is 
     * still available, if previously attached.
     */
    width: auto;
    padding-left: 0;
  }
}
_x000D_
<p class="marquee">
   <span>
       When I had journeyed half of our life's way, I found myself
       within a shadowed forest, for I had lost the path that 
       does not stray. – (Dante Alighieri, <i>Divine Comedy</i>. 
       1265-1321)
   </span>
   </p>
_x000D_
_x000D_
_x000D_


No hardcoded values — dependent on paragraph width — have been inserted.

The animation applies the CSS3 transform property (use prefixes where needed) so it performs well.

If you need to insert a delay just once at the beginning then also set an animation-delay. If you need instead to insert a small delay at every loop then try to play with an higher padding-left (e.g. 150%)

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 get the selected date value while using Bootstrap Datepicker?

For bootstrap datepicker you can use:

$("#inputWithDatePicer").data('datepicker').getFormattedDate('yyyy-mm-dd');

List an Array of Strings in alphabetical order

Weird, your code seems to work for me:

import java.util.Arrays;

public class Test
{
    public static void main(String[] args)
    {
        // args is the list of guests
        Arrays.sort(args);
        for(int i = 0; i < args.length; i++)
            System.out.println(args[i]);
    }
}

I ran that code using "java Test Bobby Joe Angel" and here is the output:

$ java Test Bobby Joe Angel
Angel
Bobby
Joe

Pass a JavaScript function as parameter

You can use a JSON as well to store and send JS functions.

Check the following:

var myJSON = 
{
    "myFunc1" : function (){
        alert("a");
    }, 
    "myFunc2" : function (functionParameter){
        functionParameter();
    }
}



function main(){
    myJSON.myFunc2(myJSON.myFunc1);
}

This will print 'a'.

The following has the same effect with the above:

var myFunc1 = function (){
    alert('a');
}

var myFunc2 = function (functionParameter){
    functionParameter();
}

function main(){
    myFunc2(myFunc1);
}

Which is also has the same effect with the following:

function myFunc1(){
    alert('a');
}


function myFunc2 (functionParameter){
    functionParameter();
}

function main(){
    myFunc2(myFunc1);
}

And a object paradigm using Class as object prototype:

function Class(){
    this.myFunc1 =  function(msg){
        alert(msg);
    }

    this.myFunc2 = function(callBackParameter){
        callBackParameter('message');
    }
}


function main(){    
    var myClass = new Class();  
    myClass.myFunc2(myClass.myFunc1);
}

Delete a database in phpMyAdmin

  1. Connect to your localhost.
  2. Open your favorite browser.
  3. Make sure your localhost is working.
  4. Type in url= localhost.
  5. Scroll down click on phpadmin once phpadmin is open.
  6. Click on database.
  7. Mark check the database you want remove.
  8. Click on drop.

If this don't work

  1. Click on database go to operation
  2. Click drop database

How to set 'X-Frame-Options' on iframe?

Since the solution wasn't really mentioned for the server side:

One has to set things like this (example from apache), this isn't the best option as it allows in everything, but after you see your server working correctly you can easily change the settings.

           Header set Access-Control-Allow-Origin "*"
           Header set X-Frame-Options "allow-from *"

Linq order by, group by and order by each group?

I think you want an additional projection that maps each group to a sorted-version of the group:

.Select(group => group.OrderByDescending(student => student.Grade))

It also appears like you might want another flattening operation after that which will give you a sequence of students instead of a sequence of groups:

.SelectMany(group => group)

You can always collapse both into a single SelectMany call that does the projection and flattening together.


EDIT: As Jon Skeet points out, there are certain inefficiencies in the overall query; the information gained from sorting each group is not being used in the ordering of the groups themselves. By moving the sorting of each group to come before the ordering of the groups themselves, the Max query can be dodged into a simpler First query.

Linux: is there a read or recv from socket with timeout?

Install a handler for SIGALRM, then use alarm() or ualarm() before a regular blocking recv(). If the alarm goes off, the recv() will return an error with errno set to EINTR.

The easiest way to transform collection to array?

For example, you have collection ArrayList with elements Student class:

List stuList = new ArrayList();
Student s1 = new Student("Raju");
Student s2 = new Student("Harish");
stuList.add(s1);
stuList.add(s2);
//now you can convert this collection stuList to Array like this
Object[] stuArr = stuList.toArray();           // <----- toArray() function will convert collection to array

How do I add multiple "NOT LIKE '%?%' in the WHERE clause of sqlite3?

I'm not sure why you're avoiding the AND clause. It is the simplest solution.

Otherwise, you would need to do an INTERSECT of multiple queries:

SELECT word FROM table WHERE word NOT LIKE '%a%'
INTERSECT
SELECT word FROM table WHERE word NOT LIKE '%b%'
INTERSECT
SELECT word FROM table WHERE word NOT LIKE '%c%';

Alternatively, you can use a regular expression if your version of SQL supports it.

How do I divide so I get a decimal value?

Please Convert your input in double and divide.

How to pass url arguments (query string) to a HTTP request on Angular?

You can use Url Parameters from the official documentation.

Example: this.httpClient.get(this.API, { params: new HttpParams().set('noCover', noCover) })

How to clear the cache in NetBeans

The NetBeans cachedir is a directory consisting of files that may become large, may change frequently, and can be deleted and recreated at any time. For example, the results of the Java classpath scan reside in the cachedir.

NetBeans 7.1 and older By default the userdir is inside a (hidden) directory called .netbeans stored in the user's home directory. The home directory is ${HOME} on Unix-like systems, and %USERPROFILE% (usually set to C:\Documents and Settings\) on Windows. The cachedir can be found in var/cache subfolder of the userdir. As the name suggests, the userdir is unique per user. For each version of NetBeans installed, the userdir will be a unique subdirectory such as .netbeans/. To find out your exact userdir location, go to the IDE's main menu, and choose Help > About. (Mac: NetBeans > About NetBeans). NetBeans 7.1 allows to separate the cache directory using a switch --cachedir to a desired location.

Examples A Windows user jdoe running NetBeans 5.0 is likely to find his userdir under C:\Documents and Settings\jdoe.netbeans\5.0\ A Windows Vista user jdoe running NetBeans 5.0 is likely to find his userdir under C:\Users\jdoe.netbeans\5.0\ A Mac OS X user jdoe running NetBeans 5.0 is likely to find his userdir under /Users/jdoe/.netbeans/5.0/ (To open this folder in the Finder, choose Go > Go to Folder from the Finder menu, type /Users/jdoe/.netbeans/5.0/ into the box, and click Go.) A Linux user jdoe running NetBeans 5.0 is likely to find his userdir under /home/jdoe/.netbeans/5.0/

For More Info

See this documentation at the NetBeans site: NetBeans 7.2 and newer

Open mvc view in new window from controller

You can use Tommy's method in forms as well:

@using (Html.BeginForm("Action", "Controller", FormMethod.Get, new { target = "_blank" }))
{
//code
}

Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>

You can convert the IEnumerable to IQueryable.

items = items.AsQueryable().OrderBy("Name ASC");

How to pause for specific amount of time? (Excel/VBA)

Wait and Sleep functions lock Excel and you can't do anything else until the delay finishes. On the other hand Loop delays doesn't give you an exact time to wait.

So, I've made this workaround joining a little bit of both concepts. It loops until the time is the time you want.

Private Sub Waste10Sec()
   target = (Now + TimeValue("0:00:10"))
   Do
       DoEvents 'keeps excel running other stuff
   Loop Until Now >= target
End Sub

You just need to call Waste10Sec where you need the delay

Accessing JSON object keys having spaces

The way to do this is via the bracket notation.

_x000D_
_x000D_
var test = {_x000D_
    "id": "109",_x000D_
    "No. of interfaces": "4"_x000D_
}_x000D_
alert(test["No. of interfaces"]);
_x000D_
_x000D_
_x000D_

For more info read out here:

Can I apply multiple background colors with CSS3?

In case someone needs a CSS background with different color repeating horizontal stripes, here is how I managed to achieve this:

_x000D_
_x000D_
body {_x000D_
  font-family: 'Lucida Grande', 'Helvetica Neue', Helvetica, Arial, sans-serif;_x000D_
  font-size: 13px;_x000D_
}_x000D_
_x000D_
.css-stripes {_x000D_
  margin: 0 auto;_x000D_
  width: 200px;_x000D_
  padding: 100px;_x000D_
  text-align: center;_x000D_
  /* For browsers that do not support gradients */_x000D_
  background-color: #F691FF;_x000D_
  /* Safari 5.1 to 6.0 */_x000D_
  background: -webkit-repeating-linear-gradient(#F691FF, #EC72A8);_x000D_
  /* Opera 11.1 to 12.0 */_x000D_
  background: -o-repeating-linear-gradient(#F691FF, #EC72A8);_x000D_
  /* Firefox 3.6 to 15 */_x000D_
  background: -moz-repeating-linear-gradient(#F691FF, #EC72A8);_x000D_
  /* Standard syntax */_x000D_
  background-image: repeating-linear-gradient(to top, #F691FF, #EC72A8);_x000D_
  background-size: 1px 2px;_x000D_
}
_x000D_
<div class="css-stripes">Hello World!</div>
_x000D_
_x000D_
_x000D_

JSfiddle

PHP + curl, HTTP POST sample code?

If the form is using redirects, authentication, cookies, SSL (https), or anything else other than a totally open script expecting POST variables, you are going to start gnashing your teeth really quick. Take a look at Snoopy, which does exactly what you have in mind while removing the need to set up a lot of the overhead.

How to render string with html tags in Angular 4+?

Use one way flow syntax property binding:

<div [innerHTML]="comment"></div>

From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the <b> element."

Python - TypeError: 'int' object is not iterable

Your problem is with this line:

number4 = list(cow[n])

It tries to take cow[n], which returns an integer, and make it a list. This doesn't work, as demonstrated below:

>>> a = 1
>>> list(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>>

Perhaps you meant to put cow[n] inside a list:

number4 = [cow[n]]

See a demonstration below:

>>> a = 1
>>> [a]
[1]
>>>

Also, I wanted to address two things:

  1. Your while-statement is missing a : at the end.
  2. It is considered very dangerous to use input like that, since it evaluates its input as real Python code. It would be better here to use raw_input and then convert the input to an integer with int.

To split up the digits and then add them like you want, I would first make the number a string. Then, since strings are iterable, you can use sum:

>>> a = 137
>>> a = str(a)
>>> # This way is more common and preferred
>>> sum(int(x) for x in a)
11
>>> # But this also works
>>> sum(map(int, a))
11
>>>

Using jquery to get all checked checkboxes with a certain class name

$(document).ready(function(){
    $('input.checkD[type="checkbox"]').click(function(){
        if($(this).prop("checked") == true){
            $(this).val('true');
        }
        else if($(this).prop("checked") == false){
            $(this).val('false');
        }
    });
});

Sass - Converting Hex to RGBa for background opacity

SASS has a built-in rgba() function to evaluate values.

rgba($color, $alpha)

E.g.

rgba(#00aaff, 0.5) => rgba(0, 170, 255, 0.5)

An example using your own variables:

$my-color: #00aaff;
$my-opacity: 0.5;

.my-element {
  color: rgba($my-color, $my-opacity);
}

Outputs:

.my-element {
  color: rgba(0, 170, 255, 0.5);
}

how to create dynamic two dimensional array in java?

How about making a custom class containing an array, and use the array of your custom class.

How do I install Maven with Yum?

Maven is packaged for Fedora since mid 2014, so it is now pretty easy. Just type

sudo dnf install maven

Now test the installation, just run maven in a random directory

mvn

And it will fail, because you did not specify a goal, e.g. mvn package

[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.102 s
[INFO] Finished at: 2017-11-14T13:45:00+01:00
[INFO] Final Memory: 8M/176M
[INFO] ------------------------------------------------------------------------
[ERROR] No goals have been specified for this build

[...]

How to Consolidate Data from Multiple Excel Columns All into One Column

You didn't mention if you are using Excel 2003 or 2007, but you may run into an issue with the # of rows in Excel 2003 being capped at 65,536. If you are using 2007, the limit is 1,048,576.

Also, can I ask what your end goal is for your analysis? If you need to perform many statistical calculations on your data, I would recommend moving out of the Excel environment into something that is more directly suited for data manipulation and analysis, such as R.

There are a variety of options for connecting R to Excel, including

  1. RExcel
  2. RODBC
  3. Other options in the R manual

Regardless of what you choose to use to move data in/out of R, the code to change from wide to long format is pretty trivial. I enjoy the melt() function from the reshape package. That code would look like:

library(reshape)
#Fake data, 4 columns, 20k rows
df <- data.frame(foo = rnorm(20000)
    , bar = rlnorm(20000)
    , fee = rnorm(20000)
    , fie = rlnorm(20000)
)
#Create new object with 1 column, 80k rows
df.m <- melt(df)

From there, you can perform any number of statistical or graphing operations. If you use the RExcel plugin above, you can fire all of this up and run it within Excel itself. The R community is very active and can help address any and all questions you may encounter.

Good luck!

How can I detect if Flash is installed and if not, display a hidden div that informs the user?

I used Adobe's detection kit, originally suggested by justpassinby. Their system is nice because it detects the version number and compares it for you against your 'required version'

One bad thing is it does an alert showing the detected version of flash, which isn't very user friendly. All of a sudden a box pops up with some seemingly random numbers.

Some modifications you might want to consider:

  • remove the alert
  • change it so it returns an object (or array) --- first element is boolean true/false for "was the required version found on user's machine" --- second element is the actual version number found on user's machine

Add new row to excel Table (VBA)

I actually just found that if you want to add multiple rows below the selection in your table Selection.ListObject.ListRows.Add AlwaysInsert:=True works really well. I just duplicated the code five times to add five rows to my table

How to revert initial git commit?

You can delete the HEAD and restore your repository to a new state, where you can create a new initial commit:

git update-ref -d HEAD

After you create a new commit, if you have already pushed to remote, you will need to force it to the remote in order to overwrite the previous initial commit:

git push --force origin

Environment Specific application.properties file in Spring Boot application

My Point , IN this arent way asking developer to create all environment related in single go, resulting in risk of exposing Production Configuration to end developer

as per 12-Factor, shouldnt be enviornment specific reside in Enviornment only .

How do we do for CI CD

  • Build Spring one time and promote to aother environment, in that case, if we have spring jar has all environment, it iwll security risk, having all environment variable in GIT

convert datetime to date format dd/mm/yyyy

Here is a method, that takes datetime(format:01-01-2012 12:00:00) and returns string(format: 01-01-2012)

public static string GetDateFromDateTime(DateTime datevalue){
    return datevalue.ToShortDateString(); 
}

How to use nanosleep() in C? What are `tim.tv_sec` and `tim.tv_nsec`?

tv_nsec is the sleep time in nanoseconds. 500000us = 500000000ns, so you want:

nanosleep((const struct timespec[]){{0, 500000000L}}, NULL);

Excel VBA - Pass a Row of Cell Values to an Array and then Paste that Array to a Relative Reference of Cells

When i Tried your Code i got en Error when i wanted to fill the Array.

you can try to fill the Array like This.

Sub Testing_Data()
Dim k As Long, S2 As Worksheet, VArray

Application.ScreenUpdating = False
Set S2 = ThisWorkbook.Sheets("Sheet1")
With S2
    VArray = .Range("A1:A" & .Cells(Rows.Count, "A").End(xlUp).Row)
End With
For k = 2 To UBound(VArray, 1)
    S2.Cells(k, "B") = VArray(k, 1) / 100
    S2.Cells(k, "C") = VArray(k, 1) * S2.Cells(k, "B")
Next

End Sub

Max size of an iOS application

Please be aware that the warning on iTunes Connect does not say anything about the limit being only for over-the-air delivery. It would be preferable if the warning mentioned this.

enter image description here

How to parse Excel (XLS) file in Javascript/HTML5

XLS is a binary proprietary format used by Microsoft. Parsing XLS with server side languages is very difficult without using some specific library or Office Interop. Doing this with javascript is mission impossible. Thanks to the HTML5 File API you can read its binary contents but in order to parse and interpret it you will need to dive into the specifications of the XLS format. Starting from Office 2007, Microsoft embraced the Open XML file formats (xslx for Excel) which is a standard.

Firebug like plugin for Safari browser

Other than the builtin developer tools, there is none that i know of. You might, however, be able to use Firebug Lite.

Convert a Python int into a big-endian string of bytes

Using the bitstring module:

>>> bitstring.BitArray(uint=1245427, length=24).bytes
'\x13\x00\xf3'

Note though that for this method you need to specify the length in bits of the bitstring you are creating.

Internally this is pretty much the same as Alex's answer, but the module has a lot of extra functionality available if you want to do more with your data.

How to overwrite the output directory in spark

df.write.mode('overwrite').parquet("/output/folder/path") works if you want to overwrite a parquet file using python. This is in spark 1.6.2. API may be different in later versions

How does DISTINCT work when using JPA and Hibernate

Depending on the underlying JPQL or Criteria API query type, DISTINCT has two meanings in JPA.

Scalar queries

For scalar queries, which return a scalar projection, like the following query:

List<Integer> publicationYears = entityManager
.createQuery(
    "select distinct year(p.createdOn) " +
    "from Post p " +
    "order by year(p.createdOn)", Integer.class)
.getResultList();

LOGGER.info("Publication years: {}", publicationYears);

The DISTINCT keyword should be passed to the underlying SQL statement because we want the DB engine to filter duplicates prior to returning the result set:

SELECT DISTINCT
    extract(YEAR FROM p.created_on) AS col_0_0_
FROM
    post p
ORDER BY
    extract(YEAR FROM p.created_on)

-- Publication years: [2016, 2018]

Entity queries

For entity queries, DISTINCT has a different meaning.

Without using DISTINCT, a query like the following one:

List<Post> posts = entityManager
.createQuery(
    "select p " +
    "from Post p " +
    "left join fetch p.comments " +
    "where p.title = :title", Post.class)
.setParameter(
    "title", 
    "High-Performance Java Persistence eBook has been released!"
)
.getResultList();

LOGGER.info(
    "Fetched the following Post entity identifiers: {}", 
    posts.stream().map(Post::getId).collect(Collectors.toList())
);

is going to JOIN the post and the post_comment tables like this:

SELECT p.id AS id1_0_0_,
       pc.id AS id1_1_1_,
       p.created_on AS created_2_0_0_,
       p.title AS title3_0_0_,
       pc.post_id AS post_id3_1_1_,
       pc.review AS review2_1_1_,
       pc.post_id AS post_id3_1_0__
FROM   post p
LEFT OUTER JOIN
       post_comment pc ON p.id=pc.post_id
WHERE
       p.title='High-Performance Java Persistence eBook has been released!'

-- Fetched the following Post entity identifiers: [1, 1]

But the parent post records are duplicated in the result set for each associated post_comment row. For this reason, the List of Post entities will contain duplicate Post entity references.

To eliminate the Post entity references, we need to use DISTINCT:

List<Post> posts = entityManager
.createQuery(
    "select distinct p " +
    "from Post p " +
    "left join fetch p.comments " +
    "where p.title = :title", Post.class)
.setParameter(
    "title", 
    "High-Performance Java Persistence eBook has been released!"
)
.getResultList();
 
LOGGER.info(
    "Fetched the following Post entity identifiers: {}", 
    posts.stream().map(Post::getId).collect(Collectors.toList())
);

But then DISTINCT is also passed to the SQL query, and that's not desirable at all:

SELECT DISTINCT
       p.id AS id1_0_0_,
       pc.id AS id1_1_1_,
       p.created_on AS created_2_0_0_,
       p.title AS title3_0_0_,
       pc.post_id AS post_id3_1_1_,
       pc.review AS review2_1_1_,
       pc.post_id AS post_id3_1_0__
FROM   post p
LEFT OUTER JOIN
       post_comment pc ON p.id=pc.post_id
WHERE
       p.title='High-Performance Java Persistence eBook has been released!'
 
-- Fetched the following Post entity identifiers: [1]

By passing DISTINCT to the SQL query, the EXECUTION PLAN is going to execute an extra Sort phase which adds overhead without bringing any value since the parent-child combinations always return unique records because of the child PK column:

Unique  (cost=23.71..23.72 rows=1 width=1068) (actual time=0.131..0.132 rows=2 loops=1)
  ->  Sort  (cost=23.71..23.71 rows=1 width=1068) (actual time=0.131..0.131 rows=2 loops=1)
        Sort Key: p.id, pc.id, p.created_on, pc.post_id, pc.review
        Sort Method: quicksort  Memory: 25kB
        ->  Hash Right Join  (cost=11.76..23.70 rows=1 width=1068) (actual time=0.054..0.058 rows=2 loops=1)
              Hash Cond: (pc.post_id = p.id)
              ->  Seq Scan on post_comment pc  (cost=0.00..11.40 rows=140 width=532) (actual time=0.010..0.010 rows=2 loops=1)
              ->  Hash  (cost=11.75..11.75 rows=1 width=528) (actual time=0.027..0.027 rows=1 loops=1)
                    Buckets: 1024  Batches: 1  Memory Usage: 9kB
                    ->  Seq Scan on post p  (cost=0.00..11.75 rows=1 width=528) (actual time=0.017..0.018 rows=1 loops=1)
                          Filter: ((title)::text = 'High-Performance Java Persistence eBook has been released!'::text)
                          Rows Removed by Filter: 3
Planning time: 0.227 ms
Execution time: 0.179 ms

Entity queries with HINT_PASS_DISTINCT_THROUGH

To eliminate the Sort phase from the execution plan, we need to use the HINT_PASS_DISTINCT_THROUGH JPA query hint:

List<Post> posts = entityManager
.createQuery(
    "select distinct p " +
    "from Post p " +
    "left join fetch p.comments " +
    "where p.title = :title", Post.class)
.setParameter(
    "title", 
    "High-Performance Java Persistence eBook has been released!"
)
.setHint(QueryHints.HINT_PASS_DISTINCT_THROUGH, false)
.getResultList();
 
LOGGER.info(
    "Fetched the following Post entity identifiers: {}", 
    posts.stream().map(Post::getId).collect(Collectors.toList())
);

And now, the SQL query will not contain DISTINCT but Post entity reference duplicates are going to be removed:

SELECT
       p.id AS id1_0_0_,
       pc.id AS id1_1_1_,
       p.created_on AS created_2_0_0_,
       p.title AS title3_0_0_,
       pc.post_id AS post_id3_1_1_,
       pc.review AS review2_1_1_,
       pc.post_id AS post_id3_1_0__
FROM   post p
LEFT OUTER JOIN
       post_comment pc ON p.id=pc.post_id
WHERE
       p.title='High-Performance Java Persistence eBook has been released!'
 
-- Fetched the following Post entity identifiers: [1]

And the Execution Plan is going to confirm that we no longer have an extra Sort phase this time:

Hash Right Join  (cost=11.76..23.70 rows=1 width=1068) (actual time=0.066..0.069 rows=2 loops=1)
  Hash Cond: (pc.post_id = p.id)
  ->  Seq Scan on post_comment pc  (cost=0.00..11.40 rows=140 width=532) (actual time=0.011..0.011 rows=2 loops=1)
  ->  Hash  (cost=11.75..11.75 rows=1 width=528) (actual time=0.041..0.041 rows=1 loops=1)
        Buckets: 1024  Batches: 1  Memory Usage: 9kB
        ->  Seq Scan on post p  (cost=0.00..11.75 rows=1 width=528) (actual time=0.036..0.037 rows=1 loops=1)
              Filter: ((title)::text = 'High-Performance Java Persistence eBook has been released!'::text)
              Rows Removed by Filter: 3
Planning time: 1.184 ms
Execution time: 0.160 ms

Spring Boot + JPA : Column name annotation ignored

I also tried all the above and nothing works. I got field called "gunName" in DB and i couldn't handle this, till i used example below:

@Column(name="\"gunName\"")
public String gunName;

with properties:

spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

also see this: https://stackoverflow.com/a/35708531

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

If you are using Python 3.7.3 and Windows 10 64-bit machine then try the following command. Go to the download folder and Install following command:

pip install PyAudio-0.2.11-cp37-cp37m-win_amd64.whl

and it should work.

How to open the Chrome Developer Tools in a new window?

Just type ctrl+shift+I in google chrome & you will land in an isolated developer window.

MSSQL Error 'The underlying provider failed on Open'

When you receive this exception, make sure to expand the detail and look at the inner exception details as it will provide details on why the login failed. In my case the connection string contained a user that did not have access to my database.

Regardless of whether you use Integrated Security (the context of the logged in Windows User) or an individual SQL account, make sure that the user has proper access under 'Security' for the database you are trying to access to prevent this issue.

Return a value if no rows are found in Microsoft tSQL

My solition is working

can testing by change where 1=2 to where 1=1

select * from (
    select col_x,case when count(1) over (partition by 1) =1 then 1 else HIDE end as HIDE from (
    select 'test' col_x,1 as HIDE
    where 1=2
    union 
    select 'if no rows write here that you want' as col_x,0 as HIDE
    ) a
    ) b where HIDE=1

Flexbox: how to get divs to fill up 100% of the container width without wrapping?

In my case, just using flex-shrink: 0 didn't work. But adding flex-grow: 1 to it worked.

.item {
    flex-shrink: 0;
    flex-grow: 1;
}

How to get whole and decimal part of a number?

Cast it as an int and subtract

$integer = (int)$your_number;
$decimal = $your_number - $integer;

Or just to get the decimal for comparison

$decimal = $your_number - (int)$your_number

List supported SSL/TLS versions for a specific OpenSSL build

This worked for me:

openssl s_client -help 2>&1  > /dev/null | egrep "\-(ssl|tls)[^a-z]"

Please let me know if this is wrong.

How do I order my SQLITE database in descending order, for an android app?

This a terrible thing! It costs my a few hours! this is my table rows :

private String USER_ID = "user_id";
private String REMEMBER_UN = "remember_un";
private String REMEMBER_PWD = "remember_pwd";
private String HEAD_URL = "head_url";
private String USER_NAME = "user_name";
private String USER_PPU = "user_ppu";
private String CURRENT_TIME = "current_time";

Cursor c = db.rawQuery("SELECT * FROM " + TABLE +" ORDER BY " + CURRENT_TIME + " DESC",null);

Every time when I update the table , I will update the CURRENT_TIME for sort. But I found that it is not work.The result is not sorted what I want. Finally, I found that, the column "current_time" is the default row of sqlite.

The solution is, rename the column "cur_time" instead of "current_time".

Removing spaces from a variable input using PowerShell 4.0

The Replace operator means Replace something with something else; do not be confused with removal functionality.

Also you should send the result processed by the operator to a variable or to another operator. Neither .Replace(), nor -replace modifies the original variable.

To remove all spaces, use 'Replace any space symbol with empty string'

$string = $string -replace '\s',''

To remove all spaces at the beginning and end of the line, and replace all double-and-more-spaces or tab symbols to spacebar symbol, use

$string = $string -replace '(^\s+|\s+$)','' -replace '\s+',' '

or the more native System.String method

$string = $string.Trim()

Regexp is preferred, because ' ' means only 'spacebar' symbol, and '\s' means 'spacebar, tab and other space symbols'. Note that $string.Replace() does 'Normal' replace, and $string -replace does RegEx replace, which is more heavy but more functional.

Note that RegEx have some special symbols like dot (.), braces ([]()), slashes (\), hats (^), mathematical signs (+-) or dollar signs ($) that need do be escaped. ( 'my.space.com' -replace '\.','-' => 'my-space-com'. A dollar sign with a number (ex $1) must be used on a right part with care

'2033' -replace '(\d+)',$( 'Data: $1')
Data: 2033

UPDATE: You can also use $str = $str.Trim(), along with TrimEnd() and TrimStart(). Read more at System.String MSDN page.

'LIKE ('%this%' OR '%that%') and something=else' not working

Break out the LIKE clauses into 2 separate statements, i.e.:

(fieldname1 LIKE '%this%' or fieldname1 LIKE '%that%' ) and something=else

Use of "global" keyword in Python

This is explained well in the Python FAQ

What are the rules for local and global variables in Python?

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python

What is the difference between Multiple R-squared and Adjusted R-squared in a single-variate least squares regression?

Note that, in addition to number of predictive variables, the Adjusted R-squared formula above also adjusts for sample size. A small sample will give a deceptively large R-squared.

Ping Yin & Xitao Fan, J. of Experimental Education 69(2): 203-224, "Estimating R-squared shrinkage in multiple regression", compares different methods for adjusting r-squared and concludes that the commonly-used ones quoted above are not good. They recommend the Olkin & Pratt formula.

However, I've seen some indication that population size has a much larger effect than any of these formulas indicate. I am not convinced that any of these formulas are good enough to allow you to compare regressions done with very different sample sizes (e.g., 2,000 vs. 200,000 samples; the standard formulas would make almost no sample-size-based adjustment). I would do some cross-validation to check the r-squared on each sample.

Using parameters in batch files at Windows command line

Batch Files automatically pass the text after the program so long as their are variables to assign them to. They are passed in order they are sent; e.g. %1 will be the first string sent after the program is called, etc.

If you have Hello.bat and the contents are:

@echo off
echo.Hello, %1 thanks for running this batch file (%2)
pause

and you invoke the batch in command via

hello.bat APerson241 %date%

you should receive this message back:

Hello, APerson241 thanks for running this batch file (01/11/2013)

const vs constexpr on variables

I believe there is a difference. Let's rename them so that we can talk about them more easily:

const     double PI1 = 3.141592653589793;
constexpr double PI2 = 3.141592653589793;

Both PI1 and PI2 are constant, meaning you can not modify them. However only PI2 is a compile-time constant. It shall be initialized at compile time. PI1 may be initialized at compile time or run time. Furthermore, only PI2 can be used in a context that requires a compile-time constant. For example:

constexpr double PI3 = PI1;  // error

but:

constexpr double PI3 = PI2;  // ok

and:

static_assert(PI1 == 3.141592653589793, "");  // error

but:

static_assert(PI2 == 3.141592653589793, "");  // ok

As to which you should use? Use whichever meets your needs. Do you want to ensure that you have a compile time constant that can be used in contexts where a compile-time constant is required? Do you want to be able to initialize it with a computation done at run time? Etc.

Is there a command to refresh environment variables from the command prompt in Windows?

To solve this I have changed the environment variable using BOTH setx and set, and then restarted all instances of explorer.exe. This way any process subsequently started will have the new environment variable.

My batch script to do this:

setx /M ENVVAR "NEWVALUE"
set ENVVAR="NEWVALUE"

taskkill /f /IM explorer.exe
start explorer.exe >nul
exit

The problem with this approach is that all explorer windows that are currently opened will be closed, which is probably a bad idea - But see the post by Kev to learn why this is necessary

Print: Entry, ":CFBundleIdentifier", Does Not Exist

Update React using react-native upgrade did it for me.

Disclaimer: this overwrites all your iOS configurations, use with caution!

How to parse/read a YAML file into a Python object?

If your YAML file looks like this:

# tree format
treeroot:
    branch1:
        name: Node 1
        branch1-1:
            name: Node 1-1
    branch2:
        name: Node 2
        branch2-1:
            name: Node 2-1

And you've installed PyYAML like this:

pip install PyYAML

And the Python code looks like this:

import yaml
with open('tree.yaml') as f:
    # use safe_load instead load
    dataMap = yaml.safe_load(f)

The variable dataMap now contains a dictionary with the tree data. If you print dataMap using PrettyPrint, you will get something like:

{
    'treeroot': {
        'branch1': {
            'branch1-1': {
                'name': 'Node 1-1'
            },
            'name': 'Node 1'
        },
        'branch2': {
            'branch2-1': {
                'name': 'Node 2-1'
            },
            'name': 'Node 2'
        }
    }
}

So, now we have seen how to get data into our Python program. Saving data is just as easy:

with open('newtree.yaml', "w") as f:
    yaml.dump(dataMap, f)

You have a dictionary, and now you have to convert it to a Python object:

class Struct:
    def __init__(self, **entries): 
        self.__dict__.update(entries)

Then you can use:

>>> args = your YAML dictionary
>>> s = Struct(**args)
>>> s
<__main__.Struct instance at 0x01D6A738>
>>> s...

and follow "Convert Python dict to object".

For more information you can look at pyyaml.org and this.

How to use SVG markers in Google Maps API v3

Things are going better, right now you can use SVG files.

        marker = new google.maps.Marker({
            position: {lat: 36.720426, lng: -4.412573},
            map: map,
            draggable: true,
            icon: "img/tree.svg"
        });

Reading inputStream using BufferedReader.readLine() is too slow

I have a longer test to try. This takes an average of 160 ns to read each line as add it to a List (Which is likely to be what you intended as dropping the newlines is not very useful.

public static void main(String... args) throws IOException {
    final int runs = 5 * 1000 * 1000;

    final ServerSocket ss = new ServerSocket(0);
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Socket serverConn = ss.accept();
                String line = "Hello World!\n";
                BufferedWriter br = new BufferedWriter(new OutputStreamWriter(serverConn.getOutputStream()));
                for (int count = 0; count < runs; count++)
                    br.write(line);
                serverConn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();

    Socket conn = new Socket("localhost", ss.getLocalPort());

    long start = System.nanoTime();
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;

    List<String> responseData = new ArrayList<String>();
    while ((line = in.readLine()) != null) {
        responseData.add(line);
    }
    long time = System.nanoTime() - start;
    System.out.println("Average time to read a line was " + time / runs + " ns.");
    conn.close();
    ss.close();
}

prints

Average time to read a line was 158 ns.

If you want to build a StringBuilder, keeping newlines I would suggets the following approach.

Reader r = new InputStreamReader(conn.getInputStream());
String line;

StringBuilder sb = new StringBuilder();
char[] chars = new char[4*1024];
int len;
while((len = r.read(chars))>=0) {
    sb.append(chars, 0, len);
}

Still prints

Average time to read a line was 159 ns.

In both cases, the speed is limited by the sender not the receiver. By optimising the sender, I got this timing down to 105 ns per line.

Stratified Train/Test-split in scikit-learn

TL;DR : Use StratifiedShuffleSplit with test_size=0.25

Scikit-learn provides two modules for Stratified Splitting:

  1. StratifiedKFold : This module is useful as a direct k-fold cross-validation operator: as in it will set up n_folds training/testing sets such that classes are equally balanced in both.

Heres some code(directly from above documentation)

>>> skf = cross_validation.StratifiedKFold(y, n_folds=2) #2-fold cross validation
>>> len(skf)
2
>>> for train_index, test_index in skf:
...    print("TRAIN:", train_index, "TEST:", test_index)
...    X_train, X_test = X[train_index], X[test_index]
...    y_train, y_test = y[train_index], y[test_index]
...    #fit and predict with X_train/test. Use accuracy metrics to check validation performance
  1. StratifiedShuffleSplit : This module creates a single training/testing set having equally balanced(stratified) classes. Essentially this is what you want with the n_iter=1. You can mention the test-size here same as in train_test_split

Code:

>>> sss = StratifiedShuffleSplit(y, n_iter=1, test_size=0.5, random_state=0)
>>> len(sss)
1
>>> for train_index, test_index in sss:
...    print("TRAIN:", train_index, "TEST:", test_index)
...    X_train, X_test = X[train_index], X[test_index]
...    y_train, y_test = y[train_index], y[test_index]
>>> # fit and predict with your classifier using the above X/y train/test

C - freeing structs

Mallocs and frees need to be paired up.

malloc grabbed a chunk of memory big enough for Person.

When you free you tell malloc the piece of memory starting "here" is no longer needed, it knows how much it allocated and frees it.

Whether you call

 free(testPerson) 

or

 free(testPerson->firstName)

all that free() actually receives is an address, the same address, it can't tell which you called. Your code is much clearer if you use free(testPerson) though - it clearly matches up the with malloc.

How can I get log4j to delete old rotating log files?

There is no default value to control deleting old log files created by DailyRollingFileAppender. But you can write your own custom Appender that deletes old log files in much the same way as setting maxBackupIndex does for RollingFileAppender.

Simple instructions found here

From 1:

If you are trying to use the Apache Log4J DailyRollingFileAppender for a daily log file, you may need to want to specify the maximum number of files which should be kept. Just like rolling RollingFileAppender supports maxBackupIndex. But the current version of Log4j (Apache log4j 1.2.16) does not provide any mechanism to delete old log files if you are using DailyRollingFileAppender. I tried to make small modifications in the original version of DailyRollingFileAppender to add maxBackupIndex property. So, it would be possible to clean up old log files which may not be required for future usage.

How to find a min/max with Ruby

You can do

[5, 10].min

or

[4, 7].max

They come from the Enumerable module, so anything that includes Enumerable will have those methods available.

v2.4 introduces own Array#min and Array#max, which are way faster than Enumerable's methods because they skip calling #each.

@nicholasklick mentions another option, Enumerable#minmax, but this time returning an array of [min, max].

[4, 5, 7, 10].minmax
=> [4, 10]

New warnings in iOS 9: "all bitcode will be dropped"

Disclaimer: This is intended for those supporting a continuous integration workflow that require an automated process. If you don't, please use Xcode as described in Javier's answer.

This worked for me to set ENABLE_BITCODE = NO via the command line:

find . -name *project.pbxproj | xargs sed -i -e 's/\(GCC_VERSION = "";\)/\1\ ENABLE_BITCODE = NO;/g'

Note that this is likely to be unstable across Xcode versions. It was tested with Xcode 7.0.1 and as part of a Cordova 4.0 project.

regex pattern to match the end of a string

Use this Regex pattern: /([^/]*)$

Remap values in pandas column with a dict

Given map is faster than replace (@JohnE's solution) you need to be careful with Non-Exhaustive mappings where you intend to map specific values to NaN. The proper method in this case requires that you mask the Series when you .fillna, else you undo the mapping to NaN.

import pandas as pd
import numpy as np

d = {'m': 'Male', 'f': 'Female', 'missing': np.NaN}
df = pd.DataFrame({'gender': ['m', 'f', 'missing', 'Male', 'U']})

keep_nan = [k for k,v in d.items() if pd.isnull(v)]
s = df['gender']

df['mapped'] = s.map(d).fillna(s.mask(s.isin(keep_nan)))

    gender  mapped
0        m    Male
1        f  Female
2  missing     NaN
3     Male    Male
4        U       U

How should you diagnose the error SEHException - External component has thrown an exception

I got this error while running unit tests on inmemory caching I was setting up. It flooded the cache. After invalidating the cache and restarting the VM, it worked fine.

How to do the equivalent of pass by reference for primitives in Java

Make a

class PassMeByRef { public int theValue; }

then pass a reference to an instance of it. Note that a method that mutates state through its arguments is best avoided, especially in parallel code.

What is the difference between Scope_Identity(), Identity(), @@Identity, and Ident_Current()?

Here is another good explanation from the book:

As for the difference between SCOPE_IDENTITY and @@IDENTITY, suppose that you have a stored procedure P1 with three statements:
- An INSERT that generates a new identity value
- A call to a stored procedure P2 that also has an INSERT statement that generates a new identity value
- A statement that queries the functions SCOPE_IDENTITY and @@IDENTITY The SCOPE_IDENTITY function will return the value generated by P1 (same session and scope). The @@IDENTITY function will return the value generated by P2 (same session irrespective of scope).

How do I insert an image in an activity with android studio?

I'll Explain how to add an image using Android studio(2.3.3). First you need to add the image into res/drawable folder in the project. Like below

enter image description here


Now in go to activity_main.xml (or any activity you need to add image) and select the Design view. There you can see your Palette tool box on left side. You need to drag and drop ImageView.

enter image description here

It will prompt you Resources dialog box. In there select Drawable under the project section you can see your image. Like below

enter image description here

Select the image you want press Ok you can see the image on the Design view. If you want it configure using xml it would look like below.

<ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/homepage"
        tools:layout_editor_absoluteX="55dp"
        tools:layout_editor_absoluteY="130dp" />

You need to give image location using

app:srcCompat="@drawable/imagename"

Run a mySQL query as a cron job?

It depends on what runs cron on your system, but all you have to do to run a php script from cron is to do call the location of the php installation followed by the script location. An example with crontab running every hour:

# crontab -e
00 * * * * /usr/local/bin/php /home/path/script.php

On my system, I don't even have to put the path to the php installation:

00 * * * * php /home/path/script.php

On another note, you should not be using mysql extension because it is deprecated, unless you are using an older installation of php. Read here for a comparison.

Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?

Behavior differences

Some differences on Bash 4.3.11:

  • POSIX vs Bash extension:

  • regular command vs magic

    • [ is just a regular command with a weird name.

      ] is just the last argument of [.

    Ubuntu 16.04 actually has an executable for it at /usr/bin/[ provided by coreutils, but the bash built-in version takes precedence.

    Nothing is altered in the way that Bash parses the command.

    In particular, < is redirection, && and || concatenate multiple commands, ( ) generates subshells unless escaped by \, and word expansion happens as usual.

    • [[ X ]] is a single construct that makes X be parsed magically. <, &&, || and () are treated specially, and word splitting rules are different.

      There are also further differences like = and =~.

    In Bashese: [ is a built-in command, and [[ is a keyword: https://askubuntu.com/questions/445749/whats-the-difference-between-shell-builtin-and-shell-keyword

  • <

  • && and ||

    • [[ a = a && b = b ]]: true, logical and
    • [ a = a && b = b ]: syntax error, && parsed as an AND command separator cmd1 && cmd2
    • [ a = a ] && [ b = b ]: POSIX reliable equivalent
    • [ a = a -a b = b ]: almost equivalent, but deprecated by POSIX because it is insane and fails for some values of a or b like ! or ( which would be interpreted as logical operations
  • (

    • [[ (a = a || a = b) && a = b ]]: false. Without ( ), would be true because [[ && ]] has greater precedence than [[ || ]]
    • [ ( a = a ) ]: syntax error, () is interpreted as a subshell
    • [ \( a = a -o a = b \) -a a = b ]: equivalent, but (), -a, and -o are deprecated by POSIX. Without \( \) would be true because -a has greater precedence than -o
    • { [ a = a ] || [ a = b ]; } && [ a = b ] non-deprecated POSIX equivalent. In this particular case however, we could have written just: [ a = a ] || [ a = b ] && [ a = b ] because the || and && shell operators have equal precedence unlike [[ || ]] and [[ && ]] and -o, -a and [
  • word splitting and filename generation upon expansions (split+glob)

    • x='a b'; [[ $x = 'a b' ]]: true, quotes not needed
    • x='a b'; [ $x = 'a b' ]: syntax error, expands to [ a b = 'a b' ]
    • x='*'; [ $x = 'a b' ]: syntax error if there's more than one file in the current directory.
    • x='a b'; [ "$x" = 'a b' ]: POSIX equivalent
  • =

    • [[ ab = a? ]]: true, because it does pattern matching (* ? [ are magic). Does not glob expand to files in current directory.
    • [ ab = a? ]: a? glob expands. So may be true or false depending on the files in the current directory.
    • [ ab = a\? ]: false, not glob expansion
    • = and == are the same in both [ and [[, but == is a Bash extension.
    • case ab in (a?) echo match; esac: POSIX equivalent
    • [[ ab =~ 'ab?' ]]: false, loses magic with '' in Bash 3.2 and above and provided compatibility to bash 3.1 is not enabled (like with BASH_COMPAT=3.1)
    • [[ ab? =~ 'ab?' ]]: true
  • =~

    • [[ ab =~ ab? ]]: true, POSIX extended regular expression match, ? does not glob expand
    • [ a =~ a ]: syntax error. No bash equivalent.
    • printf 'ab\n' | grep -Eq 'ab?': POSIX equivalent (single line data only)
    • awk 'BEGIN{exit !(ARGV[1] ~ ARGV[2])}' ab 'ab?': POSIX equivalent.

Recommendation: always use []

There are POSIX equivalents for every [[ ]] construct I've seen.

If you use [[ ]] you:

  • lose portability
  • force the reader to learn the intricacies of another bash extension. [ is just a regular command with a weird name, no special semantics are involved.

Thanks to Stéphane Chazelas for important corrections and additions.

How to make button look like a link?

You can't style buttons as links reliably throughout browsers. I've tried it, but there's always some weird padding, margin or font issues in some browser. Either live with letting the button look like a button, or use onClick and preventDefault on a link.

How can I format a number into a string with leading zeros?

Usually String.Format("format", object) is preferable to object.ToString("format"). Therefore,

String.Format("{0:00000}", 15);  

is preferable to,

Key = i.ToString("000000");

How to track down access violation "at address 00000000"

An access violation at anywhere near adress '00000000' indicates a null pointer access. You're using something before it's ever been created, most likely, or after it's been FreeAndNil()'d.

A lot of times this is caused by accessing a component in the wrong place during form creation, or by having your main form try and access something in a datamodule that hasn't been created yet.

MadExcept makes it pretty easy to track these things down, and is free for non-commercial use. (Actually, a commercial use license is pretty inexpensive as well, and well worth the money.)

Listing all permutations of a string/integer

I hope this will suffice:

using System;
                
public class Program
{
    public static void Main()
    {
        //Example using word cat
        permute("cat");
    
    }

static void permute(string word){
    for(int i=0; i < word.Length; i++){
        char start = word[0];
        for(int j=1; j < word.Length; j++){
            string left = word.Substring(1,j-1);
            string right = word.Substring(j);
            Console.WriteLine(start+right+left);
        }
        if(i+1 < word.Length){
            word = wordChange(word, i + 1);
        }
            
    }
}

static string wordChange(string word, int index){
    string newWord = "";
    for(int i=0; i<word.Length; i++){
        if(i== 0)
            newWord += word[index];
        else if(i== index)
            newWord += word[0];
        else
            newWord += word[i];
    }
    return newWord;
}

output:

cat
cta
act
atc
tca
tac

NTFS performance and large volumes of files and directories

Here's some advice from someone with an environment where we have folders containing tens of millions of files.

  1. A folder stores the index information (links to child files & child folder) in an index file. This file will get very large when you have a lot of children. Note that it doesn't distinguish between a child that's a folder and a child that's a file. The only difference really is the content of that child is either the child's folder index or the child's file data. Note: I am simplifying this somewhat but this gets the point across.
  2. The index file will get fragmented. When it gets too fragmented, you will be unable to add files to that folder. This is because there is a limit on the # of fragments that's allowed. It's by design. I've confirmed it with Microsoft in a support incident call. So although the theoretical limit to the number of files that you can have in a folder is several billions, good luck when you start hitting tens of million of files as you will hit the fragmentation limitation first.
  3. It's not all bad however. You can use the tool: contig.exe to defragment this index. It will not reduce the size of the index (which can reach up to several Gigs for tens of million of files) but you can reduce the # of fragments. Note: The Disk Defragment tool will NOT defrag the folder's index. It will defrag file data. Only the contig.exe tool will defrag the index. FYI: You can also use that to defrag an individual file's data.
  4. If you DO defrag, don't wait until you hit the max # of fragment limit. I have a folder where I cannot defrag because I've waited until it's too late. My next test is to try to move some files out of that folder into another folder to see if I could defrag it then. If this fails, then what I would have to do is 1) create a new folder. 2) move a batch of files to the new folder. 3) defrag the new folder. repeat #2 & #3 until this is done and then 4) remove the old folder and rename the new folder to match the old.

To answer your question more directly: If you're looking at 100K entries, no worries. Go knock yourself out. If you're looking at tens of millions of entries, then either:

a) Make plans to sub-divide them into sub-folders (e.g., lets say you have 100M files. It's better to store them in 1000 folders so that you only have 100,000 files per folder than to store them into 1 big folder. This will create 1000 folder indices instead of a single big one that's more likely to hit the max # of fragments limit or

b) Make plans to run contig.exe on a regular basis to keep your big folder's index defragmented.

Read below only if you're bored.

The actual limit isn't on the # of fragment, but on the number of records of the data segment that stores the pointers to the fragment.

So what you have is a data segment that stores pointers to the fragments of the directory data. The directory data stores information about the sub-directories & sub-files that the directory supposedly stored. Actually, a directory doesn't "store" anything. It's just a tracking and presentation feature that presents the illusion of hierarchy to the user since the storage medium itself is linear.

npm WARN package.json: No repository field

As dan_nl stated, you can add a private fake repository in package.json. You don't even need name and version for it:

{
  ...,
  "repository": {
    "private": true
  }
}

Update: This feature is undocumented and might not work. Choose the following option.

Better still: Set the private flag directly. This way npm doesn't ask for a README file either:

{
  "name": ...,
  "description": ...,
  "version": ...,
  "private": true
}

Java: Retrieving an element from a HashSet

The idea that you need to get the reference to the object that is contained inside a Set object is common. It can be archived by 2 ways:

  1. Use HashSet as you wanted, then:

    public Object getObjectReference(HashSet<Xobject> set, Xobject obj) {
        if (set.contains(obj)) {
            for (Xobject o : set) {
                if (obj.equals(o))
                    return o;
            }
        }
        return null;
    }
    

For this approach to work, you need to override both hashCode() and equals(Object o) methods In the worst scenario we have O(n)

  1. Second approach is to use TreeSet

    public Object getObjectReference(TreeSet<Xobject> set, Xobject obj) {
        if (set.contains(obj)) {
            return set.floor(obj);
        }
        return null;
    }
    

This approach gives O(log(n)), more efficient. You don't need to override hashCode for this approach but you have to implement Comparable interface. ( define function compareTo(Object o)).

ERROR 1064 (42000): You have an error in your SQL syntax; Want to configure a password as root being the user

While using mysql version 8.0 + , use the following syntax to update root password after starting mysql daemon with --skip-grant-tables option

UPDATE user SET PASSWORD FOR 'root'@'localhost' = PASSWORD('your_new_password')

How to display a readable array - Laravel

For everyone still searching for a nice way to achieve this, the recommended way is the dump() function from symfony/var-dumper.

It is added to documentation since version 5.2: https://laravel.com/docs/5.2/helpers#method-dd

How to get http headers in flask?

from flask import request
request.headers.get('your-header-name')

request.headers behaves like a dictionary, so you can also get your header like you would with any dictionary:

request.headers['your-header-name']

The Android emulator is not starting, showing "invalid command-line parameter"

As an alternative to the PROGRA~2 method (which is not working for example in IntelliJ IDEA), you can create a symbolic link.

It can be named, for example, prg to Program Files (run mklink /? from the command line to learn how to do it). Then run the emulator as C:\prg\Android\android-sdk\tools\emulator.exe. Also change the path to SDK/emulator in your IDE.

Git/GitHub can't push to master

The below cmnds will fix the issue.

 git pull --rebase
 git push

Dynamically generating a QR code with PHP

I know the question is how to generate QR codes using PHP, but for others who are looking for a way to generate codes for websites doing this in pure javascript is a good way to do it. The jquery-qrcode jquery plugin does it well.

Using sed, Insert a line above or below the pattern?

Insert a new verse after the given verse in your stanza:

sed -i '/^lorem ipsum dolor sit amet$/ s:$:\nconsectetur adipiscing elit:' FILE

FTP/SFTP access to an Amazon S3 Bucket

Filezilla just released a Pro version of their FTP client. It connects to S3 buckets in a streamlined FTP like experience. I use it myself (no affiliation whatsoever) and it works great.

If strings starts with in PowerShell

$Group is an object, but you will actually need to check if $Group.samaccountname.StartsWith("string").

Change $Group.StartsWith("S_G_") to $Group.samaccountname.StartsWith("S_G_").

Use -notlike to filter out multiple strings in PowerShell

don't use -notLike, -notMatch with Regular-Expression works in one line:

Get-MailBoxPermission -id newsletter | ? {$_.User -NotMatch "NT-AUTORIT.*|.*-Admins|.*Administrators|.*Manage.*"}

What is a 'NoneType' object?

Your error's occurring due to something like this:
>>> None + "hello world"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
>>>

Python's None object is roughly equivalent to null, nil, etc. in other languages.

How can I tell where mongoDB is storing data? (its not in the default /data/db!)

On MongoDB 4.4+ and on CentOS 8, I found the path by running:

grep dbPath /etc/mongod.conf

What is an undefined reference/unresolved external symbol error and how do I fix it?

Microsoft offers a #pragma to reference the correct library at link time;

#pragma comment(lib, "libname.lib")

In addition to the library path including the directory of the library, this should be the full name of the library.

'ssh' is not recognized as an internal or external command

Actually you have 2 problems here: First is that you don't have ssh installed, second is that you don't know how to deploy

Install SSH

It seems that ssh is not installed on your computer.

You can install openssh from here : http://openssh.en.softonic.com/download

Generate your key

Than you will have to geneate your ssh-key. There's a good tutorial about this here:

https://help.github.com/articles/generating-ssh-keys#platform-windows

Deploy

To deploy, you just have to push your code over git. Something like this:

git push fort master

If you get permission denied, be sure that you have put your public_key in the dashboard in the git tab.

SSH

The ssh command gives you access to your remote node. You should have received a password by email and now that you have ssh installed, you should be asked for a password when trying to connect. just input that password. If you want to use your private ssh key to connect to your server rather then typing that password, you can follow this : http://fortrabbit.com/docs/how-to/ssh-sftp/enable-public-key-authentication

How do I execute multiple SQL Statements in Access' Query Editor?

You might find it better to use a 3rd party program to enter the queries into Access such as WinSQL I think from memory WinSQL supports multiple queries via it's batch feature.

I ultimately found it easier to just write a program in perl to do bulk INSERTS into an Access via ODBC. You could use vbscript or any language that supports ODBC though.

You can then do anything you like and have your own complicated logic to handle the importing.

If hasClass then addClass to parent

You probably want to change the condition to if ($(this).hasClass('active'))

Also, hasClass and addClass take classnames, not selectors.
Therefore, you shouldn't include a ..

PLS-00103: Encountered the symbol when expecting one of the following:

The problem is that the else and if are two operators here. Since you open a new 'if' you need a corresponding 'end if'.

Thus:

declare
mark number :=50;
begin
  mark :=& mark;
  if (mark between 85 and 100) then
    dbms_output.put_line('mark is A ');
  else 
    if (mark between 50 and 65) then
      dbms_output.put_line('mark is D ');
    else 
      if (mark between 66 and 75) then
        dbms_output.put_line('mark is C ');
      else 
        if (mark between 76 and 84) then
          dbms_output.put_line('mark is B');
        else 
          dbms_output.put_line('mark is F');
        end if;
      end if;
    end if;
  end if;
end;
/

Alternatively you can use elsif:

declare
mark number :=50;
begin
  mark :=& mark;
  if (mark between 85 and 100)
    then
    dbms_output.put_line('mark is A ');
  elsif (mark between 50 and 65) then
    dbms_output.put_line('mark is D ');
  elsif (mark between 66 and 75) then
    dbms_output.put_line('mark is C ');
  elsif (mark between 76 and 84) then
    dbms_output.put_line('mark is B');
  else 
    dbms_output.put_line('mark is F');
  end if;
end;
/

Converting string format to datetime in mm/dd/yyyy

You are looking for the DateTime.Parse() method (MSDN Article)

So you can do:

var dateTime = DateTime.Parse("01/01/2001");

Which will give you a DateTime typed object.

If you need to specify which date format you want to use, you would use DateTime.ParseExact (MSDN Article)

Which you would use in a situation like this (Where you are using a British style date format):

string[] formats= { "dd/MM/yyyy" }
var dateTime = DateTime.ParseExact("01/01/2001", formats, new CultureInfo("en-US"), DateTimeStyles.None);

pandas: best way to select all columns whose names start with X

Based on @EdChum's answer, you can try the following solution:

df[df.columns[pd.Series(df.columns).str.contains("foo")]]

This will be really helpful in case not all the columns you want to select start with foo. This method selects all the columns that contain the substring foo and it could be placed in at any point of a column's name.

In essence, I replaced .startswith() with .contains().

What are the rules for casting pointers in C?

Casting pointers is usually invalid in C. There are several reasons:

  1. Alignment. It's possible that, due to alignment considerations, the destination pointer type is not able to represent the value of the source pointer type. For example, if int * were inherently 4-byte aligned, casting char * to int * would lose the lower bits.

  2. Aliasing. In general it's forbidden to access an object except via an lvalue of the correct type for the object. There are some exceptions, but unless you understand them very well you don't want to do it. Note that aliasing is only a problem if you actually dereference the pointer (apply the * or -> operators to it, or pass it to a function that will dereference it).

The main notable cases where casting pointers is okay are:

  1. When the destination pointer type points to character type. Pointers to character types are guaranteed to be able to represent any pointer to any type, and successfully round-trip it back to the original type if desired. Pointer to void (void *) is exactly the same as a pointer to a character type except that you're not allowed to dereference it or do arithmetic on it, and it automatically converts to and from other pointer types without needing a cast, so pointers to void are usually preferable over pointers to character types for this purpose.

  2. When the destination pointer type is a pointer to structure type whose members exactly match the initial members of the originally-pointed-to structure type. This is useful for various object-oriented programming techniques in C.

Some other obscure cases are technically okay in terms of the language requirements, but problematic and best avoided.

How does setTimeout work in Node.JS?

The semantics of setTimeout are roughly the same as in a web browser: the timeout arg is a minimum number of ms to wait before executing, not a guarantee. Furthermore, passing 0, a non-number, or a negative number, will cause it to wait a minimum number of ms. In Node, this is 1ms, but in browsers it can be as much as 50ms.

The reason for this is that there is no preemption of JavaScript by JavaScript. Consider this example:

setTimeout(function () {
  console.log('boo')
}, 100)
var end = Date.now() + 5000
while (Date.now() < end) ;
console.log('imma let you finish but blocking the event loop is the best bug of all TIME')

The flow here is:

  1. schedule the timeout for 100ms.
  2. busywait for 5000ms.
  3. return to the event loop. check for pending timers and execute.

If this was not the case, then you could have one bit of JavaScript "interrupt" another. We'd have to set up mutexes and semaphors and such, to prevent code like this from being extremely hard to reason about:

var a = 100;
setTimeout(function () {
  a = 0;
}, 0);
var b = a; // 100 or 0?

The single-threadedness of Node's JavaScript execution makes it much simpler to work with than most other styles of concurrency. Of course, the trade-off is that it's possible for a badly-behaved part of the program to block the whole thing with an infinite loop.

Is this a better demon to battle than the complexity of preemption? That depends.

How do I copy a 2 Dimensional array in Java?

I am using this function:

public static int[][] copy(final int[][] array) {
    if (array != null) {
        final int[][] copy = new int[array.length][];

        for (int i = 0; i < array.length; i++) {
            final int[] row = array[i];

            copy[i] = new int[row.length];
            System.arraycopy(row, 0, copy[i], 0, row.length);
        }

        return copy;
    }

    return null;
}

The big advantage of this approach is that it can also copy arrays that don't have the same row count such as:

final int[][] array = new int[][] { { 5, 3, 6 }, { 1 } };

How to import component into another root component in Angular 2

above answers In simple words, you have to register under @NgModule's

declarations: [
    AppComponent, YourNewComponentHere
  ] 

of app.module.ts

do not forget to import that component.

How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time?

The Philippe solution but cleaner:

My subtraction data is: '2018-09-22T11:05:00.000Z'

import datetime
import pandas as pd

df_modified = pd.to_datetime(df_reference.index.values) - datetime.datetime(2018, 9, 22, 11, 5, 0)

Understanding generators in Python

First of all, the term generator originally was somewhat ill-defined in Python, leading to lots of confusion. You probably mean iterators and iterables (see here). Then in Python there are also generator functions (which return a generator object), generator objects (which are iterators) and generator expressions (which are evaluated to a generator object).

According to the glossary entry for generator it seems that the official terminology is now that generator is short for "generator function". In the past the documentation defined the terms inconsistently, but fortunately this has been fixed.

It might still be a good idea to be precise and avoid the term "generator" without further specification.

CSS How to set div height 100% minus nPx

If you need to support IE6, use JavaScript so manage the size of the wrapper div (set the position of the element in pixels after reading the window size). If you don't want to use JavaScript, then this can't be done. There are workarounds but expect a week or two to make it work in every case and in every browser.

For other modern browsers, use this css:

position: absolute;
top: 60px;
bottom: 0px;

jQuery jump or scroll to certain position, div or target on the page from button onclick

$("html, body").scrollTop($(element).offset().top); // <-- Also integer can be used

How can I specify the required Node.js version in package.json?

There's another, simpler way to do this:

  1. npm install Node@8 (saves Node 8 as dependency in package.json)
  2. Your app will run using Node 8 for anyone - even Yarn users!

This works because node is just a package that ships node as its package binary. It just includes as node_module/.bin which means it only makes node available to package scripts. Not main shell.

See discussion on Twitter here: https://twitter.com/housecor/status/962347301456015360

What is the iBeacon Bluetooth Profile

It seems to based on advertisement data, particularly the manufacturer data:

4C00 02 15 585CDE931B0142CC9A1325009BEDC65E 0000 0000 C5

<company identifier (2 bytes)> <type (1 byte)> <data length (1 byte)>
    <uuid (16 bytes)> <major (2 bytes)> <minor (2 bytes)> <RSSI @ 1m>
  • Apple Company Identifier (Little Endian), 0x004c
  • data type, 0x02 => iBeacon
  • data length, 0x15 = 21
  • uuid: 585CDE931B0142CC9A1325009BEDC65E
  • major: 0000
  • minor: 0000
  • meaured power at 1 meter: 0xc5 = -59

I have this node.js script working on Linux with the sample AirLocate app example.

What is JavaScript's highest integer value that a number can go to without losing precision?

Jimmy's answer correctly represents the continuous JavaScript integer spectrum as -9007199254740992 to 9007199254740992 inclusive (sorry 9007199254740993, you might think you are 9007199254740993, but you are wrong! Demonstration below or in jsfiddle).

_x000D_
_x000D_
console.log(9007199254740993);
_x000D_
_x000D_
_x000D_

However, there is no answer that finds/proves this programatically (other than the one CoolAJ86 alluded to in his answer that would finish in 28.56 years ;), so here's a slightly more efficient way to do that (to be precise, it's more efficient by about 28.559999999968312 years :), along with a test fiddle:

_x000D_
_x000D_
/**_x000D_
 * Checks if adding/subtracting one to/from a number yields the correct result._x000D_
 *_x000D_
 * @param number The number to test_x000D_
 * @return true if you can add/subtract 1, false otherwise._x000D_
 */_x000D_
var canAddSubtractOneFromNumber = function(number) {_x000D_
    var numMinusOne = number - 1;_x000D_
    var numPlusOne = number + 1;_x000D_
    _x000D_
    return ((number - numMinusOne) === 1) && ((number - numPlusOne) === -1);_x000D_
}_x000D_
_x000D_
//Find the highest number_x000D_
var highestNumber = 3; //Start with an integer 1 or higher_x000D_
_x000D_
//Get a number higher than the valid integer range_x000D_
while (canAddSubtractOneFromNumber(highestNumber)) {_x000D_
    highestNumber *= 2;_x000D_
}_x000D_
_x000D_
//Find the lowest number you can't add/subtract 1 from_x000D_
var numToSubtract = highestNumber / 4;_x000D_
while (numToSubtract >= 1) {_x000D_
    while (!canAddSubtractOneFromNumber(highestNumber - numToSubtract)) {_x000D_
        highestNumber = highestNumber - numToSubtract;_x000D_
    }_x000D_
    _x000D_
    numToSubtract /= 2;_x000D_
}        _x000D_
_x000D_
//And there was much rejoicing.  Yay.    _x000D_
console.log('HighestNumber = ' + highestNumber);
_x000D_
_x000D_
_x000D_

Returning a boolean value in a JavaScript function

Don't forget to use var/let while declaring any variable.See below examples for JS compiler behaviour.

function  func(){
return true;
}

isBool = func();
console.log(typeof (isBool));   // output - string


let isBool = func();
console.log(typeof (isBool));   // output - boolean

how to kill hadoop jobs

Use of folloing command is depreciated

hadoop job -list
hadoop job -kill $jobId

consider using

mapred job -list
mapred job -kill $jobId

Text Editor For Linux (Besides Vi)?

Vim is a nice upgrade for Vi, offering decent features and a more usable set of keybindings and default behaviour. However, graphical versions like GVim, KVim and even Cream are extremely lacking in my opinion. I've been using Geany a lot lately, but it also has its shortcomings.

I just can't find something in the league of Programmers Notepad, Smultron or TextMate on Linux. A shame, since I want to live in an all open source cyberworld, I'm stuck hopping from one almost-right editor to another.

How best to include other scripts?

1. Neatest

I explored almost every suggestion and here is the neatest one that worked for me:

script_root=$(dirname $(readlink -f $0))

It works even when the script is symlinked to a $PATH directory.

See it in action here: https://github.com/pendashteh/hcagent/blob/master/bin/hcagent

2. The coolest

# Copyright https://stackoverflow.com/a/13222994/257479
script_root=$(ls -l /proc/$$/fd | grep "255 ->" | sed -e 's/^.\+-> //')

This is actually from another answer on this very page, but I'm adding it to my answer too!

2. The most reliable

Alternatively, in the rare case that those didn't work, here is the bullet proof approach:

# Copyright http://stackoverflow.com/a/7400673/257479
myreadlink() { [ ! -h "$1" ] && echo "$1" || (local link="$(expr "$(command ls -ld -- "$1")" : '.*-> \(.*\)$')"; cd $(dirname $1); myreadlink "$link" | sed "s|^\([^/].*\)\$|$(dirname $1)/\1|"); }
whereis() { echo $1 | sed "s|^\([^/].*/.*\)|$(pwd)/\1|;s|^\([^/]*\)$|$(which -- $1)|;s|^$|$1|"; } 
whereis_realpath() { local SCRIPT_PATH=$(whereis $1); myreadlink ${SCRIPT_PATH} | sed "s|^\([^/].*\)\$|$(dirname ${SCRIPT_PATH})/\1|"; } 

script_root=$(dirname $(whereis_realpath "$0"))

You can see it in action in taskrunner source: https://github.com/pendashteh/taskrunner/blob/master/bin/taskrunner

Hope this help someone out there :)

Also, please leave it as a comment if one did not work for you and mention your operating system and emulator. Thanks!

How do I deal with installing peer dependencies in Angular CLI?

You can ignore the peer dependency warnings by using the --force flag with Angular cli when updating dependencies.

ng update @angular/cli @angular/core --force

For a full list of options, check the docs: https://angular.io/cli/update

Do you get charged for a 'stopped' instance on EC2?

When you stop an instance, it is 'deleted'. As such there's nothing to be charged for. If you have an Elastic IP or EBS, then you'll be charged for those - but nothing related to the instance itself.

How do I prevent the error "Index signature of object type implicitly has an 'any' type" when compiling typescript with noImplicitAny flag enabled?

Declare type which its key is string and value can be any then declare the object with this type and the lint won't show up

type MyType = {[key: string]: any};

So your code will be

type ISomeType = {[key: string]: any};

    let someObject: ISomeType = {
        firstKey:   'firstValue',
        secondKey:  'secondValue',
        thirdKey:   'thirdValue'
    };

    let key: string = 'secondKey';

    let secondValue: string = someObject[key];

Letsencrypt add domain to existing certificate

You can replace the certificate by just running the certbot again with ./certbot-auto certonly

You will be prompted with this message if you try to generate a certificate for a domain that you have already covered by an existing certificate:

-------------------------------------------------------------------------------
You have an existing certificate that contains a portion of the domains you
requested (ref: /etc/letsencrypt/renewal/<domain>.conf)

It contains these names: <domain>

You requested these names for the new certificate: <domain>,
<the domain you want to add to the cert>.

Do you want to expand and replace this existing certificate with the new
certificate?
-------------------------------------------------------------------------------

Just chose Expand and replace it.

Kotlin - Property initialization using "by lazy" vs. "lateinit"

If you use an unchangable variable, then it is better to initialize with by lazy { ... } or val. In this case you can be sure that it will always be initialized when needed and at most 1 time.

If you want a non-null variable, that can change it's value, use lateinit var. In Android development you can later initialize it in such events like onCreate, onResume. Be aware, that if you call REST request and access this variable, it may lead to an exception UninitializedPropertyAccessException: lateinit property yourVariable has not been initialized, because the request can execute faster than that variable could initialize.

Convert double to string

Try c.ToString("F6");

(For a full explanation of numeric formatting, see MSDN)

C - casting int to char and append char to char

Casting int to char involves losing data and the compiler will probably warn you.

Extracting a particular byte from an int sounds more reasonable and can be done like this:

number & 0x000000ff; /* first byte */
(number & 0x0000ff00) >> 8; /* second byte */
(number & 0x00ff0000) >> 16; /* third byte */
(number & 0xff000000) >> 24; /* fourth byte */

How do I add items to an array in jQuery?

Hope this will help you..

var list = [];
    $(document).ready(function () {
        $('#test').click(function () {
            var oRows = $('#MainContent_Table1 tr').length;
            $('#MainContent_Table1 tr').each(function (index) {
                list.push(this.cells[0].innerHTML);
            });
        });
    });

Storage permission error in Marshmallow

it's worked for me

 boolean hasPermission = (ContextCompat.checkSelfPermission(AddContactActivity.this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
    if (!hasPermission) {
        ActivityCompat.requestPermissions(AddContactActivity.this,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                REQUEST_WRITE_STORAGE);
    }

   @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode)
    {
        case REQUEST_WRITE_STORAGE: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                //reload my activity with permission granted or use the features what required the permission
            } else
            {
                Toast.makeText(AddContactActivity.this, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
            }
        }
    }

}

Where is Android Studio layout preview?

I am using Android studio 3.3 and this method worked for me: open settings from file/settings from the left panel select Editor then layout Editor then from the right panel uncheck third option which is "Hide preview window when editing non-layout files" then hit apply then ok. then go to view/tool windows/preview is enable now in the design tab of layout XD. Do not forget up vote and marking this answer as the right answer. Happy coding. enter image description here

Use JAXB to create Object from XML String

Or if you want a simple one-liner:

Person person = JAXB.unmarshal(new StringReader("<?xml ..."), Person.class);

How to get the focused element with jQuery?

$(':focus')[0] will give you the actual element.

$(':focus') will give you an array of elements, usually only one element is focused at a time so this is only better if you somehow have multiple elements focused.

std::cin input with spaces?

You have to use cin.getline():

char input[100];
cin.getline(input,sizeof(input));

Cannot find libcrypto in Ubuntu

I solved this on 12.10 by installing libssl-dev.

sudo apt-get install libssl-dev

How to print time in format: 2009-08-10 18:17:54.811

You could use strftime, but struct tm doesn't have resolution for parts of seconds. I'm not sure if that's absolutely required for your purposes.

struct tm tm;
/* Set tm to the correct time */
char s[20]; /* strlen("2009-08-10 18:17:54") + 1 */
strftime(s, 20, "%F %H:%M:%S", &tm);

How do I install a Python package with a .whl file?

On the MacOS, with pip installed via MacPorts into the MacPorts python2.7, I had to use @Dunes solution:

sudo python -m pip install some-package.whl

Where python was replaced by the MacPorts python in my case, which is python2.7 or python3.5 for me.

The -m option is "Run library module as script" according to the manpage.

(I had previously run sudo port install py27-pip py27-wheel to install pip and wheel into my python 2.7 installation first.)

How to pass parameters on onChange of html select

jQuery solution

How do I get the text value of a selected option

Select elements typically have two values that you want to access.
First there's the value to be sent to the server, which is easy:

$( "#myselect" ).val();
// => 1

The second is the text value of the select.
For example, using the following select box:

<select id="myselect">
  <option value="1">Mr</option>
  <option value="2">Mrs</option>
  <option value="3">Ms</option>
  <option value="4">Dr</option>
  <option value="5">Prof</option>
</select>

If you wanted to get the string "Mr" if the first option was selected (instead of just "1") you would do that in the following way:

$( "#myselect option:selected" ).text();
// => "Mr"  

See also

get path for my .exe

In addition:

AppDomain.CurrentDomain.BaseDirectory
Assembly.GetEntryAssembly().Location

Pass a variable to a PHP script running from the command line

Using getopt() function we can also read a parameter from the command line just. Pass a value with the php running command:

php abc.php --name=xyz

File abc.php

$val = getopt(null, ["name:"]);
print_r($val); // Output: ['name' => 'xyz'];

HTML5 Canvas background image

Canvas does not using .png file as background image. changing to other file extensions like gif or jpg works fine.

Collection was modified; enumeration operation may not execute

When a subscriber unsubscribes you are changing contents of the collection of Subscribers during enumeration.

There are several ways to fix this, one being changing the for loop to use an explicit .ToList():

public void NotifySubscribers(DataRecord sr)  
{
    foreach(Subscriber s in subscribers.Values.ToList())
    {
                                              ^^^^^^^^^  
        ...

Why does Maven have such a bad rep?

My take here, based on the pitfalls of convention over configuration:

http://chriswongdevblog.blogspot.com/2011/01/trouble-with-being-conventional.html

My issue with Maven is the difficulty in discovery and limitless complexity. That, and watching colleagues waste half a work day day fighting Maven build issues. Also IMHO, the Maven integration with Eclipse makes things worse, because you have multiplied the number of places where things go wrong.

jQuery Mobile Page refresh mechanism

I found this thread looking to create an ajax page refresh button with jQuery Mobile.

@sgissinger had the closest answer to what I was looking for, but it was outdated.

I updated for jQuery Mobile 1.4

function refreshPage() {
  jQuery.mobile.pageContainer.pagecontainer('change', window.location.href, {
    allowSamePageTransition: true,
    transition: 'none',
    reloadPage: true 
    // 'reload' parameter not working yet: //github.com/jquery/jquery-mobile/issues/7406
  });
}

// Run it with .on
$(document).on( "click", '#refresh', function() {
  refreshPage();
});

Capturing standard out and error with Start-Process

Here's a kludgy way to get the output from another powershell process:

start-process -wait -nonewwindow powershell 'ps | Export-Clixml out.xml'; import-clixml out.xml

How to Correctly handle Weak Self in Swift Blocks with Arguments

If you are crashing than you probably need [weak self]

My guess is that the block you are creating is somehow still wired up.

Create a prepareForReuse and try clearing the onTextViewEditClosure block inside that.

func prepareForResuse() {
   onTextViewEditClosure = nil
   textView.delegate = nil
}

See if that prevents the crash. (It's just a guess).

Insert all values of a table into another table in SQL

If you are transferring a lot data permanently, i.e not populating a temp table, I would recommend using SQL Server Import/Export Data for table-to-table mappings.

Import/Export tool is usually better than straight SQL when you have type conversions and possible value truncation in your mapping. Generally, the more complex your mapping, the more productive you are using an ETL tool like Integration Services (SSIS) instead of direct SQL.

Import/Export tool is actually an SSIS wizard, and you can save your work as a dtsx package.

offsetting an html anchor to adjust for fixed header

You can achieve this without an ID using the a[name]:not([href]) css selector. This simply looks for links with a name and no href e.g. <a name="anc1"></a>

An example rule might be:

a[name]:not([href]){
    display: block;    
    position: relative;     
    top: -100px;
    visibility: hidden;
}

Align DIV to bottom of the page

Nathan Lee's answer is perfect. I just wanted to add something about position:absolute;. If you wanted to use position:absolute; like you had in your code, you have to think of it as pushing it away from one side of the page.

For example, if you wanted your div to be somewhere in the bottom, you would have to use position:absolute; top:500px;. That would push your div 500px from the top of the page. Same rule applies for all other directions.

DEMO

MessageBox Buttons?

if(DialogResult.OK==MessageBox.Show("Do you Agree with me???"))
{
         //do stuff if yess
}
else
{
         //do stuff if No
}

How to detect when facebook's FB.init is complete

The Facebook API watches for the FB._apiKey so you can watch for this before calling your own application of the API with something like:

window.fbAsyncInit = function() {
  FB.init({
    //...your init object
  });
  function myUseOfFB(){
    //...your FB API calls
  };
  function FBreadyState(){
    if(FB._apiKey) return myUseOfFB();
    setTimeout(FBreadyState, 100); // adjust time as-desired
  };
  FBreadyState();
}; 

Not sure this makes a difference but in my case--because I wanted to be sure the UI was ready--I've wrapped the initialization with jQuery's document ready (last bit above):

  $(document).ready(FBreadyState);

Note too that I'm NOT using async = true to load Facebook's all.js, which in my case seems to be helping with signing into the UI and driving features more reliably.

How do I programmatically "restart" an Android app?

With the Process Phoenix library. The Activity you want to relaunch is named "A".

Java flavor

// Java
public void restart(){
    ProcessPhoenix.triggerRebirth(context);
}

Kotlin flavor

// kotlin
fun restart() {
    ProcessPhoenix.triggerRebirth(context)
}

How do I convert a list into a string with spaces in Python?

For Non String list we can do like this as well

" ".join(map(str, my_list))

How can I keep Bootstrap popovers alive while being hovered?

Here's my take: http://jsfiddle.net/WojtekKruszewski/Zf3m7/22/

Sometimes while moving mouse from popover trigger to actual popover content diagonally, you hover over elements below. I wanted to handle such situations – as long as you reach popover content before the timeout fires, you're safe (the popover won't disappear). It requires delay option.

This hack basically overrides Popover leave function, but calls the original (which starts timer to hide the popover). Then it attaches a one-off listener to mouseenter popover content element's.

If mouse enters the popover, the timer is cleared. Then it turns it listens to mouseleave on popover and if it's triggered, it calls the original leave function so that it could start hide timer.

var originalLeave = $.fn.popover.Constructor.prototype.leave;
$.fn.popover.Constructor.prototype.leave = function(obj){
  var self = obj instanceof this.constructor ?
    obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
  var container, timeout;

  originalLeave.call(this, obj);

  if(obj.currentTarget) {
    container = $(obj.currentTarget).siblings('.popover')
    timeout = self.timeout;
    container.one('mouseenter', function(){
      //We entered the actual popover – call off the dogs
      clearTimeout(timeout);
      //Let's monitor popover content instead
      container.one('mouseleave', function(){
        $.fn.popover.Constructor.prototype.leave.call(self, self);
      });
    })
  }
};

How to open the default webbrowser using java

Hope you don't mind but I cobbled together all the helpful stuff, from above, and came up with a complete class ready for testing...

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class MultiBrowPop {

    public static void main(String[] args) {
        OUT("\nWelcome to Multi Brow Pop.\nThis aims to popup a browsers in multiple operating systems.\nGood luck!\n");

        String url = "http://www.birdfolk.co.uk/cricmob";
        OUT("We're going to this page: "+ url);

        String myOS = System.getProperty("os.name").toLowerCase();
        OUT("(Your operating system is: "+ myOS +")\n");

        try {
            if(Desktop.isDesktopSupported()) { // Probably Windows
                OUT(" -- Going with Desktop.browse ...");
                Desktop desktop = Desktop.getDesktop();
                desktop.browse(new URI(url));
            } else { // Definitely Non-windows
                Runtime runtime = Runtime.getRuntime();
                if(myOS.contains("mac")) { // Apples
                    OUT(" -- Going on Apple with 'open'...");
                    runtime.exec("open " + url);
                } 
                else if(myOS.contains("nix") || myOS.contains("nux")) { // Linux flavours 
                    OUT(" -- Going on Linux with 'xdg-open'...");
                    runtime.exec("xdg-open " + url);
                }
                else 
                    OUT("I was unable/unwilling to launch a browser in your OS :( #SadFace");
            }
            OUT("\nThings have finished.\nI hope you're OK.");
        }
        catch(IOException | URISyntaxException eek) {
            OUT("**Stuff wrongly: "+ eek.getMessage());
        }
    }

    private static void OUT(String str) {
        System.out.println(str);
    }
}

Create a menu Bar in WPF?

Yes, a menu gives you the bar but it doesn't give you any items to put in the bar. You need something like (from one of my own projects):

<!-- Menu. -->
<Menu Width="Auto" Height="20" Background="#FFA9D1F4" DockPanel.Dock="Top">
    <MenuItem Header="_Emulator">
    <MenuItem Header="Load..." Click="MenuItem_Click" />
    <MenuItem Header="Load again" Click="menuEmulLoadLast" />
    <Separator />
    <MenuItem Click="MenuItem_Click">
        <MenuItem.Header>
            <DockPanel>
                <TextBlock>Step</TextBlock>
                <TextBlock Width="10"></TextBlock>
                <TextBlock HorizontalAlignment="Right">F2</TextBlock>
            </DockPanel>
        </MenuItem.Header>
    </MenuItem>
    :

Read a text file in R line by line

You should take care with readLines(...) and big files. Reading all lines at memory can be risky. Below is a example of how to read file and process just one line at time:

processFile = function(filepath) {
  con = file(filepath, "r")
  while ( TRUE ) {
    line = readLines(con, n = 1)
    if ( length(line) == 0 ) {
      break
    }
    print(line)
  }

  close(con)
}

Understand the risk of reading a line at memory too. Big files without line breaks can fill your memory too.

GridView - Show headers on empty data source

I was just working through this problem, and none of these solutions would work for me. I couldn't use the EmptyDataTemplate property because I was creating my GridView dynamically with custom fields which provide filters in the headers. I couldn't use the example almny posted because I'm using ObjectDataSources instead of DataSet or DataTable. However, I found this answer posted on another StackOverflow question, which links to this elegant solution that I was able to make work for my particular situation. It involves overriding the CreateChildControls method of the GridView to create the same header row that would have been created had there been real data. I thought it worth posting here, where it's likely to be found by other people in a similar fix.

Maven2: Best practice for Enterprise Project (EAR file)

i have made a github repository to show what i think is a good (or best practices) startup project structure...

https://github.com/StefanHeimberg/stackoverflow-1134894

some keywords:

  • Maven 3
  • BOM (DependencyManagement of own dependencies)
  • Parent for all Projects (DependencyManagement from external dependencies and PluginManagement for global Project configuration)
  • JUnit / Mockito / DBUnit
  • Clean War project without WEB-INF/lib because dependencies are in EAR/lib folder.
  • Clean Ear project.
  • Minimal deployment descriptors for Java EE7
  • No Local EJB Interface because @LocalBean is sufficient.
  • Minimal maven configuration through maven user properties
  • Actual Deployment Descriptors for Servlet 3.1 / EJB 3.2 / JPA 2.1
  • usage of macker-maven-plugin to check architecture rules
  • Integration Tests enabled, but skipped. (skipITs=false) useful to enable on CI Build Server

Maven Output:

Reactor Summary:

MyProject - BOM .................................... SUCCESS [  0.494 s]
MyProject - Parent ................................. SUCCESS [  0.330 s]
MyProject - Common ................................. SUCCESS [  3.498 s]
MyProject - Persistence ............................ SUCCESS [  1.045 s]
MyProject - Business ............................... SUCCESS [  1.233 s]
MyProject - Web .................................... SUCCESS [  1.330 s]
MyProject - Application ............................ SUCCESS [  0.679 s]
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 8.817 s
Finished at: 2015-01-27T00:51:59+01:00
Final Memory: 24M/207M
------------------------------------------------------------------------