Programs & Examples On #Eigen

Eigen is a C++ template library for linear algebra: matrices, vectors, and related algorithms.

If strings starts with in PowerShell

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

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

NumPy ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

The error message explains it pretty well:

ValueError: The truth value of an array with more than one element is ambiguous. 
Use a.any() or a.all()

What should bool(np.array([False, False, True])) return? You can make several plausible arguments:

(1) True, because bool(np.array(x)) should return the same as bool(list(x)), and non-empty lists are truelike;

(2) True, because at least one element is True;

(3) False, because not all elements are True;

and that's not even considering the complexity of the N-d case.

So, since "the truth value of an array with more than one element is ambiguous", you should use .any() or .all(), for example:

>>> v = np.array([1,2,3]) == np.array([1,2,4])
>>> v
array([ True,  True, False], dtype=bool)
>>> v.any()
True
>>> v.all()
False

and you might want to consider np.allclose if you're comparing arrays of floats:

>>> np.allclose(np.array([1,2,3+1e-8]), np.array([1,2,3]))
True

g++ ld: symbol(s) not found for architecture x86_64

I had a similar warning/error/failure when I was simply trying to make an executable from two different object files (main.o and add.o). I was using the command:

gcc -o exec main.o add.o

But my program is a C++ program. Using the g++ compiler solved my issue:

g++ -o exec main.o add.o

I was always under the impression that gcc could figure these things out on its own. Apparently not. I hope this helps someone else searching for this error.

What does it mean to have an index to scalar variable error? python

exponent is a 1D array. This means that exponent[0] is a scalar, and exponent[0][i] is trying to access it as if it were an array.

Did you mean to say:

L = identity(len(l))
for i in xrange(len(l)):
    L[i][i] = exponent[i]

or even

L = diag(exponent)

?

MySQL Error: #1142 - SELECT command denied to user

This error happened on my server when I imported a view with an invalid definer.

Removing the faulty view fixed the error.

The error message didn't say anything about the view in question, but was "complaining" about one of the tables, that was used in the view.

What properties can I use with event.target?

//Do it like---
function dragStart(this_,event) {
    var row=$(this_).attr('whatever');
    event.dataTransfer.setData("Text", row);
}

Face recognition Library

You should look at http://libccv.org/

It's fairly new, but it provides a free open source high level API for face detection.

(...and, I dare say, is pretty damn amazing)

Edit: Worth noting also, that this is one of the few libs that does NOT depend on opencv, and just for kicks, here's a copy of the code for face detection off the documentation page, to give you an idea of whats involved:

#include <ccv.h>
int main(int argc, char** argv)
{
    ccv_dense_matrix_t* image = 0;
    ccv_read(argv[1], &image, CCV_IO_GRAY | CCV_IO_ANY_FILE);
    ccv_bbf_classifier_cascade_t* cascade = ccv_load_bbf_classifier_cascade(argv[2]);         ccv_bbf_params_t params = { .interval = 8, .min_neighbors = 2, .accurate = 1, .flags = 0, .size = ccv_size(24, 24) };
    ccv_array_t* faces = ccv_bbf_detect_objects(image, &cascade, 1, params);
    int i;
    for (i = 0; i < faces->rnum; i++)
    {
        ccv_comp_t* face = (ccv_comp_t*)ccv_array_get(faces, i);
        printf("%d %d %d %d\n", face->rect.x, face->rect.y, face->rect.width, face->rect.y);
    }
    ccv_array_free(faces);
    ccv_bbf_classifier_cascade_free(cascade);
    ccv_matrix_free(image);
    return 0;
} 

Alternative to iFrames with HTML5

No, there isn't an equivalent. The <iframe> element is still valid in HTML5. Depending on what exact interaction you need there might be different APIs. For example there's the postMessage method which allows you to achieve cross domain javascript interaction. But if you want to display cross domain HTML contents (styled with CSS and made interactive with javascript) iframe stays as a good way to do.

Uploading multiple files using formData()

This worked for me:

let formData = new FormData()
formData.append('files', file1)
formData.append('files', file2)

How abstraction and encapsulation differ?

Below is a semester long course distilled in a few paragraphs.

Object-Oriented Analysis and Design (OOAD) is actually based on not just two but four principles. They are:

  • Abstraction: means that you only incorporate those features of an entity which are required in your application. So, if every bank account has an opening date but your application doesn't need to know an account's opening date, then you simply don't add the OpeningDate field in your Object-Oriented Design (of the BankAccount class). Abstraction in OOAD has nothing to do with abstract classes in OOP.

    Per the principle of Abstraction, your entities are an abstraction of what they are in the real world. This way, you design an abstraction of Bank Account down to only that level of detail that is needed by your application.

  • Inheritance: is more of a coding-trick than an actual principle. It saves you from re-writing those functionalities that you have written somewhere else. However, the thinking is that there must be a relation between the new code you are writing and the old code you are wanting to re-use. Otherwise, nobody prevents you from writing an Animal class which is inheriting from BankAccount, even if it is totally non-sensical.

    Just like you may inherit your parents' wealth, you may inherit fields and methods from your parent class. So, taking everything that parent class has and then adding something more if need be, is inheritance. Don't go looking for inheritance in your Object Oriented Design. Inheritance will naturally present itself.

  • Polymorphism: is a consequence of inheritance. Inheriting a method from the parent is useful, but being able to modify a method if the situation demands, is polymorphism. You may implement a method in the subclass with exactly the same signature as in parent class so that when called, the method from child class is executed. This is the principle of Polymorphism.

  • Encapsulation: implies bundling the related functionality together and giving access to only the needful. Encapsulation is the basis of meaningful class designing in Object Oriented Design, by:

    • putting related data and methods together; and,
    • exposing only the pieces of data and methods relevant for functioning with external entities.

Another simplified answer is here.


People who argue that "Abstraction of OOAD results in the abstract keyword of OOP"... Well that is incorrect.

Example: When you design a University in an application using object oriented principles, you only design an "abstraction" of the university. Even though there is usually one cash dispensing ATM in almost every university, you may not incorporate that fact if it's not needed for your application. And now though you have designed only an abstraction of the university, you are not required to put abstract in your class declaration. Your abstract design of university will be a normal class in your application.

How can I set my Cygwin PATH to find javac?

To bring more prominence to the useful comment by @johanvdw:

If you want to ensure your your javac file path is always know when cygwin starts, you may edit your .bash_profile file. In this example you would add export PATH=$PATH:"/cygdrive/C/Program Files/Java/jdk1.6.0_23/bin/" somewhere in the file.

When Cygwin starts, it'll search directories in PATH and this one for executable files to run.

NSPhotoLibraryUsageDescription key must be present in Info.plist to use camera roll

Thanks @rmaddy, I added this just after other key-string pairs in Info.plist and fixed the problem:

<key>NSPhotoLibraryUsageDescription</key>
<string>Photo Library Access Warning</string>

Edit:

I also ended up having similar problems on different components of my app. Ended up adding all these keys so far (after updating to Xcode8/iOS10):

<key>NSPhotoLibraryUsageDescription</key>
<string>This app requires access to the photo library.</string>
<key>NSMicrophoneUsageDescription</key>
<string>This app does not require access to the microphone.</string>
<key>NSCameraUsageDescription</key>
<string>This app requires access to the camera.</string>

Checkout this developer.apple.com link for full list of property list key references.

Full List:

Apple Music:

<key>NSAppleMusicUsageDescription</key>
<string>My description about why I need this capability</string>

Bluetooth:

<key>NSBluetoothPeripheralUsageDescription</key>  
<string>My description about why I need this capability</string>

Calendar:

<key>NSCalendarsUsageDescription</key>
<string>My description about why I need this capability</string>

Camera:

<key>NSCameraUsageDescription</key>
<string>My description about why I need this capability</string>

Contacts:

<key>NSContactsUsageDescription</key>
<string>My description about why I need this capability</string>

FaceID:

<key>NSFaceIDUsageDescription</key>
<string>My description about why I need this capability</string>

Health Share:

<key>NSHealthShareUsageDescription</key>
<string>My description about why I need this capability</string>

Health Update:

<key>NSHealthUpdateUsageDescription</key>
<string>My description about why I need this capability</string>

Home Kit:

<key>NSHomeKitUsageDescription</key>
<string>My description about why I need this capability</string>

Location:

<key>NSLocationUsageDescription</key>
<string>My description about why I need this capability</string>

Location (Always):

<key>NSLocationAlwaysUsageDescription</key>
<string>My description about why I need this capability</string>

Location (When in use):

<key>NSLocationWhenInUseUsageDescription</key>
<string>My description about why I need this capability</string>

Microphone:

<key>NSMicrophoneUsageDescription</key>
<string>My description about why I need this capability</string>

Motion (Accelerometer):

<key>NSMotionUsageDescription</key>
<string>My description about why I need this capability</string>

NFC (Near-field communication):

<key>NFCReaderUsageDescription</key>
<string>My description about why I need this capability</string>

Photo Library:

<key>NSPhotoLibraryUsageDescription</key>
<string>My description about why I need this capability</string>

Photo Library (Write-only access):

<key>NSPhotoLibraryAddUsageDescription</key>
<string>My description about why I need this capability</string>

Reminders:

<key>NSRemindersUsageDescription</key>
<string>My description about why I need this capability</string>

Siri:

<key>NSSiriUsageDescription</key>
<string>My description about why I need this capability</string>

Speech Recognition:

<key>NSSpeechRecognitionUsageDescription</key>
<string>My description about why I need this capability</string>

Text in Border CSS HTML

Text in Border with transparent text background

_x000D_
_x000D_
.box{
    background-image: url("https://i.stack.imgur.com/N39wV.jpg");
    width: 350px;
    padding: 10px;
}

/*begin first box*/
.first{
    width: 300px;
    height: 100px;
    margin: 10px;
    border-width: 0 2px 0 2px;
    border-color: #333;
    border-style: solid;
    position: relative;
}

.first span {
    position: absolute;
    display: flex;
    right: 0;
    left: 0;
    align-items: center;
}
.first .foo{
    top: -8px;
}
.first .bar{
    bottom: -8.5px;
}
.first span:before{
    margin-right: 15px;
}
.first span:after {
    margin-left: 15px;
}
.first span:before , .first span:after {
    content: ' ';
    height: 2px;
    background: #333;
    display: block;
    width: 50%;
}


/*begin second box*/
.second{
    width: 300px;
    height: 100px;
    margin: 10px;
    border-width: 2px 0 2px 0;
    border-color: #333;
    border-style: solid;
    position: relative;
}

.second span {
    position: absolute;
    top: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
}
.second .foo{
    left: -15px;
}
.second .bar{
    right: -15.5px;
}
.second span:before{
    margin-bottom: 15px;
}
.second span:after {
    margin-top: 15px;
}
.second span:before , .second span:after {
    content: ' ';
    width: 2px;
    background: #333;
    display: block;
    height: 50%;
}
_x000D_
<div class="box">
    <div class="first">
        <span class="foo">FOO</span>
        <span class="bar">BAR</span>
    </div>

   <br>

    <div class="second">
        <span class="foo">FOO</span>
        <span class="bar">BAR</span>
    </div>
</div>
_x000D_
_x000D_
_x000D_

Date format in the json output using spring boot

If you have Jackson integeration with your application to serialize your bean to JSON format, then you can use Jackson anotation @JsonFormat to format your date to specified format.
In your case if you need your date into yyyy-MM-dd format you need to specify @JsonFormat above your field on which you want to apply this format.

For Example :

public class Subject {

     private String uid;
     private String number;
     private String initials;

     @JsonFormat(pattern="yyyy-MM-dd")
     private Date dateOfBirth;  

     //Other Code  

}  

From Docs :

annotation used for configuring details of how values of properties are to be serialized.

More Reference Doc

Hope this helps.

Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)

Add the following to the top of your file # coding=utf-8

If you go to the link in the error you can seen the reason why:

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=

Inline list initialization in VB.NET

Use this syntax for VB.NET 2005/2008 compatibility:

Dim theVar As New List(Of String)(New String() {"one", "two", "three"})

Although the VB.NET 2010 syntax is prettier.

if condition in sql server update query

Something like this should work:

UPDATE
    table_Name
SET 
  column_A = CASE WHEN @flag = '1' THEN column_A + @new_value ELSE column_A END,
  column_B = CASE WHEN @flag = '0' THEN column_B + @new_value ELSE column_B END
WHERE
    ID = @ID

Sass and combined child selector

Without the combined child selector you would probably do something similar to this:

foo {
  bar {
    baz {
      color: red;
    }
  }
}

If you want to reproduce the same syntax with >, you could to this:

foo {
  > bar {
    > baz {
      color: red;
    }
  }
}

This compiles to this:

foo > bar > baz {
  color: red;
}

Or in sass:

foo
  > bar
    > baz
      color: red

Getting JSONObject from JSONArray

Here is your json:

{
    "syncresponse": {
       "synckey": "2011-09-30 14:52:00",
        "createdtrs": [

        ],
        "modtrs": [

        ],
        "deletedtrs": [
          {
           "companyid": "UTB17",
           "username": "DA",
           "date": "2011-09-26",
           "reportid": "31341"
      }
       ]
   }
}

and it's parsing:

JSONObject object = new JSONObject(result);
String syncresponse = object.getString("syncresponse");
JSONObject object2 = new JSONObject(syncresponse);
String synckey = object2.getString("synckey");
JSONArray jArray1 = object2.getJSONArray("createdtrs");
JSONArray jArray2 = object2.getJSONArray("modtrs");
JSONArray jArray3 = object2.getJSONArray("deletedtrs");
for(int i = 0; i < jArray3 .length(); i++)
{
   JSONObject object3 = jArray3.getJSONObject(i);
   String comp_id = object3.getString("companyid");
   String username = object3.getString("username");
   String date = object3.getString("date");
   String report_id = object3.getString("reportid");
}

Multiple REPLACE function in Oracle

In case all your source and replacement strings are just one character long, you can simply use the TRANSLATE function:

  SELECT translate('THIS IS UPPERCASE', 'THISUP', 'thisup') 
  FROM DUAL

See the Oracle documentation for details.

Setting ANDROID_HOME enviromental variable on Mac OS X

