Programs & Examples On #Collectionviewsource

The Extensible Application Markup Language (XAML) proxy of a CollectionView class.

Error: the entity type requires a primary key

None of the answers worked until I removed the HasNoKey() method from the entity. Dont forget to remove this from your data context or the [Key] attribute will not fix anything.

An error occurred while updating the entries. See the inner exception for details

Click "View Detail..." a window will open where you can expand the "Inner Exception" my guess is that when you try to delete the record there is a reference constraint violation. The inner exception will give you more information on that so you can modify your code to remove any references prior to deleting the record.

enter image description here

ListBox vs. ListView - how to choose for data binding

A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.

If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).

Viewing full version tree in git

if you happen to not have a graphical interface available you can also print out the commit graph on the command line:

git log --oneline --graph --decorate --all

if this command complains with an invalid option --oneline, use:

git log --pretty=oneline --graph --decorate --all

How do you run a command for each line of a file?

If you know you don't have any whitespace in the input:

xargs chmod 755 < file.txt

If there might be whitespace in the paths, and if you have GNU xargs:

tr '\n' '\0' < file.txt | xargs -0 chmod 755

How to download all dependencies and packages to directory

# aptitude clean
# aptitude --download-only install <your_package_here>
# cp /var/cache/apt/archives/*.deb <your_directory_here>

Finding length of char array

If you are expecting 4 as output then try this:

char a[]={0x00,0xdc,0x01,0x04};

How to view DLL functions?

Without telling us what language this dll/assembly is from, we can only guess.

So how about .NET Reflector

Programmatically Lighten or Darken a hex color (or rgb, and blend colors)

I've long wanted to be able to produce tints/shades of colours, here is my JavaScript solution:

const varyHue = function (hueIn, pcIn) {
    const truncate = function (valIn) {
        if (valIn > 255) {
            valIn = 255;
        } else if (valIn < 0)  {
            valIn = 0;
        }
        return valIn;
    };

    let red   = parseInt(hueIn.substring(0, 2), 16);
    let green = parseInt(hueIn.substring(2, 4), 16);
    let blue  = parseInt(hueIn.substring(4, 6), 16);
    let pc    = parseInt(pcIn, 10);    //shade positive, tint negative
    let max   = 0;
    let dif   = 0;

    max = red;

    if (pc < 0) {    //tint: make lighter
        if (green < max) {
            max = green;
        }

        if (blue < max) {
            max = blue;
        }

        dif = parseInt(((Math.abs(pc) / 100) * (255 - max)), 10);

        return leftPad(((truncate(red + dif)).toString(16)), '0', 2)  + leftPad(((truncate(green + dif)).toString(16)), '0', 2) + leftPad(((truncate(blue + dif)).toString(16)), '0', 2);
    } else {    //shade: make darker
        if (green > max) {
            max = green;
        }

        if (blue > max) {
            max = blue;
        }

        dif = parseInt(((pc / 100) * max), 10);

        return leftPad(((truncate(red - dif)).toString(16)), '0', 2)  + leftPad(((truncate(green - dif)).toString(16)), '0', 2) + leftPad(((truncate(blue - dif)).toString(16)), '0', 2);
    }
};

Decompile an APK, modify it and then recompile it

The answers are already kind of outdated or not complete. This maybe works for non-protected apks (no Proguard), but nowadays nobody deploys an unprotected apk. The way I was able to modify a (my) well-protected apk (Proguard, security check which checks for "hacking tools", security check, which checks if the app is repackaged with debug mode,...) is via apktool as already mentioned by other ones here. But nobody explained, that you have to sign the app again.

apktool d app.apk
//generates a folder with smali bytecode files. 

//Do something with it.

apktool b [folder name] -o modified.apk
//generates the modified apk.

//and then
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore ~/.android/debug.keystore modified.apk androiddebugkey
//signs the app the the debug key (the password is android)

//this apk can be installed on a device.

In my test, the original release apk had no logging. After I decompiled with apktool I exchanged a full byte code file without logging by a full byte code file with logging, re-compiled and signed it and I was able to install it on my device. Afterwards I was able to see the logs in Android Studio as I connected the app to it.

In my opinion, decompiling with dex2jar and JD-GUI is only helpful to get a better understanding what the classes are doing, just for reading purposes. But since everything is proguarded, I'm not sure that you can ever re-compile this half-baked Java code to a working apk. If so, please let me know. I think, the only way is to manipulate the byte code itself as mentioned in this example.

How to check for a JSON response using RSpec?

Simple and easy to way to do this.

# set some variable on success like :success => true in your controller
controller.rb
render :json => {:success => true, :data => data} # on success

spec_controller.rb
parse_json = JSON(response.body)
parse_json["success"].should == true

Closing Bootstrap modal onclick

Close the modal with universal $().hide() method:

$('#product-options').hide();

Session variables in ASP.NET MVC

Great answers from the guys but I would caution you against always relying on the Session. It is quick and easy to do so, and of course would work but would not be great in all cicrumstances.

For example if you run into a scenario where your hosting doesn't allow session use, or if you are on a web farm, or in the example of a shared SharePoint application.

If you wanted a different solution you could look at using an IOC Container such as Castle Windsor, creating a provider class as a wrapper and then keeping one instance of your class using the per request or session lifestyle depending on your requirements.

The IOC would ensure that the same instance is returned each time.

More complicated yes, if you need a simple solution just use the session.

Here are some implementation examples below out of interest.

Using this method you could create a provider class along the lines of:

public class CustomClassProvider : ICustomClassProvider
{
    public CustomClassProvider(CustomClass customClass)
    { 
        CustomClass = customClass;
    }

    public string CustomClass { get; private set; }
}

And register it something like:

public void Install(IWindsorContainer container, IConfigurationStore store)
{
    container.Register(
            Component.For<ICustomClassProvider>().UsingFactoryMethod(
                () => new CustomClassProvider(new CustomClass())).LifestylePerWebRequest());
    }

Python: list of lists

When you run the code

listoflists.append((list, list[0]))

You are not (as I think you expect) adding a copy of list to the end of listoflists. What you are doing is adding a reference to list to the end of listoflists. Thus, every time you update list, it updates every reference to list, which in this case, is every item in listoflists

What you could do instead is something like this:

listoflists = []
for i in range(1, 10):
    listoflists.append((range(i), 0))

how to toggle attr() in jquery

$(".list-toggle").click(function() {
    $(this).attr('colspan') ? 
    $(this).removeAttr('colspan') : $(this).attr('colspan', 6);
});

How to position one element relative to another with jQuery?

tl;dr: (try it here)

If you have the following HTML:

<div id="menu" style="display: none;">
   <!-- menu stuff in here -->
   <ul><li>Menu item</li></ul>
</div>

<div class="parent">Hover over me to show the menu here</div>

then you can use the following JavaScript code:

$(".parent").mouseover(function() {
    // .position() uses position relative to the offset parent, 
    var pos = $(this).position();

    // .outerWidth() takes into account border and padding.
    var width = $(this).outerWidth();

    //show the menu directly over the placeholder
    $("#menu").css({
        position: "absolute",
        top: pos.top + "px",
        left: (pos.left + width) + "px"
    }).show();
});

But it doesn't work!

This will work as long as the menu and the placeholder have the same offset parent. If they don't, and you don't have nested CSS rules that care where in the DOM the #menu element is, use:

$(this).append($("#menu"));

just before the line that positions the #menu element.

But it still doesn't work!

You might have some weird layout that doesn't work with this approach. In that case, just use jQuery.ui's position plugin (as mentioned in an answer below), which handles every conceivable eventuality. Note that you'll have to show() the menu element before calling position({...}); the plugin can't position hidden elements.

Update notes 3 years later in 2012:

(The original solution is archived here for posterity)

So, it turns out that the original method I had here was far from ideal. In particular, it would fail if:

  • the menu's offset parent is not the placeholder's offset parent
  • the placeholder has a border/padding

Luckily, jQuery introduced methods (position() and outerWidth()) way back in 1.2.6 that make finding the right values in the latter case here a lot easier. For the former case, appending the menu element to the placeholder works (but will break CSS rules based on nesting).

Convert decimal to binary in python

Without the 0b in front:

"{0:b}".format(int)

Starting with Python 3.6 you can also use formatted string literal or f-string, --- PEP:

f"{int:b}"

Change color inside strings.xml

Use CDATA in the below way for formatting your text

<resources>
<string name="app_name">DemoShareActionButton</string>
<string name="intro_message">
    <b>
    <![CDATA[ This sample shows you how a provide a context-sensitive ShareActionProvider.
    ]]>
    </b>
    </string>

Just add any tag you want before the <![CDATA[ and you will get your proper output.

MySQL TEXT vs BLOB vs CLOB

TEXT is a data-type for text based input. On the other hand, you have BLOB and CLOB which are more suitable for data storage (images, etc) due to their larger capacity limits (4GB for example).

As for the difference between BLOB and CLOB, I believe CLOB has character encoding associated with it, which implies it can be suited well for very large amounts of text.

BLOB and CLOB data can take a long time to retrieve, relative to how quick data from a TEXT field can be retrieved. So, use only what you need.

Eclipse Error: "Failed to connect to remote VM"

Another possibility is that the debug agent is binding to the wrong network interface.

I've just seen this when trying to debug a Windows 10 JVM inside a VirtualBox VM, and I'm trying to connect from Eclipse running on the VirtualBox host. In my case, the agent only bound to the 127.0.0.1 interface.

To fix, you can qualify the address including the IP of the interface you want to bind to. For example:

java -agentlib:jdwp=transport=dt_socket,server=y,address=192.168.0.5:8000,suspend=n <other arguments>

C - Convert an uppercase letter to lowercase

One way to make sure it is correct is by using character instead of ascii code.

if ((a >= 65) && (a <= 90))

what you want is to lower a case. it's better to use something like if (a >= 'A' && a <= 'Z') . You don't have to remind all ascii code :)

Converting Decimal to Binary Java

//converts decimal to binary string
String convertToBinary(int decimalNumber){  
    String binary="";
    while(decimalNumber>0){
        int remainder=decimalNumber%2;
        //line below ensures the remainders are reversed
        binary=remainder+binary;
        decimalNumber=decimalNumber/2;
    }
    return binary;

}

Simple jQuery, PHP and JSONP example?

More Suggestion

JavaScript:

$.ajax({
        url: "http://FullUrl",
        dataType: 'jsonp',
        success: function (data) {

            //Data from the server in the in the variable "data"
            //In the form of an array

        }

});

PHP CallBack:

<?php

$array = array(
     '0' => array('fullName' => 'Meni Samet', 'fullAdress' => 'New York, NY'),
     '1' => array('fullName' => 'Test 2', 'fullAdress' => 'Paris'),
);

if(isset ($_GET['callback']))
{
    header("Content-Type: application/json");

    echo $_GET['callback']."(".json_encode($array).")";

}
?>

Conversion hex string into ascii in bash command line

You can use xxd:

$cat hex.txt
68 65 6c 6c 6f
$cat hex.txt | xxd -r -p
hello

Maven Java EE Configuration Marker with Java Server Faces 1.2

I have encountered this with Maven projects too. This is what I had to do to get around the problem:

First update your web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
                    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
                    version="3.0">
<display-name>Servlet 3.0 Web Application</display-name>

Then right click on your project and select Properties -> Project Facets In there you will see the version of your Dynamic Web Module. This needs to change from version 2.3 or whatever to version 2.5 or above (I chose 3.0).

However to do this I had to uncheck the tick box for Dynamic Web Module -> Apply, then do a Maven Update on the project. Go back into the Project Facets window and it should already match your web.xml configuration - 3.0 in my case. You should be able to change it if not.

If this does not work for you then try right-clicking on the Dynamic Web Module Facet and select change version (and ensure it is not locked).

Or you can follow this steps:

  1. Window > Show View > Other > General > navigator
  2. There is a .settings folder under your project directory
  3. Change the dynamic web module version in this line to 3.0
  4. Change the Java version in this line to 1.5 or higher

don't forget to update your project

Hope that works!

how to calculate percentage in python

def percentage_match(mainvalue,comparevalue):
    if mainvalue >= comparevalue:
        matched_less = mainvalue - comparevalue
        no_percentage_matched = 100 - matched_less*100.0/mainvalue
        no_percentage_matched = str(no_percentage_matched) + ' %'
        return no_percentage_matched 
    else:
        print('please checkout your value')

print percentage_match(100,10)
Ans = 10.0 %

open resource with relative path in Java

@GianCarlo: You can try calling System property user.dir that will give you root of your java project and then do append this path to your relative path for example:

String root = System.getProperty("user.dir");
String filepath = "/path/to/yourfile.txt"; // in case of Windows: "\\path \\to\\yourfile.txt
String abspath = root+filepath;



// using above path read your file into byte []
File file = new File(abspath);
FileInputStream fis = new FileInputStream(file);
byte []filebytes = new byte[(int)file.length()];
fis.read(filebytes);

Declaring variable workbook / Worksheet vba

Third solution: I would set ws to a sheet of workbook wb as the use of Sheet("name") always refers to the active workbook, which might change as your code develops.

sub kl() 

    Dim wb As Workbook
    Dim ws As Worksheet

    Set wb = ActiveWorkbook
    'be aware as this might produce an error, if Shet "name" does not exist
    Set ws = wb.Sheets("name")
    ' if wb is other than the active workbook
    wb.activate
    ws.Select

End Sub

Any way to return PHP `json_encode` with encode UTF-8 and not Unicode?

This function found here, works fine for me

function jsonRemoveUnicodeSequences($struct) {
   return preg_replace("/\\\\u([a-f0-9]{4})/e", "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode($struct));
}

How to copy from CSV file to PostgreSQL table with headers in CSV file?

I have been using this function for a while with no problems. You just need to provide the number columns there are in the csv file, and it will take the header names from the first row and create the table for you:

create or replace function data.load_csv_file
    (
        target_table  text, -- name of the table that will be created
        csv_file_path text,
        col_count     integer
    )

    returns void

as $$

declare
    iter      integer; -- dummy integer to iterate columns with
    col       text; -- to keep column names in each iteration
    col_first text; -- first column name, e.g., top left corner on a csv file or spreadsheet

begin
    set schema 'data';

    create table temp_table ();

    -- add just enough number of columns
    for iter in 1..col_count
    loop
        execute format ('alter table temp_table add column col_%s text;', iter);
    end loop;

    -- copy the data from csv file
    execute format ('copy temp_table from %L with delimiter '','' quote ''"'' csv ', csv_file_path);

    iter := 1;
    col_first := (select col_1
                  from temp_table
                  limit 1);

    -- update the column names based on the first row which has the column names
    for col in execute format ('select unnest(string_to_array(trim(temp_table::text, ''()''), '','')) from temp_table where col_1 = %L', col_first)
    loop
        execute format ('alter table temp_table rename column col_%s to %s', iter, col);
        iter := iter + 1;
    end loop;

    -- delete the columns row // using quote_ident or %I does not work here!?
    execute format ('delete from temp_table where %s = %L', col_first, col_first);

    -- change the temp table name to the name given as parameter, if not blank
    if length (target_table) > 0 then
        execute format ('alter table temp_table rename to %I', target_table);
    end if;
end;

$$ language plpgsql;

Can pm2 run an 'npm start' script

To use npm run

pm2 start npm --name "{app_name}" -- run {script_name}

How to unlock a file from someone else in Team Foundation Server

In my case, I tried unlocking the file with tf lock but was told I couldn't because the stale workspace on an old computer that no longer existed was a local workspace. I then tried deleting the workspace with tf workspace /delete, but deleting the workspace did not remove the lock (and then I couldn't try to unlock it again because I just got an error saying the workspace no longer existed).

I ended up tf destroying the file and checking it in again, which was pretty silly and had the undesirable effect of removing\ it from previous changesets, but at least got us working again. It wasn't that big a deal in this case since the file had never been changed since being checked in.

Transaction marked as rollback only: How do I find the cause

Found a good explanation with solutions: https://vcfvct.wordpress.com/2016/12/15/spring-nested-transactional-rollback-only/

1) remove the @Transacional from the nested method if it does not really require transaction control. So even it has exception, it just bubbles up and does not affect transactional stuff.

