Programs & Examples On #Drb

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

Claiming that the C++ compiler can produce more optimal code than a competent assembly language programmer is a very bad mistake. And especially in this case. The human always can make the code better than the compiler can, and this particular situation is a good illustration of this claim.

The timing difference you're seeing is because the assembly code in the question is very far from optimal in the inner loops.

(The below code is 32-bit, but can be easily converted to 64-bit)

For example, the sequence function can be optimized to only 5 instructions:

    .seq:
        inc     esi                 ; counter
        lea     edx, [3*eax+1]      ; edx = 3*n+1
        shr     eax, 1              ; eax = n/2
        cmovc   eax, edx            ; if CF eax = edx
        jnz     .seq                ; jmp if n<>1

The whole code looks like:

include "%lib%/freshlib.inc"
@BinaryType console, compact
options.DebugMode = 1
include "%lib%/freshlib.asm"

start:
        InitializeAll
        mov ecx, 999999
        xor edi, edi        ; max
        xor ebx, ebx        ; max i

    .main_loop:

        xor     esi, esi
        mov     eax, ecx

    .seq:
        inc     esi                 ; counter
        lea     edx, [3*eax+1]      ; edx = 3*n+1
        shr     eax, 1              ; eax = n/2
        cmovc   eax, edx            ; if CF eax = edx
        jnz     .seq                ; jmp if n<>1

        cmp     edi, esi
        cmovb   edi, esi
        cmovb   ebx, ecx

        dec     ecx
        jnz     .main_loop

        OutputValue "Max sequence: ", edi, 10, -1
        OutputValue "Max index: ", ebx, 10, -1

        FinalizeAll
        stdcall TerminateAll, 0

In order to compile this code, FreshLib is needed.

In my tests, (1 GHz AMD A4-1200 processor), the above code is approximately four times faster than the C++ code from the question (when compiled with -O0: 430 ms vs. 1900 ms), and more than two times faster (430 ms vs. 830 ms) when the C++ code is compiled with -O3.

The output of both programs is the same: max sequence = 525 on i = 837799.

Angular2 get clicked element id

You can retrieve the value of an attribute by its name, enabling you to get the value of a custom attribute such as an attribute from a Directive:

<button (click)="toggle($event)" id="btn1" myCustomAttribute="somevalue"></button>


toggle( event: Event ) {
  const eventTarget: Element = event.target as Element;
  const elementId: string = eventTarget.id;
  const attribVal: string = eventTarget.attributes['myCustomAttribute'].nodeValue;
}

ERROR 403 in loading resources like CSS and JS in my index.php

Find out the web server user

open up terminal and type lsof -i tcp:80

This will show you the user of the web server process Here is an example from a raspberry pi running debian:

COMMAND   PID     USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
apache2  7478 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7664 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7794 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)

The user is www-data

If you give ownership of the web files to the web server:

chown www-data:www-data -R /opt/lamp/htdocs

And chmod 755 for good measure:

chmod 755 -R /opt/lamp/htdocs

Let me know how you go, maybe you need to use 'sudo' before the command, i.e. sudo chown www-data:www-data -R /opt/lamp/htdocs

if it doesn't work, please give us the output of: ls -al /opt/lamp/htdocs

How to query values from xml nodes?

if you have only one xml in your table, you can convert it in 2 steps:

CREATE TABLE Batches( 
   BatchID int,
   RawXml xml 
)

declare @xml xml=(select top 1 RawXml from @Batches)

SELECT  --b.BatchID,
        x.XmlCol.value('(ReportHeader/OrganizationReportReferenceIdentifier)[1]','VARCHAR(100)') AS OrganizationReportReferenceIdentifier,
        x.XmlCol.value('(ReportHeader/OrganizationNumber)[1]','VARCHAR(100)') AS OrganizationNumber
FROM    @xml.nodes('/CasinoDisbursementReportXmlFile/CasinoDisbursementReport') x(XmlCol)

IntelliJ IDEA generating serialVersionUID

With version v2018.2.1

Go to

Preference > Editor > Inspections > Java > Serialization issues > toggle "Serializable class without 'serialVersionUID'".

A warning should appear next to the class declaration.

Eclipse C++ : "Program "g++" not found in PATH"

I had the same problem in Sublime..

  1. Right click on my computer
  2. Advanced system settings
  3. Environment variables
  4. in system variables, change path to location of '...\MinGW\bin'

Example: D:\work\sublime\MinGW\bin

How to convert image into byte array and byte array to base64 String in android?

I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:

String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
    fis = new FileInputStream(imagefile);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
}

Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);    
byte[] b = baos.toByteArray(); 
encImage = Base64.encodeToString(b, Base64.DEFAULT);

Python base64 data decode

Python 3 (and 2)

import base64
a = 'eW91ciB0ZXh0'
base64.b64decode(a)

Python 2

A quick way to decode it without importing anything:

'eW91ciB0ZXh0'.decode('base64')

or more descriptive

>>> a = 'eW91ciB0ZXh0'
>>> a.decode('base64')
'your text'

Getting attributes of Enum's value

Performance matters

If you want better performance this is the way to go:

public static class AdvancedEnumExtensions
{
    /// <summary>
    /// Gets the custom attribute <typeparamref name="T"/> for the enum constant, if such a constant is defined and has such an attribute; otherwise null.
    /// </summary>
    public static T GetCustomAttribute<T>(this Enum value) where T : Attribute
    {
        return GetField(value)?.GetCustomAttribute<T>(inherit: false);
    }

    /// <summary>
    /// Gets the FieldInfo for the enum constant, if such a constant is defined; otherwise null.
    /// </summary>
    public static FieldInfo GetField(this Enum value)
    {
        ulong u64 = ToUInt64(value);
        return value
            .GetType()
            .GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)
            .Where(f => ToUInt64(f.GetRawConstantValue()) == u64)
            .FirstOrDefault();
    }

    /// <summary>
    /// Checks if an enum constant is defined for this enum value
    /// </summary>
    public static bool IsDefined(this Enum value)
    {
        return GetField(value) != null;
    }

    /// <summary>
    /// Converts the enum value to UInt64
    /// </summary>
    public static ulong ToUInt64(this Enum value) => ToUInt64((object)value);

    private static ulong ToUInt64(object value)
    {
        switch (Convert.GetTypeCode(value))
        {
            case TypeCode.SByte:
            case TypeCode.Int16:
            case TypeCode.Int32:
            case TypeCode.Int64:
                return unchecked((ulong)Convert.ToInt64(value, CultureInfo.InvariantCulture));

            case TypeCode.Byte:
            case TypeCode.UInt16:
            case TypeCode.UInt32:
            case TypeCode.UInt64:
            case TypeCode.Char:
            case TypeCode.Boolean:
                return Convert.ToUInt64(value, CultureInfo.InvariantCulture);

            default: throw new InvalidOperationException("UnknownEnumType");
        }
    }
}

Why does this have better performance?

Because the built-in methods all use code very similar to this except they also run a bunch of other code we don't care about. C#'s Enum code is quite horrible in general.

The above code has been Linq-ified and streamlined so it only contains the bits we care about.

Why is the built-in code slow?

First regarding Enum.ToString() -vs- Enum.GetName(..)

Always use the latter. (Or better yet neither, as will become clear below.)

ToString() uses the latter internally, but again, also does a bunch of other stuff we don't want, e.g. tries to combine flags, print out numbers etc. We are only interested in constants defined inside the enum.

Enum.GetName in turn gets all fields, creates a string array for all names, uses the above ToUInt64 on all of their RawConstantValues to create an UInt64 array of all values, sorts both arrays according to the UInt64 value, and finally gets the name from the name-array by doing a BinarySearch in the UInt64-array to find the index of the value we wanted.

...and then we throw the fields and the sorted arrays away use that name to find the field again.

One word: "Ugh!"

postgresql - replace all instances of a string within text field

You want to use postgresql's replace function:

replace(string text, from text, to text)

for instance :

UPDATE <table> SET <field> = replace(<field>, 'cat', 'dog')

Be aware, though, that this will be a string-to-string replacement, so 'category' will become 'dogegory'. the regexp_replace function may help you define a stricter match pattern for what you want to replace.

Table with fixed header and fixed column on pure css

An example using only CSS:

_x000D_
_x000D_
.table {_x000D_
  table-layout: fixed;_x000D_
  width: 500px;_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
.header th {_x000D_
  font-family: Calibri;_x000D_
  font-size: small;_x000D_
  font-weight: lighter;_x000D_
  border-left: 1px solid #000;_x000D_
  background: #d0d0d0;_x000D_
}_x000D_
_x000D_
.body_panel {_x000D_
  display: inline-block;_x000D_
  width: 520px;_x000D_
  height: 300px;_x000D_
  overflow-y: scroll;_x000D_
}_x000D_
_x000D_
.body tr {_x000D_
  border-bottom: 1px solid #d0d0d0;_x000D_
}_x000D_
_x000D_
.body td {_x000D_
  border-left: 1px solid #d0d0d0;_x000D_
  padding-left: 3px;_x000D_
  font-family: Calibri;_x000D_
  font-size: small;_x000D_
  overflow: hidden;_x000D_
  white-space: nowrap;_x000D_
  text-overflow: ellipsis;_x000D_
}
_x000D_
<body>_x000D_
_x000D_
  <table class="table">_x000D_
_x000D_
    <thead class="header">_x000D_
_x000D_
      <tr>_x000D_
        <th style="width:20%;">teste</th>_x000D_
        <th style="width:30%;">teste 2</th>_x000D_
        <th style="width:50%;">teste 3</th>_x000D_
      </tr>_x000D_
_x000D_
    </thead>_x000D_
  </table>_x000D_
_x000D_
  <div class="body_panel">_x000D_
_x000D_
    <table class="table">_x000D_
      <tbody class="body">_x000D_
_x000D_
        <tr>_x000D_
          <td style="width:20%;">asbkj k kajsb ksb kabkb</td>_x000D_
          <td style="width:30%;">2</td>_x000D_
          <td style="width:50%;">3</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
          <td style="width:20%;">2</td>_x000D_
          <td style="width:30%;">2</td>_x000D_
          <td style="width:50%;">3</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
          <td style="width:20%;">2</td>_x000D_
          <td style="width:30%;">2</td>_x000D_
          <td style="width:50%;">3</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
          <td style="width:20%;">2</td>_x000D_
          <td style="width:30%;">2</td>_x000D_
          <td style="width:50%;">3</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
          <td style="width:20%;">2</td>_x000D_
          <td style="width:30%;">2</td>_x000D_
          <td style="width:50%;">3</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
          <td style="width:20%;">2</td>_x000D_
          <td style="width:30%;">2</td>_x000D_
          <td style="width:50%;">3</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
          <td style="width:20%;">2</td>_x000D_
          <td style="width:30%;">2</td>_x000D_
          <td style="width:50%;">3</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
          <td style="width:20%;">2</td>_x000D_
          <td style="width:30%;">2</td>_x000D_
          <td style="width:50%;">3</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
          <td style="width:20%;">2</td>_x000D_
          <td style="width:30%;">2</td>_x000D_
          <td style="width:50%;">3</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
          <td style="width:20%;">2</td>_x000D_
          <td style="width:30%;">2</td>_x000D_
          <td style="width:50%;">3</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
          <td style="width:20%;">2</td>_x000D_
          <td style="width:30%;">2</td>_x000D_
          <td style="width:50%;">3</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
          <td style="width:20%;">2</td>_x000D_
          <td style="width:30%;">2</td>_x000D_
          <td style="width:50%;">3</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
          <td style="width:20%;">2</td>_x000D_
          <td style="width:30%;">2</td>_x000D_
          <td style="width:50%;">3</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
          <td style="width:20%;">2</td>_x000D_
          <td style="width:30%;">2</td>_x000D_
          <td style="width:50%;">3</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
          <td style="width:20%;">2</td>_x000D_
          <td style="width:30%;">2</td>_x000D_
          <td style="width:50%;">3</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
          <td style="width:20%;">2</td>_x000D_
          <td style="width:30%;">2</td>_x000D_
          <td style="width:50%;">3</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
          <td style="width:20%;">2</td>_x000D_
          <td style="width:30%;">2</td>_x000D_
          <td style="width:50%;">3</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
          <td style="width:20%;">2</td>_x000D_
          <td style="width:30%;">2</td>_x000D_
          <td style="width:50%;">3</td>_x000D_
        </tr>_x000D_
_x000D_
      </tbody>_x000D_
    </table>_x000D_
_x000D_
  </div>_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to determine the IP address of a Solaris system

The following shell script gives a nice tabular result of interfaces and IP addresses (excluding the loopback interface) It has been tested on a Solaris box

/usr/sbin/ifconfig -a | awk '/flags/ {printf $1" "} /inet/ {print $2}' | grep -v lo

ce0: 10.106.106.108
ce0:1: 10.106.106.23
ce0:2: 10.106.106.96
ce1: 10.106.106.109

How to download files using axios

My answer is a total hack- I just created a link that looks like a button and add the URL to that.

<a class="el-button"
  style="color: white; background-color: #58B7FF;"
  :href="<YOUR URL ENDPOINT HERE>"
  :download="<FILE NAME NERE>">
<i class="fa fa-file-excel-o"></i>&nbsp;Excel
</a>

I'm using the excellent VueJs hence the odd anotations, however, this solution is framework agnostic. The idea would work for any HTML based design.

How to get item's position in a list?

Here is another way to do this:

try:
   id = testlist.index('1')
   print testlist[id]
except ValueError:
   print "Not Found"

nginx: send all requests to a single html page

Your original rewrite should almost work. I'm not sure why it would be redirecting, but I think what you really want is just

rewrite ^ /base.html break;

You should be able to put that in a location or directly in the server.

Github Push Error: RPC failed; result=22, HTTP code = 413

when I used the https url to push to the remote master, I met the same proble, I changed it to the SSH address, and everything resumed working flawlessly.

fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

You probably have one .OBJ or .LIB file that's targeted for x64 (that's the module machine type) while you're linking for x86 (that's the target machine type).

Use DUMPBIN /HEADERS on your .OBJ files and check for the machine entry in the FILE HEADER VALUES block.