A lot of correct answers here. However, one item is missing and I wasn't able to run the emulator from the command line without it.

export JAVA_HOME=$(/usr/libexec/java_home)
export PATH=$PATH:$JAVA_HOME/bin

export ANDROID_HOME=$HOME/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/emulator       # can't run emulator without it
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/platform-tools

So it's a compilation of the answers above plus a solution for this problem.

And if you use zsh (instead of bash) the file to edit is ~/.zshrc.

failed to push some refs to [email protected]

For anyone arriving here from a Google search with the same error message. Also be aware that you can have a problem if you are using sqlite3

https://devcenter.heroku.com/articles/sqlite3

Git Commit Messages: 50/72 Formatting

Is the maximum recommended title length really 50?

I have believed this for years, but as I just noticed the documentation of "git commit" actually states

$ git help commit | grep -C 1 50
      Though not required, it’s a good idea to begin the commit message with
      a single short (less than 50 character) line summarizing the change,
      followed by a blank line and then a more thorough description. The text

$  git version
git version 2.11.0

One could argue that "less then 50" can only mean "no longer than 49".

String format currency

I strongly suspect the problem is simply that the current culture of the thread handling the request isn't set appropriately.

You can either set it for the whole request, or specify the culture while formatting. Either way, I would suggest not use string.Format with a composite format unless you really have more than one thing to format (or a wider message). Instead, I'd use:

@price.ToString("C", culture)

It just makes it somewhat simpler.

EDIT: Given your comment, it sounds like you may well want to use a UK culture regardless of the culture of the user. So again, either set the UK culture as the thread culture for the whole request, or possibly introduce your own helper class with a "constant":

public static class Cultures
{
    public static readonly CultureInfo UnitedKingdom = 
        CultureInfo.GetCultureInfo("en-GB");
}

Then:

@price.ToString("C", Cultures.UnitedKingdom)

In my experience, having a "named" set of cultures like this makes the code using it considerably simpler to read, and you don't need to get the string right in multiple places.

Git: "Corrupt loose object"

Just remove .git folder and add it again. This simple solution worked for me.

How to change background and text colors in Sublime Text 3

For How do I change the overall colors (background and font)?

For MAC : goto Sublime text -> Preferences -> color scheme

Python class returning value

the worked proposition for me is __call__ on class who create list of little numbers:

import itertools
    
class SmallNumbers:
    def __init__(self, how_much):
        self.how_much = int(how_much)
        self.work_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
        self.generated_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
        start = 10
        end = 100
        for cmb in range(2, len(str(self.how_much)) + 1):
            self.ListOfCombinations(is_upper_then=start, is_under_then=end, combinations=cmb)
            start *= 10
            end *= 10

    def __call__(self, number, *args, **kwargs):
        return self.generated_list[number]

    def ListOfCombinations(self, is_upper_then, is_under_then, combinations):
        multi_work_list = eval(str('self.work_list,') * combinations)
        nbr = 0
        for subset in itertools.product(*multi_work_list):
            if is_upper_then <= nbr < is_under_then:
                self.generated_list.append(''.join(subset))
                if self.how_much == nbr:
                    break
            nbr += 1

and to run it:

if __name__ == '__main__':
        sm = SmallNumbers(56)
        print(sm.generated_list)
        print(sm.generated_list[34], sm.generated_list[27], sm.generated_list[10])
        print('The Best', sm(15), sm(55), sm(49), sm(0))

result

['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56']
34 27 10
The Best 15 55 49 0

Preventing console window from closing on Visual Studio C/C++ Console application

add “| pause” in command arguments box under debugging section at project properties.

What's onCreate(Bundle savedInstanceState)

If you save the state of the application in a bundle (typically non-persistent, dynamic data in onSaveInstanceState), it can be passed back to onCreate if the activity needs to be recreated (e.g., orientation change) so that you don't lose this prior information. If no data was supplied, savedInstanceState is null.

... you should use the onPause() method to write any persistent data (such as user edits) to storage. In addition, the method onSaveInstanceState(Bundle) is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle, to be later received in onCreate(Bundle) if the activity needs to be re-created. See the Process Lifecycle section for more information on how the lifecycle of a process is tied to the activities it is hosting. Note that it is important to save persistent data in onPause() instead of onSaveInstanceState(Bundle) because the latter is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.

source

Implementing a HashMap in C

The best approach depends on the expected key distribution and number of collisions. If relatively few collisions are expected, it really doesn't matter which method is used. If lots of collisions are expected, then which to use depends on the cost of rehashing or probing vs. manipulating the extensible bucket data structure.

But here is source code example of An Hashmap Implementation in C

What does the C++ standard state the size of int, long type to be?

I notice that all the other answers here have focused almost exclusively on integral types, while the questioner also asked about floating-points.

I don't think the C++ standard requires it, but compilers for the most common platforms these days generally follow the IEEE754 standard for their floating-point numbers. This standard specifies four types of binary floating-point (as well as some BCD formats, which I've never seen support for in C++ compilers):

  • Half precision (binary16) - 11-bit significand, exponent range -14 to 15
  • Single precision (binary32) - 24-bit significand, exponent range -126 to 127
  • Double precision (binary64) - 53-bit significand, exponent range -1022 to 1023
  • Quadruple precision (binary128) - 113-bit significand, exponent range -16382 to 16383

How does this map onto C++ types, then? Generally the float uses single precision; thus, sizeof(float) = 4. Then double uses double precision (I believe that's the source of the name double), and long double may be either double or quadruple precision (it's quadruple on my system, but on 32-bit systems it may be double). I don't know of any compilers that offer half precision floating-points.

In summary, this is the usual:

  • sizeof(float) = 4
  • sizeof(double) = 8
  • sizeof(long double) = 8 or 16

Delete files older than 15 days using PowerShell

#----- Define parameters -----#
#----- Get current date ----#
$Now = Get-Date
$Days = "15" #----- define amount of days ----#
$Targetfolder = "C:\Logs" #----- define folder where files are located ----#
$Extension = "*.log" #----- define extension ----#
$Lastwrite = $Now.AddDays(-$Days)

#----- Get files based on lastwrite filter and specified folder ---#
$Files = Get-Children $Targetfolder -include $Extension -Recurse | where {$_.LastwriteTime -le "$Lastwrite"}

foreach ($File in $Files)
{
    if ($File -ne $Null)
    {
        write-host "Deleting File $File" backgroundcolor "DarkRed"
        Remove-item $File.Fullname | out-null
    }
    else
        write-host "No more files to delete" -forgroundcolor "Green"
    }
}

Why does the preflight OPTIONS request of an authenticated CORS request work in Chrome but not Firefox?

It was particular for me. I am sending a header named 'SESSIONHASH'. No problem for Chrome and Opera, but Firefox also wants this header in the list "Access-Control-Allow-Headers". Otherwise, Firefox will throw the CORS error.

Tool to Unminify / Decompress JavaScript

Wasn't really happy with the output of jsbeautifier.org for what I was putting in, so I did some more searching and found this site: http://www.centralinternet.com.br/javascript-beautifier

Worked extremely well for me.

Determine device (iPhone, iPod Touch) with iOS

I'd like to add that to retrieve the front and enclosure color of the device there's a private API:

UIDevice *device = [UIDevice currentDevice];
SEL selector = NSSelectorFromString([device.systemVersion hasPrefix:@"7"] ? @"_deviceInfoForKey:" :  @"deviceInfoForKey:");
if ([device respondsToSelector:selector]) {
    NSLog(@"DeviceColor: %@ DeviceEnclosureColor: %@", [device performSelector:selector withObject:@"DeviceColor"], [device performSelector:selector withObject:@"DeviceEnclosureColor"]);
}

I've blogged about this and provide a sample app:

http://www.futuretap.com/blog/device-colors/

Is there a way to automatically build the package.json file for Node.js projects

use command npm init -f to generate package.json file and after that use --save after each command so that each module will automatically get updated inside your package.json for ex: npm install express --save

Make button width fit to the text

If you are aiming for maximum browser support, modern approach is to place button in a div with display:flex; and flex-direction:row; The same trick will work for height with flex-direction:column; or both height and width(will require 2 divs)

What is the common header format of Python files?

I strongly favour minimal file headers, by which I mean just:

  • The hashbang (#! line) if this is an executable script
  • Module docstring
  • Imports, grouped in the standard way, eg:
  import os    # standard library
  import sys

  import requests  # 3rd party packages

  from mypackage import (  # local source
      mymodule,
      myothermodule,
  )

ie. three groups of imports, with a single blank line between them. Within each group, imports are sorted. The final group, imports from local source, can either be absolute imports as shown, or explicit relative imports.

Everything else is a waste of time, visual space, and is actively misleading.

If you have legal disclaimers or licencing info, it goes into a separate file. It does not need to infect every source code file. Your copyright should be part of this. People should be able to find it in your LICENSE file, not random source code.

Metadata such as authorship and dates is already maintained by your source control. There is no need to add a less-detailed, erroneous, and out-of-date version of the same info in the file itself.

I don't believe there is any other data that everyone needs to put into all their source files. You may have some particular requirement to do so, but such things apply, by definition, only to you. They have no place in “general headers recommended for everyone”.

Trusting all certificates using HttpClient over HTTPS

enter image description here

A sspi failed in xamarin android.

I found this solution; put this code before you hit on an HTTPS link

const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
ServicePointManager.SecurityProtocol = Tls12;

MySQL parameterized queries

Here is another way to do it. It's documented on the MySQL official website. https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html

In the spirit, it's using the same mechanic of @Trey Stout's answer. However, I find this one prettier and more readable.

insert_stmt = (
  "INSERT INTO employees (emp_no, first_name, last_name, hire_date) "
  "VALUES (%s, %s, %s, %s)"
)
data = (2, 'Jane', 'Doe', datetime.date(2012, 3, 23))
cursor.execute(insert_stmt, data)

And to better illustrate any need for variables:

NB: note the escape being done.

employee_id = 2
first_name = "Jane"
last_name = "Doe"

insert_stmt = (
  "INSERT INTO employees (emp_no, first_name, last_name, hire_date) "
  "VALUES (%s, %s, %s, %s)"
)
data = (employee_id, conn.escape_string(first_name), conn.escape_string(last_name), datetime.date(2012, 3, 23))
cursor.execute(insert_stmt, data)

Visual Studio 2015 is very slow

After upgrading from VS2013, I found that when debugging in Visual Studio 2015, it would freeze, I unchecked "Tools>Options>Debugging>General>Enable Diagnostics Tools while debugging" It brought debugging sessions back to normal. While Diagnostics are useful, I don't need them all the time so if at any point I need them I can turn it back on.

Remove Identity from a column in a table

Just for someone who have the same problem I did. If you just want to make some insert just once you can do something like this.

Lets suppose you have a table with two columns

ID Identity (1,1) | Name Varchar

and want to insert a row with the ID = 4. So you Reseed it to 3 so the next one is 4

DBCC CHECKIDENT([YourTable], RESEED, 3)

Make the Insert

INSERT  INTO [YourTable]
        ( Name )
VALUES  ( 'Client' )

And get your seed back to the highest ID, lets suppose is 15

DBCC CHECKIDENT([YourTable], RESEED, 15)

Done!

How to store decimal values in SQL Server?

The other answers are right. Assuming your examples reflect the full range of possibilities what you want is DECIMAL(3, 1). Or, DECIMAL(14, 1) will allow a total of 14 digits. It's your job to think about what's enough.

installing requests module in python 2.7 windows

On windows 10 run cmd.exe with admin rights then type :

1) cd \Python27\scripts

2) pip install requests

It should work. My case was with python 2.7

Which HTML Parser is the best?

Self plug: I have just released a new Java HTML parser: jsoup. I mention it here because I think it will do what you are after.

Its party trick is a CSS selector syntax to find elements, e.g.:

String html = "<html><head><title>First parse</title></head>"
  + "<body><p>Parsed HTML into a doc.</p></body></html>";
Document doc = Jsoup.parse(html);
Elements links = doc.select("a");
Element head = doc.select("head").first();

See the Selector javadoc for more info.

This is a new project, so any ideas for improvement are very welcome!

How to import/include a CSS file using PHP code and not HTML code?

_trace its directory, I guess

echo css('lib/datatables_rqs/jquery.dataTables.css');

Which command do I use to generate the build of a Vue app?

For NPM => npm run Build For Yarn => yarn run build

You also can check scripts in package.json file

How do you remove duplicates from a list whilst preserving order?

Not to kick a dead horse (this question is very old and already has lots of good answers), but here is a solution using pandas that is quite fast in many circumstances and is dead simple to use.

import pandas as pd

my_list = [0, 1, 2, 3, 4, 1, 2, 3, 5]

>>> pd.Series(my_list).drop_duplicates().tolist()
# Output:
# [0, 1, 2, 3, 4, 5]

Multiplication on command line terminal

A simple shell function (no sed needed) should do the trick of interpreting '5X5'

