Programs & Examples On #Labeling

Label points in geom_point

The ggrepel package works great for repelling overlapping text labels away from each other. You can use either geom_label_repel() (draws rectangles around the text) or geom_text_repel() functions.

library(ggplot2)
library(ggrepel)

nba <- read.csv("http://datasets.flowingdata.com/ppg2008.csv", sep = ",")

nbaplot <- ggplot(nba, aes(x= MIN, y = PTS)) + 
  geom_point(color = "blue", size = 3)

### geom_label_repel
nbaplot + 
  geom_label_repel(aes(label = Name),
                  box.padding   = 0.35, 
                  point.padding = 0.5,
                  segment.color = 'grey50') +
  theme_classic()

enter image description here

### geom_text_repel
# only label players with PTS > 25 or < 18
# align text vertically with nudge_y and allow the labels to 
# move horizontally with direction = "x"
ggplot(nba, aes(x= MIN, y = PTS, label = Name)) + 
  geom_point(color = dplyr::case_when(nba$PTS > 25 ~ "#1b9e77", 
                                      nba$PTS < 18 ~ "#d95f02",
                                      TRUE ~ "#7570b3"), 
             size = 3, alpha = 0.8) +
  geom_text_repel(data          = subset(nba, PTS > 25),
                  nudge_y       = 32 - subset(nba, PTS > 25)$PTS,
                  size          = 4,
                  box.padding   = 1.5,
                  point.padding = 0.5,
                  force         = 100,
                  segment.size  = 0.2,
                  segment.color = "grey50",
                  direction     = "x") +
  geom_label_repel(data         = subset(nba, PTS < 18),
                  nudge_y       = 16 - subset(nba, PTS < 18)$PTS,
                  size          = 4,
                  box.padding   = 0.5,
                  point.padding = 0.5,
                  force         = 100,
                  segment.size  = 0.2,
                  segment.color = "grey50",
                  direction     = "x") +
  scale_x_continuous(expand = expand_scale(mult = c(0.2, .2))) +
  scale_y_continuous(expand = expand_scale(mult = c(0.1, .1))) +
  theme_classic(base_size = 16)

Edit: To use ggrepel with lines, see this and this.

Created on 2019-05-01 by the reprex package (v0.2.0).

How to remove part of a string?

I wanted to remove "www." from a href so I did this:

const str = "https://www.example.com/path";

str.split("www.").join("");

// https://example.com/path

How to clear Tkinter Canvas?

Every canvas item is an object that Tkinter keeps track of. If you are clearing the screen by just drawing a black rectangle, then you effectively have created a memory leak -- eventually your program will crash due to the millions of items that have been drawn.