OR:

2) if nested method does need transaction control, make it as REQUIRE_NEW for the propagation policy that way even if throws exception and marked as rollback only, the caller will not be affected.

How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script?

interestingly in my git-bash on windows sed "" did the trick already:

$ echo -e "abc\r" >tst.txt
$ file tst.txt
tst.txt: ASCII text, with CRLF line terminators
$ sed -i "" tst.txt
$ file tst.txt
tst.txt: ASCII text

My guess is that sed ignores them when reading lines from input and always writes unix line endings on output.

How to create a new object instance from a Type

I can across this question because I was looking to implement a simple CloneObject method for arbitrary class (with a default constructor)

With generic method you can require that the type implements New().

Public Function CloneObject(Of T As New)(ByVal src As T) As T
    Dim result As T = Nothing
    Dim cloneable = TryCast(src, ICloneable)
    If cloneable IsNot Nothing Then
        result = cloneable.Clone()
    Else
        result = New T
        CopySimpleProperties(src, result, Nothing, "clone")
    End If
    Return result
End Function

With non-generic assume the type has a default constructor and catch an exception if it doesn't.

Public Function CloneObject(ByVal src As Object) As Object
    Dim result As Object = Nothing
    Dim cloneable As ICloneable
    Try
        cloneable = TryCast(src, ICloneable)
        If cloneable IsNot Nothing Then
            result = cloneable.Clone()
        Else
            result = Activator.CreateInstance(src.GetType())
            CopySimpleProperties(src, result, Nothing, "clone")
        End If
    Catch ex As Exception
        Trace.WriteLine("!!! CloneObject(): " & ex.Message)
    End Try
    Return result
End Function

How to use select/option/NgFor on an array of objects in Angular2

I don't know what things were like in the alpha, but I'm using beta 12 right now and this works fine. If you have an array of objects, create a select like this:

<select [(ngModel)]="simpleValue"> // value is a string or number
    <option *ngFor="let obj of objArray" [value]="obj.value">{{obj.name}}</option>
</select>

If you want to match on the actual object, I'd do it like this:

<select [(ngModel)]="objValue"> // value is an object
    <option *ngFor="let obj of objArray" [ngValue]="obj">{{obj.name}}</option>
</select>

Jquery click event not working after append method

The .on() method is used to delegate events to elements, dynamically added or already present in the DOM:

_x000D_
_x000D_
// STATIC-PARENT              on  EVENT    DYNAMIC-CHILD_x000D_
$('#registered_participants').on('click', '.new_participant_form', function() {_x000D_
_x000D_
  var $td = $(this).closest('tr').find('td');_x000D_
  var part_name = $td.eq(1).text();_x000D_
  console.log( part_name );_x000D_
_x000D_
});_x000D_
_x000D_
_x000D_
$('#add_new_participant').click(function() {_x000D_
_x000D_
  var first_name = $.trim( $('#f_name_participant').val() );_x000D_
  var last_name  = $.trim( $('#l_name_participant').val() );_x000D_
  var role       = $('#new_participant_role').val();_x000D_
  var email      = $('#email_participant').val();_x000D_
  _x000D_
  if(!first_name && !last_name) return;_x000D_
_x000D_
  $('#registered_participants').append('<tr><td><a href="#" class="new_participant_form">Participant Registration</a></td><td>' + first_name + ' ' + last_name + '</td><td>' + role + '</td><td>0% done</td></tr>');_x000D_
_x000D_
});
_x000D_
<table id="registered_participants" class="tablesorter">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Form</th>_x000D_
      <th>Name</th>_x000D_
      <th>Role</th>_x000D_
      <th>Progress </th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td><a href="#" class="new_participant_form">Participant Registration</a></td>_x000D_
      <td>Smith Johnson</td>_x000D_
      <td>Parent</td>_x000D_
      <td>60% done</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>_x000D_
_x000D_
<input type="text" id="f_name_participant" placeholder="Name">_x000D_
<input type="text" id="l_name_participant" placeholder="Surname">_x000D_
<select id="new_participant_role">_x000D_
  <option>Parent</option>_x000D_
  <option>Child</option>_x000D_
</select>_x000D_
<button id="add_new_participant">Add New Entry</button>_x000D_
_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Read more: http://api.jquery.com/on/

How to give environmental variable path for file appender in configuration file in log4j

I got this working.

  1. In my log4j.properties. I specified

log4j.appender.file.File=${LogFilePath}

  1. in eclipse - JVM arguments

-DLogFilePath=C:\work\MyLogFile.log

Converting ArrayList to HashMap

Using a supposed name property as the map key:

for (Product p: productList) { s.put(p.getName(), p); }

How to assert two list contain the same elements in Python?

Converting your lists to sets will tell you that they contain the same elements. But this method cannot confirm that they contain the same number of all elements. For example, your method will fail in this case:

L1 = [1,2,2,3]
L2 = [1,2,3,3]

You are likely better off sorting the two lists and comparing them:

def checkEqual(L1, L2):
    if sorted(L1) == sorted(L2):
        print "the two lists are the same"
        return True
    else:
        print "the two lists are not the same"
        return False

Note that this does not alter the structure/contents of the two lists. Rather, the sorting creates two new lists

How to concatenate two strings in C++?

strcat(destination,source) can be used to concatenate two strings in c++.

To have a deep understanding you can lookup in the following link-

http://www.cplusplus.com/reference/cstring/strcat/

Bash: Echoing a echo command with a variable in bash

You just need to use single quotes:

$ echo "$TEST"
test
$ echo '$TEST'
$TEST

Inside single quotes special characters are not special any more, they are just normal characters.

XML Schema Validation : Cannot find the declaration of element

cvc-elt.1: Cannot find the declaration of element 'Root'. [7]

Your schemaLocation attribute on the root element should be xsi:schemaLocation, and you need to fix it to use the right namespace.

You should probably change the targetNamespace of the schema and the xmlns of the document to http://myNameSpace.com (since namespaces are supposed to be valid URIs, which Test.Namespace isn't, though urn:Test.Namespace would be ok). Once you do that it should find the schema. The point is that all three of the schema's target namespace, the document's namespace, and the namespace for which you're giving the schema location must be the same.

(though it still won't validate as your <element2> contains an <element3> in the document where the schema expects item)

How to drop SQL default constraint without knowing its name?

Useful for some columns that had multiple default constraints or check constraints created:

Modified https://stackoverflow.com/a/16359095/206730 script

Note: this script is for sys.check_constraints

declare @table_name nvarchar(128)
declare @column_name nvarchar(128)
declare @constraint_name nvarchar(128)
declare @constraint_definition nvarchar(512)

declare @df_name nvarchar(128)
declare @cmd nvarchar(128) 

PRINT 'DROP CONSTRAINT [Roles2016.UsersCRM].Estado'

declare constraints cursor for 
 select t.name TableName, c.name ColumnName, d.name ConstraintName, d.definition ConstraintDefinition
 from sys.tables t   
 join sys.check_constraints d  on d.parent_object_id = t.object_id  
 join sys.columns c  on c.object_id = t.object_id      
 and c.column_id = d.parent_column_id
 where t.name = N'Roles2016.UsersCRM' and c.name = N'Estado'

open constraints
fetch next from constraints into @table_name , @column_name, @constraint_name, @constraint_definition
while @@fetch_status = 0
BEGIN
    print 'CONSTRAINT: ' + @constraint_name
    select @cmd = 'ALTER TABLE [' + @table_name +  '] DROP CONSTRAINT [' +  @constraint_name + ']'
    print @cmd
    EXEC sp_executeSQL @cmd;

  fetch next from constraints into @table_name , @column_name, @constraint_name, @constraint_definition
END

close constraints 
deallocate constraints

How to install Laravel's Artisan?

While you are working with Laravel you must be in root of laravel directory structure. There are App, route, public etc folders is root directory. Just follow below step to fix issue. check composer status using : composer -v

First, download the Laravel installer using Composer:

composer global require "laravel/installer"

Please check with below command:

php artisan serve

still not work then create new project with existing code. using LINK

SoapFault exception: Could not connect to host

I had a bad php.ini configuration. Verify the path and the certificate validity...

[openssl]
openssl.cafile = "C:/good/phpath/ca-bundle.crt"

Because my new \SoapClient($wsdl) was https !

UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128)

The problem is that you're trying to print an unicode character to a possibly non-unicode terminal. You need to encode it with the 'replace option before printing it, e.g. print ch.encode(sys.stdout.encoding, 'replace').

Android: How do I get string from resources using its name?

There is also a set of predefined Android strings such as "Ok", "Cancel" and many others - so you don't have to declare all. They're available simply by:

getString(android.R.string.ok)

(In this case, "Ok" string). BTW there are also other Android resources available like for example icons images etc.

webpack command not working

webpack is not only in your node-modules/webpack/bin/ directory, it's also linked in node_modules/.bin.

You have the npm bin command to get the folder where npm will install executables.

You can use the scripts property of your package.json to use webpack from this directory which will be exported.

"scripts": {
  "scriptName": "webpack --config etc..."
}

For example:

"scripts": {
  "build": "webpack --config webpack.config.js"
}

You can then run it with:

npm run build

Or even with arguments:

npm run build -- <args>