$ function calc { bc -l <<< ${@//[xX]/*}; };
$ calc 5X5
25
$ calc 5x5
25
$ calc '5*5'
25

TypeError: 'NoneType' object is not iterable in Python

You're calling write_file with arguments like this:

write_file(foo, bar)

But you haven't defined 'foo' correctly, or you have a typo in your code so that it's creating a new empty variable and passing it in.

Can iterators be reset in Python?

Return a newly created iterator at the last iteration during the 'iter()' call

class ResetIter: 
  def __init__(self, num):
    self.num = num
    self.i = -1

  def __iter__(self):
    if self.i == self.num-1: # here, return the new object
      return self.__class__(self.num) 
    return self

  def __next__(self):
    if self.i == self.num-1:
      raise StopIteration

    if self.i <= self.num-1:
      self.i += 1
      return self.i


reset_iter = ResetRange(10)
for i in reset_iter:
  print(i, end=' ')
print()

for i in reset_iter:
  print(i, end=' ')
print()

for i in reset_iter:
  print(i, end=' ')

Output:

0 1 2 3 4 5 6 7 8 9 
0 1 2 3 4 5 6 7 8 9 
0 1 2 3 4 5 6 7 8 9 

XSLT string replace

replace isn't available for XSLT 1.0.

Codesling has a template for string-replace you can use as a substitute for the function:

<xsl:template name="string-replace-all">
    <xsl:param name="text" />
    <xsl:param name="replace" />
    <xsl:param name="by" />
    <xsl:choose>
        <xsl:when test="$text = '' or $replace = ''or not($replace)" >
            <!-- Prevent this routine from hanging -->
            <xsl:value-of select="$text" />
        </xsl:when>
        <xsl:when test="contains($text, $replace)">
            <xsl:value-of select="substring-before($text,$replace)" />
            <xsl:value-of select="$by" />
            <xsl:call-template name="string-replace-all">
                <xsl:with-param name="text" select="substring-after($text,$replace)" />
                <xsl:with-param name="replace" select="$replace" />
                <xsl:with-param name="by" select="$by" />
            </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="$text" />
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

invoked as:

<xsl:variable name="newtext">
    <xsl:call-template name="string-replace-all">
        <xsl:with-param name="text" select="$text" />
        <xsl:with-param name="replace" select="a" />
        <xsl:with-param name="by" select="b" />
    </xsl:call-template>
</xsl:variable>

On the other hand, if you literally only need to replace one character with another, you can call translate which has a similar signature. Something like this should work fine:

<xsl:variable name="newtext" select="translate($text,'a','b')"/>

Also, note, in this example, I changed the variable name to "newtext", in XSLT variables are immutable, so you can't do the equivalent of $foo = $foo like you had in your original code.

Detecting installed programs via registry

HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Compatibility Assistant\Persisted

Android Layout Weight

i would suppose to set the EditTexts width to wrap_content and put the two buttons into a LinearLayout whose width is fill_parent and weight set to 1.

Dialog throwing "Unable to add window — token null is not for an application” with getApplication() as context

I think it may happen as well if you are trying to show a dialog from a thread which is not the main UI thread.

Use runOnUiThread() in that case.

Undefined symbols for architecture x86_64 on Xcode 6.1

Check if that file is included in Build Phases -> Compiled Sources

async await return Task

You need to use the await keyword when use async and your function return type should be generic Here is an example with return value:

public async Task<object> MethodName()
{
    return await Task.FromResult<object>(null);
}

Here is an example with no return value:

public async Task MethodName()
{
    await Task.CompletedTask;
}

Read these:

TPL: http://msdn.microsoft.com/en-us/library/dd460717(v=vs.110).aspx and Tasks: http://msdn.microsoft.com/en-us/library/system.threading.tasks(v=vs.110).aspx

Async: http://msdn.microsoft.com/en-us/library/hh156513.aspx Await: http://msdn.microsoft.com/en-us/library/hh156528.aspx

Refresh certain row of UITableView based on Int in Swift

In Swift 3.0

let rowNumber: Int = 2
let sectionNumber: Int = 0

let indexPath = IndexPath(item: rowNumber, section: sectionNumber)

self.tableView.reloadRows(at: [indexPath], with: .automatic)

byDefault, if you have only one section in TableView, then you can put section value 0.

javascript filter array of objects

You can do this very easily with the [].filter method:

var filterednames = names.filter(function(obj) {
    return (obj.name === "Joe") && (obj.age < 30);
});

You will need to add a shim for browsers that don't support the [].filter method: this MDN page gives such code.

Field 'browser' doesn't contain a valid alias configuration

In my experience, this error was as a result of improper naming of aliases in Webpack. In that I had an alias named redux and webpack tried looking for the redux that comes with the redux package in my alias path.

To fix this, I had to rename the alias to something different like Redux.

Can not find the tag library descriptor of springframework

This problem normally appears while copy pasting the tag lib URL from the internet. Usually the quotes "" in which the URL http://www.springframework.org/tags is embedded might not be correct. Try removing quotes and type them manually. This resolved the issue for me.

How can I switch themes in Visual Studio 2012

For those who are using "High Contrast" windows themes but still want a regular Visual Studio theme you might notice that the theme selector drop down is disabled. You can still change it by doing the following...

  1. Going to the registry key: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0_Config\Themes (or whichever version of VS you are using)
  2. Export the key of the theme you want (it's a bunch of random letters / numbers) to a .reg file.
  3. Then copy the "high contrast" key's name (again random letters / numbers)
  4. Delete the high contrast key and then rename the dark theme to the copied name
  5. Then import the exported theme from the reg file.

This permanently sets the theme to the one you've chosen.

How to make two plots side-by-side using Python?

Check this page out: http://matplotlib.org/examples/pylab_examples/subplots_demo.html

plt.subplots is similar. I think it's better since it's easier to set parameters of the figure. The first two arguments define the layout (in your case 1 row, 2 columns), and other parameters change features such as figure size:

import numpy as np
import matplotlib.pyplot as plt

x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(5, 3))
axes[0].plot(x1, y1)
axes[1].plot(x2, y2)
fig.tight_layout()

enter image description here

How to force a SQL Server 2008 database to go Offline

You need to use WITH ROLLBACK IMMEDIATE to boot other conections out with no regards to what or who is is already using it.

Or use WITH NO_WAIT to not hang and not kill existing connections. See http://www.blackwasp.co.uk/SQLOffline.aspx for details

Connect HTML page with SQL server using javascript

<script>
var name=document.getElementById("name").value;
var address= document.getElementById("address").value;
var age= document.getElementById("age").value;

$.ajax({
      type:"GET",
      url:"http://hostname/projectfolder/webservicename.php?callback=jsondata&web_name="+name+"&web_address="+address+"&web_age="+age,
      crossDomain:true,
      dataType:'jsonp',
      success: function jsondata(data)
           {

            var parsedata=JSON.parse(JSON.stringify(data));
            var logindata=parsedata["Status"];

            if("sucess"==logindata)
            {   
                alert("success");
            }
            else
            {
                alert("failed");
            }
          }  
    }); 
<script>

You need to use web services. In the above code I have php web service to be used which has a callback function which is optional. Assuming you know HTML5 I did not post the html code. In the url you can send the details to the web server.

Javascript "Uncaught TypeError: object is not a function" associativity question

JavaScript does require semicolons, it's just that the interpreter will insert them for you on line breaks where possible*.

Unfortunately, the code

var a = new B(args)(stuff)()

does not result in a syntax error, so no ; will be inserted. (An example which can run is

var answer = new Function("x", "return x")(function(){return 42;})();

To avoid surprises like this, train yourself to always end a statement with ;.


* This is just a rule of thumb and not always true. The insertion rule is much more complicated. This blog page about semicolon insertion has more detail.

How to get integer values from a string in Python?

>>> import itertools
>>> int(''.join(itertools.takewhile(lambda s: s.isdigit(), string1)))

Byte Array in Python

In Python 3, we use the bytes object, also known as str in Python 2.

# Python 3
key = bytes([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])

# Python 2
key = ''.join(chr(x) for x in [0x13, 0x00, 0x00, 0x00, 0x08, 0x00])

I find it more convenient to use the base64 module...

# Python 3
key = base64.b16decode(b'130000000800')

# Python 2
key = base64.b16decode('130000000800')

You can also use literals...

# Python 3
key = b'\x13\0\0\0\x08\0'

# Python 2
key = '\x13\0\0\0\x08\0'

PHP Sort a multidimensional array by element containing date

For 'd/m/Y' dates:

usort($array, function ($a, $b, $i = 'datetime') { 
    $t1 = strtotime(str_replace('/', '-', $a[$i]));
    $t2 = strtotime(str_replace('/', '-', $b[$i]));

    return $t1 > $t2;
});

where $i is the array index

Retrieve filename from file descriptor in C

Impossible. A file descriptor may have multiple names in the filesystem, or it may have no name at all.

Edit: Assuming you are talking about a plain old POSIX system, without any OS-specific APIs, since you didn't specify an OS.

Correct way to integrate jQuery plugins in AngularJS

i have alreay 2 situations where directives and services/factories didnt play well.

the scenario is that i have (had) a directive that has dependency injection of a service, and from the directive i ask the service to make an ajax call (with $http).

in the end, in both cases the ng-Repeat did not file at all, even when i gave the array an initial value.

i even tried to make a directive with a controller and an isolated-scope

only when i moved everything to a controller and it worked like magic.

example about this here Initialising jQuery plugin (RoyalSlider) in Angular JS

How to change the date format of a DateTimePicker in vb.net

You need to set the Format of the DateTimePicker to Custom and then assign the CustomFormat.

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    DateTimePicker1.Format = DateTimePickerFormat.Custom
    DateTimePicker1.CustomFormat = "dd/MM/yyyy"
End Sub

How to compare two List<String> to each other?

You could also use Except(produces the set difference of two sequences) to check whether there's a difference or not:

IEnumerable<string> inFirstOnly = a1.Except(a2);
IEnumerable<string> inSecondOnly = a2.Except(a1);
bool allInBoth = !inFirstOnly.Any() && !inSecondOnly.Any();

So this is an efficient way if the order and if the number of duplicates does not matter(as opposed to the accepted answer's SequenceEqual). Demo: Ideone

If you want to compare in a case insentive way, just add StringComparer.OrdinalIgnoreCase:

a1.Except(a2, StringComparer.OrdinalIgnoreCase)

Excel Reference To Current Cell

Without INDIRECT(): =CELL("width", OFFSET($A$1,ROW()-1,COLUMN()-1) )

Verilog: How to instantiate a module

This is all generally covered by Section 23.3.2 of SystemVerilog IEEE Std 1800-2012.

The simplest way is to instantiate in the main section of top, creating a named instance and wiring the ports up in order:

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  clk, rst_n, data_rx_1, data_tx ); 

endmodule

This is described in Section 23.3.2.1 of SystemVerilog IEEE Std 1800-2012.

This has a few draw backs especially regarding the port order of the subcomponent code. simple refactoring here can break connectivity or change behaviour. for example if some one else fixs a bug and reorders the ports for some reason, switching the clk and reset order. There will be no connectivity issue from your compiler but will not work as intended.

module subcomponent(
  input        rst_n,       
  input        clk,
  ...

It is therefore recommended to connect using named ports, this also helps tracing connectivity of wires in the code.

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  .clk(clk), .rst_n(rst_n), .data_rx(data_rx_1), .data_tx(data_tx) ); 

endmodule

This is described in Section 23.3.2.2 of SystemVerilog IEEE Std 1800-2012.

Giving each port its own line and indenting correctly adds to the readability and code quality.

subcomponent subcomponent_instance_name (
  .clk      ( clk       ), // input
  .rst_n    ( rst_n     ), // input
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

So far all the connections that have been made have reused inputs and output to the sub module and no connectivity wires have been created. What happens if we are to take outputs from one component to another:

clk_gen( 
  .clk      ( clk_sub   ), // output
  .en       ( enable    )  // input

subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

This nominally works as a wire for clk_sub is automatically created, there is a danger to relying on this. it will only ever create a 1 bit wire by default. An example where this is a problem would be for the data:

Note that the instance name for the second component has been changed

subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_temp )  // output [9:0]
);
subcomponent subcomponent_instance_name2 (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_temp ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

The issue with the above code is that data_temp is only 1 bit wide, there would be a compile warning about port width mismatch. The connectivity wire needs to be created and a width specified. I would recommend that all connectivity wires be explicitly written out.

wire [9:0] data_temp
subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_temp )  // output [9:0]
);
subcomponent subcomponent_instance_name2 (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_temp ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

Moving to SystemVerilog there are a few tricks available that save typing a handful of characters. I believe that they hinder the code readability and can make it harder to find bugs.

Use .port with no brackets to connect to a wire/reg of the same name. This can look neat especially with lots of clk and resets but at some levels you may generate different clocks or resets or you actually do not want to connect to the signal of the same name but a modified one and this can lead to wiring bugs that are not obvious to the eye.

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  .clk,                    // input **Auto connect**
  .rst_n,                  // input **Auto connect**
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

endmodule

This is described in Section 23.3.2.3 of SystemVerilog IEEE Std 1800-2012.

Another trick that I think is even worse than the one above is .* which connects unmentioned ports to signals of the same wire. I consider this to be quite dangerous in production code. It is not obvious when new ports have been added and are missing or that they might accidentally get connected if the new port name had a counter part in the instancing level, they get auto connected and no warning would be generated.

subcomponent subcomponent_instance_name (
  .*,                      // **Auto connect**
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

This is described in Section 23.3.2.4 of SystemVerilog IEEE Std 1800-2012.

hasOwnProperty in JavaScript

hasOwnProperty() is a nice property to validate object keys. Example:

var obj = {a:1, b:2};

obj.hasOwnProperty('a') // true

How to save a Python interactive session?

I'd like to suggest another way to maintain python session through tmux on linux. you run tmux, attach your self to the session you opened (if not attached after opening it directly). execute python and do whatever you are doing on it. then detach from session. detaching from a tmux session does not close the session. the session remains open.

pros of this method: you can attach to this session from any other device (in case you can ssh your pc)

cons of this method: this method does not relinquish the resources used by the opened python session until you actually exist the python interpreter.

Change Button color onClick

There are indeed global variables in javascript. You can learn more about scopes, which are helpful in this situation.

Your code could look like this:

<script>
    var count = 1;
    function setColor(btn, color) {
        var property = document.getElementById(btn);
        if (count == 0) {
            property.style.backgroundColor = "#FFFFFF"
            count = 1;        
        }
        else {
            property.style.backgroundColor = "#7FFF00"
            count = 0;
        }
    }
</script>

Hope this helps.

Multiple left joins on multiple tables in one query

The JOIN statements are also part of the FROM clause, more formally a join_type is used to combine two from_item's into one from_item, multiple one of which can then form a comma-separated list after the FROM. See http://www.postgresql.org/docs/9.1/static/sql-select.html .

So the direct solution to your problem is:

SELECT something
FROM
    master as parent LEFT JOIN second as parentdata
        ON parent.secondary_id = parentdata.id,
    master as child LEFT JOIN second as childdata
        ON child.secondary_id = childdata.id
WHERE parent.id = child.parent_id AND parent.parent_id = 'rootID'

A better option would be to only use JOIN's, as it has already been suggested.

Removing underline with href attribute

Add a style with the attribute text-decoration:none;:

There are a number of different ways of doing this.

Inline style:

<a href="xxx.html" style="text-decoration:none;">goto this link</a>

Inline stylesheet:

<html>
<head>
<style type="text/css">
   a {
      text-decoration:none;
   }
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

External stylesheet:

<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

stylesheet.css:

a {
      text-decoration:none;
   }

Renaming the current file in Vim

There’s a function in Gary Bernhardt’s .vimrc that handles this.

function! RenameFile()
let old_name = expand('%')
let new_name = input('New file name: ', expand('%'), 'file')
if new_name != '' && new_name != old_name
    exec ':saveas ' . new_name
    exec ':silent !rm ' . old_name
    redraw!
endif
endfunction
map <leader>n :call RenameFile()<cr>

How to get day of the month?

tl;dr

LocalDate           // Represent a date-only, without time-of-day and without time zone.
.now()              // Better to pass a `ZoneId` optional argument to `now` as shown below than rely implicitly on the JVM’s current default time zone.
.getDayOfMonth()    // Interrogate for the day of the month (1-31). 

java.time

The modern approach is the LocalDate class to represent a date-only value.

A time zone is crucial in determine the current date. For any given moment, the date varies around the globe by zone.

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate ld = LocalDate.now( z ) ;
int dayOfMonth = ld.getDayOfMonth();

You can also get the day-of-week.

DayOfWeek dow = ld.getDayOfWeek();

About java.time

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

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

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

Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.

Where to obtain the java.time classes?

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


Joda-Time

UPDATE: The Joda-Time project is now in maintenance mode, and advises migration to the java.time classes. This section left intact for history.

Using the Joda-Time 2.5 library rather than the notoriously troublesome java.util.Date and .Calendar classes.

Time zone is crucial to determining a date. Better to specify the zone rather than rely implicitly on the JVM’s current default time zone being assigned.

DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zone ).withTimeAtStartOfDay();
int dayOfMonth = now.getDayOfMonth();

Or use similar code with the LocalDate class that has no time-of-day portion.

Spring Boot JPA - configuring auto reconnect

For those who want to do it from YAML with multiple data sources, there is a great blog post about it: https://springframework.guru/how-to-configure-multiple-data-sources-in-a-spring-boot-application/

It basically says you both need to configure data source properties and datasource like this:

@Bean
@Primary
@ConfigurationProperties("app.datasource.member")
public DataSourceProperties memberDataSourceProperties() {
    return new DataSourceProperties();
}

@Bean
@Primary
@ConfigurationProperties("app.datasource.member.hikari")
public DataSource memberDataSource() {
    return memberDataSourceProperties().initializeDataSourceBuilder()
            .type(HikariDataSource.class).build();
}

Do not forget to remove @Primary from other datasources.

Determine .NET Framework version for dll

If you have DotPeek from JetBrains, you can see it in Assembly Explorer.

Can you see this screenshot? im not:(

Replace specific text with a redacted version using Python

You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.

NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.

Example:

Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.

Returns:

NER with spacy

Just be aware that this is not 100%!

Here are a little snippet for you to try out:

import spacy

phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
   doc = nlp(phrase)
   replaced = ""
   for token in doc:
      if token in doc.ents:
         replaced+="XXXX "
      else:
         replaced+=token.text+" "

Read more here: https://spacy.io/usage/linguistic-features#named-entities

You could, instead of replacing with XXXX, replace based on the entity type, like:

if ent.label_ == "PERSON":
   replaced += "<PERSON> "

Then:

import re, random

personames = ["Jack", "Mike", "Bob", "Dylan"]

phrase = re.replace("<PERSON>", random.choice(personames), phrase)

How to enable/disable bluetooth programmatically in android

I used the below code to disable BT when my app launches and works fine. Not sure if this the correct way to implement this as google recommends not using "bluetooth.disable();" without explicit user action to turn off Bluetooth.

    BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
    bluetooth.disable();

I only used the below permission.

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

How to hide elements without having them take space on the page?

use style instead like

<div style="display:none;"></div>

Showing alert in angularjs when user leaves a page

The other examples here work fine for the old versions of ui-router (>=0.3.x) but all state events, such as $stateChangeStart, are deprecated as of 1.0. The new ui-router 1.0 code uses the $transitions service. So you need to inject $transitions into your component then use the $transitions.onBefore method as the code below demonstrates.

$transitions.onBefore({}, function(transition) {
  return confirm("Are you sure you want to leave this page?");
});

This is just a super simple example. The $transitions service can accept more complicated responses such as promises. See the HookResult type for more information.

How to upload a file and JSON data in Postman?

To send image along with json data in postman you just have to follow the below steps .

  • Make your method to post in postman
  • go to the body section and click on form-data
  • provide your field name select file from the dropdown list as shown below
  • you can also provide your other fields .
  • now just write your image storing code in your controller as shown below .

postman : enter image description here

my controller :

public function sendImage(Request $request)
{
    $image=new ImgUpload;  
    if($request->hasfile('image'))  
    {  
        $file=$request->file('image');  
        $extension=$file->getClientOriginalExtension();  
        $filename=time().'.'.$extension;  
        $file->move('public/upload/userimg/',$filename);  
        $image->image=$filename;  
    }  
    else  
    {  
        return $request;  
        $image->image='';  
    }  
    $image->save();
    return response()->json(['response'=>['code'=>'200','message'=>'image uploaded successfull']]);
}

That's it hope it will help you

How can one run multiple versions of PHP 5.x on a development LAMP server?

One way to do this is to have your main version of php set up with mod_php and run all of the others through fast cgi on different ports (i.e. 81, 82, 83 etc). This won't guarantee totally consistent behavior though.

Oracle SQL, concatenate multiple columns + add text

select 'i like' || type_column || ' with' ect....

get parent's view from a layout

Check my answer here

The use of Layout Inspector tool can be very convenient when you have a complex view or you are using a third party library where you can't add an id to a view

Update span tag value with JQuery

Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.

    $("legend").each(function() {
        var SoftwareItem = $(this).text();
        itemCost = GetItemCost(SoftwareItem);
        $("input:checked").each(function() {               
            var Component = $(this).next("label").text();
            itemCost += GetItemCost(Component);
        });            
        $(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
    });

Express.js Response Timeout

There is already a Connect Middleware for Timeout support:

var timeout = express.timeout // express v3 and below
var timeout = require('connect-timeout'); //express v4

app.use(timeout(120000));
app.use(haltOnTimedout);

function haltOnTimedout(req, res, next){
  if (!req.timedout) next();
}

If you plan on using the Timeout middleware as a top-level middleware like above, the haltOnTimedOut middleware needs to be the last middleware defined in the stack and is used for catching the timeout event. Thanks @Aichholzer for the update.

Side Note:

Keep in mind that if you roll your own timeout middleware, 4xx status codes are for client errors and 5xx are for server errors. 408s are reserved for when:

The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time.

Can constructors be async?

Your problem is comparable to the creation of a file object and opening the file. In fact there are a lot of classes where you have to perform two steps before you can actually use the object: create + Initialize (often called something similar to Open).

The advantage of this is that the constructor can be lightweight. If desired, you can change some properties before actually initializing the object. When all properties are set, the Initialize/Open function is called to prepare the object to be used. This Initialize function can be async.

The disadvantage is that you have to trust the user of your class that he will call Initialize() before he uses any other function of your class. In fact if you want to make your class full proof (fool proof?) you have to check in every function that the Initialize() has been called.

The pattern to make this easier is to declare the constructor private and make a public static function that will construct the object and call Initialize() before returning the constructed object. This way you'll know that everyone who has access to the object has used the Initialize function.

The example shows a class that mimics your desired async constructor

public MyClass
{
    public static async Task<MyClass> CreateAsync(...)
    {
        MyClass x = new MyClass();
        await x.InitializeAsync(...)
        return x;
    }

    // make sure no one but the Create function can call the constructor:
    private MyClass(){}

    private async Task InitializeAsync(...)
    {
        // do the async things you wanted to do in your async constructor
    }

    public async Task<int> OtherFunctionAsync(int a, int b)
    {
        return await ... // return something useful
    }

Usage will be as follows:

public async Task<int> SomethingAsync()
{
    // Create and initialize a MyClass object
    MyClass myObject = await MyClass.CreateAsync(...);

    // use the created object:
    return await myObject.OtherFunctionAsync(4, 7);
}

MySQL & Java - Get id of the last inserted value (JDBC)

Alternatively you can do:

Statement stmt = db.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
numero = stmt.executeUpdate();

ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
    risultato=rs.getString(1);
}

But use Sean Bright's answer instead for your scenario.

After MySQL install via Brew, I get the error - The server quit without updating PID file

While Installing from source,please follow the instruction in file INSTALL-SOURCE

where installation instruction are given in section 2.8

after installation ,check are there any process running of mysql with ps aux | grep mysql

You'll find like this

root      1817  0.0  0.0 108336  1228 ?        S    Jan21   0:00 /bin/sh /usr/local/mysql/bin/mysqld_safe --datadir=/usr/local/mysql/data --pid-file=/usr/local/mysql/data/mail.gaurav.local.pid
mysql     2141  0.0  1.2 497660 24588 ?        Sl   Jan21   0:26 /usr/local/mysql/bin/mysqld --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data --plugin-dir=/usr/local/mysql/lib/plugin --user=mysql --log-error=/usr/local/mysql/data/mail.gaurav.local.err --pid-file=/usr/local/mysql/data/mail.gaurav.local.pid --socket=/tmp/mysql.sock --port=3306
root      5659  0.0  0.0 103256   840 pts/13   S+   11:30   0:00 grep mysql

kill all process related to mysql,and then try to start mysql server

How to generate a random string of 20 characters

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

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

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

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

Conditionally Remove Dataframe Rows with R

Logic index:

d<-d[!(d$A=="B" & d$E==0),]

How to send a message to a particular client with socket.io

Here is the full solution for Android Client + Socket IO Server (Lot of code but works). There seems to be lack of support for Android and IOS when it comes to socket io which is a tragedy of sorts.

Basically creating a room name by joining user unique id from mysql or mongo then sorting it (done in Android Client and sent to server). So each pair has a unique but common amongst the pair room name. Then just go about chatting in that room.

For quick refernce how room is created in Android

 // Build The Chat Room
        if (Integer.parseInt(mySqlUserId) < Integer.parseInt(toMySqlUserId)) {
            room = "ic" + mySqlUserId + toMySqlUserId;
        } else {
            room = "ic" + toMySqlUserId + mySqlUserId;
        }

The Full Works

Package Json

"dependencies": {
    "express": "^4.17.1",
    "socket.io": "^2.3.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.6"
  }

Socket IO Server

app = require('express')()
http = require('http').createServer(app)
io = require('socket.io')(http)

app.get('/', (req, res) => {

    res.send('Chat server is running on port 5000')
})

io.on('connection', (socket) => {

    // console.log('one user connected ' + socket.id);

    // Join Chat Room
    socket.on('join', function(data) {

        console.log('======Joined Room========== ');
        console.log(data);

        // Json Parse String To Access Child Elements
        var messageJson = JSON.parse(data);
        const room = messageJson.room;
        console.log(room);

        socket.join(room);

    });

    // On Receiving Individual Chat Message (ic_message)
    socket.on('ic_message', function(data) {
        console.log('======IC Message========== ');
        console.log(data);

        // Json Parse String To Access Child Elements
        var messageJson = JSON.parse(data);
        const room = messageJson.room;
        const message = messageJson.message;

        console.log(room);
        console.log(message);

        // Sending to all clients in room except sender
        socket.broadcast.to(room).emit('new_msg', {
            msg: message
        });

    });

    socket.on('disconnect', function() {
        console.log('one user disconnected ' + socket.id);
    });

});

http.listen(5000, () => {

    console.log('Node app is running on port 5000')
})

Android Socket IO Class

public class SocketIOClient {

    public Socket mSocket;

    {
        try {
            mSocket = IO.socket("http://192.168.1.5:5000");
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    public Socket getSocket() {
        return mSocket;
    }
}

Android Activity

public class IndividualChatSocketIOActivity extends AppCompatActivity {

    // Activity Number For Bottom Navigation Menu
    private final Context mContext = IndividualChatSocketIOActivity.this;

    // Strings
    private String mySqlUserId;
    private String toMySqlUserId;

    // Widgets
    private EditText etTextMessage;
    private ImageView ivSendMessage;

    // Socket IO
    SocketIOClient socketIOClient = new SocketIOClient();
    private String room;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        // Widgets
        etTextMessage = findViewById(R.id.a_chat_et_text_message);
        ivSendMessage = findViewById(R.id.a_chat_iv_send_message);

        // Get The MySql UserId from Shared Preference
        mySqlUserId = StartupMethods.getFromSharedPreferences("shared",
                                                              "id",
                                                              mContext);

        // Variables From Individual List Adapter
        Intent intent = getIntent();

        if (intent.hasExtra("to_id")) {

            toMySqlUserId = Objects.requireNonNull(Objects.requireNonNull(getIntent().getExtras())
                                                          .get("to_id"))
                                   .toString();
        }

        // Build The Chat Room
        if (Integer.parseInt(mySqlUserId) < Integer.parseInt(toMySqlUserId)) {
            room = "ic" + mySqlUserId + toMySqlUserId;
        } else {
            room = "ic" + toMySqlUserId + mySqlUserId;
        }

        connectToSocketIO();

        joinChat();

        leaveChat();

        getChatMessages();

        sendChatMessages();

    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    private void connectToSocketIO() {

        socketIOClient.mSocket = socketIOClient.getSocket();
        socketIOClient.mSocket.on(Socket.EVENT_CONNECT_ERROR,
                                  onConnectError);
        socketIOClient.mSocket.on(Socket.EVENT_CONNECT_TIMEOUT,
                                  onConnectError);
        socketIOClient.mSocket.on(Socket.EVENT_CONNECT,
                                  onConnect);
        socketIOClient.mSocket.on(Socket.EVENT_DISCONNECT,
                                  onDisconnect);
        socketIOClient.mSocket.connect();
    }

    private void joinChat() {

        // Prepare To Send Data Through WebSockets
        JSONObject jsonObject = new JSONObject();

        // Header Fields
        try {

            jsonObject.put("room",
                           room);

            socketIOClient.mSocket.emit("join",
                                        String.valueOf(jsonObject));

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private void leaveChat() {
    }

    private void getChatMessages() {

        socketIOClient.mSocket.on("new_msg",
                                  new Emitter.Listener() {
                                      @Override
                                      public void call(Object... args) {
                                          try {
                                              JSONObject messageJson = new JSONObject(args[0].toString());
                                              String message = String.valueOf(messageJson);

                                              runOnUiThread(new Runnable() {
                                                  @Override
                                                  public void run() {
                                                      Toast.makeText(IndividualChatSocketIOActivity.this,
                                                                     message,
                                                                     Toast.LENGTH_SHORT)
                                                           .show();
                                                  }
                                              });
                                          } catch (JSONException e) {
                                              e.printStackTrace();
                                          }
                                      }
                                  });
    }

    private void sendChatMessages() {

        ivSendMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String message = etTextMessage.getText()
                                              .toString()
                                              .trim();

                // Prepare To Send Data Thru WebSockets
                JSONObject jsonObject = new JSONObject();

                // Header Fields
                try {
                    jsonObject.put("room",
                                   room);

                    jsonObject.put("message",
                                   message);

                    socketIOClient.mSocket.emit("ic_message",
                                                String.valueOf(jsonObject));

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    public Emitter.Listener onConnect = new Emitter.Listener() {
        @Override
        public void call(Object... args) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(IndividualChatSocketIOActivity.this,
                                   "Connected To Socket Server",
                                   Toast.LENGTH_SHORT)
                         .show();

                }
            });

            Log.d("TAG",
                  "Socket Connected!");
        }
    };

    private Emitter.Listener onConnectError = new Emitter.Listener() {
        @Override
        public void call(Object... args) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                }
            });
        }
    };
    private Emitter.Listener onDisconnect = new Emitter.Listener() {
        @Override
        public void call(Object... args) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                }
            });
        }
    };

}