To clear a canvas, use the delete method. Give it the special parameter "all" to delete all items on the canvas (the string "all"" is a special tag that represents all items on the canvas):

canvas.delete("all")

If you want to delete only certain items on the canvas (such as foreground objects, while leaving the background objects on the display) you can assign tags to each item. Then, instead of "all", you could supply the name of a tag.

If you're creating a game, you probably don't need to delete and recreate items. For example, if you have an object that is moving across the screen, you can use the move or coords method to move the item.

Android webview & localStorage

I've also had problem with data being lost after application is restarted. Adding this helped:

webView.getSettings().setDatabasePath("/data/data/" + webView.getContext().getPackageName() + "/databases/");

Builder Pattern in Effective Java

You should make the Builder class as static and also you should make the fields final and have getters to get those values. Don't provide setters to those values. In this way your class will be perfectly immutable.

public class NutritionalFacts {
    private final int sodium;
    private final int fat;
    private final int carbo;

    public int getSodium(){
        return sodium;
    }

    public int getFat(){
        return fat;
    }

    public int getCarbo(){
        return carbo;
    }

    public static class Builder {
        private int sodium;
        private int fat;
        private int carbo;

        public Builder sodium(int s) {
            this.sodium = s;
            return this;
        }

        public Builder fat(int f) {
            this.fat = f;
            return this;
        }

        public Builder carbo(int c) {
            this.carbo = c;
            return this;
        }

        public NutritionalFacts build() {
            return new NutritionalFacts(this);
        }
    }

    private NutritionalFacts(Builder b) {
        this.sodium = b.sodium;
        this.fat = b.fat;
        this.carbo = b.carbo;
    }
}

And now you can set the properties as follows:

NutritionalFacts n = new NutritionalFacts.Builder().sodium(10).carbo(15).
fat(5).build();

What do these three dots in React do?

Its called spread operator. For eg let hello={name: '',msg:''} let hello1={...hello} Now hello object properties is copied to hello1.

How to get Javascript Select box's selected text

I know no-one is asking for a jQuery solution here, but might be worth mentioning that with jQuery you can just ask for:$('#selectorid').val()

What is the fastest way to create a checksum for large files in C#

I know that I am late to party but performed test before actually implement the solution.

I did perform test against inbuilt MD5 class and also md5sum.exe. In my case inbuilt class took 13 second where md5sum.exe too around 16-18 seconds in every run.

    DateTime current = DateTime.Now;
    string file = @"C:\text.iso";//It's 2.5 Gb file
    string output;
    using (var md5 = MD5.Create())
    {
        using (var stream = File.OpenRead(file))
        {
            byte[] checksum = md5.ComputeHash(stream);
            output = BitConverter.ToString(checksum).Replace("-", String.Empty).ToLower();
            Console.WriteLine("Total seconds : " + (DateTime.Now - current).TotalSeconds.ToString() + " " + output);
        }
    }

Bootstrap Modal sitting behind backdrop

In my case, I could fix it by adding css for the .modal-backdrop

.modal-backdrop {
  z-index: -1;
}

Although this works, form controls still seem to appear above the backdrop, clicking anywhere dismisses the modal, but it doesn't look great.

A better workaround for me is to bind to the shown event (once the page is loaded) and to correct the z-index property.

$('.modal').on('shown.bs.modal', function() {
  $(this).css("z-index", parseInt($('.modal-backdrop').css('z-index')) + 1);
});

In this case, if you are OK with changing the DOM on modal shown:

$('.modal').on('shown.bs.modal', function() {
  //Make sure the modal and backdrop are siblings (changes the DOM)
  $(this).before($('.modal-backdrop'));
  //Make sure the z-index is higher than the backdrop
  $(this).css("z-index", parseInt($('.modal-backdrop').css('z-index')) + 1);
});

How can I change the thickness of my <hr> tag

height attribute has been deprecated in html 5. What I would do is create a border around the hr and increase the thickness of the border as such: hr style="border:solid 2px black;"

What is the difference between instanceof and Class.isAssignableFrom(...)?

When using instanceof, you need to know the class of B at compile time. When using isAssignableFrom() it can be dynamic and change during runtime.

How to convert HH:mm:ss.SSS to milliseconds?

If you want to parse the format yourself you could do it easily with a regex such as

private static Pattern pattern = Pattern.compile("(\\d{2}):(\\d{2}):(\\d{2}).(\\d{3})");

public static long dateParseRegExp(String period) {
    Matcher matcher = pattern.matcher(period);
    if (matcher.matches()) {
        return Long.parseLong(matcher.group(1)) * 3600000L 
            + Long.parseLong(matcher.group(2)) * 60000 
            + Long.parseLong(matcher.group(3)) * 1000 
            + Long.parseLong(matcher.group(4)); 
    } else {
        throw new IllegalArgumentException("Invalid format " + period);
    }
}

However, this parsing is quite lenient and would accept 99:99:99.999 and just let the values overflow. This could be a drawback or a feature.

MySQL error 1449: The user specified as a definer does not exist

quick fix to work around and dump the file:

mysqldump --single-transaction -u root -p xyz_live_db > xyz_live_db_bkup110116.sql

Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp()

If you are starting out a react-native app and seeing this issue, then you have to follow all the instructions listed in firebase (when you setup iOS/android app) or the instructions @ React-native google auth android DEVELOPER_ERROR Code 10 question

enter image description here

How to compare data between two table in different databases using Sql Server 2008?

If both database on same server. You can check similar tables by using following query :

select 
      fdb.name, sdb.name 
from 
      FIRSTDBNAME.sys.tables fdb 
      join SECONDDBNAME.sys.tables sdb
      on fdb.name = sdb.name -- compare same name tables
order by 
      1     

By listing out similar table you can compare columns schema using sys.columns view.

Hope this helps you.

AngularJS : Clear $watch

$watch returns a deregistration function. Calling it would deregister the $watcher.

var listener = $scope.$watch("quartz", function () {});
// ...
listener(); // Would clear the watch

phpMyAdmin mbstring error

Using xampp, this will work (php7 has been extracted to the xampp\php directory):

Make the following changes in the php.ini:

  1. uncommend (remove the ;)

;extension=php_mbstring.dll

  1. uncommend (remove the ;)

;extension=php_mysqli.dll

  1. set the path to the extention Directory

extension_dir = "ext"

to the full path, for example:

extension_dir = "C:\xammp\php\ext"

Additional, change the xampp-settings in the httpd-xampp.conf:

  1. change

LoadFile "C:/xampp/php/php5ts.dll"

to

LoadFile "C:/xampp/php/php7ts.dll"

  1. change

LoadModule php5_module "C:/xampp/php/php5apache2_4.dll"

to

LoadModule php7_module "C:/xampp/php/php7apache2_4.dll"

  1. change all appearance (3 times) of

IfModule php5_module

to

IfModule php7_module

That's it.

How to uninstall a windows service and delete its files without rebooting

Are you not able to stop the service before the update (and restart after the update) using the commands below?

net stop <service name>
net start <service name>

Whenever I'm testing/deploying a service I'm able to upload files without reinstalling as long as the service is stopped. I'm not sure if the issue you are having is different.

How to use *ngIf else?

In Angular 4, 5 and 6

We can simply create a template reference variable [2] and link that to the else condition inside an *ngIf directive

The possible Syntaxes [1] are:

<!-- Only If condition -->
<div *ngIf="condition">...</div>
<!-- or -->
<ng-template [ngIf]="condition"><div>...</div></ng-template>


<!-- If and else conditions -->
<div *ngIf="condition; else elseBlock">...</div>
<!-- or -->
<ng-template #elseBlock>...</ng-template>

<!-- If-then-else -->
<div *ngIf="condition; then thenBlock else elseBlock"></div>
<ng-template #thenBlock>...</ng-template>
<ng-template #elseBlock>...</ng-template>


<!-- If and else conditions (storing condition value locally) -->
<div *ngIf="condition as value; else elseBlock">{{value}}</div>
<ng-template #elseBlock>...</ng-template>

DEMO: https://stackblitz.com/edit/angular-feumnt?embed=1&file=src/app/app.component.html

Sources:

  1. https://angular.io/api/common/NgIf#syntax
  2. https://angular.io/guide/template-syntax#template-reference-variables--var-

How to use OrderBy with findAll in Spring Data

Please have a look at the Spring Data JPA - Reference Documentation, section 5.3. Query Methods, especially at section 5.3.2. Query Creation, in "Table 3. Supported keywords inside method names" (links as of 2019-05-03).

I think it has exactly what you need and same query as you stated should work...

How do you get the contextPath from JavaScript, the right way?

Reviewer the solution by this Checking the solution of this page, make the following solution I hope it works: Example:

Javascript:

var context = window.location.pathname.substring(0, window.location.pathname.indexOf("/",2)); 
var url =window.location.protocol+"//"+ window.location.host +context+"/bla/bla";

How to run vbs as administrator from vbs?

`My vbs file path :

D:\QTP Practice\Driver\Testany.vbs'

objShell = CreateObject("Shell.Application")

objShell.ShellExecute "cmd.exe","/k echo test", "", "runas", 1

set x=createobject("wscript.shell")

wscript.sleep(2000)

x.sendkeys "CD\"&"{ENTER}"&"cd D:"&"{ENTER}"&"cd "&"QTP Practice\Driver"&"{ENTER}"&"Testany.vbs"&"{ENTER}"

--from google search and some tuning, working for me

How to click or tap on a TextView text

You can use TextWatcher for TextView, is more flexible than ClickLinstener (not best or worse, only more one way).

holder.bt_foo_ex.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // code during!

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // code before!

        }

        @Override
        public void afterTextChanged(Editable s) {
            // code after!

        }
    });

initialize a const array in a class initializer in C++

With C++11 the answer to this question has now changed and you can in fact do:

struct a {
    const int b[2];
    // other bits follow

    // and here's the constructor
    a();
};

a::a() :
    b{2,3}
{
     // other constructor work
}

int main() {
 a a;
}

How to get HTTP response code for a URL in Java?

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");

. . . . . . .

System.out.println("Value" + connection.getResponseCode());
             System.out.println(connection.getResponseMessage());
             System.out.println("content"+connection.getContent());

Find text string using jQuery?

This will select just the leaf elements that contain "I am a simple string".

$('*:contains("I am a simple string")').each(function(){
     if($(this).children().length < 1) 
          $(this).css("border","solid 2px red") });

Paste the following into the address bar to test it.

javascript: $('*:contains("I am a simple string")').each(function(){ if($(this).children().length < 1) $(this).css("border","solid 2px red") }); return false;

If you want to grab just "I am a simple string". First wrap the text in an element like so.

$('*:contains("I am a simple string")').each(function(){
     if($(this).children().length < 1) 
          $(this).html( 
               $(this).text().replace(
                    /"I am a simple string"/
                    ,'<span containsStringImLookingFor="true">"I am a simple string"</span>' 
               )  
           ) 
});

and then do this.

$('*[containsStringImLookingFor]').css("border","solid 2px red");

How do I get the current location of an iframe?

I did some tests in Firefox 3 comparing the value of .src and .documentWindow.location.href in an iframe. (Note: The documentWindow is called contentDocument in Chrome, so instead of .documentWindow.location.href in Chrome it will be .contentDocument.location.href.)

src is always the last URL that was loaded in the iframe without user interaction. I.e., it contains the first value for the URL, or the last value you set up with Javascript from the containing window doing:

document.getElementById("myiframe").src = 'http://www.google.com/';

If the user navigates inside the iframe, you can't anymore access the value of the URL using src. In the previous example, if the user goes away from www.google.com and you do:

alert(document.getElementById("myiframe").src);

You will still get "http://www.google.com".

documentWindow.location.href is only available if the iframe contains a page in the same domain as the containing window, but if it's available it always contains the right value for the URL, even if the user navigates in the iframe.

If you try to access documentWindow.location.href (or anything under documentWindow) and the iframe is in a page that doesn't belong to the domain of the containing window, it will raise an exception:

document.getElementById("myiframe").src = 'http://www.google.com/';
alert(document.getElementById("myiframe").documentWindow.location.href);
Error: Permission denied to get property Location.href

I have not tested any other browser.

Hope it helps!

When should I write the keyword 'inline' for a function/method?

I'd like to contribute to all of the great answers in this thread with a convincing example to disperse any remaining misunderstanding.

Given two source files, such as:

  • inline111.cpp:

    #include <iostream>
    
    void bar();
    
    inline int fun() {
      return 111;
    }
    
    int main() {
      std::cout << "inline111: fun() = " << fun() << ", &fun = " << (void*) &fun;
      bar();
    }
    
  • inline222.cpp:

    #include <iostream>
    
    inline int fun() {
      return 222;
    }
    
    void bar() {
      std::cout << "inline222: fun() = " << fun() << ", &fun = " << (void*) &fun;
    }
    

  • Case A:

    Compile:

    g++ -std=c++11 inline111.cpp inline222.cpp
    

    Output:

    inline111: fun() = 111, &fun = 0x4029a0
    inline222: fun() = 111, &fun = 0x4029a0
    

    Discussion:

    1. Even thou you ought to have identical definitions of your inline functions, C++ compiler does not flag it if that is not the case (actually, due to separate compilation it has no ways to check it). It is your own duty to ensure this!

    2. Linker does not complain about One Definition Rule, as fun() is declared as inline. However, because inline111.cpp is the first translation unit (which actually calls fun()) processed by compiler, the compiler instantiates fun() upon its first call-encounter in inline111.cpp. If compiler decides not to expand fun() upon its call from anywhere else in your program (e.g. from inline222.cpp), the call to fun() will always be linked to its instance produced from inline111.cpp (the call to fun() inside inline222.cpp may also produce an instance in that translation unit, but it will remain unlinked). Indeed, that is evident from the identical &fun = 0x4029a0 print-outs.

    3. Finally, despite the inline suggestion to the compiler to actually expand the one-liner fun(), it ignores your suggestion completely, which is clear because fun() = 111 in both of the lines.


  • Case B:

    Compile (notice reverse order):

    g++ -std=c++11 inline222.cpp inline111.cpp
    

    Output:

    inline111: fun() = 222, &fun = 0x402980
    inline222: fun() = 222, &fun = 0x402980
    

    Discussion:

    1. This case asserts what have been discussed in Case A.

    2. Notice an important point, that if you comment out the actual call to fun() in inline222.cpp (e.g. comment out cout-statement in inline222.cpp completely) then, despite the compilation order of your translation units, fun() will be instantiated upon it's first call encounter in inline111.cpp, resulting in print-out for Case B as inline111: fun() = 111, &fun = 0x402980.


  • Case C:

    Compile (notice -O2):

    g++ -std=c++11 -O2 inline222.cpp inline111.cpp
    

    or

    g++ -std=c++11 -O2 inline111.cpp inline222.cpp
    

    Output:

    inline111: fun() = 111, &fun = 0x402900
    inline222: fun() = 222, &fun = 0x402900
    

    Discussion:

    1. As is described here, -O2 optimization encourages compiler to actually expand the functions that can be inlined (Notice also that -fno-inline is default without optimization options). As is evident from the outprint here, the fun() has actually been inline expanded (according to its definition in that particular translation unit), resulting in two different fun() print-outs. Despite this, there is still only one globally linked instance of fun() (as required by the standard), as is evident from identical &fun print-out.

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

Root cause: Corrupted user profile of user account used to start database

The main thread here seems to be a corrupted user account profile for the account that is used to start the DB engine. This is the account that was specified for the "SQL Server Database" engine during installation. In the setup event log, it's also indicated by the following entry:

SQLSVCACCOUNT:                 NT AUTHORITY\SYSTEM

According to the link provided by @royki:

The root cause of this issue, in most cases, is that the profile of the user being used for the service account (in my case it was local system) is corrupted.

This would explain why other respondents had success after changing to different accounts:

  • bmjjr suggests changing to "NT AUTHORITY\NETWORK SERVICE"
  • comments to @bmjjr indicate different accounts "I used NT AUTHORITY\LOCAL SERVICE. That helped too"
  • @Julio Nobre had success with "NT Authority\System "

Fix: reset the corrupt user profile

To fix the user profile that's causing the error, follow the steps listed KB947215.

The main steps from KB947215 are summarized as follows:-

  1. Open regedit
  2. Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
  3. Navigate to the SID for the corrupted profile

    To find the SID, click on each SID GUID, review the value for the ProfileImagePath value, and see if it's the correct account. For system accounts, there's a different way to know the SID for the account that failed:

The main system account SIDs of interest are:

SID          Name               Also Known As
S-1-5-18     Local System       NT AUTHORITY\SYSTEM
S-1-5-19     LocalService       NT AUTHORITY\LOCAL SERVICE
S-1-5-20     NetworkService     NT AUTHORITY\NETWORK SERVICE

For information on additional SIDs, see Well-known security identifiers in Windows operating systems.

  1. If there are two entries (e.g. with a .bak) at the end for the SID in question, or the SID in question ends in .bak, ensure to follow carefully the steps in the KB947215 article.
  2. Reset the values for RefCount and State to be 0.
  3. Reboot.
  4. Retry the SQL Server installation.

What is the difference between char s[] and char *s?

char *s1 = "Hello world"; // Points to fixed character string which is not allowed to modify
char s2[] = "Hello world"; // As good as fixed array of characters in string so allowed to modify

// s1[0] = 'J'; // Illegal
s2[0] = 'J'; // Legal

OnClickListener in Android Studio

protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_my);
    titolorecuperato = (TextView) findViewById(R.id.textView);
    String stitolo = titolorecuperato.getText().toString();

    Button btnHome = (Button) findViewById(R.id.button);

    btnHome.setOnClickListener(new View.OnClickListener() {

       @Override
        public void onClick(View view) {

       }
});

same thing as Nic007 said before.

You do need to write code inside "onCreate" method. Sorry me too for the indent... (first comment here)

how to replace an entire column on Pandas.DataFrame

For those that struggle with the "SettingWithCopy" warning, here's a workaround which may not be so efficient, but still gets the job done.

Suppose you with to overwrite column_1 and column_3, but retain column_2 and column_4

columns_to_overwrite = ["column_1", "column_3"]

First delete the columns that you intend to replace...

original_df.drop(labels=columns_to_overwrite, axis="columns", inplace=True)

... then re-insert the columns, but using the values that you intended to overwrite

original_df[columns_to_overwrite] = other_data_frame[columns_to_overwrite]

How to iterate through a list of objects in C++

Since C++ 11, you could do the following:

for(const auto& student : data)
{
  std::cout << student.name << std::endl;
}

SOAP request to WebService with java

A SOAP request is an XML file consisting of the parameters you are sending to the server.

The SOAP response is equally an XML file, but now with everything the service wants to give you.

Basically the WSDL is a XML file that explains the structure of those two XML.


To implement simple SOAP clients in Java, you can use the SAAJ framework (it is shipped with JSE 1.6 and above):

SOAP with Attachments API for Java (SAAJ) is mainly used for dealing directly with SOAP Request/Response messages which happens behind the scenes in any Web Service API. It allows the developers to directly send and receive soap messages instead of using JAX-WS.

See below a working example (run it!) of a SOAP web service call using SAAJ. It calls this web service.

import javax.xml.soap.*;

public class SOAPClientSAAJ {

    // SAAJ - SOAP Client Testing
    public static void main(String args[]) {
        /*
            The example below requests from the Web Service at:
             http://www.webservicex.net/uszip.asmx?op=GetInfoByCity


            To call other WS, change the parameters below, which are:
             - the SOAP Endpoint URL (that is, where the service is responding from)
             - the SOAP Action

            Also change the contents of the method createSoapEnvelope() in this class. It constructs
             the inner part of the SOAP envelope that is actually sent.
         */
        String soapEndpointUrl = "http://www.webservicex.net/uszip.asmx";
        String soapAction = "http://www.webserviceX.NET/GetInfoByCity";

        callSoapWebService(soapEndpointUrl, soapAction);
    }

    private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
        SOAPPart soapPart = soapMessage.getSOAPPart();

        String myNamespace = "myNamespace";
        String myNamespaceURI = "http://www.webserviceX.NET";

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);

            /*
            Constructed SOAP Request Message:
            <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myNamespace="http://www.webserviceX.NET">
                <SOAP-ENV:Header/>
                <SOAP-ENV:Body>
                    <myNamespace:GetInfoByCity>
                        <myNamespace:USCity>New York</myNamespace:USCity>
                    </myNamespace:GetInfoByCity>
                </SOAP-ENV:Body>
            </SOAP-ENV:Envelope>
            */

        // SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyElem = soapBody.addChildElement("GetInfoByCity", myNamespace);
        SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("USCity", myNamespace);
        soapBodyElem1.addTextNode("New York");
    }

    private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
        try {
            // Create SOAP Connection
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();

            // Send SOAP Message to SOAP Server
            SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);

            // Print the SOAP Response
            System.out.println("Response SOAP Message:");
            soapResponse.writeTo(System.out);
            System.out.println();

            soapConnection.close();
        } catch (Exception e) {
            System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");
            e.printStackTrace();
        }
    }

    private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();

        createSoapEnvelope(soapMessage);

        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", soapAction);

        soapMessage.saveChanges();

        /* Print the request message, just for debugging purposes */
        System.out.println("Request SOAP Message:");
        soapMessage.writeTo(System.out);
        System.out.println("\n");

        return soapMessage;
    }

}

C++ Compare char array with string

"dev" is not a string it is a const char * like var1. Thus you are indeed comparing the memory adresses. Being that var1 is a char pointer, *var1 is a single char (the first character of the pointed to character sequence to be precise). You can't compare a char against a char pointer, which is why that did not work.

Being that this is tagged as c++, it would be sensible to use std::string instead of char pointers, which would make == work as expected. (You would just need to do const std::string var1 instead of const char *var1.

window.location.href not working

Please check you are using // not \\ by-mistake , like below

Wrong:"http:\\stackoverflow.com"

Right:"http://stackoverflow.com"

open existing java project in eclipse

The typical pattern is to check out the root project folder (=the one containing a file called ".project") from SVN using eclipse's svn integration (SVN repository exploring perspective). The project is then recognized automatically.

C++ error : terminate called after throwing an instance of 'std::bad_alloc'

Something throws an exception of type std::bad_alloc, indicating that you ran out of memory. This exception is propagated through until main, where it "falls off" your program and causes the error message you see.

Since nobody here knows what "RectInvoice", "rectInvoiceVector", "vect", "im" and so on are, we cannot tell you what exactly causes the out-of-memory condition. You didn't even post your real code, because w h looks like a syntax error.

Sending and receiving UDP packets?

The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.

If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.

Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.

In the sender you set:

 byte [] IP= { (byte)192, (byte)168, 1, 106 };
 InetAddress address = InetAddress.getByAddress(IP);

but might be simpler to use the address in string form:

 InetAddress address = InetAddress.getByName("192.168.1.106");

In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.

Here's a simple UDP Receiver that works :

import java.io.IOException;
import java.net.*;

public class Receiver {

    public static void main(String[] args) {
        int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
        new Receiver().run(port);
    }

    public void run(int port) {    
      try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        String sendString = "polo";
        byte[] sendData = sendString.getBytes("UTF-8");

        System.out.printf("Listening on udp:%s:%d%n",
                InetAddress.getLocalHost().getHostAddress(), port);     
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                           receiveData.length);

        while(true)
        {
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData(), 0,
                                 receivePacket.getLength() );
              System.out.println("RECEIVED: " + sentence);
              // now send acknowledgement packet back to sender     
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                   receivePacket.getAddress(), receivePacket.getPort());
              serverSocket.send(sendPacket);
        }
      } catch (IOException e) {
              System.out.println(e);
      }
      // should close serverSocket in finally block
    }
}

Ansible: filter a list by its attributes

I've submitted a pull request (available in Ansible 2.2+) that will make this kinds of situations easier by adding jmespath query support on Ansible. In your case it would work like:

- debug: msg="{{ addresses | json_query(\"private_man[?type=='fixed'].addr\") }}"

would return:

ok: [localhost] => {
    "msg": [
        "172.16.1.100"
    ]
}

How to customize the configuration file of the official PostgreSQL Docker image?

Using docker compose you can mount a volume with postgresql.auto.conf. Example:

version: '2'

services:
  db:
    image: postgres:10.9-alpine
    volumes:
      - postgres:/var/lib/postgresql/data:z
      - ./docker/postgres/postgresql.auto.conf:/var/lib/postgresql/data/postgresql.auto.conf
    ports:
      - 5432:5432

Return list from async/await method

In addition to @takemyoxygen's answer the convention of having a function name that ends in Async is that this function is truly asynchronous. I.e. it does not start a new thread and it doesn't simply call Task.Run. If that is all the code that is in your function, it will be better to remove it completely and simply have:

List<Item> list = await Task.Run(() => manager.GetList());

BootStrap : Uncaught TypeError: $(...).datetimepicker is not a function

I had this problem. Solution for me was to remove links to Vue.js files. Vue.js and JQuery have some conflicts in datepicker and datetimepicker functions.

Rename all files in a folder with a prefix in a single command

If your filenames contain no whitepace and you don't have any subdirectories, you can use a simple for loop:

$ for FILENAME in *; do mv $FILENAME Unix_$FILENAME; done 

Otherwise use the convenient rename command (which is a perl script) - although it might not be available out of the box on every Unix (e.g. OS X doesn't come with rename).

A short overview at debian-administration.org:

If your filenames contain whitespace it's easier to use find, on Linux the following should work:

$ find . -type f -name '*' -printf "echo mv '%h/%f' '%h/Unix_%f\n'" | sh

On BSD systems, there is no -printf option, unfortunately. But GNU findutils should be installable (on e.g. Mac OS X with brew install findutils).

$ gfind . -type f -name '*' -printf "mv \"%h/%f\" \"%h/Unix_%f\"\n" | sh

Scrollview can host only one direct child

Wrap all the children inside of another LinearLayout with wrap_content for both the width and the height as well as the vertical orientation.

Adding a collaborator to my free GitHub account?

Yes the set of instructions above are outdated. For the new GitHub the Settings button must be clicked.

Also the person you try to add as a collaborator must have an existing GitHub account. In other words he should have signed up on GitHub first because it is not possible to send collaboration requests merely by typing in the email address of the collaborator.

How to change the background-color of jumbrotron?

I put the jumbotron in a <header> class and added background-color: black !important; to the header class in css.

How to change the color of progressbar in C# .NET 3.5?

The VB.Net colored progressbar which respects WXP Visual Styles answer is ...

I started with the answer from 'user1032613' on 3/17/12. Note that this is now a Module, not a class. From there I converted the code but more was needed. In particular the converted code showed a DirectCast function to convert the 'state' integer to a IntPtr type which didn't work.

Imports System.Runtime.InteropServices

Public Module ModifyProgressBarColor

    Private Declare Function SendMessage Lib "User32" Alias "SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Long) As Long

    <DllImport("user32.dll", CharSet:=CharSet.Auto, SetLastError:=False)> _
    Private Function SendMessage(hWnd As IntPtr, Msg As UInteger, w As IntPtr, l As IntPtr) As IntPtr
    End Function

    <System.Runtime.CompilerServices.Extension()> _
    Public Sub SetState(pBar As ProgressBar, state As Integer)

        '-- Convert state as integer to type IntPtr
        Dim s As IntPtr
        Dim y As Integer = state
        s = IntPtr.op_Explicit(y)

        '-- Modify bar color
        SendMessage(pBar.Handle, 1040, s, IntPtr.Zero)

    End Sub

End Module

And again just call this in the using code with this line:

Call ModifyProgressBarColor.SetState(prb, 2)

BTW - I tried other colors - 0, 4, 5 - they all just displayed green.

Android: Create a toggle button with image and no text

I know this is a little late, however for anyone interested, I've created a custom component that is basically a toggle image button, the drawable can have states as well as the background

https://gist.github.com/akshaydashrath/9662072

Should I call Close() or Dispose() for stream objects?

No, you shouldn't call those methods manually. At the end of the using block the Dispose() method is automatically called which will take care to free unmanaged resources (at least for standard .NET BCL classes such as streams, readers/writers, ...). So you could also write your code like this:

using (Stream responseStream = response.GetResponseStream())
    using (StreamReader reader = new StreamReader(responseStream))
        using (StreamWriter writer = new StreamWriter(filename))
        {
            int chunkSize = 1024;
            while (!reader.EndOfStream)
            {
                 char[] buffer = new char[chunkSize];
                 int count = reader.Read(buffer, 0, chunkSize);
                 if (count != 0)
                 {
                     writer.Write(buffer, 0, count);
                 }
            }
         }

The Close() method calls Dispose().

Determine the number of rows in a range

That single last line worked perfectly @GSerg.

The other function was what I had been working on but I don't like having to resort to UDF's unless absolutely necessary.

I had been trying a combination of excel and vba and had got this to work - but its clunky compared with your answer.

strArea = Sheets("Oper St Report CC").Range("cc_rev").CurrentRegion.Address
cc_rev_rows = "=ROWS(" & strArea & ")"
Range("cc_rev_count").Formula = cc_rev_rows

How to Read and Write from the Serial Port

Note that usage of a SerialPort.DataReceived event is optional. You can set proper timeout using SerialPort.ReadTimeout and continuously call SerialPort.Read() after you wrote something to a port until you get a full response.

Moreover you can use SerialPort.BaseStream property to extract an underlying Stream instance. The benefit of using a Stream is that you can easily utilize various decorators with it:

var port = new SerialPort();
// LoggingStream inherits Stream, implements IDisposable, needen abstract methods and 
// overrides needen virtual methods. 
Stream portStream = new LoggingStream(port.BaseStream);
portStream.Write(...); // Logs write buffer.
portStream.Read(...); // Logs read buffer.

For more information check:

How can I get the count of milliseconds since midnight for the current?

tl;dr

You ask for the fraction of a second of the current time as a number of milliseconds (not count from epoch).

Instant.now()                               // Get current moment in UTC, then…
       .get( ChronoField.MILLI_OF_SECOND )  // interrogate a `TemporalField`.

2017-04-25T03:01:14.113Z ? 113

  1. Get the fractional second in nanoseconds (billions).
  2. Divide by a thousand to truncate to milliseconds (thousands).

See this code run live at IdeOne.com.

Using java.time

The modern way is with the java.time classes.

Capture the current moment in UTC.

Instant.now()

Use the Instant.get method to interrogate for the value of a TemporalField. In our case, the TemporalField we want is ChronoField.MILLI_OF_SECOND.

int millis = Instant.now().get( ChronoField.MILLI_OF_SECOND ) ;  // Get current moment in UTC, then interrogate a `TemporalField`.

Or do the math yourself.

More likely you are asking this for a specific time zone. The fraction of a second is likely to be the same as with Instant but there are so many anomalies with time zones, I hesitate to make that assumption.

ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "America/Montreal" ) ) ;

Interrogate for the fractional second. The Question asked for milliseconds, but java.time classes use a finer resolution of nanoseconds. That means the number of nanoseconds will range from from 0 to 999,999,999.

long nanosFractionOfSecond = zdt.getNano();

If you truly want milliseconds, truncate the finer data by dividing by one million. For example, a half second is 500,000,000 nanoseconds and also is 500 milliseconds.

long millis = ( nanosFractionOfSecond / 1_000_000L ) ;  // Truncate nanoseconds to milliseconds, by a factor of one million.

About java.time

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

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

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

Where to obtain the java.time classes?

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

Why must wait() always be in synchronized block

Thread wait on the monitoring object (object used by synchronization block), There can be n number of monitoring object in whole journey of a single thread. If Thread wait outside the synchronization block then there is no monitoring object and also other thread notify to access for the monitoring object, so how would the thread outside the synchronization block would know that it has been notified. This is also one of the reason that wait(), notify() and notifyAll() are in object class rather than thread class.

Basically the monitoring object is common resource here for all the threads, and monitoring objects can only be available in synchronization block.

class A {
   int a = 0;
  //something......
  public void add() {
   synchronization(this) {
      //this is your monitoring object and thread has to wait to gain lock on **this**
       }
  }

RegExp matching string not starting with my

/^(?!my).*/

(?!expression) is a negative lookahead; it matches a position where expression doesn't match starting at that position.

Stop Excel from automatically converting certain text values to dates

(Assuming Excel 2003...)

When using the Text-to-Columns Wizard has, in Step 3 you can dictate the data type for each of the columns. Click on the column in the preview and change the misbehaving column from "General" to "Text."

How can I be notified when an element is added to the page?

Warning!

This answer is now outdated. DOM Level 4 introduced MutationObserver, providing an effective replacement for the deprecated mutation events. See this answer to another question for a better solution than the one presented here. Seriously. Don't poll the DOM every 100 milliseconds; it will waste CPU power and your users will hate you.

Since mutation events were deprecated in 2012, and you have no control over the inserted elements because they are added by someone else's code, your only option is to continuously check for them.

function checkDOMChange()
{
    // check for any new element being inserted here,
    // or a particular node being modified

    // call the function again after 100 milliseconds
    setTimeout( checkDOMChange, 100 );
}

Once this function is called, it will run every 100 milliseconds, which is 1/10 (one tenth) of a second. Unless you need real-time element observation, it should be enough.

Reading a string with spaces with sscanf

The following line will start reading a number (%d) followed by anything different from tabs or newlines (%[^\t\n]).

sscanf("19 cool kid", "%d %[^\t\n]", &age, buffer);

How do I drag and drop files into an application?

Another common gotcha is thinking you can ignore the Form DragOver (or DragEnter) events. I typically use the Form's DragOver event to set the AllowedEffect, and then a specific control's DragDrop event to handle the dropped data.

Excel Date Conversion from yyyymmdd to mm/dd/yyyy

for converting dd/mm/yyyy to mm/dd/yyyy

=DATE(RIGHT(a1,4),MID(a1,4,2),LEFT(a1,2))

Accessing variables from other functions without using global variables

I don't know specifics of your issue, but if the function needs the value then it can be a parameter passed through the call.

Globals are considered bad because globals state and multiple modifiers can create hard to follow code and strange errors. To many actors fiddling with something can create chaos.

Gradient text color

The way this effect works is very simple. The element is given a background which is the gradient. It goes from one color to another depending on the colors and color-stop percentages given for it.

For example, in rainbow text sample (note that I've converted the gradient into the standard syntax):

  • The gradient starts at color #f22 at 0% (that is the left edge of the element). First color is always assumed to start at 0% even though the percentage is not mentioned explicitly.
  • Between 0% to 14.25%, the color changes from #f22 to #f2f gradually. The percenatge is set at 14.25 because there are seven color changes and we are looking for equal splits.
  • At 14.25% (of the container's size), the color will exactly be #f2f as per the gradient specified.
  • Similarly the colors change from one to another depending on the bands specified by color stop percentages. Each band should be a step of 14.25%.

So, we end up getting a gradient like in the below snippet. Now this alone would mean the background applies to the entire element and not just the text.

_x000D_
_x000D_
.rainbow {_x000D_
  background-image: linear-gradient(to right, #f22, #f2f 14.25%, #22f 28.5%, #2ff 42.75%, #2f2 57%, #2f2 71.25%, #ff2 85.5%, #f22);_x000D_
  color: transparent;_x000D_
}
_x000D_
<span class="rainbow">Rainbow text</span>
_x000D_
_x000D_
_x000D_

Since, the gradient needs to be applied only to the text and not to the element on the whole, we need to instruct the browser to clip the background from the areas outside the text. This is done by setting background-clip: text.

(Note that the background-clip: text is an experimental property and is not supported widely.)


Now if you want the text to have a simple 3 color gradient (that is, say from red - orange - brown), we just need to change the linear-gradient specification as follows:

  • First parameter is the direction of the gradient. If the color should be red at left side and brown at the right side then use the direction as to right. If it should be red at right and brown at left then give the direction as to left.
  • Next step is to define the colors of the gradient. Since our gradient should start as red on the left side, just specify red as the first color (percentage is assumed to be 0%).
  • Now, since we have two color changes (red - orange and orange - brown), the percentages must be set as 100 / 2 for equal splits. If equal splits are not required, we can assign the percentages as we wish.
  • So at 50% the color should be orange and then the final color would be brown. The position of the final color is always assumed to be at 100%.

Thus the gradient's specification should read as follows:

background-image: linear-gradient(to right, red, orange 50%, brown).

If we form the gradients using the above mentioned method and apply them to the element, we can get the required effect.

_x000D_
_x000D_
.red-orange-brown {_x000D_
  background-image: linear-gradient(to right, red, orange 50%, brown);_x000D_
  color: transparent;_x000D_
  -webkit-background-clip: text;_x000D_
  background-clip: text;_x000D_
}_x000D_
.green-yellowgreen-yellow-gold {_x000D_
  background-image: linear-gradient(to right, green, yellowgreen 33%, yellow 66%, gold);_x000D_
  color: transparent;_x000D_
  -webkit-background-clip: text;_x000D_
  background-clip: text;_x000D_
}
_x000D_
<span class="red-orange-brown">Red to Orange to Brown</span>_x000D_
_x000D_
<br>_x000D_
_x000D_
<span class="green-yellowgreen-yellow-gold">Green to Yellow-green to Yellow to Gold</span>
_x000D_
_x000D_
_x000D_

CSS: Center block, but align contents to the left

Is this what you are looking for? Flexbox...

_x000D_
_x000D_
.container{_x000D_
  display: flex;_x000D_
  flex-flow: row wrap;_x000D_
  justify-content: center;_x000D_
  align-content: center;_x000D_
  align-items: center;_x000D_
}_x000D_
.inside{_x000D_
  height:100px;_x000D_
  width:100px;_x000D_
  background:gray;_x000D_
  border:1px solid;_x000D_
}
_x000D_
<section class="container">_x000D_
  <section class="inside">_x000D_
    A_x000D_
  </section>_x000D_
  <section class="inside">_x000D_
    B_x000D_
  </section>_x000D_
  <section class="inside">_x000D_
    C_x000D_
  </section>_x000D_
</section>
_x000D_
_x000D_
_x000D_

How to generate .json file with PHP?

Use PHP's json methods to create the json then write it to a file with fwrite.

How to draw a rectangle around a region of interest in python

As the other answers said, the function you need is cv2.rectangle(), but keep in mind that the coordinates for the bounding box vertices need to be integers if they are in a tuple, and they need to be in the order of (left, top) and (right, bottom). Or, equivalently, (xmin, ymin) and (xmax, ymax).

How to represent multiple conditions in a shell if statement?

$ g=3
$ c=133
$ ([ "$g$c" = "1123" ] || [ "$g$c" = "2456" ]) && echo "abc" || echo "efg"
efg
$ g=1
$ c=123
$ ([ "$g$c" = "1123" ] || [ "$g$c" = "2456" ]) && echo "abc" || echo "efg"
abc

Is there a function to round a float in C or do I need to write my own?

#include <math.h>

double round(double x);
float roundf(float x);

Don't forget to link with -lm. See also ceil(), floor() and trunc().

Set Date in a single line

Use the constructor Date(year,month,date) in Java 8 it is deprecated:

Date date = new Date(1990, 10, 26, 0, 0);

The best way is to use SimpleDateFormat

DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date = format.parse("26/10/1985");

you need to import import java.text.SimpleDateFormat;

How do I purge a linux mail box with huge number of emails?

You can simply delete the /var/mail/username file to delete all emails for a specific user. Also, emails that are outgoing but have not yet been sent will be stored in /var/spool/mqueue.

How do I update the element at a certain position in an ArrayList?

 import java.util.ArrayList;
 import java.util.Iterator;


 public class javaClass {

public static void main(String args[]) {


    ArrayList<String> alstr = new ArrayList<>();
    alstr.add("irfan");
    alstr.add("yogesh");
    alstr.add("kapil");
    alstr.add("rajoria");

    for(String str : alstr) {
        System.out.println(str);
    }
    // update value here
    alstr.set(3, "Ramveer");
    System.out.println("with Iterator");
    Iterator<String>  itr = alstr.iterator();

    while (itr.hasNext()) {
        Object obj = itr.next();
        System.out.println(obj);

    }
}}

Resetting a setTimeout

You can store a reference to that timeout, and then call clearTimeout on that reference.

// in the example above, assign the result
var timeoutHandle = window.setTimeout(...);

// in your click function, call clearTimeout
window.clearTimeout(timeoutHandle);

// then call setTimeout again to reset the timer
timeoutHandle = window.setTimeout(...);

What is the use of static constructors?

Static constructors are also very useful when you have static fields that rely upon each other such that the order of initialization is important. If you run your code through a formatter/beautifier that changes the order of the fields then you may find yourself with null values where you didn't expect them.

Example: Suppose we had this class:

class ScopeMonitor
{
    static string urlFragment = "foo/bar";
    static string firstPart= "http://www.example.com/";
    static string fullUrl= firstPart + urlFragment;
}

When you access fullUr, it will be "http://www.example.com/foo/bar".

Months later you're cleaning up your code and alphabetize the fields (let's say they're part of a much larger list, so you don't notice the problem). You have:

class ScopeMonitor
{
    static string firstPart= "http://www.example.com/";
    static string fullUrl= firstPart + urlFragment;
    static string urlFragment = "foo/bar";
}

Your fullUrl value is now just "http://www.example.com/" since urlFragment hadn't been initialized at the time fullUrl was being set. Not good. So, you add a static constructor to take care of the initialization:

class ScopeMonitor
{
    static string firstPart= "http://www.example.com/";
    static string fullUrl;
    static string urlFragment = "foo/bar";

    static ScopeMonitor()
    {
        fullUrl= firstPart + urlFragment;

    }
}

Now, no matter what order you have the fields, the initialization will always be correct.

How to convert a List<String> into a comma separated string without iterating List explicitly

If you want to convert list into the CSV format .........

List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");

// CSV format
String csv = ids.toString().replace("[", "").replace("]", "")
            .replace(", ", ",");

// CSV format surrounded by single quote 
// Useful for SQL IN QUERY

String csvWithQuote = ids.toString().replace("[", "'").replace("]", "'")
            .replace(", ", "','");

How to track untracked content?

http://progit.org/book/ch6-6.html

I think you should read this to learn a little about submodule. It's well-written, and it doesn't take much time to read it.

The activity must be exported or contain an intent-filter

If you're trying to launch a specific activity instead of running the launcher one. When you select that activity. the android studio might through this error, Either you need to make it launcher activity, just like answered by few others. or you need to add android:exported="true" inside your activity tag inside manifest. It allows any external tool to run your specific activity directly without making it a launcher activity

How do you set the width of an HTML Helper TextBox in ASP.NET MVC?

My real sample for MVC 3 is here:

<% using (Html.BeginForm()) { %>

<p>

Start Date: <%: Html.TextBox("datepicker1", DateTime.Now.ToString("MM/dd/yyyy"), new { style = "width:80px;", maxlength = 10 })%> 

End Date: <%: Html.TextBox("datepicker2", DateTime.Now.ToString("MM/dd/yyyy"), new { style = "width:80px;", maxlength = 10 })%> 

<input type="submit" name="btnSubmit" value="Search" /> 

</p>

<% } %>

So, we have following

"datepicker1" - ID of the control

DateTime.Now.ToString("MM/dd/yyyy") - value by default

style = "width:80px;" - width of the textbox

maxlength = 10 - we can input 10 characters only

How do you format an unsigned long long int using printf?

You may want to try using the inttypes.h library that gives you types such as int32_t, int64_t, uint64_t etc. You can then use its macros such as:

uint64_t x;
uint32_t y;

printf("x: %"PRId64", y: %"PRId32"\n", x, y);

This is "guaranteed" to not give you the same trouble as long, unsigned long long etc, since you don't have to guess how many bits are in each data type.

LaTeX beamer: way to change the bullet indentation?

Beamer just delegates responsibility for managing layout of itemize environments back to the base LaTeX packages, so there's nothing funky you need to do in Beamer itself to alter the apperaance / layout of your lists.

Since Beamer redefines itemize, item, etc., the fully proper way to manipulate things like indentation is to redefine the Beamer templates. I get the impression that you're not looking to go that far, but if that's not the case, let me know and I'll elaborate.

There are at least three ways of accomplishing your goal from within your document, without mussing about with Beamer templates.

With itemize

In the following code snippet, you can change the value of \itemindent from 0em to whatever you please, including negative values. 0em is the default item indentation.

The advantage of this method is that the list is styled normally. The disadvantage is that Beamer's redefinition of itemize and \item means that the number of paramters that can be manipulated to change the list layout is limited. It can be very hard to get the spacing right with multi-line items.

\begin{itemize}
  \setlength{\itemindent}{0em}
  \item This is a normally-indented item.
\end{itemize}

With list

In the following code snippet, the second parameter to \list is the bullet to use, and the third parameter is a list of layout parameters to change. The \leftmargin parameter adjusts the indentation of the entire list item and all of its rows; \itemindent alters the indentation of subsequent lines.

The advantage of this method is that you have all of the flexibility of lists in non-Beamer LaTeX. The disadvantage is that you have to setup the bullet style (and other visual elements) manually (or identify the right command for the template you're using). Note that if you leave the second argument empty, no bullet will be displayed and you'll save some horizontal space.

\begin{list}{$\square$}{\leftmargin=1em \itemindent=0em}
  \item This item uses the margin and indentation provided above.
\end{list}

Defining a customlist environment

The shortcomings of the list solution can be ameliorated by defining a new customlist environment that basically redefines the itemize environment from Beamer but also incorporates the \leftmargin and \itemindent (etc.) parameters. Put the following in your preamble:

\makeatletter
\newenvironment{customlist}[2]{
  \ifnum\@itemdepth >2\relax\@toodeep\else
      \advance\@itemdepth\@ne%
      \beamer@computepref\@itemdepth%
      \usebeamerfont{itemize/enumerate \beameritemnestingprefix body}%
      \usebeamercolor[fg]{itemize/enumerate \beameritemnestingprefix body}%
      \usebeamertemplate{itemize/enumerate \beameritemnestingprefix body begin}%
      \begin{list}
        {
            \usebeamertemplate{itemize \beameritemnestingprefix item}
        }
        { \leftmargin=#1 \itemindent=#2
            \def\makelabel##1{%
              {%  
                  \hss\llap{{%
                    \usebeamerfont*{itemize \beameritemnestingprefix item}%
                        \usebeamercolor[fg]{itemize \beameritemnestingprefix item}##1}}%
              }%  
            }%  
        }
  \fi
}
{
  \end{list}
  \usebeamertemplate{itemize/enumerate \beameritemnestingprefix body end}%
}
\makeatother

Now, to use an itemized list with custom indentation, you can use the following environment. The first argument is for \leftmargin and the second is for \itemindent. The default values are 2.5em and 0em respectively.

\begin{customlist}{2.5em}{0em}
   \item Any normal item can go here.
\end{customlist}

A custom bullet style can be incorporated into the customlist solution using the standard Beamer mechanism of \setbeamertemplate. (See the answers to this question on the TeX Stack Exchange for more information.)

Alternatively, the bullet style can just be modified directly within the environment, by replacing \usebeamertemplate{itemize \beameritemnestingprefix item} with whatever bullet style you'd like to use (e.g. $\square$).

How do I clear inner HTML

const destroy = container => {
  document.getElementById(container).innerHTML = '';
};

Faster previous

const destroyFast = container => {
  const el = document.getElementById(container);
  while (el.firstChild) el.removeChild(el.firstChild);
};

What is the right way to write my script 'src' url for a local development environment?

This is an old post but...

You can reference the working directory (the folder the .html file is located in) with ./, and the directory above that with ../

Example directory structure:

/html/public/
- index.html
- script2.js
- js/
   - script.js

To load script.js from inside index.html:

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

This goes to the current working directory (location of index.html) and then to the js folder, and then finds the script.

You could also specify ../ to go one directory above the working directory, to load things from there. But that is unusual.

Executing another application from Java

Yes it is possible using ProcessBuilder.

ProcessBuilder example:

import java.io.*;
import java.util.*;

public class CmdProcessBuilder {
  public static void main(String args[]) 
     throws InterruptedException,IOException 
  {
    List<String> command = new ArrayList<String>();
    command.add(args[0]);


    ProcessBuilder builder = new ProcessBuilder(command);
    Map<String, String> environ = builder.environment();

    final Process process = builder.start();
    InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line;
    while ((line = br.readLine()) != null) {
      System.out.println(line);
    }
    System.out.println("Program terminated!");
  }
}

Check these examples:

http://www.rgagnon.com/javadetails/java-0014.html

http://www.java-tips.org/java-se-tips/java.util/from-runtime.exec-to-processbuilder.html

R: Print list to a text file

I solve this problem by mixing the solutions above.

sink("/Users/my/myTest.dat")
writeLines(unlist(lapply(k, paste, collapse=" ")))
sink()

I think it works well

First char to upper case

Or you can do

s = Character.toUpperCase(s.charAt(0)) + s.substring(1); 

Add Class to Object on Page Load

I would recommend using jQuery with this function:

$(document).ready(function(){
 $('#about').addClass('expand');
});

This will add the expand class to an element with id of about when the dom is ready on page load.

Bad Request, Your browser sent a request that this server could not understand

I got Bad Request, Your browser sent a request that this server could not understand when I tried to download a file to the target machine using curl.
I solved it by instead using scp to copy the file from the source machine to the target machine.

How to navigate back to the last cursor position in Visual Studio Code?

I am on Mac OSX, so I can't answer for windows users:

I added a custom keymap entry and set it to Ctrl+? + Ctrl+?, while the original default is Ctrl+- and Ctrl+Shift+- (which translates to Ctrl+ß and Ctrl+Shift+ß on my german keyboard).

One can simply modify it in the user keymap settings:

{ "key": "ctrl+left",  "command": "workbench.action.navigateBack" },
{ "key": "ctrl+right", "command": "workbench.action.navigateForward" }

For the accepted answer I actually wonder :) Alt+? / Alt+? jumps wordwise for me (which is kinda standard in all editors). Did they really do this mapping for the windows version?

CodeIgniter htaccess and URL rewrite issues

if not working

$config['uri_protocol'] = 'AUTO';

change it to

$config['uri_protocol'] = 'PATH_INFO';

if not working change it to

$config['uri_protocol'] = 'QUERY_STRING';

if use this

$config['uri_protocol'] = 'ORIG_PATH_INFO';

with redirect or header location to url not in htaccess will not work you must add the url in htaccess to work

How can I modify a saved Microsoft Access 2007 or 2010 Import Specification?

I am able to use this feature on my machine using MS Access 2007.

  • On the Ribbon, select External Data
  • Select the "Text File" option
  • This displays the Get External Data Wizard
  • Specify the location of the file you wish to import
  • Click OK. This displays the "Import Text Wizard"
  • On the bottom of this dialog screen is the Advanced button you referenced
  • Clicking on this button should display the Import Specification screen and allow you to select and modify an existing import spec.

For what its worth, I'm using Access 2007 SP1

How to find out "The most popular repositories" on Github?

Ranking by stars or forks is not working. Each promoted or created by a famous company repository is popular at the beginning. Also it is possible to have a number of them which are in trend right now (publications, marketing, events). It doesn't mean that those repositories are useful/popular.

The gitmostwanted.com project (repo at github) analyses GH Archive data in order to highlight the most interesting repositories and exclude others. Just compare the results with mentioned resources.

Force update of an Android app when a new version is available

You can notify your users that there is a new version of the current app available to update. Also, if this condition is true, you can block login in the app.

Please see if this provides you the solution.

Best way to store passwords in MYSQL database

Store a unique salt for the user (generated from username + email for example), and store a password. On login, get the salt from database and hash salt + password.
Use bcrypt to hash the passwords.

jQuery - how can I find the element with a certain id?

If you're trying to find an element by id, you don't need to search the table only - it should be unique on the page, and so you should be able to use:

var verificaHorario = $('#' + horaInicial);

If you need to search only in the table for whatever reason, you can use:

var verificaHorario = $("#tbIntervalos").find("td#" + horaInicial)

Classes cannot be accessed from outside package

Do you by any chance have two PUBLICclass classes in your project, where one is public (the one of which you posted the signature here), and another one which is package visible, and you import the wrong one in your code ?

How can I convert String[] to ArrayList<String>

Like this :

String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
List<String> wordList = new ArrayList<String>(Arrays.asList(words));

or

List myList = new ArrayList();
String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
Collections.addAll(myList, words);

How to replace text in a column of a Pandas dataframe?

For anyone else arriving here from Google search on how to do a string replacement on all columns (for example, if one has multiple columns like the OP's 'range' column): Pandas has a built in replace method available on a dataframe object.

df.replace(',', '-', regex=True)

Source: Docs

How can I make content appear beneath a fixed DIV element?

To those suggesting the use of margin-top or padding-top to move the main division below the fixed menu - you don't seem to be testing it completely.

If you set a margin or padding, it will scroll with the page and you will lose lines - go try this page

Looks good, does it not? Highlight a word on the bottom visible line and press page-down - the line with the highlighted word, and a few other lines, will be scrolled under the fixed division.

Margin-top or padding-top WILL position the main division below the fixed division but it all falls flat on its face when you page-down or click the scroll bar to scroll one viewport height of the page.

Same problem if you page-up, lines "fall off" the bottom of the view-port.

Does anyone have an actual fix for THIS problem?

I know how to position things - that's fairly easy if you know the basics about margins, padding, etc. - but how do you prevent the loss of lines when scrolling?

I've looked at a lot of examples of what are claimed to be a properly functioning pages with fixed divisions at the top, but they don't work! They all have problems which scrolling.

I have come across some pages appear to work but if the fixed division is made higher, lines will be lost. I believe I know why they appear to work.

Think in terms of how text on a totally normal (no fancy formatting) page scrolls. Do you see the bottom line when you scroll up or do you see the next line - the bottom one having scrolled off the top of the viewport?

Answer - you see the bottom line scrolled to become the top line.

The fixed menu pages that seem to work really don't. Scroll them and the bottom line is scrolled off the viewport but since the next line is visible, it appears that the fixed division works - but we know better, don't we?

If the fixed division gets higher than the height of one line of text, they fail and lines are lost.

The only pages that I've seen that actually work properly are on sites such as yahoo and I don't have the time, nor inclination, to dig down into what is a lot of CSS, HTML, and JavaScript on the pages to get to the heart of the matter.

So - go to that page and see if you can make changes ("inspect" the elements and make changes to the CSS rules) that fix the scrolling problems.

If you can, come back and share your discovery with world.

My page is a good place to look at what it takes to be able to fix a division at the top, center it (and the main division) and restrict it to a max-width. It may help some of you but I'm sorry I don't have a fix for the scrolling problem

Play with the height of the fix division - make it short enough so that only one line shows and then play with the scrolling. Then make it large enough for two lines and then three and play with the scrolling. You'll see the issues.

Here is a page that is supposed to work but it doesn't - read the very last comment - they describe the problem in a different way but it is the same problem

I just tested the page again in Chrome and it seems to work fairly satisfactorily. With FF the problem exists. Haven't tried IE again, yet.

So - what is different with FF?

Here's a page at cNet which works with chrome and ff - so what are they doing?

More testing with Chrome shows that it fails to fully display the bottom line when scrolled. Just part of the line that was at the bottom is visiable when your scroll - so, still need a fix.

Zip folder in C#

In .NET 4.5 the ZipFile.CreateFromDirectory(startPath, zipPath); method does not cover a scenario where you wish to zip a number of files and sub-folders without having to put them within a folder. This is valid when you wish the unzip to put the files directly within the current folder.

This code worked for me:

public static class FileExtensions
{
    public static IEnumerable<FileSystemInfo> AllFilesAndFolders(this DirectoryInfo dir)
    {
        foreach (var f in dir.GetFiles())
            yield return f;
        foreach (var d in dir.GetDirectories())
        {
            yield return d;
            foreach (var o in AllFilesAndFolders(d))
                yield return o;
        }
    }
}

void Test()
{
    DirectoryInfo from = new DirectoryInfo(@"C:\Test");
    using (FileStream zipToOpen = new FileStream(@"Test.zip", FileMode.Create))
    {
        using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
        {
            foreach (FileInfo file in from.AllFilesAndFolders().Where(o => o is FileInfo).Cast<FileInfo>())
            {
                var relPath = file.FullName.Substring(from.FullName.Length+1);
                ZipArchiveEntry readmeEntry = archive.CreateEntryFromFile(file.FullName, relPath);
            }
        }
    }
}

Folders don't need to be "created" in the zip-archive. The second parameter "entryName" in CreateEntryFromFile should be a relative path, and when unpacking the zip-file the directories of the relative paths will be detected and created.

ORA-01652 Unable to extend temp segment by in tablespace

I found the solution to this. There is a temporary tablespace called TEMP which is used internally by database for operations like distinct, joins,etc. Since my query(which has 4 joins) fetches almost 50 million records the TEMP tablespace does not have that much space to occupy all data. Hence the query fails even though my tablespace has free space.So, after increasing the size of TEMP tablespace the issue was resolved. Hope this helps someone with the same issue. Thanks :)

Center icon in a div - horizontally and vertically

Horizontal centering is as easy as:

text-align: center

Vertical centering when the container is a known height:

height: 100px;
line-height: 100px;
vertical-align: middle

Vertical centering when the container isn't a known height AND you can set the image in the background:

background: url(someimage) no-repeat center center;

bash script read all the files in directory

You can go without the loop:

find /path/to/dir -type f -exec /your/first/command \{\} \; -exec /your/second/command \{\} \; 

HTH

jQuery or Javascript - how to disable window scroll without overflow:hidden;

Without external variables:

       $('.element').bind('mousewheel', function(e, d) {
            if((this.scrollTop === (this.scrollHeight - this.offsetHeight) && d < 0)
                || (this.scrollTop === 0 && d > 0)) {
                e.preventDefault();
            }
        });

Show how many characters remaining in a HTML text box using JavaScript

Try the following code for instance:

working code in jsfiddle.net

For textArea, use this:

<textarea id="txtBox"></textarea>
...
...

For textBox, use this:

<input type="text" id="txtBox"/>
<br>
<input type="text" id="counterBox"/>
<script>
 var txtBoxRef = document.querySelector("#txtBox");
 var counterRef = document.querySelector("#counterBox");
 txtBoxRef.addEventListener("keydown",function(){
  var remLength = 0;
  remLength = 160 - parseInt(txtBoxRef.value.length);
  if(remLength < 0)
   {
    txtBoxRef.value = txtBoxRef.value.substring(0, 160);
    return false;
   }
  counterRef.value = remLength + " characters remaining...";
 },true);
</script>

Hope this Helps!

Why is Git better than Subversion?

"Why Git is Better than X" outlines the various pros and cons of Git vs other SCMs.

Briefly:

  • Git tracks content rather than files
  • Branches are lightweight and merging is easy, and I mean really easy.
  • It's distributed, basically every repository is a branch. It's much easier to develop concurrently and collaboratively than with Subversion, in my opinion. It also makes offline development possible.
  • It doesn't impose any workflow, as seen on the above linked website, there are many workflows possible with Git. A Subversion-style workflow is easily mimicked.
  • Git repositories are much smaller in file size than Subversion repositories. There's only one ".git" directory, as opposed to dozens of ".svn" repositories (note Subversion 1.7 and higher now uses a single directory like Git.)
  • The staging area is awesome, it allows you to see the changes you will commit, commit partial changes and do various other stuff.
  • Stashing is invaluable when you do "chaotic" development, or simply want to fix a bug while you're still working on something else (on a different branch).
  • You can rewrite history, which is great for preparing patch sets and fixing your mistakes (before you publish the commits)
  • … and a lot more.

There are some disadvantages:

  • There aren't many good GUIs for it yet. It's new and Subversion has been around for a lot longer, so this is natural as there are a few interfaces in development. Some good ones include TortoiseGit and GitHub for Mac.
  • Partial checkouts/clones of repositories are not possible at the moment (I read that it's in development). However, there is submodule support. Git 1.7+ supports sparse checkouts.
  • It might be harder to learn, even though I did not find this to be the case (about a year ago). Git has recently improved its interface and is quite user friendly.

In the most simplistic usage, Subversion and Git are pretty much the same. There isn't much difference between:

svn checkout svn://foo.com/bar bar
cd bar
# edit
svn commit -m "foo"

and

git clone [email protected]:foo/bar.git
cd bar
# edit
git commit -a -m "foo"
git push

Where Git really shines is branching and working with other people.

How to run java application by .bat file

Sure, call the java executable.

Mine is C:\Program Files\Java\jre6\bin\java.exe, so to run it I would do

C:\Program Files\Java\jre6\bin\java.exe -jar myjarfile.jar

How can I change the font-size of a select option?

Add a CSS class to the <option> tag to style it: http://jsfiddle.net/Ahreu/

Currently WebKit browsers don't support this behavior, as it's undefined by the spec. Take a look at this: How to style a select tag's option element?

Searching for file in directories recursively

For file and directory search purpose I would want to offer use specialized multithreading .NET library that possess a wide search opportunities and works very fast.

All information about library you can find on GitHub: https://github.com/VladPVS/FastSearchLibrary

If you want to download it you can do it here: https://github.com/VladPVS/FastSearchLibrary/releases

If you have any questions please ask them.

It is one demonstrative example how you can use it:

class Searcher
{
    private static object locker = new object(); 

    private FileSearcher searcher;

    List<FileInfo> files;

    public Searcher()
    {
        files = new List<FileInfo>(); // create list that will contain search result
    }

    public void Startsearch()
    {
        CancellationTokenSource tokenSource = new CancellationTokenSource();
        // create tokenSource to get stop search process possibility

        searcher = new FileSearcher(@"C:\", (f) =>
        {
            return Regex.IsMatch(f.Name, @".*[Dd]ragon.*.jpg$");
        }, tokenSource);  // give tokenSource in constructor


        searcher.FilesFound += (sender, arg) => // subscribe on FilesFound event
        {
            lock (locker) // using a lock is obligatorily
            {
                arg.Files.ForEach((f) =>
                {
                    files.Add(f); // add the next received file to the search results list
                    Console.WriteLine($"File location: {f.FullName}, \nCreation.Time: {f.CreationTime}");
                });

                if (files.Count >= 10) // one can choose any stopping condition
                    searcher.StopSearch();
            }
        };

        searcher.SearchCompleted += (sender, arg) => // subscribe on SearchCompleted event
        {
            if (arg.IsCanceled) // check whether StopSearch() called
                Console.WriteLine("Search stopped.");
            else
                Console.WriteLine("Search completed.");

            Console.WriteLine($"Quantity of files: {files.Count}"); // show amount of finding files
        };

        searcher.StartSearchAsync();
        // start search process as an asynchronous operation that doesn't block the called thread
    }
}

css divide width 100% to 3 column

As it's 2018, use flexbox - no more inline-block whitespace issues:

_x000D_
_x000D_
body {
  margin: 0;
}

#wrapper {
  display: flex;
  height: 200px;
}

#wrapper > div {
  flex-grow: 1;
}

#wrapper > div:first-of-type { background-color: red }
#wrapper > div:nth-of-type(2) { background-color: blue }
#wrapper > div:nth-of-type(3) { background-color: green }
_x000D_
<div id="wrapper">
  <div id="c1"></div>
  <div id="c2"></div>
  <div id="c3"></div>
</div>
_x000D_
_x000D_
_x000D_

Or even CSS grid if you are creating a grid.

_x000D_
_x000D_
body {
  margin: 0;
}

#wrapper {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-auto-rows: minmax(200px, auto);
}

#wrapper>div:first-of-type { background-color: red }
#wrapper>div:nth-of-type(2) { background-color: blue }
#wrapper>div:nth-of-type(3) { background-color: green }
_x000D_
<div id="wrapper">
  <div id="c1"></div>
  <div id="c2"></div>
  <div id="c3"></div>
</div>
_x000D_
_x000D_
_x000D_


Use CSS calc():

_x000D_
_x000D_
body {
  margin: 0;
}

div {
  height: 200px;
  width: 33.33%; /* as @passatgt mentioned in the comment, for the older browsers fallback */
  width: calc(100% / 3);
  display: inline-block;
}

div:first-of-type { background-color: red }
div:nth-of-type(2) { background-color: blue }
div:nth-of-type(3) { background-color: green }
_x000D_
<div></div><div></div><div></div>
_x000D_
_x000D_
_x000D_

JSFiddle


References:

Add rows to CSV File in powershell

Create a new custom object and add it to the object array that Import-Csv creates.

$fileContent = Import-csv $file -header "Date", "Description"
$newRow = New-Object PsObject -Property @{ Date = 'Text4' ; Description = 'Text5' }
$fileContent += $newRow

svn: E155004: ..(path of resource).. is already locked

Still if it doesn't work, just lock all the files and unlock. Now clean up again, It will work.

svn update svn cleanup

How to create a regex for accepting only alphanumeric characters?

Try below Alphanumeric regex

"^[a-zA-Z0-9]*$"

^ - Start of string

[a-zA-Z0-9]* - multiple characters to include

$ - End of string

See more: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

Change size of axes title and labels in ggplot2

To change the size of (almost) all text elements, in one place, and synchronously, rel() is quite efficient:
g+theme(text = element_text(size=rel(3.5))

You might want to tweak the number a bit, to get the optimum result. It sets both the horizontal and vertical axis labels and titles, and other text elements, on the same scale. One exception is faceted grids' titles which must be manually set to the same value, for example if both x and y facets are used in a graph:
theme(text = element_text(size=rel(3.5)), strip.text.x = element_text(size=rel(3.5)), strip.text.y = element_text(size=rel(3.5)))

.NET Global exception handler in console application

No, that's the correct way to do it. This worked exactly as it should, something you can work from perhaps:

using System;

class Program {
    static void Main(string[] args) {
        System.AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
        throw new Exception("Kaboom");
    }

    static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e) {
        Console.WriteLine(e.ExceptionObject.ToString());
        Console.WriteLine("Press Enter to continue");
        Console.ReadLine();
        Environment.Exit(1);
    }
}

Do keep in mind that you cannot catch type and file load exceptions generated by the jitter this way. They happen before your Main() method starts running. Catching those requires delaying the jitter, move the risky code into another method and apply the [MethodImpl(MethodImplOptions.NoInlining)] attribute to it.

Microsoft.ReportViewer.Common Version=12.0.0.0

In My cases, After installing Sql server data tools by Visual Studio 2015 installer, problem has been resolved

Here is the screenshot for installing data tools

How to select count with Laravel's fluent query builder?

$count = DB::table('category_issue')->count();

will give you the number of items.

For more detailed information check Fluent Query Builder section in beautiful Laravel Documentation.

How to create javascript delay function

You do not need to use an anonymous function with setTimeout. You can do something like this:

setTimeout(doSomething, 3000);

function doSomething() {
   //do whatever you want here
}

How to markdown nested list items in Bitbucket?

4 spaces do the trick even inside definition list:

Endpoint
: `/listAgencies`

Method
: `GET`

Arguments
:   * `level` - bla-bla.
    * `withDisabled` - should we include disabled `AGENT`s.
    * `userId` - bla-bla.

I am documenting API using BitBucket Wiki and Markdown proprietary extension for definition list is most pleasing (MD's table syntax is awful, imaging multiline and embedding requirements...).

Querying data by joining two tables in two database on different servers

If the database link option is not available, another route you could take is to link the tables via ODBC to something such as MS Access or Crystal reports and do the join there.

How do I push amended commit to the remote Git repository?

If you have not pushed the code to your remote branch (GitHub/Bitbucket) you can change the commit message on the command line as below.

 git commit --amend -m "Your new message"

If you're working on a specific branch, do this:

git commit --amend -m "BRANCH-NAME: new message"

If you've already pushed the code with a wrong message then you need to be careful when changing the message. i.e after you change the commit message and try pushing it again you end up with having issues. To make it smooth follow the following steps.

Please read the entire answer before doing it

git commit --amend -m "BRANCH-NAME : your new message"

git push -f origin BRANCH-NAME                # Not a best practice. Read below why?

Important note: When you use the force push directly you might end up with code issues that other developers are working on the same branch. So to avoid those conflicts you need to pull the code from your branch before making the force push:

 git commit --amend -m "BRANCH-NAME : your new message"
 git pull origin BRANCH-NAME
 git push -f origin BRANCH-NAME

This is the best practice when changing the commit message, if it was already pushed.

"No backupset selected to be restored" SQL Server 2012

Another potential reason for this glitch appears to be Google Drive. Google Drive is compressing bak files or something, so if you want to transfer a database backup via Google Drive, it appears you must zip it first.

Find Number of CPUs and Cores per CPU using Command Prompt

Based upon your comments - your path statement has been changed/is incorrect or the path variable is being incorrectly used for another purpose.

Java 8 - Best way to transform a list: map or foreach?

One of the main benefits of using streams is that it gives the ability to process data in a declarative way, that is, using a functional style of programming. It also gives multi-threading capability for free meaning there is no need to write any extra multi-threaded code to make your stream concurrent.

Assuming the reason you are exploring this style of programming is that you want to exploit these benefits then your first code sample is potentially not functional since the foreach method is classed as being terminal (meaning that it can produce side-effects).

The second way is preferred from functional programming point of view since the map function can accept stateless lambda functions. More explicitly, the lambda passed to the map function should be

  1. Non-interfering, meaning that the function should not alter the source of the stream if it is non-concurrent (e.g. ArrayList).
  2. Stateless to avoid unexpected results when doing parallel processing (caused by thread scheduling differences).

Another benefit with the second approach is if the stream is parallel and the collector is concurrent and unordered then these characteristics can provide useful hints to the reduction operation to do the collecting concurrently.

Spring MVC - Why not able to use @RequestBody and @RequestParam together

It's too late to answer this question, but it could help for new readers, It seems version issues. I ran all these tests with spring 4.1.4 and found that the order of @RequestBody and @RequestParam doesn't matter.

  1. same as your result
  2. same as your result
  3. gave body= "name=abc", and name = "abc"
  4. Same as 3.
  5. body ="name=abc", name = "xyz,abc"
  6. same as 5.

Unicode (UTF-8) reading and writing to files in Python

In the notation

u'Capit\xe1n\n'

the "\xe1" represents just one byte. "\x" tells you that "e1" is in hexadecimal. When you write

Capit\xc3\xa1n

into your file you have "\xc3" in it. Those are 4 bytes and in your code you read them all. You can see this when you display them:

>>> open('f2').read()
'Capit\\xc3\\xa1n\n'

You can see that the backslash is escaped by a backslash. So you have four bytes in your string: "\", "x", "c" and "3".

Edit:

As others pointed out in their answers you should just enter the characters in the editor and your editor should then handle the conversion to UTF-8 and save it.

If you actually have a string in this format you can use the string_escape codec to decode it into a normal string:

In [15]: print 'Capit\\xc3\\xa1n\n'.decode('string_escape')
Capitán

The result is a string that is encoded in UTF-8 where the accented character is represented by the two bytes that were written \\xc3\\xa1 in the original string. If you want to have a unicode string you have to decode again with UTF-8.

To your edit: you don't have UTF-8 in your file. To actually see how it would look like:

s = u'Capit\xe1n\n'
sutf8 = s.encode('UTF-8')
open('utf-8.out', 'w').write(sutf8)

Compare the content of the file utf-8.out to the content of the file you saved with your editor.

How to change current working directory using a batch file

Just use cd /d %root% to switch driver letters and change directories.

Alternatively, use pushd %root% to switch drive letters when changing directories as well as storing the previous directory on a stack so you can use popd to switch back.

Note that pushd will also allow you to change directories to a network share. It will actually map a network drive for you, then unmap it when you execute the popd for that directory.

What's a good hex editor/viewer for the Mac?

I have recently started using 0xED, and like it a lot.

How to fix "unable to open stdio.h in Turbo C" error?

If you have problems like that, first of all your TC folder put in to the C:..drive. after completing installation open turbo c blue screen. there is a OPTIONS > Directories ..in that you can see for option to set up path..

  1. include directories..you can set path there now.. C:\TC\INCUDE
  2. libraries Directories..you can set path there...C:\TC\LIB
  3. if you want to store your output in BIN then you can set..C:\TC\BIN..otherwise you can set another path where you want to store your output..

Finally you can give OK and finished processes.. It will now work properly

Dictionary text file

http://www.math.sjsu.edu/~foster/dictionary.txt

350,000 words

Very late, but might be useful for others.

Virtual Memory Usage from Java under Linux, too much memory used

No, you can't configure memory amount needed by VM. However, note that this is virtual memory, not resident, so it just stays there without harm if not actually used.

Alernatively, you can try some other JVM then Sun one, with smaller memory footprint, but I can't advise here.

What does the exclamation mark do before the function?

! is a logical NOT operator, it's a boolean operator that will invert something to its opposite.

Although you can bypass the parentheses of the invoked function by using the BANG (!) before the function, it will still invert the return, which might not be what you wanted. As in the case of an IEFE, it would return undefined, which when inverted becomes the boolean true.

Instead, use the closing parenthesis and the BANG (!) if needed.

// I'm going to leave the closing () in all examples as invoking the function with just ! and () takes away from what's happening.

(function(){ return false; }());
=> false

!(function(){ return false; }());
=> true

!!(function(){ return false; }());
=> false

!!!(function(){ return false; }());
=> true

Other Operators that work...

+(function(){ return false; }());
=> 0

-(function(){ return false; }());
=> -0

~(function(){ return false; }());
=> -1

Combined Operators...

+!(function(){ return false; }());
=> 1

-!(function(){ return false; }());
=> -1

!+(function(){ return false; }());
=> true

!-(function(){ return false; }());
=> true

~!(function(){ return false; }());
=> -2

~!!(function(){ return false; }());
=> -1

+~(function(){ return false; }());
+> -1

How to find tags with only certain attributes - BeautifulSoup

Just pass it as an argument of findAll:

>>> from BeautifulSoup import BeautifulSoup
>>> soup = BeautifulSoup("""
... <html>
... <head><title>My Title!</title></head>
... <body><table>
... <tr><td>First!</td>
... <td valign="top">Second!</td></tr>
... </table></body><html>
... """)
>>>
>>> soup.findAll('td')
[<td>First!</td>, <td valign="top">Second!</td>]
>>>
>>> soup.findAll('td', valign='top')
[<td valign="top">Second!</td>]

In a simple to understand explanation, what is Runnable in Java?

Runnable is an interface defined as so:

interface Runnable {
    public void run();
}

To make a class which uses it, just define the class as (public) class MyRunnable implements Runnable {

It can be used without even making a new Thread. It's basically your basic interface with a single method, run, that can be called.

If you make a new Thread with runnable as it's parameter, it will call the run method in a new Thread.

It should also be noted that Threads implement Runnable, and that is called when the new Thread is made (in the new thread). The default implementation just calls whatever Runnable you handed in the constructor, which is why you can just do new Thread(someRunnable) without overriding Thread's run method.

How to update/modify an XML file in python?

To make this process more robust, you could consider using the SAX parser (that way you don't have to hold the whole file in memory), read & write till the end of tree and then start appending.

Getting the names of all files in a directory with PHP

Recursive code to explore all the file contained in a directory ('$path' contains the path of the directory):

function explore_directory($path)
{
    $scans = scandir($path);

    foreach($scans as $scan)
    {
        $new_path = $path.$scan;

        if(is_dir($new_path))
        {
            $new_path = $new_path."/";
            explore_directory($new_path);
        }
        else // A file
        {
            /*
                  Body of code
            */
        }
    }
}

Apache server keeps crashing, "caught SIGTERM, shutting down"

try to disable the rewrite module in ubuntu using sudo a2dismod rewrite. This will perhaps stop your apache server to crash.

How do you test your Request.QueryString[] variables?

I do have functions for each (actually it's one small class, with lots of statics):

  • GetIntegerFromQuerystring(val)
  • GetIntegerFromPost(val)
  • ....

It returns -1 if fails (which is almost always OK for me, I have some other functions for negative numbers as well).

Dim X as Integer = GetIntegerFromQuerystring("id")
If x = -1 Then Exit Sub

Get Value of Radio button group

Your quotes only need to surround the value part of the attribute-equals selector, [attr='val'], like this:

$('a#check_var').click(function() {
  alert($("input:radio[name='r']:checked").val()+ ' '+
        $("input:radio[name='s']:checked").val());
});?

You can see the working version here.

Listview Scroll to the end of the list after updating the list

The transcript mode is what you want and is used by Google Talk and the SMS/MMS application. Are you correctly calling notifyDatasetChanged() on your adapter when you add items?

Loop through a date range with JavaScript

If you want an efficient way with milliseconds:

var daysOfYear = [];
for (var d = begin; d <= end; d = d + 86400000) {
    daysOfYear.push(new Date(d));
}

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

The CORS issue should be fixed in the backend. Temporary workaround uses this option.

  1. Go to C:\Program Files\Google\Chrome\Application

  2. Open command prompt

  3. Execute the command chrome.exe --disable-web-security --user-data-dir="c:/ChromeDevSession"

Using the above option, you can able to open new chrome without security. this chrome will not throw any cors issue.

enter image description here

In where shall I use isset() and !empty()

Neither is a good way to check for valid input.

  • isset() is not sufficient because – as has been noted already – it considers an empty string to be a valid value.
  • ! empty() is not sufficient either because it rejects '0', which could be a valid value.

Using isset() combined with an equality check against an empty string is the bare minimum that you need to verify that an incoming parameter has a value without creating false negatives:

if( isset($_GET['gender']) and ($_GET['gender'] != '') )
{
  ...
}

But by "bare minimum", I mean exactly that. All the above code does is determine whether there is some value for $_GET['gender']. It does not determine whether the value for $_GET['gender'] is valid (e.g., one of ("Male", "Female","FileNotFound")).

For that, see Josh Davis's answer.

How to add an object to an ArrayList in Java

Try this one:

Data objt = new Data(name, address, contact);
Contacts.add(objt);

How do I rename a repository on GitHub?

  1. open this url (https://github.com/) from your browser

  2. Go to repositories at the Right end of the page

  3. Open the link of repository that you want to rename

  4. click Settings (you will find in the Navigation bar)

  5. At the top you will find a box Called (Repository name) where you write the new name

  6. Press Rename

Blue and Purple Default links, how to remove?

REMOVE DEFAULT LINK SOLVED that :visited thing is css.... you just go to your HTML and add a simple

< a href="" style="text-decoration: none" > < /a>

... thats the way html pages used to be

PHP date() with timezone?

U can just add, timezone difference to unix timestamp. Example for Moscow (UTC+3)

echo date('d.m.Y H:i:s', time() + 3 * 60 * 60);

How to import multiple csv files in a single load?

Note that you can use other tricks like :

-- One or more wildcard:
       .../Downloads20*/*.csv
--  braces and brackets   
       .../Downloads201[1-5]/book.csv
       .../Downloads201{11,15,19,99}/book.csv

How can I find which tables reference a given table in Oracle SQL Developer?

To add to the above answer for sql developer plugin, using the below xml will help in getting the column associated with the foreign key.

    <items>
        <item type="editor" node="TableNode" vertical="true">
        <title><![CDATA[FK References]]></title>
        <query>
            <sql>
                <![CDATA[select a.owner,
                                a.constraint_name,
                                a.table_name,
                                b.column_name,
                                a.status
                         from   all_constraints a
                         join   all_cons_columns b ON b.constraint_name = a.constraint_name
                         where  a.constraint_type = 'R'
                                and exists(
                                   select 1
                                   from   all_constraints
                                   where  constraint_name=a.r_constraint_name
                                          and constraint_type in ('P', 'U')
                                          and table_name = :OBJECT_NAME
                                          and owner = :OBJECT_OWNER)
                                   order by table_name, constraint_name]]>
            </sql>
        </query>
        </item>
    </items>

Is Java RegEx case-insensitive?

Yes, case insensitivity can be enabled and disabled at will in Java regex.

It looks like you want something like this:

    System.out.println(
        "Have a meRry MErrY Christmas ho Ho hO"
            .replaceAll("(?i)\\b(\\w+)(\\s+\\1)+\\b", "$1")
    );
    // Have a meRry Christmas ho

Note that the embedded Pattern.CASE_INSENSITIVE flag is (?i) not \?i. Note also that one superfluous \b has been removed from the pattern.

The (?i) is placed at the beginning of the pattern to enable case-insensitivity. In this particular case, it is not overridden later in the pattern, so in effect the whole pattern is case-insensitive.

It is worth noting that in fact you can limit case-insensitivity to only parts of the whole pattern. Thus, the question of where to put it really depends on the specification (although for this particular problem it doesn't matter since \w is case-insensitive.

To demonstrate, here's a similar example of collapsing runs of letters like "AaAaaA" to just "A".

    System.out.println(
        "AaAaaA eeEeeE IiiIi OoooOo uuUuUuu"
            .replaceAll("(?i)\\b([A-Z])\\1+\\b", "$1")
    ); // A e I O u

Now suppose that we specify that the run should only be collapsed only if it starts with an uppercase letter. Then we must put the (?i) in the appropriate place:

    System.out.println(
        "AaAaaA eeEeeE IiiIi OoooOo uuUuUuu"
            .replaceAll("\\b([A-Z])(?i)\\1+\\b", "$1")
    ); // A eeEeeE I O uuUuUuu

More generally, you can enable and disable any flag within the pattern as you wish.

See also

Related questions

How to make a select with array contains value clause in psql

Try

SELECT * FROM table WHERE arr @> ARRAY['s']::varchar[]

CSS - Make divs align horizontally

This seems close to what you want:

_x000D_
_x000D_
#foo {_x000D_
  background: red;_x000D_
  max-height: 100px;_x000D_
  overflow-y: hidden;_x000D_
}_x000D_
_x000D_
.bar {_x000D_
  background: blue;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  float: left;_x000D_
  margin: 1em;_x000D_
}
_x000D_
<div id="foo">_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Cache an HTTP 'Get' service response in AngularJS?

I think there's an even easier way now. This enables basic caching for all $http requests (which $resource inherits):

 var app = angular.module('myApp',[])
      .config(['$httpProvider', function ($httpProvider) {
            // enable http caching
           $httpProvider.defaults.cache = true;
      }])

Why is String immutable in Java?

If HELLO is your String then you can't change HELLO to HILLO. This property is called immutability property.

You can have multiple pointer String variable to point HELLO String.

But if HELLO is char Array then you can change HELLO to HILLO. Eg,

char[] charArr = 'HELLO';
char[1] = 'I'; //you can do this

Answer:

Programming languages have immutable data variables so that it can be used as keys in key, value pair. String variables are used as keys/indices, so they are immutable.

Double vs. BigDecimal?

There are two main differences from double:

  • Arbitrary precision, similarly to BigInteger they can contain number of arbitrary precision and size
  • Base 10 instead of Base 2, a BigDecimal is n*10^scale where n is an arbitrary large signed integer and scale can be thought of as the number of digits to move the decimal point left or right

The reason you should use BigDecimal for monetary calculations is not that it can represent any number, but that it can represent all numbers that can be represented in decimal notion and that include virtually all numbers in the monetary world (you never transfer 1/3 $ to someone).

Force IE9 to emulate IE8. Possible?

On the client side you can add and remove websites to be displayed in Compatibility View from Compatibility View Settings window of IE:

Tools-> Compatibility View Settings

MySQL - How to increase varchar size of an existing column in a database without breaking existing data?

For me this has worked-

ALTER TABLE table_name ALTER COLUMN column_name VARCHAR(50)

Connection string with relative path to the database file

This worked for me:

string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
    + HttpContext.Current.Server.MapPath("\\myPath\\myFile.db")
    + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\"";

I'm querying an XLSX file so don't worry about any of the other stuff in the connection string but the Data Source.

So my answer is:

HttpContext.Current.Server.MapPath("\\myPath\\myFile.db")

How to Replace Multiple Characters in SQL?

Here are the steps

  1. Create a CLR function

See following code:

public partial class UserDefinedFunctions 
{

[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString Replace2(SqlString inputtext, SqlString filter,SqlString      replacewith)
{

    string str = inputtext.ToString();
    try
    {
        string pattern = (string)filter;
        string replacement = (string)replacewith;
        Regex rgx = new Regex(pattern);
        string result = rgx.Replace(str, replacement);
        return (SqlString)result;

    }
    catch (Exception s)
    {
        return (SqlString)s.Message;
    }
}
}
  1. Deploy your CLR function

  2. Now Test it

See following code:

create table dbo.test(dummydata varchar(255))
Go
INSERT INTO dbo.test values('P@ssw1rd'),('This 12is @test')
Go
Update dbo.test
set dummydata=dbo.Replace2(dummydata,'[0-9@]','')

select * from dbo.test
dummydata, Psswrd, This is test booom!!!!!!!!!!!!!

How to change default JRE for all Eclipse workspaces?

I navigated to:

Eclipse>Pref>Java>Installed JRE>Search...

2 of them popped up and I checked the latest one. Before I did this I also went to About>Check for Updates and updated it. I didn't have to reinstall any JRE or JDK either. I might have done it a while back, except it was with 1.6 not 1.4. Hope that helps!

How to resolve Nodejs: Error: ENOENT: no such file or directory

Running

npm run scss
npm run start 

in that order in terminal solved the issue for me.

how can get index & count in vuejs

this might be a dirty code but i think it can suffice

<div v-for="(counter in counters">
{{ counter }}) {{ userlist[counter-1].name }}
</div>

on your script add this one

data(){return {userlist: [],user_id: '',counters: 0,edit: false,}},

mysql after insert trigger which updates another table's column

With your requirements you don't need BEGIN END and IF with unnecessary SELECT in your trigger. So you can simplify it to this

CREATE TRIGGER occupy_trig AFTER INSERT ON occupiedroom 
FOR EACH ROW
  UPDATE BookingRequest
     SET status = 1
   WHERE idRequest = NEW.idRequest;

Format numbers in django templates

Django's contributed humanize application does this:

{% load humanize %}
{{ my_num|intcomma }}

Be sure to add 'django.contrib.humanize' to your INSTALLED_APPS list in the settings.py file.

How do you sort a dictionary by value?

Actually in C#, dictionaries don't have sort() methods. As you are more interested in sort by values, you can't get values until you provide them key. In short, you need to iterate through them using LINQ's OrderBy(),

var items = new Dictionary<string, int>();
items.Add("cat", 0);
items.Add("dog", 20);
items.Add("bear", 100);
items.Add("lion", 50);

// Call OrderBy() method here on each item and provide them the IDs.
foreach (var item in items.OrderBy(k => k.Key))
{
    Console.WriteLine(item);// items are in sorted order
}

You can do one trick:

var sortedDictByOrder = items.OrderBy(v => v.Value);

or:

var sortedKeys = from pair in dictName
            orderby pair.Value ascending
            select pair;

It also depends on what kind of values you are storing: single (like string, int) or multiple (like List, Array, user defined class). If it's single you can make list of it and then apply sort.
If it's user defined class, then that class must implement IComparable, ClassName: IComparable<ClassName> and override compareTo(ClassName c) as they are more faster and more object oriented than LINQ.

How to get index of an item in java.util.Set

you can extend LinkedHashSet adding your desired getIndex() method. It's 15 minutes to implement and test it. Just go through the set using iterator and counter, check the object for equality. If found, return the counter.

Why do I get "Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'." when I try to use sp_executesql?

The solution is to put an N in front of both the type and the SQL string to indicate it is a double-byte character string:

DECLARE @SQL NVARCHAR(100) 
SET @SQL = N'SELECT TOP 1 * FROM sys.tables' 
EXECUTE sp_executesql @SQL

HTML: How to limit file upload to be only images?

Edited

If things were as they SHOULD be, you could do this via the "Accept" attribute.

http://www.webmasterworld.com/forum21/6310.htm

However, browsers pretty much ignore this, so this is irrelavant. The short answer is, i don't think there is a way to do it in HTML. You'd have to check it server-side instead.

The following older post has some information that could help you with alternatives.

File input 'accept' attribute - is it useful?

What's faster, SELECT DISTINCT or GROUP BY in MySQL?

All of the answers above are correct, for the case of DISTINCT on a single column vs GROUP BY on a single column. Every db engine has its own implementation and optimizations, and if you care about the very little difference (in most cases) then you have to test against specific server AND specific version! As implementations may change...

BUT, if you select more than one column in the query, then the DISTINCT is essentially different! Because in this case it will compare ALL columns of all rows, instead of just one column.

So if you have something like:

// This will NOT return unique by [id], but unique by (id,name)
SELECT DISTINCT id, name FROM some_query_with_joins

// This will select unique by [id].
SELECT id, name FROM some_query_with_joins GROUP BY id

It is a common mistake to think that DISTINCT keyword distinguishes rows by the first column you specified, but the DISTINCT is a general keyword in this manner.

So people you have to be careful not to take the answers above as correct for all cases... You might get confused and get the wrong results while all you wanted was to optimize!

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object?

In order to handle arrays with the $resource service, it's suggested that you use the query method. As you can see below, the query method is built to handle arrays.

    { 'get':    {method:'GET'},
      'save':   {method:'POST'},
      'query':  {method:'GET', isArray:true},
      'remove': {method:'DELETE'},
      'delete': {method:'DELETE'} 
   };

User $resource("apiUrl").query();

Remove sensitive files and their commits from Git history

So, It looks something like this:

git rm --cached /config/deploy.rb
echo /config/deploy.rb >> .gitignore

Remove cache for tracked file from git and add that file to .gitignore list

Case insensitive std::string.find()

Since you're doing substring searches (std::string) and not element (character) searches, there's unfortunately no existing solution I'm aware of that's immediately accessible in the standard library to do this.

Nevertheless, it's easy enough to do: simply convert both strings to upper case (or both to lower case - I chose upper in this example).

std::string upper_string(const std::string& str)
{
    string upper;
    transform(str.begin(), str.end(), std::back_inserter(upper), toupper);
    return upper;
}

std::string::size_type find_str_ci(const std::string& str, const std::string& substr)
{
    return upper(str).find(upper(substr) );
}

This is not a fast solution (bordering into pessimization territory) but it's the only one I know of off-hand. It's also not that hard to implement your own case-insensitive substring finder if you are worried about efficiency.

Additionally, I need to support std::wstring/wchar_t. Any ideas?

tolower/toupper in locale will work on wide-strings as well, so the solution above should be just as applicable (simple change std::string to std::wstring).

[Edit] An alternative, as pointed out, is to adapt your own case-insensitive string type from basic_string by specifying your own character traits. This works if you can accept all string searches, comparisons, etc. to be case-insensitive for a given string type.

CSS disable hover effect

Add the following to add hover effect on disabled button:

.buttonDisabled:hover
  {
    /*your code goes here*/     
  }

How to load all the images from one of my folder into my web page, using Jquery/Javascript

Here is one way to do it. Involves doing a little PHP as well.

The PHP part:

$filenameArray = [];

$handle = opendir(dirname(realpath(__FILE__)).'/images/');
        while($file = readdir($handle)){
            if($file !== '.' && $file !== '..'){
                array_push($filenameArray, "images/$file");
            }
        }

echo json_encode($filenameArray);

The jQuery part:

$.ajax({
            url: "getImages.php",
            dataType: "json",
            success: function (data) {

                $.each(data, function(i,filename) {
                    $('#imageDiv').prepend('<img src="'+ filename +'"><br>');
                });
            }
        });

So basically you do a PHP file to return you the list of image filenames as JSON, grab that JSON using an ajax call, and prepend/append them to the html. You would probably want to filter the files u grab from the folder.

Had some help on the php part from 1

Is it possible to auto-format your code in Dreamweaver?

Coding toolbar (Edit > Toolbars > Coding) and select Code Format Settings to set your preferred formatting.

You can also access the formatting option from Commands > Apply Source Formatting or only apply it to a select block of code by selecting the Apply Source Formatting to Selection option.

http://www.hongkiat.com/blog/10-useful-dreamweaver-tips-for-beginners/

How to pass 2D array (matrix) in a function in C?

2D array:

int sum(int array[][COLS], int rows)
{

}

3D array:

int sum(int array[][B][C], int A)
{

}

4D array:

int sum(int array[][B][C][D], int A)
{

}

and nD array:

int sum(int ar[][B][C][D][E][F].....[N], int A)
{

}

Add a reference column migration in Rails 4

Another syntax of doing the same thing is:

rails g migration AddUserToUpload user:belongs_to

DateTime fields from SQL Server display incorrectly in Excel

Here's a simple macro that can be run after pasting data from SSMS. It's easiest if you copy it to your PERSONAL.XLSB file and add a button to the Quick Access Toolbar or a new custom group/tab in the ribbon. Run the macro immediately after pasting while the data is still selected. It can also be run if a single cell is selected within the data - it will automatically select the current area before running (same as ctrl-a). To run the macro on only a subset of data, select the desired subset before running. It can handle the data including or excluding headers, but assumes there at at least 2 rows in the current area.

It efficiently tests each column to see if the first non-NULL value looks to be a date/time value in the strange format. If it is, it sets the entire column to the default system date/time format, even if your date format is 'd/m/y'.

Sub FixSSMSDateFormats()

'Intended for copied data from SSMS and handles headers included
'For selection or current area, checks each column...
'   If the first non-NULL value is in strange time format, then change entire column to system date/time format

Dim values As Variant, r As Long, c As Long

If Selection.Count = 1 Then Selection.CurrentRegion.Select

values = Selection.Value

For c = 1 To UBound(values, 2)

    For r = 2 To UBound(values, 1)
    
        If TypeName(values(r, c)) = "Double" Then
            If values(r, c) > 1 And Selection(r, c).NumberFormat = "mm:ss.0" Then
                Selection.Columns(c).NumberFormat = "m/d/yyyy h:mm"
            End If
            Exit For
        ElseIf values(r, c) <> "NULL" Then
            Exit For
        End If
    
    Next

Next

End Sub

Is it possible to change the speed of HTML's <marquee> tag?

You can Change the speed by adding scrolldelay

_x000D_
_x000D_
<marquee style="font-family: lato; color: #FFFFFF" bgcolor="#00224f" scrolldelay="400">Now the Speed is Delay to 400 Milliseconds</marquee>
_x000D_
_x000D_
_x000D_

resource error in android studio after update: No Resource Found

in your projects build.gradle file... write as below.. i have solved that error by change the appcompat version from v7.23.0.0 to v7.22.2.1..

dependencies

{

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

}

Below screen shot is for better understanding.

How to set timer in android?

ok since this isn't cleared up yet there are 3 simple ways to handle this. Below is an example showing all 3 and at the bottom is an example showing just the method I believe is preferable. Also remember to clean up your tasks in onPause, saving state if necessary.


import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Handler.Callback;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class main extends Activity {
    TextView text, text2, text3;
    long starttime = 0;
    //this  posts a message to the main thread from our timertask
    //and updates the textfield
   final Handler h = new Handler(new Callback() {

        @Override
        public boolean handleMessage(Message msg) {
           long millis = System.currentTimeMillis() - starttime;
           int seconds = (int) (millis / 1000);
           int minutes = seconds / 60;
           seconds     = seconds % 60;

           text.setText(String.format("%d:%02d", minutes, seconds));
            return false;
        }
    });
   //runs without timer be reposting self
   Handler h2 = new Handler();
   Runnable run = new Runnable() {

        @Override
        public void run() {
           long millis = System.currentTimeMillis() - starttime;
           int seconds = (int) (millis / 1000);
           int minutes = seconds / 60;
           seconds     = seconds % 60;

           text3.setText(String.format("%d:%02d", minutes, seconds));

           h2.postDelayed(this, 500);
        }
    };

   //tells handler to send a message
   class firstTask extends TimerTask {

        @Override
        public void run() {
            h.sendEmptyMessage(0);
        }
   };

   //tells activity to run on ui thread
   class secondTask extends TimerTask {

        @Override
        public void run() {
            main.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                   long millis = System.currentTimeMillis() - starttime;
                   int seconds = (int) (millis / 1000);
                   int minutes = seconds / 60;
                   seconds     = seconds % 60;

                   text2.setText(String.format("%d:%02d", minutes, seconds));
                }
            });
        }
   };


   Timer timer = new Timer();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        text = (TextView)findViewById(R.id.text);
        text2 = (TextView)findViewById(R.id.text2);
        text3 = (TextView)findViewById(R.id.text3);

        Button b = (Button)findViewById(R.id.button);
        b.setText("start");
        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Button b = (Button)v;
                if(b.getText().equals("stop")){
                    timer.cancel();
                    timer.purge();
                    h2.removeCallbacks(run);
                    b.setText("start");
                }else{
                    starttime = System.currentTimeMillis();
                    timer = new Timer();
                    timer.schedule(new firstTask(), 0,500);
                    timer.schedule(new secondTask(),  0,500);
                    h2.postDelayed(run, 0);
                    b.setText("stop");
                }
            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
        timer.cancel();
        timer.purge();
        h2.removeCallbacks(run);
        Button b = (Button)findViewById(R.id.button);
        b.setText("start");
    }
}


the main thing to remember is that the UI can only be modified from the main ui thread so use a handler or activity.runOnUIThread(Runnable r);

Here is what I consider to be the preferred method.


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class TestActivity extends Activity {

    TextView timerTextView;
    long startTime = 0;

    //runs without a timer by reposting this handler at the end of the runnable
    Handler timerHandler = new Handler();
    Runnable timerRunnable = new Runnable() {

        @Override
        public void run() {
            long millis = System.currentTimeMillis() - startTime;
            int seconds = (int) (millis / 1000);
            int minutes = seconds / 60;
            seconds = seconds % 60;

            timerTextView.setText(String.format("%d:%02d", minutes, seconds));

            timerHandler.postDelayed(this, 500);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_activity);

        timerTextView = (TextView) findViewById(R.id.timerTextView);

        Button b = (Button) findViewById(R.id.button);
        b.setText("start");
        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Button b = (Button) v;
                if (b.getText().equals("stop")) {
                    timerHandler.removeCallbacks(timerRunnable);
                    b.setText("start");
                } else {
                    startTime = System.currentTimeMillis();
                    timerHandler.postDelayed(timerRunnable, 0);
                    b.setText("stop");
                }
            }
        });
    }

  @Override
    public void onPause() {
        super.onPause();
        timerHandler.removeCallbacks(timerRunnable);
        Button b = (Button)findViewById(R.id.button);
        b.setText("start");
    }

}


asp.net: Invalid postback or callback argument

This is probably not the cause of your issue, but I noticed you were using optgroups in your dropdown so I figured this might help someone should they wind up here with this issue. For me, I needed to create a dropdownlist that would render with optgroups, and I ended up using the accepted answer here but while it would render the control correctly, it gave me this error. How I got past that is detailed in my answer here.

WAITING at sun.misc.Unsafe.park(Native Method)

I had a similar issue, and following previous answers (thanks!), I was able to search and find how to handle correctly the ThreadPoolExecutor terminaison.

In my case, that just fix my progressive increase of similar blocked threads:

  • I've used ExecutorService::awaitTermination(x, TimeUnit) and ExecutorService::shutdownNow() (if necessary) in my finally clause.
  • For information, I've used the following commands to detect thread count & list locked threads:

    ps -u javaAppuser -L|wc -l

    jcmd `ps -C java -o pid=` Thread.print >> threadPrintDayA.log

    jcmd `ps -C java -o pid=` Thread.print >> threadPrintDayAPlusOne.log

    cat threadPrint*.log |grep "pool-"|wc -l

Calculating Pearson correlation and significance in Python

def pearson(x,y):
  n=len(x)
  vals=range(n)

  sumx=sum([float(x[i]) for i in vals])
  sumy=sum([float(y[i]) for i in vals])

  sumxSq=sum([x[i]**2.0 for i in vals])
  sumySq=sum([y[i]**2.0 for i in vals])

  pSum=sum([x[i]*y[i] for i in vals])
  # Calculating Pearson correlation
  num=pSum-(sumx*sumy/n)
  den=((sumxSq-pow(sumx,2)/n)*(sumySq-pow(sumy,2)/n))**.5
  if den==0: return 0
  r=num/den
  return r

javac error: Class names are only accepted if annotation processing is explicitly requested

i think this is also because of incorrect compilation..

so for linux (ubuntu).....

javac file.java

java file

Convert any object to a byte[]

What you're looking for is serialization. There are several forms of serialization available for the .Net platform

Difference between $.ajax() and $.get() and $.load()

Very basic but

  • $.load(): Load a piece of html into a container DOM.
  • $.get(): Use this if you want to make a GET call and play extensively with the response.
  • $.post(): Use this if you want to make a POST call and don’t want to load the response to some container DOM.
  • $.ajax(): Use this if you need to do something when XHR fails, or you need to specify ajax options (e.g. cache: true) on the fly.

Redirect on select option in select box

For someone who doesn't want to use inline JS.

<select data-select-name>
    <option value="">Select...</option>
    <option value="http://google.com">Google</option>
    <option value="http://yahoo.com">Yahoo</option>
</select>
<script type="text/javascript">
    document.addEventListener('DOMContentLoaded',function() {
        document.querySelector('select[data-select-name]').onchange=changeEventHandler;
    },false);

    function changeEventHandler(event) {
        window.location.href = this.options[this.selectedIndex].value;
    }
</script>

How to Verify if file exist with VB script

There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :

Option Explicit
DIM fso    
Set fso = CreateObject("Scripting.FileSystemObject")

If (fso.FileExists("C:\Program Files\conf")) Then
  WScript.Echo("File exists!")
  WScript.Quit()
Else
  WScript.Echo("File does not exist!")
End If

WScript.Quit()

How to open existing project in Eclipse

Right click in navigator-Import-existing project..-select the base directory of your project

Add day(s) to a Date object

date.setTime( date.getTime() + days * 86400000 );

Where will log4net create this log file?

I think your sample is saving to your project folders and unless the default iis, or .NET , user has create permission then it won't be able to create the logs folder.

I'd create the logs folder first and allow the iis user full permission and see if the log file is being created.

How to use ArgumentCaptor for stubbing?

Hypothetically, if search landed you on this question then you probably want this:

doReturn(someReturn).when(someObject).doSomething(argThat(argument -> argument.getName().equals("Bob")));

Why? Because like me you value time and you are not going to implement .equals just for the sake of the single test scenario.

And 99 % of tests fall apart with null returned from Mock and in a reasonable design you would avoid return null at all costs, use Optional or move to Kotlin. This implies that verify does not need to be used that often and ArgumentCaptors are just too tedious to write.

RuntimeWarning: DateTimeField received a naive datetime

In the model, do not pass the value:

timezone.now()

Rather, remove the parenthesis, and pass:

timezone.now

If you continue to get a runtime error warning, consider changing the model field from DateTimeField to DateField.

Pass arguments into C program from command line

Take a look at the getopt library; it's pretty much the gold standard for this sort of thing.

Use of for_each on map elements

It's unfortunate that you don't have Boost however if your STL implementation has the extensions then you can compose mem_fun_ref and select2nd to create a single functor suitable for use with for_each. The code would look something like this:

#include <algorithm>
#include <map>
#include <ext/functional>   // GNU-specific extension for functor classes missing from standard STL

using namespace __gnu_cxx;  // for compose1 and select2nd

class MyClass
{
public:
    void Method() const;
};

std::map<int, MyClass> Map;

int main(void)
{
    std::for_each(Map.begin(), Map.end(), compose1(std::mem_fun_ref(&MyClass::Method), select2nd<std::map<int, MyClass>::value_type>()));
}

Note that if you don't have access to compose1 (or the unary_compose template) and select2nd, they are fairly easy to write.

unknown type name 'uint8_t', MinGW

EDIT:

To Be Clear: If the order of your #includes matters and it is not part of your design pattern (read: you don't know why), then you need to rethink your design. Most likely, this just means you need to add the #include to the header file causing problems.

At this point, I have little interest in discussing/defending the merits of the example but will leave it up as it illustrates some nuances in the compilation process and why they result in errors.

END EDIT

You need to #include the stdint.h BEFORE you #include any other library interfaces that need it.

Example:

My LCD library uses uint8_t types. I wrote my library with an interface (Display.h) and an implementation (Display.c)

In display.c, I have the following includes.

#include <stdint.h>
#include <string.h>
#include <avr/io.h>
#include <Display.h>
#include <GlobalTime.h>

And this works.

However, if I re-arrange them like so:

#include <string.h>
#include <avr/io.h>
#include <Display.h>
#include <GlobalTime.h>
#include <stdint.h>

I get the error you describe. This is because Display.h needs things from stdint.h but can't access it because that information is compiled AFTER Display.h is compiled.

So move stdint.h above any library that need it and you shouldn't get the error anymore.

On postback, how can I check which control cause postback in Page_Init event

If you need to check which control caused the postback, then you could just directly compare ["__EVENTTARGET"] to the control you are interested in:

if (specialControl.UniqueID == Page.Request.Params["__EVENTTARGET"])
{
    /*do special stuff*/
}

This assumes you're just going to be comparing the result from any GetPostBackControl(...) extension method anyway. It may not handle EVERY situation, but if it works it is simpler. Plus, you won't scour the page looking for a control you didn't care about to begin with.

Create new user in MySQL and give it full access to one database

To me this worked.

CREATE USER 'spowner'@'localhost' IDENTIFIED BY '1234'; 
GRANT ALL PRIVILEGES ON test.* To 'spowner'@'localhost'; 
FLUSH PRIVILEGES;

where

  • spowner : user name
  • 1234 : password of spowner
  • test : database 'spowner' has access right to

MySQL Error 1093 - Can't specify target table for update in FROM clause

Try to save result of Select statement in separate variable and then use that for delete query.

How to simulate POST request?

It would be helpful if you provided more information - e.g. what OS your using, what you want to accomplish, etc. But, generally speaking cURL is a very powerful command-line tool I frequently use (in linux) for imitating HTML requests:

For example:

curl --data "post1=value1&post2=value2&etc=valetc" http://host/resource

OR, for a RESTful API:

curl -X POST -d @file http://host/resource

You can check out more information here-> http://curl.haxx.se/


EDITs:

OK. So basically you're looking to stress test your REST server? Then cURL really isn't helpful unless you want to write your own load-testing program, even then sockets would be the way to go. I would suggest you check out Gatling. The Gatling documentation explains how to set up the tool, and from there your can run all kinds of GET, POST, PUT and DELETE requests.

Unfortunately, short of writing your own program - i.e. spawning a whole bunch of threads and inundating your REST server with different types of requests - you really have to rely on a stress/load-testing toolkit. Just using a REST client to send requests isn't going to put much stress on your server.


More EDITs

So in order to simulate a post request on a socket, you basically have to build the initial socket connection with the server. I am not a C# guy, so I can't tell you exactly how to do that; I'm sure there are 1001 C# socket tutorials on the web. With most RESTful APIs you usually need to provide a URI to tell the server what to do. For example, let's say your API manages a library, and you are using a POST request to tell the server to update information about a book with an id of '34'. Your URI might be

http://localhost/library/book/34

Therefore, you should open a connection to localhost on port 80 (or 8080, or whatever port your server is on), and pass along an HTML request header. Going with the library example above, your request header might look as follows:

POST library/book/34 HTTP/1.0\r\n
X-Requested-With: XMLHttpRequest\r\n
Content-Type: text/html\r\n
Referer: localhost\r\n
Content-length: 36\r\n\r\n
title=Learning+REST&author=Some+Name

From here, the server should shoot back a response header, followed by whatever the API is programed to tell the client - usually something to say the POST succeeded or failed. To stress test your API, you should essentially do this over and over again by creating a threaded process.

Also, if you are posting JSON data, you will have to alter your header and content accordingly. Frankly, if you are looking to do this quick and clean, I would suggest using python (or perl) which has several libraries for creating POST, PUT, GET and DELETE request, as well as POSTing and PUTing JSON data. Otherwise, you might end up doing more programming than stress testing. Hope this helps!

MySQL Daemon Failed to Start - centos 6

I just had this error. I could not connect remotely to my mysql server. I tried restarting mysql server with service mysqld restart (I used root). It stopped but did not start again. Turns out my memory was full. Cleared out a few GBs and it is working fine.

Chrome refuses to execute an AJAX script due to wrong MIME type

In my case, I use

$.getJSON(url, function(json) { ... });

to make the request (to Flickr's API), and I got the same MIME error. Like the answer above suggested, adding the following code:

$.ajaxSetup({ dataType: "jsonp" });

Fixed the issue and I no longer see the MIME type error in Chrome's console.