Programs & Examples On #Qwebview

The QWebView class is the main widget component of the Qt WebKit web browsing module. It can be used in various applications to display web content live from the Internet.

How to change a string into uppercase

>>> s = 'sdsd'
>>> s.upper()
'SDSD'

See String Methods.

How to send push notification to web browser?

May I redefine you question as below

Can we have our own back-end to send push notification to Chrome, Firefox, Opera & Safari?

Yes. By today (2017/05), you can use same client and server side implementation to handle Chrome, Firefox and Opera (no Safari). Because they have implemented web push notifications in a same way. That is Push API protocol by W3C. But Safari have their own old architecture. So we have to maintain Safari separately.

Refer browser-push repo for guide lines to implement web push notification for your web-app with your own back-end. It explains with examples how you can add web push notification support for your web application without any third party services.

Compile error: package javax.servlet does not exist

Even after trying suggested solution, it was not solving my problem because there where many instance of java path were entered by me.

  1. I removed all java related path (different version java) from "Path, JAVA_HOME, JRE_HOME" and created from fresh.

  2. i have set (path may changes as per different installation)
    a. JAVA_HOME as C:\Program Files\Java\jdk1.8.0_191
    b. JRE_HOME as C:\Program Files\Java\jdk1.8.0_191\jre\lib
    c. add binary file path in path: C:\Program Files\Java\jdk1.8.0_191\bin
    d. CLASSPATH as C:\apache-tomcat-7.0.93\lib

  3. never try in the same command prompt if its already open while doing changes/creting system/user variables. close it and open new one.

Reference Image: enter image description here

Converting a number with comma as decimal point to float

Might look excessive but will convert any given format no mater the locale:

function normalizeDecimal($val, int $precision = 4): string
{
    $input = str_replace(' ', '', $val);
    $number = str_replace(',', '.', $input);
    if (strpos($number, '.')) {
        $groups = explode('.', str_replace(',', '.', $number));
        $lastGroup = array_pop($groups);
        $number = implode('', $groups) . '.' . $lastGroup;
    }
    return bcadd($number, 0, $precision);
}

Output:

.12           -> 0.1200
123           -> 123.0000
123.91        -> 12345678.9100
123 456 78.91 -> 12345678.9100
123,456,78.91 -> 12345678.9100
123.456.78,91 -> 12345678.9100
123 456 78,91 -> 12345678.9100

How to debug Spring Boot application with Eclipse?

There's section 19.2 in Spring Boot Reference that tells you about starting your application with remote debugging support enabled.

$ java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n \
   -jar target/myproject-0.0.1-SNAPSHOT.jar

After you start your application just add that Remote Java Application configuration in Run/Debug configurations, select the port/address you defined when starting your app, and then you are free to debug.

How to create a byte array in C++?

Byte is not a standard type in C or C++. Try char, which is usually and at least 8 bits long.

How to replace special characters in a string?

That depends on what you mean. If you just want to get rid of them, do this:
(Update: Apparently you want to keep digits as well, use the second lines in that case)

String alphaOnly = input.replaceAll("[^a-zA-Z]+","");
String alphaAndDigits = input.replaceAll("[^a-zA-Z0-9]+","");

or the equivalent:

String alphaOnly = input.replaceAll("[^\\p{Alpha}]+","");
String alphaAndDigits = input.replaceAll("[^\\p{Alpha}\\p{Digit}]+","");

(All of these can be significantly improved by precompiling the regex pattern and storing it in a constant)

Or, with Guava:

private static final CharMatcher ALNUM =
  CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z'))
  .or(CharMatcher.inRange('0', '9')).precomputed();
// ...
String alphaAndDigits = ALNUM.retainFrom(input);

But if you want to turn accented characters into something sensible that's still ascii, look at these questions:

True/False vs 0/1 in MySQL

Some "front ends", with the "Use Booleans" option enabled, will treat all TINYINT(1) columns as Boolean, and vice versa.

This allows you to, in the application, use TRUE and FALSE rather than 1 and 0.

This doesn't affect the database at all, since it's implemented in the application.

There is not really a BOOLEAN type in MySQL. BOOLEAN is just a synonym for TINYINT(1), and TRUE and FALSE are synonyms for 1 and 0.

If the conversion is done in the compiler, there will be no difference in performance in the application. Otherwise, the difference still won't be noticeable.

You should use whichever method allows you to code more efficiently, though not using the feature may reduce dependency on that particular "front end" vendor.

How to dock "Tool Options" to "Toolbox"?

In the detached window (Tool Options), the name of the view (Paintbrush) is a grab-bar.

Put your cursor over the grab-bar, click and drag it to the dock area in the main window in order to reattach it to the main window.

Display a RecyclerView in Fragment

This was asked some time ago now, but based on the answer that @nacho_zona3 provided, and previous experience with fragments, the issue is that the views have not been created by the time you are trying to find them with the findViewById() method in onCreate() to fix this, move the following code:

// 1. get a reference to recyclerView
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.list);

// 2. set layoutManger
recyclerView.setLayoutManager(new LinearLayoutManager(this));

// this is data fro recycler view
ItemData itemsData[] = { new ItemData("Indigo",R.drawable.circle),
        new ItemData("Red",R.drawable.color_ic_launcher),
        new ItemData("Blue",R.drawable.indigo),
        new ItemData("Green",R.drawable.circle),
        new ItemData("Amber",R.drawable.color_ic_launcher),
        new ItemData("Deep Orange",R.drawable.indigo)};


// 3. create an adapter
MyAdapter mAdapter = new MyAdapter(itemsData);
// 4. set adapter
recyclerView.setAdapter(mAdapter);
// 5. set item animator to DefaultAnimator
recyclerView.setItemAnimator(new DefaultItemAnimator()); 

to your fragment's onCreateView() call. A small amount of refactoring is required because all variables and methods called from this method have to be static. The final code should look like:

 public class ColorsFragment extends Fragment {

     public ColorsFragment() {}

     @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container,
         Bundle savedInstanceState) {

         View rootView = inflater.inflate(R.layout.fragment_colors, container, false);
         // 1. get a reference to recyclerView
         RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.list);

         // 2. set layoutManger
         recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

         // this is data fro recycler view
         ItemData itemsData[] = {
             new ItemData("Indigo", R.drawable.circle),
                 new ItemData("Red", R.drawable.color_ic_launcher),
                 new ItemData("Blue", R.drawable.indigo),
                 new ItemData("Green", R.drawable.circle),
                 new ItemData("Amber", R.drawable.color_ic_launcher),
                 new ItemData("Deep Orange", R.drawable.indigo)
         };


         // 3. create an adapter
         MyAdapter mAdapter = new MyAdapter(itemsData);
         // 4. set adapter
         recyclerView.setAdapter(mAdapter);
         // 5. set item animator to DefaultAnimator
         recyclerView.setItemAnimator(new DefaultItemAnimator());

         return rootView;
     }
 }

So the main thing here is that anywhere you call findViewById() you will need to use rootView.findViewById()

Notepad++ change text color?

You can use the "User-Defined Language" option available at the notepad++. You do not need to do the xml-based hacks, where the formatting would be available only in the searched window, with the formatting rules.

Sample for your reference here.

How to add/subtract dates with JavaScript?

All these functions for adding date are wrong. You are passing the wrong month to the Date function. More information about the problem : http://www.domdigger.com/blog/?p=9

Counting number of occurrences in column?

=arrayformula(if(isblank(B2:B),iferror(1/0),mmult(sign(B2:B=TRANSPOSE(A2:A)),A2:A)))

I got this from a good tutorial - can't remember the title - probably about using MMult

Hosting ASP.NET in IIS7 gives Access is denied?

OS : Windows 7 & IIS 7

If you still have permission denied after adding IUSR & NETWORK SERVICE. Add also IIS_WPG. The addition of this last user solved my problem.

For people who can't find those users: when you're trying to add a user in security of the folder (properties of the folder), click on "Advanced" of the window "Select Users or Groups". Change the location to the computer name then click on "Find Now". You'll find those users in the list below.

VBA (Excel) Initialize Entire Array without Looping

I want to initialize every single element of the array to some initial value. So if I have an array Dim myArray(300) As Integer of 300 integers, for example, all 300 elements would hold the same initial value (say, the number 13).

Can anyone explain how to do this, without looping? I'd like to do it in one statement if possible.

What do I win?

Sub SuperTest()
   Dim myArray
   myArray = Application.Transpose([index(Row(1:300),)-index(Row(1:300),)+13])
End Sub

How to run a script as root on Mac OS X?

In order for sudo to work the way everyone suggest, you need to be in the admin group.

Select All checkboxes using jQuery

Here is a simple way to do this :

Html :

<input type="checkbox" id="selectall" class="css-checkbox " name="selectall"/>Selectall<br>
<input type="checkbox" class="checkboxall" value="checkbox1"/>checkbox1<br>
<input type="checkbox" class="checkboxall" value="checkbox2"/>checkbox2<br>
<input type="checkbox" class="checkboxall" value="checkbox3"/>checkbox3<br>

jquery :

$(document).ready(function(){
$("#selectall").click(function(){
        if(this.checked){
            $('.checkboxall').each(function(){
                $(".checkboxall").prop('checked', true);
            })
        }else{
            $('.checkboxall').each(function(){
                $(".checkboxall").prop('checked', false);
            })
        }
    });
});

Using %s in C correctly - very basic level

%s is the representation of an array of char

char string[10] // here is a array of chars, they max length is 10;
char character; // just a char 1 letter/from the ascii map

character = 'a'; // assign 'a' to character
printf("character %c  ",a); //we will display 'a' to stout

so string is an array of char we can assign multiple character per space of memory

string[0]='h';
string[1]='e';
string[2]='l';
string[3]='l';
string[4]='o';
string[5]=(char) 0;//asigning the last element of the 'word' a mark so the string ends

this assignation can be done at initialization like char word="this is a word" // the word array of chars got this string now and is statically defined

toy can also assign values to the array of chars assigning it with functions like strcpy;

strcpy(string,"hello" );

this do the same as the example and automatically add the (char) 0 at the end

so if you print it with %S printf("my string %s",string);

and how string is a array we can just display part of it

//                         the array    one char
printf("first letter of wrd %s     is    :%c ",string,string[1]  );

Restore a postgres backup file using the command line?

I didnt see here mentions about dump file extension (*.dump).

This solution worked for me:

I got a dump file and needed to recover it.

First I tried to do this with pg_restore and got:

pg_restore: error: input file appears to be a text format dump. Please use psql.

I did it with psql and worked well:

psql -U myUser-d myDataBase < path_to_the_file/file.dump

How to round up integer division and have int result in Java?

this might be helpfull,, Subtract the remainder to the legnth and make it a divisible number and then divide it with 153

int r=message.length()%153;       //Calculate the remainder by %153
return (message.length()-r)/153;  // find the pages by adding the remainder and 
                                  //then divide by 153 

How to write to a JSON file in the correct format

Require the JSON library, and use to_json.

require 'json'
tempHash = {
    "key_a" => "val_a",
    "key_b" => "val_b"
}
File.open("public/temp.json","w") do |f|
  f.write(tempHash.to_json)
end

Your temp.json file now looks like:

{"key_a":"val_a","key_b":"val_b"}

Using Java 8 to convert a list of objects into a string obtained from the toString() method

StringListName = ObjectListName.stream().map( m -> m.toString() ).collect( Collectors.toList() );

"Auth Failed" error with EGit and GitHub

You need to install msysgit, after installing you need to open Git Bash and enter there these commands:

$ git config --global user.name "Gennadiy Zlobin" (your name)
$ git config --global user.email [email protected] (your email)
$ ssh-keygen -C "[email protected]" -t rsa (your email)

Now your generated keys are in C:\Users\username\.ssh (in Windows 7).
Next you load the content of your public key to your project on Github
In Eclipse open Window->Preferences->General->Network->SSH2 and set your ~/.ssh as SSH Home

After that go to Key Management tab and Load existing Key - set here your private key in ~/.ssh.

After that you can push your project to Github (but I set ssh protocol, not git+ssh).

Convert to absolute value in Objective-C

You can use this function to get the absolute value:

+(NSNumber *)absoluteValue:(NSNumber *)input {
  return [NSNumber numberWithDouble:fabs([input doubleValue])];
}

Table columns, setting both min and max width with css

Tables work differently; sometimes counter-intuitively.

The solution is to use width on the table cells instead of max-width.

Although it may sound like in that case the cells won't shrink below the given width, they will actually.
with no restrictions on c, if you give the table a width of 70px, the widths of a, b and c will come out as 16, 42 and 12 pixels, respectively.
With a table width of 400 pixels, they behave like you say you expect in your grid above.
Only when you try to give the table too small a size (smaller than a.min+b.min+the content of C) will it fail: then the table itself will be wider than specified.

I made a snippet based on your fiddle, in which I removed all the borders and paddings and border-spacing, so you can measure the widths more accurately.

_x000D_
_x000D_
table {_x000D_
  width: 70px;_x000D_
}_x000D_
_x000D_
table, tbody, tr, td {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  border: 0;_x000D_
  border-spacing: 0;_x000D_
}_x000D_
_x000D_
.a, .c {_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
.b {_x000D_
  background-color: #F77;_x000D_
}_x000D_
_x000D_
.a {_x000D_
  min-width: 10px;_x000D_
  width: 20px;_x000D_
  max-width: 20px;_x000D_
}_x000D_
_x000D_
.b {_x000D_
  min-width: 40px;_x000D_
  width: 45px;_x000D_
  max-width: 45px;_x000D_
}_x000D_
_x000D_
.c {}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td class="a">A</td>_x000D_
    <td class="b">B</td>_x000D_
    <td class="c">C</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

PHP session handling errors

This was a known bug in version(s) of PHP . Depending on your server environment, you can try setting the sessions folder to 777:

/var/lib/php/session (your location may vary)

I ended up using this workaround:

session_save_path('/path/not/accessable_to_world/sessions');
ini_set('session.gc_probability', 1);

You will have to create this folder and make it writeable. I havent messed around with the permissions much, but 777 worked for me (obviously).

Make sure the place where you are storing your sessions isn't accessible to the world.

This solution may not work for everyone, but I hope it helps some people!

SoapUI "failed to load url" error when loading WSDL

For java version above 1.8, Use below command to setup soapUI jar

java -jar --add-modules java.xml.bind --add-modules java.xml.ws <path for jar file+jar file name.jar>

onclick="javascript:history.go(-1)" not working in Chrome

javascript:history.go(-1);

was used in the older browser.IE6. For other browser compatibility try

window.history.go(-1);

where -1 represent the number of pages you want to go back (-1,-2...etc) and return false is required to prevent default event.

For example :

<a href="#" onclick="window.history.go(-1); return false;"> Link </a>   

How to center a button within a div?

Easiest thing is input it as a "div" give it a "margin:0 auto " but if you want it to be centered u need to give it a width

  Div{
   Margin: 0 auto ;
   Width: 100px ;
  }

Why is it OK to return a 'vector' from a function?

I think you are referring to the problem in C (and C++) that returning an array from a function isn't allowed (or at least won't work as expected) - this is because the array return will (if you write it in the simple form) return a pointer to the actual array on the stack, which is then promptly removed when the function returns.