This allow you to have you webpack.config.js in the root folder of your project without having webpack globally installed or having your webpack configuration in the node_modules folder.

Set port for php artisan.php serve

You can use many ports together for each project,

  php artisan serve --port=8000

  php artisan serve --port=8001   

  php artisan serve --port=8002

  php artisan serve --port=8003

java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy

Please change small "mm" month to capital "MM" it will work.for reference below is the sample code.

        Date myDate = new Date();
        SimpleDateFormat sm = new SimpleDateFormat("MM-dd-yyyy");
       
        String strDate = sm.format(myDate);
        
        Date dt = sm.parse(strDate);
        System.out.println(strDate);

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

If you want to allow all origins and keep credentials true, this worked for me:

app.use(cors({
  origin: function(origin, callback){
    return callback(null, true);
  },
  optionsSuccessStatus: 200,
  credentials: true
}));

How do I change Bootstrap 3 column order on mobile layout?

The answers here work for just 2 cells, but as soon as those columns have more in them it can lead to a bit more complexity. I think I've found a generalized solution for any number of cells in multiple columns.

#Goals Get a vertical sequence of tags on mobile to arrange themselves in whatever order the design calls for on tablet/desktop. In this concrete example, one tag must enter flow earlier than it normally would, and another later than it normally would.

##Mobile

[1 headline]
[2 image]
[3 qty]
[4 caption]
[5 desc]

##Tablet+

[2 image  ][1 headline]
[         ][3 qty     ]
[         ][5 desc    ]
[4 caption][          ]
[         ][          ]

So headline needs to shuffle right on tablet+, and technically, so does desc - it sits above the caption tag that precedes it on mobile. You'll see in a moment 4 caption is in trouble too.

Let's assume every cell could vary in height, and needs to be flush top-to-bottom with its next cell (ruling out weak tricks like a table).

As with all Bootstrap Grid problems step 1 is to realize the HTML has to be in mobile-order, 1 2 3 4 5, on the page. Then, determine how to get tablet/desktop to reorder itself in this way - ideally without Javascript.

The solution to get 1 headline and 3 qty to sit to the right not the left is to simply set them both pull-right. This applies CSS float: right, meaning they find the first open space they'll fit to the right. You can think of the browser's CSS processor working in the following order: 1 fits in to the right top corner. 2 is next and is regular (float: left), so it goes to top-left corner. Then 3, which is float: right so it leaps over underneath 1.

But this solution wasn't enough for 4 caption; because the right 2 cells are so short 2 image on the left tends to be longer than the both of them combined. Bootstrap Grid is a glorified float hack, meaning 4 caption is float: left. With 2 image occupying so much room on the left, 4 caption attempts to fit in the next available space - often the right column, not the left where we wanted it.

The solution here (and more generally for any issue like this) was to add a hack tag, hidden on mobile, that exists on tablet+ to push caption out, that then gets covered up by a negative margin - like this:

[2 image  ][1 headline]
[         ][3 qty     ]
[         ][4 hack    ]
[5 caption][6 desc ^^^]
[         ][          ]

http://jsfiddle.net/b9chris/52VtD/16633/

HTML:

<div id=headline class="col-xs-12 col-sm-6 pull-right">Product Headline</div>
<div id=image class="col-xs-12 col-sm-6">Product Image</div>
<div id=qty class="col-xs-12 col-sm-6 pull-right">Qty, Add to cart</div>
<div id=hack class="hidden-xs col-sm-6">Hack</div>
<div id=caption class="col-xs-12 col-sm-6">Product image caption</div>
<div id=desc class="col-xs-12 col-sm-6 pull-right">Product description</div>

CSS:

#hack { height: 50px; }

@media (min-width: @screen-sm) {
    #desc { margin-top: -50px; }
}

So, the generalized solution here is to add hack tags that can disappear on mobile. On tablet+ the hack tags allow displayed tags to appear earlier or later in the flow, then get pulled up or down to cover up those hack tags.

Note: I've used fixed heights for the sake of the simple example in the linked jsfiddle, but the actual site content I was working on varies in height in all 5 tags. It renders properly with relatively large variance in tag heights, especially image and desc.

Note 2: Depending on your layout, you may have a consistent enough column order on tablet+ (or larger resolutions), that you can avoid use of hack tags, using margin-bottom instead, like so:

Note 3: This uses Bootstrap 3. Bootstrap 4 uses a different grid set, and won't work with these examples.

http://jsfiddle.net/b9chris/52VtD/16632/

Double border with different color

Maybe use outline property

    <div class="borders">
      Hello
    </div>

    .borders{
    border: 1px solid grey; 
    outline: 2px solid white;
     }

https://jsfiddle.net/Ivan5646/5eunf13f/

<script> tag vs <script type = 'text/javascript'> tag

Douglas Crockford says:

type="text/javascript"

This attribute is optional. Since Netscape 2, the default programming language in all browsers has been JavaScript. In XHTML, this attribute is required and unnecessary. In HTML, it is better to leave it out. The browser knows what to do.

In HTML 4.01 and XHTML 1(.1), the type attribute for <script> elements is required.

Max retries exceeded with URL in requests

just import time and add :

time.sleep(6)

somewhere in the for loop, to avoid sending too many request to the server in a short time. the number 6 means: 6 seconds. keep testing numbers starting from 1, until you reach the minimum seconds that will help to avoid the problem.

How to increment a datetime by one day?

Incrementing dates can be accomplished using timedelta objects:

import datetime

datetime.datetime.now() + datetime.timedelta(days=1)

Look up timedelta objects in the Python docs: http://docs.python.org/library/datetime.html

How to print a percentage value in python?

There is a way more convenient 'percent'-formatting option for the .format() format method:

>>> '{:.1%}'.format(1/3.0)
'33.3%'

How to detect a remote side socket close?

You can also check for socket output stream error while writing to client socket.

out.println(output);
if(out.checkError())
{
    throw new Exception("Error transmitting data.");
}

How to show data in a table by using psql command line interface?

On windows use the name of the table in quotes: TABLE "user"; or SELECT * FROM "user";

Linq to Entities - SQL "IN" clause

I also tried to work with an SQL-IN-like thing - querying against an Entity Data Model. My approach is a string builder to compose a big OR-expression. That's terribly ugly, but I'm afraid it's the only way to go right now.

Now well, that looks like this:

Queue<Guid> productIds = new Queue<Guid>(Products.Select(p => p.Key));
if(productIds.Count > 0)
{
    StringBuilder sb = new StringBuilder();
    sb.AppendFormat("{0}.ProductId = Guid\'{1}\'", entities.Products.Name, productIds.Dequeue());
    while(productIds.Count > 0)
    {
        sb.AppendFormat(" OR {0}.ProductId = Guid\'{1}\'",
          entities.Products.Name, productIds.Dequeue());
    }
}

Working with GUIDs in this context: As you can see above, there is always the word "GUID" before the GUID ifself in the query string fragments. If you don't add this, ObjectQuery<T>.Where throws the following exception:

The argument types 'Edm.Guid' and 'Edm.String' are incompatible for this operation., near equals expression, line 6, column 14.

Found this in MSDN Forums, might be helpful to have in mind.

Matthias

... looking forward for the next version of .NET and Entity Framework, when everything get's better. :)

How to sort pandas data frame using values from several columns?

DataFrame.sort is deprecated; use DataFrame.sort_values.

>>> df.sort_values(['c1','c2'], ascending=[False,True])
   c1   c2
0   3   10
3   2   15
1   2   30
4   2  100
2   1   20
>>> df.sort(['c1','c2'], ascending=[False,True])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/ampawake/anaconda/envs/pseudo/lib/python2.7/site-packages/pandas/core/generic.py", line 3614, in __getattr__
    return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'sort'

How do I iterate through children elements of a div using jQuery?

Use children() and each(), you can optionally pass a selector to children

$('#mydiv').children('input').each(function () {
    alert(this.value); // "this" is the current element in the loop
});

You could also just use the immediate child selector:

$('#mydiv > input').each(function () { /* ... */ });

Make A List Item Clickable (HTML/CSS)

How about putting all content inside link?

<li><a href="#" onClick="..." ... >Backpack <img ... /></a></li>

Seems like the most natural thing to try.

VC++ fatal error LNK1168: cannot open filename.exe for writing

I also had this same issue. My console window was no longer open, but I was able to see my application running by going to processes within task manager. The process name was the name of my application. Once I ended the process I was able to build and compile my code with no issues.

jQuery: Handle fallback for failed AJAX Request

Dougs answer is correct, but you actually can use $.getJSON and catch errors (not having to use $.ajax). Just chain the getJSON call with a call to the fail function:

$.getJSON('/foo/bar.json')
    .done(function() { alert('request successful'); })
    .fail(function() { alert('request failed'); });

Live demo: http://jsfiddle.net/NLDYf/5/

This behavior is part of the jQuery.Deferred interface.
Basically it allows you to attach events to an asynchronous action after you call that action, which means you don't have to pass the event function to the action.

Read more about jQuery.Deferred here: http://api.jquery.com/category/deferred-object/

Scatter plot and Color mapping in Python

Subplot Colorbar

For subplots with scatter, you can trick a colorbar onto your axes by building the "mappable" with the help of a secondary figure and then adding it to your original plot.

As a continuation of the above example:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(10)
y = x
t = x
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.scatter(x, y, c=t, cmap='viridis')
ax2.scatter(x, y, c=t, cmap='viridis_r')


# Build your secondary mirror axes:
fig2, (ax3, ax4) = plt.subplots(1, 2)

# Build maps that parallel the color-coded data
# NOTE 1: imshow requires a 2-D array as input
# NOTE 2: You must use the same cmap tag as above for it match
map1 = ax3.imshow(np.stack([t, t]),cmap='viridis')
map2 = ax4.imshow(np.stack([t, t]),cmap='viridis_r')

# Add your maps onto your original figure/axes
fig.colorbar(map1, ax=ax1)
fig.colorbar(map2, ax=ax2)
plt.show()

Scatter subplots with COLORBAR

Note that you will also output a secondary figure that you can ignore.

Set inputType for an EditText Programmatically?

i've solve all with

.setInputType(InputType.TYPE_CLASS_NUMBER);

for see clear data and

.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);

for see the dots (if the data is a number, it isn't choice che other class)

How to generate javadoc comments in Android Studio

ALT+SHIFT+G will create the auto generated comments for your method (place the cursor at starting position of your method).

psql: FATAL: role "postgres" does not exist

If you're using docker, make sure you're NOT using POSTGRES_USER=something_else, as this variable is used by the standard image to know the name of the PostgreSQL admin user (default as postgres).

In my case, I was using this variable with the intent to set another user to my specific database, but it ended up of course changing the main PostgreSQL user.

How to enable or disable an anchor using jQuery?

For situations where you must put text or html content within an anchor tag, but you simply don't want any action to be taken at all when that element is clicked (like when you want a paginator link to be in the disabled state because it's the current page), simply cut out the href. ;)