Android Gradle

// SocketIO
implementation ('io.socket:socket.io-client:1.0.0') {
    // excluding org.json which is provided by Android
    exclude group: 'org.json', module: 'json'
}

How to include (source) R script in other scripts

I solved my problem using entire address where my code is: Before:

if(!exists("foo", mode="function")) source("utils.r")

After:

if(!exists("foo", mode="function")) source("C:/tests/utils.r")

Get the IP Address of local computer

The problem with all the approaches based on gethostbyname is that you will not get all IP addresses assigned to a particular machine. Servers usually have more than one adapter.

Here is an example of how you can iterate through all Ipv4 and Ipv6 addresses on the host machine:

void ListIpAddresses(IpAddresses& ipAddrs)
{
  IP_ADAPTER_ADDRESSES* adapter_addresses(NULL);
  IP_ADAPTER_ADDRESSES* adapter(NULL);

  // Start with a 16 KB buffer and resize if needed -
  // multiple attempts in case interfaces change while
  // we are in the middle of querying them.
  DWORD adapter_addresses_buffer_size = 16 * KB;
  for (int attempts = 0; attempts != 3; ++attempts)
  {
    adapter_addresses = (IP_ADAPTER_ADDRESSES*)malloc(adapter_addresses_buffer_size);
    assert(adapter_addresses);

    DWORD error = ::GetAdaptersAddresses(
      AF_UNSPEC, 
      GAA_FLAG_SKIP_ANYCAST | 
        GAA_FLAG_SKIP_MULTICAST | 
        GAA_FLAG_SKIP_DNS_SERVER |
        GAA_FLAG_SKIP_FRIENDLY_NAME, 
      NULL, 
      adapter_addresses,
      &adapter_addresses_buffer_size);

    if (ERROR_SUCCESS == error)
    {
      // We're done here, people!
      break;
    }
    else if (ERROR_BUFFER_OVERFLOW == error)
    {
      // Try again with the new size
      free(adapter_addresses);
      adapter_addresses = NULL;

      continue;
    }
    else
    {
      // Unexpected error code - log and throw
      free(adapter_addresses);
      adapter_addresses = NULL;

      // @todo
      LOG_AND_THROW_HERE();
    }
  }

  // Iterate through all of the adapters
  for (adapter = adapter_addresses; NULL != adapter; adapter = adapter->Next)
  {
    // Skip loopback adapters
    if (IF_TYPE_SOFTWARE_LOOPBACK == adapter->IfType)
    {
      continue;
    }

    // Parse all IPv4 and IPv6 addresses
    for (
      IP_ADAPTER_UNICAST_ADDRESS* address = adapter->FirstUnicastAddress; 
      NULL != address;
      address = address->Next)
    {
      auto family = address->Address.lpSockaddr->sa_family;
      if (AF_INET == family)
      {
        // IPv4
        SOCKADDR_IN* ipv4 = reinterpret_cast<SOCKADDR_IN*>(address->Address.lpSockaddr);

        char str_buffer[INET_ADDRSTRLEN] = {0};
        inet_ntop(AF_INET, &(ipv4->sin_addr), str_buffer, INET_ADDRSTRLEN);
        ipAddrs.mIpv4.push_back(str_buffer);
      }
      else if (AF_INET6 == family)
      {
        // IPv6
        SOCKADDR_IN6* ipv6 = reinterpret_cast<SOCKADDR_IN6*>(address->Address.lpSockaddr);

        char str_buffer[INET6_ADDRSTRLEN] = {0};
        inet_ntop(AF_INET6, &(ipv6->sin6_addr), str_buffer, INET6_ADDRSTRLEN);

        std::string ipv6_str(str_buffer);

        // Detect and skip non-external addresses
        bool is_link_local(false);
        bool is_special_use(false);

        if (0 == ipv6_str.find("fe"))
        {
          char c = ipv6_str[2];
          if (c == '8' || c == '9' || c == 'a' || c == 'b')
          {
            is_link_local = true;
          }
        }
        else if (0 == ipv6_str.find("2001:0:"))
        {
          is_special_use = true;
        }

        if (! (is_link_local || is_special_use))
        {
          ipAddrs.mIpv6.push_back(ipv6_str);
        }
      }
      else
      {
        // Skip all other types of addresses
        continue;
      }
    }
  }

  // Cleanup
  free(adapter_addresses);
  adapter_addresses = NULL;

  // Cheers!
}