But in this case, it works, because the std::vector is a class, and classes, like structs, can (and will) be copied to the callers context. [Actually, most compilers will optimise out this particular type of copy using something called "Return Value Optimisation", specifically introduced to avoid copying large objects when they are returned from a function, but that's an optimisation, and from a programmers perspective, it will behave as if the assignment constructor was called for the object]

As long as you don't return a pointer or a reference to something that is within the function returning, you are fine.

How do I measure a time interval in C?

Using the time.h library, try something like this:

long start_time, end_time, elapsed;

start_time = clock();
// Do something
end_time = clock();

elapsed = (end_time - start_time) / CLOCKS_PER_SEC * 1000;

Remove json element

For those of you who came here looking for how to remove an object from a JSON array based on object value:

_x000D_
_x000D_
let users = [{"name": "Ben"},{"name": "Tim"},{"name": "Harry"}];

 for (let [i, user] of users.entries()) {
    if (user.name == "Tim") {
        users.splice(i, 1);
    }
 }
_x000D_
_x000D_
_x000D_

User Tim is now removed from JSON array users.

Is it possible to simulate key press events programmatically?

just use CustomEvent

Node.prototype.fire=function(type,options){
     var event=new CustomEvent(type);
     for(var p in options){
         event[p]=options[p];
     }
     this.dispatchEvent(event);
}

4 ex want to simulate ctrl+z

window.addEventListener("keyup",function(ev){
     if(ev.ctrlKey && ev.keyCode === 90) console.log(ev); // or do smth
     })

 document.fire("keyup",{ctrlKey:true,keyCode:90,bubbles:true})

How to print React component on click of a button?

There is kind of two solutions on the client. One is with frames like you posted. You can use an iframe though:

var content = document.getElementById("divcontents");
var pri = document.getElementById("ifmcontentstoprint").contentWindow;
pri.document.open();
pri.document.write(content.innerHTML);
pri.document.close();
pri.focus();
pri.print();

This expects this html to exist

<iframe id="ifmcontentstoprint" style="height: 0px; width: 0px; position: absolute"></iframe>

The other solution is to use the media selector and on the media="print" styles hide everything you don't want to print.

<style type="text/css" media="print">
   .no-print { display: none; }
</style>

Last way requires some work on the server. You can send all the HTML+CSS to the server and use one of many components to generate a printable document like PDF. I've tried setups doing this with PhantomJs.

How to delete object?

You can use extension methods to achive this.

public static ObjRemoverExtension {
    public static void DeleteObj<T>(this T obj) where T: new()
    {
        obj = null;
    }
}

And then you just import it in a desired source file and use on any object. GC will collect it. Like this:Car.DeleteObj()

EDIT Sorry didn't notice the method of class/all references part, but i'll leave it anyway.

Creating a Plot Window of a Particular Size

This will depend on the device you're using. If you're using a pdf device, you can do this:

pdf( "mygraph.pdf", width = 11, height = 8 )
plot( x, y )

You can then divide up the space in the pdf using the mfrow parameter like this:

par( mfrow = c(2,2) )

That makes a pdf with four panels available for plotting. Unfortunately, some of the devices take different units than others. For example, I think that X11 uses pixels, while I'm certain that pdf uses inches. If you'd just like to create several devices and plot different things to them, you can use dev.new(), dev.list(), and dev.next().

Other devices that might be useful include:

There's a list of all of the devices here.

C++ delete vector, objects, free memory

You can call clear, and that will destroy all the objects, but that will not free the memory. Looping through the individual elements will not help either (what action would you even propose to take on the objects?) What you can do is this:

vector<tempObject>().swap(tempVector);

That will create an empty vector with no memory allocated and swap it with tempVector, effectively deallocating the memory.

C++11 also has the function shrink_to_fit, which you could call after the call to clear(), and it would theoretically shrink the capacity to fit the size (which is now 0). This is however, a non-binding request, and your implementation is free to ignore it.

Interpreting "condition has length > 1" warning from `if` function

The way I cam across this question was when I tried doing something similar where I was defining a function and it was being called with the array like others pointed out

You could do something like this however for this scenarios its less elegant compared to Sven's method.

sapply(a, function(x) afunc(x))

afunc<-function(a){
  if (a>0){
    a/sum(a)
  }
  else 1
}

no suitable HttpMessageConverter found for response type

This is not answering the problem but if anyone comes to this question when they stumble upon this exception of no suitable message converter found, here is my problem and solution.

In Spring 4.0.9, we were able to send this

    JSONObject jsonCredential = new JSONObject();
    jsonCredential.put(APPLICATION_CREDENTIALS, data);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

ResponseEntity<String> res = restTemplate.exchange(myRestUrl), HttpMethod.POST,request, String.class);

In Spring 4.3.5 release, we starting seeing errors with the message that converter was not found.

The way Convertors work is that if you have it in your classpath, they get registered.

Jackson-asl was still in classpath but was not being recognized by spring. We replaced Jackson-asl with faster-xml jackson core.

Once we added I could see the converter being registered.

enter image description here

Setting the MySQL root user password on OS X

The instructions provided in the mysql website is so clear, than the above mentioned

  1. $ sudo /usr/local/mysql/support-files/mysql.server stop
  2. $ sudo /usr/local/mysql/support-files/mysql.server start --skip-grant-tables
  3. /usr/local/mysql/bin/mysql
  4. mysql> FLUSH PRIVILEGES;
  5. mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';
  6. mysql> exit or Ctrl + z
  7. $ sudo /usr/local/mysql/support-files/mysql.server stop
  8. $ sudo /usr/local/mysql/support-files/mysql.server start
  9. /usr/local/mysql/support-files/mysql -u root -p
  10. Enter the new password i.e MyNewPass

Reference: http://dev.mysql.com/doc/refman/5.7/en/resetting-permissions.html

When to use throws in a Java method declaration?

If you are catching an exception type, you do not need to throw it, unless you are going to rethrow it. In the example you post, the developer should have done one or another, not both.

Typically, if you are not going to do anything with the exception, you should not catch it.

The most dangerous thing you can do is catch an exception and not do anything with it.

A good discussion of when it is appropriate to throw exceptions is here

When to throw an exception?

Elegant Python function to convert CamelCase to snake_case?

Just in case someone needs to transform a complete source file, here is a script that will do it.

# Copy and paste your camel case code in the string below
camelCaseCode ="""
    cv2.Matx33d ComputeZoomMatrix(const cv2.Point2d & zoomCenter, double zoomRatio)
    {
      auto mat = cv2.Matx33d::eye();
      mat(0, 0) = zoomRatio;
      mat(1, 1) = zoomRatio;
      mat(0, 2) = zoomCenter.x * (1. - zoomRatio);
      mat(1, 2) = zoomCenter.y * (1. - zoomRatio);
      return mat;
    }
"""

import re
def snake_case(name):
    s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
    return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()

def lines(str):
    return str.split("\n")

def unlines(lst):
    return "\n".join(lst)

def words(str):
    return str.split(" ")

def unwords(lst):
    return " ".join(lst)

def map_partial(function):
    return lambda values : [  function(v) for v in values]

import functools
def compose(*functions):
    return functools.reduce(lambda f, g: lambda x: f(g(x)), functions, lambda x: x)

snake_case_code = compose(
    unlines ,
    map_partial(unwords),
    map_partial(map_partial(snake_case)),
    map_partial(words),
    lines
)
print(snake_case_code(camelCaseCode))

Apache HttpClient Interim Error: NoHttpResponseException

I have faced same issue, I resolved by adding "connection: close" as extention,

Step 1: create a new class ConnectionCloseExtension

import com.github.tomakehurst.wiremock.common.FileSource;
import com.github.tomakehurst.wiremock.extension.Parameters;
import com.github.tomakehurst.wiremock.extension.ResponseTransformer;
import com.github.tomakehurst.wiremock.http.HttpHeader;
import com.github.tomakehurst.wiremock.http.HttpHeaders;
import com.github.tomakehurst.wiremock.http.Request;
import com.github.tomakehurst.wiremock.http.Response;

public class ConnectionCloseExtension extends ResponseTransformer {
  @Override
  public Response transform(Request request, Response response, FileSource files, Parameters parameters) {
    return Response.Builder
        .like(response)
        .headers(HttpHeaders.copyOf(response.getHeaders())
            .plus(new HttpHeader("Connection", "Close")))
        .build();
  }

  @Override
  public String getName() {
    return "ConnectionCloseExtension";
  }
}

Step 2: set extension class in wireMockServer like below,

final WireMockServer wireMockServer = new WireMockServer(options()
                .extensions(ConnectionCloseExtension.class)
                .port(httpPort));

How to view log output using docker-compose run?

Update July 1st 2019

docker-compose logs <name-of-service>

From the documentation:

Usage: logs [options] [SERVICE...]

Options:

--no-color Produce monochrome output.

-f, --follow Follow log output.

-t, --timestamps Show timestamps.

--tail="all" Number of lines to show from the end of the logs for each container.

See docker logs

You can start Docker compose in detached mode and attach yourself to the logs of all container later. If you're done watching logs you can detach yourself from the logs output without shutting down your services.

  1. Use docker-compose up -d to start all services in detached mode (-d) (you won't see any logs in detached mode)
  2. Use docker-compose logs -f -t to attach yourself to the logs of all running services, whereas -f means you follow the log output and the -t option gives you timestamps (See Docker reference)
  3. Use Ctrl + z or Ctrl + c to detach yourself from the log output without shutting down your running containers

If you're interested in logs of a single container you can use the docker keyword instead:

  1. Use docker logs -t -f <name-of-service>

Save the output

To save the output to a file you add the following to your logs command:

  1. docker-compose logs -f -t >> myDockerCompose.log

Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type

I've had a same problem with react-redux types. The simplest solution was add to tsconfig.json:

"noImplicitAny": false

Example:

{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "isolatedModules": true,
    "jsx": "react",
    "lib": ["es6"],
    "moduleResolution": "node",
    "noEmit": true,
    "strict": true,
    "target": "esnext",
    "noImplicitAny": false,
  },
  "exclude": ["node_modules", "babel.config.js", "metro.config.js", "jest.config.js"]
}

How to use WHERE IN with Doctrine 2

I know it's an old post but may be helpful for someone. I would vote & enhance @Daniel Espendiller answer by addressing the question asked in comments about ints

To make this work for int's in proper way, make sure the values in array are of type int, you can type cast to int before passing...

 $qb->andWhere('foo.field IN (:ints)');
 $qb->setParameter('ints', array(1, 2), 
 \Doctrine\DBAL\Connection::PARAM_INT_ARRAY);

Tested for select/delete in symfony 3.4 & doctrine-bundle: 1.8

Reduce size of legend area in barplot

The cex parameter will do that for you.

a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
        col = 1:6, space = c(0, 2))
legend("topright", 
       legend = c("a", "b", "c", "d", "e", "f"), 
       fill = 1:6, ncol = 2,
       cex = 0.75)

The plot

What's the difference between 'git merge' and 'git rebase'?

I found one really interesting article on git rebase vs merge, thought of sharing it here

  • If you want to see the history completely same as it happened, you should use merge. Merge preserves history whereas rebase rewrites it.
  • Merging adds a new commit to your history
  • Rebasing is better to streamline a complex history, you are able to change the commit history by interactive rebase.

JComboBox Selection Change Listener?

You may try these

 int selectedIndex = myComboBox.getSelectedIndex();

-or-

Object selectedObject = myComboBox.getSelectedItem();

-or-

String selectedValue = myComboBox.getSelectedValue().toString();

Parse JSON object with string and value only

My pseudocode example will be as follows:

JSONArray jsonArray = "[{id:\"1\", name:\"sql\"},{id:\"2\",name:\"android\"},{id:\"3\",name:\"mvc\"}]";
JSON newJson = new JSON();

for (each json in jsonArray) {
    String id = json.get("id");
    String name = json.get("name");

    newJson.put(id, name);
}

return newJson;

Real world use of JMS/message queues?

I've used it to send intraday trades between different fund management systems. If you want to learn more about what a great technology messaging is, I can thoroughly recommend the book "Enterprise Integration Patterns". There are some JMS examples for things like request/reply and publish/subscribe.

Messaging is an excellent tool for integration.

Connection Strings for Entity Framework

Silverlight applications do not have direct access to machine.config.

Notice: Trying to get property of non-object error

@Balamanigandan your Original Post :- PHP Notice: Trying to get property of non-object error

Your are trying to access the Null Object. From AngularJS your are not passing any Objects instead you are passing the $_GET element. Try by using $_GET['uid'] instead of $objData->token

Global variables in AngularJS

Try this, you will not force to inject $rootScope in controller.

app.run(function($rootScope) {
    $rootScope.Currency = 'USD';
});

You can only use it in run block because config block will not provide you to use service of $rootScope.

warning: incompatible implicit declaration of built-in function ‘xyz’

I met these warnings on mempcpy function. Man page says this function is a GNU extension and synopsis shows:

#define _GNU_SOURCE
#include <string.h>