<a>3 (current page, I'm totally disabled!)</a>

The answer by @michael-meadows tipped me off to this, but his was still addressing scenarios where you still have to / are working with jQuery/JS. In this case, if you have control over writing the html itself, simply x-ing the href tag is all you need to do, so the solution is a pure HTML one!

Other solutions without jQuery finagling which keep the href require you to put a # in the href, but that causes the page to bounce to the top, and you just want it to be plain old disabled. Or leaving it empty, but depending on browser, that still does stuff like jump to the top, and, it is invalid HTML according to the IDEs. But apparently an a tag is totally valid HTML without an HREF.

Lastly, you might say: Okay, why not just dump the a tag altogether than? Because often you can't, the a tag is used for styling purposes in the CSS framework or control you're using, like Bootstrap's paginator:

http://twitter.github.io/bootstrap/components.html#pagination

nodejs module.js:340 error: cannot find module

Faced the same problem while trying to run node-red.

node <directory structure where js  is located>/red. js

In my case it was :

node AppData/Roaming/npm/node_modules/node-red/red.js

new DateTime() vs default(DateTime)

The answer is no. Keep in mind that in both cases, mdDate.Kind = DateTimeKind.Unspecified.

Therefore it may be better to do the following:

DateTime myDate = new DateTime(1, 1, 1, 0, 0, 0, DateTimeKind.Utc);

The myDate.Kind property is readonly, so it cannot be changed after the constructor is called.

Disabling Minimize & Maximize On WinForm?

Right Click the form you want to hide them on, choose Controls -> Properties.

In Properties, set

  • Control Box -> False
  • Minimize Box -> False
  • Maximize Box -> False

You'll do this in the designer.

1067 error on attempt to start MySQL

...an old one... anyway I had the same issue with MariaDB

In my case most pathes contain special characters like: # Wrapping pathes in my.ini in double quotes made the trick - e.g.

datadir="C:/#windata64/db/MariaDB/data"

System.BadImageFormatException: Could not load file or assembly

I found a different solution to this issue. Apparently my IIS 7 did not have 32bit mode enabled in my Application Pool by default.

To enable 32bit mode, open IIS and select your Application Pool. Mine was named "ASP.NET v4.0".
Right click, go to "Advanced Settings" and change the section named: "Enabled 32-bit Applications" to true.

Restart your web server and try again.

I found the fix from this blog reference: http://darrell.mozingo.net/2009/01/17/running-iis-7-in-32-bit-mode/

Additionally, you can change the settings on Visual Studio. In my case, I went to Tools > Options > Projects and Solutions > Web Projects and checked Use the 64 bit version of IIS Express for web sites and projects - This was on VS Pro 2015. Nothing else fixed it but this.

How to use the pass statement?

pass in Python basically does nothing, but unlike a comment it is not ignored by interpreter. So you can take advantage of it in a lot of places by making it a place holder:

1: Can be used in class

class TestClass: 
    pass

2: Can be use in loop and conditional statements:

if (something == true):  # used in conditional statement
    pass
   
while (some condition is true):  # user is not sure about the body of the loop
    pass

3: Can be used in function :

def testFunction(args): # programmer wants to implement the body of the function later
    pass

pass is mostly used when programmer does not want to give implementation at the moment but still wants to create a certain class/function/conditional statement which can be used later on. Since the Python interpreter does not allow for blank or unimplemented class/function/conditional statement it gives an error:

IndentationError: expected an indented block

pass can be used in such scenarios.

<img>: Unsafe value used in a resource URL context

I'm using rc.4 and this method works for ES2015(ES6):

import {DomSanitizationService} from '@angular/platform-browser';

@Component({
  templateUrl: 'build/pages/veeu/veeu.html'
})
export class VeeUPage {
  static get parameters() {
    return [NavController, App, MenuController, DomSanitizationService];
  }

  constructor(nav, app, menu, sanitizer) {

    this.app = app;
    this.nav = nav;
    this.menu = menu;
    this.sanitizer = sanitizer;    
  }

  photoURL() {
    return this.sanitizer.bypassSecurityTrustUrl(this.mediaItems[1].url);
  }
}

In the HTML:

<iframe [src]='photoURL()' width="640" height="360" frameborder="0"
    webkitallowfullscreen mozallowfullscreen allowfullscreen>
</iframe>

Using a function will ensure that the value doesn't change after you sanitize it. Also be aware that the sanitization function you use depends on the context.

For images, bypassSecurityTrustUrl will work but for other uses you need to refer to the documentation:

https://angular.io/docs/ts/latest/api/platform-browser/index/DomSanitizer-class.html

Remove space above and below <p> tag HTML

I don't why you would put a<p>element there. But another way of removing spaces in between the paragraphs is by declaring only one paragraph

<ul>
   <p><li>HI THERE</li>
    <br>
    <li>ME</li>
     </p>
   </ul>

jQuery event to trigger action when a div is made visible

Use jQuery Waypoints :

$('#contentDiv').waypoint(function() {
   alert('do something');
});

Other examples on the site of jQuery Waypoints.

Multiple line comment in Python

Try this

'''
This is a multiline
comment. I can type here whatever I want.
'''

Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode -- just like #-prepended comments. In effect, it acts exactly like a comment.

On the other hand, if you say this behavior must be documented in the official docs to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.

In any case your editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to an editor that does.

Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.

Not only should the editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.

Keyword not supported: "data source" initializing Entity Framework Context

Just use \" instead ", it should resolve the issue.

Download File to server from URL

prodigitalson's answer didn't work for me. I got missing fopen in CURLOPT_FILE more details.

This worked for me, including local urls:

function downloadUrlToFile($url, $outFileName)
{   
    if(is_file($url)) {
        copy($url, $outFileName); 
    } else {
        $options = array(
          CURLOPT_FILE    => fopen($outFileName, 'w'),
          CURLOPT_TIMEOUT =>  28800, // set this to 8 hours so we dont timeout on big files
          CURLOPT_URL     => $url
        );

        $ch = curl_init();
        curl_setopt_array($ch, $options);
        curl_exec($ch);
        curl_close($ch);
    }
}

reducing number of plot ticks

When a log scale is used the number of major ticks can be fixed with the following command

import matplotlib.pyplot as plt

....

plt.locator_params(numticks=12)
plt.show()

The value set to numticks determines the number of axis ticks to be displayed.

Credits to @bgamari's post for introducing the locator_params() function, but the nticks parameter throws an error when a log scale is used.

Disable arrow key scrolling in users browser

Summary

Simply prevent the default browser action:

window.addEventListener("keydown", function(e) {
    // space and arrow keys
    if([32, 37, 38, 39, 40].indexOf(e.code) > -1) {
        e.preventDefault();
    }
}, false);

If you need to support Internet Explorer or other older browsers, use e.keyCode instead of e.code, but keep in mind that keyCode is deprecated.

Original answer

I used the following function in my own game:

var keys = {};
window.addEventListener("keydown",
    function(e){
        keys[e.code] = true;
        switch(e.code){
            case 37: case 39: case 38:  case 40: // Arrow keys
            case 32: e.preventDefault(); break; // Space
            default: break; // do not block other keys
        }
    },
false);
window.addEventListener('keyup',
    function(e){
        keys[e.code] = false;
    },
false);

The magic happens in e.preventDefault();. This will block the default action of the event, in this case moving the viewpoint of the browser.

If you don't need the current button states you can simply drop keys and just discard the default action on the arrow keys:

var arrow_keys_handler = function(e) {
    switch(e.code){
        case 37: case 39: case 38:  case 40: // Arrow keys
        case 32: e.preventDefault(); break; // Space
        default: break; // do not block other keys
    }
};
window.addEventListener("keydown", arrow_keys_handler, false);

Note that this approach also enables you to remove the event handler later if you need to re-enable arrow key scrolling:

window.removeEventListener("keydown", arrow_keys_handler, false);

References

How to store printStackTrace into a string

Guava makes this easy with Throwables.getStackTraceAsString(Throwable):

Exception e = ...
String stackTrace = Throwables.getStackTraceAsString(e);

Internally, this does what @Zach L suggests.

How do I move a file from one location to another in Java?

Java 6

public boolean moveFile(String sourcePath, String targetPath) {

    File fileToMove = new File(sourcePath);

    return fileToMove.renameTo(new File(targetPath));
}

Java 7 (Using NIO)

public boolean moveFile(String sourcePath, String targetPath) {

    boolean fileMoved = true;

    try {

        Files.move(Paths.get(sourcePath), Paths.get(targetPath), StandardCopyOption.REPLACE_EXISTING);

    } catch (Exception e) {

        fileMoved = false;
        e.printStackTrace();
    }

    return fileMoved;
}

Vertically align text within a div

To make Omar's (or Mahendra's) solution even more universal, the block of code relative to Firefox should be replaced by the following:

/* Firefox */
display: flex;
justify-content: center;
align-items: center;

The problem with Omar's code, otherwise operative, arises when you want to center the box in the screen or in its immediate ancestor. This centering is done either by setting its position to

position: relative; or position:static; (not with position:absolute nor fixed).

And then margin: auto; or margin-right: auto; margin-left: auto;

Under this box center aligning environment, Omar's suggestion does not work. It doesn't work either in Internet Explorer 8 (yet 7.7% market share). So for Internet Explorer 8 (and other browsers), a workaround as seen in other above solutions should be considered.

Using group by on two fields and count in SQL

SELECT group,subGroup,COUNT(*) FROM tablename GROUP BY group,subgroup

How to SUM parts of a column which have same text value in different column in the same row

A PivotTable might suit, though I am not quite certain of the layout of your data:

SO19669814 example

The bold numbers (one of each pair of duplicates) need not be shown as the field does not have to be subtotalled eg:

SO19669814 second example

Android Studio: Application Installation Failed

I solve this problem by: Enable Instant Run

Settings>Build, Execution, Deployment>Instant Run

How do I check for vowels in JavaScript?

cycles, arrays, regexp... for what? It can be much quicker :)

function isVowel(char)
{
    return char === 'a' || char === 'e' || char === 'i' || char === 'o' || char === 'u' || false;
}

Python slice first and last element in list

Another python3 solution uses tuple unpacking with the "*" character:

first, *_, last = range(1, 10)

What is the difference between varchar and nvarchar?

Jeffrey L Whitledge with ~47000 reputation score recommends usage of nvarchar

Solomon Rutzky with with ~33200 reputation score recommends: Do NOT always use NVARCHAR. That is a very dangerous, and often costly, attitude / approach.

What are the main performance differences between varchar and nvarchar SQL Server data types?

https://www.sqlservercentral.com/articles/disk-is-cheap-orly-4

Both persons of such a high reputation, what does a learning sql server database developer choose?

There are many warnings in answers and comments about performance issues if you are not consistent in choices.

There are comments pro/con nvarchar for performance.

There are comments pro/con varchar for performance.

I have a particular requirement for a table with many hundreds of columns, which in itself is probably unusual ?

I'm choosing varchar to avoid going close to the 8060 byte table record size limit of SQL*server 2012.

Use of nvarchar, for me, goes over this 8060 byte limit.

I'm also thinking that I should match the data types of the related code tables to the data types of the primary central table.

I have seen use of varchar column at this place of work, South Australian Government, by previous experienced database developers, where the table row count is going to be several millions or more (and very few nvarchar columns, if any, in these very large tables), so perhaps the expected data row volumes becomes part of this decision.

How to redirect to previous page in Ruby On Rails?

In rails 5, as per the instructions in Rails Guides, you can use:

redirect_back(fallback_location: root_path)

The 'back' location is pulled from the HTTP_REFERER header which is not guaranteed to be set by the browser. Thats why you should provide a 'fallback_location'.

What is setContentView(R.layout.main)?

Set the activity content from a layout resource. The resource will be inflated, adding all top-level views to the activity.

  • Activity is basically a empty window
  • SetContentView is used to fill the window with the UI provided from layout file incase of setContentView(R.layout.somae_file).
  • Here layoutfile is inflated to view and added to the Activity context(Window).

Colorizing text in the console with C++

Add a little Color to your Console Text

  HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
  // you can loop k higher to see more color choices
  for(int k = 1; k < 255; k++)
  {
    // pick the colorattribute k you want
    SetConsoleTextAttribute(hConsole, k);
    cout << k << " I want to be nice today!" << endl;
  }

alt text

Character Attributes Here is how the "k" value be interpreted.

Using Cygwin to Compile a C program; Execution error

Windows path C:\src under cygwin becomes /cygdrive/c/src

How do you split a list into evenly sized chunks?

I have one solution below which does work but more important than that solution is a few comments on other approaches. First, a good solution shouldn't require that one loop through the sub-iterators in order. If I run

g = paged_iter(list(range(50)), 11))
i0 = next(g)
i1 = next(g)
list(i1)
list(i0)

The appropriate output for the last command is

 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

not

 []

As most of the itertools based solutions here return. This isn't just the usual boring restriction about accessing iterators in order. Imagine a consumer trying to clean up poorly entered data which reversed the appropriate order of blocks of 5, i.e., the data looks like [B5, A5, D5, C5] and should look like [A5, B5, C5, D5] (where A5 is just five elements not a sublist). This consumer would look at the claimed behavior of the grouping function and not hesitate to write a loop like

i = 0
out = []
for it in paged_iter(data,5)
    if (i % 2 == 0):
         swapped = it
    else: 
         out += list(it)
         out += list(swapped)
    i = i + 1

This will produce mysteriously wrong results if you sneakily assume that sub-iterators are always fully used in order. It gets even worse if you want to interleave elements from the chunks.