Generate JSON string from NSDictionary in iOS

This will work in swift4 and swift5.

let dataDict = "the dictionary you want to convert in jsonString" 

let jsonData = try! JSONSerialization.data(withJSONObject: dataDict, options: JSONSerialization.WritingOptions.prettyPrinted)

let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String

print(jsonString)

C# : Passing a Generic Object

You need to define something in the interface, such as:

public interface ITest
{
    string Name { get; }
}

Implement ITest in your classes:

public class MyClass1 : ITest
{
    public string Name { get { return "Test1"; } }
}

public class MyClass2 : ITest
{
    public string Name { get { return "Test2"; } }
}

Then restrict your generic Print function, to ITest:

public void Print<T>(T test) where T : ITest
{
}

The transaction manager has disabled its support for remote/network transactions

In case others have the same issue:

I had a similar error happening. turned out I was wrapping several SQL statements in a transactions, where one of them executed on a linked server (Merge statement in an EXEC(...) AT Server statement). I resolved the issue by opening a separate connection to the linked server, encapsulating that statement in a try...catch then abort the transaction on the original connection in case the catch is tripped.

HTML-encoding lost when attribute read from input field

For those who prefer plain javascript, here is the method I have used successfully:

function escapeHTML (str)
{
    var div = document.createElement('div');
    var text = document.createTextNode(str);
    div.appendChild(text);
    return div.innerHTML;
}

Simple way to encode a string according to a password?

Whoever came here (and the bountier) seemed to be looking for one-liners with not much setup, which other answers don't provide. So I'm putting forward base64.

Now, keep in mind that this is basic obfuscation only, and is in **NO WAY OK FOR SECURITY**, but here are some one-liners:

from base64 import urlsafe_b64encode, urlsafe_b64decode

def encode(data, key):
    return urlsafe_b64encode(bytes(key+data, 'utf-8'))

def decode(enc, key):
    return urlsafe_b64decode(enc)[len(key):].decode('utf-8')

print(encode('hi', 'there')) # b'dGhlcmVoaQ=='
print(decode(encode('hi', 'there'), 'there')) # 'hi'

A few things to note:

  • you will want to deal with more/less byte-to-string encoding/decoding on your own, depending on your I/O. Look into bytes() and bytes::decode()
  • base64 is easily recognizable by the types of characters used, and often ending with = characters. People like me absolutely go around decoding them in the javascript console when we see them on websites. It's as easy as btoa(string) (js)
  • the order is key+data, as in b64, what characters appear at the end depends on what characters are at the beginning (because of byte offsets. Wikipedia has some nice explanations). In this scenario, the beginning of the encoded string will be the same for everything encoded with that key. The plus is that the data will be more obfuscated. Doing it the other way around will result on the data part being exactly the same for everyone, regardless of key.

Now, if what you wanted didn't even need a key of any kind, but just some obfuscation, you can yet again just use base64, without any kinds of key:

from base64 import urlsafe_b64encode, urlsafe_b64decode

def encode(data):
    return urlsafe_b64encode(bytes(data, 'utf-8'))

def decode(enc):
    return urlsafe_b64decode(enc).decode()

print(encode('hi')) # b'aGk='
print(decode(encode('hi'))) # 'hi'

Combination of async function + await + setTimeout

await setTimeout(()=>{}, 200);

Will work if your Node version is 15 and above.

Compare two dates in Java

It's not clear to me what you want, but I'll mention that the Date class also has a compareTo method, which can be used to determine with one call if two Date objects are equal or (if they aren't equal) which occurs sooner. This allows you to do something like:

switch (today.compareTo(questionDate)) {
    case -1:  System.out.println("today is sooner than questionDate");  break;
    case 0:   System.out.println("today and questionDate are equal");  break;
    case 1:   System.out.println("today is later than questionDate");  break;
    default:  System.out.println("Invalid results from date comparison"); break;
}

It should be noted that the API docs don't guarantee the results to be -1, 0, and 1, so you may want to use if-elses rather than a switch in any production code. Also, if the second date is null, you'll get a NullPointerException, so wrapping your code in a try-catch may be useful.

Embedding JavaScript engine into .NET

I just tried RemObjects Script for .Net.

It works, although I had to use a static factory (var a=A.createA();) from JavaScript instead of the var a=new A() syntax. (ExposeType function only exposes statics!) Not much documentation and the source is written with Delphi Prism, which is rather unusual for me and the RedGate Reflector.

So: Easy to use and setup, but not much help for advanced scenarios.

Also having to install something instead of just dropping the assemblies in a directory is a negative for me...

Assign JavaScript variable to Java Variable in JSP

As JavaScript is client side and JSP is Server side.

So Javascript does not execute until it gets to the browser, But Java executes on the server. So, Java does not know the value of the JavaScript variable.

However you assign value of Java variable to JavaScript variable.

jQuery AJAX form data serialize using PHP

I just had the same problem: You have to unserialize the data on the php side.

Add to the beginning of your php file (Attention this short version would replace all other post variables):

parse_str($_POST["data"], $_POST);

json_decode to array

Try like this:

$json_string = 'https://example.com/jsondata.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata);
print_r($obj->Result);
foreach($obj->Result as $value){
  echo $value->id; //change accordingly
}

How do I get the calling method name and type using reflection?

You can use it by using the StackTrace and then you can get reflective types from that.

StackTrace stackTrace = new StackTrace();           // get call stack
StackFrame[] stackFrames = stackTrace.GetFrames();  // get method calls (frames)

StackFrame callingFrame = stackFrames[1];
MethodInfo method = callingFrame.GetMethod();
Console.Write(method.Name);
Console.Write(method.DeclaringType.Name);

HTML5 placeholder css padding

I found the answer that remedied my frustrations regarding this on John Catterfeld's blog.

... Chrome (v20-30) implements almost all styles but with a major caveat – the placeholder styles do no resize the input box, so stay clear of things like line-height and padding top or bottom.

If you are using line-height or padding you are going to be frustrated with the resulting placeholder. I haven't found a way around that up to this point.

Is it possible to put a ConstraintLayout inside a ScrollView?

use NestedScrollView with viewport true is working good for me

<android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="700dp">

        </android.support.constraint.ConstraintLayout>

</android.support.v4.widget.NestedScrollView>

Firebase (FCM) how to get token

Instead of this:

    // [START refresh_token]
    @Override
    public void onTokenRefresh() {
//        Get updated InstanceID token.
//        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
//        Log.d(TAG, "Refreshed token: " + refreshedToken);
//
//        TODO: Implement this method to send any registration to your app's servers.
//        sendRegistrationToServer(refreshedToken);
//
        Intent intent = new Intent(this, RegistrationIntentService.class);
        startService(intent);
    }
    // [END refresh_token]

Do this:

    // [START refresh_token]
    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
//        Log.d(TAG, "Refreshed token: " + refreshedToken);

        // Implement this method to send token to your app's server
       sendRegistrationToServer(refreshedToken);

    }
    // [END refresh_token]

And one more thing:

You need to call sendRegistrationToServer() method which will update token on server, if you are sending push notifications from server.

UPDATE:

New Firebase token is generated (onTokenRefresh() is called) when:

  • The app deletes Instance ID
  • The app is restored on a new device
  • The user uninstalls/reinstall the app
  • The user clears app data.

Use of PUT vs PATCH methods in REST API real life scenarios

Though Dan Lowe's excellent answer very thoroughly answered the OP's question about the difference between PUT and PATCH, its answer to the question of why PATCH is not idempotent is not quite correct.

To show why PATCH isn't idempotent, it helps to start with the definition of idempotence (from Wikipedia):

The term idempotent is used more comprehensively to describe an operation that will produce the same results if executed once or multiple times [...] An idempotent function is one that has the property f(f(x)) = f(x) for any value x.

In more accessible language, an idempotent PATCH could be defined as: After PATCHing a resource with a patch document, all subsequent PATCH calls to the same resource with the same patch document will not change the resource.

Conversely, a non-idempotent operation is one where f(f(x)) != f(x), which for PATCH could be stated as: After PATCHing a resource with a patch document, subsequent PATCH calls to the same resource with the same patch document do change the resource.

To illustrate a non-idempotent PATCH, suppose there is a /users resource, and suppose that calling GET /users returns a list of users, currently:

[{ "id": 1, "username": "firstuser", "email": "[email protected]" }]

Rather than PATCHing /users/{id}, as in the OP's example, suppose the server allows PATCHing /users. Let's issue this PATCH request:

PATCH /users
[{ "op": "add", "username": "newuser", "email": "[email protected]" }]

Our patch document instructs the server to add a new user called newuser to the list of users. After calling this the first time, GET /users would return:

[{ "id": 1, "username": "firstuser", "email": "[email protected]" },
 { "id": 2, "username": "newuser", "email": "[email protected]" }]

Now, if we issue the exact same PATCH request as above, what happens? (For the sake of this example, let's assume that the /users resource allows duplicate usernames.) The "op" is "add", so a new user is added to the list, and a subsequent GET /users returns:

[{ "id": 1, "username": "firstuser", "email": "[email protected]" },
 { "id": 2, "username": "newuser", "email": "[email protected]" },
 { "id": 3, "username": "newuser", "email": "[email protected]" }]

The /users resource has changed again, even though we issued the exact same PATCH against the exact same endpoint. If our PATCH is f(x), f(f(x)) is not the same as f(x), and therefore, this particular PATCH is not idempotent.

Although PATCH isn't guaranteed to be idempotent, there's nothing in the PATCH specification to prevent you from making all PATCH operations on your particular server idempotent. RFC 5789 even anticipates advantages from idempotent PATCH requests:

A PATCH request can be issued in such a way as to be idempotent, which also helps prevent bad outcomes from collisions between two PATCH requests on the same resource in a similar time frame.

In Dan's example, his PATCH operation is, in fact, idempotent. In that example, the /users/1 entity changed between our PATCH requests, but not because of our PATCH requests; it was actually the Post Office's different patch document that caused the zip code to change. The Post Office's different PATCH is a different operation; if our PATCH is f(x), the Post Office's PATCH is g(x). Idempotence states that f(f(f(x))) = f(x), but makes no guarantes about f(g(f(x))).

Bind class toggle to window scroll event

Thanks to Flek for answering my question in his comment:

http://jsfiddle.net/eTTZj/30/

<div ng-app="myApp" scroll id="page" ng-class="{min:boolChangeClass}">

    <header></header>
    <section></section>

</div>

app = angular.module('myApp', []);
app.directive("scroll", function ($window) {
    return function(scope, element, attrs) {
        angular.element($window).bind("scroll", function() {
             if (this.pageYOffset >= 100) {
                 scope.boolChangeClass = true;
             } else {
                 scope.boolChangeClass = false;
             }
            scope.$apply();
        });
    };
});

SUM OVER PARTITION BY

I think the query you want is this:

SELECT BrandId, SUM(ICount),
       SUM(sum(ICount)) over () as TotalCount,
       100.0 * SUM(ICount) / SUM(sum(Icount)) over () as Percentage
FROM Table 
WHERE DateId  = 20130618
group by BrandId;

This does the group by for brand. And it calculates the "Percentage". This version should produce a number between 0 and 100.

How can I check if mysql is installed on ubuntu?

In an RPM-based Linux, you can check presence of MySQL like this:

rpm -qa | grep mysql

For debian or other dpkg-based systems, check like this: *

dpkg -l mysql-server libmysqlclientdev*

*

error::make_unique is not a member of ‘std’

In my case I was needed update the std=c++

I mean in my gradle file was this

android {
    ...

    defaultConfig {
        ...

        externalNativeBuild {
            cmake {
                cppFlags "-std=c++11", "-Wall"
                arguments "-DANDROID_STL=c++_static",
                        "-DARCORE_LIBPATH=${arcore_libpath}/jni",
                        "-DARCORE_INCLUDE=${project.rootDir}/app/src/main/libs"
            }
        }
       ....
    }

I changed this line

android {
    ...

    defaultConfig {
        ...

        externalNativeBuild {
            cmake {
                cppFlags "-std=c++17", "-Wall"   <-- this number from 11 to 17 (or 14)
                arguments "-DANDROID_STL=c++_static",
                        "-DARCORE_LIBPATH=${arcore_libpath}/jni",
                        "-DARCORE_INCLUDE=${project.rootDir}/app/src/main/libs"
            }
        }
       ....
    }

That's it...

How to use sed to extract substring

You should not parse XML using tools like sed, or awk. It's error-prone.

If input changes, and before name parameter you will get new-line character instead of space it will fail some day producing unexpected results.

If you are really sure, that your input will be always formated this way, you can use cut. It's faster than sed and awk:

cut -d'"' -f2 < input.txt

It will be better to first parse it, and extract only parameter name attribute:

xpath -q -e //@name input.txt | cut -d'"' -f2

To learn more about xpath, see this tutorial: http://www.w3schools.com/xpath/

Angular + Material - How to refresh a data source (mat-table)

There are two ways to do it because Angular Material is inconsistent, and this is very poorly documented. Angular material table won't update when a new row will arrive. Surprisingly it is told it is because performance issues. But it looks more like a by design issue, they can not change. It should be expected for the table to update when new row occurs. If this behavior should not be enabled by default there should be a switch to switch it off.

Anyways, we can not change Angular Material. But we can basically use a very poorly documented method to do it:

One - if you use an array directly as a source:

call table.renderRows()

where table is ViewChild of the mat-table

Second - if you use sorting and other features

table.renderRows() surprisingly won't work. Because mat-table is inconsistent here. You need to use a hack to tell the source changed. You do it with this method:

this.dataSource.data = yourDataSource;

where dataSource is MatTableDataSource wrapper used for sorting and other features.

Serializing class instance to JSON

I just do:

data=json.dumps(myobject.__dict__)

This is not the full answer, and if you have some sort of complicated object class you certainly will not get everything. However I use this for some of my simple objects.

One that it works really well on is the "options" class that you get from the OptionParser module. Here it is along with the JSON request itself.

  def executeJson(self, url, options):
        data=json.dumps(options.__dict__)
        if options.verbose:
            print data
        headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
        return requests.post(url, data, headers=headers)

rails generate model

For me what happened was that I generated the app with rails new rails new chapter_2 but the RVM --default had rails 4.0.2 gem, but my chapter_2 project use a new gemset with rails 3.2.16.

So when I ran

rails generate scaffold User name:string email:string

the console showed

Usage:
   rails new APP_PATH [options]

So I fixed the RVM and the gemset with the rails 3.2.16 gem , and then generated the app again then I executed

 rails generate scaffold User name:string email:string

and it worked

Oracle date format picture ends before converting entire input string

you need to alter session

you can try before insert

 sql : alter session set nls_date_format = 'YYYY-MM-DD HH24:MI:SS'

How to remove/delete a large file from commit history in Git repository?

You can do this using the branch filter command:

git filter-branch --tree-filter 'rm -rf path/to/your/file' HEAD

How can I compare time in SQL Server?

convert(varchar(5), thedate, 108) between @leftTime and @rightTime

Explanation:

if you have varchar(5) you will obtain HH:mm

if you have varchar(8) you obtain HH:mm ss

108 obtains only the time from the SQL date

@leftTime and @rightTime are two variables to compare

Update UI from Thread in Android

You should do this with the help of AsyncTask (an intelligent backround thread) and ProgressDialog

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called begin, doInBackground, processProgress and end.

The 4 steps

When an asynchronous task is executed, the task goes through 4 steps:

onPreExecute(), invoked on the UI thread immediately after the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.

doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.

onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.

onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter. Threading rules

There are a few threading rules that must be followed for this class to work properly:

The task instance must be created on the UI thread. execute(Params...) must be invoked on the UI thread. Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually. The task can be executed only once (an exception will be thrown if a second execution is attempted.)

Example code
What the adapter does in this example is not important, more important to understand that you need to use AsyncTask to display a dialog for the progress.

private class PrepareAdapter1 extends AsyncTask<Void,Void,ContactsListCursorAdapter > {
    ProgressDialog dialog;
    @Override
    protected void onPreExecute() {
        dialog = new ProgressDialog(viewContacts.this);
        dialog.setMessage(getString(R.string.please_wait_while_loading));
        dialog.setIndeterminate(true);
        dialog.setCancelable(false);
        dialog.show();
    }
    /* (non-Javadoc)
     * @see android.os.AsyncTask#doInBackground(Params[])
     */
    @Override
    protected ContactsListCursorAdapter doInBackground(Void... params) {
        cur1 = objItem.getContacts();
        startManagingCursor(cur1);

        adapter1 = new ContactsListCursorAdapter (viewContacts.this,
                R.layout.contact_for_listitem, cur1, new String[] {}, new int[] {});

        return adapter1;
    }

    protected void onPostExecute(ContactsListCursorAdapter result) {
        list.setAdapter(result);
        dialog.dismiss();
    }
}

"Connection for controluser as defined in your configuration failed" with phpMyAdmin in XAMPP

If you got here and you are using Debian/Ubuntu (or any other dpkg based distro), execute the following command:

sudo dpkg-reconfigure phpmyadmin

The phpmyadmin package contains the script to perform this operation for you, all it needs is a user with permissions. sudo is not required if you're logged in as root, of course.

EDIT: It might be worth trying to drop the current phpmyadmin user.

HTML: How to create a DIV with only vertical scroll-bars for long paragraphs?

For any case set overflow-x to hidden and I prefer to set max-height in order to limit the expansion of the height of the div. Your code should looks like this:

overflow-y: scroll;
overflow-x: hidden;
max-height: 450px;

Install Node.js on Ubuntu

Follow the instructions given here at NodeSource which is dedicated to creating a sustainable ecosystem for Node.js.

For Node.js >= 4.X

# Using Ubuntu
curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash -
sudo apt-get install -y nodejs

# Using Debian, as root
curl -sL https://deb.nodesource.com/setup_4.x | bash -
apt-get install -y nodejs

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;

Search all of Git history for a string?

Try the following commands to search the string inside all previous tracked files:

git log --patch  | less +/searching_string

or

git rev-list --all | GIT_PAGER=cat xargs git grep 'search_string'

which needs to be run from the parent directory where you'd like to do the searching.

Why is HttpClient BaseAddress not working?

It turns out that, out of the four possible permutations of including or excluding trailing or leading forward slashes on the BaseAddress and the relative URI passed to the GetAsync method -- or whichever other method of HttpClient -- only one permutation works. You must place a slash at the end of the BaseAddress, and you must not place a slash at the beginning of your relative URI, as in the following example.

using (var handler = new HttpClientHandler())
using (var client = new HttpClient(handler))
{
    client.BaseAddress = new Uri("http://something.com/api/");
    var response = await client.GetAsync("resource/7");
}

Even though I answered my own question, I figured I'd contribute the solution here since, again, this unfriendly behavior is undocumented. My colleague and I spent most of the day trying to fix a problem that was ultimately caused by this oddity of HttpClient.

How do I configure Maven for offline development?

Before going offline you have to make sure that everything is in your local repo, which is required while working offline. Running "mvn dependency:go-offline" for the project(s)/pom(s), you intend to work on, will reduce the efforts to achieve this.

But it´s usually not the whole story, because dependency:go-offline will only download the "bare build" plugins (go-offline / resolve-plugins does not resolve all plugin dependencies). So you have to find a way to download deploy / test / site plugins (and maybe others) and their dependencies into your repo.

Furthermore dependency:go-offline does not download the pom´s artifact itself, so you have to dependency:copy it if required.

Sometimes - as MaDa wrote - you do not know, what you will need, while being offline, which makes it pretty impossible to have a "sufficient" repo.

Anyway having a properly filled repo you only have to add "<offline>true</offline>" to Maven´s settings.xml to go offline.

Do not change the Maven profile (id) you used to fill your repo, while being offline. Maven recognizes the downloaded artifacts in its metadata with an "identity", which is bound to the profile id.

Javascript string/integer comparisons

Parse the string into an integer using parseInt:

javascript:alert(parseInt("2", 10)>parseInt("10", 10))

What's the syntax for mod in java

In Java it is the % operator: 15.17.3. Remainder Operator %

Note that there is also floorMod in the java.lang.Math class which will give a different result from % for arguments with different signs:

public static int floorMod?(int x, int y)

How to center a View inside of an Android Layout?

Step #1: Wrap whatever it is you want centered on the screen in a full-screen RelativeLayout.

Step #2: Give that child view (the one, which you want centered inside the RelativeLayout) the android:layout_centerInParent="true" attribute.

Does Java support structs?

Java 14 has added support for Records, which are structured data types that are very easy to build.

You can declare a Java record like this:

public record AuditInfo(
    LocalDateTime createdOn,
    String createdBy,
    LocalDateTime updatedOn,
    String updatedBy
) {}
 
public record PostInfo(
    Long id,
    String title,
    AuditInfo auditInfo
) {}

And, the Java compiler will generate the following Java class associated to the AuditInfo Record:

public final class PostInfo
        extends java.lang.Record {
    private final java.lang.Long id;
    private final java.lang.String title;
    private final AuditInfo auditInfo;
 
    public PostInfo(
            java.lang.Long id,
            java.lang.String title,
            AuditInfo auditInfo) {
        /* compiled code */
    }
 
    public java.lang.String toString() { /* compiled code */ }
 
    public final int hashCode() { /* compiled code */ }
 
    public final boolean equals(java.lang.Object o) { /* compiled code */ }
 
    public java.lang.Long id() { /* compiled code */ }
 
    public java.lang.String title() { /* compiled code */ }
 
    public AuditInfo auditInfo() { /* compiled code */ }
}
 
public final class AuditInfo
        extends java.lang.Record {
    private final java.time.LocalDateTime createdOn;
    private final java.lang.String createdBy;
    private final java.time.LocalDateTime updatedOn;
    private final java.lang.String updatedBy;
 
    public AuditInfo(
            java.time.LocalDateTime createdOn,
            java.lang.String createdBy,
            java.time.LocalDateTime updatedOn,
            java.lang.String updatedBy) {
        /* compiled code */
    }
 
    public java.lang.String toString() { /* compiled code */ }
 
    public final int hashCode() { /* compiled code */ }
 
    public final boolean equals(java.lang.Object o) { /* compiled code */ }
 
    public java.time.LocalDateTime createdOn() { /* compiled code */ }
 
    public java.lang.String createdBy() { /* compiled code */ }
 
    public java.time.LocalDateTime updatedOn() { /* compiled code */ }
 
    public java.lang.String updatedBy() { /* compiled code */ }
}

Notice that the constructor, accessor methods, as well as equals, hashCode, and toString are created for you, so it's very convenient to use Java Records.

A Java Record can be created like any other Java object:

PostInfo postInfo = new PostInfo(
    1L,
    "High-Performance Java Persistence",
    new AuditInfo(
        LocalDateTime.of(2016, 11, 2, 12, 0, 0),
        "Vlad Mihalcea",
        LocalDateTime.now(),
        "Vlad Mihalcea"
    )
);

How can I create C header files

  1. Open your favorite text editor
  2. Create a new file named whatever.h
  3. Put your function prototypes in it

DONE.

Example whatever.h

#ifndef WHATEVER_H_INCLUDED
#define WHATEVER_H_INCLUDED
int f(int a);
#endif

Note: include guards (preprocessor commands) added thanks to luke. They avoid including the same header file twice in the same compilation. Another possibility (also mentioned on the comments) is to add #pragma once but it is not guaranteed to be supported on every compiler.

Example whatever.c

#include "whatever.h"

int f(int a) { return a + 1; }

And then you can include "whatever.h" into any other .c file, and link it with whatever.c's object file.

Like this:

sample.c

#include "whatever.h"

int main(int argc, char **argv)
{
    printf("%d\n", f(2)); /* prints 3 */
    return 0;
}

To compile it (if you use GCC):

$ gcc -c whatever.c -o whatever.o
$ gcc -c sample.c -o sample.o

To link the files to create an executable file:

$ gcc sample.o whatever.o -o sample

You can test sample:

$ ./sample
3
$

Android webview & localStorage

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

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

php: catch exception and continue execution, is it possible?

Another angle on this is returning an Exception, NOT throwing one, from the processing code.

I needed to do this with a templating framework I'm writing. If the user attempts to access a property that doesn't exist on the data, I return the error from deep within the processing function, rather than throwing it.

Then, in the calling code, I can decide whether to throw this returned error, causing the try() to catch(), or just continue:

// process the template
    try
    {
        // this function will pass back a value, or a TemplateExecption if invalid
            $result = $this->process($value);

        // if the result is an error, choose what to do with it
            if($result instanceof TemplateExecption)
            {
                if(DEBUGGING == TRUE)
                {
                    throw($result); // throw the original error
                }
                else
                {
                    $result = NULL; // ignore the error
                }
            }
    }

// catch TemplateExceptions
    catch(TemplateException $e)
    {
        // handle template exceptions
    }

// catch normal PHP Exceptions
    catch(Exception $e)
    {
        // handle normal exceptions
    }

// if we get here, $result was valid, or ignored
    return $result;

The result of this is I still get the context of the original error, even though it was thrown at the top.

Another option might be to return a custom NullObject or a UnknownProperty object and compare against that before deciding to trip the catch(), but as you can re-throw errors anyway, and if you're fully in control of the overall structure, I think this is a neat way round the issue of not being able to continue try/catches.

Vertically align text within a div

Update April 10, 2016

Flexboxes should now be used to vertically (or even horizontally) align items.

_x000D_
_x000D_
body {
    height: 150px;
    border: 5px solid cyan; 
    font-size: 50px;
    
    display: flex;
    align-items: center; /* Vertical center alignment */
    justify-content: center; /* Horizontal center alignment */
}
_x000D_
Middle
_x000D_
_x000D_
_x000D_

A good guide to flexbox can be read on CSS Tricks. Thanks Ben (from comments) for pointing it out. I didn't have time to update.


A good guy named Mahendra posted a very working solution here.

The following class should make the element horizontally and vertically centered to its parent.

.absolute-center {

    /* Internet Explorer 10 */
    display: -ms-flexbox;
    -ms-flex-pack: center;
    -ms-flex-align: center;

    /* Firefox */
    display: -moz-box;
    -moz-box-pack: center;
    -moz-box-align: center;

    /* Safari, Opera, and Chrome */
    display: -webkit-box;
    -webkit-box-pack: center;
    -webkit-box-align: center;

    /* W3C */
    display: box;
    box-pack: center;
    box-align: center;
}

How does collections.defaultdict work?

Since the question is about "how it works", some readers may want to see more nuts and bolts. Specifically, the method in question is the __missing__(key) method. See: https://docs.python.org/2/library/collections.html#defaultdict-objects .

More concretely, this answer shows how to make use of __missing__(key) in a practical way: https://stackoverflow.com/a/17956989/1593924

To clarify what 'callable' means, here's an interactive session (from 2.7.6 but should work in v3 too):

>>> x = int
>>> x
<type 'int'>
>>> y = int(5)
>>> y
5
>>> z = x(5)
>>> z
5

>>> from collections import defaultdict
>>> dd = defaultdict(int)
>>> dd
defaultdict(<type 'int'>, {})
>>> dd = defaultdict(x)
>>> dd
defaultdict(<type 'int'>, {})
>>> dd['a']
0
>>> dd
defaultdict(<type 'int'>, {'a': 0})

That was the most typical use of defaultdict (except for the pointless use of the x variable). You can do the same thing with 0 as the explicit default value, but not with a simple value:

>>> dd2 = defaultdict(0)

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    dd2 = defaultdict(0)
TypeError: first argument must be callable

Instead, the following works because it passes in a simple function (it creates on the fly a nameless function which takes no arguments and always returns 0):

>>> dd2 = defaultdict(lambda: 0)
>>> dd2
defaultdict(<function <lambda> at 0x02C4C130>, {})
>>> dd2['a']
0
>>> dd2
defaultdict(<function <lambda> at 0x02C4C130>, {'a': 0})
>>> 

And with a different default value:

>>> dd3 = defaultdict(lambda: 1)
>>> dd3
defaultdict(<function <lambda> at 0x02C4C170>, {})
>>> dd3['a']
1
>>> dd3
defaultdict(<function <lambda> at 0x02C4C170>, {'a': 1})
>>> 

How to watch and reload ts-node when TypeScript files change

Specifically for this issue I've created the tsc-watch library. you can find it on npm.

Obvious use case would be:

tsc-watch server.ts --outDir ./dist --onSuccess "node ./dist/server.js"

How many times does each value appear in a column?

The quickest way would be with a pivot table. Make sure your column of data has a header row, highlight the data and the header, from the insert ribbon select pivot table and then drag your header from the pivot table fields list to the row labels and to the values boxes.

Cannot use string offset as an array in php

I believe what are you asking about is a variable interpolation in PHP.

Let's do a simple fixture:

$obj = (object) array('foo' => array('bar'), 'property' => 'value');
$var = 'foo';

Now we have an object, where:

print_r($obj);

Will give output:

stdClass Object
    (
        [foo] => Array
            (
                [0] => bar
            )

        [property] => value
    )

And we have variable $var containing string "foo".

If you'll try to use:

$give_me_foo = $obj->$var[0];

Instead of:

$give_me_foo = $obj->foo[0];

You get "Cannot use string offset as an array [...]" error message as a result, because what you are trying to do, is in fact sending message $var[0] to object $obj. And - as you can see from fixture - there is no content of $var[0] defined. Variable $var is a string and not an array.

What you can do in this case is to use curly braces, which will assure that at first is called content of $var, and subsequently the rest of message-sent:

$give_me_foo = $obj->{$var}[0];

The result is "bar", as you would expect.

Java - removing first character of a string

My version of removing leading chars, one or multiple. For example, String str1 = "01234", when removing leading '0', result will be "1234". For a String str2 = "000123" result will be again "123". And for String str3 = "000" result will be empty string: "". Such functionality is often useful when converting numeric strings into numbers.The advantage of this solution compared with regex (replaceAll(...)) is that this one is much faster. This is important when processing large number of Strings.

 public static String removeLeadingChar(String str, char ch) {
    int idx = 0;
    while ((idx < str.length()) && (str.charAt(idx) == ch))
        idx++;
    return str.substring(idx);
}

Error Code: 2013. Lost connection to MySQL server during query

I faced this same issue. I believe it happens when you have foreign keys to larger tables (which takes time).

I tried to run the create table statement again without the foreign key declarations and found it worked.

Then after creating the table, I added the foreign key constrains using ALTER TABLE query.

Hope this will help someone.

How can I check if a checkbox is checked?

remember is undefined … and the checked property is a boolean not a number.

function validate(){
    var remember = document.getElementById('remember');
    if (remember.checked){
        alert("checked") ;
    }else{
        alert("You didn't check it! Let me check it for you.")
    }
}

Display Parameter(Multi-value) in Report

You can use the "Join" function to create a single string out of the array of labels, like this:

=Join(Parameters!Product.Label, ",")

How to recursively find and list the latest modified files in a directory with subdirectories and times

GNU find (see man find) has a -printf parameter for displaying the files in Epoch mtime and relative path name.

redhat> find . -type f -printf '%T@ %P\n' | sort -n | awk '{print $2}'

What is the difference between absolute and relative xpaths? Which is preferred in Selenium automation testing?

Consider Below Html

<html>
  <body>
    <input type ="text" id="username">
  </body>

</html>

so Absoulte path= html/body/input and Relative path = //*[@id="username"]

Disadvantage with Absolute xpath is maintenance is high if there is nay change made in html it may disturb the entire path and also sometime we need to write long absolute xpaths so relative xpaths are preferred

Xcode stops working after set "xcode-select -switch"

You should be pointing it towards the Developer directory, not the Xcode application bundle. Run this:

sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer

With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.

No line-break after a hyphen

You could also wrap the relevant text with

<span style="white-space: nowrap;"></span>

Getting "file not found" in Bridging Header when importing Objective-C frameworks into Swift project

I have the same issue. I changed all my imports from #import "HMSegmentedControl.h" to #import <HMSegmentedControl/HMSegmentedControl.h> for example.

Method Call Chaining; returning a pointer vs a reference?

It's canonical to use references for this; precedence: ostream::operator<<. Pointers and references here are, for all ordinary purposes, the same speed/size/safety.

Warning: Cannot modify header information - headers already sent by ERROR

You are trying to send headers information after outputing content.

If you want to do this, look for output buffering.

Therefore, look to use ob_start();

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

This answer might be useful:

Regex (grep) for multi-line search needed

To find recursively you can use flags -R (recursive) and --include (GLOB pattern). See:

Use grep --exclude/--include syntax to not grep through certain files

C++ alignment when printing cout <<

Another way to make column aligned is as follows:

using namespace std;

cout.width(20); cout << left << "Artist";
cout.width(20); cout << left << "Title";
cout.width(10); cout << left << "Price";
...
cout.width(20); cout << left << artist;
cout.width(20); cout << left << title;
cout.width(10); cout << left << price;

We should estimate maximum length of values for each column. In this case, values of "Artist" column should not exceed 20 characters and so on.

How can I switch language in google play?

Answer below the dotted line below is the original that's now outdated.

Here is the latest information ( Thank you @deadfish ):

add &hl=<language> like &hl=pl or &hl=en

example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl

All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en

......................................................................

To change the actual local market:

Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html

To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720

How to filter a dictionary according to an arbitrary condition function?

dict((k, v) for (k, v) in points.iteritems() if v[0] < 5 and v[1] < 5)

Android load from URL to Bitmap

If you are using Picasso for Images you can try method below!

public static Bitmap getImageBitmapFromURL(Context context, String imageUrl){
    Bitmap imageBitmap = null;
    try {
      imageBitmap = new AsyncTask<Void, Void, Bitmap>() {
        @Override
        protected Bitmap doInBackground(Void... params) {
          try {
            int targetHeight = 200;
            int targetWidth = 200;

            return Picasso.with(context).load(String.valueOf(imageUrl))
              //.resize(targetWidth, targetHeight)
              .placeholder(R.drawable.raw_image)
              .error(R.drawable.raw_error_image)
              .get();
          } catch (IOException e) {
            e.printStackTrace();
          }
          return null;
        }
      }.execute().get();
    } catch (InterruptedException e) {
      e.printStackTrace();
    } 
  return imageBitmap;
  }

What does the Excel range.Rows property really do?

Your two examples are the only things I have ever used the Rows and Columns properties for, but in theory you could do anything with them that can be done with a Range object.

The return type of those properties is itself a Range, so you can do things like:

Dim myRange as Range
Set myRange = Sheet1.Range(Cells(2,2),Cells(8,8))
myRange.Rows(3).Select

Which will select the third row in myRange (Cells B4:H4 in Sheet1).

update: To do what you want to do, you could use:

Dim interestingRows as Range
Set interestingRows = Sheet1.Range(startRow & ":" & endRow)

update #2: Or, to get a subset of rows from within a another range:

Dim someRange As Range
Dim interestingRows As Range

Set myRange = Sheet1.Range(Cells(2, 2), Cells(8, 8))

startRow = 3
endRow = 6

Set interestingRows = Range(myRange.Rows(startRow), myRange.Rows(endRow))

Using setImageDrawable dynamically to set image in an ImageView

All the answers posted do not apply today. For example, getDrawable() is deprecated. Here is an updated answer, cheers!

ContextCompat.getDrawable(mContext, drawable)

From documented method

public static final android.graphics.drawable.Drawable getDrawable(@NotNull android.content.Context context,
@android.support.annotation.DrawableRes int id

is it possible to add colors to python output?

If your console (like your standard ubuntu console) understands ANSI color codes, you can use those.

Here an example:

print ('This is \x1b[31mred\x1b[0m.') 

Multiprocessing vs Threading Python

The threading module uses threads, the multiprocessing module uses processes. The difference is that threads run in the same memory space, while processes have separate memory. This makes it a bit harder to share objects between processes with multiprocessing. Since threads use the same memory, precautions have to be taken or two threads will write to the same memory at the same time. This is what the global interpreter lock is for.

Spawning processes is a bit slower than spawning threads.

push object into array

Add an object to an array

class App extends React.Component {
  state = {
  value: ""
  };

items = [
  {
    id: 0,
    title: "first item"
  },
  {
    id: 1,
    title: "second item"
  },
  {
    id: 2,
    title: "third item"
  }
];

handleChange = e => {
  this.setState({
    value: e.target.value
  });
};

handleAddItem = () => {
  if (this.state.value === "") return;
  const item = new Object();
  item.id = this.items.length;
  item.title = this.state.value;
  this.items.push(item);
  this.setState({
    value: ""
  });

  console.log(this.items);
};

render() {
  const items = this.items.map(item => <p>{item.title}</p>);
  return (
    <>
      <label>
        <input
          value={this.state.value}
          type="text"
          onChange={this.handleChange}
        />
        <button onClick={this.handleAddItem}>Add item</button>
      </label>
      <h1>{items}</h1>
    </>
  );
}
}

ReactDOM.render(<App />, document.getElementById("root"));

Pass a reference to DOM object with ng-click

The angular way is shown in the angular docs :)

https://docs.angularjs.org/api/ng/directive/ngReadonly

Here is the example they use:

<body>
    Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
    <input type="text" ng-readonly="checked" value="I'm Angular"/>
</body>

Basically the angular way is to create a model object that will hold whether or not the input should be readonly and then set that model object accordingly. The beauty of angular is that most of the time you don't need to do any dom manipulation. You just have angular render the view they way your model is set (let angular do the dom manipulation for you and keep your code clean).

So basically in your case you would want to do something like below or check out this working example.

<button ng-click="isInput1ReadOnly = !isInput1ReadOnly">Click Me</button>
<input type="text" ng-readonly="isInput1ReadOnly" value="Angular Rules!"/>

How to solve PHP error 'Notice: Array to string conversion in...'

When you have many HTML inputs named C[] what you get in the POST array on the other end is an array of these values in $_POST['C']. So when you echo that, you are trying to print an array, so all it does is print Array and a notice.

To print properly an array, you either loop through it and echo each element, or you can use print_r.

Alternatively, if you don't know if it's an array or a string or whatever, you can use var_dump($var) which will tell you what type it is and what it's content is. Use that for debugging purposes only.

Transparent image - background color

If I understand you right, you can do this:

<img src="image.png" style="background-color:red;" />

In fact, you can even apply a whole background-image to the image, resulting in two "layers" without the need for multi-background support in the browser ;)

Difference between HttpModule and HttpClientModule

Don't want to be repetitive, but just to summarize in other way (features added in new HttpClient):

  • Automatic conversion from JSON to an object
  • Response type definition
  • Event firing
  • Simplified syntax for headers
  • Interceptors

I wrote an article, where I covered the difference between old "http" and new "HttpClient". The goal was to explain it in the easiest way possible.

Simply about new HttpClient in Angular

Xcode Product -> Archive disabled

Select active scheme to Generic iOs Device.

select to Generic iOs Device

Counting unique / distinct values by group in a data frame

In dplyr you may use n_distinct to "count the number of unique values":

library(dplyr)
myvec %>%
  group_by(name) %>%
  summarise(n_distinct(order_no))

Java - Change int to ascii

You can convert a number to ASCII in java. example converting a number 1 (base is 10) to ASCII.

char k = Character.forDigit(1, 10);
System.out.println("Character: " + k);
System.out.println("Character: " + ((int) k));

Output:

Character: 1
Character: 49

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

If you want to select multiple files from the file selector dialog that displays when you select browse then you are mostly out of luck. You will need to use a Java applet or something similar (I think there is one that use a small flash file, I will update if I find it). Currently a single file input only allows the selection of a single file.

If you are talking about using multiple file inputs then there shouldn't be much difference from using one. Post some code and I will try to help further.


Update: There is one method to use a single 'browse' button that uses flash. I have never personally used this but I have read a fair amount about it. I think its your best shot.

http://swfupload.org/

Checking for multiple conditions using "when" on single task in ansible

Adding to https://stackoverflow.com/users/1638814/nvartolomei answer, which will probably fix your error.

Strictly answering your question, I just want to point out that the when: statement is probably correct, but would look easier to read in multiline and still fulfill your logic:

when: 
  - sshkey_result.rc == 1
  - github_username is undefined or 
    github_username |lower == 'none'

https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html#the-when-statement

How to remove commits from a pull request

This is what helped me:

  1. Create a new branch with the existing one. Let's call the existing one branch_old and new as branch_new.

  2. Reset branch_new to a stable state, when you did not have any problem commit at all. For example, to put it at your local master's level do the following:

    git reset —hard master git push —force origin

  3. cherry-pick the commits from branch_old into branch_new

  4. git push

How can I pass a class member function as a callback?

This question and answer from the C++ FAQ Lite covers your question and the considerations involved in the answer quite nicely I think. Short snippet from the web page I linked:

Don’t.

Because a member function is meaningless without an object to invoke it on, you can’t do this directly (if The X Window System was rewritten in C++, it would probably pass references to objects around, not just pointers to functions; naturally the objects would embody the required function and probably a whole lot more).

html/css buttons that scroll down to different div sections on a webpage

try this:

<input type="button" onClick="document.getElementById('middle').scrollIntoView();" />

Add Auto-Increment ID to existing table?

If you run the following command :

ALTER TABLE users ADD id int NOT NULL AUTO_INCREMENT PRIMARY KEY;

This will show you the error :

ERROR 1060 (42S21): Duplicate column name 'id'

This is because this command will try to add the new column named id to the existing table.

To modify the existing column you have to use the following command :

ALTER TABLE users MODIFY id int NOT NULL AUTO_INCREMENT PRIMARY KEY;

This should work for changing the existing column constraint....!

How to stop creating .DS_Store on Mac?

Please install http://asepsis.binaryage.com/ and then reboot your mac.

ASEPSIS redirect all .DS_Store on your mac to /usr/local/.dscage

After that, You could delete recursively all .DS_Store from your mac.

find ~ -name ".DS_Store" -delete
or
find <your path> -name ".DS_Store" -delete

You should repeat procedure after each Mac major update.

How to write data with FileOutputStream without losing old data?

Use the constructor for appending material to the file:

FileOutputStream(File file, boolean append)
Creates a file output stream to write to the file represented by the specified File object.

So to append to a file say "abc.txt" use

FileOutputStream fos=new FileOutputStream(new File("abc.txt"),true);

How to use the 'main' parameter in package.json?

As far as I know, it's the main entry point to your node package (library) for npm. It's needed if your npm project becomes a node package (library) which can be installed via npm by others.


Let's say you have a library with a build/, dist/, or lib/ folder. In this folder, you got the following compiled file for your library:

-lib/
--bundle.js

Then in your package.json, you tell npm how to access the library (node package):

{
  "name": "my-library-name",
  "main": "lib/bundle.js",
  ...
}

After installing the node package with npm to your JS project, you can import functionalities from your bundled bundle.js file:

import { add, subtract } from 'my-library-name';

This holds also true when using Code Splitting (e.g. Webpack) for your library. For instance, this webpack.config.js makes use of code splitting the project into multiple bundles instead of one.

module.exports = {
  entry: {
    main: './src/index.js',
    add: './src/add.js',
    subtract: './src/subtract.js',
  },
  output: {
    path: `${__dirname}/lib`,
    filename: '[name].js',
    library: 'my-library-name',
    libraryTarget: 'umd',
  },
  ...
}

Still, you would define one main entry point to your library in your package.json:

{
  "name": "my-library-name",
  "main": "lib/main.js",
  ...
}

Then when using the library, you can import your files from your main entry point:

import { add, subtract } from 'my-library-name';

However, you can also bypass the main entry point from the package.json and import the code splitted bundles:

import add from 'my-library-name/lib/add';
import subtract from 'my-library-name/lib/subtract';

After all, the main property in your package.json only points to your main entry point file of your library.

How does the communication between a browser and a web server take place?

Your browser first resolves the servername via DNS to an IP. Then it opens a TCP connection to the webserver and tries to communicate via HTTP. Usually that is on TCP-port 80 but you can specify a different one (http://server:portnumber).

HTTP looks like this:

Once it is connected, it sends the request, which looks like:

GET /site HTTP/1.0
Header1: bla
Header2: blub
{emptyline}

E.g., a header might be Authorization or Range. See here for more.

Then the server responds like this:

200 OK
Header3: foo
Header4: bar

content following here...

E.g., a header might be Date or Content-Type. See here for more.

Look at Wikipedia for HTTP for some more information about this protocol.

How can I see an the output of my C programs using Dev-C++?

Add a line getchar(); or system("pause"); before your return 0; in main function. It will work for you.

'sprintf': double precision in C

You need to write it like sprintf(aa, "%9.7lf", a)

Check out http://en.wikipedia.org/wiki/Printf for some more details on format codes.

How to construct a std::string from a std::vector<char>?

Just for completeness, another way is std::string(&v[0]) (although you need to ensure your string is null-terminated and std::string(v.data()) is generally to be preferred.

The difference is that you can use the former technique to pass the vector to functions that want to modify the buffer, which you cannot do with .data().

Convert DOS line endings to Linux line endings in Vim

:%s/\r\+//g

In Vim, that strips all carriage returns, and leaves only newlines.

Converting a number with comma as decimal point to float

Using str_replace() to remove the dots is not overkill.

$string_number = '1.512.523,55';
// NOTE: You don't really have to use floatval() here, it's just to prove that it's a legitimate float value.
$number = floatval(str_replace(',', '.', str_replace('.', '', $string_number)));

// At this point, $number is a "natural" float.
print $number;

This is almost certainly the least CPU-intensive way you can do this, and odds are that even if you use some fancy function to do it, that this is what it does under the hood.

How to use Boost in Visual Studio 2010

Also a little note: If you want to reduce the compilation-time, you can add the flag

-j2

to run two parallel builds at the same time. This might reduce it to viewing one movie ;)

Differences between socket.io and websockets

Im going to provide an argument against using socket.io.

I think using socket.io solely because it has fallbacks isnt a good idea. Let IE8 RIP.

In the past there have been many cases where new versions of NodeJS has broken socket.io. You can check these lists for examples... https://github.com/socketio/socket.io/issues?q=install+error

If you go to develop an Android app or something that needs to work with your existing app, you would probably be okay working with WS right away, socket.io might give you some trouble there...

Plus the WS module for Node.JS is amazingly simple to use.

Android Studio : Failure [INSTALL_FAILED_OLDER_SDK]

<uses-sdk android:minSdkVersion="19"/>

In AndroidManifest.xml worked for me on Android Studio(Beta)0.8.2.

Maintaining the final state at end of a CSS3 animation

Try adding animation-fill-mode: forwards;. For example like this:

-webkit-animation: bubble 1.0s forwards; /* for less modern browsers */
        animation: bubble 1.0s forwards;

What is the actual use of Class.forName("oracle.jdbc.driver.OracleDriver") while connecting to a database?

It registers the driver; something of the form:

public class SomeDriver implements Driver {
  static {
    try {
      DriverManager.registerDriver(new SomeDriver());
    } catch (SQLException e) {
      // TODO Auto-generated catch block
    }
  }

  //etc: implemented methods
}

How to POST a FORM from HTML to ASPX page

This is very possible. I mocked up 3 pages which should give you a proof of concept:

.aspx page:

<form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:TextBox TextMode="password" ID="TextBox2" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </div>
</form>

code behind:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    For Each s As String In Request.Form.AllKeys
        Response.Write(s & ": " & Request.Form(s) & "<br />")
    Next
End Sub

Separate HTML page:

<form action="http://localhost/MyTestApp/Default.aspx" method="post">
    <input name="TextBox1" type="text" value="" id="TextBox1" />
    <input name="TextBox2" type="password" id="TextBox2" />
    <input type="submit" name="Button1" value="Button" id="Button1" />
</form>

...and it regurgitates the form values as expected. If this isn't working, as others suggested, use a traffic analysis tool (fiddler, ethereal), because something probably isn't going where you're expecting.

Better way to find control in ASP.NET

If you're looking for a specific type of control you could use a recursive loop like this one - http://weblogs.asp.net/eporter/archive/2007/02/24/asp-net-findcontrol-recursive-with-generics.aspx

Here's an example I made that returns all controls of the given type

/// <summary>
/// Finds all controls of type T stores them in FoundControls
/// </summary>
/// <typeparam name="T"></typeparam>
private class ControlFinder<T> where T : Control 
{
    private readonly List<T> _foundControls = new List<T>();
    public IEnumerable<T> FoundControls
    {
        get { return _foundControls; }
    }    

    public void FindChildControlsRecursive(Control control)
    {
        foreach (Control childControl in control.Controls)
        {
            if (childControl.GetType() == typeof(T))
            {
                _foundControls.Add((T)childControl);
            }
            else
            {
                FindChildControlsRecursive(childControl);
            }
        }
    }
}

How to run a cron job on every Monday, Wednesday and Friday?

Here's my example crontab I always use as a template:

    # Use the hash sign to prefix a comment
    # +---------------- minute (0 - 59)
    # |  +------------- hour (0 - 23)
    # |  |  +---------- day of month (1 - 31)
    # |  |  |  +------- month (1 - 12)
    # |  |  |  |  +---- day of week (0 - 7) (Sunday=0 or 7)
    # |  |  |  |  |
    # *  *  *  *  *  command to be executed
    #--------------------------------------------------------------------------

To run my cron job every Monday, Wednesady and Friday at 7:00PM, the result will be:

      0 19 * * 1,3,5 nohup /home/lathonez/script.sh > /tmp/script.log 2>&1

source

Numpy isnan() fails on an array of floats (from pandas dataframe apply)

Make sure you import csv file using Pandas

import pandas as pd

condition = pd.isnull(data[i][j])

returning a Void object

It is possible to create instances of Void if you change the security manager, so something like this:

static Void getVoid() throws SecurityException, InstantiationException,
        IllegalAccessException, InvocationTargetException {
    class BadSecurityManager extends SecurityManager {
    
        @Override
        public void checkPermission(Permission perm) { }
    
        @Override
        public void checkPackageAccess(String pkg) { }

    }
    System.setSecurityManager(badManager = new BadSecurityManager());
    Constructor<?> constructor = Void.class.getDeclaredConstructors()[0];
    if(!constructor.isAccessible()) {
        constructor.setAccessible(true);
    }
    return (Void) constructor.newInstance();
}

Obviously this is not all that practical or safe; however, it will return an instance of Void if you are able to change the security manager.