When #define is added to my source before the #include, declarations for the GNU extensions are made visible and warnings disappear.

Android - How to regenerate R class?

I have tried all the solutions above. But they unfortunately it did not solve my problem. My R.java was gone as soon as I pasted a new picture to my drawable folder. After reading the answers for this question I tried to delete the icon I have previously pasted (while Build Automatically Enabled) and everything was fine afetr. Hope this will help someone!

Android: Go back to previous activity

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

This will get you to a previous activity keeping its stack and clearing all activities after it from the stack.

For example, if stack was A->B->C->D and you start B with this flag, stack will be A->B

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

You should be able to use Linq here:

var matchingvalues = myList
    .Where(stringToCheck => stringToCheck.Contains(myString));

If you simply wish to return the first matching item:

var match = myList
    .FirstOrDefault(stringToCheck => stringToCheck.Contains(myString));

if(match != null)
    //Do stuff

The value violated the integrity constraints for the column

You can replace the values "null" from the original file & field/column.

What is setup.py?

setup.py is a Python file like any other. It can take any name, except by convention it is named setup.py so that there is not a different procedure with each script.

Most frequently setup.py is used to install a Python module but server other purposes:

Modules:

Perhaps this is most famous usage of setup.py is in modules. Although they can be installed using pip, old Python versions did not include pip by default and they needed to be installed separately.

If you wanted to install a module but did not want to install pip, just about the only alternative was to install the module from setup.py file. This could be achieved via python setup.py install. This would install the Python module to the root dictionary (without pip, easy_install ect).

This method is often used when pip will fail. For example if the correct Python version of the desired package is not available via pipperhaps because it is no longer maintained, , downloading the source and running python setup.py install would perform the same thing, except in the case of compiled binaries are required, (but will disregard the Python version -unless an error is returned).

Another use of setup.py is to install a package from source. If a module is still under development the wheel files will not be available and the only way to install is to install from the source directly.

Building Python extensions:

When a module has been built it can be converted into module ready for distribution using a distutils setup script. Once built these can be installed using the command above.

A setup script is easy to build and once the file has been properly configured and can be compiled by running python setup.py build (see link for all commands).

Once again it is named setup.py for ease of use and by convention, but can take any name.

Cython:

Another famous use of setup.py files include compiled extensions. These require a setup script with user defined values. They allow fast (but once compiled are platform dependant) execution. Here is a simple example from the documentation:

from distutils.core import setup
from Cython.Build import cythonize

setup(
    name = 'Hello world app',
    ext_modules = cythonize("hello.pyx"),
)

This can be compiled via python setup.py build

Cx_Freeze:

Another module requiring a setup script is cx_Freeze. This converts Python script to executables. This allows many commands such as descriptions, names, icons, packages to include, exclude ect and once run will produce a distributable application. An example from the documentation:

import sys
from cx_Freeze import setup, Executable
build_exe_options = {"packages": ["os"], "excludes": ["tkinter"]} 

base = None
if sys.platform == "win32":
    base = "Win32GUI"

setup(  name = "guifoo",
        version = "0.1",
        description = "My GUI application!",
        options = {"build_exe": build_exe_options},
        executables = [Executable("guifoo.py", base=base)])

This can be compiled via python setup.py build.

So what is a setup.py file?

Quite simply it is a script that builds or configures something in the Python environment.

A package when distributed should contain only one setup script but it is not uncommon to combine several together into a single setup script. Notice this often involves distutils but not always (as I showed in my last example). The thing to remember it just configures Python package/script in some way.

It takes the name so the same command can always be used when building or installing.

Configure Apache .conf for Alias

Sorry not sure what was going on this worked in the end:

<VirtualHost *> 
    ServerName example.com
    DocumentRoot /var/www/html/mjp

    Alias /ncn "/var/www/html/ncn"

    <Directory "/var/www/html/ncn">
        Options None
        AllowOverride None
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

Measure the time it takes to execute a t-sql query

Another way is using a SQL Server built-in feature named Client Statistics which is accessible through Menu > Query > Include Client Statistics.

You can run each query in separated query window and compare the results which is given in Client Statistics tab just beside the Messages tab.

For example in image below it shows that the average time elapsed to get the server reply for one of my queries is 39 milliseconds.

Result

You can read all 3 ways for acquiring execution time in here. You may even need to display Estimated Execution Plan ctrlL for further investigation about your query.

How copy data from Excel to a table using Oracle SQL Developer

You may directly right-click on the table name - that also shows the "Import Data.." option.Then you can follow few simple steps & succeed.

Do anyone know how to import a new table with data from excel?

Accessing @attribute from SimpleXML

Unfortunately I have a unique build (stuck with Gentoo for the moment) of PHP 5.5, and what I found was that

 $xml->tagName['attribute']

was the only solution that worked. I tried all of Bora's methods above, including the 'Right & Quick' format, and they all failed.

The fact that this is the easiest format is a plus, but didn't enjoy thinking I was insane trying all of the formats others were saying worked.

Njoy for what its worth (did I mention unique build?).

Reading file line by line (with space) in Unix Shell scripting - Issue

Try this,

IFS=''
while read line
do
    echo $line
done < file.txt

EDIT:

From man bash

IFS - The Internal Field Separator that is used for word
splitting after expansion and to split lines into words
with  the  read  builtin  command. The default value is
``<space><tab><newline>''

round() doesn't seem to be rounding properly

Formatting works correctly even without having to round:

"%.1f" % n

How to convert numbers between hexadecimal and decimal

An extension method for converting a byte array into a hex representation. This pads each byte with leading zeros.

    /// <summary>
    /// Turns the byte array into its Hex representation.
    /// </summary>
    public static string ToHex(this byte[] y)
    {
        StringBuilder sb = new StringBuilder();
        foreach (byte b in y)
        {
            sb.Append(b.ToString("X").PadLeft(2, "0"[0]));
        }
        return sb.ToString();
    }

Resolve host name to an ip address

You could use a C function getaddrinfo() to get the numerical address - both ipv4 and ipv6. See the example code here

How to escape the equals sign in properties files

I've been able to input values within the character ":

db_user="postgresql"
db_passwd="this,is,my,password"

Writing file to web server - ASP.NET

protected void TestSubmit_ServerClick(object sender, EventArgs e)
{
    using (StreamWriter w = new StreamWriter(Server.MapPath("~/data.txt"), true))
    {
        w.WriteLine(TextBox1.Text); // Write the text
    }
}

Is there a good Valgrind substitute for Windows?

As jakobengblom2 pointed out, valgrind has a suit of tools. Depending which one you are talking about there are different windows counter parts. I will only mention OSS or free tools here.

1. MemCheck:

Dr. Memory. It is a relatively new tool, works very well on Windows 7. My favorite feature is that it groups the same leaks' allocation stacks in the report.

http://code.google.com/p/drmemory/