Second, a decent number of the suggested solutions implicitly rely on the fact that iterators have a deterministic order (they don't e.g. set) and while some of the solutions using islice may be ok it worries me.

Third, the itertools grouper approach works but the recipe relies on internal behavior of the zip_longest (or zip) functions that isn't part of their published behavior. In particular, the grouper function only works because in zip_longest(i0...in) the next function is always called in order next(i0), next(i1), ... next(in) before starting over. As grouper passes n copies of the same iterator object it relies on this behavior.

Finally, while the solution below can be improved if you make the assumption criticized above that sub-iterators are accessed in order and fully perused without this assumption one MUST implicitly (via call chain) or explicitly (via deques or other data structure) store elements for each subiterator somewhere. So don't bother wasting time (as I did) assuming one could get around this with some clever trick.

def paged_iter(iterat, n):
    itr = iter(iterat)
    deq = None
    try:
        while(True):
            deq = collections.deque(maxlen=n)
            for q in range(n):
                deq.append(next(itr))
            yield (i for i in deq)
    except StopIteration:
        yield (i for i in deq)

Django DB Settings 'Improperly Configured' Error

You can't just fire up Python and check things, Django doesn't know what project you want to work on. You have to do one of these things:

  • Use python manage.py shell
  • Use django-admin.py shell --settings=mysite.settings (or whatever settings module you use)
  • Set DJANGO_SETTINGS_MODULE environment variable in your OS to mysite.settings
  • (This is removed in Django 1.6) Use setup_environ in the python interpreter:

    from django.core.management import setup_environ
    from mysite import settings
    
    setup_environ(settings)
    

Naturally, the first way is the easiest.

Store query result in a variable using in PL/pgSQL

The usual pattern is EXISTS(subselect):

BEGIN
  IF EXISTS(SELECT name
              FROM test_table t
             WHERE t.id = x
               AND t.name = 'test')
  THEN
     ---
  ELSE
     ---
  END IF;

This pattern is used in PL/SQL, PL/pgSQL, SQL/PSM, ...

Convert data.frame column to a vector?

I use lists to filter dataframes by whether or not they have a value %in% a list.

I had been manually creating lists by exporting a 1 column dataframe to Excel where I would add " ", around each element, before pasting into R: list <- c("el1", "el2", ...) which was usually followed by FilteredData <- subset(Data, Column %in% list).

After searching stackoverflow and not finding an intuitive way to convert a 1 column dataframe into a list, I am now posting my first ever stackoverflow contribution:

# assuming you have a 1 column dataframe called "df"
list <- c()
for(i in 1:nrow(df)){
  list <- append(list, df[i,1])
}
View(list)
# This list is not a dataframe, it is a list of values
# You can filter a dataframe using "subset([Data], [Column] %in% list")

How to select the first element of a set with JSTL?

Look here for a description of the statusVar variable. You can do something like below, where the "status" variable contains the current status of the iteration. This is very useful if you need special annotations for the first and last iteraton. In the case below I want to ommit the comma behind the last tag. Of course you can replace status.last with status.first to do something special on the first itteration:

<td>
    <c:forEach var="tag" items="${idea.tags}" varStatus="status">
        <span>${tag.name not status.last ? ', ' : ''}</span>
    </c:forEach>
</td>

Possible options are: current, index, count, first, last, begin, step, and end

Finding the index of an item in a list

One thing that is really helpful in learning Python is to use the interactive help function:

>>> help(["foo", "bar", "baz"])
Help on list object:

class list(object)
 ...

 |
 |  index(...)
 |      L.index(value, [start, [stop]]) -> integer -- return first index of value
 |

which will often lead you to the method you are looking for.

In UML class diagrams, what are Boundary Classes, Control Classes, and Entity Classes?

Boundary Control Entity pattern have two versions:
- old structural, described at 127 (entity as an data model elements, control as an functions, boundary as an application interface)
- new object pattern


As an object pattern:
- Boundary is an interface for "other world"
- Control in an any internal logic (like a service in DDD pattern)
- Entity is an an persistence serwis for objects (like a repository in DDD pattern).
All classes have operations (see Fowler anemic domain model anti-pattern)
All of them is an Model component in MVC pattern. The rules:
- Only Boundary provide services for the "other world"
- Boundary can call only to Controll
- Control can call anybody
- Entity can't call anybody (!), only be called.

jz

How to load CSS Asynchronously

you can try to get it in a lot of ways :

1.Using media="bogus" and a <link> at the foot

<head>
    <!-- unimportant nonsense -->
    <link rel="stylesheet" href="style.css" media="bogus">
</head>
<body>
    <!-- other unimportant nonsense, such as content -->
    <link rel="stylesheet" href="style.css">
</body>

2.Inserting DOM in the old way

<script type="text/javascript">
(function(){
  var bsa = document.createElement('script');
     bsa.type = 'text/javascript';
     bsa.async = true;
     bsa.src = 'https://s3.buysellads.com/ac/bsa.js';
  (document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild(bsa);
})();
</script>

3.if you can try plugins you could try loadCSS

<script>
  // include loadCSS here...
  function loadCSS( href, before, media ){ ... }
  // load a file
  loadCSS( "path/to/mystylesheet.css" );
</script>

how to release localhost from Error: listen EADDRINUSE

The aforementioned killall -9 node, suggested by Patrick works as expected and solves the problem but you may want to read the edit part of this very answer about why kill -9 may not be the best way to do it.

On top of that you might want to target a single process rather than blindly killing all active processes.

In that case, first get the process ID (PID) of the process running on that port (say 8888):

lsof -i tcp:8888

This will return something like:

COMMAND   PID    USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
node     57385   You   11u  IPv6 0xac745b2749fd2be3      0t0  TCP *:ddi-tcp-1

(LISTEN) Then just do (ps - actually do not. Please keep reading below):

kill -9 57385

How to set a maximum execution time for a mysql query?

pt_kill has an option for such. But it is on-demand, not continually monitoring. It does what @Rafa suggested. However see --sentinel for a hint of how to come close with cron.

Compare two different files line by line in python

I have just been faced with the same challenge, but I thought "Why programming this in Python if you can solve it with a simple "grep"?, which led to the following Python code:

import subprocess
from subprocess import PIPE

try:
  output1, errors1 = subprocess.Popen(["c:\\cygwin\\bin\\grep", "-Fvf" ,"c:\\file1.txt", "c:\\file2.txt"], shell=True, stdout=PIPE, stderr=PIPE).communicate();
  output2, errors2 = subprocess.Popen(["c:\\cygwin\\bin\\grep", "-Fvf" ,"c:\\file2.txt", "c:\\file1.txt"], shell=True, stdout=PIPE, stderr=PIPE).communicate();
  if (len(output1) + len(output2) + len(errors1) + len(errors2) > 0):
    print ("Compare result : There are differences:");
    if (len(output1) + len(output2) > 0):
      print ("  Output differences : ");
      print (output1);
      print (output2);
    if (len(errors1) + len(errors2) > 0):
      print (" Errors : ");
      print (errors1);
      print (errors2);
  else:
    print ("Compare result : Both files are equal");
except Exception as ex:
  print("Compare result : Exception during comparison");
  print(ex);
  raise;

The trick behind this is the following: grep -Fvf file1.txt file2.txt verifies if all entries in file2.txt are present in file1.txt. By doing this in both directions we can see if the content of both files are "equal". I put "equal" between quotes because duplicate lines are disregarded in this way of working.

Obviously, this is just an example: you can replace grep by any commandline file comparison tool.

Why should I use core.autocrlf=true in Git?

I am a .NET developer, and have used Git and Visual Studio for years. My strong recommendation is set line endings to true. And do it as early as you can in the lifetime of your Repository.

That being said, I HATE that Git changes my line endings. A source control should only save and retrieve the work I do, it should NOT modify it. Ever. But it does.

What will happen if you don't have every developer set to true, is ONE developer eventually will set to true. This will begin to change the line endings of all of your files to LF in your repo. And when users set to false check those out, Visual Studio will warn you, and ask you to change them. You will have 2 things happen very quickly. One, you will get more and more of those warnings, the bigger your team the more you get. The second, and worse thing, is that it will show that every line of every modified file was changed(because the line endings of every line will be changed by the true guy). Eventually you won't be able to track changes in your repo reliably anymore. It is MUCH easier and cleaner to make everyone keep to true, than to try to keep everyone false. As horrible as it is to live with the fact that your trusted source control is doing something it should not. Ever.

Programmatically extract contents of InstallShield setup.exe

http://www.compdigitec.com/labs/files/isxunpack.exe

Usage: isxunpack.exe yourinstallshield.exe

It will extract in the same folder.

MySQL: Enable LOAD DATA LOCAL INFILE

All: Evidently this is working as designed. Please see new ref man dated 2019-7-23, Section 6.1.6, Security Issues with LOAD DATA LOCAL.

how to make window.open pop up Modal?

I was able to make parent window disable. However making the pop-up always keep raised didn't work. Below code works even for frame tags. Just add id and class property to frame tag and it works well there too.

In parent window use:

<head>    
<style>
.disableWin{
     pointer-events: none;
}
</style>
<script type="text/javascript">
    function openPopUp(url) {
      disableParentWin(); 
      var win = window.open(url);
      win.focus();
      checkPopUpClosed(win);
    }
    /*Function to detect pop up is closed and take action to enable parent window*/
   function checkPopUpClosed(win) {
         var timer = setInterval(function() {
              if(win.closed) {
                  clearInterval(timer);                  
                  enableParentWin();
              }
          }, 1000);
     }
     /*Function to enable parent window*/ 
     function enableParentWin() {
          window.document.getElementById('mainDiv').class="";
     }
     /*Function to enable parent window*/ 
     function disableParentWin() {
          window.document.getElementById('mainDiv').class="disableWin";
     }

</script>
</head>

<body>
<div id="mainDiv class="">
</div>
</body>    

Error 405 (Method Not Allowed) Laravel 5

Your routes.php file needs to be setup correctly.

What I am assuming your current setup is like:

Route::post('/empresas/eliminar/{id}','CompanyController@companiesDelete');

or something. Define a route for the delete method instead.

Route::delete('/empresas/eliminar/{id}','CompanyController@companiesDelete');

Now if you are using a Route resource, the default route name to be used for the 'DELETE' method is .destroy. Define your delete logic in that function instead.

Notepad++: Multiple words search in a file (may be in different lines)?

Possible solution

  1. In Notepad++ , click search menu, the click Find
  2. in FIND WHAT : enter this ==> cat|town
  3. Select REGULAR EXPRESSION radiobutton
  4. click FIND IN CURRENT DOCUMENT

Screenshot

How to get child process from parent process

I am not sure if I understand you correctly, does this help?

ps --ppid <pid of the parent>

Convert byte to string in Java

This is my version:

public String convertBytestoString(InputStream inputStream)
{
    int bytes;
    byte[] buffer = new byte[1024];

    bytes = inputStream.read(buffer);
    String stringData = new String(buffer,0,bytes);

    return stringData;

}

"The public type <<classname>> must be defined in its own file" error in Eclipse

If .java file contains top level (not nested) public class, it have same name as that public class. So if you have class like public class A{...} it needs to be placed in A.java file. Because of that we can't have two public classes in one .java file.

If having two public classes would be allowed then, and lets say aside from public A class file would also contain public class B{} it would require from A.java file to be also named as B.java but files can't have two (or more) names (at least in all systems on which Java can be run).

So assuming your code is placed in StaticDemoShow.java file you have two options:

  1. If you want to have other class in same file make them non-public (lack of visibility modifier will represent default/package-private visibility)

    class StaticDemo { // It can no longer public
    
        static int a = 3;
        static int b = 4;
    
        static {
            System.out.println("Voila! Static block put into action");
        }
    
        static void show() {
            System.out.println("a= " + a);
            System.out.println("b= " + b);
        }
    
    }
    
    public class StaticDemoShow { // Only one top level public class in same .java file
        public static void main() {
            StaticDemo.show();
        }
    }
    
  2. Move all public classes to their own .java files. So in your case you would need to split it into two files:

    • StaticDemo.java

      public class StaticDemo { // Note: same name as name of file
      
          static int a = 3;
          static int b = 4;
      
          static {
              System.out.println("Voila! Static block put into action");
          }
      
          static void show() {
              System.out.println("a= " + a);
              System.out.println("b= " + b);
          }
      
      }
      
    • StaticDemoShow.java

      public class StaticDemoShow { 
          public static void main() {
              StaticDemo.show();
          }
      }
      

'numpy.ndarray' object is not callable error

The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:

In [16]: import numpy as np

In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()

TypeError: 'numpy.ndarray' object is not callable

If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean or pd.rolling_std to a numpy array earlier in your code.

What I mean is something like this:

In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan,  nan,  nan])

In [4]: pd.rolling_mean = np.array([1,2,3])

In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...

TypeError: 'numpy.ndarray' object is not callable

So, basically you need to search the rest of your codebase for pd.rolling_mean = ... and/or pd.rolling_std = ... to see where you may have overwritten them.


Also, if you'd like, you can put in reload(pd) just before your snippet, which should make it run by restoring the value of pd to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.

How is a tag different from a branch in Git? Which should I use, here?

The Git Parable explains how a typical DVCS gets created and why their creators did what they did. Also, you might want to take a look at Git for Computer Scientist; it explains what each type of object in Git does, including branches and tags.

Can there be an apostrophe in an email address?

Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.

Non-resolvable parent POM for Could not find artifact and 'parent.relativePath' points at wrong local POM

Give the relative path URL value to the pom.xml file
../parentfoldername/pom.xml

Where does PHP store the error log? (php5, apache, fastcgi, cpanel)