Check if string contains only whitespace

Use the str.isspace() method:

Return True if there are only whitespace characters in the string and there is at least one character, False otherwise.

A character is whitespace if in the Unicode character database (see unicodedata), either its general category is Zs (“Separator, space”), or its bidirectional class is one of WS, B, or S.

Combine that with a special case for handling the empty string.

Alternatively, you could use str.strip() and check if the result is empty.

Android Crop Center of Bitmap

You can used following code that can solve your problem.

Matrix matrix = new Matrix();
matrix.postScale(0.5f, 0.5f);
Bitmap croppedBitmap = Bitmap.createBitmap(bitmapOriginal, 100, 100,100, 100, matrix, true);

Above method do postScalling of image before cropping, so you can get best result with cropped image without getting OOM error.

For more detail you can refer this blog

Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss

I was trying to format the date string received from a JSON response e.g. 2016-03-09T04:50:00-0800 to yyyy-MM-dd. So here's what I tried and it worked and helped me assign the formatted date string a calendar widget.

String DATE_FORMAT_I = "yyyy-MM-dd'T'HH:mm:ss";
String DATE_FORMAT_O = "yyyy-MM-dd";


SimpleDateFormat formatInput = new SimpleDateFormat(DATE_FORMAT_I);
SimpleDateFormat formatOutput = new SimpleDateFormat(DATE_FORMAT_O);

Date date = formatInput.parse(member.getString("date"));
String dateString = formatOutput.format(date);

This worked. Thanks.

Eclipse - "Workspace in use or cannot be created, chose a different one."

Check that you have enough rights to workspace directory. I got this error when I didn't have write permission to workspace.

How to get the selected item from ListView?

You are implementing the Click Handler rather than Select Handler. A List by default doesn't suppose to have selection.

What you should change, in your above example, is to

public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
    MyClass item = (MyClass) adapter.getItem(position);
}

Login to Microsoft SQL Server Error: 18456

first see the details of the error if "state" is "1" Ensure the database is set for both SQL and Windows authentication under SQL server / Properties / Security.

for other state see the above answers ....

how to use a like with a join in sql?

When writing queries with our server LIKE or INSTR (or CHARINDEX in T-SQL) takes too long, so we use LEFT like in the following structure:

select *
from little
left join big
on left( big.key, len(little.key) ) = little.key

I understand that might only work with varying endings to the query, unlike other suggestions with '%' + b + '%', but is enough and much faster if you only need b+'%'.

Another way to optimize it for speed (but not memory) is to create a column in "little" that is "len(little.key)" as "lenkey" and user that instead in the query above.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

Had similar error with the same result with Gradle and was able to solve it by following:

//compile 'org.slf4j:slf4j-api:1.7.1'
compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.1'
compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.1'
compile group: 'org.apache.logging.log4j', name: 'log4j-slf4j-impl', version: '2.1'

Out-commented line is the one which caused the error output. I believe you can transfer this to Maven.

Can regular expressions be used to match nested patterns?

Yes, if it is .NET RegEx-engine. .Net engine supports finite state machine supplied with an external stack. see details

How to edit one specific row in Microsoft SQL Server Management Studio 2008?

Use the "Edit top 200" option, then click on "Show SQL panel", modify your query with your WHERE clause, and execute the query. You'll be able to edit the results.

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

The easiest way to get what you want is set your table style as UITableViewStyleGrouped, separator style as UITableViewCellSeparatorStyleNone:

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN; // return 0.01f; would work same 
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

Do not try return footer view as nil, don't forget set header height and header view, after you must get what you desired.

how to remove multiple columns in r dataframe?

x <-dplyr::select(dataset_df, -c('coloumn1', 'column2'))

This works for me.

How to refresh activity after changing language (Locale) inside application

I solved my problem with this code

public void setLocale(String lang) {

        myLocale = new Locale(lang);
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;
        res.updateConfiguration(conf, dm);

        onConfigurationChanged(conf);
    }



    @Override
    public void onConfigurationChanged(Configuration newConfig) 
    {
        iv.setImageDrawable(getResources().getDrawable(R.drawable.keyboard));
        greet.setText(R.string.greet);
        textView1.setText(R.string.langselection);

        super.onConfigurationChanged(newConfig);

    }

jQuery changing css class to div

$(document).ready(function () {

            $("#divId").toggleClass('cssclassname'); // toggle class
});

**OR**

$(document).ready(function() {
        $("#objectId").click(function() {  // click or other event to change the div class
                $("#divId").toggleClass("cssclassname");     // toggle class
        )}; 
)};

Maven: How to rename the war file for the project?

You need to configure the war plugin:

<project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.3</version>
        <configuration>
          <warName>bird.war</warName>
        </configuration>
      </plugin>
    </plugins>
  </build>
  ...
</project>

More info here

jQuery Ajax File Upload

To get all your form inputs, including the type="file" you need to use FormData object. you will be able to see the formData content in the debugger -> network ->Headers after you will submit the form.

var url = "YOUR_URL";

var form = $('#YOUR_FORM_ID')[0];
var formData = new FormData(form);


$.ajax(url, {
    method: 'post',
    processData: false,
    contentType: false,
    data: formData
}).done(function(data){
    if (data.success){ 
        alert("Files uploaded");
    } else {
        alert("Error while uploading the files");
    }
}).fail(function(data){
    console.log(data);
    alert("Error while uploading the files");
});

Push item to associative array in PHP

i use php5.6

code:

$person = ["name"=>"mohammed", "age"=>30];

$person['addr'] = "Sudan";

print_r($person) 

output

Array( ["name"=>"mohammed", "age"=>30, "addr"=>"Sudan"] )

How to Solve Max Connection Pool Error

May be this is alltime multiple connection open issue, you are somewhere in your code opening connections and not closing them properly. use

 using (SqlConnection con = new SqlConnection(connectionString))
        {
            con.Open();
         }

Refer this article: http://msdn.microsoft.com/en-us/library/ms254507(v=vs.80).aspx, The Using block in Visual Basic or C# automatically disposes of the connection when the code exits the block, even in the case of an unhandled exception.

Render HTML to an image

Use this code, it will surely work:

_x000D_
_x000D_
<script type="text/javascript">_x000D_
 $(document).ready(function () {_x000D_
  setTimeout(function(){_x000D_
   downloadImage();_x000D_
  },1000)_x000D_
 });_x000D_
 _x000D_
 function downloadImage(){_x000D_
  html2canvas(document.querySelector("#dvContainer")).then(canvas => {_x000D_
  a = document.createElement('a'); _x000D_
  document.body.appendChild(a); _x000D_
  a.download = "test.png"; _x000D_
  a.href =  canvas.toDataURL();_x000D_
  a.click();_x000D_
 });  _x000D_
 }_x000D_
</script>
_x000D_
_x000D_
_x000D_

Just do not forget to include Html2CanvasJS file in your program. https://html2canvas.hertzen.com/dist/html2canvas.js

How to get datas from List<Object> (Java)?

Thanks All for your responses. Good solution was to use 'brain`s' method:

List<Object> list = getHouseInfo();
for (int i=0; i<list.size; i++){
Object[] row = (Object[]) list.get(i);
System.out.println("Element "+i+Arrays.toString(row));
}

Problem solved. Thanks again.

With MySQL, how can I generate a column containing the record index in a table?

I know the OP is asking for a mysql answer but since I found the other answers not working for me,

  • Most of them fail with order by
  • Or they are simply very inefficient and make your query very slow for a fat table

So to save time for others like me, just index the row after retrieving them from database

example in PHP:

$users = UserRepository::loadAllUsersAndSortByScore();

foreach($users as $index=>&$user){
    $user['rank'] = $index+1;
}

example in PHP using offset and limit for paging:

$limit = 20; //page size
$offset = 3; //page number

$users = UserRepository::loadAllUsersAndSortByScore();

foreach($users as $index=>&$user){
    $user['rank'] = $index+1+($limit*($offset-1));
}

jQuery UI tabs. How to select a tab based on its id not based on index

                <div id="tabs" style="width: 290px">
                    <ul >
                        <li><a id="myTab1" href="#tabs-1" style="color: Green">Báo cáo chu?n</a></li>
                        <li><a id="myTab2" href="#tabs-2" style="color: Green">Báo cáo m? r?ng</a></li>
                    </ul>
                    <div id="tabs-1" style="overflow-x: auto">
                        <ul class="nav">

                            <li><a href="@Url.Content("~/Report/ReportDate")"><span class=""></span>Báo cáo theo ngày</a></li>

                        </ul>
                    </div>
                    <div id="tabs-2" style="overflow-x: auto; height: 290px">
                        <ul class="nav">

                            <li><a href="@Url.Content("~/Report/PetrolReport#tabs-2")"><span class=""></span>Báo cáo nhiên li?u</a></li>
                        </ul>
                    </div>
                </div>


        var index = $("#tabs div").index($("#tabs-1" ));
        $("#tabs").tabs("select", index);
       $("#tabs-1")[0].classList.remove("ui-tabs-hide");

How to calculate the running time of my program?

Use System.nanoTime to get the current time.

long startTime = System.nanoTime();
.....your program....
long endTime   = System.nanoTime();
long totalTime = endTime - startTime;
System.out.println(totalTime);

The above code prints the running time of the program in nanoseconds.

Convert dictionary values into array

There is a ToArray() function on Values:

Foo[] arr = new Foo[dict.Count];    
dict.Values.CopyTo(arr, 0);

But I don't think its efficient (I haven't really tried, but I guess it copies all these values to the array). Do you really need an Array? If not, I would try to pass IEnumerable:

IEnumerable<Foo> foos = dict.Values;

How to find the socket connection state in C?

You could call getsockopt just like the following:

int error = 0;
socklen_t len = sizeof (error);
int retval = getsockopt (socket_fd, SOL_SOCKET, SO_ERROR, &error, &len);

To test if the socket is up:

if (retval != 0) {
    /* there was a problem getting the error code */
    fprintf(stderr, "error getting socket error code: %s\n", strerror(retval));
    return;
}

if (error != 0) {
    /* socket has a non zero error status */
    fprintf(stderr, "socket error: %s\n", strerror(error));
}

Swift - How to detect orientation changes

Swift 3 Above code updated:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)

    if UIDevice.current.orientation.isLandscape {
        print("Landscape")
    } else {
        print("Portrait")
    }
}

How to resolve conflicts in EGit

This guide was helpful for me http://wiki.eclipse.org/EGit/User_Guide#Resolving_a_merge_conflict.

UPDATED Just a note on that about my procedure, this is how I proceed:

  1. Commit My change
  2. Fetch (Syncrhonize workspace)
  3. Pull
  4. Manage Conflicts with Merge Tool (Team->Merge Tool) and Save
  5. Add each file to stage (Team -> Add to index)
  6. Now the Commit Message in the Stage window is prefilled with "Merged XXX". You can leave as it is or change the commit message
  7. Commit and Push

It is dangerous in some cases but it is very usefull to avoid to use external tool like Git Extension or Source Tree

How can I select and upload multiple files with HTML and PHP, using HTTP POST?

Full solution in Firefox 5:

<html>
<head>
</head>
<body>
 <form name="uploader" id="uploader" action="multifile.php" method="POST" enctype="multipart/form-data" >
  <input id="infile" name="infile[]" type="file" onBlur="submit();" multiple="true" ></input> 
 </form>

<?php
echo "No. files uploaded : ".count($_FILES['infile']['name'])."<br>"; 


$uploadDir = "images/";
for ($i = 0; $i < count($_FILES['infile']['name']); $i++) {

 echo "File names : ".$_FILES['infile']['name'][$i]."<br>";
 $ext = substr(strrchr($_FILES['infile']['name'][$i], "."), 1); 

 // generate a random new file name to avoid name conflict
 $fPath = md5(rand() * time()) . ".$ext";

 echo "File paths : ".$_FILES['infile']['tmp_name'][$i]."<br>";
 $result = move_uploaded_file($_FILES['infile']['tmp_name'][$i], $uploadDir . $fPath);

 if (strlen($ext) > 0){
  echo "Uploaded ". $fPath ." succefully. <br>";
 }
}
echo "Upload complete.<br>";
?>

</body>
</html>

Short description of the scoping rules?

Python resolves your variables with -- generally -- three namespaces available.

At any time during execution, there are at least three nested scopes whose namespaces are directly accessible: the innermost scope, which is searched first, contains the local names; the namespaces of any enclosing functions, which are searched starting with the nearest enclosing scope; the middle scope, searched next, contains the current module's global names; and the outermost scope (searched last) is the namespace containing built-in names.

There are two functions: globals and locals which show you the contents two of these namespaces.

Namespaces are created by packages, modules, classes, object construction and functions. There aren't any other flavors of namespaces.

In this case, the call to a function named x has to be resolved in the local name space or the global namespace.

Local in this case, is the body of the method function Foo.spam.

Global is -- well -- global.

The rule is to search the nested local spaces created by method functions (and nested function definitions), then search global. That's it.

There are no other scopes. The for statement (and other compound statements like if and try) don't create new nested scopes. Only definitions (packages, modules, functions, classes and object instances.)

Inside a class definition, the names are part of the class namespace. code2, for instance, must be qualified by the class name. Generally Foo.code2. However, self.code2 will also work because Python objects look at the containing class as a fall-back.

An object (an instance of a class) has instance variables. These names are in the object's namespace. They must be qualified by the object. (variable.instance.)

From within a class method, you have locals and globals. You say self.variable to pick the instance as the namespace. You'll note that self is an argument to every class member function, making it part of the local namespace.

See Python Scope Rules, Python Scope, Variable Scope.

Keyboard shortcuts are not active in Visual Studio with Resharper installed

I had the same problem with Visual Studio 2015 and Resharper 9.2

"Resharper 9 keyboard shortcuts not working in Visual Studio 2015"

I had tried all possible resetting and applying keyboard schemes and found the answer from Yuri Fedoseev.

My Windows 10 language configuration only had Swedish in the language preferences "Control Panel\Clock, Language, and Region\Language"

The solution was to add English(I chose the US version) in the language list. And then go to Resharper > Options > Keyboard & Menus > Apply Scheme. (perhaps you do not even need to apply the scheme)