I have also used UMDH( http://support.microsoft.com/kb/268343 ) and found it quiet useful and easy to setup. It works from Win2000 to Win7.

AppVerifier is a must have swissknife for windows native code developers, its "memory" checker does similar job http://msdn.microsoft.com/en-us/library/dd371695%28v=vs.85%29.aspx

2. Callgrind:

My favorite is verysleepy ( http://www.codersnotes.com/sleepy ) It is tiny but very useful and easy to use.

If you need more features, AMD CodeAnalyst™ Performance Analyzer is free: http://developer.amd.com/documentation/videos/pages/introductiontoamdcodeanalystperformanceanalyzer.aspx

Windows Performance Analysis tools is free from Microsoft, not very easy to use but can get the job done if you are willing to spend the time. http://blogs.microsoft.co.il/blogs/sasha/archive/2008/03/15/xperf-windows-performance-toolkit.aspx Download: http://msdn.microsoft.com/en-us/performance/cc752957

3. Massif:

Similar(not quite exact match) free tools on windows are:

VMMap from sysinternals : http://technet.microsoft.com/en-us/sysinternals/dd535533

!heap command in windbg : http://hacksoflife.blogspot.com/2009/06/heap-debugging-memoryresource-leak-with.html

4. Cachegrind:

Above mentioned Windows Performance Tools has certain level of L2 cache miss profiling capability but not quite as good and easy to use as Cachegrind.

5. DRD:

Haven't found anything free and as powerful on Windows yet, the only free tool for windows I can find that is slightly close is the "lock" checker in AppVerifier: http://msdn.microsoft.com/en-us/library/dd371695%28v=vs.85%29.aspx

How do I print an IFrame from javascript in Safari/Chrome

Use this:

window.onload = setTimeout("window.print()", 1000);

How to delete a file or folder?

Use

shutil.rmtree(path[, ignore_errors[, onerror]])

(See complete documentation on shutil) and/or

os.remove

and

os.rmdir

(Complete documentation on os.)

TypeLoadException says 'no implementation', but it is implemented

Just to add my experience as it has not been covered in other answers:

I got this problem when running unit tests in MsTest.

The classes under test were in a signed assembly.

A different version of this assembly happened to be in the GAC (but with the same assembly version number).

Dependency resolution algorithm for strong named assemblies is slightly different to non-signed as the GAC is checked first.

So MsTest was picking up the GAC'd assembly rather than using the one from the bin folder, and trying to run the tests against it, which was obviously not working.

Solution was to remove the GAC'd assembly.

Note, the clue for me was this was not happening on the build server when the tests were run, because the build would compile the assemblies with a new assembly version number. This meant that older versions of the assembly in the GAC would not be picked up.

Also, I found a potential workaround here, if you cannot for some reason access the GAC: https://johanleino.wordpress.com/2014/02/20/workaround-for-unit-testing-code-that-reside-in-the-gac/

SQL multiple column ordering

SELECT  *
FROM    mytable
ORDER BY
        column1 DESC, column2 ASC

Cross origin requests are only supported for HTTP but it's not cross-domain

For all python users:

Simply go to your destination folder in the terminal.

cd projectFoder

then start HTTP server For Python3+:

python -m http.server 8000

Serving HTTP on :: port 8000 (http://[::]:8000/) ...

go to your link: http://0.0.0.0:8000/

Enjoy :)

Why I got " cannot be resolved to a type" error?

I had my own instance of this error, and in my case none of the above solutions resolved the "cannot be resolved to a type" error by themselves, although they were necessary steps toward doing so. I found something silly that did though.

This seemed to be due a bug in Eclipse (Luna Service Release 1a (4.4.1) in my case). In the file where you're seeing the error, try saving after making and then undoing a trivial change (e.g. deleting one character and then typing it back in). For some reason this caused all my class references to resolve.

What happens when a duplicate key is put into a HashMap?

I always used:

HashMap<String, ArrayList<String>> hashy = new HashMap<String, ArrayList<String>>();

if I wanted to apply multiple things to one identifying key.

public void MultiHash(){
    HashMap<String, ArrayList<String>> hashy = new HashMap<String, ArrayList<String>>();
    String key = "Your key";

    ArrayList<String> yourarraylist = hashy.get(key);

    for(String valuessaved2key : yourarraylist){
        System.out.println(valuessaved2key);
    }

}

you could always do something like this and create yourself a maze!

public void LOOK_AT_ALL_THESE_HASHMAPS(){
    HashMap<String, HashMap<String, HashMap<String, HashMap<String, String>>>> theultimatehashmap = new HashMap <String, HashMap<String, HashMap<String, HashMap<String, String>>>>();
    String ballsdeep_into_the_hashmap = theultimatehashmap.get("firststring").get("secondstring").get("thirdstring").get("forthstring");
}

Symfony2 : How to get form validation errors after binding the request to the form

For Symfony 2.1 onwards for use with Twig error display I altered the function to add a FormError instead of simply retrieving them, this way you have more control over errors and do not have to use error_bubbling on each individual input. If you do not set it in the manner below {{ form_errors(form) }} will remain blank:

/**
 * @param \Symfony\Component\Form\Form $form
 *
 * @return void
 */
private function setErrorMessages(\Symfony\Component\Form\Form $form) {      

    if ($form->count() > 0) {
        foreach ($form->all() as $child) {
            if (!$child->isValid()) {
                if( isset($this->getErrorMessages($child)[0]) ) {
                    $error = new FormError( $this->getErrorMessages($child)[0] );
                    $form->addError($error);
                }
            }
        }
    }

}

How to generate a random string of 20 characters

You may use the class java.util.Random with method

char c = (char)(rnd.nextInt(128-32))+32 

20x to get Bytes, which you interpret as ASCII. If you're fine with ASCII.

32 is the offset, from where the characters are printable in general.

how to exit a python script in an if statement

This works fine for me:

while True:
   answer = input('Do you want to continue?:')
   if answer.lower().startswith("y"):
      print("ok, carry on then")
   elif answer.lower().startswith("n"):
      print("sayonara, Robocop")
      exit()

edit: use input in python 3.2 instead of raw_input

Http post and get request in angular 6

For reading full response in Angular you should add the observe option:

{ observe: 'response' }
    return this.http.get(`${environment.serverUrl}/api/posts/${postId}/comments/?page=${page}&size=${size}`, { observe: 'response' });

java.lang.ClassCastException

A ClassCastException ocurrs when you try to cast an instance of an Object to a type that it is not. Casting only works when the casted object follows an "is a" relationship to the type you are trying to cast to. For Example

Apple myApple = new Apple();
Fruit myFruit = (Fruit)myApple;

This works because an apple 'is a' fruit. However if we reverse this.

Fruit myFruit = new Fruit();
Apple myApple = (Apple)myFruit;

This will throw a ClasCastException because a Fruit is not (always) an Apple.

It is good practice to guard any explicit casts with an instanceof check first:

if (myApple instanceof Fruit) {
  Fruit myFruit = (Fruit)myApple;
}

Transaction isolation levels relation with locks on table

As brb tea says, depends on the database implementation and the algorithm they use: MVCC or Two Phase Locking.

CUBRID (open source RDBMS) explains the idea of this two algorithms:

  • Two-phase locking (2PL)

The first one is when the T2 transaction tries to change the A record, it knows that the T1 transaction has already changed the A record and waits until the T1 transaction is completed because the T2 transaction cannot know whether the T1 transaction will be committed or rolled back. This method is called Two-phase locking (2PL).

  • Multi-version concurrency control (MVCC)

The other one is to allow each of them, T1 and T2 transactions, to have their own changed versions. Even when the T1 transaction has changed the A record from 1 to 2, the T1 transaction leaves the original value 1 as it is and writes that the T1 transaction version of the A record is 2. Then, the following T2 transaction changes the A record from 1 to 3, not from 2 to 4, and writes that the T2 transaction version of the A record is 3.

When the T1 transaction is rolled back, it does not matter if the 2, the T1 transaction version, is not applied to the A record. After that, if the T2 transaction is committed, the 3, the T2 transaction version, will be applied to the A record. If the T1 transaction is committed prior to the T2 transaction, the A record is changed to 2, and then to 3 at the time of committing the T2 transaction. The final database status is identical to the status of executing each transaction independently, without any impact on other transactions. Therefore, it satisfies the ACID property. This method is called Multi-version concurrency control (MVCC).

The MVCC allows concurrent modifications at the cost of increased overhead in memory (because it has to maintain different versions of the same data) and computation (in REPETEABLE_READ level you can't loose updates so it must check the versions of the data, like Hiberate does with Optimistick Locking).

In 2PL Transaction isolation levels control the following:

  • Whether locks are taken when data is read, and what type of locks are requested.

  • How long the read locks are held.

  • Whether a read operation referencing rows modified by another transaction:

    • Block until the exclusive lock on the row is freed.

    • Retrieve the committed version of the row that existed at the time the statement or transaction started.

    • Read the uncommitted data modification.

Choosing a transaction isolation level does not affect the locks that are acquired to protect data modifications. A transaction always gets an exclusive lock on any data it modifies and holds that lock until the transaction completes, regardless of the isolation level set for that transaction. For read operations, transaction isolation levels primarily define the level of protection from the effects of modifications made by other transactions.

A lower isolation level increases the ability of many users to access data at the same time, but increases the number of concurrency effects, such as dirty reads or lost updates, that users might encounter.

Concrete examples of the relation between locks and isolation levels in SQL Server (use 2PL except on READ_COMMITED with READ_COMMITTED_SNAPSHOT=ON)

  • READ_UNCOMMITED: do not issue shared locks to prevent other transactions from modifying data read by the current transaction. READ UNCOMMITTED transactions are also not blocked by exclusive locks that would prevent the current transaction from reading rows that have been modified but not committed by other transactions. [...]

  • READ_COMMITED:

    • If READ_COMMITTED_SNAPSHOT is set to OFF (the default): uses shared locks to prevent other transactions from modifying rows while the current transaction is running a read operation. The shared locks also block the statement from reading rows modified by other transactions until the other transaction is completed. [...] Row locks are released before the next row is processed. [...]
    • If READ_COMMITTED_SNAPSHOT is set to ON, the Database Engine uses row versioning to present each statement with a transactionally consistent snapshot of the data as it existed at the start of the statement. Locks are not used to protect the data from updates by other transactions.
  • REPETEABLE_READ: Shared locks are placed on all data read by each statement in the transaction and are held until the transaction completes.

  • SERIALIZABLE: Range locks are placed in the range of key values that match the search conditions of each statement executed in a transaction. [...] The range locks are held until the transaction completes.

Django: How can I call a view function from template?

For example, a logout button can be written like this:

<button class="btn btn-primary" onclick="location.href={% url 'logout'%}">Logout</button>

Where logout endpoint:

#urls.py:
url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name='logout'),

Error in spring application context schema

What @forhas and @HRgiger did also worked for me. I am using spring-data-mongodb instead of jpa.

However, for mongodb bindings, you should not remove the version of mongodb reference xsd, just keep it with version: http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd. context and beans versions should be removed.

How to remove all white space from the beginning or end of a string?

Trim() Removes all leading and trailing white-space characters from the current string. Trim(Char) Removes all leading and trailing instances of a character from the current string. Trim(Char[]) Removes all leading and trailing occurrences of a set of characters specified in an array from the current string.

Look at the following example that I quoted from Microsoft's documentation page.

char[] charsToTrim = { '*', ' ', '\''};
string banner = "*** Much Ado About Nothing ***";
string result = banner.Trim(charsToTrim);
Console.WriteLine("Trimmmed\n   {0}\nto\n   '{1}'", banner, result);

// The example displays the following output:
//       Trimmmed
//          *** Much Ado About Nothing ***
//       to
//          'Much Ado About Nothing'

Cast int to varchar

Yes

SELECT id || '' FROM some_table;
or SELECT id::text FROM some_table;

is postgresql, but mySql doesn't allow that!

short cut in mySql:

SELECT concat(id, '') FROM some_table;

Removing multiple keys from a dictionary safely

I have tested the performance of three methods:

# Method 1: `del`
for key in remove_keys:
    if key in d:
        del d[key]

# Method 2: `pop()`
for key in remove_keys:
    d.pop(key, None)

# Method 3: comprehension
{key: v for key, v in d.items() if key not in remove_keys}

Here are the results of 1M iterations:

  1. del: 2.03s 2.0 ns/iter (100%)
  2. pop(): 2.38s 2.4 ns/iter (117%)
  3. comprehension: 4.11s 4.1 ns/iter (202%)

So both del and pop() are the fastest. Comprehensions are 2x slower. But anyway, we speak nanoseconds here :) Dicts in Python are ridiculously fast.

Detect if string contains any spaces

A secondary option would be to check otherwise, with not space (\S), using an expression similar to:

^\S+$

Test

_x000D_
_x000D_
function has_any_spaces(regex, str) {_x000D_
 if (regex.test(str) || str === '') {_x000D_
  return false;_x000D_
 }_x000D_
 return true;_x000D_
}_x000D_
_x000D_
const expression = /^\S+$/g;_x000D_
const string = 'foo  baz bar';_x000D_
_x000D_
console.log(has_any_spaces(expression, string));
_x000D_
_x000D_
_x000D_

Here, we can for instance push strings without spaces into an array:

_x000D_
_x000D_
const regex = /^\S+$/gm;_x000D_
const str = `_x000D_
foo_x000D_
foo baz_x000D_
bar_x000D_
foo baz bar_x000D_
abc_x000D_
abc abc_x000D_
abc abc abc_x000D_
`;_x000D_
let m, arr = [];_x000D_
_x000D_
while ((m = regex.exec(str)) !== null) {_x000D_
 // This is necessary to avoid infinite loops with zero-width matches_x000D_
 if (m.index === regex.lastIndex) {_x000D_
  regex.lastIndex++;_x000D_
 }_x000D_
_x000D_
 // Here, we push those strings without spaces in an array_x000D_
 m.forEach((match, groupIndex) => {_x000D_
  arr.push(match);_x000D_
 });_x000D_
}_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

How to grant all privileges to root user in MySQL 8.0

The specified user just doesn't exist on your MySQL (so, MySQL is trying to create it with GRANT as it did before version 8, but fails with the limitations, introduced in this version).

MySQL's pretty dumb at this point, so if you have 'root'@'localhost' and trying to grant privileges to 'root'@'%' it treats them as different users, rather than generalized notion for root user on any host, including localhost.

The error message is also misleading.

So, if you're getting the error message, check your existing users with something like this

SELECT CONCAT("'", user, "'@'", host, "'") FROM mysql.user;

and then create missing user (as Mike advised) or adjust your GRANT command to the actual exisiting user specificaion.

(Excel) Conditional Formatting based on Adjacent Cell Value

I don't know if maybe it's a difference in Excel version but this question is 6 years old and the accepted answer didn't help me so this is what I figured out:

Under Conditional Formatting > Manage Rules:

  1. Make a new rule with "Use a formula to determine which cells to format"
  2. Make your rule, but put a dollar sign only in front of the letter: $A2<$B2
  3. Under "Applies to", Manually select the second column (It would not work for me if I changed the value in the box, it just kept snapping back to what was already there), so it looks like $B$2:$B$100 (assuming you have 100 rows)

This worked for me in Excel 2016.

Asp.net 4.0 has not been registered

The aspnet_regiis approach described above doesn't appear to work on Windows 8.1:

C:\Windows\system32>aspnet_regiis -i

Microsoft (R) ASP.NET RegIIS version 4.0.30319.33440
Administration utility to install and uninstall ASP.NET on the local machine.
Copyright (C) Microsoft Corporation. All rights reserved.
Start installing ASP.NET (4.0.30319.33440).
This option is not supported on this version of the operating system. Administrators should instead install/uninstall ASP.NET 4.5 with IIS8 using the "Turn Windows Features On/Off" dialog, the Server Manager management tool, or the dism.exe command line tool. For more details please see http://go.microsoft.com/fwlink/?LinkID=216771.
Finished installing ASP.NET (4.0.30319.33440).

As indicated in the message, I went to:

  1. Start
  2. Turn Windows features on or off
  3. .NET Framework 4.5 Advanced Services

and checked ASP.NET 4.5.

This seems to have resolved the problem.

how to create a window with two buttons that will open a new window

You add your ActionListener twice to button. So correct your code for button2 to

  JButton button2 = new JButton("hello agin2");
  panel.add(button2);
  button2.addActionListener (new Action2());//note the button2 here instead of button

Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater

Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g

You need to merge the remote branch into your current branch by running git pull.

If your local branch is already up-to-date, you may also need to run git pull --rebase.

A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.

Count length of array and return 1 if it only contains one element

Instead of writing echo $cars.length write echo @($cars).length

Foreign Key to non-primary key

Necromancing.
I assume when somebody lands here, he needs a foreign key to column in a table that contains non-unique keys.

The problem is, that if you have that problem, the database-schema is denormalized.

You're for example keeping rooms in a table, with a room-uid primary key, a DateFrom and a DateTo field, and another uid, here RM_ApertureID to keep track of the same room, and a soft-delete field, like RM_Status, where 99 means 'deleted', and <> 99 means 'active'.

So when you create the first room, you insert RM_UID and RM_ApertureID as the same value as RM_UID. Then, when you terminate the room to a date, and re-establish it with a new date range, RM_UID is newid(), and the RM_ApertureID from the previous entry becomes the new RM_ApertureID.

So, if that's the case, RM_ApertureID is a non-unique field, and so you can't set a foreign-key in another table.

And there is no way to set a foreign key to a non-unique column/index, e.g. in T_ZO_REM_AP_Raum_Reinigung (WHERE RM_UID is actually RM_ApertureID).
But to prohibit invalid values, you need to set a foreign key, otherwise, data-garbage is the result sooner rather than later...

Now what you can do in this case (short of rewritting the entire application) is inserting a CHECK-constraint, with a scalar function checking the presence of the key:

IF  EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]'))
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung DROP CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fu_Constaint_ValidRmApertureId]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fu_Constaint_ValidRmApertureId]
GO




CREATE FUNCTION [dbo].[fu_Constaint_ValidRmApertureId](
     @in_RM_ApertureID uniqueidentifier 
    ,@in_DatumVon AS datetime 
    ,@in_DatumBis AS datetime 
    ,@in_Status AS integer 
) 
    RETURNS bit 
AS 
BEGIN   
    DECLARE @bNoCheckForThisCustomer AS bit 
    DECLARE @bIsInvalidValue AS bit 
    SET @bNoCheckForThisCustomer = 'false' 
    SET @bIsInvalidValue = 'false' 

    IF @in_Status = 99 
        RETURN 'false' 


    IF @in_DatumVon > @in_DatumBis 
    BEGIN 
        RETURN 'true' 
    END 


    IF @bNoCheckForThisCustomer = 'true'
        RETURN @bIsInvalidValue 


    IF NOT EXISTS
    ( 
        SELECT 
             T_Raum.RM_UID 
            ,T_Raum.RM_Status 
            ,T_Raum.RM_DatumVon 
            ,T_Raum.RM_DatumBis 
            ,T_Raum.RM_ApertureID 
        FROM T_Raum 
        WHERE (1=1) 
        AND T_Raum.RM_ApertureID = @in_RM_ApertureID 
        AND @in_DatumVon >= T_Raum.RM_DatumVon 
        AND @in_DatumBis <= T_Raum.RM_DatumBis 
        AND T_Raum.RM_Status <> 99  
    ) 
        SET @bIsInvalidValue = 'true' -- IF ! 

    RETURN @bIsInvalidValue 
END 



GO



IF  EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]'))
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung DROP CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
GO


-- ALTER TABLE dbo.T_AP_Kontakte WITH CHECK ADD CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]  
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung WITH NOCHECK ADD CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung] 
CHECK 
( 
    NOT 
    ( 
        dbo.fu_Constaint_ValidRmApertureId(ZO_RMREM_RM_UID, ZO_RMREM_GueltigVon, ZO_RMREM_GueltigBis, ZO_RMREM_Status) = 1 
    ) 
) 
GO


IF  EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]')) 
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung CHECK CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung] 
GO

CSS centred header image

If you set the margin to be margin:0 auto the image will be centered.

This will give top + bottom a margin of 0, and left and right a margin of 'auto'. Since the div has a width (200px), the image will be 200px wide and the browser will auto set the left and right margin to half of what is left on the page, which will result in the image being centered.

Open Redis port for remote connections

In my case, I'm using redis-stable

Go to redis-stable path 
 cd /home/ubuntu/software/redis-stable

Open the redis.conf

vim redis.conf

Change the bind 127.0.0.1 to bind 0.0.0.0

change the protected-mode yes to protected-mode no

Restart the redis-server:

/etc/init.d/redis-server stop
 redis-server redis.conf

How does String substring work in Swift

Swift 4

extension String {
    subscript(_ i: Int) -> String {
        let idx1 = index(startIndex, offsetBy: i)
        let idx2 = index(idx1, offsetBy: 1)
        return String(self[idx1..<idx2])
    }
}

let s = "hello"

s[0]    // h
s[1]    // e
s[2]    // l
s[3]    // l
s[4]    // o

Max parallel http connections in a browser?

  1. Yes, wildcard domain will work for you.
  2. Not aware of any limits on connections. Limits if any will be browser specific.

Hive load CSV with commas in quoted fields

If you can re-create or parse your input data, you can specify an escape character for the CREATE TABLE:

ROW FORMAT DELIMITED FIELDS TERMINATED BY "," ESCAPED BY '\\';

Will accept this line as 4 fields

1,some text\, with comma in it,123,more text

Truncate/round whole number in JavaScript?

If you have a string, parse it as an integer:

var num = '20.536';
var result = parseInt(num, 10);  // 20

If you have a number, ECMAScript 6 offers Math.trunc for completely consistent truncation, already available in Firefox 24+ and Edge:

var num = -2147483649.536;
var result = Math.trunc(num);  // -2147483649

If you can’t rely on that and will always have a positive number, you can of course just use Math.floor:

var num = 20.536;
var result = Math.floor(num);  // 20

And finally, if you have a number in [−2147483648, 2147483647], you can truncate to 32 bits using any bitwise operator. | 0 is common, and >>> 0 can be used to obtain an unsigned 32-bit integer:

var num = -20.536;
var result = num | 0;  // -20

Redirecting unauthorized controller in ASP.NET MVC

In your Startup.Auth.cs file add this line:

LoginPath = new PathString("/Account/Login"),

Example:

// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        // Enables the application to validate the security stamp when the user logs in.
        // This is a security feature which is used when you change a password or add an external login to your account.  
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
        validateInterval: TimeSpan.FromMinutes(30),
        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
    }
});

can you add HTTPS functionality to a python flask web server?

Don't use openssl or pyopenssl its now become obselete in python

Refer the Code below

from flask import Flask, jsonify
import os

ASSETS_DIR = os.path.dirname(os.path.abspath(__file__))
app = Flask(__name__)


@app.route('/')
def index():
    return 'Flask is running!'


@app.route('/data')
def names():
    data = {"names": ["John", "Jacob", "Julie", "Jennifer"]}
    return jsonify(data)


if __name__ == '__main__':
    context = ('local.crt', 'local.key')#certificate and key files
    app.run(debug=True, ssl_context=context)

Change background color on mouseover and remove it after mouseout

After lot of struggle finally got it working. ( Perfectly tested)

The below example will also support the fact that color of already clicked button should not be changes

JQuery Code

var flag = 0; // Flag is to check if you are hovering on already clicked item

$("a").click(function() {
    $('a').removeClass("YourColorClass");
    $(this).addClass("YourColorClass");
    flag=1;
}); 

$("a").mouseover(function() {
    if ($(this).hasClass("YourColorClass")) {
        flag=1;
    }
    else{
        $(this).addClass("YourColorClass");
    };
});

$("a").mouseout(function() {
    if (flag == 0) {
        $(this).removeClass("YourColorClass");
    }
    else{
        flag = 0;
    }
});

Explanation of the UML arrows

My favourite UML "cheat sheet" is UML Distilled, by Martin Fowler. It's the only one of his books that I've read that I do recommend.

How find out which process is using a file in Linux?

You can use the fuser command, like:

fuser file_name

You will receive a list of processes using the file.

You can use different flags with it, in order to receive a more detailed output.

You can find more info in the fuser's Wikipedia article, or in the man pages.

Move SQL Server 2008 database files to a new folder location

This is a complete procedure to transfer database and logins from an istance to a new one, scripting logins and relocating datafile and log files on the destination. Everything using metascripts.

http://zaboilab.com/sql-server-toolbox/massive-database-migration-between-sql-server-instances-the-complete-procedure

Sorry for the off-site procedure but scripts are very long. You have to:
- Script logins with original SID and HASHED password
- Create script to backup database using metascripts
- Create script to restore database passing relocate parameters using again metascripts
- Run the generated scripts on source and destination instance.
See details and download scripts following the link above.

Difference between arguments and parameters in Java

The term parameter refers to any declaration within the parentheses following the method/function name in a method/function declaration or definition; the term argument refers to any expression within the parentheses of a method/function call. i.e.

  1. parameter used in function/method definition.
  2. arguments used in function/method call.

Please have a look at the below example for better understanding:

package com.stackoverflow.works;

public class ArithmeticOperations {

    public static int add(int x, int y) { //x, y are parameters here
        return x + y;
    }

    public static void main(String[] args) {
        int x = 10;
        int y = 20;
        int sum = add(x, y); //x, y are arguments here
        System.out.println("SUM IS: " +sum);
    }

}

Thank you!

How to convert a string of numbers to an array of numbers?

You can transform array of strings to array of numbers in one line:

const arrayOfNumbers = arrayOfStrings.map(e => +e);

DateTimeFormat in TypeScript

This should work...

var displayDate = new Date().toLocaleDateString();

alert(displayDate);

But I suspect you are trying it on something else, for example:

var displayDate = Date.now.toLocaleDateString(); // No!

alert(displayDate);

How do you check if a variable is an array in JavaScript?

Something I just came up with:

if (item.length) //This is an array else //not an array

Passing multiple values to a single PowerShell script parameter

Parameters take input before arguments. What you should do instead is add a parameter that accepts an array, and make it the first position parameter. ex:

param(
    [Parameter(Position = 0)]
    [string[]]$Hosts,
    [string]$VLAN
    )

foreach ($i in $Hosts)  
{ 
    Do-Stuff $i
}

Then call it like:

.\script.ps1 host1, host2, host3 -VLAN 2

Notice the comma between the values. This collects them in an array

Relative div height

When you set a percentage height on an element who's parent elements don't have heights set, the parent elements have a default

height: auto;

You are asking the browser to calculate a height from an undefined value. Since that would equal a null-value, the result is that the browser does nothing with the height of child elements.

Besides using a JavaScript solution you could use this deadly easy table method:

#parent3 {
    display: table;
    width: 100%;
}

#parent3 .between {
    display: table-row;
}

#parent3 .child {
    display: table-cell;
}

Preview on http://jsbin.com/IkEqAfi/1

  • Example 1: Not working
  • Example 2: Fix height
  • Example 3: Table method

But: Bare in mind, that the table method only works properly in all modern Browsers and the Internet Explorer 8 and higher. As Fallback you could use JavaScript.

Controller 'ngModel', required by directive '...', can't be found

You can also remove the line

  require: 'ngModel',

if you don't need ngModel in this directive. Removing ngModel will allow you to make a directive without thatngModel error.

Windows service on Local Computer started and then stopped error

Use Timer and tick event to copy your files.

On start the service, start the time and specify the interval in the time.

So the service is keep running and copy the files ontick.

Hope it help.

MySQL, create a simple function

this is a mysql function example. I hope it helps. (I have not tested it yet, but should work)

DROP FUNCTION IF EXISTS F_TEST //
CREATE FUNCTION F_TEST(PID INT) RETURNS VARCHAR
BEGIN
/*DECLARE VALUES YOU MAY NEED, EXAMPLE:
  DECLARE NOM_VAR1 DATATYPE [DEFAULT] VALUE;
  */
  DECLARE NAME_FOUND VARCHAR DEFAULT "";

    SELECT EMPLOYEE_NAME INTO NAME_FOUND FROM TABLE_NAME WHERE ID = PID;
  RETURN NAME_FOUND;
END;//

How to insert a newline in front of a pattern?

In my case the below method works.

sed -i 's/playstation/PS4/' input.txt

Can be written as:

sed -i 's/playstation/PS4\nplaystation/' input.txt

PS4
playstation

Consider using \\n while using it in a string literal.

  • sed : is stream editor

  • -i : Allows to edit the source file

  • +: Is delimiter.

I hope the above information works for you .

Cassandra cqlsh - connection refused

This is because of some pre-configurations in the cassandra. And to fix this, there are following commented lines in the cassandra-env.sh file:

#add this if you’re having trouble connecting:
#JVM_OPTS="$JVM_OPTS -Djava.rmi.server.hostname=<public name>

where you have to start fixing the error.

Open the terminal and start fixing using the following easy steps:

Step-1

use

sudo nano /etc/cassandra/cassandra-env.sh

this command and search for JVM_OPTS="$JVM_OPTS -Djava.rmi.server.hostname= uncomment the line by simply removing # attached in the start of the line.

NOTE: If you have never opened this file to fix this error then you will find JVM_OPTS="$JVM_OPTS -Djava.rmi.server.hostname=<public name>

Step-2 Now replace <public name> with 127.0.0.1

Step-3 Save the file and restart the cassandra using systemctl restart cassandra.service (if you haven't the server is alredy running). OR start the cassandra using systemctl start cassandra.service (if the server is not running).

Step-4 Check the status either by using sudo service cassandra status or systemctl status cassandra.service.

Note: Once check the system monitor whether cassandra is running there or not.

Try cqlsh now. It'll work.

Note: nano is editor you can use other editors you are comfortable with.

Why would Oracle.ManagedDataAccess not work when Oracle.DataAccess does?

Try to add the path to tnsnames.ora to the config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <oracle.manageddataaccess.client>
    <version number="4.112.3.60">
      <settings>
        <setting name="TNS_ADMIN" value="C:\oracle\product\10.2.0\client_1\NETWORK\ADMIN\" />
      </settings>
    </version>
  </oracle.manageddataaccess.client>
</configuration>

How to use unicode characters in Windows command line?

It's is quite difficult to change the default Codepage of Windows console. When you search the web you find different proposals, however some of them may break your Windows entirely, i.e. your PC does not boot anymore.

The most secure solution is this one: Go to your Registry key HKEY_CURRENT_USER\Software\Microsoft\Command Processor and add String value Autorun = chcp 65001.

Or you can use this small Batch-Script for the most common code pages.

@ECHO off

SET ROOT_KEY="HKEY_CURRENT_USER"


FOR /f "skip=2 tokens=3" %%i in ('reg query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage /v OEMCP') do set OEMCP=%%i

ECHO System default values:

ECHO.
ECHO ...............................................
ECHO Select Codepage 
ECHO ...............................................
ECHO.
ECHO 1 - CP1252
ECHO 2 - UTF-8
ECHO 3 - CP850
ECHO 4 - ISO-8859-1
ECHO 5 - ISO-8859-15
ECHO 6 - US-ASCII
ECHO.
ECHO 9 - Reset to System Default (CP%OEMCP%)
ECHO 0 - EXIT
ECHO.


SET /P  CP="Select a Codepage: "

if %CP%==1 (
    echo Set default Codepage to CP1252
    reg add "%ROOT_KEY%\Software\Microsoft\Command Processor" /v Autorun /t REG_SZ /d "@chcp 1252>nul" /f
) else if %CP%==2 (
    echo Set default Codepage to UTF-8
    reg add "%ROOT_KEY%\Software\Microsoft\Command Processor" /v Autorun /t REG_SZ /d "@chcp 65001>nul" /f
) else if %CP%==3 (
    echo Set default Codepage to CP850
    reg add "%ROOT_KEY%\Software\Microsoft\Command Processor" /v Autorun /t REG_SZ /d "@chcp 850>nul" /f
) else if %CP%==4 (
    echo Set default Codepage to ISO-8859-1
    add "%ROOT_KEY%\Software\Microsoft\Command Processor" /v Autorun /t REG_SZ /d "@chcp 28591>nul" /f
) else if %CP%==5 (
    echo Set default Codepage to ISO-8859-15
    add "%ROOT_KEY%\Software\Microsoft\Command Processor" /v Autorun /t REG_SZ /d "@chcp 28605>nul" /f
) else if %CP%==6 (
    echo Set default Codepage to ASCII
    add "%ROOT_KEY%\Software\Microsoft\Command Processor" /v Autorun /t REG_SZ /d "@chcp 20127>nul" /f
) else if %CP%==9 (
    echo Reset Codepage to System Default
    reg delete "%ROOT_KEY%\Software\Microsoft\Command Processor" /v AutoRun /f
) else if %CP%==0 (
    echo Bye
) else (
    echo Invalid choice
    pause
)

Using @chcp 65001>nul instead of chcp 65001 suppresses the output "Active code page: 65001" you would get every time you start a new command line windows.

A full list of all available number you can get from Code Page Identifiers

Note, the settings will apply only for the current user. If you like to set it for all users, replace line SET ROOT_KEY="HKEY_CURRENT_USER" by SET ROOT_KEY="HKEY_LOCAL_MACHINE"

Most efficient way to append arrays in C#?

Olmo's suggestion is very good, but I'd add this: If you're not sure about the size, it's better to make it a little bigger than a little smaller. When a list is full, keep in mind it will double its size to add more elements.

For example: suppose you will need about 50 elements. If you use a 50 elements size and the final number of elements is 51, you'll end with a 100 sized list with 49 wasted positions.

c# replace \" characters

\ => \\ and " => \"

so Replace("\\\"","")

Where do I configure log4j in a JUnit test class?

I use system properties in log4j.xml:

...
<param name="File" value="${catalina.home}/logs/root.log"/>
...

and start tests with:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.16</version>
    <configuration>
        <systemProperties>
            <property>
                <name>catalina.home</name>
                <value>${project.build.directory}</value>
            </property>
        </systemProperties>
    </configuration>
</plugin>

SSL handshake fails with - a verisign chain certificate - that contains two CA signed certificates and one self-signed certificate

When you see "Verify return code: 19 (self signed certificate in certificate chain)", then, either the servers is really trying to use a self-signed certificate (which a client is never going to be able to verify), or OpenSSL hasn't got access to the necessary root but the server is trying to provide it itself (which it shouldn't do because it's pointless - a client can never trust a server to supply the root corresponding to the server's own certificate).

Again, adding -showcerts will help you diagnose which.

How to undo a git merge with conflicts

If using latest Git,

git merge --abort

else this will do the job in older git versions

git reset --merge

or

git reset --hard

How to Execute SQL Script File in Java?

JDBC does not support this option (although a specific DB driver may offer this). Anyway, there should not be a problem with loading all file contents into memory.

Finding a branch point with Git?

Given that so many of the answers in this thread do not give the answer the question was asking for, here is a summary of the results of each solution, along with the script I used to replicate the repository given in the question.

The log

Creating a repository with the structure given, we get the git log of:

$ git --no-pager log --graph --oneline --all --decorate
* b80b645 (HEAD, branch_A) J - Work in branch_A branch
| *   3bd4054 (master) F - Merge branch_A into branch master
| |\  
| |/  
|/|   
* |   a06711b I - Merge master into branch_A
|\ \  
* | | bcad6a3 H - Work in branch_A
| | * b46632a D - Work in branch master
| |/  
| *   413851d C - Merge branch_A into branch master
| |\  
| |/  
|/|   
* | 6e343aa G - Work in branch_A
| * 89655bb B - Work in branch master
|/  
* 74c6405 (tag: branch_A_tag) A - Work in branch master
* 7a1c939 X - Work in branch master

My only addition, is the tag which makes it explicit about the point at which we created the branch and thus the commit we wish to find.

The solution which works

The only solution which works is the one provided by lindes correctly returns A:

$ diff -u <(git rev-list --first-parent branch_A) \
          <(git rev-list --first-parent master) | \
      sed -ne 's/^ //p' | head -1
74c6405d17e319bd0c07c690ed876d65d89618d5

As Charles Bailey points out though, this solution is very brittle.

If you branch_A into master and then merge master into branch_A without intervening commits then lindes' solution only gives you the most recent first divergance.

That means that for my workflow, I think I'm going to have to stick with tagging the branch point of long running branches, since I can't guarantee that they can be reliably be found later.

This really all boils down to gits lack of what hg calls named branches. The blogger jhw calls these lineages vs. families in his article Why I Like Mercurial More Than Git and his follow-up article More On Mercurial vs. Git (with Graphs!). I would recommend people read them to see why some mercurial converts miss not having named branches in git.

The solutions which don't work

The solution provided by mipadi returns two answers, I and C:

$ git rev-list --boundary branch_A...master | grep ^- | cut -c2-
a06711b55cf7275e8c3c843748daaa0aa75aef54
413851dfecab2718a3692a4bba13b50b81e36afc

The solution provided by Greg Hewgill return I

$ git merge-base master branch_A
a06711b55cf7275e8c3c843748daaa0aa75aef54
$ git merge-base --all master branch_A
a06711b55cf7275e8c3c843748daaa0aa75aef54

The solution provided by Karl returns X:

$ diff -u <(git log --pretty=oneline branch_A) \
          <(git log --pretty=oneline master) | \
       tail -1 | cut -c 2-42
7a1c939ec325515acfccb79040b2e4e1c3e7bbe5

The script

mkdir $1
cd $1
git init
git commit --allow-empty -m "X - Work in branch master"
git commit --allow-empty -m "A - Work in branch master"
git branch branch_A
git tag branch_A_tag     -m "Tag branch point of branch_A"
git commit --allow-empty -m "B - Work in branch master"
git checkout branch_A
git commit --allow-empty -m "G - Work in branch_A"
git checkout master
git merge branch_A       -m "C - Merge branch_A into branch master"
git checkout branch_A
git commit --allow-empty -m "H - Work in branch_A"
git merge master         -m "I - Merge master into branch_A"
git checkout master
git commit --allow-empty -m "D - Work in branch master"
git merge branch_A       -m "F - Merge branch_A into branch master"
git checkout branch_A
git commit --allow-empty -m "J - Work in branch_A branch"

I doubt the git version makes much difference to this, but:

$ git --version
git version 1.7.1

Thanks to Charles Bailey for showing me a more compact way to script the example repository.

How to generate service reference with only physical wsdl file

There are two ways to go about this. You can either use the IDE to generate a WSDL, or you can do it via the command line.

1. To create it via the IDE:

In the solution explorer pane, right click on the project that you would like to add the Service to:

enter image description here

Then, you can enter the path to your service WSDL and hit go:

enter image description here

2. To create it via the command line:

Open a VS 2010 Command Prompt (Programs -> Visual Studio 2010 -> Visual Studio Tools)
Then execute:

WSDL /verbose C:\path\to\wsdl

WSDL.exe will then output a .cs file for your consumption.

If you have other dependencies that you received with the file, such as xsd's, add those to the argument list:

WSDL /verbose C:\path\to\wsdl C:\path\to\some\xsd C:\path\to\some\xsd

If you need VB output, use /language:VB in addition to the /verbose.

React-router v4 this.props.history.push(...) not working

Don't use with Router.

handleSubmit(e){
   e.preventDefault();
   this.props.form.validateFieldsAndScroll((err,values)=>{
      if(!err){
        this.setState({
            visible:false
        });
        this.props.form.resetFields();
        console.log(values.username);
        const path = '/list/';
        this.props.history.push(path);
      }
   })
}

It works well.

Declaring and using MySQL varchar variables

Looks like you forgot the @ in variable declaration. Also I remember having problems with SET in MySql a long time ago.

Try

DECLARE @FOO varchar(7);
DECLARE @oldFOO varchar(7);
SELECT @FOO = '138';
SELECT @oldFOO = CONCAT('0', @FOO);

update mypermits 
   set person = @FOO 
 where person = @oldFOO;

How to make an empty div take space

In building a custom set of layout tags, I found another answer to this problem. Provided here is the custom set of tags and their CSS classes.

HTML

<layout-table>
   <layout-header> 
       <layout-column> 1 a</layout-column>
       <layout-column>  </layout-column>
       <layout-column> 3 </layout-column>
       <layout-column> 4 </layout-column>
   </layout-header>

   <layout-row> 
       <layout-column> a </layout-column>
       <layout-column> a 1</layout-column>
       <layout-column> a </layout-column>
       <layout-column> a </layout-column>
   </layout-row>

   <layout-footer> 
       <layout-column> 1 </layout-column>
       <layout-column>  </layout-column>
       <layout-column> 3 b</layout-column>
       <layout-column> 4 </layout-column>
   </layout-footer>
</layout-table>

CSS

layout-table
{
    display : table;
    clear : both;
    table-layout : fixed;
    width : 100%;
}

layout-table:unresolved
{
    color : red;
    border: 1px blue solid;
    empty-cells : show;
}

layout-header, layout-footer, layout-row 
{
    display : table-row;
    clear : both;   
    empty-cells : show;
    width : 100%;
}

layout-column 
{ 
    display : table-column;
    float : left;
    width : 25%;
    min-width : 25%;
    empty-cells : show;
    box-sizing: border-box;
    /* border: 1px solid white; */
    padding : 1px 1px 1px 1px;
}

layout-row:nth-child(even)
{ 
    background-color : lightblue;
}

layout-row:hover 
{ background-color: #f5f5f5 }

The key here is the Box-Sizing and Padding.

Understanding unique keys for array children in React.js

Warning: Each child in an array or iterator should have a unique "key" prop.

This is a warning as for array items which we are going to iterate over will need a unique resemblance.

React handles iterating component rendering as arrays.

Better way to resolve this is provide index on the array items you are going to iterate over.for example:

class UsersState extends Component
    {
        state = {
            users: [
                {name:"shashank", age:20},
                {name:"vardan", age:30},
                {name:"somya", age:40}
            ]
        }
    render()
        {
            return(
                    <div>
                        {
                            this.state.users.map((user, index)=>{
                                return <UserState key={index} age={user.age}>{user.name}</UserState>
                            })
                        }
                    </div>
                )
        }

index is React built-in props.

Is JavaScript object-oriented?

Javascript is a multi-paradigm language that supports procedural, object-oriented (prototype-based) and functional programming styles.

Here is an article discussing how to do OO in Javascript.

package android.support.v4.app does not exist ; in Android studio 0.8

None of the above solutions worked for me. What finally worked was:

Instead of

import android.support.v4.content.FileProvider;

Use this

import androidx.core.content.FileProvider;

This path is updated as of AndroidX (the repackaged Android Support Library).

Ruby value of a hash key?

How about this?

puts "ok" if hash_variable["key"] == "X"

You can access hash values with the [] operator

Why doesn't indexOf work on an array IE8?

You can use this to replace the function if it doesn't exist:

<script>
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(elt /*, from*/) {
        var len = this.length >>> 0;

        var from = Number(arguments[1]) || 0;
        from = (from < 0) ? Math.ceil(from) : Math.floor(from);
        if (from < 0)
            from += len;

        for (; from < len; from++) {
            if (from in this && this[from] === elt)
                return from;
        }
        return -1;
    };
}
</script>

Comment out HTML and PHP together

I agree that Pascal's solution is the way to go, but for those saying that it adds an extra task to remove the comments, you can use the following comment style trick to simplify your life:

<?php /* ?>
<tr>
      <td><?php echo $entry_keyword; ?></td>
      <td><input type="text" name="keyword" value="<?php echo $keyword; ?>" /></td>
    </tr>
    <tr>
      <td><?php echo $entry_sort_order; ?></td>
      <td><input name="sort_order" value="<?php echo $sort_order; ?>" size="1" /></td>
    </tr>
<?php // */ ?>

In order to stop the code block being commented out, simply change the opening comment to:

<?php //* ?>

How to close Browser Tab After Submitting a Form?

You can try this methods

window.open(location, '_self').close();

Appending values to dictionary in Python

To append entries to the table:

for row in data:
    name = ???     # figure out the name of the drug
    number = ???   # figure out the number you want to append
    drug_dictionary[name].append(number)

To loop through the data:

for name, numbers in drug_dictionary.items():
    print name, numbers

How do I vertically align text in a paragraph?

you could use

    line-height:35px;

You really shouldnt set a height on paragraph as its not good for accessibility (what happens if the user increase text size etc)

Instead use a Div with a hight and the p inside it with the correct line-height:

    <div style="height:35px;"><p style="line-height:35px;">text</p></div>

Create instance of generic type in Java?

You are correct. You can't do new E(). But you can change it to

private static class SomeContainer<E> {
    E createContents(Class<E> clazz) {
        return clazz.newInstance();
    }
}

It's a pain. But it works. Wrapping it in the factory pattern makes it a little more tolerable.

How To change the column order of An Existing Table in SQL Server 2008

This can be an issue when using Source Control and automated deployments to a shared development environment. Where I work we have a very large sample DB on our development tier to work with (a subset of our production data).

Recently I did some work to remove one column from a table and then add some extra ones on the end. I then had to undo my column removal so I re-added it on the end which means the table and all references are correct in the environment but the Source Control automated deployment will no longer work because it complains about the table definition changing.

The real problem here is that the table + indexes are ~120GB and the environment only has ~60GB free so I'll need to either:

a) Rename the existing columns which are in the wrong order, add new columns in the right order, update the data then drop the old columns

OR

b) Rename the table, create a new table with the correct order, insert to the new table from the old and delete from the old as I go along

The SSMS/TFS Schema compare option of using a temp table won't work because there isn't enough room on disc to do it.

I'm not trying to say this is the best way to go about things or that column order really matters, just that I have a scenario where it is an issue and I'm sharing the options I've thought of to fix the issue

How can I mock the JavaScript window object using Jest?

Instead of window use global

it('correct url is called', () => {
  global.open = jest.fn();
  statementService.openStatementsReport(111);
  expect(global.open).toBeCalled();
});

you could also try

const open = jest.fn()
Object.defineProperty(window, 'open', open);

Javascript receipt printing using POS Printer

You could try using https://www.printnode.com which is essentially exactly the service that you are looking for. You download and install a desktop client onto the users computer - https://www.printnode.com/download. You can then discover and print to any printers on that user's computer using their JSON API https://www.printnode.com/docs/api/curl/. They have lots of libs here: https://github.com/PrintNode/

Good ways to manage a changelog using git?

I also made a library for this. It is fully configurable with a Mustache template. That can:

I also made:

More details on Github: https://github.com/tomasbjerre/git-changelog-lib

From command line:

npx git-changelog-command-line -std -tec "
# Changelog

Changelog for {{ownerName}} {{repoName}}.