php --info | grep error

This is helpful. commented by sjas on question. so i included it as a answer.

lexical or preprocessor issue file not found occurs while archiving?

My project was building fine until I updated to Xcode 10.1. After the Xcode update, started getting Lexical or preprocessor Issue errors on build. Some XCDataModel header files could not be found.

This fixed the issue.

Go to Build Settings, Header Search Paths Change the appropriate value from $(SRCROOT) non-recursive to recursive.

This ensures that subfolders are also searched for headers during build.

enter image description here

How to perform runtime type checking in Dart?

There are two operators for type testing: E is T tests for E an instance of type T while E is! T tests for E not an instance of type T.

Note that E is Object is always true, and null is T is always false unless T===Object.

Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails

Empty both your tables' data and run the command. It will work.

Simple PHP form: Attachment to email (code golf)

I haven't tested the email part of this (my test box does not send email) but I think it will work.

<?php
if ($_POST) {
$s = md5(rand());
mail('[email protected]', 'attachment', "--$s

{$_POST['m']}
--$s
Content-Type: application/octet-stream; name=\"f\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment

".chunk_split(base64_encode(join(file($_FILES['f']['tmp_name']))))."
--$s--", "MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"$s\"");
exit;
}
?>
<form method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'] ?>">
<textarea name="m"></textarea><br>
<input type="file" name="f"/><br>
<input type="submit">
</form>

How to execute an SSIS package from .NET?

So there is another way you can actually fire it from any language. The best way I think, you can just create a batch file which will call your .dtsx package.

Next you call the batch file from any language. As in windows platform, you can run batch file from anywhere, I think this will be the most generic approach for your purpose. No code dependencies.

Below is a blog for more details..

https://www.mssqltips.com/sqlservertutorial/218/command-line-tool-to-execute-ssis-packages/

Happy coding.. :)

Thanks, Ayan

Spring JPA selecting specific columns

In my case i created a separate entity class without the fields that are not required (only with the fields that are required).

Map the entity to the same table. Now when all the columns are required i use the old entity, when only some columns are required, i use the lite entity.

e.g.

@Entity
@Table(name = "user")
Class User{
         @Column(name = "id", unique=true, nullable=false)
         int id;
         @Column(name = "name", nullable=false)
         String name;
         @Column(name = "address", nullable=false)
         Address address;
}

You can create something like :

@Entity
@Table(name = "user")
Class UserLite{
         @Column(name = "id", unique=true, nullable=false)
         int id;
         @Column(name = "name", nullable=false)
         String name;
}

This works when you know the columns to fetch (and this is not going to change).

won't work if you need to dynamically decide the columns.

How to initialize a list of strings (List<string>) with many string values

Just remove () at the end.

List<string> optionList = new List<string>
            { "AdditionalCardPersonAdressType", /* rest of elements */ };

Can't ignore UserInterfaceState.xcuserstate

Had a friend show me this amazing site https://www.gitignore.io/. Enter the IDE of your choice or other options and it will automatically generate a gitignore file consisting of useful ignores, one of which is the xcuserstate. You can preview the gitignore file before downloading.

What is the difference between a pandas Series and a single-column DataFrame?

Series is a one-dimensional object that can hold any data type such as integers, floats and strings e.g

   import pandas as pd
   x = pd.Series([A,B,C]) 

0 A
1 B
2 C

The first column of Series is known as index i.e 0,1,2 the second column is your actual data i.e A,B,C

DataFrames is two-dimensional object that can hold series, list, dictionary

df=pd.DataFrame(rd(5,4),['A','B','C','D','E'],['W','X','Y','Z'])

git checkout tag, git pull fails in branch

First, make sure you are on the right branch.
Then (one time only):

git branch --track

After that this works again:

git pull

jQuery validation plugin: accept only alphabetical characters?

Just a small addition to Nick's answer (which works great !) :

If you want to allow spaces in between letters, for example , you may restrict to enter only letters in full name, but it should allow space as well - just list the space as below with a comma. And in the same way if you need to allow any other specific character:

jQuery.validator.addMethod("lettersonly", function(value, element) 
{
return this.optional(element) || /^[a-z," "]+$/i.test(value);
}, "Letters and spaces only please");       

How to write LaTeX in IPython Notebook?

I developed prettyPy, which offers a nice way to print equation. Unfortunately, it's not performant and needs testing.

Example:

enter image description here

Granted, sympy is a great alternative and although prettyPy doesn't allow for evaluating expressions, variable initialization is not required.

Check if list is empty in C#

gridview itself has a method that checks if the datasource you are binding it to is empty, it lets you display something else.

Android: How to enable/disable option menu item on button click?

You could save the item as a variable when creating the option menu and then change its properties at will.

private MenuItem securedConnection;
private MenuItem insecuredConnection;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.connect_menu, menu);
    securedConnection = menu.getItem(0);
    insecuredConnection =  menu.getItem(1);
    return true;
}

public void foo(){
       securedConnection.setEnabled(true);
}    

Preloading images with jQuery

I would use an Manifest file to tell (modern) web browsers to also load all relevant images and cache them. Use Grunt and grunt-manifest to do this automatically and never worry again about preload scripts, cache invalidators, CDN etc.

https://github.com/gunta/grunt-manifest

Converting from signed char to unsigned char and back again?

Yes this is safe.

The c language uses a feature called integer promotion to increase the number of bits in a value before performing calculations. Therefore your CLAMP255 macro will operate at integer (probably 32 bit) precision. The result is assigned to a jbyte, which reduces the integer precision back to 8 bits fit in to the jbyte.

What is the equivalent of bigint in C#?

You can use long type or Int64

How to subtract date/time in JavaScript?

If you wish to get difference in wall clock time, for local timezone and with day-light saving awareness.


Date.prototype.diffDays = function (date: Date): number {

    var utcThis = Date.UTC(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds());
    var utcOther = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds());

    return (utcThis - utcOther) / 86400000;
};

Test


it('diffDays - Czech DST', function () {
    // expect this to parse as local time
    // with Czech calendar DST change happened 2012-03-25 02:00
    var pre = new Date('2012/03/24 03:04:05');
    var post = new Date('2012/03/27 03:04:05');

    // regardless DST, you still wish to see 3 days
    expect(pre.diffDays(post)).toEqual(-3);
});

Diff minutes or seconds is in same fashion.

MySQL Workbench Edit Table Data is read only

If you set a default schema for your DB Connection then Select will run in readonly mode until you set explicitly your schema

USE mydb;
SELECT * FROM mytable

this will also run in edit mode:

SELECT * FROM mydb.mytable 

(MySql 5.2.42 / MacOsX)

I hope this helps.

How does the "final" keyword in Java work? (I can still modify an object.)

The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be:

  1. variable
  2. method
  3. class

The final keyword can be applied with the variables, a final variable that has no value, is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only.

Java final variable:

If you make any variable as final, you cannot change the value of final variable(It will be constant).

Example of final variable

There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because final variable once assigned a value can never be changed.

class Bike9{  
    final int speedlimit=90;//final variable  
    void run(){  
        speedlimit=400;  // this will make error
    }  

    public static void main(String args[]){  
    Bike9 obj=new  Bike9();  
    obj.run();  
    }  
}//end of class  

Java final class:

If you make any class as final, you cannot extend it.

Example of final class

final class Bike{}  

class Honda1 extends Bike{    //cannot inherit from final Bike,this will make error
  void run(){
      System.out.println("running safely with 100kmph");
   }  

  public static void main(String args[]){  
      Honda1 honda= new Honda();  
      honda.run();  
      }  
  }  

Java final method:

If you make any method as final, you cannot override it.

Example of final method (run() in Honda cannot override run() in Bike)

class Bike{  
  final void run(){System.out.println("running");}  
}  

class Honda extends Bike{  
   void run(){System.out.println("running safely with 100kmph");}  

   public static void main(String args[]){  
   Honda honda= new Honda();  
   honda.run();  
   }  
}  

shared from: http://www.javatpoint.com/final-keyword

Undefined or null for AngularJS

I asked the same question of the lodash maintainers a while back and they replied by mentioning the != operator can be used here:

if(newVal != null) {
  // newVal is defined
}

This uses JavaScript's type coercion to check the value for undefined or null.

If you are using JSHint to lint your code, add the following comment blocks to tell it that you know what you are doing - most of the time != is considered bad.

/* jshint -W116 */ 
if(newVal != null) {
/* jshint +W116 */
  // newVal is defined
}

True/False vs 0/1 in MySQL

If you are into performance, then it is worth using ENUM type. It will probably be faster on big tables, due to the better index performance.