increase font size of hyperlink text html

increase the padding size of font and then try to increase font size:-

style="padding-bottom:40px; font-size: 50px;"

On Selenium WebDriver how to get Text from Span Tag

String kk = wd.findElement(By.xpath(//*[@id='customSelect_3']/div[1]/span));

kk.getText().toString();

System.out.println(+kk.getText().toString());

Bootstrap dropdown menu not working (not dropping down when clicked)

Just Remove the type="text/javascript"

<script src="JavaScript/jquery.js" />
<script src="JavaScript/bootstrap-min.js" />

Here is the update - http://jsfiddle.net/andieje/kRX6n/

Attempt to write a readonly database - Django w/ SELinux error

You can change acls without touching the ownership and permissions of file/directory.

Use the following commands:

setfacl -m u:www-data:rwx /home/user/website
setfacl -m u:www-data:rw /home/user/website/db.sqlite3

How to call another components function in angular2

It depends on the relation between your components (parent / child) but the best / generic way to make communicate components is to use a shared service.

See this doc for more details:

That being said, you could use the following to provide an instance of the com1 into com2:

<div>
  <com1 #com1>...</com1>
  <com2 [com1ref]="com1">...</com2>
</div>

In com2, you can use the following:

@Component({
  selector:'com2'
})
export class com2{
  @Input()
  com1ref:com1;

  function2(){
    // i want to call function 1 from com1 here
    this.com1ref.function1();
  }
}

Differences between git pull origin master & git pull origin/master

git pull = git fetch + git merge origin/branch

git pull and git pull origin branch only differ in that the latter will only "update" origin/branch and not all origin/* as git pull does.

git pull origin/branch will just not work because it's trying to do a git fetch origin/branch which is invalid.

Question related: git fetch + git merge origin/master vs git pull origin/master

html select scroll bar

One options will be to show the selected option above (or below) the select list like following:

HTML

<div id="selText"><span>&nbsp;</span></div><br/>
<select size="4" id="mySelect" style="width:65px;color:#f98ad3;">
    <option value="1" selected>option 1 The Long Option</option>
    <option value="2">option 2</option>
    <option value="3">option 3</option>
    <option value="4">option 4</option>
    <option value="5">option 5 Another Longer than the Long Option ;)</option>
    <option value="6">option 6</option>
</select>

JavaScript

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"   
  type="text/javascript"></script> 
<script type="text/javascript">
$(document).ready(function(){        
    $("select#mySelect").change(function(){
      //$("#selText").html($($(this).children("option:selected")[0]).text());
       var txt = $($(this).children("option:selected")[0]).text();
       $("<span>" + txt + "<br/></span>").appendTo($("#selText span:last"));
    });
});
</script>

PS:- Set height of div#selText otherwise it will keep shifting select list downward.

Python set to list

s = set([1,2,3])
print [ x for x in iter(s) ]

Browser Caching of CSS files

Unless you've messed with your server, yes it's cached. All the browsers are supposed to handle it the same. Some people (like me) might have their browsers configured so that it doesn't cache any files though. Closing the browser doesn't invalidate the file in the cache. Changing the file on the server should cause a refresh of the file however.

How to read file with async/await properly?

To use await/async you need methods that return promises. The core API functions don't do that without wrappers like promisify:

const fs = require('fs');
const util = require('util');

// Convert fs.readFile into Promise version of same    
const readFile = util.promisify(fs.readFile);

function getStuff() {
  return readFile('test');
}

// Can't use `await` outside of an async function so you need to chain
// with then()
getStuff().then(data => {
  console.log(data);
})

As a note, readFileSync does not take a callback, it returns the data or throws an exception. You're not getting the value you want because that function you supply is ignored and you're not capturing the actual return value.

How do I replace text inside a div element?

If you're inclined to start using a lot of JavaScript on your site, jQuery makes playing with the DOM extremely simple.

http://docs.jquery.com/Manipulation

Makes it as simple as: $("#field-name").text("Some new text.");

Quoting backslashes in Python string literals

What Harley said, except the last point - it's not actually necessary to change the '/'s into '\'s before calling open. Windows is quite happy to accept paths with forward slashes.

infile = open('c:/folder/subfolder/file.txt')

The only time you're likely to need the string normpathed is if you're passing to to another program via the shell (using os.system or the subprocess module).

How to insert a data table into SQL Server database table?

If it's the first time for you to save your datatable

Do this (using bulk copy). Assure there are no PK/FK constraint

SqlBulkCopy bulkcopy = new SqlBulkCopy(myConnection);
//I assume you have created the table previously
//Someone else here already showed how  
bulkcopy.DestinationTableName = table.TableName;
try                             
{                                 
    bulkcopy.WriteToServer(table);                            
}     
    catch(Exception e)
{
    messagebox.show(e.message);
} 

Now since you already have a basic record. And you just want to check new record with the existing one. You can simply do this.

This will basically take existing table from database

DataTable Table = new DataTable();

SqlConnection Connection = new SqlConnection("ConnectionString");
//I assume you know better what is your connection string

SqlDataAdapter adapter = new SqlDataAdapter("Select * from " + TableName, Connection);

adapter.Fill(Table);

Then pass this table to this function

public DataTable CompareDataTables(DataTable first, DataTable second)
{
    first.TableName = "FirstTable";
    second.TableName = "SecondTable";

    DataTable table = new DataTable("Difference");

    try
    {
        using (DataSet ds = new DataSet())
        {
            ds.Tables.AddRange(new DataTable[] { first.Copy(), second.Copy() });

            DataColumn[] firstcolumns = new DataColumn[ds.Tables[0].Columns.Count];

            for (int i = 0; i < firstcolumns.Length; i++)
            {
                firstcolumns[i] = ds.Tables[0].Columns[i];
            }

            DataColumn[] secondcolumns = new DataColumn[ds.Table[1].Columns.Count];

            for (int i = 0; i < secondcolumns.Length; i++)
            {
                secondcolumns[i] = ds.Tables[1].Columns[i];
            }

            DataRelation r = new DataRelation(string.Empty, firstcolumns, secondcolumns, false);

            ds.Relations.Add(r);

            for (int i = 0; i < first.Columns.Count; i++)
            {
                table.Columns.Add(first.Columns[i].ColumnName, first.Columns[i].DataType);
            }

            table.BeginLoadData();

            foreach (DataRow parentrow in ds.Tables[0].Rows)
            {
                DataRow[] childrows = parentrow.GetChildRows(r);
                if (childrows == null || childrows.Length == 0)
                    table.LoadDataRow(parentrow.ItemArray, true);
            }

            table.EndLoadData();

        }
    }

    catch (Exception ex)
    {
        throw ex;
    }

    return table;
}

This will return a new DataTable with the changed rows updated. Please ensure you call the function correctly. The DataTable first is supposed to be the latest.

Then repeat the bulkcopy function all over again with this fresh datatable.

Days between two dates?

Assuming you’ve literally got two date objects, you can subtract one from the other and query the resulting timedelta object for the number of days:

>>> from datetime import date
>>> a = date(2011,11,24)
>>> b = date(2011,11,17)
>>> a-b
datetime.timedelta(7)
>>> (a-b).days
7

And it works with datetimes too — I think it rounds down to the nearest day:

>>> from datetime import datetime
>>> a = datetime(2011,11,24,0,0,0)
>>> b = datetime(2011,11,17,23,59,59)
>>> a-b
datetime.timedelta(6, 1)
>>> (a-b).days
6

C++ Object Instantiation

On the contrary, you should always prefer stack allocations, to the extent that as a rule of thumb, you should never have new/delete in your user code.

As you say, when the variable is declared on the stack, its destructor is automatically called when it goes out of scope, which is your main tool for tracking resource lifetime and avoiding leaks.

So in general, every time you need to allocate a resource, whether it's memory (by calling new), file handles, sockets or anything else, wrap it in a class where the constructor acquires the resource, and the destructor releases it. Then you can create an object of that type on the stack, and you're guaranteed that your resource gets freed when it goes out of scope. That way you don't have to track your new/delete pairs everywhere to ensure you avoid memory leaks.

The most common name for this idiom is RAII

Also look into smart pointer classes which are used to wrap the resulting pointers on the rare cases when you do have to allocate something with new outside a dedicated RAII object. You instead pass the pointer to a smart pointer, which then tracks its lifetime, for example by reference counting, and calls the destructor when the last reference goes out of scope. The standard library has std::unique_ptr for simple scope-based management, and std::shared_ptr which does reference counting to implement shared ownership.

Many tutorials demonstrate object instantiation using a snippet such as ...

So what you've discovered is that most tutorials suck. ;) Most tutorials teach you lousy C++ practices, including calling new/delete to create variables when it's not necessary, and giving you a hard time tracking lifetime of your allocations.

Fill DataTable from SQL Server database

If the variable table contains invalid characters (like a space) you should add square brackets around the variable.

public DataTable fillDataTable(string table)
{
    string query = "SELECT * FROM dstut.dbo.[" + table + "]";

    using(SqlConnection sqlConn = new SqlConnection(conSTR))
    using(SqlCommand cmd = new SqlCommand(query, sqlConn))
    {
        sqlConn.Open();
        DataTable dt = new DataTable();
        dt.Load(cmd.ExecuteReader());
        return dt;
    }
}

By the way, be very careful with this kind of code because is open to Sql Injection. I hope for you that the table name doesn't come from user input

Java 8 forEach with index

Since you are iterating over an indexable collection (lists, etc.), I presume that you can then just iterate with the indices of the elements:

IntStream.range(0, params.size())
  .forEach(idx ->
    query.bind(
      idx,
      params.get(idx)
    )
  )
;

The resulting code is similar to iterating a list with the classic i++-style for loop, except with easier parallelizability (assuming, of course, that concurrent read-only access to params is safe).

how to create a logfile in php?

create a logfile in php, to do it you need to pass data on function and it will create log file for you.

function wh_log($log_msg)
{
    $log_filename = "log";
    if (!file_exists($log_filename)) 
    {
        // create directory/folder uploads.
        mkdir($log_filename, 0777, true);
    }
    $log_file_data = $log_filename.'/log_' . date('d-M-Y') . '.log';
    // if you don't add `FILE_APPEND`, the file will be erased each time you add a log
    file_put_contents($log_file_data, $log_msg . "\n", FILE_APPEND);
} 
// call to function
wh_log("this is my log message");

Calculating the position of points in a circle

The angle between each of your points is going to be 2Pi/x so you can say that for points n= 0 to x-1 the angle from a defined 0 point is 2nPi/x.

Assuming your first point is at (r,0) (where r is the distance from the centre point) then the positions relative to the central point will be:

rCos(2nPi/x),rSin(2nPi/x)

How to get data from Magento System Configuration

you should you use following code

$configValue = Mage::getStoreConfig(
                   'sectionName/groupName/fieldName',
                   Mage::app()->getStore()
               ); 

Mage::app()->getStore() this will add store code in fetch values so that you can get correct configuration values for current store this will avoid incorrect store's values because magento is also use for multiple store/views so must add store code to fetch anything in magento.

if we have more then one store or multiple views configured then this will insure that we are getting values for current store

"Undefined reference to" template class constructor

You will have to define the functions inside your header file.
You cannot separate definition of template functions in to the source file and declarations in to header file.

When a template is used in a way that triggers its intstantation, a compiler needs to see that particular templates definition. This is the reason templates are often defined in the header file in which they are declared.

Reference:
C++03 standard, § 14.7.2.4:

The definition of a non-exported function template, a non-exported member function template, or a non-exported member function or static data member of a class template shall be present in every translation unit in which it is explicitly instantiated.

EDIT:
To clarify the discussion on the comments:
Technically, there are three ways to get around this linking problem:

  • To move the definition to the .h file
  • Add explicit instantiations in the .cpp file.
  • #include the .cpp file defining the template at the .cpp file using the template.

Each of them have their pros and cons,

Moving the defintions to header files may increase the code size(modern day compilers can avoid this) but will increase the compilation time for sure.

Using the explicit instantiation approach is moving back on to traditional macro like approach.Another disadvantage is that it is necessary to know which template types are needed by the program. For a simple program this is easy but for complicated program this becomes difficult to determine in advance.

While including cpp files is confusing at the same time shares the problems of both above approaches.

I find first method the easiest to follow and implement and hence advocte using it.

The remote server returned an error: (407) Proxy Authentication Required

Thought of writing this answer as nothing worked from above & you don't want to specify proxy location.

If you're using httpClient then consider this.

HttpClientHandler handler = new HttpClientHandler();

IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = CredentialCache.DefaultCredentials;
handler.Proxy = proxy;

var client = new HttpClient(handler);
// your next steps...

And if you're using HttpWebRequest:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri + _endpoint);

IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = CredentialCache.DefaultCredentials;
request.Proxy = proxy;

Kind referencce: https://medium.com/@siriphonnot/the-remote-server-returned-an-error-407-proxy-authentication-required-86ae489e401b

Skip to next iteration in loop vba

For i = 2 To 24
  Level = Cells(i, 4)
  Return = Cells(i, 5)

  If Return = 0 And Level = 0 Then GoTo NextIteration
  'Go to the next iteration
  Else
  End If
  ' This is how you make a line label in VBA - Do not use keyword or
  ' integer and end it in colon
  NextIteration:
Next

Eclipse - Unable to install breakpoint due to missing line number attributes

Dont know if this is still relevant, perhaps another sailor will find this useful.

The message appears when one has a class file compiled the debug flags turned off.

In eclipse, you can turn it on by the afore mentioned options,

Window --> Preferences --> Java --> Compiler --> Classfile Generation: "add line number attributes to generated class file"

But if you have a jar file, then you would get the compiled output. There is no easy way to fix this problem.

If you have access to the source and use ant to get the jar file, you may modify the ant task as follows.

  <javac  destdir="${build.destDir}" srcdir="${build.srcDir}" source="1.6" fork="true" target="${javac.target}" debug="on" debuglevel="lines,vars,source" deprecation="on" memoryInitialSize="512m" memoryMaximumSize="1024m" optimize="true"   >

Happy debugging..

ref: http://doc.sumy.ua/prog/Java/javanut/ch16_04.htm

How to include external Python code to use in other files?

You will need to import the other file as a module like this:

import Math

If you don't want to prefix your Calculate function with the module name then do this:

from Math import Calculate

If you want to import all members of a module then do this:

from Math import *

Edit: Here is a good chapter from Dive Into Python that goes a bit more in depth on this topic.

Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted

Just set the memory_limit specifying the full route of your composer.phar file and update, in my case with the command:

php -d memory_limit=-1 C:/wamp64/composer.phar update

Laravel: PDOException: could not find driver

ERROR: could not find driver (SQL: select * from tests where slug = a limit 1)

I was getting the above error in my laravel project, i am using nginx server on ubuntu 16.04

This error is because, php-mysql driver is missing. To install it type following command.

sudo apt-get install php7.2-mysql

Please specify your current php version in above command.

Open php.ini file and uncomment the followling line of code(Remove Semicolon).

;extension=pdo_mysql

Then Restart the nginx and php service

sudo systemctl restart php7.2-fpm
sudo systemctl restart nginx

It worked for me.

Export table to file with column headers (column names) using the bcp utility and SQL Server 2008

Everyone's versions do things a little different. This is the version that I have developed over the years. This version seems to account for all of the issues I have encountered. Simply populate a data set into a table then pass the table name to this stored procedure.

I call this stored procedure like this:

EXEC    @return_value = *DB_You_Create_The_SP_In*.[dbo].[Export_CSVFile]
        @DB = N'*YourDB*',
        @TABLE_NAME = N'*YourTable*',
        @Dir = N'*YourOutputDirectory*',
        @File = N'*YourOutputFileName*'

There are also two other variables:

  • @NullBlanks -- This will take any field that doesn't have a value and null it. This is useful because in the true sense of the CSV specification each data point should have quotes around them. If you have a large data set this will save you a fair amount of space by not having "" (two double quotes) in those fields. If you don't find this useful then set it to 0.
  • @IncludeHeaders -- I have one stored procedure for outputting CSV files, so I do have that flag in the event I don't want headers.

This will create the stored procedure:

CREATE PROCEDURE [dbo].[Export_CSVFile] 
(@DB varchar(128),@TABLE_NAME varchar(128), @Dir varchar(255), @File varchar(250),@NULLBLANKS bit=1,@IncludeHeader bit=1)
AS

DECLARE @CSVHeader varchar(max)=''  --CSV Header
, @CmdExc varchar(max)=''           --EXEC commands
, @SQL varchar(max)=''              --SQL Statements
, @COLUMN_NAME varchar(128)=''      --Column Names
, @DATA_TYPE varchar(15)=''         --Data Types

DECLARE @T table (COLUMN_NAME varchar(128),DATA_TYPE varchar(15))

--BEGIN Ensure Dir variable has a backslash as the final character
IF NOT RIGHT(@Dir,1) = '\' BEGIN SET @Dir=@Dir+'\' END
--END

--BEGIN Drop TEMP Table IF Exists
SET @SQL='IF (EXISTS (SELECT * FROM '+@DB+'.INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = ''TEMP_'+@TABLE_NAME+''')) BEGIN EXEC(''DROP TABLE ['+@DB+'].[dbo].[TEMP_'+@TABLE_NAME+']'') END'
EXEC(@SQL)
--END

SET @SQL='SELECT COLUMN_NAME,DATA_TYPE FROM '+@DB+'.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='''+@TABLE_NAME+''' ORDER BY ORDINAL_POSITION'
INSERT INTO @T
EXEC (@SQL)

SET @SQL=''
WHILE exists(SELECT * FROM @T)
    BEGIN
        SELECT top(1) @DATA_TYPE=DATA_TYPE,@COLUMN_NAME=COLUMN_NAME FROM @T
        IF @DATA_TYPE LIKE '%char%' OR @DATA_TYPE LIKE '%text'
            BEGIN 
            IF @NULLBLANKS = 1
                BEGIN
                    SET @SQL+='CASE PATINDEX(''%[0-9,a-z]%'','+@COLUMN_NAME+') WHEN ''0'' THEN NULL ELSE ''"''+RTRIM(LTRIM('+@COLUMN_NAME+'))+''"'' END AS ['+@COLUMN_NAME+'],' 
                END
            ELSE
                BEGIN
                    SET @SQL+='''"''+RTRIM(LTRIM('+@COLUMN_NAME+'))+''"'' AS ['+@COLUMN_NAME+'],' 
                END
            END
        ELSE
            BEGIN SET @SQL+=@COLUMN_NAME+',' END
            SET @CSVHeader+='"'+@COLUMN_NAME+'",'
            DELETE top(1) @T
    END 

IF LEN(@CSVHeader)>1 BEGIN SET @CSVHeader=RTRIM(LTRIM(LEFT(@CSVHeader,LEN(@CSVHeader)-1))) END

IF LEN(@SQL)>1 BEGIN SET @SQL= 'SELECT '+ LEFT(@SQL,LEN(@SQL)-1) + ' INTO ['+@DB+'].[dbo].[TEMP_'+@TABLE_NAME+'] FROM ['+@DB+'].[dbo].['+@TABLE_NAME+']' END
EXEC(@SQL)

IF @IncludeHeader=0 
    BEGIN
        --BEGIN Create Data file
        SET  @CmdExc ='BCP "'+@DB+'.dbo.TEMP_'+@TABLE_NAME+'" out "'+@Dir+'Data_'+@TABLE_NAME+'.csv" /c /t, -T' 
        EXEC master..xp_cmdshell @CmdExc
        --END
        SET  @CmdExc ='del '+@Dir+@File EXEC master..xp_cmdshell @CmdExc
        SET  @CmdExc ='ren '+@Dir+'Data_'+@TABLE_NAME+'.csv '+@File EXEC master..xp_cmdshell @CmdExc
    END 
else
    BEGIN

        --BEGIN Create Header and main file
        SET  @CmdExc ='echo '+@CSVHeader+'> '+@Dir+@File EXEC master..xp_cmdshell @CmdExc
        --END

        --BEGIN Create Data file
        SET  @CmdExc ='BCP "'+@DB+'.dbo.TEMP_'+@TABLE_NAME+'" out "'+@Dir+'Data_'+@TABLE_NAME+'.csv" /c /t, -T' 
        EXEC master..xp_cmdshell @CmdExc
        --END

        --BEGIN Merge Data File With Header File
        SET @CmdExc = 'TYPE '+@Dir+'Data_'+@TABLE_NAME+'.csv >> '+@Dir+@File EXEC master..xp_cmdshell @CmdExc
        --END

        --BEGIN Delete Data File
        SET @CmdExc = 'DEL /q '+@Dir+'Data_'+@TABLE_NAME+'.csv' EXEC master..xp_cmdshell @CmdExc
        --END
    END
--BEGIN Drop TEMP Table IF Exists
SET @SQL='IF (EXISTS (SELECT * FROM '+@DB+'.INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = ''TEMP_'+@TABLE_NAME+''')) BEGIN EXEC(''DROP TABLE ['+@DB+'].[dbo].[TEMP_'+@TABLE_NAME+']'') END'
EXEC(@SQL)

Java properties UTF-8 encoding in Eclipse

If the properties are for XML or HTML, it's safest to use XML entities. They're uglier to read, but it means that the properties file can be treated as straight ASCII, so nothing will get mangled.

Note that HTML has entities that XML doesn't, so I keep it safe by using straight XML: http://www.w3.org/TR/html4/sgml/entities.html

How to install VS2015 Community Edition offline

For the latest VS2015 sp3, the command line shoud be:

en_visual_studio_community_2015_with_update_3_x86_x64_web_installer_8922963.exe /Layout c:\VS2015sp3_offline

Remove empty strings from a list of strings

>>> lstr = ['hello', '', ' ', 'world', ' ']
>>> lstr
['hello', '', ' ', 'world', ' ']

>>> ' '.join(lstr).split()
['hello', 'world']

>>> filter(None, lstr)
['hello', ' ', 'world', ' ']

Compare time

>>> from timeit import timeit
>>> timeit('" ".join(lstr).split()', "lstr=['hello', '', ' ', 'world', ' ']", number=10000000)
4.226747989654541
>>> timeit('filter(None, lstr)', "lstr=['hello', '', ' ', 'world', ' ']", number=10000000)
3.0278358459472656

Notice that filter(None, lstr) does not remove empty strings with a space ' ', it only prunes away '' while ' '.join(lstr).split() removes both.

To use filter() with white space strings removed, it takes a lot more time:

>>> timeit('filter(None, [l.replace(" ", "") for l in lstr])', "lstr=['hello', '', ' ', 'world', ' ']", number=10000000)
18.101892948150635

How to trim a list in Python

>>> [1,2,3,4,5,6,7,8,9][:5]
[1, 2, 3, 4, 5]
>>> [1,2,3][:5]
[1, 2, 3]

How to compare two java objects

You need to implement the equals() method in your MyClass.

The reason that == didn't work is this is checking that they refer to the same instance. Since you did new for each, each one is a different instance.

The reason that equals() didn't work is because you didn't implement it yourself yet. I believe it's default behavior is the same thing as ==.

Note that you should also implement hashcode() if you're going to implement equals() because a lot of java.util Collections expect that.

How do I tell if .NET 3.5 SP1 is installed?

You could go to SmallestDotNet using IE from the server. That will tell you the version and also provide a download link if you're out of date.

JAX-WS client : what's the correct path to access the local WSDL?

Had the exact same problem that is described herein. No matter what I did, following the above examples, to change the location of my WSDL file (in our case from a web server), it was still referencing the original location embedded within the source tree of the server process.

After MANY hours trying to debug this, I noticed that the Exception was always being thrown from the exact same line (in my case 41). Finally this morning, I decided to just send my source client code to our trade partner so they can at least understand how the code looks, but perhaps build their own. To my shock and horror I found a bunch of class files mixed in with my .java files within my client source tree. How bizarre!! I suspect these were a byproduct of the JAX-WS client builder tool.

Once I zapped those silly .class files and performed a complete clean and rebuild of the client code, everything works perfectly!! Redonculous!!

YMMV, Andrew

How to copy a file to another path?

File.Move(@"c:\filename", @"c:\filenamet\filename.txt");

Difference between Activity and FragmentActivity

A FragmentActivity is a subclass of Activity that was built for the Android Support Package.

The FragmentActivity class adds a couple new methods to ensure compatibility with older versions of Android, but other than that, there really isn't much of a difference between the two. Just make sure you change all calls to getLoaderManager() and getFragmentManager() to getSupportLoaderManager() and getSupportFragmentManager() respectively.

UPDATE multiple tables in MySQL using LEFT JOIN

                DECLARE @cols VARCHAR(max),@colsUpd VARCHAR(max), @query VARCHAR(max),@queryUpd VARCHAR(max), @subQuery VARCHAR(max)
DECLARE @TableNameTest NVARCHAR(150)
SET @TableNameTest = @TableName+ '_Staging';
SELECT  @colsUpd = STUF  ((SELECT DISTINCT '], T1.[' + name,']=T2.['+name+'' FROM sys.columns
                 WHERE object_id = (
                                    SELECT top 1 object_id 
                                      FROM sys.objects
                                     WHERE name = ''+@TableNameTest+''
                                    )
                and name not in ('Action','Record_ID')
                FOR XML PATH('')
            ), 1, 2, ''
        ) + ']'


  Select @queryUpd ='Update T1
SET '+@colsUpd+'
FROM '+@TableName+' T1
INNER JOIN '+@TableNameTest+' T2
ON T1.Record_ID = T2.Record_Id
WHERE T2.[Action] = ''Modify'''
EXEC (@queryUpd)

Explicit Return Type of Lambda

You can explicitly specify the return type of a lambda by using -> Type after the arguments list:

[]() -> Type { }

However, if a lambda has one statement and that statement is a return statement (and it returns an expression), the compiler can deduce the return type from the type of that one returned expression. You have multiple statements in your lambda, so it doesn't deduce the type.

What is the difference between properties and attributes in HTML?

well these are specified by the w3c what is an attribute and what is a property http://www.w3.org/TR/SVGTiny12/attributeTable.html

but currently attr and prop are not so different and there are almost the same

but they prefer prop for some things

Summary of Preferred Usage

The .prop() method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the .attr() method.

well actually you dont have to change something if you use attr or prop or both, both work but i saw in my own application that prop worked where atrr didnt so i took in my 1.6 app prop =)

Java method: Finding object in array list given a known attribute value

Assuming that you've written an equals method for Dog correctly that compares based on the id of the Dog the easiest and simplest way to return an item in the list is as follows.

if (dogList.contains(dog)) {
   return dogList.get(dogList.indexOf(dog));
}

That's less performance intensive that other approaches here. You don't need a loop at all in this case. Hope this helps.

P.S You can use Apache Commons Lang to write a simple equals method for Dog as follows:

@Override
public boolean equals(Object obj) {     
   EqualsBuilder builder = new EqualsBuilder().append(this.getId(), obj.getId());               
   return builder.isEquals();
}

How to make RatingBar to show five stars

Additionally, if you set a layout_weight, this supersedes the numStars attribute.

urlencoded Forward slash is breaking URL

I solved this by using 2 custom functions like so:

function slash_replace($query){

    return str_replace('/','_', $query);
}

function slash_unreplace($query){

    return str_replace('_','/', $query);
}

So to encode I could call:

rawurlencode(slash_replace($param))

and to decode I could call

slash_unreplace(rawurldecode($param);

Cheers!

Why is Java Vector (and Stack) class considered obsolete or deprecated?

Vector synchronizes on each individual operation. That's almost never what you want to do.

Generally you want to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe (if you iterate over a Vector, for instance, you still need to take out a lock to avoid anyone else changing the collection at the same time, which would cause a ConcurrentModificationException in the iterating thread) but also slower (why take out a lock repeatedly when once will be enough)?

Of course, it also has the overhead of locking even when you don't need to.

Basically, it's a very flawed approach to synchronization in most situations. As Mr Brian Henk pointed out, you can decorate a collection using the calls such as Collections.synchronizedList - the fact that Vector combines both the "resized array" collection implementation with the "synchronize every operation" bit is another example of poor design; the decoration approach gives cleaner separation of concerns.

As for a Stack equivalent - I'd look at Deque/ArrayDeque to start with.

Read only file system on Android

I think the safest way is remounting the /system as read-write, using:

mount -o remount,rw /system

and when done, remount it as read-only:

mount -o remount,ro /system

whitespaces in the path of windows filepath

path = r"C:\Users\mememe\Google Drive\Programs\Python\file.csv"

Closing the path in r"string" also solved this problem very well.

typecast string to integer - Postgres

If the value contains non-numeric characters, you can convert the value to an integer as follows:

SELECT CASE WHEN <column>~E'^\\d+$' THEN CAST (<column> AS INTEGER) ELSE 0 END FROM table;

The CASE operator checks the < column>, if it matches the integer pattern, it converts the rate into an integer, otherwise it returns 0

How to get the primary IP address of the local machine on Linux and OS X?

I just utilize Network Interface Names, my custom command is

[[ $(ip addr | grep enp0s25) != '' ]] && ip addr show dev enp0s25 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p' || ip addr show dev eth0 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p' 

in my own notebook

[flying@lempstacker ~]$ cat /etc/redhat-release 
CentOS Linux release 7.2.1511 (Core) 
[flying@lempstacker ~]$ [[ $(ip addr | grep enp0s25) != '' ]] && ip addr show dev enp0s25 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p' || ip addr show dev eth0 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p'
192.168.2.221
[flying@lempstacker ~]$

but if the network interface owns at least one ip, then it will show all ip belong to it

for example

Ubuntu 16.10

root@yakkety:~# sed -r -n 's@"@@g;s@^VERSION=(.*)@\1@p' /etc/os-release
16.04.1 LTS (Xenial Xerus)
root@yakkety:~# [[ $(ip addr | grep enp0s25) != '' ]] && ip addr show dev enp0s25 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p' || ip addr show dev eth0 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p'
178.62.236.250
root@yakkety:~#

Debian Jessie

root@jessie:~# sed -r -n 's@"@@g;s@^PRETTY_NAME=(.*)@\1@p' /etc/os-release
Debian GNU/Linux 8 (jessie)
root@jessie:~# [[ $(ip addr | grep enp0s25) != '' ]] && ip addr show dev enp0s25 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p' || ip addr show dev eth0 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p'
192.81.222.54
root@jessie:~# 

CentOS 6.8

[root@centos68 ~]# cat /etc/redhat-release 
CentOS release 6.8 (Final)
[root@centos68 ~]# [[ $(ip addr | grep enp0s25) != '' ]] && ip addr show dev enp0s25 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p' || ip addr show dev eth0 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p'
162.243.17.224
10.13.0.5
[root@centos68 ~]# ip route get 1 | awk '{print $NF;exit}'
162.243.17.224
[root@centos68 ~]#

Fedora 24

[root@fedora24 ~]# cat /etc/redhat-release 
Fedora release 24 (Twenty Four)
[root@fedora24 ~]# [[ $(ip addr | grep enp0s25) != '' ]] && ip addr show dev enp0s25 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p' || ip addr show dev eth0 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p'
104.131.54.185
10.17.0.5
[root@fedora24 ~]# ip route get 1 | awk '{print $NF;exit}'
104.131.54.185
[root@fedora24 ~]#

It seems like that command ip route get 1 | awk '{print $NF;exit}' provided by link is more accurate, what's more, it more shorter.

np.mean() vs np.average() in Python NumPy?

np.average takes an optional weight parameter. If it is not supplied they are equivalent. Take a look at the source code: Mean, Average

np.mean:

try:
    mean = a.mean
except AttributeError:
    return _wrapit(a, 'mean', axis, dtype, out)
return mean(axis, dtype, out)

np.average:

...
if weights is None :
    avg = a.mean(axis)
    scl = avg.dtype.type(a.size/avg.size)
else:
    #code that does weighted mean here

if returned: #returned is another optional argument
    scl = np.multiply(avg, 0) + scl
    return avg, scl
else:
    return avg
...

Can't use Swift classes inside Objective-C

My issue was that the auto-generation of the -swift.h file was not able to understand a subclass of CustomDebugStringConvertible. I changed class to be a subclass of NSObject instead. After that, the -swift.h file now included the class properly.

Check if process returns 0 with batch file

How to write a compound statement with if?

You can write a compound statement in an if block using parenthesis. The first parenthesis must come on the line with the if and the second on a line by itself.

if %ERRORLEVEL% == 0 (
    echo ErrorLevel is zero
    echo A second statement
) else if %ERRORLEVEL% == 1 (
    echo ErrorLevel is one
    echo A second statement
) else (
   echo ErrorLevel is > 1
   echo A second statement
)

Javascript window.open pass values using POST

I used a variation of the above but instead of printing html I built a form and submitted it to the 3rd party url:

    var mapForm = document.createElement("form");
    mapForm.target = "Map";
    mapForm.method = "POST"; // or "post" if appropriate
    mapForm.action = "http://www.url.com/map.php";

    var mapInput = document.createElement("input");
    mapInput.type = "text";
    mapInput.name = "addrs";
    mapInput.value = data;
    mapForm.appendChild(mapInput);

    document.body.appendChild(mapForm);

    map = window.open("", "Map", "status=0,title=0,height=600,width=800,scrollbars=1");

if (map) {
    mapForm.submit();
} else {
    alert('You must allow popups for this map to work.');
}

How do I pipe or redirect the output of curl -v?

I found the same thing: curl by itself would print to STDOUT, but could not be piped into another program.

At first, I thought I had solved it by using xargs to echo the output first:

curl -s ... <url> | xargs -0 echo | ...

But then, as pointed out in the comments, it also works without the xargs part, so -s (silent mode) is the key to preventing extraneous progress output to STDOUT:

curl -s ... <url> | perl  -ne 'print $1 if /<sometag>([^<]+)/'

The above example grabs the simple <sometag> content (containing no embedded tags) from the XML output of the curl statement.

Trim last 3 characters of a line WITHOUT using sed, or perl, etc

You can use awk just to print the first 'field' if there won't be any spaces (or if there will be, change the separator'.

I put the fields you had above into a file and did this

awk '{ print $1 }' < test.txt 
1234567890
1234567891

I don't know if that's any better.

Java Singleton and Synchronization

Enum singleton

The simplest way to implement a Singleton that is thread-safe is using an Enum

public enum SingletonEnum {
  INSTANCE;
  public void doSomething(){
    System.out.println("This is a singleton");
  }
}

This code works since the introduction of Enum in Java 1.5

Double checked locking

If you want to code a “classic” singleton that works in a multithreaded environment (starting from Java 1.5) you should use this one.

public class Singleton {

  private static volatile Singleton instance = null;

  private Singleton() {
  }

  public static Singleton getInstance() {
    if (instance == null) {
      synchronized (Singleton.class){
        if (instance == null) {
          instance = new Singleton();
        }
      }
    }
    return instance ;
  }
}

This is not thread-safe before 1.5 because the implementation of the volatile keyword was different.

Early loading Singleton (works even before Java 1.5)

This implementation instantiates the singleton when the class is loaded and provides thread safety.

public class Singleton {

  private static final Singleton instance = new Singleton();

  private Singleton() {
  }

  public static Singleton getInstance() {
    return instance;
  }

  public void doSomething(){
    System.out.println("This is a singleton");
  }

}

How to get the timezone offset in GMT(Like GMT+7:00) from android device?

This is how Google recommends getting TimezoneOffset.

Calendar calendar = Calendar.getInstance(Locale.getDefault());
int offset = -(calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET)) / (60 * 1000)

https://developer.android.com/reference/java/util/Date#getTimezoneOffset()

How to programmatically set drawableLeft on Android button?

Simply you can try this also

txtVw.setCompoundDrawablesWithIntrinsicBounds(R.drawable.smiley, 0, 0, 0);

TypeError: 'list' object cannot be interpreted as an integer

range is expecting an integer argument, from which it will build a range of integers:

>>> range(10)
range(0, 10)
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

Moreover, giving it a list will raise a TypeError because range will not know how to handle it:

>>> range([1, 2, 3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'list' object cannot be interpreted as an integer
>>>

If you want to access the items in myList, loop over the list directly:

for i in myList:
    ...

Demo:

>>> myList = [1, 2, 3]
>>> for i in myList:
...     print(i)
...
1
2
3
>>>

Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

You always can do a session flush. Flush will synchronize the state of all your objects in session (please, someone correct me if i'm wrong), and maybe it would solve your problem in some cases.

Implementing your own equals and hashcode may help you too.

C# int to byte[]

byte[] Take_Byte_Arr_From_Int(Int64 Source_Num)
{
   Int64 Int64_Num = Source_Num;
   byte Byte_Num;
   byte[] Byte_Arr = new byte[8];
   for (int i = 0; i < 8; i++)
   {
      if (Source_Num > 255)
      {
         Int64_Num = Source_Num / 256;
         Byte_Num = (byte)(Source_Num - Int64_Num * 256);
      }
      else
      {
         Byte_Num = (byte)Int64_Num;
         Int64_Num = 0;
      }
      Byte_Arr[i] = Byte_Num;
      Source_Num = Int64_Num;
   }
   return (Byte_Arr);
}

How to find path of active app.config file?

Strictly speaking, there is no single configuration file. Excluding ASP.NET1 there can be three configuration files using the inbuilt (System.Configuration) support. In addition to the machine config: app.exe.config, user roaming, and user local.

To get the "global" configuration (exe.config):

ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
                    .FilePath

Use different ConfigurationUserLevel values for per-use roaming and non-roaming configuration files.


1 Which has a completely different model where the content of a child folders (IIS-virtual or file system) web.config can (depending on the setting) add to or override the parent's web.config.

How do I install soap extension?

find this line in php.ini :

;extension=soap

then remove the semicolon ; and restart Apache server

How Do I Take a Screen Shot of a UIView?

I have created usable extension for UIView to take screenshot in Swift:

extension UIView{

var screenshot: UIImage{

    UIGraphicsBeginImageContext(self.bounds.size);
    let context = UIGraphicsGetCurrentContext();
    self.layer.renderInContext(context)
    let screenShot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return screenShot
}
}

To use it just type:

let screenshot = view.screenshot

Is it necessary to assign a string to a variable before comparing it to another?

if ([statusString isEqualToString:@"Wrong"]) {
    // do something
}

How can I detect browser type using jQuery?

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    alert('sdfsd');_x000D_
    checkOperatingSystem();_x000D_
   });_x000D_
   function checkOperatingSystem(){_x000D_
       var  userAgent = navigator.userAgent || navigator.vendor || window.opera;_x000D_
_x000D_
       _x000D_
       if (/android/i.test(userAgent)) {_x000D_
           alert('android');_x000D_
       }_x000D_
_x000D_
       _x000D_
       if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {_x000D_
           alert('ios');_x000D_
       }_x000D_
_x000D_
      _x000D_
       if (navigator.appVersion.indexOf("Win")!=-1)_x000D_
       {_x000D_
           _x000D_
       }_x000D_
_x000D_
      _x000D_
       if (navigator.appVersion.indexOf("Mac")!=-1)_x000D_
       {_x000D_
           _x000D_
       }  _x000D_
   }
_x000D_
_x000D_
_x000D_

How to implement class constants?

You can mark properties with readonly modifier in your declaration:

export class MyClass {
  public static readonly MY_PUBLIC_CONSTANT = 10;
  private static readonly myPrivateConstant = 5;
}

@see TypeScript Deep Dive book - Readonly

Can we update primary key values of a table?

Short answer: yes you can. Of course you'll have to make sure that the new value doesn't match any existing value and other constraints are satisfied (duh).

What exactly are you trying to do?

How to convert an object to JSON correctly in Angular 2 with TypeScript

In your product.service.ts you are using stringify method in a wrong way..

Just use

JSON.stringify(product) 

instead of

JSON.stringify({product})

i have checked your problem and after this it's working absolutely fine.

How can I get a side-by-side diff when I do "git diff"?

There are a lot of good answers on this thread. My solution for this issue was to write a script.

Name this 'git-scriptname' (and make it executable and put it in your PATH, like any script), and you can invoke it like a normal git command by running

$ git scriptname

The actual functionality is just the last line. Here's the source:

#!/usr/bin/env zsh
#
#   Show a side-by-side diff of a particular file how it currently exists between:
#       * the file system
#       * in HEAD (latest committed changes)

function usage() {
    cat <<-HERE
    USAGE

    $(basename $1) <file>

    Show a side-by-side diff of a particular file between the current versions:

        * on the file system (latest edited changes)
        * in HEAD (latest committed changes)

HERE
}

if [[ $# = 0 ]]; then
    usage $0
    exit
fi

file=$1
diff -y =(git show HEAD:$file) $file | pygmentize -g | less -R

How do I create a Linked List Data Structure in Java?

The obvious solution to developers familiar to Java is to use the LinkedList class already provided in java.util. Say, however, you wanted to make your own implementation for some reason. Here is a quick example of a linked list that inserts a new link at the beginning of the list, deletes from the beginning of the list and loops through the list to print the links contained in it. Enhancements to this implementation include making it a double-linked list, adding methods to insert and delete from the middle or end, and by adding get and sort methods as well.

Note: In the example, the Link object doesn't actually contain another Link object - nextLink is actually only a reference to another link.

class Link {
    public int data1;
    public double data2;
    public Link nextLink;

    //Link constructor
    public Link(int d1, double d2) {
        data1 = d1;
        data2 = d2;
    }

    //Print Link data
    public void printLink() {
        System.out.print("{" + data1 + ", " + data2 + "} ");
    }
}

class LinkList {
    private Link first;

    //LinkList constructor
    public LinkList() {
        first = null;
    }

    //Returns true if list is empty
    public boolean isEmpty() {
        return first == null;
    }

    //Inserts a new Link at the first of the list
    public void insert(int d1, double d2) {
        Link link = new Link(d1, d2);
        link.nextLink = first;
        first = link;
    }

    //Deletes the link at the first of the list
    public Link delete() {
        Link temp = first;
        if(first == null){
         return null;
         //throw new NoSuchElementException(); // this is the better way. 
        }
        first = first.nextLink;
        return temp;
    }

    //Prints list data
    public void printList() {
        Link currentLink = first;
        System.out.print("List: ");
        while(currentLink != null) {
            currentLink.printLink();
            currentLink = currentLink.nextLink;
        }
        System.out.println("");
    }
}  

class LinkListTest {
    public static void main(String[] args) {
        LinkList list = new LinkList();

        list.insert(1, 1.01);
        list.insert(2, 2.02);
        list.insert(3, 3.03);
        list.insert(4, 4.04);
        list.insert(5, 5.05);

        list.printList();

        while(!list.isEmpty()) {
            Link deletedLink = list.delete();
            System.out.print("deleted: ");
            deletedLink.printLink();
            System.out.println("");
        }
        list.printList();
    }
}

Python: maximum recursion depth exceeded while calling a Python object

Python don't have a great support for recursion because of it's lack of TRE (Tail Recursion Elimination).

This means that each call to your recursive function will create a function call stack and because there is a limit of stack depth (by default is 1000) that you can check out by sys.getrecursionlimit (of course you can change it using sys.setrecursionlimit but it's not recommended) your program will end up by crashing when it hits this limit.

As other answer has already give you a much nicer way for how to solve this in your case (which is to replace recursion by simple loop) there is another solution if you still want to use recursion which is to use one of the many recipes of implementing TRE in python like this one.

N.B: My answer is meant to give you more insight on why you get the error, and I'm not advising you to use the TRE as i already explained because in your case a loop will be much better and easy to read.

Error handling in getJSON calls

Here's my addition.

From http://www.learnjavascript.co.uk/jq/reference/ajax/getjson.html and the official source

"The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead."

I did that and here is Luciano's updated code snippet:

$.getJSON("example.json", function() {
  alert("success");
})
.done(function() { alert('getJSON request succeeded!'); })
.fail(function() { alert('getJSON request failed! '); })
.always(function() { alert('getJSON request ended!'); });

And with error description plus showing all json data as a string:

$.getJSON("example.json", function(data) {
  alert(JSON.stringify(data));
})
.done(function() { alert('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { alert('getJSON request failed! ' + textStatus); })
.always(function() { alert('getJSON request ended!'); });

If you don't like alerts, substitute them with console.log

$.getJSON("example.json", function(data) {
  console.log(JSON.stringify(data));
})
.done(function() { console.log('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { console.log('getJSON request failed! ' + textStatus); })
.always(function() { console.log('getJSON request ended!'); });

How can I use Google's Roboto font on a website?

For Website you can use 'Roboto' font as below:

If you have created separate css file then put below line at the top of css file as:

@import url('https://fonts.googleapis.com/css?family=Roboto:300,300i,400,400i,500,500i,700,700i,900,900i');

Or if you don't want to create separate file then add above line in between <style>...</style>:

<style>
  @import url('https://fonts.googleapis.com/css? 
  family=Roboto:300,300i,400,400i,500,500i,700,700i,900,900i');
</style>

then:

html, body {
    font-family: 'Roboto', sans-serif;
}

Is there a way to use two CSS3 box shadows on one element?

You can comma-separate shadows:

box-shadow: inset 0 2px 0px #dcffa6, 0 2px 5px #000;

Get the element with the highest occurrence in an array

There are a lot of answers already but just want to share with you what I came up with :) Can't say this solution counts on any edge case but anyway )

const getMostFrequentElement = ( arr ) => {
  const counterSymbolKey = 'counter'
  const mostFrequentSymbolKey = 'mostFrequentKey'

  const result = arr.reduce( ( acc, cur ) => {
    acc[ cur ] = acc[ cur ] ? acc[ cur ] + 1 : 1

    if ( acc[ cur ] > acc[ Symbol.for( counterSymbolKey ) ] ) {
      acc[ Symbol.for( mostFrequentSymbolKey ) ] = cur
      acc[ Symbol.for( counterSymbolKey ) ] = acc[ cur ]
    }

    return acc
  }, {
    [ Symbol.for( mostFrequentSymbolKey ) ]: null,
    [ Symbol.for( counterSymbolKey ) ]: 0
  } )

  return result[ Symbol.for( mostFrequentSymbolKey ) ]
}

Hope it will be helpful for someone )

How to write subquery inside the OUTER JOIN Statement

You need the "correlation id" (the "AS SS" thingy) on the sub-select to reference the fields in the "ON" condition. The id's assigned inside the sub select are not usable in the join.

SELECT
       cs.CUSID
       ,dp.DEPID
FROM
    CUSTMR cs
        LEFT OUTER JOIN (
            SELECT
                    DEPID
                    ,DEPNAME
                FROM
                    DEPRMNT 
                WHERE
                    dp.DEPADDRESS = 'TOKYO'
        ) ss
            ON (
                ss.DEPID = cs.CUSID
                AND ss.DEPNAME = cs.CUSTNAME
            )
WHERE
    cs.CUSID != '' 

How do I create a unique constraint that also allows nulls?

Maybe consider an "INSTEAD OF" trigger and do the check yourself? With a non-clustered (non-unique) index on the column to enable the lookup.

How to add an Access-Control-Allow-Origin header

According to the official docs, browsers do not like it when you use the

Access-Control-Allow-Origin: "*"

header if you're also using the

Access-Control-Allow-Credentials: "true"

header. Instead, they want you to allow their origin specifically. If you still want to allow all origins, you can do some simple Apache magic to get it to work (make sure you have mod_headers enabled):

Header set Access-Control-Allow-Origin "%{HTTP_ORIGIN}e" env=HTTP_ORIGIN

Browsers are required to send the Origin header on all cross-domain requests. The docs specifically state that you need to echo this header back in the Access-Control-Allow-Origin header if you are accepting/planning on accepting the request. That's what this Header directive is doing.

load Js file in HTML

I had the same problem, and found the answer. If you use node.js with express, you need to give it its own function in order for the js file to be reached. For example:

const script = path.join(__dirname, 'script.js');
const server = express().get('/', (req, res) => res.sendFile(script))

Can you write nested functions in JavaScript?

Not only can you return a function which you have passed into another function as a variable, you can also use it for calculation inside but defining it outside. See this example:

    function calculate(a,b,fn) {
      var c = a * 3 + b + fn(a,b);
      return  c;
    }

    function sum(a,b) {
      return a+b;
    }

    function product(a,b) {
      return a*b;
    }

    document.write(calculate (10,20,sum)); //80
    document.write(calculate (10,20,product)); //250

Setting the character encoding in form submit for Internet Explorer

Just got the same problem and I have a relatively simple solution that does not require any change in the page character encoding(wich is a pain in the ass).

For example, your site is in utf-8 and you want to post a form to a site in iso-8859-1. Just change the action of the post to a page on your site that will convert the posted values from utf-8 to iso-8859-1.

this could be done easily in php with something like this:

<?php
$params = array();
foreach($_POST as $key=>$value) {
    $params[] = $key."=".rawurlencode(utf8_decode($value));
}
$params = implode("&",$params);

//then you redirect to the final page in iso-8859-1
?>

Add new column with foreign key constraint in one command

Try this:

ALTER TABLE product
ADD FOREIGN KEY (product_ID) REFERENCES product(product_ID);

How to navigate to to different directories in the terminal (mac)?

To check that the file you're trying to open actually exists, you can change directories in terminal using cd. To change to ~/Desktop/sass/css: cd ~/Desktop/sass/css. To see what files are in the directory: ls.

If you want information about either of those commands, use the man page: man cd or man ls, for example.

Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.

On Mac OS X, you can also use open to open a finder window: open . will open the current directory in finder. (open ~/Desktop/sass/css will open the ~/Desktop/sass/css).

'invalid value encountered in double_scalars' warning, possibly numpy

It looks like a floating-point calculation error. Check the numpy.seterr function to get more information about where it happens.

How do I create a new user in a SQL Azure database?

Edit - Contained User (v12 and later)

As of Sql Azure 12, databases will be created as Contained Databases which will allow users to be created directly in your database, without the need for a server login via master.

CREATE USER [MyUser] WITH PASSWORD = 'Secret';
ALTER ROLE [db_datareader] ADD MEMBER [MyUser];

Note when connecting to the database when using a contained user that you must always specify the database in the connection string.

Connecting via a contained User

Traditional Server Login - Database User (Pre v 12)

Just to add to @Igorek's answer, you can do the following in Sql Server Management Studio:

Create the new Login on the server
In master (via the Available databases drop down in SSMS - this is because USE master doesn't work in Azure):

enter image description here

create the login:

CREATE LOGIN username WITH password='password';

Create the new User in the database
Switch to the actual database (again via the available databases drop down, or a new connection)

CREATE USER username FROM LOGIN username;

(I've assumed that you want the user and logins to tie up as username, but change if this isn't the case.)

Now add the user to the relevant security roles

EXEC sp_addrolemember N'db_owner', N'username'
GO

(Obviously an app user should have less privileges than dbo.)

Git's famous "ERROR: Permission to .git denied to user"

I recently ran into this issue for on old repo on my machine that had been pushed up using https. steps 5 and 6 solved my issue by re-setting the remote url for my repo from using the https url to the ssh url

checking the remote is using the https url

> git remote -v
origin  https://github.com/ExampleUser/ExampleRepo.git (fetch)
origin  https://github.com/ExampleUser/ExampleRepo.git (push)

then re-setting the origin to use the ssh url

> git remote set-url origin [email protected]:ExampleUser/ExampleRepo.git

verifying new remote

> git remote -v
origin  [email protected]:ExampleUser/ExampleRepo.git (fetch)
origin  [email protected]:ExampleUser/ExampleRepo.git (push)

could now successfully git push -u origin

i'm still not sure what setting i would have changed that might have caused the push to fail when the remote is https but this was the solution to my issue

Saving Excel workbook to constant path with filename from two fields

Ok, at that time got it done with the help of a friend and the code looks like this.

Sub Saving()

Dim part1 As String

Dim part2 As String


part1 = Range("C5").Value

part2 = Range("C8").Value


ActiveWorkbook.SaveAs Filename:= _

"C:\-docs\cmat\Desktop\pieteikumi\" & part1 & " " & part2 & ".xlsm", FileFormat:= _
xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False

End Sub

How do I edit this part (FileFormat:= _ xlOpenXMLWorkbookMacroEnabled) for it to save as Excel 97-2013 Workbook, have tried several variations with no success. Thankyou

Seems, that I found the solution, but my idea is flawed. By doing this FileFormat:= _ xlOpenXMLWorkbook, it drops out a popup saying, the you cannot save this workbook as a file without Macro enabled. So, is this impossible?

Disable same origin policy in Chrome

If you are using Google Chrome on Linux, following command works.

google-chrome  --disable-web-security

Default SecurityProtocol in .NET 4.5

The BEST solution to this problem appears to be to upgrade to at least .NET 4.6 or later, which will automatically choose strong protocols as well as strong ciphers.

If you can't upgrade to .NET 4.6, the advice of setting

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

And using the registry settings:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft.NETFramework\v4.0.30319 – SchUseStrongCrypto = DWORD of 1 HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft.NETFramework\v4.0.30319 – SchUseStrongCrypto = DWORD of 1

Results in using something other than TLS 1.0 and a strong cipher.

In my testing, only the setting in the Wow6432Node made any difference, even though my test application was built for Any CPU.

Select current date by default in ASP.Net Calendar control

If you are already doing databinding:

<asp:Calendar ID="Calendar1" runat="server"  SelectedDate="<%# DateTime.Today %>" />

Will do it. This does require that somewhere you are doing a Page.DataBind() call (or a databind call on a parent control). If you are not doing that and you absolutely do not want any codebehind on the page, then you'll have to create a usercontrol that contains a calendar control and sets its selecteddate.

How can I search for a multiline pattern in a file?

Why don't you go for awk:

awk '/Start pattern/,/End pattern/' filename

Pure Javascript listen to input value change

Default usage

el.addEventListener('input', function () {
    fn();
});

But, if you want to fire event when you change inputs value manualy via JS you should use custom event(any name, like 'myEvent' \ 'ev' etc.) IF you need to listen forms 'change' or 'input' event and you change inputs value via JS - you can name your custom event 'change' \ 'input' and it will work too.

var event = new Event('input');
el.addEventListener('input', function () { 
  fn();
});
form.addEventListener('input', function () { 
  anotherFn();
});


el.value = 'something';
el.dispatchEvent(input);

https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

Why doesn't importing java.util.* include Arrays and Lists?

Take a look at this forum http://htmlcoderhelper.com/why-is-using-a-wild-card-with-a-java-import-statement-bad/. Theres a discussion on how using wildcards can lead to conflicts if you add new classes to the packages and if there are two classes with the same name in different packages where only one of them will be imported.

Update


It gives that warning because your the line should actually be

List<Integer> i = new ArrayList<Integer>(Arrays.asList(0,1,2,3,4,5,6,7,8,9,10));
List<Integer> j = new ArrayList<Integer>();

You need to specify the type for array list or the compiler will give that warning because it cannot identify that you are using the list in a type safe way.

How to know when a web page was last updated?

01. Open the page for which you want to get the information.

02. Clear the address bar [where you type the address of the sites]:

and type or copy/paste from below:

javascript:alert(document.lastModified)

03. Press Enter or Go button.

Error ITMS-90717: "Invalid App Store Icon"

Alternative:(Using Sierra or High Sierra and Ionic)

  1. Copy and Paste the App Store icon to the desktop.
  2. Open the image. Click File Menu->Duplicate.
  3. Save it by unticking the Alpha channel.
  4. Replace the current App Store icon with this one.
  5. Validate and upload.

How to get the error message from the error code returned by GetLastError()?

Updated (11/2017) to take into consideration some comments.

Easy example:

wchar_t buf[256];
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
               NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 
               buf, (sizeof(buf) / sizeof(wchar_t)), NULL);

select count(*) from table of mysql in php

You need to alias the aggregate using the as keyword in order to call it from mysql_fetch_assoc

$result=mysql_query("SELECT count(*) as total from Students");
$data=mysql_fetch_assoc($result);
echo $data['total'];

importing external ".txt" file in python

Import gives you access to other modules in your program. You can't decide to import a text file. If you want to read from a file that's in the same directory, you can look at this. Here's another StackOverflow post about it.

iOS - Calling App Delegate method from ViewController

You can add #define uAppDelegate (AppDelegate *)[[UIApplication sharedApplication] delegate] in your project's Prefix.pch file and then call any method of your AppDelegate in any UIViewController with the below code.

[uAppDelegate showLoginView];

How to export a mysql database using Command Prompt?

mysqldump -h [host] -p -u [user] [database name] > filename.sql

Example in localhost

mysqldump -h localhost -p -u root cookbook > cookbook.sql

maven compilation failure

Inside in yours classses on which is complain maven is some dependecy which belongs to some jar's try right these jars re-build with maven command, i use this command mvn clean install -DskipTests=true should be work in this case when some symbols from classes is missing

Get user's non-truncated Active Directory groups from command line

A little stale post, but I figured what the heck. Does "whoami" meet your needs?

I just found out about it today (from the same Google search that brought me here, in fact). Windows has had a whoami tool since XP (part of an add on toolkit) and has been built-in since Vista.

whoami /groups

Lists all the AD groups for the currently logged-on user. I believe it does require you to be logged on AS that user, though, so this won't help if your use case requires the ability to run the command to look at another user.

Group names only:

whoami /groups /fo list |findstr /c:"Group Name:"

Parser Error when deploy ASP.NET application

I had the same issue. Ran 5 or 6 hours of researches. A simple solution seems to be working. I just had to convert my folder to application from iis. It worked fine. (this was a scenario where I had done a migration from server 2003 to server 2008 R2)

(1) Open IIS and select the website and the appropriate folder that needs to be converted. Right-click and select Convert to Application.

enter image description here

Programmatically select a row in JTable

You can do it calling setRowSelectionInterval :

table.setRowSelectionInterval(0, 0);

to select the first row.

Render Partial View Using jQuery in ASP.NET MVC

You'll need to create an Action on your Controller that returns the rendered result of the "UserDetails" partial view or control. Then just use an Http Get or Post from jQuery to call the Action to get the rendered html to be displayed.

how to increase sqlplus column output length?

This worked like a charm for me with a CLOB column:

set long 20000000
set linesize 32767
column YOUR_COLUMN_NAME format a32767
select YOUR_COLUMN_NAME from YOUR_TABLE;

How to align an image dead center with bootstrap

Twitter bootstrap has a class that centers: .pagination-centered

It worked for me to do:

<div class="row-fluid">
   <div class="span12 pagination-centered"><img src="header.png" alt="header" /></div>
</div>

The css for the class is:

.pagination-centered {
  text-align: center;
}

How to change the default docker registry from docker.io to my private registry?

I tried to add the following options in the /etc/docker/daemon.json. (I used CentOS7)

"add-registry": ["192.168.100.100:5001"],
"block-registry": ["docker.io"],

after that, restarted docker daemon. And it's working without docker.io. I hope this someone will be helpful.

Angular routerLink does not navigate to the corresponding component

Try changing the links as below:

  <ul class="nav navbar-nav item">
    <li>
        <a [routerLink]="['/home']" routerLinkActive="active">Home</a>
    </li>
    <li>
        <a [routerLink]="['/about']" routerLinkActive="active">About this</a>
    </li>
  </ul>

Also, add the following in the header of index.html:

<base href="/">

Change a Git remote HEAD to point to something besides master

For gitolite people, gitolite supports a command called -- wait for it -- symbolic-ref. It allows you to run that command remotely if you have W (write) permission to the repo.

Twitter Bootstrap scrollable table rows and fixed header

Interesting question, I tried doing this by just doing a fixed position row, but this way seems to be a much better one. Source at bottom.

css

thead { display:block; background: green; margin:0px; cell-spacing:0px; left:0px; }
tbody { display:block; overflow:auto; height:100px; }
th { height:50px; width:80px; }
td { height:50px; width:80px; background:blue; margin:0px; cell-spacing:0px;}

html

<table>
    <thead>
        <tr><th>hey</th><th>ho</th></tr>
    </thead>
    <tbody>
        <tr><td>test</td><td>test</td></tr>
        <tr><td>test</td><td>test</td></tr>
        <tr><td>test</td><td>test</td></tr>
</tbody>

http://www.imaputz.com/cssStuff/bigFourVersion.html

Adding days to a date in Python

Here is another method to add days on date using dateutil's relativedelta.

from datetime import datetime
from dateutil.relativedelta import relativedelta

print 'Today: ',datetime.now().strftime('%d/%m/%Y %H:%M:%S') 
date_after_month = datetime.now()+ relativedelta(days=5)
print 'After 5 Days:', date_after_month.strftime('%d/%m/%Y %H:%M:%S')

Output:

Today: 25/06/2015 15:56:09

After 5 Days: 30/06/2015 15:56:09

Extract values in Pandas value_counts()

If anyone missed it out in the comments, try this:

dataframe[column].value_counts().to_frame()

How to save .xlsx data to file as a blob

Here's my implementation using the fetch api. The server endpoint sends a stream of bytes and the client receives a byte array and creates a blob out of it. A .xlsx file will then be generated.

return fetch(fullUrlEndpoint, options)
  .then((res) => {
    if (!res.ok) {
      const responseStatusText = res.statusText
      const errorMessage = `${responseStatusText}`
      throw new Error(errorMessage);
    }
    return res.arrayBuffer();
  })
    .then((ab) => {
      // BE endpoint sends a readable stream of bytes
      const byteArray = new Uint8Array(ab);
      const a = window.document.createElement('a');
      a.href = window.URL.createObjectURL(
        new Blob([byteArray], {
          type:
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        }),
      );
      a.download = `${fileName}.XLSX`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    })
    .catch(error => {
      throw new Error('Error occurred:' + error);
    });

sqlplus how to find details of the currently connected database session

select sys_context('USERENV','INSTANCE_NAME') from dual;

&

select instance_name from v$instance;

will give you the instance name. You can also use select * from global_name; to view the global name of the instance.

What is your most productive shortcut with Vim?

You are talking about text selecting and copying, I think that you should give a look to the Vim Visual Mode.

In the visual mode, you are able to select text using Vim commands, then you can do whatever you want with the selection.

Consider the following common scenarios:

You need to select to the next matching parenthesis.

You could do:

  • v% if the cursor is on the starting/ending parenthesis
  • vib if the cursor is inside the parenthesis block

You want to select text between quotes:

  • vi" for double quotes
  • vi' for single quotes

You want to select a curly brace block (very common on C-style languages):

  • viB
  • vi{

You want to select the entire file:

  • ggVG

Visual block selection is another really useful feature, it allows you to select a rectangular area of text, you just have to press Ctrl-V to start it, and then select the text block you want and perform any type of operation such as yank, delete, paste, edit, etc. It's great to edit column oriented text.

Duplicate Entire MySQL Database

To remote server

mysqldump mydbname | ssh host2 "mysql mydbcopy"

To local server

mysqldump mydbname | mysql mydbcopy

Odd behavior when Java converts int to byte?

In Java, an int is 32 bits. A byte is 8 bits .

Most primitive types in Java are signed, and byte, short, int, and long are encoded in two's complement. (The char type is unsigned, and the concept of a sign is not applicable to boolean.)

In this number scheme the most significant bit specifies the sign of the number. If more bits are needed, the most significant bit ("MSB") is simply copied to the new MSB.

So if you have byte 255: 11111111 and you want to represent it as an int (32 bits) you simply copy the 1 to the left 24 times.

Now, one way to read a negative two's complement number is to start with the least significant bit, move left until you find the first 1, then invert every bit afterwards. The resulting number is the positive version of that number

For example: 11111111 goes to 00000001 = -1. This is what Java will display as the value.

What you probably want to do is know the unsigned value of the byte.

You can accomplish this with a bitmask that deletes everything but the least significant 8 bits. (0xff)

So:

byte signedByte = -1;
int unsignedByte = signedByte & (0xff);

System.out.println("Signed: " + signedByte + " Unsigned: " + unsignedByte);

Would print out: "Signed: -1 Unsigned: 255"

What's actually happening here?

We are using bitwise AND to mask all of the extraneous sign bits (the 1's to the left of the least significant 8 bits.) When an int is converted into a byte, Java chops-off the left-most 24 bits

1111111111111111111111111010101
&
0000000000000000000000001111111
=
0000000000000000000000001010101

Since the 32nd bit is now the sign bit instead of the 8th bit (and we set the sign bit to 0 which is positive), the original 8 bits from the byte are read by Java as a positive value.

How can I close a dropdown on click outside?

This is the Angular Bootstrap DropDowns button sample with close outside of component.

without use bootstrap.js

// .html
<div class="mx-3 dropdown" [class.show]="isTestButton">
  <button class="btn dropdown-toggle"
          (click)="isTestButton = !isTestButton">
    <span>Month</span>
  </button>
  <div class="dropdown-menu" [class.show]="isTestButton">
    <button class="btn dropdown-item">Month</button>
    <button class="btn dropdown-item">Week</button>
  </div>
</div>

// .ts
import { Component, ElementRef, HostListener } from "@angular/core";

@Component({
  selector: "app-test",
  templateUrl: "./test.component.html",
  styleUrls: ["./test.component.scss"]
})
export class TestComponent {

  isTestButton = false;

  constructor(private eleRef: ElementRef) {
  }


  @HostListener("document:click", ["$event"])
  docEvent($e: MouseEvent) {
    if (!this.isTestButton) {
      return;
    }
    const paths: Array<HTMLElement> = $e["path"];
    if (!paths.some(p => p === this.eleRef.nativeElement)) {
      this.isTestButton = false;
    }
  }
}

Why do I get "a label can only be part of a statement and a declaration is not a statement" if I have a variable that is initialized after a label?

The language standard simply doesn't allow for it. Labels can only be followed by statements, and declarations do not count as statements in C. The easiest way to get around this is by inserting an empty statement after your label, which relieves you from keeping track of the scope the way you would need to inside a block.

#include <stdio.h>
int main () 
{
    printf("Hello ");
    goto Cleanup;
Cleanup: ; //This is an empty statement.
    char *str = "World\n";
    printf("%s\n", str);
}

JQuery - Storing ajax response into global variable

I know the thread is old but i thought someone else might find this useful. According to the jquey.com

var bodyContent = $.ajax({
  url: "script.php",
  global: false,
  type: "POST",
  data: "name=value",
  dataType: "html",
  async:false,
  success: function(msg){
     alert(msg);
  }
}).responseText;

would help to get the result to a string directly. Note the .responseText; part.

File path to resource in our war/WEB-INF folder?

I know this is late, but this is how I normally do it,

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();           
InputStream stream = classLoader.getResourceAsStream("../test/foo.txt");

What is the best Java email address validation method?

If you're looking to verify whether an email address is valid, then VRFY will get you some of the way. I've found it's useful for validating intranet addresses (that is, email addresses for internal sites). However it's less useful for internet mail servers (see the caveats at the top of this page)

Google Chrome redirecting localhost to https

I also have been struggling with this issue. Seems that HSTS is intended for only domain names. So if you are developing in local machine, it much easier to use IP address. So I switched from localhost to 127.0.0.1

Using both Python 2.x and Python 3.x in IPython Notebook

These instructions explain how to install a python2 and python3 kernel in separate virtual environments for non-anaconda users. If you are using anaconda, please find my other answer for a solution directly tailored to anaconda.

I assume that you already have jupyter notebook installed.


First make sure that you have a python2 and a python3 interpreter with pip available.

On ubuntu you would install these by:

sudo apt-get install python-dev python3-dev python-pip python3-pip

Next prepare and register the kernel environments

python -m pip install virtualenv --user

# configure python2 kernel
python -m virtualenv -p python2 ~/py2_kernel
source ~/py2_kernel/bin/activate
python -m pip install ipykernel
ipython kernel install --name py2 --user
deactivate

# configure python3 kernel
python -m virtualenv -p python3 ~/py3_kernel
source ~/py3_kernel/bin/activate
python -m pip install ipykernel
ipython kernel install --name py3 --user
deactivate

To make things easier, you may want to add shell aliases for the activation command to your shell config file. Depending on the system and shell you use, this can be e.g. ~/.bashrc, ~/.bash_profile or ~/.zshrc

alias kernel2='source ~/py2_kernel/bin/activate'
alias kernel3='source ~/py3_kernel/bin/activate'

After restarting your shell, you can now install new packages after activating the environment you want to use.

kernel2
python -m pip install <pkg-name>
deactivate

or

kernel3
python -m pip install <pkg-name>
deactivate

What's the actual use of 'fail' in JUnit test case?

This is how I use the Fail method.

There are three states that your test case can end up in

  1. Passed : The function under test executed successfully and returned data as expected
  2. Not Passed : The function under test executed successfully but the returned data was not as expected
  3. Failed : The function did not execute successfully and this was not

intended (Unlike negative test cases that expect a exception to occur).

If you are using eclipse there three states are indicated by a Green, Blue and red marker respectively.

I use the fail operation for the the third scenario.

e.g. : public Integer add(integer a, Integer b) { return new Integer(a.intValue() + b.intValue())}

  1. Passed Case : a = new Interger(1), b= new Integer(2) and the function returned 3
  2. Not Passed Case: a = new Interger(1), b= new Integer(2) and the function returned soem value other than 3
  3. Failed Case : a =null , b= null and the function throws a NullPointerException

CustomErrors mode="Off"

I also had this problem, but when using Apache and mod_mono. For anyone else in that situation, you need to restart Apache after changing web.config to force the new version to be read.

How to ignore PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException?

I got the same error while executing the below spring-boot + RestAssured simple test.

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static com.jayway.restassured.RestAssured.when;
import static org.apache.http.HttpStatus.SC_OK;

@RunWith(SpringJUnit4ClassRunner.class)
public class GeneratorTest {

@Test
public void generatorEndPoint() {
    when().get("https://bal-bla-bla-bla.com/generators")
            .then().statusCode(SC_OK);
    }
}

The simple fix in my case is to add 'useRelaxedHTTPSValidations()'

RestAssured.useRelaxedHTTPSValidation();

Then the test looks like

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static com.jayway.restassured.RestAssured.when;
import static org.apache.http.HttpStatus.SC_OK;

@RunWith(SpringJUnit4ClassRunner.class)
public class GeneratorTest {

@Before
public void setUp() {
   RestAssured.useRelaxedHTTPSValidation();
}


@Test
public void generatorEndPoint() {
    when().get("https://bal-bla-bla-bla.com/generators")
            .then().statusCode(SC_OK);
    }
}

How do I share a global variable between c files?

If you want to use global variable i of file1.c in file2.c, then below are the points to remember:

  1. main function shouldn't be there in file2.c
  2. now global variable i can be shared with file2.c by two ways:
    a) by declaring with extern keyword in file2.c i.e extern int i;
    b) by defining the variable i in a header file and including that header file in file2.c.

PDO with INSERT INTO through prepared statements

Please add try catch also in your code so that you can be sure that there in no exception.

try {
    $hostname = "servername";
    $dbname = "dbname";
    $username = "username";
    $pw = "password";
    $pdo = new PDO ("mssql:host=$hostname;dbname=$dbname","$username","$pw");
  } catch (PDOException $e) {
    echo "Failed to get DB handle: " . $e->getMessage() . "\n";
    exit;
  }

Setting background images in JFrame

You can use the Background Panel class. It does the custom painting as explained above but gives you options to display the image scaled, tiled or normal size. It also explains how you can use a JLabel with an image as the content pane for the frame.

Conditional statement in a one line lambda function in python?

Use the exp1 if cond else exp2 syntax.

rate = lambda T: 200*exp(-T) if T>200 else 400*exp(-T)

Note you don't use return in lambda expressions.

OPENSSL file_get_contents(): Failed to enable crypto

Ok I have found a solution. The problem is that the site uses SSLv3. And I know that there are some problems in the openssl module. Some time ago I had the same problem with the SSL versions.

<?php
function getSSLPage($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSLVERSION,3); 
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

var_dump(getSSLPage("https://eresearch.fidelity.com/eresearch/evaluate/analystsOpinionsReport.jhtml?symbols=api"));
?>

When you set the SSL Version with curl to v3 then it works.

Edit:

Another problem under Windows is that you don't have access to the certificates. So put the root certificates directly to curl.

http://curl.haxx.se/docs/caextract.html

here you can download the root certificates.

curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/certs/cacert.pem");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

Then you can use the CURLOPT_SSL_VERIFYPEER option with true otherwise you get an error.

jQuery: count number of rows in a table

I found this to work really well if you want to count rows without counting the th and any rows from tables inside of tables:

var rowCount = $("#tableData > tbody").children().length;

UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>

for me changing the Mysql character encoding the same as my code helped to sort out the solution. `photo=open('pic3.png',encoding=latin1), strong text enter image description here

Have nginx access_log and error_log log to STDOUT and STDERR of master process

If the question is docker related... the official nginx docker images do this by making softlinks towards stdout/stderr

RUN ln -sf /dev/stdout /var/log/nginx/access.log && ln -sf /dev/stderr /var/log/nginx/error.log

REF: https://microbadger.com/images/nginx

Missing Maven dependencies in Eclipse project

All above did not worked with me. For the fix was only to delete the repository folder under .m2 and then do a maven update from eclipse.

How to update single value inside specific array item in redux

You can use map. Here is an example implementation:

case 'SOME_ACTION':
   return { 
       ...state, 
       contents: state.contents.map(
           (content, i) => i === 1 ? {...content, text: action.payload}
                                   : content
       )
    }

What is the best way to remove the first element from an array?

You can't do it at all, let alone quickly. Arrays in Java are fixed size. Two things you could do are:

  1. Shift every element up one, then set the last element to null.
  2. Create a new array, then copy it.

You can use System.arraycopy for either of these. Both of these are O(n), since they copy all but 1 element.

If you will be removing the first element often, consider using LinkedList instead. You can use LinkedList.remove, which is from the Queue interface, for convenience. With LinkedList, removing the first element is O(1). In fact, removing any element is O(1) once you have a ListIterator to that position. However, accessing an arbitrary element by index is O(n).

How to test a variable is null in python

You can do this in a try and catch block:

try:
    if val is None:
        print("null")
except NameError:
    # throw an exception or do something else

SQL Server Insert Example

Here are 4 ways to insert data into a table.

  1. Simple insertion when the table column sequence is known.

    INSERT INTO Table1 VALUES (1,2,...)

  2. Simple insertion into specified columns of the table.

    INSERT INTO Table1(col2,col4) VALUES (1,2)

  3. Bulk insertion when...

    1. You wish to insert every column of Table2 into Table1
    2. You know the column sequence of Table2
    3. You are certain that the column sequence of Table2 won't change while this statement is being used (perhaps you the statement will only be used once).

    INSERT INTO Table1 {Column sequence} SELECT * FROM Table2

  4. Bulk insertion of selected data into specified columns of Table2.

.

INSERT INTO Table1 (Column1,Column2 ....)
    SELECT Column1,Column2...
       FROM Table2

Show row number in row header of a DataGridView

private void setRowNumber(DataGridView dgv)
{
    foreach (DataGridViewRow row in dgv.Rows)
    {
        row.HeaderCell.Value = (row.Index + 1).ToString();
    }
}

This worked for me.

How to check the installed version of React-Native

If you want to see which version of react-native, react or another one you are running, open your terminal or cmd and run the desired command

npm view react-native version
0.63.4
npm view react version
17.0.1
npm view react-scripts version
4.0.1
npm view react-dom version
17.0.1

see my terminal

When to create variables (memory management)

So notice variables are on the stack, the values they refer to are on the heap. So having variables is not too bad but yes they do create references to other entities. However in the simple case you describe it's not really any consequence. If it is never read again and within a contained scope, the compiler will probably strip it out before runtime. Even if it didn't the garbage collector will be able to safely remove it after the stack squashes. If you are running into issues where you have too many stack variables, it's usually because you have really deep stacks. The amount of stack space needed per thread is a better place to adjust than to make your code unreadable. The setting to null is also no longer needed

How can I check if the array of objects have duplicate property values?

Try an simple loop:

var repeat = [], tmp, i = 0;

while(i < values.length){
  repeat.indexOf(tmp = values[i++].name) > -1 ? values.pop(i--) : repeat.push(tmp)
}

Demo

How can you customize the numbers in an ordered list?

You can also specify your own numbers in the HTML - e.g. if the numbers are being provided by a database:

_x000D_
_x000D_
ol {_x000D_
  list-style: none;_x000D_
}_x000D_
_x000D_
ol>li:before {_x000D_
  content: attr(seq) ". ";_x000D_
}
_x000D_
<ol>_x000D_
  <li seq="1">Item one</li>_x000D_
  <li seq="20">Item twenty</li>_x000D_
  <li seq="300">Item three hundred</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

The seq attribute is made visible using a method similar to that given in other answers. But instead of using content: counter(foo), we use content: attr(seq).

Demo in CodePen with more styling

How to make a div 100% height of the browser window

You need to do two things, one is to set the height to 100% which you already did. Second is set the position to absolute. That should do the trick.

html,
body {
  height: 100%;
  min-height: 100%;
  position: absolute;
}

Source

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object

Pretty sure pk_OrderID is the PK of AC_Shipping_Addresses

And you are trying to insert a duplicate via the _Order.OrderNumber

Do a

select * from AC_Shipping_Addresses where pk_OrderID = 165863;

or select count(*) ....

Pretty sure you will get a row returned.

What it is telling you is you are already using pk_OrderID = 165863 and cannot have another row with that value.

if you want to not insert if there is a row

insert into table (pk, value) 
select 11 as pk, 'val' as value 
where not exists (select 1 from table where pk = 11) 

Calculate correlation with cor(), only for numerical columns

if you have a dataframe where some columns are numeric and some are other (character or factor) and you only want to do the correlations for the numeric columns, you could do the following:

set.seed(10)

x = as.data.frame(matrix(rnorm(100), ncol = 10))
x$L1 = letters[1:10]
x$L2 = letters[11:20]

cor(x)

Error in cor(x) : 'x' must be numeric

but

cor(x[sapply(x, is.numeric)])

             V1         V2          V3          V4          V5          V6          V7
V1   1.00000000  0.3025766 -0.22473884 -0.72468776  0.18890578  0.14466161  0.05325308
V2   0.30257657  1.0000000 -0.27871430 -0.29075170  0.16095258  0.10538468 -0.15008158
V3  -0.22473884 -0.2787143  1.00000000 -0.22644156  0.07276013 -0.35725182 -0.05859479
V4  -0.72468776 -0.2907517 -0.22644156  1.00000000 -0.19305921  0.16948333 -0.01025698
V5   0.18890578  0.1609526  0.07276013 -0.19305921  1.00000000  0.07339531 -0.31837954
V6   0.14466161  0.1053847 -0.35725182  0.16948333  0.07339531  1.00000000  0.02514081
V7   0.05325308 -0.1500816 -0.05859479 -0.01025698 -0.31837954  0.02514081  1.00000000
V8   0.44705527  0.1698571  0.39970105 -0.42461411  0.63951574  0.23065830 -0.28967977
V9   0.21006372 -0.4418132 -0.18623823 -0.25272860  0.15921890  0.36182579 -0.18437981
V10  0.02326108  0.4618036 -0.25205899 -0.05117037  0.02408278  0.47630138 -0.38592733
              V8           V9         V10
V1   0.447055266  0.210063724  0.02326108
V2   0.169857120 -0.441813231  0.46180357
V3   0.399701054 -0.186238233 -0.25205899
V4  -0.424614107 -0.252728595 -0.05117037
V5   0.639515737  0.159218895  0.02408278
V6   0.230658298  0.361825786  0.47630138
V7  -0.289679766 -0.184379813 -0.38592733
V8   1.000000000  0.001023392  0.11436143
V9   0.001023392  1.000000000  0.15301699
V10  0.114361431  0.153016985  1.00000000

"You have mail" message in terminal, os X

I was also having this issue of "You have mail" coming up every time I started Terminal.

What I discovered is this.

Something I'd installed (not entirely sure what, but possibly a script or something associated with an Alfred Workflow [at a guess]) made a change to the OS X system to start presenting Terminal bash notifications. Prior to that, it appears Wordpress had attempted to use the Local Mail system to send a message. The message bounced, due to it having an invalid Recipient address. The bounced message then ended up in the local system mail inbox. So Terminal (bash) was then notifying me that "You have mail".

You can access the mail by simply using the command

mail

This launches you into Mail, and it will right away show you a list of messages that are stored there. If you want to see the content of the first message, use

t

This will show you the content of the first message, in full. You'll need to scroll down through the message to view it all, by hitting the down-arrow key.

If you want to jump to the end of the message, use the

spacebar

If you want to abort viewing the message, use

q 

To view the next message in the queue use

n

... assuming there's more than one message.

NOTE: You need to use these commands at the mail ? command prompt. They won't work whilst you are in the process of viewing a message. Hitting n whilst viewing a message will just cause an error message related to regular expressions. So, if in the midst of viewing a message, hit q to quit from that, or hit spacebar to jump to the end of the message, and then at the ? prompt, hit n.

Viewing the content of the messages in this way may help you identify what attempted to send the message(s).

You can also view a specific message by just inputting its number at the ? prompt. 3, for instance, will show you the content of the third message (if there are that many in there).

DELETING MESSAGES

Use the d command (at the ? command prompt )

d [message number]

To delete each message when you are done looking at them. For example, d 2 will delete message number 2. Or you can delete a list of messages, such as d 1 2 5 7. Or you can delete a range of messages with (for example), d 3-10. You can find the message numbers in the list of messages mail shows you.

To delete all the messages, from the mail prompt (?) use the command d *.

As per a comment on this post, you will need to use q to quit mail, which also saves any changes.

If you'd like to see the mail all in one output, use this command at the bash prompt (i.e. not from within mail, but from your regular command prompt):

cat /var/mail/<username>

And, if you wish to delete the emails all in one hit, use this command

sudo rm /var/mail/<username>

In my particular case, there were a number of messages. It looks like the one was a returned message that bounced. It was sent by a local Wordpress installation. It was a notification for when user "Admin" (me) changed its password. Two additional messages where there. Both seemed to be to the same incident.

What I don't know, and can't answer for you either, is WHY I only recently started seeing this mail notification each time I open Terminal. The mails were generated a couple of months ago, and yet I only noticed this "you have mail" appearing in the last few weeks. I suspect it's the result of something a workflow I installed in Alfred, and that workflow using Terminal bash to provide notifications... or something along those lines.

Simply deleting the messages

If you have no interest in determining the source of the messages, and just wish to get rid of them, it may be easier to do so without using the mail command (which can be somewhat fiddly). As pointed out by a few other people, you can use this command instead:

sudo rm /var/mail/YOURUSERNAME

What's the Kotlin equivalent of Java's String[]?

you can use too:

val frases = arrayOf("texto01","texto02 ","anotherText","and ")

for example.

How to use @Nullable and @Nonnull annotations more effectively?

Other than your IDE giving you hints when you pass null to methods that expect the argument to not be null, there are further advantages:

This can help your code be more maintainable (since you do not need null checks) and less error-prone.

Large WCF web service request failing with (400) HTTP Bad Request

I found the answer to the Bad Request 400 problem.

It was the default server binding setting. You would need to add to server and client default setting.

binding name="" openTimeout="00:10:00" closeTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" maxReceivedMessageSize="2147483647" maxBufferPoolSize="2147483647" maxBufferSize="2147483647">

Hide Spinner in Input Number - Firefox 29

I mixed few answers from answers above and from How to remove the arrows from input[type="number"] in Opera in scss:

input[type=number] {
  &,
  &::-webkit-inner-spin-button,
  &::-webkit-outer-spin-button {
    -webkit-appearance: none;
    -moz-appearance: textfield;
    appearance: none;

    &:hover,
    &:focus {
      -moz-appearance: number-input;
    }
  }
}

Tested on chrome, firefox, safari