{{#tags}}
## {{name}}
 {{#issues}}
  {{#hasIssue}}
   {{#hasLink}}
### {{name}} [{{issue}}]({{link}}) {{title}} {{#hasIssueType}} *{{issueType}}* {{/hasIssueType}} {{#hasLabels}} {{#labels}} *{{.}}* {{/labels}} {{/hasLabels}}
   {{/hasLink}}
   {{^hasLink}}
### {{name}} {{issue}} {{title}} {{#hasIssueType}} *{{issueType}}* {{/hasIssueType}} {{#hasLabels}} {{#labels}} *{{.}}* {{/labels}} {{/hasLabels}}
   {{/hasLink}}
  {{/hasIssue}}
  {{^hasIssue}}
### {{name}}
  {{/hasIssue}}

  {{#commits}}
**{{{messageTitle}}}**

{{#messageBodyItems}}
 * {{.}} 
{{/messageBodyItems}}

[{{hash}}](https://github.com/{{ownerName}}/{{repoName}}/commit/{{hash}}) {{authorName}} *{{commitTime}}*

  {{/commits}}

 {{/issues}}
{{/tags}}
"

Or in Jenkins:

enter image description here

What permission do I need to access Internet from an Android application?

just put above line like below

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.avocats.activeavocats"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="9"
    android:targetSdkVersion="16" />

 <uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >


    <activity
        android:name="com.example.exp.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Is there an opposite of include? for Ruby Arrays?

if @players.exclude?(p.name)
    ...
end

ActiveSupport adds the exclude? method to Array, Hash, and String. This is not pure Ruby, but is used by a LOT of rubyists.

Source: Active Support Core Extensions (Rails Guides)

Create a dictionary with list comprehension

In Python 3 and Python 2.7+, dictionary comprehensions look like the below:

d = {k:v for k, v in iterable}

For Python 2.6 or earlier, see fortran's answer.

Redirect pages in JSP?

<%
    String redirectURL = "http://whatever.com/myJSPFile.jsp";
    response.sendRedirect(redirectURL);
%>

How can I refresh a page with jQuery?

Use location.reload():

$('#something').click(function() {
    location.reload();
});

The reload() function takes an optional parameter that can be set to true to force a reload from the server rather than the cache. The parameter defaults to false, so by default the page may reload from the browser's cache.

How to run TypeScript files from command line?

You can use esrun that executes almost instantly a typescript file.

Advantages over ts-node:

  • very fast (use esbuild),
  • you can use ES modules without having to add "types": "module" to your package.json,
  • you can also use it as a replacement to Node to execute modern Javascript with ES modules, decorators, class fields, etc...

How to use a ViewBag to create a dropdownlist?

@Html.DropDownListFor(m => m.Departments.id, (SelectList)ViewBag.Department, "Select", htmlAttributes: new { @class = "form-control" })

Missing Push Notification Entitlement

In my case, even I created a myapp.profile and set it in xcode manually, and when I chose "show in finder" and located the embedded.mobileprovision and checked to make sure aps-environment is there in the file, the error was still there.

I then went to developer center and found that the status of XC: myapp.profile is invalid. I updated it and installed the XC: myapp.profile and it worked fine.

I think xcode is trying to manage the profile and you need to check the provisioning profile when you submit your binary to store, and ensure it is the correct one. And according to other answers it can be caused for various reasons so it can be really annoying.

UPDATE:

Once you've signed with the downloaded profile and confirmed that aps-environment was there when you try to submit to App Store, you should be able to change the profile and code signing entity to automatic and iOS Developer. Hope it can be improved in Xcode 7.

Install specific version using laravel installer

Using composer you can specify the version you want easily by running

composer create-project laravel/laravel="5.1.*" myProject

Using the 5.1.* will ensure that you get all the latest patches in the 5.1 branch.

Proper way to catch exception from JSON.parse

This promise will not resolve if the argument of JSON.parse() can not be parsed into a JSON object.

Promise.resolve(JSON.parse('{"key":"value"}')).then(json => {
    console.log(json);
}).catch(err => {
    console.log(err);
});

Vue.js : How to set a unique ID for each component instance?

Update: Code will throw an error if ._uid property does not exist in the instance so that you can update it to use something custom or new unique id property if provided by Vue.

Although zxzak's answer is great; _uid is not a published api property. To save a headache in case it changes in the future, you can update your code with just one change with a plugin solution like below.

Vue.use({
    install: function(Vue, options) {
        Object.defineProperty(Vue.prototype, "uniqId", {
            get: function uniqId() {
                if ('_uid' in this) {
                   return this._uid;
                }
                throw new Error("_uid property does not exist");
            }
        });
    }
});

How to change PHP version used by composer

Another possibility to make composer think you're using the correct version of PHP is to add to the config section of a composer.json file a platform option, like this:

"config": {
    "platform": {
        "php": "<ver>"
    }
},

Where <ver> is the PHP version of your choice.

Snippet from the docs:

Lets you fake platform packages (PHP and extensions) so that you can emulate a production env or define your target platform in the config. Example: {"php": "7.0.3", "ext-something": "4.0.3"}.

How to load a model from an HDF5 file in Keras?

According to official documentation https://keras.io/getting-started/faq/#how-can-i-install-hdf5-or-h5py-to-save-my-models-in-keras

you can do :

first test if you have h5py installed by running the

import h5py

if you dont have errors while importing h5py you are good to save:

from keras.models import load_model

model.save('my_model.h5')  # creates a HDF5 file 'my_model.h5'
del model  # deletes the existing model

# returns a compiled model
# identical to the previous one
model = load_model('my_model.h5')

If you need to install h5py http://docs.h5py.org/en/latest/build.html

Moving average or running mean

You can calculate a running mean with:

import numpy as np

def runningMean(x, N):
    y = np.zeros((len(x),))
    for ctr in range(len(x)):
         y[ctr] = np.sum(x[ctr:(ctr+N)])
    return y/N

But it's slow.

Fortunately, numpy includes a convolve function which we can use to speed things up. The running mean is equivalent to convolving x with a vector that is N long, with all members equal to 1/N. The numpy implementation of convolve includes the starting transient, so you have to remove the first N-1 points:

def runningMeanFast(x, N):
    return np.convolve(x, np.ones((N,))/N)[(N-1):]

On my machine, the fast version is 20-30 times faster, depending on the length of the input vector and size of the averaging window.

Note that convolve does include a 'same' mode which seems like it should address the starting transient issue, but it splits it between the beginning and end.

Is it possible to play music during calls so that the partner can hear it ? Android

I think this is possible in one case

1.Some of the native music players in android device where handling this,they restrict the music when call is in TelephonyManager.EXTRA_STATE_OFFHOOK (OFFHOOK STATE) so there is no way of playing the background music using native players and some other players like "poweramp music palyer"

2.By using the MediaPlayer class also it is not possible(clearly mentioned in documentation)

3.It is possible only in one case if your developing custom music player(with out using MediaPlayer class) in that implements

AudioManager.OnAudioFocusChangeListener by using this you can get the state of the audiomanager in the below code "focusChange=AUDIOFOCUS_LOSS_TRANSIENT"(this state calls when music is playing in background any incoming call came) this state is completely in developers hand whether to play or pause the music. As according to your requriment as for question you asked if you want to play the music when call is in OFFHOOK STATE dont pause playing music in OFFHOOK STATE .And this is only possible when headset is disabled

AudioManager am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
     
    OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() {
        public void onAudioFocusChange(int focusChange) {
            if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT
                // Pause playback (during incoming call) 
            } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                // Resume playback (incoming call ends)
            } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
                am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
                am.abandonAudioFocus(afChangeListener);
                // Stop playback (when any other app playing music  in that situation current app stop the audio)
            }
        }
    };

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

Convert string to JSON array

Try this piece of code:

try {        
    Log.e("log_tag", "Error in convert String" + result.toString());
    JSONObject json_data = new JSONObject(result);

    String status = json_data.getString("Status");
    {
        String data = json_data.getString("locations");
        JSONArray json_data1 = new JSONArray(data);
        for (int i = 0; i < json_data1.length(); i++) {
            json_data = json_data1.getJSONObject(i);

            String lat = json_data.getString("lat");
            String lng = json_data.getString("long");
        }
    }
}

Export DataTable to Excel with Open Xml SDK in c#

I tried accepted answer and got message saying generated excel file is corrupted when trying to open. I was able to fix it by doing few modifications like adding below line end of the code.

workbookPart.Workbook.Save();

I have posted full code @ Export DataTable to Excel with Open XML in c#

How to print without newline or space?

The new (as of Python 3.x) print function has an optional end parameter that lets you modify the ending character:

print("HELLO", end="")
print("HELLO")

Output:

HELLOHELLO

There's also sep for separator:

print("HELLO", "HELLO", "HELLO", sep="")

Output:

HELLOHELLOHELLO

If you wanted to use this in Python 2.x just add this at the start of your file:

from __future__ import print_function

Activate a virtualenv with a Python script

The simplest solution to run your script under virtualenv's interpreter is to replace the default shebang line with path to your virtualenv's interpreter like so at the beginning of the script:

#!/path/to/project/venv/bin/python

Make the script executable:

chmod u+x script.py

Run the script:

./script.py

Voila!

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

I got this error by putting the <customErrors> tag inside of <system.webServer> instead of <system.web> where it belongs. There was a little squiggle under the <customErrors> tag but I didn't notice it right away.

VBA: How to display an error message just like the standard error message which has a "Debug" button?

First the good news. This code does what you want (please note the "line numbers")

Sub a()
 10:    On Error GoTo ErrorHandler
 20:    DivisionByZero = 1 / 0
 30:    Exit Sub
 ErrorHandler:
 41: If Err.Number <> 0 Then
 42:    Msg = "Error # " & Str(Err.Number) & " was generated by " _
         & Err.Source & Chr(13) & "Error Line: " & Erl & Chr(13) & Err.Description
 43:    MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
 44:    End If
 50:    Resume Next
 60: End Sub

When it runs, the expected MsgBox is shown:

alt text

And now the bad news:
Line numbers are a residue of old versions of Basic. The programming environment usually took charge of inserting and updating them. In VBA and other "modern" versions, this functionality is lost.

However, Here there are several alternatives for "automatically" add line numbers, saving you the tedious task of typing them ... but all of them seem more or less cumbersome ... or commercial.

HTH!

How to convert dataframe into time series?

See this question: Converting data.frame to xts order.by requires an appropriate time-based object, which suggests looking at argument to order.by,

Currently acceptable classes include: ‘Date’, ‘POSIXct’, ‘timeDate’, as well as ‘yearmon’ and ‘yearqtr’ where the index values remain unique.

And further suggests an explicit conversion using order.by = as.POSIXct,

df$Date <- as.POSIXct(strptime(df$Date,format),tz="UTC")
xts(df[, -1], order.by=as.POSIXct(df$Date))

Where your format is assigned elswhere,

format <- "%m/%d/%Y" #see strptime for details

what does "dead beef" mean?

It's a made up expression using only the letters A-F, often used when a recognisable hexadecimal number is required. Some systems use it for various purposes such as showing memory which has been freed and should not be referenced again. In a debugger this value showing up could be a sign that you have made an error. From Wikipedia:

0xDEADBEEF ("dead beef") is used by IBM RS/6000 systems, Mac OS on 32-bit PowerPC processors and the Commodore Amiga as a magic debug value. On Sun Microsystems' Solaris, it marks freed kernel memory. On OpenVMS running on Alpha processors, DEAD_BEEF can be seen by pressing CTRL-T.

The number 0xDEADBEEF is equal to the less recognisable decimal number 3735928559 (unsigned) or -559038737 (signed).

Is there a way to suppress JSHint warning for one given line?

As you can see in the documentation of JSHint you can change options per function or per file. In your case just place a comment in your file or even more local just in the function that uses eval:

/*jshint evil:true */

function helloEval(str) {
    /*jshint evil:true */
    eval(str);
}

multiprocessing: How do I share a dict among multiple processes?

Maybe you can try pyshmht, sharing memory based hash table extension for Python.

Notice

  1. It's not fully tested, just for your reference.

  2. It currently lacks lock/sem mechanisms for multiprocessing.

Define constant variables in C++ header

You could simply define a series of const ints in a header file:

// Constants.h
#if !defined(MYLIB_CONSTANTS_H)
#define MYLIB_CONSTANTS_H 1

const int a = 100;
const int b = 0x7f;

#endif

This works because in C++ a name at namespace scope (including the global namespace) that is explicitly declared const and not explicitly declared extern has internal linkage, so these variables would not cause duplicate symbols when you link together translation units. Alternatively you could explicitly declare the constants as static.

static const int a = 100;
static const int b = 0x7f;

This is more compatible with C and more readable for people that may not be familiar with C++ linkage rules.

If all the constants are ints then another method you could use is to declare the identifiers as enums.

enum mylib_constants {
    a = 100;
    b = 0x7f;
};

All of these methods use only a header and allow the declared names to be used as compile time constants. Using extern const int and a separate implementation file prevents the names from being used as compile time constants.


Note that the rule that makes certain constants implicitly internal linkage does apply to pointers, exactly like constants of other types. The tricky thing though is that marking a pointer as const requires syntax a little different that most people use to make variables of other types const. You need to do:

int * const ptr;

to make a constant pointer, so that the rule will apply to it.

Also note that this is one reason I prefer to consistently put const after the type: int const instead of const int. I also put the * next to the variable: i.e. int *ptr; instead of int* ptr; (compare also this discussion).

I like to do these sorts of things because they reflect the general case of how C++ really works. The alternatives (const int, int* p) are just special cased to make some simple things more readable. The problem is that when you step out of those simple cases, the special cased alternatives become actively misleading.

So although the earlier examples show the common usage of const, I would actually recommend people write them like this:

int const a = 100;
int const b = 0x7f;

and

static int const a = 100;
static int const b = 0x7f;

Wrap text in <td> tag

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
    border: 1px solid black;
}
</style>
</head>
<body>

<table>
  <tr>
    <th>Poem</th>
    <th>Poem</th>
  </tr>
  <tr>
    <td nowrap>Never increase, beyond what is necessary, the number of entities required to explain anything</td>
    <td>Never increase, beyond what is necessary, the number of entities required to explain anything</td>
  </tr>
</table>

<p>The nowrap attribute is not supported in HTML5. Use CSS instead.</p>

</body>
</html>

How to set the authorization header using curl

If you don't have the token at the time of the call is made, You will have to make two calls, one to get the token and the other to extract the token form the response, pay attention to

grep token | cut -d, -f1 | cut -d\" -f4

as it is the part which is dealing with extracting the token from the response.

echo "Getting token response and extracting token"    
def token = sh (returnStdout: true, script: """
    curl -S -i -k -X POST https://www.example.com/getToken -H \"Content-Type: application/json\" -H \"Accept: application/json\" -d @requestFile.json | grep token | cut -d, -f1 | cut -d\\" -f4
""").split()

After extracting the token you can use the token to make subsequent calls as follows.

echo "Token : ${token[-1]}"       
echo "Making calls using token..."       
curl -S -i -k  -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer ${token[-1]}" https://www.example.com/api/resources 

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

add async in main()

and await before

follow my code

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  var fsconnect = FirebaseFirestore.instance;

  myget() async {
    var d = await fsconnect.collection("students").get();
    // print(d.docs[0].data());

    for (var i in d.docs) {
      print(i.data());
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(
        title: Text('Firebase Firestore App'),
      ),
      body: Column(
        children: <Widget>[
          RaisedButton(
            child: Text('send data'),
            onPressed: () {
              fsconnect.collection("students").add({
                'name': 'sarah',
                'title': 'xyz',
                'email': '[email protected]',
              });
              print("send ..");
            },
          ),
          RaisedButton(
            child: Text('get data'),
            onPressed: () {
              myget();
              print("get data ...");
            },
          )
        ],
      ),
    ));
  }
}

javascript setTimeout() not working

Please change your code as follows:

<script>
    var button = document.getElementById("reactionTester");
    var start = document.getElementById("start");
    function init() {
        var startInterval/*in milliseconds*/ = Math.floor(Math.random()*30)*1000;
        setTimeout(startTimer,startInterval); 
    }
    function startTimer(){
        document.write("hey");
    }
</script>

See if that helps. Basically, the difference is references the 'startTimer' function instead of executing it.

Restoring Nuget References?

  1. Copy packages.config file of project and applies all version modify
  2. Unistall all package and remove depencies

    $packages = Get-Package -ProjectName [nameOfProjectToRestore]
    foreach ($package in $packages) {
        uninstall-package  -projectname [nameOfProjectToRestore] -id $package.Id -version $package.version -RemoveDependencies -force ;
    }
    
  3. Clear the packages folder in the root of project

  4. Copy the modifies package.config to root folder of website

  5. Run this code to restore the project

    $packages = Get-Package -ProjectName [nameOfProjectToRestore]
    foreach ($package in $packages) {
        uninstall-package  -projectname [nameOfProjectToRestore] -id $package.Id -version $package.version -RemoveDependencies -force ;
    }
    foreach ($package in $packages) {
        install-package  $package.Id -ProjectName [nameOfProjectToRestore] -Version $package.Version
    }
    

Easiest way to flip a boolean value?

Just because I like to question code. I propose that you can also make use of the ternary by doing something like this:

Example:

bool flipValue = false;
bool bShouldFlip = true;
flipValue = bShouldFlip ? !flipValue : flipValue;

Log4net does not write the log in the log file

Use this FAQ page: Apache log4net Frequently Asked Questions

About 3/4 of the way down it tells you how to enable log4net debugging by using application tracing. This will tell you where your issue is.

The basics are:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="log4net.Internal.Debug" value="true"/>
    </appSettings>
</configuration>

And you see the trace in the standard output

How do I populate a JComboBox with an ArrayList?

I believe you can create a new Vector using your ArrayList and pass that to the JCombobox Constructor.

JComboBox<String> combobox = new JComboBox<String>(new Vector<String>(myArrayList));

my example is only strings though.

How to get datetime in JavaScript?

You can convert Date to almost any format using the Snippet I have added below.

Code:

dateFormat(new Date(),"dd/mm/yy h:MM TT")
//"20/06/14 6:49 PM"

Other examples

// Can also be used as a standalone function
dateFormat(new Date(), "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM

dateFormat(new Date(),"dddd d mmmm yyyy")
//Monday 2 June 2014"

Snippet:

Add following code taken from this link into your code.

var dateFormat = function () {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
        timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
        timezoneClip = /[^-+\dA-Z]/g,
        pad = function (val, len) {
            val = String(val);
            len = len || 2;
            while (val.length < len) val = "0" + val;
            return val;
        };

    // Regexes and supporting functions are cached through closure
    return function (date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
            d = date[_ + "Date"](),
            D = date[_ + "Day"](),
            m = date[_ + "Month"](),
            y = date[_ + "FullYear"](),
            H = date[_ + "Hours"](),
            M = date[_ + "Minutes"](),
            s = date[_ + "Seconds"](),
            L = date[_ + "Milliseconds"](),
            o = utc ? 0 : date.getTimezoneOffset(),
            flags = {
                d:    d,
                dd:   pad(d),
                ddd:  dF.i18n.dayNames[D],
                dddd: dF.i18n.dayNames[D + 7],
                m:    m + 1,
                mm:   pad(m + 1),
                mmm:  dF.i18n.monthNames[m],
                mmmm: dF.i18n.monthNames[m + 12],
                yy:   String(y).slice(2),
                yyyy: y,
                h:    H % 12 || 12,
                hh:   pad(H % 12 || 12),
                H:    H,
                HH:   pad(H),
                M:    M,
                MM:   pad(M),
                s:    s,
                ss:   pad(s),
                l:    pad(L, 3),
                L:    pad(L > 99 ? Math.round(L / 10) : L),
                t:    H < 12 ? "a"  : "p",
                tt:   H < 12 ? "am" : "pm",
                T:    H < 12 ? "A"  : "P",
                TT:   H < 12 ? "AM" : "PM",
                Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
                o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
                S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
            };

        return mask.replace(token, function ($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
}();

// Some common format strings
dateFormat.masks = {
    "default":      "ddd mmm dd yyyy HH:MM:ss",
    shortDate:      "m/d/yy",
    mediumDate:     "mmm d, yyyy",
    longDate:       "mmmm d, yyyy",
    fullDate:       "dddd, mmmm d, yyyy",
    shortTime:      "h:MM TT",
    mediumTime:     "h:MM:ss TT",
    longTime:       "h:MM:ss TT Z",
    isoDate:        "yyyy-mm-dd",
    isoTime:        "HH:MM:ss",
    isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
        "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
        "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
    ],
    monthNames: [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
        "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
    ]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
    return dateFormat(this, mask, utc);
};

Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

In Eclipse Mars.2 Release (4.5.2):
Project Explorer -> Context menu -> Properties -> JavaBuildPath -> Libraries
select JRE... and press Edit: Switch to Workspace JRE (jdk1.8.0_77)

Works for me.

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

Open terminal. Type the following

echo>sure.sh
chmod 700 sure.sh

Paste this inside sure.sh

#!\bin\bash

echo -n 'Are you sure? [Y/n] '
read yn

if [ "$yn" = "n" ]; then
    exit 1
fi

exit 0

Close sure.sh and type this in terminal.

alias sure='~/sure&&'

Now, if you type sure before typing the command it will give you an are you sure prompt before continuing the command.

Hope this is helpful!

Best Practices for mapping one object to another

/// <summary>
/// map properties
/// </summary>
/// <param name="sourceObj"></param>
/// <param name="targetObj"></param>
private void MapProp(object sourceObj, object targetObj)
{
    Type T1 = sourceObj.GetType();
    Type T2 = targetObj.GetType();

    PropertyInfo[] sourceProprties = T1.GetProperties(BindingFlags.Instance | BindingFlags.Public);
    PropertyInfo[] targetProprties = T2.GetProperties(BindingFlags.Instance | BindingFlags.Public);

   foreach (var sourceProp in sourceProprties)
   {
       object osourceVal = sourceProp.GetValue(sourceObj, null);
       int entIndex = Array.IndexOf(targetProprties, sourceProp);
       if (entIndex >= 0)
       {
           var targetProp = targetProprties[entIndex];
           targetProp.SetValue(targetObj, osourceVal);
       }
   }
}

How to get an IFrame to be responsive in iOS Safari?

I needed a cross-browser solution. Requirements were:

  • needed to work on both iOS and elsewhere
  • don't have access to the content in the iFrame
  • need it to scroll!

Building off what I learned from @Idra regarding scrolling="no" on iOS and this post about fitting iFrame content to the screen in iOS here's what I ended up with. Hope it helps someone =)

HTML

<div id="url-wrapper"></div>

CSS

html, body{
    height: 100%;
}

#url-wrapper{
    margin-top: 51px;
    height: 100%;
}

#url-wrapper iframe{
    height: 100%;
    width: 100%;
}

#url-wrapper.ios{
    overflow-y: auto;
    -webkit-overflow-scrolling:touch !important;
    height: 100%;
}

#url-wrapper.ios iframe{
    height: 100%;
    min-width: 100%;
    width: 100px;
    *width: 100%;
}

JS

function create_iframe(url){

    var wrapper = jQuery('#url-wrapper');

    if(navigator.userAgent.match(/(iPod|iPhone|iPad)/)){
        wrapper.addClass('ios');
        var scrolling = 'no';
    }else{
        var scrolling = 'yes';
    }

    jQuery('<iframe>', {
        src: url,
        id:  'url',
        frameborder: 0,
        scrolling: scrolling
    }).appendTo(wrapper);

}

How do I get data from a table?

This is how I accomplished reading a table in javascript. Basically I drilled down into the rows and then I was able to drill down into the individual cells for each row. This should give you an idea

//gets table
var oTable = document.getElementById('myTable');

//gets rows of table
var rowLength = oTable.rows.length;

//loops through rows    
for (i = 0; i < rowLength; i++){

   //gets cells of current row
   var oCells = oTable.rows.item(i).cells;

   //gets amount of cells of current row
   var cellLength = oCells.length;

   //loops through each cell in current row
   for(var j = 0; j < cellLength; j++){
      /* get your cell info here */
      /* var cellVal = oCells.item(j).innerHTML; */
   }
}

UPDATED - TESTED SCRIPT

<table id="myTable">
    <tr>
        <td>A1</td>
        <td>A2</td>
        <td>A3</td>
    </tr>
    <tr>
        <td>B1</td>
        <td>B2</td>
        <td>B3</td>
    </tr>
</table>
<script>
    //gets table
    var oTable = document.getElementById('myTable');

    //gets rows of table
    var rowLength = oTable.rows.length;

    //loops through rows    
    for (i = 0; i < rowLength; i++){

      //gets cells of current row  
       var oCells = oTable.rows.item(i).cells;

       //gets amount of cells of current row
       var cellLength = oCells.length;

       //loops through each cell in current row
       for(var j = 0; j < cellLength; j++){

              // get your cell info here

              var cellVal = oCells.item(j).innerHTML;
              alert(cellVal);
           }
    }
</script>

jQuery: Load Modal Dialog Contents via Ajax

$(function ()    {
    $('<div>').dialog({
        modal: true,
        open: function ()
        {
            $(this).load('Sample.htm');
        },         
        height: 400,
        width: 400,
        title: 'Dynamically Loaded Page'
    });
});

http://www.devcurry.com/2010/06/load-page-dynamically-inside-jquery-ui.html

Import Package Error - Cannot Convert between Unicode and Non Unicode String Data Type

Follow the below steps to avoid (cannot convert between unicode and non-unicode string data types) this error

i) Add the Data conversion Transformation tool to your DataFlow.
ii) To open the DataFlow Conversion and select [string DT_STR] datatype.
iii) Then go to Destination flow, select Mapping.
iv) change your i/p name to copy of the name.

How to determine whether a year is a leap year?

An alternative one liner:

((((y % 4) + (int((y - (y % 100)) / y) * ((y % 400) / 100))) - 1) < 0)

This was something that I put together for fun (?) that is also 1:1 compatible with C.

(y % 4) >>>It first checks if the year is a leap year via the typical mod-4 check.

(int((y - (y % 100)) / y) >>>It then accounts for those years divisible by 100. If the year is evenly divisible by 100, this will result in a value of 1, otherwise it will result in a value of 0.

((y % 400) / 100))) >>>Next, the year is divided by 400 (and subsequently 100, to return 1, 2, or 3 if it is not.

These two values

(int(y - (y % 100)) / y)

&

((y % 400) / 100)))