The way of using it (source: http://dev.mysql.com/doc/refman/5.5/en/enum.html):

CREATE TABLE shirts (
    name VARCHAR(40),
    size ENUM('x-small', 'small', 'medium', 'large', 'x-large')
);

But, I always say that explaining the query like this:

EXPLAIN SELECT * FROM shirts WHERE size='medium';

will tell you lots of information about your query and help on building a better table structure. For this end, it is usefull to let phpmyadmin Propose a table table structure - but this is more a long time optimisation possibility, when the table is already filled with lots of data.

How do I write out a text file in C# with a code page other than UTF-8?

using System.IO;
using System.Text;

using (StreamWriter sw = new StreamWriter(File.Open(myfilename, FileMode.Create), Encoding.WhateverYouWant))
{    
    sw.WriteLine("my text...");     
}

An alternate way of getting your encoding:

using System.IO;
using System.Text;

using (var sw  = new StreamWriter(File.Open(@"c:\myfile.txt", FileMode.CreateNew), Encoding.GetEncoding("iso-8859-1"))) {
    sw.WriteLine("my text...");             
}

Check out the docs for the StreamWriter constructor.

Add space between two particular <td>s

my choice was to add a td between the two td tags and set the width to 25px. It can be more or less to your liking. This may be cheesy but it is simple and it works.

No connection could be made because the target machine actively refused it (PHP / WAMP)

I'm having the same problem with Wampserver. It’s worked for me:

You must change this file: "C:\wamp\bin\mysql[mysql_version]\my.ini" For example: "C:\wamp\bin\mysql[mysql5.6.12]\my.ini"

And change default port 3306 to 80. (Lines 20 & 27, in both)

port = 3306 To port = 80

I hope this is helpful.

Set up git to pull and push all branches

If you are moving branches to a new repo from an old one and do NOT have all the old repo branches local, you will need to track them first.

for remote in `git branch -r | grep -v '\->'`; do git branch --track $remote; done

Then add your new remote repo:

git remote add bb <path-to-new-repo>

Then you can push all using this command:

git push -u bb --all

Or you can configure the repo using the git config commands noted in the other responses here if you are not doing this one time or are only looking to move local branches.

The important point, the other responses only push all LOCAL branches. If the branches only exist on an alternate REMOTE repository they will not move without tracking them first. The for loop presented here will help with that.

Memory Allocation "Error: cannot allocate vector of size 75.1 Mb"

R has gotten to the point where the OS cannot allocate it another 75.1Mb chunk of RAM. That is the size of memory chunk required to do the next sub-operation. It is not a statement about the amount of contiguous RAM required to complete the entire process. By this point, all your available RAM is exhausted but you need more memory to continue and the OS is unable to make more RAM available to R.

Potential solutions to this are manifold. The obvious one is get hold of a 64-bit machine with more RAM. I forget the details but IIRC on 32-bit Windows, any single process can only use a limited amount of RAM (2GB?) and regardless Windows will retain a chunk of memory for itself, so the RAM available to R will be somewhat less than the 3.4Gb you have. On 64-bit Windows R will be able to use more RAM and the maximum amount of RAM you can fit/install will be increased.

If that is not possible, then consider an alternative approach; perhaps do your simulations in batches with the n per batch much smaller than N. That way you can draw a much smaller number of simulations, do whatever you wanted, collect results, then repeat this process until you have done sufficient simulations. You don't show what N is, but I suspect it is big, so try smaller N a number of times to give you N over-all.

How can I split a string with a string delimiter?

You could use the IndexOf method to get a location of the string, and split it using that position, and the length of the search string.


You can also use regular expression. A simple google search turned out with this

using System;
using System.Text.RegularExpressions;

class Program {
  static void Main() {
    string value = "cat\r\ndog\r\nanimal\r\nperson";
    // Split the string on line breaks.
    // ... The return value from Split is a string[] array.
    string[] lines = Regex.Split(value, "\r\n");

    foreach (string line in lines) {
        Console.WriteLine(line);
    }
  }
}

Using grep to search for hex strings in a file

This seems to work for me:

LANG=C grep --only-matching --byte-offset --binary --text --perl-regexp "<\x-hex pattern>" <file>

short form:

LANG=C grep -obUaP "<\x-hex pattern>" <file>

Example:

LANG=C grep -obUaP "\x01\x02" /bin/grep

Output (cygwin binary):

153: <\x01\x02>
33210: <\x01\x02>
53453: <\x01\x02>

So you can grep this again to extract offsets. But don't forget to use binary mode again.

Note: LANG=C is needed to avoid utf8 encoding issues.

how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application?

Other option that we use in our projects in order to be able to set the environment per-site is to add a Parameters.xml file to the project with the following content:

<parameters>
      <parameter name="IIS Web Application Name" defaultValue="MyApp" tags="IisApp" />    
      <parameter name="Environment" description="Environment" tags="">
        <parameterEntry kind="XmlFile" scope="Web.config"  match="/configuration/location/system.webServer/aspNetCore/environmentVariables/environmentVariable[@name='ASPNETCORE_ENVIRONMENT']/@value" />
      </parameter>    
</parameters>

The Build Action for this file is Content and the Copy Action is Copy If Newer so it will be part of the package to deploy.

Then, to deploy the package and set the environment, in the Release, under the "WinRM - IIS Web App Deployment" task (it works just as well when using the "IIS web app deploy" task), we set additional arguments for msdeploy:

-setParam:kind=ProviderPath,scope=contentPath,value="MySite" -setParam:name="Environment",value="Stage"

This way we can have multiple releases, all using the same artifact, but deployed as different environments.

semaphore implementation

The fundamental issue with your code is that you mix two APIs. Unfortunately online resources are not great at pointing this out, but there are two semaphore APIs on UNIX-like systems:

  • POSIX IPC API, which is a standard API
  • System V API, which is coming from the old Unix world, but practically available almost all Unix systems

Looking at the code above you used semget() from the System V API and tried to post through sem_post() which comes from the POSIX API. It is not possible to mix them.

To decide which semaphore API you want you don't have so many great resources. The simple best is the "Unix Network Programming" by Stevens. The section that you probably interested in is in Vol #2.

These two APIs are surprisingly different. Both support the textbook style semaphores but there are a few good and bad points in the System V API worth mentioning:

  • it builds on semaphore sets, so once you created an object with semget() that is a set of semaphores rather then a single one
  • the System V API allows you to do atomic operations on these sets. so you can modify or wait for multiple semaphores in a set
  • the SysV API allows you to wait for a semaphore to reach a threshold rather than only being non-zero. waiting for a non-zero threshold is also supported, but my previous sentence implies that
  • the semaphore resources are pretty limited on every unixes. you can check these with the 'ipcs' command
  • there is an undo feature of the System V semaphores, so you can make sure that abnormal program termination doesn't leave your semaphores in an undesired state

Mockito How to mock only the call of a method of the superclass

No, Mockito does not support this.

This might not be the answer you're looking for, but what you're seeing is a symptom of not applying the design principle:

Favor composition over inheritance

If you extract a strategy instead of extending a super class the problem is gone.

If however you are not allowed to change the code, but you must test it anyway, and in this awkward way, there is still hope. With some AOP tools (for example AspectJ) you can weave code into the super class method and avoid its execution entirely (yuck). This doesn't work if you're using proxies, you have to use bytecode modification (either load time weaving or compile time weaving). There are be mocking frameworks that support this type of trick as well, like PowerMock and PowerMockito.

I suggest you go for the refactoring, but if that is not an option you're in for some serious hacking fun.

C# Error "The type initializer for ... threw an exception

I tried your code:

CheckedListBox cb = new CheckedListBox();
for (var i = 1; i < 11; i++)
  cb.Items.Add("Item " + i, i % 3 == 0);

string fmt = RHelper.FormatQuery(cb);
Console.WriteLine(fmt);
Console.ReadLine();

It threw an exception at this line:

foreach (DataRowView item in chekedListBox.CheckedItems)

// Unable to cast object of type 'System.String' to type 'System.Data.DataRowView'.

Maybe you are also facing the same kind of problem. Instead of casting to DataRowView, try making the following changes:

foreach (var item in chekedListBox.CheckedItems)
{
    ID = ID + item.ToString(); // item["" + FieldName + ""];

Because items in CheckedListBox are of object type.

How to use SharedPreferences in Android to store, fetch and edit values

To store values in shared preferences:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name","Jayesh");
editor.commit();

To retrieve values from shared preferences:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("Name", "");

How to load image files with webpack file-loader

Alternatively you can write the same like

{
    test: /\.(svg|png|jpg|jpeg|gif)$/,
    include: 'path of input image directory',
    use: {
        loader: 'file-loader',
        options: {
            name: '[path][name].[ext]',
            outputPath: 'path of output image directory'
        }
    }
}

and then use simple import

import varName from 'relative path';

and in jsx write like <img src={varName} ..../>

.... are for other image attributes

Understanding Popen.communicate

Do not use communicate(input=""). It writes input to the process, closes its stdin and then reads all output.

Do it like this:

p=subprocess.Popen(["python","1st.py"],stdin=PIPE,stdout=PIPE)

# get output from process "Something to print"
one_line_output = p.stdout.readline()

# write 'a line\n' to the process
p.stdin.write('a line\n')

# get output from process "not time to break"
one_line_output = p.stdout.readline() 

# write "n\n" to that process for if r=='n':
p.stdin.write('n\n') 

# read the last output from the process  "Exiting"
one_line_output = p.stdout.readline()

What you would do to remove the error:

all_the_process_will_tell_you = p.communicate('all you will ever say to this process\nn\n')[0]

But since communicate closes the stdout and stdin and stderr, you can not read or write after you called communicate.

Terminating idle mysql connections

I don't see any problem, unless you are not managing them using a connection pool.

If you use connection pool, these connections are re-used instead of initiating new connections. so basically, leaving open connections and re-use them it is less problematic than re-creating them each time.

How to run SQL script in MySQL?

I came here searching for this answer as well, and here is what I found works the best for me: Note I am using Ubuntu 16.x.x

  1. Access mysql using:

mysql -u <your_user> - p

  1. At the mysql prompt, enter:

source file_name.sql

Hope this helps.

Get keys from HashMap in Java

public class MyHashMapKeys {

    public static void main(String a[]){
        HashMap<String, String> hm = new HashMap<String, String>();
        //add key-value pair to hashmap
        hm.put("first", "FIRST INSERTED");
        hm.put("second", "SECOND INSERTED");
        hm.put("third","THIRD INSERTED");
        System.out.println(hm);
        Set<String> keys = hm.keySet();
        for(String key: keys){
            System.out.println(key);
        }
    }
}

Input size vs width

HTML controls the semantic meaning of the elements. CSS controls the layout/style of the page. Use CSS when you are controlling your layout.

In short, never use size=""

How to add shortcut keys for java code in eclipse

type "syso" and then press ctrl + space

OR

type "sysout" and then press ctrl + space

Add element to a list In Scala

I will try to explain the results of all the commands you tried.

scala> val l = 1.0 :: 5.5 :: Nil
l: List[Double] = List(1.0, 5.5)

First of all, List is a type alias to scala.collection.immutable.List (defined in Predef.scala).

Using the List companion object is more straightforward way to instantiate a List. Ex: List(1.0,5.5)

scala> l
res0: List[Double] = List(1.0, 5.5)

scala> l ::: List(2.2, 3.7)
res1: List[Double] = List(1.0, 5.5, 2.2, 3.7)

::: returns a list resulting from the concatenation of the given list prefix and this list

The original List is NOT modified

scala> List(l) :+ 2.2
res2: List[Any] = List(List(1.0, 5.5), 2.2)

List(l) is a List[List[Double]] Definitely not what you want.

:+ returns a new list consisting of all elements of this list followed by elem.

The type is List[Any] because it is the common superclass between List[Double] and Double

scala> l
res3: List[Double] = List(1.0, 5.5)

l is left unmodified because no method on immutable.List modified the List.

How to remove all callbacks from a Handler?

For any specific Runnable instance, call Handler.removeCallbacks(). Note that it uses the Runnable instance itself to determine which callbacks to unregister, so if you are creating a new instance each time a post is made, you need to make sure you have references to the exact Runnable to cancel. Example:

Handler myHandler = new Handler();
Runnable myRunnable = new Runnable() {
    public void run() {
        //Some interesting task
    }
};

You can call myHandler.postDelayed(myRunnable, x) to post another callback to the message queue at other places in your code, and remove all pending callbacks with myHandler.removeCallbacks(myRunnable)

Unfortunately, you cannot simply "clear" the entire MessageQueue for a Handler, even if you make a request for the MessageQueue object associated with it because the methods for adding and removing items are package protected (only classes within the android.os package can call them). You may have to create a thin Handler subclass to manage a list of Runnables as they are posted/executed...or look at another paradigm for passing your messages between each Activity

Hope that Helps!

Insert auto increment primary key to existing table

Well, you have multiple ways to do this: -if you don't have any data on your table, just drop it and create it again.

Dropping the existing field and creating it again like this

ALTER TABLE test DROP PRIMARY KEY, DROP test_id, ADD test_id int AUTO_INCREMENT NOT NULL FIRST, ADD PRIMARY KEY (test_id);

Or just modify it

ALTER TABLE test MODIFY test_id INT AUTO_INCREMENT NOT NULL, ADD PRIMARY KEY (test_id);

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Note that the mode of opening files is 'a' or some other have alphabet 'a' will also make error because of the overwritting.

pointer = open('makeaafile.txt', 'ab+')
tes = pickle.load(pointer, encoding='utf-8')

Intel X86 emulator accelerator (HAXM installer) VT/NX not enabled

For IntelHAXM to install you have to activate Intel Virtual Technology.

To activate it, you have to restart your PC and go to BIOS. There is an option called Intel Virtual Technology that you have to enable to activate it.

After enabling it, reinstall IntelHAXM. That should solve the problem.

Bootstrap 3: how to make head of dropdown link clickable in navbar

Alternatively here's a simple jQuery solution:

$('#menu-main > li > .dropdown-toggle').click(function () {
    window.location = $(this).attr('href');
});

What is Linux’s native GUI API?

The linux kernel graphical operations are in /include/linux/fb.h as struct fb_ops. Eventually this is what add-ons like X11, Wayland, or DRM appear to reference. As these operations are only for video cards, not vector or raster hardcopy or tty oriented terminal devices, their usefulness as a GUI is limited; it's just not entirely true you need those add-ons to get graphical output if you don't mind using some assembler to bypass syscall as necessary.

How many characters can you store with 1 byte?

Yes, 1 byte does encode a character (inc spaces etc) from the ASCII set. However in data units assigned to character encoding it can and often requires in practice up to 4 bytes. This is because English is not the only character set. And even in English documents other languages and characters are often represented. The numbers of these are very many and there are very many other encoding sets, which you may have heard of e.g. BIG-5, UTF-8, UTF-32. Most computers now allow for these uses and ensure the least amount of garbled text (which usually means a missing encoding set.) 4 bytes is enough to cover these possible encodings. I byte per character does not allow for this and in use it is larger often 4 bytes per possible character for all encodings, not just ASCII. The final character may only need a byte to function or be represented on screen, but requires 4 bytes to be located in the rather vast global encoding "works".

Most common C# bitwise operations on enums

To test a bit you would do the following: (assuming flags is a 32 bit number)

Test Bit:

if((flags & 0x08) == 0x08)
(If bit 4 is set then its true) Toggle Back (1 - 0 or 0 - 1):
flags = flags ^ 0x08;
Reset Bit 4 to Zero:
flags = flags & 0xFFFFFF7F;

Round to 2 decimal places

Create a class called Round and try using the method round as Round.round(targetValue, roundToDecimalPlaces) in your code

public class Round {

        public static float round(float targetValue, int roundToDecimalPlaces ){

            int valueInTwoDecimalPlaces = (int) (targetValue * Math.pow(10, roundToDecimalPlaces));

            return (float) (valueInTwoDecimalPlaces / Math.pow(10, roundToDecimalPlaces));
        }

    }

How can I concatenate strings in VBA?

The main (very interesting) difference for me is that:
"string" & Null -> "string"
while
"string" + Null -> Null

But that's probably more useful in database apps like Access.

How can I replace a regex substring match in Javascript?

I would get the part before and after what you want to replace and put them either side.

Like:

var str   = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;

var matches = str.match(regex);

var result = matches[1] + "1" + matches[2];

// With ES6:
var result = `${matches[1]}1${matches[2]}`;

How to check the presence of php and apache on ubuntu server through ssh

How to tell on Ubuntu if apache2 is running:

sudo service apache2 status

/etc/init.d/apache2 status

ps aux | grep apache

Load image from url

Best Method I have tried instead of using any libraries

public Bitmap getbmpfromURL(String surl){
    try {
        URL url = new URL(surl);
        HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
        urlcon.setDoInput(true);
        urlcon.connect();
        InputStream in = urlcon.getInputStream();
        Bitmap mIcon = BitmapFactory.decodeStream(in);
        return  mIcon;
    } catch (Exception e) {
        Log.e("Error", e.getMessage());
        e.printStackTrace();
        return null;
    }
}

Vue template or render function not defined yet I am using neither?

In my case, I imported my component (in router) as:

import bsw from 'common-mod/src/components/webcommon/webcommon'

It is simply solved if I changed it to

import bsw from 'common-mod/src/components/webcommon/webcommon.vue'

Jenkins: Cannot define variable in pipeline stage

I think error is not coming from the specified line but from the first 3 lines. Try this instead :

node {
   stage("first") {
     def foo = "foo"
     sh "echo ${foo}"
   }
}

I think you had some extra lines that are not valid...

From declaractive pipeline model documentation, it seems that you have to use an environment declaration block to declare your variables, e.g.:

pipeline {
   environment {
     FOO = "foo"
   }

   agent none
   stages {
       stage("first") {
           sh "echo ${FOO}"
       }
   }
}

Python unexpected EOF while parsing

I'm using the follow code to get Python 2 and 3 compatibility

if sys.version_info < (3, 0):
    input = raw_input

Which is the correct C# infinite loop, for (;;) or while (true)?

The C# compiler will transform both

for(;;)
{
    // ...
}

and

while (true)
{
    // ...
}

into

{
    :label
    // ...
    goto label;
}

The CIL for both is the same. Most people find while(true) to be easier to read and understand. for(;;) is rather cryptic.

Source:

I messed a little more with .NET Reflector, and I compiled both loops with the "Optimize Code" on in Visual Studio.

Both loops compile into (with .NET Reflector):

Label_0000:
    goto Label_0000;

Raptors should attack soon.

Getting a list of values from a list of dicts

For a very simple case like this, a comprehension, as in Ismail Badawi's answer is definitely the way to go.

But when things get more complicated, and you need to start writing multi-clause or nested comprehensions with complex expressions in them, it's worth looking into other alternatives. There are a few different (quasi-)standard ways to specify XPath-style searches on nested dict-and-list structures, such as JSONPath, DPath, and KVC. And there are nice libraries on PyPI for them.

Here's an example with the library named dpath, showing how it can simplify something just a bit more complicated:

>>> dd = {
...     'fruits': [{'value': 'apple', 'blah': 2}, {'value': 'banana', 'blah': 3}],
...     'vehicles': [{'value': 'cars', 'blah':4}]}

>>> {key: [{'value': d['value']} for d in value] for key, value in dd.items()}
{'fruits': [{'value': 'apple'}, {'value': 'banana'}],
 'vehicles': [{'value': 'cars'}]}

>>> dpath.util.search(dd, '*/*/value')
{'fruits': [{'value': 'apple'}, {'value': 'banana'}],
 'vehicles': [{'value': 'cars'}]}

Or, using jsonpath-ng:

>>> [d['value'] for key, value in dd.items() for d in value]
['apple', 'banana', 'cars']
>>> [m.value for m in jsonpath_ng.parse('*.[*].value').find(dd)]
['apple', 'banana', 'cars']

This one may not look quite as simple at first glance, because find returns match objects, which include all kinds of things besides just the matched value, such as a path directly to each item. But for more complex expressions, being able to specify a path like '*.[*].value' instead of a comprehension clause for each * can make a big difference. Plus, JSONPath is a language-agnostic specification, and there are even online testers that can be very handy for debugging.

How to combine multiple conditions to subset a data-frame using "OR"?

my.data.frame <- subset(data , V1 > 2 | V2 < 4)

An alternative solution that mimics the behavior of this function and would be more appropriate for inclusion within a function body:

new.data <- data[ which( data$V1 > 2 | data$V2 < 4) , ]

Some people criticize the use of which as not needed, but it does prevent the NA values from throwing back unwanted results. The equivalent (.i.e not returning NA-rows for any NA's in V1 or V2) to the two options demonstrated above without the which would be:

 new.data <- data[ !is.na(data$V1 | data$V2) & ( data$V1 > 2 | data$V2 < 4)  , ]

Note: I want to thank the anonymous contributor that attempted to fix the error in the code immediately above, a fix that got rejected by the moderators. There was actually an additional error that I noticed when I was correcting the first one. The conditional clause that checks for NA values needs to be first if it is to be handled as I intended, since ...

> NA & 1
[1] NA
> 0 & NA
[1] FALSE

Order of arguments may matter when using '&".

Get changes from master into branch in Git

First check out to master:

git checkout master

Do all changes, hotfix and commits and push your master.

Go back to your branch, 'aq', and merge master in it:

git checkout aq
git merge master

Your branch will be up-to-date with master. A good and basic example of merge is 3.2 Git Branching - Basic Branching and Merging.

Reportviewer tool missing in visual studio 2017 RC

If you're like me and tried a few of these methods and are stuck at the point that you have the control in the toolbox and can draw it on the form but it disappears from the form and puts it down in the components, then simply edit the designer and add the following in the appropriate area of InitializeComponent() to make it visible:

this.Controls.Add(this.reportViewer1);

or

[ContainerControl].Controls.Add(this.reportViewer1);

You'll also need to make adjustments to the location and size manually after you've added the control.

Not a great answer for sure, but if you're stuck and just need to get work done for now until you have more time to figure it out, it should help.

The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1

Iterating over the answer from Tao-Nhan Nguyen, accounting the original value set for every pod, adjusting it only if it's not greater than 8.0... Add the following to the Podfile:

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      if Gem::Version.new('8.0') > Gem::Version.new(config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'])
        config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '8.0'
      end
    end
  end
end

SOAP-ERROR: Parsing WSDL: Couldn't load from - but works on WAMP

After hours of analysis reading tons of logs and internet, finally found problem.

If you use docker and php 7.4 (my case) you probably get error because default security level in OpenSSL it too high for wsdl cert. Even if you disable verify and allow self-signed in SoapClient options.

You need lower seclevel in /etc/ssl/openssl.cnf from DEFAULT@SECLEVEL=2 to

DEFAULT@SECLEVEL=1

Or just add into Dockerfile

RUN sed -i "s|DEFAULT@SECLEVEL=2|DEFAULT@SECLEVEL=1|g" /etc/ssl/openssl.cnf

Source: https://github.com/dotnet/runtime/issues/30667#issuecomment-566482876


You can verify it by run on container

curl -A 'cURL User Agent' -4 https://ewus.nfz.gov.pl/ws-broker-server-ewus/services/Auth?wsdl

Before that change I got error:

SSL routines:tls_process_ske_dhe:dh key too small

align images side by side in html

Not really sure what you meant by "the caption in the middle", but here's one solution to get your images appear side by side, using the excellent display:inline-block :

<!DOCTYPE html>
<html>
<head>
  <meta charset=utf-8 />
  <title></title>
  <style>
    div.container {
      display:inline-block;
    }

    p {
      text-align:center;
    }
  </style>
</head>
<body>
  <div class="container">
    <img src="http://placehold.it/350x150" height="200" width="200" />
    <p>This is image 1</p>
  </div>
  <div class="container">
    <img class="middle-img" src="http://placehold.it/350x150"/ height="200" width="200" />
    <p>This is image 2</p>
  </div>
  <div class="container">
    <img src="http://placehold.it/350x150" height="200" width="200" />
    <p>This is image 3</p>
  </div>
</div>
</body>
</html>

Animate the transition between fragments

For anyone else who gets caught, ensure setCustomAnimations is called before the call to replace/add when building the transaction.

How to get mouse position in jQuery without mouse-events?

var CurrentMouseXPostion;
var CurrentMouseYPostion;

$(document).mousemove(function(event) {
    CurrentMouseXPostion = event.pageX;
    CurrentMouseYPostion = event.pageY;
});

Make an eventListener on the main object , in my case the document object, to get the mouse coords every frame and store them in global variables, and like that you can read mouse Y & Z whenever youlike , wherever you like.

sql - insert into multiple tables in one query

I had the same problem. I solve it with a for loop.

Example:

If I want to write in 2 identical tables, using a loop

for x = 0 to 1

 if x = 0 then TableToWrite = "Table1"
 if x = 1 then TableToWrite = "Table2"
  Sql = "INSERT INTO " & TableToWrite & " VALUES ('1','2','3')"
NEXT

either

ArrTable = ("Table1", "Table2")

for xArrTable = 0 to Ubound(ArrTable)
 Sql = "INSERT INTO " & ArrTable(xArrTable) & " VALUES ('1','2','3')"
NEXT

If you have a small query I don't know if this is the best solution, but if you your query is very big and it is inside a dynamical script with if/else/case conditions this is a good solution.

HttpClient.GetAsync(...) never returns when using await/async

In my case 'await' never finished because of exception while executing the request, e.g. server not responding, etc. Surround it with try..catch to identify what happened, it'll also complete your 'await' gracefully.

public async Task<Stuff> GetStuff(string id)
{
    string path = $"/api/v2/stuff/{id}";
    try
    {
        HttpResponseMessage response = await client.GetAsync(path);
        if (response.StatusCode == HttpStatusCode.OK)
        {
            string json = await response.Content.ReadAsStringAsync();
            return JsonUtility.FromJson<Stuff>(json);
        }
        else
        {
            Debug.LogError($"Could not retrieve stuff {id}");
        }
    }
    catch (Exception exception)
    {
        Debug.LogError($"Exception when retrieving stuff {exception}");
    }
    return null;
}

$http.get(...).success is not a function

If you are trying to use AngularJs 1.6.6 as of 21/10/2017 the following parameter works as .success and has been depleted. The .then() method takes two arguments: a response and an error callback which will be called with a response object.

 $scope.login = function () {
        $scope.btntext = "Please wait...!";
        $http({
            method: "POST",
            url: '/Home/userlogin', // link UserLogin with HomeController 
            data: $scope.user
         }).then(function (response) {
            console.log("Result value is : " + parseInt(response));
            data = response.data;
            $scope.btntext = 'Login';
            if (data == 1) {
                window.location.href = '/Home/dashboard';
             }
            else {
            alert(data);
        }
        }, function (error) {

        alert("Failed Login");
        });

The above snipit works for a login page.

Vector of Vectors to create matrix

Vector needs to be initialized before using it as cin>>v[i][j]. Even if it was 1D vector, it still needs an initialization, see this link

After initialization there will be no errors, see this link

Export MySQL database using PHP only

This tool might be useful, it's a pure PHP based export utility: https://github.com/2createStudio/shuttle-export

Get Maven artifact version at runtime

On my spring boot application, the solution from the accepted answer worked until I recently updated my jdk to version 12. Tried all the other answers as well and couldn't get that to work.

At that point, I added the below line to the first class of my spring boot application, just after the annotation @SpringBootApplication

@PropertySources({ 
        @PropertySource("/META-INF/maven/com.my.group/my-artefact/pom.properties")
})

Later I use the below to get the value from the properties file in whichever class I want to use its value and appVersion gets the project version to me:

@Value("${version}")
private String appVersion;

Hope that helps someone.

Pass variables to AngularJS controller, best practice?

You could use ng-init in an outer div:

<div ng-init="param='value';">
    <div ng-controller="BasketController" >
        <label>param: {{value}}</label>
    </div>
</div>  

The parameter will then be available in your controller's scope:

function BasketController($scope) {
        console.log($scope.param);
}

How do I validate a date in this format (yyyy-mm-dd) using jquery?

try this Here is working Demo:

$(function() {
    $('#btnSubmit').bind('click', function(){
        var txtVal =  $('#txtDate').val();
        if(isDate(txtVal))
            alert('Valid Date');
        else
            alert('Invalid Date');
    });

function isDate(txtDate)
{
    var currVal = txtDate;
    if(currVal == '')
        return false;

    var rxDatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/; //Declare Regex
    var dtArray = currVal.match(rxDatePattern); // is format OK?

    if (dtArray == null) 
        return false;

    //Checks for mm/dd/yyyy format.
    dtMonth = dtArray[3];
    dtDay= dtArray[5];
    dtYear = dtArray[1];        

    if (dtMonth < 1 || dtMonth > 12) 
        return false;
    else if (dtDay < 1 || dtDay> 31) 
        return false;
    else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31) 
        return false;
    else if (dtMonth == 2) 
    {
        var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
        if (dtDay> 29 || (dtDay ==29 && !isleap)) 
                return false;
    }
    return true;
}

});

changed regex is:

var rxDatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/; //Declare Regex

Format specifier %02x

%02x means print at least 2 digits, prepend it with 0's if there's less. In your case it's 7 digits, so you get no extra 0 in front.

Also, %x is for int, but you have a long. Try %08lx instead.