are then multiplied together. If the year is not divisible by 100, this will always equal 0, otherwise if it is divisible by 100, but not by 400, it will result in 1, 2, or 3. If it is divisible by both 100 and 400, it will result in 0.

This value is added to (y % 4), which will only be equal to 0 if the year is a leap year after accounting for the edge-cases.

Finally, 1 is subtracted from this remaining value, resulting in -1 if the year is a leap year, and either 0, 1, or 2 if it is not. This value is compared against 0 with the less-than operator. If the year is a leap year this will result in True (or 1, if used in C), otherwise it will return False (or 0, if used in C).

Please note: this code is horribly inefficient, incredibly unreadable, and a detriment to any code attempting to follow proper practices. This was an exercise of mine to see if I could do so, and nothing more.

Further, be aware that ZeroDivisionErrors are a consequence of the input year equaling 0, and must be accounted for.

For example, a VERY basic timeit comparison of 1000 executions shows that, when compared against an equivalent codeblock utilizing simple if-statements and the modulus operator, this one-liner is roughly 5 times slower than its if-block equivalent.

That being said, I do find it highly entertaining!

How to add a margin to a table row <tr>

Because margin is ignored on tr, I usually use a workaround, by setting a transparent border-bottom or border-top and setting the background-clip property to padding-box so the background-color does not get painted underneath the border.

table {
   border-collapse: collapse; /* [1] */
}

th, td {
  border-bottom: 5px solid transparent; /* [2] */
  background-color: gold; /* [3] */
  background-clip: padding-box; /* [4] */
}
  1. Makes sure cells share a common border, but is completely optional. The solution works without it.
  2. The 5px value represents the margin that you want to achieve
  3. Sets the background-color of your row/cell
  4. Makes sure the background get not painted underneath the border

see a demo here: http://codepen.io/meodai/pen/MJMVNR?editors=1100

background-clip is supported in all modern browser. (And IE9+)

Alternatively you could use a border-spacing. But this will not work with border-collapse set to collapse.

Add another class to a div

Use Element.classList

document.getElementById('hello').classList.add('someClass');

The .add method will only add the class if it doesn't already exist on the element. So no need to worry about duplicate class names.

Is there a way to define a min and max value for EditText in Android?

There is a small error in Pratik's code. For instance, if a value is 10 and you add a 1 at the beginning to make 110, the filter function would treat the new value as 101.

See below for a fix to this:

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
    try {
        // Removes string that is to be replaced from destination
        // and adds the new string in.
        String newVal = dest.subSequence(0, dstart)
                // Note that below "toString()" is the only required:
                + source.subSequence(start, end).toString()
                + dest.subSequence(dend, dest.length());
        int input = Integer.parseInt(newVal);
        if (isInRange(min, max, input))
            return null;
    } catch (NumberFormatException nfe) { }
    return "";
}

NSDictionary to NSArray?

In Swift 4:

let dict = ["Item1":2.4, "Item2": 5.4, "Item3" : 6.5]

let array = Array(dict.values)

How do I use Linq to obtain a unique list of properties from a list of objects?

        int[] numbers = {1,2,3,4,5,3,6,4,7,8,9,1,0 };
        var nonRepeats = (from n in numbers select n).Distinct();


        foreach (var d in nonRepeats)
        {

            Response.Write(d);
        }

OUTPUT

1234567890

Ruby 'require' error: cannot load such file

The problem is that require does not load from the current directory. This is what I thought, too but then I found this thread. For example I tried the following code:

irb> f = File.new('blabla.rb')
=> #<File:blabla.rb>
irb> f.read
=> "class Tokenizer\n    def self.tokenize(string)\n        return string.split(
\" \")\n    end\nend\n"
irb> require f
LoadError: cannot load such file -- blabla.rb
        from D:/dev/Ruby193/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `req
uire'
        from D:/dev/Ruby193/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `req
uire'
        from (irb):24
        from D:/dev/Ruby193/bin/irb:12:in `<main>'

As it can be seen it read the file ok, but I could not require it (the path was not recognized). and here goes code that works:

irb f = File.new('D://blabla.rb')
=> #<File:D://blabla.rb>
irb f.read
=> "class Tokenizer\n    def self.tokenize(string)\n        return string.split(
\" \")\n    end\nend\n"
irb> require f
=> true

As you can see if you specify the full path the file loads correctly.