Programs & Examples On #Boost mpi

one of the Boost libraries, a C++-style wrapper around the Message Passing Interface (MPI) library for high-performance distributed computing.

How to bind Close command to a button

Actually, it is possible without C# code. The key is to use interactions:

<Button Content="Close">
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="Click">
      <ei:CallMethodAction TargetObject="{Binding ElementName=window}" MethodName="Close"/>
    </i:EventTrigger>
  </i:Interaction.Triggers>
</Button>

In order for this to work, just set the x:Name of your window to "window", and add these two namespaces:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"

This requires that you add the Expression Blend SDK DLL to your project, specifically Microsoft.Expression.Interactions.

In case you don't have Blend, the SDK can be downloaded here.

How can I calculate the number of lines changed between two commits in Git?

You want the --stat option of git diff, or if you're looking to parse this in a script, the --numstat option.

git diff --stat <commit-ish> <commit-ish>

--stat produces the human-readable output you're used to seeing after merges; --numstat produces a nice table layout that scripts can easily interpret.

I somehow missed that you were looking to do this on multiple commits at the same time - that's a task for git log. Ron DeVera touches on this, but you can actually do a lot more than what he mentions. Since git log internally calls the diff machinery in order to print requested information, you can give it any of the diff stat options - not just --shortstat. What you likely want to use is:

git log --author="Your name" --stat <commit1>..<commit2>

but you can use --numstat or --shortstat as well. git log can also select commits in a variety other ways - have a look at the documentation. You might be interested in things like --since (rather than specifying commit ranges, just select commits since last week) and --no-merges (merge commits don't actually introduce changes), as well as the pretty output options (--pretty=oneline, short, medium, full...).

Here's a one-liner to get total changes instead of per-commit changes from git log (change the commit selection options as desired - this is commits by you, from commit1 to commit2):

git log --numstat --pretty="%H" --author="Your Name" commit1..commit2 | awk 'NF==3 {plus+=$1; minus+=$2} END {printf("+%d, -%d\n", plus, minus)}'

(you have to let git log print some identifying information about the commit; I arbitrarily chose the hash, then used awk to only pick out the lines with three fields, which are the ones with the stat information)

How to rename JSON key

Try this:

let jsonArr = [
    {
        "_id":"5078c3a803ff4197dc81fbfb",
        "email":"[email protected]",
        "image":"some_image_url",
        "name":"Name 1"
    },
    {
        "_id":"5078c3a803ff4197dc81fbfc",
        "email":"[email protected]",
        "image":"some_image_url",
        "name":"Name 2"
    }
]

let idModified = jsonArr.map(
    obj => {
        return {
            "id" : obj._id,
            "email":obj.email,
            "image":obj.image,
            "name":obj.name
        }
    }
);
console.log(idModified);

How to trigger button click in MVC 4

as per @anaximander s answer but your signup action should look more like

    [HttpPost]
    public ActionResult SignUp(Account account)
    {
        if(ModelState.IsValid){
            //do something with account
            return RedirectToAction("Index"); 
        }
        return View("SignUp");
    }

Create <div> and append <div> dynamically

var iDiv = document.createElement('div');

iDiv.id = 'block';
iDiv.className = 'block';
document.getElementsByTagName('body')[0].appendChild(iDiv);

var div2 = document.createElement('div');

div2.className = 'block-2';
iDiv.appendChild(div2);

Insert node at a certain position in a linked list C++

Node* insert_node_at_nth_pos(Node *head, int data, int position)
{   
    /* current node */
    Node* cur = head;

    /* initialize new node to be inserted at given position */
    Node* nth = new Node;
    nth->data = data;
    nth->next = NULL;

    if(position == 0){
        /* insert new node at head */
        head = nth;
        head->next = cur;
        return head;
    }else{
        /* traverse list */
        int count = 0;            
        Node* pre = new Node;

        while(count != position){
            if(count == (position - 1)){
                pre = cur;
            }
            cur = cur->next;            
            count++;
        }

        /* insert new node here */
        pre->next = nth;
        nth->next = cur;

        return head;
    }    
}

Android: How to stretch an image to the screen width while maintaining aspect ratio?

I've been struggling with this problem in one form or another for AGES, thank you, Thank You, THANK YOU.... :)

I just wanted to point out that you can get a generalizable solution from what Bob Lee's done by just extending View and overriding onMeasure. That way you can use this with any drawable you want, and it won't break if there's no image:

    public class CardImageView extends View {
        public CardImageView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }

        public CardImageView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        public CardImageView(Context context) {
            super(context);
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            Drawable bg = getBackground();
            if (bg != null) {
                int width = MeasureSpec.getSize(widthMeasureSpec);
                int height = width * bg.getIntrinsicHeight() / bg.getIntrinsicWidth();
                setMeasuredDimension(width,height);
            }
            else {
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            }
        }
    }

Is it possible to install iOS 6 SDK on Xcode 5?

I was also running the same problem when I updated to xcode 5 it removed older sdk. But I taken the copy of older SDK from another computer and the same you can download from following link.

http://www.4shared.com/zip/NlPgsxz6/iPhoneOS61sdk.html
(www.4shared.com test account [email protected]/test)

There are 2 ways to work with.

1) Unzip and paste this folder to /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs & restart the xcode.

But this might again removed by Xcode if you update xcode.

2) Another way is Unzip and paste where you want and go to /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs and create a symbolic link here, so that the SDK will remain same even if you update the Xcode.

Another change I made, Build Setting > Architectures > standard (not 64) so list all the versions of Deployment Target

No need to download the zip if you only wanted to change the deployment target.

Here are some screenshots. enter image description here enter image description here

How to synchronize a static variable among threads running different instances of a class in Java?

We can also use ReentrantLock to achieve the synchronization for static variables.

public class Test {

    private static int count = 0;
    private static final ReentrantLock reentrantLock = new ReentrantLock(); 
    public void foo() {  
        reentrantLock.lock();
        count = count + 1;
        reentrantLock.unlock();
    }  
}

First Or Create

firstOrCreate() checks for all the arguments to be present before it finds a match.

If you only want to check on a specific field, then use firstOrCreate(['field_name' => 'value']) like

$user = User::firstOrCreate([
    'email' => '[email protected]'
], [
    'firstName' => 'abcd',
    'lastName' => 'efgh',
    'veristyName'=>'xyz',
]);

Then it check only the email

VBA shorthand for x=x+1?

Sadly there are no operation-assignment operators in VBA.

(Addition-assignment += are available in VB.Net)

Pointless workaround;

Sub Inc(ByRef i As Integer)
   i = i + 1  
End Sub
...
Static value As Integer
inc value
inc value

Invoking a jQuery function after .each() has completed

what about

$(parentSelect).nextAll().fadeOut(200, function() { 
    $(this).remove(); 
}).one(function(){
    myfunction();
}); 

java.util.regex - importance of Pattern.compile()?

Pattern.compile() allow to reuse a regex multiple times (it is threadsafe). The performance benefit can be quite significant.

I did a quick benchmark:

    @Test
    public void recompile() {
        var before = Instant.now();
        for (int i = 0; i < 1_000_000; i++) {
            Pattern.compile("ab").matcher("abcde").matches();
        }
        System.out.println("recompile " + Duration.between(before, Instant.now()));
    }

    @Test
    public void compileOnce() {
        var pattern = Pattern.compile("ab");
        var before = Instant.now();
        for (int i = 0; i < 1_000_000; i++) {
            pattern.matcher("abcde").matches();
        }
        System.out.println("compile once " + Duration.between(before, Instant.now()));
    }

compileOnce was between 3x and 4x faster. I guess it highly depends on the regex itself but for a regex that is often used, I go for a static Pattern pattern = Pattern.compile(...)

dispatch_after - GCD in Swift?

To execute a funtion or code after a delay use the next method

DispatchQueue.main.asyncAfter(deadline: .now() + 'secondsOfDelay') {
        your code here...
    }

Example - In this example the funtion getShowMovies will be executed after 1 second

DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
        self.getShowMovies()
    }

Validate phone number with JavaScript

My regex of choice is:

/^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im

Valid formats:

(123) 456-7890
(123)456-7890
123-456-7890
123.456.7890
1234567890
+31636363634
075-63546725

How do you force a makefile to rebuild a target

If you don't need to preserve any of the outputs you already successfully compiled

nmake /A 

rebuilds all

Elegant way to read file into byte[] array in Java

Have a look at the following apache commons function:

org.apache.commons.io.FileUtils.readFileToByteArray(File)

Building and running app via Gradle and Android Studio is slower than via Eclipse

Update After Android Studio 2.3

All answers are great, and I encourage to use those methods with this one to improve build speed.

After release of android 2.2 on September 2016, Android released experimental build cache feature to speed up gradle build performance, which is now official from Android Studio 2.3 Canary. (Official Release note)

It introduces a new build cache feature, which is enable by default, can speed up build times (including full builds, incremental builds, and instant run) by storing and reusing files/directories that were created in previous builds of the same or different Android project.

How to use:

Add following line in your gradle.properties file

android.enableBuildCache = true
# Set to true or false to enable or disable the build cache. If this parameter is not set, the build cache is enable by default.

Clean the cache:

  • There is a new Gradle task called cleanBuildCache for you to more easily clean the build cache. You can use it by typing the following in your terminal:

    ./gradlew cleanBuildCache

  • OR You can clean the cache for Android studio 2.2 by deleting all the files store at location

    C:\Users\<username>\.android\build-cache

Mockito test a void method throws an exception

If you ever wondered how to do it using the new BDD style of Mockito:

willThrow(new Exception()).given(mockedObject).methodReturningVoid(...));

And for future reference one may need to throw exception and then do nothing:

willThrow(new Exception()).willDoNothing().given(mockedObject).methodReturningVoid(...));

What's the best mock framework for Java?

For something a little different, you could use JRuby and Mocha which are combined in JtestR to write tests for your Java code in expressive and succinct Ruby. There are some useful mocking examples with JtestR here. One advantage of this approach is that mocking concrete classes is very straightforward.

Using a BOOL property

Apple recommends for stylistic purposes.If you write this code:

@property (nonatomic,assign) BOOL working;

Then you can not use [object isWorking].
It will show an error. But if you use below code means

@property (assign,getter=isWorking) BOOL working;

So you can use [object isWorking] .

How to handle the `onKeyPress` event in ReactJS?

React is not passing you the kind of events you might think. Rather, it is passing synthetic events.

In a brief test, event.keyCode == 0 is always true. What you want is event.charCode

Spring AMQP + RabbitMQ 3.3.5 ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN

if you use the number as your password, maybe you should try to change your password using string.

I can login using deltaqin:000000 on the website, but had this while running the program. then change the password to deltaiqn. and it works.

How to get image width and height in OpenCV?

Also for openCV in python you can do:

img = cv2.imread('myImage.jpg')
height, width, channels = img.shape 

When does System.gc() do something?

Accroding to Thinking in Java by Bruce Eckel, one use case for explicit System.gc() call is when you want to force finalization, i.e. the call to finalize method.

Impersonate tag in Web.Config

The identity section goes under the system.web section, not under authentication:

<system.web>
  <authentication mode="Windows"/>
  <identity impersonate="true" userName="foo" password="bar"/>
</system.web>

How to show loading spinner in jQuery?

I've used the following with jQuery UI Dialog. (Maybe it works with other ajax callbacks?)

$('<div><img src="/i/loading.gif" id="loading" /></div>').load('/ajax.html').dialog({
    height: 300,
    width: 600,
    title: 'Wait for it...'
});

The contains an animated loading gif until its content is replaced when the ajax call completes.

concatenate two database columns into one resultset column

If you were using SQL 2012 or above you could use the CONCAT function:

SELECT CONCAT(field1, field2, field3) FROM table1

NULL fields won't break your concatenation.

@bummi - Thanks for the comment - edited my answer to correspond to it.

Wait one second in running program

Personally I think Thread.Sleep is a poor implementation. It locks the UI etc. I personally like timer implementations since it waits then fires.

Usage: DelayFactory.DelayAction(500, new Action(() => { this.RunAction(); }));

//Note Forms.Timer and Timer() have similar implementations. 

public static void DelayAction(int millisecond, Action action)
{
    var timer = new DispatcherTimer();
    timer.Tick += delegate

    {
        action.Invoke();
        timer.Stop();
    };

    timer.Interval = TimeSpan.FromMilliseconds(millisecond);
    timer.Start();
}

error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup

Thats a linker problem.

Try to change Properties -> Linker -> System -> SubSystem (in Visual Studio).

from Windows (/SUBSYSTEM:WINDOWS) to Console (/SUBSYSTEM:CONSOLE)

This one helped me

Unit testing with Spring Security

Without answering the question about how to create and inject Authentication objects, Spring Security 4.0 provides some welcome alternatives when it comes to testing. The @WithMockUser annotation enables the developer to specify a mock user (with optional authorities, username, password and roles) in a neat way:

@Test
@WithMockUser(username = "admin", authorities = { "ADMIN", "USER" })
public void getMessageWithMockUserCustomAuthorities() {
    String message = messageService.getMessage();
    ...
}

There is also the option to use @WithUserDetails to emulate a UserDetails returned from the UserDetailsService, e.g.

@Test
@WithUserDetails("customUsername")
public void getMessageWithUserDetailsCustomUsername() {
    String message = messageService.getMessage();
    ...
}

More details can be found in the @WithMockUser and the @WithUserDetails chapters in the Spring Security reference docs (from which the above examples were copied)

Static methods in Python?

Python Static methods can be created in two ways.

  1. Using staticmethod()

    class Arithmetic:
        def add(x, y):
            return x + y
    # create add static method
    Arithmetic.add = staticmethod(Arithmetic.add)
    
    print('Result:', Arithmetic.add(15, 10))
    

Output:

Result: 25

  1. Using @staticmethod

    class Arithmetic:
    
    # create add static method
    @staticmethod
    def add(x, y):
        return x + y
    
    print('Result:', Arithmetic.add(15, 10))
    

Output:

Result: 25

Export and import table dump (.sql) using pgAdmin

  1. In pgAdmin, select the required target schema in object tree (databases->your_db_name->schemas->your_target_schema)
  2. Click on Plugins/PSQL Console (in top-bar)
  3. Write \i /path/to/yourfile.sql
  4. Press enter

How to pass integer from one Activity to another?

It's simple. On the sender side, use Intent.putExtra:

Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("intVariableName", intValue);
startActivity(myIntent);

On the receiver side, use Intent.getIntExtra:

 Intent mIntent = getIntent();
 int intValue = mIntent.getIntExtra("intVariableName", 0);

stale element reference: element is not attached to the page document

Use this code:

public class LinkTest 
{   
    public static void main(String[] args) 
    {
        WebDriver driver = new FirefoxDriver();
        driver.navigate().to("file:///C:/Users/vkiran/Desktop/xyz.html");
        List<WebElement> alllinks =driver.findElements(By.xpath("//*[@id='sliding-navigation']//a"));
        String a[]=new String[alllinks.size()];
        for(int i=0;i<alllinks.size();i++)
        {
            a[i]=alllinks.get(i).getText(); 
            if(a[i].startsWith("B"))
            {
                System.out.println("clicking on this link::"+driver.findElement(By.linkText(a[i])).getText());
                driver.findElement(By.linkText(a[i])).click();  

            }
            else
            {
                System.out.println("does not starts with B so not clicking");
            }
        }
}
}

Counting the number of non-NaN elements in a numpy ndarray in Python

np.count_nonzero(~np.isnan(data))

~ inverts the boolean matrix returned from np.isnan.

np.count_nonzero counts values that is not 0\false. .sum should give the same result. But maybe more clearly to use count_nonzero

Testing speed:

In [23]: data = np.random.random((10000,10000))

In [24]: data[[np.random.random_integers(0,10000, 100)],:][:, [np.random.random_integers(0,99, 100)]] = np.nan

In [25]: %timeit data.size - np.count_nonzero(np.isnan(data))
1 loops, best of 3: 309 ms per loop

In [26]: %timeit np.count_nonzero(~np.isnan(data))
1 loops, best of 3: 345 ms per loop

In [27]: %timeit data.size - np.isnan(data).sum()
1 loops, best of 3: 339 ms per loop

data.size - np.count_nonzero(np.isnan(data)) seems to barely be the fastest here. other data might give different relative speed results.

How to autosize and right-align GridViewColumn data in WPF?

To make each of the columns autosize you can set Width="Auto" on the GridViewColumn.

To right-align the text in the ID column you can create a cell template using a TextBlock and set the TextAlignment. Then set the ListViewItem.HorizontalContentAlignment (using a style with a setter on the ListViewItem) to make the cell template fill the entire GridViewCell.

Maybe there is a simpler solution, but this should work.

Note: the solution requires both HorizontalContentAlignment=Stretch in Window.Resources and TextAlignment=Right in the CellTemplate.

<Window x:Class="WpfApplication6.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.Resources>
    <Style TargetType="ListViewItem">
        <Setter Property="HorizontalContentAlignment" Value="Stretch" />
    </Style>
</Window.Resources>
<Grid>
    <ListView Name="lstCustomers" ItemsSource="{Binding Path=Collection}">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="ID" Width="40">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Id}" TextAlignment="Right" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" Width="Auto" />
                <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" Width="Auto"/>
            </GridView>
        </ListView.View>
    </ListView>
</Grid>
</Window>

Convert Enumeration to a Set/List

You can use Collections.list() to convert an Enumeration to a List in one line:

List<T> list = Collections.list(enumeration);

There's no similar method to get a Set, however you can still do it one line:

Set<T> set = new HashSet<T>(Collections.list(enumeration));

firestore: PERMISSION_DENIED: Missing or insufficient permissions

The above voted answers are dangerous for the health of your database. You can still make your database available just for reading and not for writing:

  service cloud.firestore {
    match /databases/{database}/documents {
     match /{document=**} {
       allow read: if true;
       allow write: if false;
      }
   }
}

Android - How to decode and decompile any APK file?

You can try this website http://www.decompileandroid.com Just upload the .apk file and rest of it will be done by this site.

How do I make a WPF TextBlock show my text on multiple lines?

This gets part way there. There is no ActualFontSize property but there is an ActualHeight and that would relate to the FontSize. Right now this only sizes for the original render. I could not figure out how to register the Converter as resize event. Actually maybe need to register the FontSize as a resize event. Please don't mark me down for an incomplete answer. I could not put code sample in a comment.

    <Window.Resources>
        <local:WidthConverter x:Key="widthConverter"/>
    </Window.Resources>
    <Grid>
        <Grid>
            <StackPanel VerticalAlignment="Center" Orientation="Vertical" >
                <Viewbox Margin="100,0,100,0">
                    <TextBlock x:Name="headerText" Text="Lorem ipsum dolor" Foreground="Black"/>
                </Viewbox>
                <TextBlock Margin="150,0,150,0" FontSize="{Binding ElementName=headerText, Path=ActualHeight, Converter={StaticResource widthConverter}}" x:Name="subHeaderText" Text="Lorem ipsum dolor, Lorem ipsum dolor, lorem isum dolor, Lorem ipsum dolor, Lorem ipsum dolor, lorem isum dolor, " TextWrapping="Wrap" Foreground="Gray" />
            </StackPanel>
        </Grid>
    </Grid>        

Converter

    [ValueConversion(typeof(double), typeof(double))]
    public class WidthConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            double width = (double)value*.7;
            return width; // columnsCount;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    } 

Change/Get check state of CheckBox

Here is a quick implementation with samples:

Checkbox to check all items:

<input id="btnSelectAll" type="checkbox">

Single item (for table row):

<input class="single-item" name="item[]" type="checkbox">

Js code for jQuery:

$(document).on('click', '#btnSelectAll', function(state) {
    if ($('#btnSelectAll').is(':checked')) {
        $('.single-item').prop('checked', true);
        $('.batch-erase').addClass('d-block');
    } else {
        $('.single-item').prop('checked', false);
        $('.batch-erase').removeClass('d-block');
    }
});

Batch delete item:

<div class="batch-erase d-none">
    <a href="/path/to/delete" class="btn btn-danger btn-sm">
        <i class="fe-trash"></i> Delete All
    </a>
</div>

TypeError: 'module' object is not callable

It seems like what you've done is imported the socket module as import socket. Therefore socket is the module. You either need to change that line to self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM), as well as every other use of the socket module, or change the import statement to from socket import socket.

Or you've got an import socket after your from socket import *:

>>> from socket import *
>>> serv = socket(AF_INET,SOCK_STREAM)
>>> import socket
>>> serv = socket(AF_INET,SOCK_STREAM)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'module' object is not callable

Python send POST with header

To make POST request instead of GET request using urllib2, you need to specify empty data, for example:

import urllib2
req = urllib2.Request("http://am.domain.com:8080/openam/json/realms/root/authenticate?authIndexType=Module&authIndexValue=LDAP")
req.add_header('X-OpenAM-Username', 'demo')
req.add_data('')
r = urllib2.urlopen(req)

Session TimeOut in web.xml

<session-config>
    <session-timeout>-1</session-timeout>
</session-config>

You can use "-1" where the session never expires. Since you do not know how much time it will take for the thread to complete.

How do I compare strings in Java?

The == operator checks to see if the two strings are exactly the same object.

The .equals() method will check if the two strings have the same value.

String.replaceAll single backslashes with double backslashes

Yes... by the time the regex compiler sees the pattern you've given it, it sees only a single backslash (since Java's lexer has turned the double backwhack into a single one). You need to replace "\\\\" with "\\\\", believe it or not! Java really needs a good raw string syntax.

If condition inside of map() React

Remove the if keyword. It should just be predicate ? true_result : false_result.

Also ? : is called ternary operator.

How do I run a simple bit of code in a new thread?

The ThreadPool.QueueUserWorkItem is pretty ideal for something simple. The only caveat is accessing a control from the other thread.

System.Threading.ThreadPool.QueueUserWorkItem(delegate {
    DoSomethingThatDoesntInvolveAControl();
}, null);

SQL get the last date time record

Exact syntax will of course depend upon database, but something like:

SELECT * FROM my_table WHERE (filename, Dates) IN (SELECT filename, Max(Dates) FROM my_table GROUP BY filename)

This will give you results exactly what you are asking for and displaying above. Fiddle: http://www.sqlfiddle.com/#!2/3af8a/1/0

How to move up a directory with Terminal in OS X

cd .. will back the directory up by one. If you want to reach a folder in the parent directory, you can do something like cd ../foldername. You can use the ".." trick as many times as you want to back up through multiple parent directories. For example, cd ../../Applications would take you to Macintosh HD/Applications

How do I modify fields inside the new PostgreSQL JSON datatype?

UPDATE test
SET data = data::jsonb - 'a' || '{"a":5}'::jsonb
WHERE data->>'b' = '2'

This seems to be working on PostgreSQL 9.5

adb uninstall failed

You can follow below steps to uninstall the app from the device via command prompt.

  1. execute the command : adb -s [devicename] uninstall -k [packagename]. this command will retain the data and cache in the device but will remove the app from the device.
  2. To remove the data and cache also from the device along with the application execute the command below. adb shell pm uninstall -k [packagename].

if it shows sucess your app is uninstalled successfully'

GROUP BY without aggregate function

If you have some column in SELECT clause , how will it select it if there is several rows ? so yes , every column in SELECT clause should be in GROUP BY clause also , you can use aggregate functions in SELECT ...

you can have column in GROUP BY clause which is not in SELECT clause , but not otherwise

How to construct a relative path in Java from two absolute paths (or URLs)?

I'm assuming you have fromPath (an absolute path for a folder), and toPath (an absolute path for a folder/file), and your're looking for a path that with represent the file/folder in toPath as a relative path from fromPath (your current working directory is fromPath) then something like this should work:

public static String getRelativePath(String fromPath, String toPath) {

  // This weirdness is because a separator of '/' messes with String.split()
  String regexCharacter = File.separator;
  if (File.separatorChar == '\\') {
    regexCharacter = "\\\\";
  }

  String[] fromSplit = fromPath.split(regexCharacter);
  String[] toSplit = toPath.split(regexCharacter);

  // Find the common path
  int common = 0;
  while (fromSplit[common].equals(toSplit[common])) {
    common++;
  }

  StringBuffer result = new StringBuffer(".");

  // Work your way up the FROM path to common ground
  for (int i = common; i < fromSplit.length; i++) {
    result.append(File.separatorChar).append("..");
  }

  // Work your way down the TO path
  for (int i = common; i < toSplit.length; i++) {
    result.append(File.separatorChar).append(toSplit[i]);
  }

  return result.toString();
}

'cout' was not declared in this scope

Put the following code before int main():

using namespace std;

And you will be able to use cout.

For example:

#include<iostream>
using namespace std;
int main(){
    char t = 'f';
    char *t1;
    char **t2;
    cout<<t;        
    return 0;
}

Now take a moment and read up on what cout is and what is going on here: http://www.cplusplus.com/reference/iostream/cout/


Further, while its quick to do and it works, this is not exactly a good advice to simply add using namespace std; at the top of your code. For detailed correct approach, please read the answers to this related SO question.

Get remote registry value

For remote registry you have to use .NET with powershell 2.0

$w32reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine',$computer1)
$keypath = 'SOFTWARE\Veritas\NetBackup\CurrentVersion'
$netbackup = $w32reg.OpenSubKey($keypath)
$NetbackupVersion1 = $netbackup.GetValue('PackageVersion')

Import Python Script Into Another?

I highly recommend the reading of a lecture in SciPy-lectures organization:

https://scipy-lectures.org/intro/language/reusing_code.html

It explains all the commented doubts.

But, new paths can be easily added and avoiding duplication with the following code:

import sys
new_path = 'insert here the new path'

if new_path not in sys.path:
    sys.path.append(new_path)
import funcoes_python #Useful python functions saved in a different script

What is the difference between the operating system and the kernel?

Basically the Kernel is the interface between hardware (devices which are available in Computer) and Application software is like MS Office, Visual Studio, etc.

If I answer "what is an OS?" then the answer could be the same. Hence the kernel is the part & core of the OS.

The very sensitive tasks of an OS like memory management, I/O management, process management are taken care of by the kernel only.

So the ultimate difference is:

  1. Kernel is responsible for Hardware level interactions at some specific range. But the OS is like hardware level interaction with full scope of computer.
  2. Kernel triggers SystemCalls to tell the OS that this resource is available at this point of time. The OS is responsible to handle those system calls in order to utilize the resource.

How do I display a decimal value to 2 decimal places?

https://msdn.microsoft.com/en-us/library/dwhawy9k%28v=vs.110%29.aspx

This link explains in detail how you can handle your problem and what you can do if you want to learn more. For simplicity purposes, what you want to do is

double whateverYouWantToChange = whateverYouWantToChange.ToString("F2");

if you want this for a currency, you can make it easier by typing "C2" instead of "F2"

jQuery text() and newlines

Try this:

$(someElem).html('this<br> has<br> newlines);

reducing number of plot ticks

There's a set_ticks() function for axis objects.

Download a file from NodeJS Server using Express

Here's how I do it:

  1. create file
  2. send file to client
  3. remove file

Code:

let fs = require('fs');
let path = require('path');

let myController = (req, res) => {
  let filename = 'myFile.ext';
  let absPath = path.join(__dirname, '/my_files/', filename);
  let relPath = path.join('./my_files', filename); // path relative to server root

  fs.writeFile(relPath, 'File content', (err) => {
    if (err) {
      console.log(err);
    }
    res.download(absPath, (err) => {
      if (err) {
        console.log(err);
      }
      fs.unlink(relPath, (err) => {
        if (err) {
          console.log(err);
        }
        console.log('FILE [' + filename + '] REMOVED!');
      });
    });
  });
};

How to reload the current state?

That would be the final solution. (inspired by @Hollan_Risley's post)

'use strict';

angular.module('app')

.config(function($provide) {
    $provide.decorator('$state', function($delegate, $stateParams) {
        $delegate.forceReload = function() {
            return $delegate.go($delegate.current, $stateParams, {
                reload: true,
                inherit: false,
                notify: true
            });
        };
        return $delegate;
    });
});

Now, whenever you need to reload, simply call:

$state.forceReload();

How to get the next auto-increment id in mysql

In PHP you can try this:

$query = mysql_query("SELECT MAX(id) FROM `your_table_name`");
$results = mysql_fetch_array($query);
$cur_auto_id = $results['MAX(id)'] + 1;

OR

$result = mysql_query("SHOW TABLE STATUS WHERE `Name` = 'your_table_name'");
$data = mysql_fetch_assoc($result);
$next_increment = $data['Auto_increment'];

How to get base url in CodeIgniter 2.*

I know this is very late, but is useful for newbies. We can atuload url helper and it will be available throughout the application. For this in application\config\autoload.php modify as follows -

$autoload['helper'] = array('url'); 

How can I set a custom date time format in Oracle SQL Developer?

With Oracle SQL Developer 3.2.20.09, i managed to set the custom format for the type DATE this way :

In : Tools > Preferences > Database > NLS

Or : Outils > Préférences > Base de donées > NLS

YYYY-MM-DD HH24:MI:SS

Settings Menu screenshot

Note that the following format does not worked for me :

DD-MON-RR HH24:MI:SS

As a result, it keeps the default format, without any error.

Comparing two files in linux terminal

You can use diff tool in linux to compare two files. You can use --changed-group-format and --unchanged-group-format options to filter required data.

Following three options can use to select the relevant group for each option:

  • '%<' get lines from FILE1

  • '%>' get lines from FILE2

  • '' (empty string) for removing lines from both files.

E.g: diff --changed-group-format="%<" --unchanged-group-format="" file1.txt file2.txt

[root@vmoracle11 tmp]# cat file1.txt 
test one
test two
test three
test four
test eight
[root@vmoracle11 tmp]# cat file2.txt 
test one
test three
test nine
[root@vmoracle11 tmp]# diff --changed-group-format='%<' --unchanged-group-format='' file1.txt file2.txt 
test two
test four
test eight

View content of H2 or HSQLDB in-memory database

This is more a comment to previous Thomas Mueller's post rather than an answer, but haven't got enough reputation for it. Another way of getting the connection if you are Spring JDBC Template is using the following:

jdbcTemplate.getDataSource().getConnection();

So on debug mode if you add to the "Expressions" view in Eclipse it will open the browser showing you the H2 Console:

org.h2.tools.Server.startWebServer(jdbcTemplate.getDataSource().getConnection());

Eclipse Expressions View

H2 Console

How to catch exception correctly from http.request()?

New service updated to use the HttpClientModule and RxJS v5.5.x:

import { Injectable }                    from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable }                    from 'rxjs/Observable';
import { catchError, tap }               from 'rxjs/operators';
import { SomeClassOrInterface}           from './interfaces';
import 'rxjs/add/observable/throw';

@Injectable() 
export class MyService {
    url = 'http://my_url';
    constructor(private _http:HttpClient) {}
    private handleError(operation: String) {
        return (err: any) => {
            let errMsg = `error in ${operation}() retrieving ${this.url}`;
            console.log(`${errMsg}:`, err)
            if(err instanceof HttpErrorResponse) {
                // you could extract more info about the error if you want, e.g.:
                console.log(`status: ${err.status}, ${err.statusText}`);
                // errMsg = ...
            }
            return Observable.throw(errMsg);
        }
    }
    // public API
    public getData() : Observable<SomeClassOrInterface> {
        // HttpClient.get() returns the body of the response as an untyped JSON object.
        // We specify the type as SomeClassOrInterfaceto get a typed result.
        return this._http.get<SomeClassOrInterface>(this.url)
            .pipe(
                tap(data => console.log('server data:', data)), 
                catchError(this.handleError('getData'))
            );
    }

Old service, which uses the deprecated HttpModule:

import {Injectable}              from 'angular2/core';
import {Http, Response, Request} from 'angular2/http';
import {Observable}              from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
//import 'rxjs/Rx';  // use this line if you want to be lazy, otherwise:
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';  // debug
import 'rxjs/add/operator/catch';

@Injectable()
export class MyService {
    constructor(private _http:Http) {}
    private _serverError(err: any) {
        console.log('sever error:', err);  // debug
        if(err instanceof Response) {
          return Observable.throw(err.json().error || 'backend server error');
          // if you're using lite-server, use the following line
          // instead of the line above:
          //return Observable.throw(err.text() || 'backend server error');
        }
        return Observable.throw(err || 'backend server error');
    }
    private _request = new Request({
        method: "GET",
        // change url to "./data/data.junk" to generate an error
        url: "./data/data.json"
    });
    // public API
    public getData() {
        return this._http.request(this._request)
          // modify file data.json to contain invalid JSON to have .json() raise an error
          .map(res => res.json())  // could raise an error if invalid JSON
          .do(data => console.log('server data:', data))  // debug
          .catch(this._serverError);
    }
}

I use .do() (now .tap()) for debugging.

When there is a server error, the body of the Response object I get from the server I'm using (lite-server) contains just text, hence the reason I use err.text() above rather than err.json().error. You may need to adjust that line for your server.

If res.json() raises an error because it could not parse the JSON data, _serverError will not get a Response object, hence the reason for the instanceof check.

In this plunker, change url to ./data/data.junk to generate an error.


Users of either service should have code that can handle the error:

@Component({
    selector: 'my-app',
    template: '<div>{{data}}</div> 
       <div>{{errorMsg}}</div>`
})
export class AppComponent {
    errorMsg: string;
    constructor(private _myService: MyService ) {}
    ngOnInit() {
        this._myService.getData()
            .subscribe(
                data => this.data = data,
                err  => this.errorMsg = <any>err
            );
    }
}

How to use XPath preceding-sibling correctly

You don't need to go level up and use .. since all buttons are on the same level:

//button[contains(.,'Arcade Reader')]/preceding-sibling::button[@name='settings']

How can I create Min stl priority_queue?

Use std::greater as the comparison function:

std::priority_queue<int, std::vector<int>, std::greater<int> > my_min_heap;

Spring Boot access static resources missing scr/main/resources

While working with Spring Boot application, it is difficult to get the classpath resources using resource.getFile() when it is deployed as JAR as I faced the same issue. This scan be resolved using Stream which will find out all the resources which are placed anywhere in classpath.

Below is the code snippet for the same -

ClassPathResource classPathResource = new ClassPathResource("fileName");
InputStream inputStream = classPathResource.getInputStream();
content = IOUtils.toString(inputStream);

How to Detect if I'm Compiling Code with a particular Visual Studio version?

In visual studio, go to help | about and look at the version of Visual Studio that you're using to compile your app.

How does it work - requestLocationUpdates() + LocationRequest/Listener

You are implementing LocationListener in your activity MainActivity. The call for concurrent location updates will therefor be like this:

mLocationClient.requestLocationUpdates(mLocationRequest, this);

Be sure that the LocationListener you're implementing is from the google api, that is import this:

import com.google.android.gms.location.LocationListener;

and not this:

import android.location.LocationListener;

and it should work just fine.

It's also important that the LocationClient really is connected before you do this. I suggest you don't call it in the onCreate or onStart methods, but in onResume. It is all explained quite well in the tutorial for Google Location Api: https://developer.android.com/training/location/index.html

Open Popup window using javascript

Change the window name in your two different calls:

function popitup(url,windowName) {
       newwindow=window.open(url,windowName,'height=200,width=150');
       if (window.focus) {newwindow.focus()}
       return false;
     }

windowName must be unique when you open a new window with same url otherwise the same window will be refreshed.

Node.js get file extension

I do think mapping the Content-Type header in the request will also work. This will work even for cases when you upload a file with no extension. (when filename does not have an extension in the request)

Assume you are sending your data using HTTP POST:

POST /upload2 HTTP/1.1
Host: localhost:7098
Connection: keep-alive
Content-Length: 1047799
Accept: */*
Origin: http://localhost:63342
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML,    like Gecko) Chrome/51.0.2704.106 Safari/537.36
Content-Type: multipart/form-data; boundary=----   WebKitFormBoundaryPDULZN8DYK3VppPp
Referer: http://localhost:63342/Admin/index.html? _ijt=3a6a054pasorvrljf8t8ea0j4h
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,az;q=0.6,tr;q=0.4
Request Payload
------WebKitFormBoundaryPDULZN8DYK3VppPp
Content-Disposition: form-data; name="image"; filename="blob"
Content-Type: image/png


------WebKitFormBoundaryPDULZN8DYK3VppPp--

Here name Content-Type header contains the mime type of the data. Mapping this mime type to an extension will get you the file extension :).

Restify BodyParser converts this header in to a property with name type

File {
  domain: 
   Domain {
     domain: null,
     _events: { .... },
     _eventsCount: 1,
     _maxListeners: undefined,
     members: [ ... ] },
  _events: {},
  _eventsCount: 0,
  _maxListeners: undefined,
  size: 1047621,
  path: '/tmp/upload_2a4ac9ef22f7156180d369162ef08cb8',
  name: 'blob',
  **type: 'image/png'**,
  hash: null,
  lastModifiedDate: Wed Jul 20 2016 16:12:21 GMT+0300 (EEST),
  _writeStream: 
  WriteStream {
   ... },
     writable: true,
     domain: 
     Domain {
        ...
     },
      _events: {},
      _eventsCount: 0,
     _maxListeners: undefined,
     path: '/tmp/upload_2a4ac9ef22f7156180d369162ef08cb8',
     fd: null,
     flags: 'w',
     mode: 438,
     start: undefined,
     pos: undefined,
     bytesWritten: 1047621,
     closed: true } 
}

You can use this header and do the extension mapping (substring etc ...) manually, but there are also ready made libraries for this. Below two were the top results when i did a google search

  • mime
  • mime-types

and their usage is simple as well:

 app.post('/upload2', function (req, res) {
  console.log(mime.extension(req.files.image.type));
 }

above snippet will print png to console.

How can I create an editable combo box in HTML/Javascript?

Was looking for an Answer as well, but all I could find was outdated.

This Issue is solved since HTML5: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist

<label>Choose a browser from this list:
<input list="browsers" name="myBrowser" /></label>
<datalist id="browsers">
  <option value="Chrome">
  <option value="Firefox">
  <option value="Internet Explorer">
  <option value="Opera">
  <option value="Safari">
  <option value="Microsoft Edge">
</datalist>

If I had not found that, I would have gone with this approach:

http://www.dhtmlgoodies.com/scripts/form_widget_editable_select/form_widget_editable_select.html

port 8080 is already in use and no process using 8080 has been listed

PID is the process ID - not the port number. You need to look for an entry with ":8080" at the end of the address/port part (the second column). Then you can look at the PID and use Task Manager to work out which process is involved... or run netstat -abn which will show the process names (but must be run under an administrator account).

Having said that, I would expect the find "8080" to find it...

Another thing to do is just visit http://localhost:8080 - on that port, chances are it's a web server of some description.

CSS vertical alignment text inside li

Simple solution for vertical align middle... for me it works like a charm

ul{display:table; text-align:center; margin:0 auto;}
li{display:inline-block; text-align:center;}
li.items_inside_li{display:inline-block; vertical-align:middle;}

How can I copy the output of a command directly into my clipboard?

I usually run this command when I have to copy my ssh-key:

cat ~/.ssh/id_rsa.pub | pbcopy

ctrl+v anywhere else.

What exactly is Spring Framework for?

What is Spring for? I will answer that question shortly, but first, let's take another look at the example by victor hugo. It's not a great example because it doesn't justify the need for a new framework.

public class BaseView {
  protected UserLister userLister;

  public BaseView() {
    userLister = new UserListerDB(); // only line of code that needs changing
  }
}

public class SomeView extends BaseView {
  public SomeView() {
    super();
  }

  public void render() {
    List<User> users = userLister.getUsers();
    view.render(users);
  }
}

Done! So now even if you have hundreds or thousands of views, you still just need to change the one line of code, as in the Spring XML approach. But changing a line of code still requires recompiling as opposed to editing XML you say? Well my fussy friend, use Ant and script away!

So what is Spring for? It's for:

  1. Blind developers who follow the herd
  2. Employers who do not ever want to hire graduate programmers because they don't teach such frameworks at Uni
  3. Projects that started off with a bad design and need patchwork (as shown by victor hugo's example)

Further reading: http://discuss.joelonsoftware.com/?joel.3.219431.12

Truncate a SQLite table if it exists?

SELECT name FROM sqlite_master where name = '<TABLE_NAME_HERE>'

If the table name does not exist then there would not be any records returned!

You can as well use

SELECT count(name) FROM sqlite_master where name = '<TABLE_NAME_HERE>' 

if the count is 1, means table exists, otherwise, it would return 0

Creating a new directory in C

You can use mkdir:

$ man 2 mkdir

#include <sys/stat.h>
#include <sys/types.h>

int result = mkdir("/home/me/test.txt", 0777);

How to adjust an UIButton's imageSize?

When changing icon size with UIEdgeInsetsMake(top, left, bottom, right), keep in mind button dimensions and the ability of UIEdgeInsetsMake to work with negative values as if they are positive.

Example: Two buttons with height 100 and aspect 1:1.

left.imageEdgeInsets = UIEdgeInsetsMake(40, 0, 40, 0)
right.imageEdgeInsets = UIEdgeInsetsMake(40, 0, 40, 0)

enter image description here

left.imageEdgeInsets = UIEdgeInsetsMake(40, 0, 40, 0)
right.imageEdgeInsets = UIEdgeInsetsMake(45, 0, 45, 0)

enter image description here

left.imageEdgeInsets = UIEdgeInsetsMake(40, 0, 40, 0)
right.imageEdgeInsets = UIEdgeInsetsMake(60, 0, 60, 0)

enter image description here

Examples 1 and 3 are identical since ABS(100 - (40 + 40)) = ABS(100 - (60 + 60))

AlertDialog styling - how to change style (color) of title, message, etc

I changed color programmatically in this way :

var builder = new AlertDialog.Builder (this);
...
...
...
var dialog = builder.Show ();
int textColorId = Resources.GetIdentifier ("alertTitle", "id", "android");
TextView textColor = dialog.FindViewById<TextView> (textColorId);
textColor?.SetTextColor (Color.DarkRed);

as alertTitle, you can change other data by this way (next example is for titleDivider):

int titleDividerId = Resources.GetIdentifier ("titleDivider", "id", "android");
View titleDivider = dialog.FindViewById (titleDividerId);
titleDivider?.SetBackgroundColor (Color.Red);

this is in C#, but in java it is the same.

How to Join to first row

From SQL Server 2012 and onwards I think this will do the trick:

SELECT DISTINCT
    o.OrderNumber ,
    FIRST_VALUE(li.Quantity) OVER ( PARTITION BY o.OrderNumber ORDER BY li.Description ) AS Quantity ,
    FIRST_VALUE(li.Description) OVER ( PARTITION BY o.OrderNumber ORDER BY li.Description ) AS Description
FROM    Orders AS o
    INNER JOIN LineItems AS li ON o.OrderID = li.OrderID

Get List of connected USB Devices

If you change the ManagementObjectSearcher to the following:

ManagementObjectSearcher searcher = 
       new ManagementObjectSearcher("root\\CIMV2", 
       @"SELECT * FROM Win32_PnPEntity where DeviceID Like ""USB%"""); 

So the "GetUSBDevices() looks like this"

static List<USBDeviceInfo> GetUSBDevices()
{
  List<USBDeviceInfo> devices = new List<USBDeviceInfo>();

  ManagementObjectCollection collection;
  using (var searcher = new ManagementObjectSearcher(@"SELECT * FROM Win32_PnPEntity where DeviceID Like ""USB%"""))
    collection = searcher.Get();      

  foreach (var device in collection)
  {
    devices.Add(new USBDeviceInfo(
    (string)device.GetPropertyValue("DeviceID"),
    (string)device.GetPropertyValue("PNPDeviceID"),
    (string)device.GetPropertyValue("Description")
    ));
  }

  collection.Dispose();
  return devices;
}

}

Your results will be limited to USB devices (as opposed to all types on your system)

Create dynamic URLs in Flask with url_for()

It takes keyword arguments for the variables:

url_for('add', variable=foo)

How can I tell if a DOM element is visible in the current viewport?

I had the same question and figured it out by using getBoundingClientRect().

This code is completely 'generic' and only has to be written once for it to work (you don't have to write it out for each element that you want to know is in the viewport).

This code only checks to see if it is vertically in the viewport, not horizontally. In this case, the variable (array) 'elements' holds all the elements that you are checking to be vertically in the viewport, so grab any elements you want anywhere and store them there.

The 'for loop', loops through each element and checks to see if it is vertically in the viewport. This code executes every time the user scrolls! If the getBoudingClientRect().top is less than 3/4 the viewport (the element is one quarter in the viewport), it registers as 'in the viewport'.

Since the code is generic, you will want to know 'which' element is in the viewport. To find that out, you can determine it by custom attribute, node name, id, class name, and more.

Here is my code (tell me if it doesn't work; it has been tested in Internet Explorer 11, Firefox 40.0.3, Chrome Version 45.0.2454.85 m, Opera 31.0.1889.174, and Edge with Windows 10, [not Safari yet])...

// Scrolling handlers...
window.onscroll = function(){
  var elements = document.getElementById('whatever').getElementsByClassName('whatever');
  for(var i = 0; i != elements.length; i++)
  {
   if(elements[i].getBoundingClientRect().top <= window.innerHeight*0.75 &&
      elements[i].getBoundingClientRect().top > 0)
   {
      console.log(elements[i].nodeName + ' ' +
                  elements[i].className + ' ' +
                  elements[i].id +
                  ' is in the viewport; proceed with whatever code you want to do here.');
   }
};

Using NotNull Annotation in method argument

@Nullable and @NotNull do nothing on their own. They are supposed to act as Documentation tools.

The @Nullable Annotation reminds you about the necessity to introduce an NPE check when:

  1. Calling methods that can return null.
  2. Dereferencing variables (fields, local variables, parameters) that can be null.

The @NotNull Annotation is, actually, an explicit contract declaring the following:

  1. A method should not return null.
  2. A variable (like fields, local variables, and parameters) cannot should not hold null value.

For example, instead of writing:

/**
 * @param aX should not be null
 */
public void setX(final Object aX ) {
    // some code
}

You can use:

public void setX(@NotNull final Object aX ) {
    // some code
}

Additionally, @NotNull is often checked by ConstraintValidators (eg. in spring and hibernate).

The @NotNull annotation doesn't do any validation on its own because the annotation definition does not provide any ConstraintValidator type reference.

For more info see:

  1. Bean validation
  2. NotNull.java
  3. Constraint.java
  4. ConstraintValidator.java

create a text file using javascript

That works better with this :

var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();

http://msdn.microsoft.com/en-us/library/5t9b5c0c(v=vs.84).aspx

Telling gcc directly to link a library statically

It is possible of course, use -l: instead of -l. For example -l:libXYZ.a to link with libXYZ.a. Notice the lib written out, as opposed to -lXYZ which would auto expand to libXYZ.

Windows service start failure: Cannot start service from the command line or debugger

Your code has nothing to do with the service installation, it is not the problem.

In order to test the service, you must install it as indicated.

For more information about installing your service : Installing and Uninstalling Services

Why does my favicon not show up?

  1. Is it really a .ico, or is it just named ".ico"?
  2. What browser are you testing in?

The absolutely easiest way to have a favicon is to place an icon called "favicon.ico" in the root folder. That just works everywhere, no code needed at all.

If you must have it in a subdirectory, use:

<link rel="shortcut icon" href="/img/favicon.ico" />

Note the / before img to ensure it is anchored to the root folder.

How to use a WSDL

Use WSDL.EXE utility to generate a Web Service proxy from WSDL.

You'll get a long C# source file that contains a class that looks like this:

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="MyService", Namespace="http://myservice.com/myservice")]
public partial class MyService : System.Web.Services.Protocols.SoapHttpClientProtocol {
    ...
}

In your client-side, Web-service-consuming code:

  1. instantiate MyService.
  2. set its Url property
  3. invoke Web methods

What does elementFormDefault do in XSD?

ElementFormDefault has nothing to do with namespace of the types in the schema, it's about the namespaces of the elements in XML documents which comply with the schema.

Here's the relevent section of the spec:

Element Declaration Schema

Component Property  {target namespace}
Representation      If form is present and its ·actual value· is qualified, 
                    or if form is absent and the ·actual value· of 
                    elementFormDefault on the <schema> ancestor is qualified, 
                    then the ·actual value· of the targetNamespace [attribute]
                    of the parent <schema> element information item, or 
                    ·absent· if there is none, otherwise ·absent·.

What that means is that the targetNamespace you've declared at the top of the schema only applies to elements in the schema compliant XML document if either elementFormDefault is "qualified" or the element is declared explicitly in the schema as having form="qualified".

For example: If elementFormDefault is unqualified -

<element name="name" type="string" form="qualified"></element>
<element name="page" type="target:TypePage"></element>

will expect "name" elements to be in the targetNamespace and "page" elements to be in the null namespace.

To save you having to put form="qualified" on every element declaration, stating elementFormDefault="qualified" means that the targetNamespace applies to each element unless overridden by putting form="unqualified" on the element declaration.

JavaScript: undefined !== undefined?

That's a bad practice to use the == equality operator instead of ===.

undefined === undefined // true
null == undefined // true
null === undefined // false

The object.x === undefined should return true if x is unknown property.

In chapter Bad Parts of JavaScript: The Good Parts, Crockford writes the following:

If you attempt to extract a value from an object, and if the object does not have a member with that name, it returns the undefined value instead.

In addition to undefined, JavaScript has a similar value called null. They are so similar that == thinks they are equal. That confuses some programmers into thinking that they are interchangeable, leading to code like

value = myObject[name];
if (value == null) {
    alert(name + ' not found.');
}

It is comparing the wrong value with the wrong operator. This code works because it contains two errors that cancel each other out. That is a crazy way to program. It is better written like this:

value = myObject[name];
if (value === undefined) {
    alert(name + ' not found.');
}

Why can't non-default arguments follow default arguments?

Required arguments (the ones without defaults), must be at the start to allow client code to only supply two. If the optional arguments were at the start, it would be confusing:

fun1("who is who", 3, "jack")

What would that do in your first example? In the last, x is "who is who", y is 3 and a = "jack".

Debug vs Release in CMake

Instead of manipulating the CMAKE_CXX_FLAGS strings directly (which could be done more nicely using string(APPEND CMAKE_CXX_FLAGS_DEBUG " -g3") btw), you can use add_compiler_options:

add_compile_options(
  "-Wall" "-Wpedantic" "-Wextra" "-fexceptions"
  "$<$<CONFIG:DEBUG>:-O0;-g3;-ggdb>"
)

This would add the specified warnings to all build types, but only the given debugging flags to the DEBUG build. Note that compile options are stored as a CMake list, which is just a string separating its elements by semicolons ;.

Is it possible to print a variable's type in standard C++?

A more generic solution without function overloading than my previous one:

template<typename T>
std::string TypeOf(T){
    std::string Type="unknown";
    if(std::is_same<T,int>::value) Type="int";
    if(std::is_same<T,std::string>::value) Type="String";
    if(std::is_same<T,MyClass>::value) Type="MyClass";

    return Type;}

Here MyClass is user defined class. More conditions can be added here as well.

Example:

#include <iostream>



class MyClass{};


template<typename T>
std::string TypeOf(T){
    std::string Type="unknown";
    if(std::is_same<T,int>::value) Type="int";
    if(std::is_same<T,std::string>::value) Type="String";
    if(std::is_same<T,MyClass>::value) Type="MyClass";
    return Type;}


int main(){;
    int a=0;
    std::string s="";
    MyClass my;
    std::cout<<TypeOf(a)<<std::endl;
    std::cout<<TypeOf(s)<<std::endl;
    std::cout<<TypeOf(my)<<std::endl;

    return 0;}

Output:

int
String
MyClass

Jquery change <p> text programmatically

"saving" is something wholly different from changing paragraph content with jquery.

If you need to save changes you will have to write them to your server somehow (likely form submission along with all the security and input sanitizing that entails). If you have information that is saved on the server then you are no longer changing the content of a paragraph, you are drawing a paragraph with dynamic content (either from a database or a file which your server altered when you did the "saving").

Judging by your question, this is a topic on which you will have to do MUCH more research.

Input page (input.html):

<form action="/saveMyParagraph.php">
    <input name="pContent" type="text"></input>
</form>

Saving page (saveMyParagraph.php) and Ouput page (output.php):

Inserting Data Into a MySQL Database using PHP

Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_list-1.xml, reason: Connection to https://dl-ssl.google.com refused

I had this issue running within a corporate network. I added a DNS entry for google DNS at 8.8.8.8, then my own corporate DNS server below this. Worked great after that.

How to automatically generate unique id in SQL like UID12345678?

Reference:https://docs.microsoft.com/en-us/sql/t-sql/functions/newid-transact-sql?view=sql-server-2017

-- Creating a table using NEWID for uniqueidentifier data type.

CREATE TABLE cust  
(  
 CustomerID uniqueidentifier NOT NULL  
   DEFAULT newid(),  
 Company varchar(30) NOT NULL,  
 ContactName varchar(60) NOT NULL,   
 Address varchar(30) NOT NULL,   
 City varchar(30) NOT NULL,  
 StateProvince varchar(10) NULL,  
 PostalCode varchar(10) NOT NULL,   
 CountryRegion varchar(20) NOT NULL,   
 Telephone varchar(15) NOT NULL,  
 Fax varchar(15) NULL  
);  
GO  
-- Inserting 5 rows into cust table.  
INSERT cust  
(CustomerID, Company, ContactName, Address, City, StateProvince,   
 PostalCode, CountryRegion, Telephone, Fax)  
VALUES  
 (NEWID(), 'Wartian Herkku', 'Pirkko Koskitalo', 'Torikatu 38', 'Oulu', NULL,  
 '90110', 'Finland', '981-443655', '981-443655')  
,(NEWID(), 'Wellington Importadora', 'Paula Parente', 'Rua do Mercado, 12', 'Resende', 'SP',  
 '08737-363', 'Brasil', '(14) 555-8122', '')  
,(NEWID(), 'Cactus Comidas para Ilevar', 'Patricio Simpson', 'Cerrito 333', 'Buenos Aires', NULL,   
 '1010', 'Argentina', '(1) 135-5555', '(1) 135-4892')  
,(NEWID(), 'Ernst Handel', 'Roland Mendel', 'Kirchgasse 6', 'Graz', NULL,  
 '8010', 'Austria', '7675-3425', '7675-3426')  
,(NEWID(), 'Maison Dewey', 'Catherine Dewey', 'Rue Joseph-Bens 532', 'Bruxelles', NULL,  
 'B-1180', 'Belgium', '(02) 201 24 67', '(02) 201 24 68');  
GO

How can I check the syntax of Python script without executing it?

Here's another solution, using the ast module:

python -c "import ast; ast.parse(open('programfile').read())"

To do it cleanly from within a Python script:

import ast, traceback

filename = 'programfile'
with open(filename) as f:
    source = f.read()
valid = True
try:
    ast.parse(source)
except SyntaxError:
    valid = False
    traceback.print_exc()  # Remove to silence any errros
print(valid)

CSS Float: Floating an image to the left of the text

Set the width of post-content and post-thumb so that you get a two-column layout.

A python class that acts like dict

Here is an alternative solution:

class AttrDict(dict):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__dict__ = self

a = AttrDict()
a.a = 1
a.b = 2

Understanding Apache's access log

You seem to be using the combined log format.

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" combined

  • %h is the remote host (ie the client IP)
  • %l is the identity of the user determined by identd (not usually used since not reliable)
  • %u is the user name determined by HTTP authentication
  • %t is the time the request was received.
  • %r is the request line from the client. ("GET / HTTP/1.0")
  • %>s is the status code sent from the server to the client (200, 404 etc.)
  • %b is the size of the response to the client (in bytes)
  • Referer is the Referer header of the HTTP request (containing the URL of the page from which this request was initiated) if any is present, and "-" otherwise.
  • User-agent is the browser identification string.

The complete(?) list of formatters can be found here. The same section of the documentation also lists other common log formats; readers whose logs don't look quite like this one may find the pattern their Apache configuration is using listed there.

Cannot install signed apk to device manually, got error "App not installed"

This can happen due to your choice of the signature version. On some phones, installation errors occur if the signature version was selected as V2. So if that happens, try selecting V1, it will surely work.

Fit image into ImageView, keep aspect ratio and then resize ImageView to image dimensions?

After searching for a day, I think this is the easiest solution:

imageView.getLayoutParams().width = 250;
imageView.getLayoutParams().height = 250;
imageView.setAdjustViewBounds(true);

REST API - file (ie images) processing - best practices

There's no easy solution. Each way has their pros and cons . But the canonical way is using the first option: multipart/form-data. As W3 recommendation guide says

The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

We aren't sending forms,really, but the implicit principle still applies. Using base64 as a binary representation, is incorrect because you're using the incorrect tool for accomplish your goal, in other hand, the second option forces your API clients to do more job in order to consume your API service. You should do the hard work in the server side in order to supply an easy-to-consume API. The first option is not easy to debug, but when you do it, it probably never changes.

Using multipart/form-data you're sticked with the REST/http philosophy. You can view an answer to similar question here.

Another option if mixing the alternatives, you can use multipart/form-data but instead of send every value separate, you can send a value named payload with the json payload inside it. (I tried this approach using ASP.NET WebAPI 2 and works fine).

IllegalMonitorStateException on wait() call

In order to deal with the IllegalMonitorStateException, you must verify that all invocations of the wait, notify and notifyAll methods are taking place only when the calling thread owns the appropriate monitor. The most simple solution is to enclose these calls inside synchronized blocks. The synchronization object that shall be invoked in the synchronized statement is the one whose monitor must be acquired.

Here is the simple example for to understand the concept of monitor

public class SimpleMonitorState {

    public static void main(String args[]) throws InterruptedException {

        SimpleMonitorState t = new SimpleMonitorState();
        SimpleRunnable m = new SimpleRunnable(t);
        Thread t1 = new Thread(m);
        t1.start();
        t.call();

    }

    public void call() throws InterruptedException {
        synchronized (this) {
            wait();
            System.out.println("Single by Threads ");
        }
    }

}

class SimpleRunnable implements Runnable {

    SimpleMonitorState t;

    SimpleRunnable(SimpleMonitorState t) {
        this.t = t;
    }

    @Override
    public void run() {

        try {
            // Sleep
            Thread.sleep(10000);
            synchronized (this.t) {
                this.t.notify();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

How to install MySQLdb package? (ImportError: No module named setuptools)

Also, you can see the build dependencies in the file setup.cfg

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

To add to the valuable content, I would like to create this reminder on why sometimes RegEx within VBA is not ideal. Not all expressions are supported, but instead may throw an Error 5017 and may leave the author guessing (which I am a victim of myself).

Whilst we can find some sources on what is supported, it would be helpfull to know which metacharacters etc. are not supported. A more in-depth explaination can be found here. Mentioned in this source:

"Although "VBScript’s regular expression ... version 5.5 implements quite a few essential regex features that were missing in previous versions of VBScript. ... JavaScript and VBScript implement Perl-style regular expressions. However, they lack quite a number of advanced features available in Perl and other modern regular expression flavors:"


So, not supported are:

  • Start of String ancor \A, alternatively use the ^ caret to match postion before 1st char in string
  • End of String ancor \Z, alternatively use the $ dollar sign to match postion after last char in string
  • Positive LookBehind, e.g.: (?<=a)b (whilst postive LookAhead is supported)
  • Negative LookBehind, e.g.: (?<!a)b (whilst negative LookAhead is supported)
  • Atomic Grouping
  • Possessive Quantifiers
  • Unicode e.g.: \{uFFFF}
  • Named Capturing Groups. Alternatively use Numbered Capturing Groups
  • Inline modifiers, e.g.: /i (case sensitivity) or /g (global) etc. Set these through the RegExp object properties > RegExp.Global = True and RegExp.IgnoreCase = True if available.
  • Conditionals
  • Regular Expression Comments. Add these with regular ' comments in script

I already hit a wall more than once using regular expressions within VBA. Usually with LookBehind but sometimes I even forget the modifiers. I have not experienced all these above mentioned backdrops myself but thought I would try to be extensive referring to some more in-depth information. Feel free to comment/correct/add. Big shout out to regular-expressions.info for a wealth of information.

P.S. You have mentioned regular VBA methods and functions, and I can confirm they (at least to myself) have been helpful in their own ways where RegEx would fail.

Should I use Python 32bit or Python 64bit

Machine learning packages like tensorflow 2.x are designed to work only on 64 bit Python as they are memory intensive.

"dd/mm/yyyy" date format in excel through vba

I got it

Cells(1, 1).Value = StartDate
Cells(1, 1).NumberFormat = "dd/mm/yyyy"

Basically, I need to set the cell format, instead of setting the date.

How can I rename a field for all documents in MongoDB?

If ever you need to do the same thing with mongoid:

Model.all.rename(:old_field, :new_field)

UPDATE

There is change in the syntax in monogoid 4.0.0:

Model.all.rename(old_field: :new_field)

remove duplicates from sql union

Union will remove duplicates. Union All does not.

What is the difference between conversion specifiers %i and %d in formatted IO functions (*printf / *scanf)

There is no difference between the %i and %d format specifiers for printf. We can see this by going to the draft C99 standard section 7.19.6.1 The fprintf function which also covers printf with respect to format specifiers and it says in paragraph 8:

The conversion specifiers and their meanings are:

and includes the following bullet:

d,i     The int argument is converted to signed decimal in the style
        [-]dddd. The precision specifies the minimum number of digits to
        appear; if the value being converted can be represented in fewer
        digits, it is expanded with leading zeros. The default precision is
        1. The result of converting a zero value with a precision of zero is
        no characters.

On the other hand for scanf there is a difference, %d assume base 10 while %i auto detects the base. We can see this by going to section 7.19.6.2 The fscanf function which covers scanf with respect to format specifier, in paragraph 12 it says:

The conversion specifiers and their meanings are:

and includes the following:

d     Matches an optionally signed decimal integer, whose format is the
      same as expected for the subject sequence of the strtol function with
      the value 10 for the base argument. The corresponding argument shall
      be a pointer to signed integer.

i     Matches an optionally signed integer, whose format is the same as
      expected for the subject sequence of the strtol function with the
      value 0 for the base argument. The corresponding argument shall be a
      pointer to signed integer.

Disable a textbox using CSS

Going further on Pekka's answer, I had a style "style1" on some of my textboxes. You can create a "style1[disabled]" so you style only the disabled textboxes using "style1" style:

.style1[disabled] { ... }

Worked ok on IE8.

Unable to install gem - Failed to build gem native extension - cannot load such file -- mkmf (LoadError)

For MacOS users:

Just do this and easily it will solve your problem:

brew install cocoapods

What is the best comment in source code you have ever encountered?

It's not strictly speaking a comment, but...

It was the mid-1990s and I was working on a big migration: small software vendor, big client, lots of pressure. We had a lot of shifting-goalpost stuff; the project was very hard to control. I was the key developer, but new to the system, and the other developer was the vendor's owner/founder.

After a few months of not quite making deadlines and not quite satisfying the client, the owner/founder brought on another developer, who was working remotely. (I'm gonna go out on a limb and say the new developer had lesser skills and experience than me.)

Well, the new guy made some changes in code that I'd already worked on, and then a month or two later I was back in the same area of the code, and there were variables I hadn't seen before. With names like StupidMark.

Dude, that's just not right. I mean, there's teamwork considerations, but also: in this environment, variable names can show up in runtime error messages. I'm just saying.

In my opinion at the time, the new guy's code wasn't getting us much closer to a deliverable product anyway, which made the insult sting a little more.

How to add pandas data to an existing csv file?

You can append to a csv by opening the file in append mode:

with open('my_csv.csv', 'a') as f:
    df.to_csv(f, header=False)

If this was your csv, foo.csv:

,A,B,C
0,1,2,3
1,4,5,6

If you read that and then append, for example, df + 6:

In [1]: df = pd.read_csv('foo.csv', index_col=0)

In [2]: df
Out[2]:
   A  B  C
0  1  2  3
1  4  5  6

In [3]: df + 6
Out[3]:
    A   B   C
0   7   8   9
1  10  11  12

In [4]: with open('foo.csv', 'a') as f:
             (df + 6).to_csv(f, header=False)

foo.csv becomes:

,A,B,C
0,1,2,3
1,4,5,6
0,7,8,9
1,10,11,12

How can I disable editing cells in a WPF Datagrid?

The WPF DataGrid has an IsReadOnly property that you can set to True to ensure that users cannot edit your DataGrid's cells.

You can also set this value for individual columns in your DataGrid as needed.

What are the differences between NP, NP-Complete and NP-Hard?

I assume that you are looking for intuitive definitions, since the technical definitions require quite some time to understand. First of all, let's remember a preliminary needed concept to understand those definitions.

  • Decision problem: A problem with a yes or no answer.

Now, let us define those complexity classes.

P

P is a complexity class that represents the set of all decision problems that can be solved in polynomial time.

That is, given an instance of the problem, the answer yes or no can be decided in polynomial time.

Example

Given a connected graph G, can its vertices be coloured using two colours so that no edge is monochromatic?

Algorithm: start with an arbitrary vertex, color it red and all of its neighbours blue and continue. Stop when you run out of vertices or you are forced to make an edge have both of its endpoints be the same color.


NP

NP is a complexity class that represents the set of all decision problems for which the instances where the answer is "yes" have proofs that can be verified in polynomial time.

This means that if someone gives us an instance of the problem and a certificate (sometimes called a witness) to the answer being yes, we can check that it is correct in polynomial time.

Example

Integer factorisation is in NP. This is the problem that given integers n and m, is there an integer f with 1 < f < m, such that f divides n (f is a small factor of n)?

This is a decision problem because the answers are yes or no. If someone hands us an instance of the problem (so they hand us integers n and m) and an integer f with 1 < f < m, and claim that f is a factor of n (the certificate), we can check the answer in polynomial time by performing the division n / f.


NP-Complete

NP-Complete is a complexity class which represents the set of all problems X in NP for which it is possible to reduce any other NP problem Y to X in polynomial time.

Intuitively this means that we can solve Y quickly if we know how to solve X quickly. Precisely, Y is reducible to X, if there is a polynomial time algorithm f to transform instances y of Y to instances x = f(y) of X in polynomial time, with the property that the answer to y is yes, if and only if the answer to f(y) is yes.

Example

3-SAT. This is the problem wherein we are given a conjunction (ANDs) of 3-clause disjunctions (ORs), statements of the form

(x_v11 OR x_v21 OR x_v31) AND 
(x_v12 OR x_v22 OR x_v32) AND 
...                       AND 
(x_v1n OR x_v2n OR x_v3n)

where each x_vij is a boolean variable or the negation of a variable from a finite predefined list (x_1, x_2, ... x_n).

It can be shown that every NP problem can be reduced to 3-SAT. The proof of this is technical and requires use of the technical definition of NP (based on non-deterministic Turing machines). This is known as Cook's theorem.

What makes NP-complete problems important is that if a deterministic polynomial time algorithm can be found to solve one of them, every NP problem is solvable in polynomial time (one problem to rule them all).


NP-hard

Intuitively, these are the problems that are at least as hard as the NP-complete problems. Note that NP-hard problems do not have to be in NP, and they do not have to be decision problems.

The precise definition here is that a problem X is NP-hard, if there is an NP-complete problem Y, such that Y is reducible to X in polynomial time.

But since any NP-complete problem can be reduced to any other NP-complete problem in polynomial time, all NP-complete problems can be reduced to any NP-hard problem in polynomial time. Then, if there is a solution to one NP-hard problem in polynomial time, there is a solution to all NP problems in polynomial time.

Example

The halting problem is an NP-hard problem. This is the problem that given a program P and input I, will it halt? This is a decision problem but it is not in NP. It is clear that any NP-complete problem can be reduced to this one. As another example, any NP-complete problem is NP-hard.

My favorite NP-complete problem is the Minesweeper problem.


P = NP

This one is the most famous problem in computer science, and one of the most important outstanding questions in the mathematical sciences. In fact, the Clay Institute is offering one million dollars for a solution to the problem (Stephen Cook's writeup on the Clay website is quite good).

It's clear that P is a subset of NP. The open question is whether or not NP problems have deterministic polynomial time solutions. It is largely believed that they do not. Here is an outstanding recent article on the latest (and the importance) of the P = NP problem: The Status of the P versus NP problem.

The best book on the subject is Computers and Intractability by Garey and Johnson.

Calculate RSA key fingerprint

The fastest way if your keys are in an SSH agent:

$ ssh-add -L | ssh-keygen -E md5 -lf /dev/stdin

Each key in the agent will be printed as:

4096 MD5:8f:c9:dc:40:ec:9e:dc:65:74:f7:20:c1:29:d1:e8:5a /Users/cmcginty/.ssh/id_rsa (RSA)

Why am I getting this redefinition of class error?

Include a few #ifndef name #define name #endif preprocessor that should solve your problem. The issue is it going from the header to the function then back to the header so it is redefining the class with all the preprocessor(#include) multiple times.

Creating CSS Global Variables : Stylesheet theme management

I do it this way:

The html:

<head>
    <style type="text/css"> <? require_once('xCss.php'); ?> </style>
</head>

The xCss.php:

<? // place here your vars
$fntBtn = 'bold 14px  Arial'
$colBorder  = '#556677' ;
$colBG0     = '#dddddd' ;
$colBG1     = '#44dddd' ;
$colBtn     = '#aadddd' ;

// here goes your css after the php-close tag: 
?>
button { border: solid 1px <?= $colBorder; ?>; border-radius:4px; font: <?= $fntBtn; ?>; background-color:<?= $colBtn; ?>; } 

Explicitly select items from a list or tuple

>>> map(myList.__getitem__, (2,2,1,3))
('baz', 'baz', 'bar', 'quux')

You can also create your own List class which supports tuples as arguments to __getitem__ if you want to be able to do myList[(2,2,1,3)].

Volatile Vs Atomic

So what will happen if two threads attack a volatile primitive variable at same time?

Usually each one can increment the value. However sometime, both will update the value at the same time and instead of incrementing by 2 total, both thread increment by 1 and only 1 is added.

Does this mean that whosoever takes lock on it, that will be setting its value first.

There is no lock. That is what synchronized is for.

And in if meantime, some other thread comes up and read old value while first thread was changing its value, then doesn't new thread will read its old value?

Yes,

What is the difference between Atomic and volatile keyword?

AtomicXxxx wraps a volatile so they are basically same, the difference is that it provides higher level operations such as CompareAndSwap which is used to implement increment.

AtomicXxxx also supports lazySet. This is like a volatile set, but doesn't stall the pipeline waiting for the write to complete. It can mean that if you read a value you just write you might see the old value, but you shouldn't be doing that anyway. The difference is that setting a volatile takes about 5 ns, bit lazySet takes about 0.5 ns.

Better way to cast object to int

int i = myObject.myField.CastTo<int>();

illegal use of break statement; javascript

I have a function next() which will maybe inspire you.

function queue(target) {
        var array = Array.prototype;

        var queueing = [];

        target.queue = queue;
        target.queued = queued;

        return target;

        function queued(action) {
            return function () {
                var self = this;
                var args = arguments;

                queue(function (next) {
                    action.apply(self, array.concat.apply(next, args));
                });
            };
        }

        function queue(action) {
            if (!action) {
                return;
            }

            queueing.push(action);

            if (queueing.length === 1) {
                next();
            }
        }

        function next() {
            queueing[0](function (err) {
                if (err) {
                    throw err;
                }

                queueing = queueing.slice(1);

                if (queueing.length) {
                    next();
                }
            });
        }
    }

Convert javascript object or array to json for ajax data

I'm not entirely sure but I think you are probably surprised at how arrays are serialized in JSON. Let's isolate the problem. Consider following code:

var display = Array();
display[0] = "none";
display[1] = "block";
display[2] = "none";

console.log( JSON.stringify(display) );

This will print:

["none","block","none"]

This is how JSON actually serializes array. However what you want to see is something like:

{"0":"none","1":"block","2":"none"}

To get this format you want to serialize object, not array. So let's rewrite above code like this:

var display2 = {};
display2["0"] = "none";
display2["1"] = "block";
display2["2"] = "none";

console.log( JSON.stringify(display2) );

This will print in the format you want.

You can play around with this here: http://jsbin.com/oDuhINAG/1/edit?js,console

Generate a unique id

This question seems to be answered, however for completeness, I would add another approach.

You can use a unique ID number generator which is based on Twitter's Snowflake id generator. C# implementation can be found here.

var id64Generator = new Id64Generator();

// ...

public string generateID(string sourceUrl)
{
    return string.Format("{0}_{1}", sourceUrl, id64Generator.GenerateId());
}

Note that one of very nice features of that approach is possibility to have multiple generators on independent nodes (probably something useful for a search engine) generating real time, globally unique identifiers.

// node 0
var id64Generator = new Id64Generator(0);

// node 1
var id64Generator = new Id64Generator(1);

// ... node 10
var id64Generator = new Id64Generator(10);

Getting Database connection in pure JPA setup

I ran into this problem today and this was the trick I did, which worked for me:

   EntityManagerFactory emf = Persistence.createEntityManagerFactory("DAOMANAGER");
   EntityManagerem = emf.createEntityManager();

   org.hibernate.Session session = ((EntityManagerImpl) em).getSession();
   java.sql.Connection connectionObj = session.connection();

Though not the best way but does the job.

Using colors with printf

#include <stdio.h>

//fonts color
#define FBLACK      "\033[30;"
#define FRED        "\033[31;"
#define FGREEN      "\033[32;"
#define FYELLOW     "\033[33;"
#define FBLUE       "\033[34;"
#define FPURPLE     "\033[35;"
#define D_FGREEN    "\033[6;"
#define FWHITE      "\033[7;"
#define FCYAN       "\x1b[36m"

//background color
#define BBLACK      "40m"
#define BRED        "41m"
#define BGREEN      "42m"
#define BYELLOW     "43m"
#define BBLUE       "44m"
#define BPURPLE     "45m"
#define D_BGREEN    "46m"
#define BWHITE      "47m"

//end color
#define NONE        "\033[0m"

int main(int argc, char *argv[])
{
    printf(D_FGREEN BBLUE"Change color!\n"NONE);

    return 0;
}

Expression must be a modifiable lvalue

Remember that a single = is always an assignment in C or C++.

Your test should be if ( match == 0 && k == M )you made a typo on the k == M test.

If you really mean k=M (i.e. a side-effecting assignment inside a test) you should for readability reasons code if (match == 0 && (k=m) != 0) but most coding rules advise not writing that.

BTW, your mistake suggests to ask for all warnings (e.g. -Wall option to g++), and to upgrade to recent compilers. The next GCC 4.8 will give you:

 % g++-trunk -Wall -c ederman.cc
 ederman.cc: In function ‘void foo()’:
 ederman.cc:9:30: error: lvalue required as left operand of assignment
          if ( match == 0 && k = M )
                               ^

and Clang 3.1 also tells you ederman.cc:9:30: error: expression is not assignable

So use recent versions of free compilers and enable all the warnings when using them.

CakePHP select default value in SELECT input

cakephp version >= 3.6

echo $this->Form->control('field_name', ['type' => 'select', 'options' => $departments, 'default' => 'your value']);

Selecting between two dates within a DateTime field - SQL Server

SELECT * 
FROM tbl 
WHERE myDate BETWEEN #date one# AND #date two#;

Inheriting constructors

You have to explicitly define the constructor in B and explicitly call the constructor for the parent.

B(int x) : A(x) { }

or

B() : A(5) { }

Placing an image to the top right corner - CSS

Position the div relatively, and position the ribbon absolutely inside it. Something like:

#content {
  position:relative;
}

.ribbon {
  position:absolute;
  top:0;
  right:0;
}

jQuery: how to trigger anchor link's click event

$(":button").click(function () {                
                $("#anchor_google")[0].click();
            });
  1. First, find the button by type(using ":") if id is not given.
  2. Second,find the anchor tag by id or in some other tag like div and $("#anchor_google")[0] returns the DOM object.

Table 'mysql.user' doesn't exist:ERROR

Your database may be corrupt. Try to check if mysql.user exists:

use mysql;
select * from user;

If these are missing you can try recreating the tables by using

mysql_install_db

or you may have to clean (completely remove it) and reinstall MySQL.

Comparing user-inputted characters in C

I see two problems:

The pointer answer is a null pointer and you are trying to dereference it in scanf, this leads to undefined behavior.

You don't need a char pointer here. You can just use a char variable as:

char answer;
scanf(" %c",&answer);

Next to see if the read character is 'y' or 'Y' you should do:

if( answer == 'y' || answer == 'Y') {
  // user entered y or Y.
}

If you really need to use a char pointer you can do something like:

char var;
char *answer = &var; // make answer point to char variable var.
scanf (" %c", answer);
if( *answer == 'y' || *answer == 'Y') {

If statement with String comparison fails

In your example you are comparing the string objects, not their content.

Your comparison should be :

if (s.equals("/quit"))

Or if s string nullity doesn't mind / or you really don't like NPEs:

if ("/quit".equals(s))

Didn't find class "com.google.firebase.provider.FirebaseInitProvider"?

This is due to MultiDex.

Steps to solve:

  1. In gradle->dependencies->(compile'com.android.support:multidex:1.0.1') Add this in dependencies

  2. In your project application class extends MultiDexApplication like this (public class MyApplication extends MultiDexApplication)

  3. Run and check

Docker error: invalid reference format: repository name must be lowercase

For me the issue was with the space in volume mapping that was not escaped. The jenkins job which was running the docker run command had a space in it and as a result docker engine was not able to understand the docker run command.

Getting a list of values from a list of dicts

Get key values from list of dictionaries in python?

  1. Get key values from list of dictionaries in python?

Ex:

data = 
[{'obj1':[{'cpu_percentage':'15%','ram':3,'memory_percentage':'66%'}]},
{'obj2': [{'cpu_percentage':'0','ram':4,'memory_percentage':'35%'}]}]

for d in data:

  for key,value in d.items(): 

      z ={key: {'cpu_percentage': d['cpu_percentage'],'memory_percentage': d['memory_percentage']} for d in value} 
      print(z)

Output:

{'obj1': {'cpu_percentage': '15%', 'memory_percentage': '66%'}}
{'obj2': {'cpu_percentage': '0', 'memory_percentage': '35%'}}

how can I enable scrollbars on the WPF Datagrid?

Add grid with defined height and width for columns and rows. Then add ScrollViewer and inside it add the dataGrid.

Exploring Docker container's file system

Try using

docker exec -it <container-name> /bin/bash

There might be possibility that bash is not implemented. for that you can use

docker exec -it <container-name> sh

scatter plot in matplotlib

Maybe something like this:

import matplotlib.pyplot
import pylab

x = [1,2,3,4]
y = [3,4,8,6]

matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

EDIT:

Let me see if I understand you correctly now:

You have:

       test1 | test2 | test3
test3 |   1   |   0  |  1

test4 |   0   |   1  |  0

test5 |   1   |   1  |  0

Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.

Let's say you results are stored in a 2-D list:

results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

We want to transform them into two variables so we are able to plot them.

And I believe this code will give you what you are looking for:

import matplotlib
import pylab


results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

x = []
y = []

for ind_1, sublist in enumerate(results):
    for ind_2, ele in enumerate(sublist):
        if ele == 1:
            x.append(ind_1)
            y.append(ind_2)       


matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

Notice that I do need to import pylab, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.

Choosing a jQuery datagrid plugin?

The three most used and well supported jQuery grid plugins today are SlickGrid, jqGrid and DataTables. See http://wiki.jqueryui.com/Grid-OtherGrids for more info.

Preferred way of getting the selected item of a JComboBox

JComboBox mycombo=new JComboBox(); //Creates mycombo JComboBox.
add(mycombo); //Adds it to the jframe.

mycombo.addItem("Hello Nepal");  //Adds data to the JComboBox.

String s=String.valueOf(mycombo.getSelectedItem());  //Assigns "Hello Nepal" to s.

System.out.println(s);  //Prints "Hello Nepal".

Escaping single quotes in JavaScript string for JavaScript evaluation

I agree that this var formattedString = string.replace(/'/g, "\\'"); works very well, but since I used this part of code in PHP with the framework Prado (you can register the js script in a PHP class) I needed this sample working inside double quotes.

The solution that worked for me is that you need to put three \ and escape the double quotes. "var string = \"l'avancement\"; var formattedString = string.replace(/'/g, \"\\\'\");"

I answer that question since I had trouble finding that three \ was the work around.

JDBC connection failed, error: TCP/IP connection to host failed

Go to Start->All Programs-> Microsoft SQL Server 2012-> Configuration Tool -> Click SQL Server Configuration Manager. enter image description here

If you see that SQL Server/ SQL Server Browser State is 'stopped'.Right click on SQL Server/SQL Server Browser and click start. In some cases above state can stop though TCP connection to port 1433 is assigned.

How to remove all white spaces in java

Why not use a regex for this?

a = a.replaceAll("\\s","");

In the context of a regex, \s will remove anything that is a space character (including space, tab characters etc). You need to escape the backslash in Java so the regex turns into \\s. Also, since Strings are immutable it is important that you assign the return value of the regex to a.

extract part of a string using bash/cut/split

Using a single sed

echo "/var/cpanel/users/joebloggs:DNS9=domain.com" | sed 's/.*\/\(.*\):.*/\1/'

Set default format of datetimepicker as dd-MM-yyyy

You can set CustomFormat property to "dd-MM-yyyy" in design mode and use dateTimePicker1.Text property to fetch string in "dd/MM/yyyy" format irrespective of display format.

How to style the parent element when hovering a child element?

Another, simpler approach (to an old question)..
would be to place elements as siblings and use:

Adjacent Sibling Selector (+) or General Sibling Selector (~)

<div id="parent">
  <!-- control should come before the target... think "cascading" ! -->
  <button id="control">Hover Me!</button>
  <div id="target">I'm hovered too!</div>
</div>
#parent {
  position: relative;
  height: 100px;
}

/* Move button control to bottom. */
#control {
  position: absolute;
  bottom: 0;
}

#control:hover ~ #target {
  background: red;
}

enter image description here

Demo Fiddle here.

How do I call Objective-C code from Swift?

Click on the New file menu, and chose file select language Objective. At that time it automatically generates a "Objective-C Bridging Header" file that is used to define some class name.

"Objective-C Bridging Header" under "Swift Compiler - Code Generation".

Declaring and initializing arrays in C

It is not possible to assign values to an array all at once after initialization. The best alternative would be to use a loop.

for(i=0;i<N;i++)
{
     array[i] = i;
}

You can hard code and assign values like --array[0] = 1 and so on.

Memcpy can also be used if you have the data stored in an array already.

unable to install pg gem

Issue is gem dependency so before installing pg make sure you have installed "libpq-dev"

Ubuntu systems:

sudo apt-get install libpq-dev

RHEL systems:

yum install postgresql-devel

Mac:

brew install postgresql

HREF="" automatically adds to current page URL (in PHP). Can't figure it out

Add http:// in front of url

Incorrect

<a href="www.example.com">www.example.com</span></p>

Correct

<a href="http://www.example.com">www.example.com</span></p>

How to make a copy of an object in C#

Properties in your object are value types and you can use the shallow copy in such situation like that:

obj myobj2 = (obj)myobj.MemberwiseClone();

But in other situations, like if any members are reference types, then you need Deep Copy. You can get a deep copy of an object using Serialization and Deserialization techniques with the help of BinaryFormatter class:

public static T DeepCopy<T>(T other)
{
    using (MemoryStream ms = new MemoryStream())
    {
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Context = new StreamingContext(StreamingContextStates.Clone);
        formatter.Serialize(ms, other);
        ms.Position = 0;
        return (T)formatter.Deserialize(ms);
    }
}

The purpose of setting StreamingContext: We can introduce special serialization and deserialization logic to our code with the help of either implementing ISerializable interface or using built-in attributes like OnDeserialized, OnDeserializing, OnSerializing, OnSerialized. In all cases StreamingContext will be passed as an argument to the methods(and to the special constructor in case of ISerializable interface). With setting ContextState to Clone, we are just giving hint to that method about the purpose of the serialization.

Additional Info: (you can also read this article from MSDN)

Shallow copying is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed; for a reference type, the reference is copied but the referred object is not; therefore the original object and its clone refer to the same object.

Deep copy is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, a new copy of the referred object is performed.

How to use cURL in Java?

Using standard java libs, I suggest looking at the HttpUrlConnection class http://java.sun.com/javase/6/docs/api/java/net/HttpURLConnection.html

It can handle most of what curl can do with setting up the connection. What you do with the stream is up to you.

Warning: date_format() expects parameter 1 to be DateTime

Best way is use DateTime object to convert your date.

$myDateTime = DateTime::createFromFormat('Y-m-d', $weddingdate);
$formattedweddingdate = $myDateTime->format('d-m-Y');

Note: It will support for PHP 5 >= 5.3.0 only.

How can I create an observable with a delay

Using the following imports:

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/delay';

Try this:

let fakeResponse = [1,2,3];
let delayedObservable = Observable.of(fakeResponse).delay(5000);
delayedObservable.subscribe(data => console.log(data));

UPDATE: RXJS 6

The above solution doesn't really work anymore in newer versions of RXJS (and of angular for example).

So the scenario is that I have an array of items to check with an API with. The API only accepts a single item, and I do not want to kill the API by sending all requests at once. So I need a timed release of items on the Observable stream with a small delay in between.

Use the following imports:

import { from, of } from 'rxjs';
import { delay } from 'rxjs/internal/operators';
import { concatMap } from 'rxjs/internal/operators';

Then use the following code:

const myArray = [1,2,3,4];

from(myArray).pipe(
        concatMap( item => of(item).pipe ( delay( 1000 ) ))
    ).subscribe ( timedItem => {
        console.log(timedItem)
    });

It basically creates a new 'delayed' Observable for every item in your array. There are probably many other ways of doing it, but this worked fine for me, and complies with the 'new' RXJS format.

Add onclick event to newly added element in JavaScript

You can also set attribute:

elem.setAttribute("onclick","alert('blah');");

How can we dynamically allocate and grow an array

You can do something like this:

String [] wordList;
int wordCount = 0;
int occurrence = 1;
int arraySize = 100;
int arrayGrowth = 50;
wordList = new String[arraySize];
while ((strLine = br.readLine()) != null)   {
     // Store the content into an array
     Scanner s = new Scanner(strLine);
     while(s.hasNext()) {
         if (wordList.length == wordCount) {
              // expand list
              wordList = Arrays.copyOf(wordList, wordList.length + arrayGrowth);
         }
         wordList[wordCount] = s.next();
         wordCount++;
     } 
}

Using java.util.Arrays.copyOf(String[]) is basically doing the same thing as:

if (wordList.length == wordCount) {
    String[] temp = new String[wordList.length + arrayGrowth];
    System.arraycopy(wordList, 0, temp, 0, wordList.length);
    wordList = temp;
}

except it is one line of code instead of three. :)

How does a PreparedStatement avoid or prevent SQL injection?

Consider two ways of doing the same thing:

PreparedStatement stmt = conn.createStatement("INSERT INTO students VALUES('" + user + "')");
stmt.execute();

Or

PreparedStatement stmt = conn.prepareStatement("INSERT INTO student VALUES(?)");
stmt.setString(1, user);
stmt.execute();

If "user" came from user input and the user input was

Robert'); DROP TABLE students; --

Then in the first instance, you'd be hosed. In the second, you'd be safe and Little Bobby Tables would be registered for your school.

WPF ListView - detect when selected item is clicked

You can handle click on list view item like this:

<ListView.ItemTemplate>
  <DataTemplate>
     <Button BorderBrush="Transparent" Background="Transparent" Focusable="False">
        <i:Interaction.Triggers>
                <i:EventTrigger EventName="Click">
                    <i:InvokeCommandAction Command="{Binding DataContext.MyCommand, ElementName=ListViewName}" CommandParameter="{Binding}"/>
                </i:EventTrigger>
        </i:Interaction.Triggers>
      <Button.Template>
      <ControlTemplate>
         <Grid VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
    ...

Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?

If you want more compact code, I suggest using Apache Commons DbUtils. In this case:

Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
    conn = // Retrieve connection
    stmt = conn.prepareStatement(// Some SQL);
    rs = stmt.executeQuery();
} catch(Exception e) {
    // Error Handling
} finally {
    DbUtils.closeQuietly(rs);
    DbUtils.closeQuietly(stmt);
    DbUtils.closeQuietly(conn);
}

str_replace with array

str_replace with arrays just performs all the replacements sequentially. Use strtr instead to do them all at once:

$new_message = strtr($message, 'lmnopq...', 'abcdef...');

Adding a column to a dataframe in R

That is a pretty standard use case for apply():

R> vec <- 1:10
R> DF <- data.frame(start=c(1,3,5,7), end=c(2,6,7,9))
R> DF$newcol <- apply(DF,1,function(row) mean(vec[ row[1] : row[2] ] ))
R> DF
  start end newcol
1     1   2    1.5
2     3   6    4.5
3     5   7    6.0
4     7   9    8.0
R> 

You can also use plyr if you prefer but here is no real need to go beyond functions from base R.

gradlew: Permission Denied

chmod +x gradlew

Just run the above comment. that's all enjoy your coding...

ElasticSearch: Unassigned Shards, how to fix?

I was having this issue as well, and I found an easy way to resolve it.

  • Get the index of unassigned shards

    $ curl -XGET http://172.16.4.140:9200/_cat/shards
    
  • Install curator Tools, and use it to delete index

    $ curator --host 172.16.4.140 delete indices --older-than 1 \
           --timestring '%Y.%m.%d' --time-unit days --prefix logstash
    

    NOTE: In my case, the index is logstash of the day 2016-04-21

  • Then check the shards again, all the unassigned shards go away!

How to add a custom CA Root certificate to the CA Store used by pip in Windows?

I think nt86's solution is the most appropriate because it leverages the underlying Windows infrastructure (certificate store). But it doesn't explain how to install python-certifi-win32 to start with since pip is non functional.

The trick is to use --trustedhost to install python-certifi-win32 and then after that, pip will automatically use the windows certificate store to load the certificate used by the proxy.

So in a nutshell, you should do:

pip install python-certifi-win32 -trustedhost pypi.org

and after that you should be good to go

Saving and loading objects and using pickle

It seems you want to save your class instances across sessions, and using pickle is a decent way to do this. However, there's a package called klepto that abstracts the saving of objects to a dictionary interface, so you can choose to pickle objects and save them to a file (as shown below), or pickle the objects and save them to a database, or instead of use pickle use json, or many other options. The nice thing about klepto is that by abstracting to a common interface, it makes it easy so you don't have to remember the low-level details of how to save via pickling to a file, or otherwise.

Note that It works for dynamically added class attributes, which pickle cannot do...

dude@hilbert>$ python
Python 2.7.6 (default, Nov 12 2013, 13:26:39) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from klepto.archives import file_archive 
>>> db = file_archive('fruits.txt')
>>> class Fruits: pass
... 
>>> banana = Fruits()
>>> banana.color = 'yellow'
>>> banana.value = 30
>>> 
>>> db['banana'] = banana 
>>> db.dump()
>>> 

Then we restart…

dude@hilbert>$ python
Python 2.7.6 (default, Nov 12 2013, 13:26:39) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from klepto.archives import file_archive
>>> db = file_archive('fruits.txt')
>>> db.load()
>>> 
>>> db['banana'].color
'yellow'
>>> 

Klepto works on python2 and python3.

Get the code here: https://github.com/uqfoundation

Reverting to a previous revision using TortoiseSVN

I have used the same instructions Stefan used, taken from Tortoise website.

But it's important to click COMMIT right after. I was getting crazy until I realized that.

If you need to make an older revision your head revision do the following:

  1. Select the file or folder in which you need to revert the changes. If you want to revert all changes, this should be the top level folder.

  2. Select TortoiseSVN ? Show Log to display a list of revisions. You may need to use Show All or Next 100 to show the revision(s) you are interested in.

  3. Right click on the selected revision, then select Context Menu ? Revert to this revision. This will discard all changes after the selected revision.

  4. Make a commit.

Vue.js - How to properly watch for nested data

Personally I prefer this clean implementation:

watch: {
  myVariable: {
     handler(newVal, oldVal){  // here having access to the new and old value
       // do stuff
     },
     deep: true,
     immediate: true //  Also very important the immediate in case you need it, the callback will be called immediately after the start of the observation

  }
}

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

I understand where the problem lies and when I look at the specs its clear that unescaped single quotes should be parsed correctly.

I am using jquery`s jQuery.parseJSON function to parse the JSON string but still getting the parse error when there is a single quote in the data that is prepared with json_encode.

Could it be a mistake in my implementation that looks like this (PHP - server side):

$data = array();

$elem = array();
$elem['name'] = 'Erik';
$elem['position'] = 'PHP Programmer';
$data[] = json_encode($elem);

$elem = array();
$elem['name'] = 'Carl';
$elem['position'] = 'C Programmer';
$data[] = json_encode($elem);

$jsonString = "[" . implode(", ", $data) . "]";

The final step is that I store the JSON encoded string into an JS variable:

<script type="text/javascript">
employees = jQuery.parseJSON('<?=$marker; ?>');
</script>

If I use "" instead of '' it still throws an error.

SOLUTION:

The only thing that worked for me was to use bitmask JSON_HEX_APOS to convert the single quotes like this:

json_encode($tmp, JSON_HEX_APOS);

Is there another way of tackle this issue? Is my code wrong or poorly written?

Thanks

SyntaxError: unexpected EOF while parsing

Here is one of my mistakes that produced this exception: I had a try block without any except or finally blocks. This will not work:

try:
    lets_do_something_beneficial()

To fix this, add an except or finally block:

try:
    lets_do_something_beneficial()
finally:
    lets_go_to_sleep()

JQuery Validate Dropdown list

The documentation for required() states:

To force a user to select an option from a select box, provide an empty options like <option value="">Choose...</option>

By having value="none" in your <option> tag, you are preventing the validation call from ever being made. You can also remove your custom validation rule, simplifying your code. Here's a jsFiddle showing it in action:

http://jsfiddle.net/Kn3v5/

If you can't change the value attribute to the empty string, I don't know what to tell you...I couldn't find any way to get it to validate otherwise.

build maven project with propriatery libraries included

The really quick and dirty way is to point to a local file:

<dependency>
      <groupId>sampleGroupId</groupId>  
       <artifactId>sampleArtifactId</artifactId>  
       <version>1.0</version> 
      <scope>system</scope>
      <systemPath>C:\DEV\myfunnylib\yourJar.jar</systemPath>
</dependency>

However this will only live on your machine (obviously), for sharing it usually makes sense to use a proper m2 archive (nexus/artifactory) or if you do not have any of these or don't want to set one up a local maven structured archive and configure a "repository" in your pom:

local:

<repositories>
    <repository>
        <id>my-local-repo</id>
        <url>file://C:/DEV//mymvnrepo</url>
    </repository>
</repositories>

remote:

<repositories>
    <repository>
        <id>my-remote-repo</id>
        <url>http://192.168.0.1/whatever/mavenserver/youwant/repo</url>
    </repository>
</repositories>

How can you strip non-ASCII characters from a string? (in C#)

I use this regular expression to filter out bad characters in a filename.

Regex.Replace(directory, "[^a-zA-Z0-9\\:_\- ]", "")

That should be all the characters allowed for filenames.

Create an ArrayList of unique values

You could use a Set. It is a collection which doesn't accept duplicates.

Set colspan dynamically with jquery

You'd need to remove the blank table cell element entirely, and change the colspan attribute on another cell in the row to encompass the released space, e.g.:

refToCellToRemove.remove();
refTocellToExpand.colspan = 4;

Note that setting it via setAttribute (which would otherwise be correct) will not work properly on IE.

Beware: IE does some very strange table layout things when you muck about with colspans dynamically. If you can avoid it, I would.

numpy array TypeError: only integer scalar arrays can be converted to a scalar index

I ran into the problem when venturing to use numpy.concatenate to emulate a C++ like pushback for 2D-vectors; If A and B are two 2D numpy.arrays, then numpy.concatenate(A,B) yields the error.

The fix was to simply to add the missing brackets: numpy.concatenate( ( A,B ) ), which are required because the arrays to be concatenated constitute to a single argument

jQuery: enabling/disabling datepicker

This works for me on toggling enable and disable datepicker of JQuery:

if (condition) {
          $('#ElementID').datepicker(); //Enable datepicker                   
} else {
         //Disable datepicker without the ability to enter any character on text input
          $('#ElementID').datepicker('destroy');
          $('#ElementID').attr('readonly', true); }

I don't know why but when I use enable/disable in datepicker options, it doesn't behave the way it should be. It only works after you enable and disable it, but once you disable it, it doesn't enable again after, so the code above works perfectly fine for me:

if (condition) {
      $('#ElementID').datepicker('enable'); //Enable datepicker                   
} else {
      //Disable datepicker but I cannot enable it again once it goes through this condition
      $('#ElementID').datepicker('disable');  }

How to use variables in a command in sed?

Say:

sed "s|\$ROOT|${HOME}|" abc.sh

Note:

  • Use double quotes so that the shell would expand variables.
  • Use a separator different than / since the replacement contains /
  • Escape the $ in the pattern since you don't want to expand it.

EDIT: In order to replace all occurrences of $ROOT, say

sed "s|\$ROOT|${HOME}|g" abc.sh

Globally catch exceptions in a WPF application?

Use the Application.DispatcherUnhandledException Event. See this question for a summary (see Drew Noakes' answer).

Be aware that there'll be still exceptions which preclude a successful resuming of your application, like after a stack overflow, exhausted memory, or lost network connectivity while you're trying to save to the database.

Angular - Can't make ng-repeat orderBy work

Here's a version of @Julian Mosquera's code that also supports a "fallback" field to use in case the primary field happens to be null or undefined:

yourApp.filter('orderObjectBy', function() {
  return function(items, field, fallback, reverse) {
    var filtered = [];
    angular.forEach(items, function(item) {
      filtered.push(item);
    });
    filtered.sort(function (a, b) {
      var af = a[field];
      if(af === undefined || af === null) { af = a[fallback]; }

      var bf = b[field];
      if(bf === undefined || bf === null) { bf = b[fallback]; }

      return (af > bf ? 1 : -1);
    });
    if(reverse) filtered.reverse();
    return filtered;
  };
});

Insert multiple lines into a file after specified pattern using shell script

sed '/^cdef$/r'<(
    echo "line1"
    echo "line2"
    echo "line3"
    echo "line4"
) -i -- input.txt

HorizontalScrollView within ScrollView Touch Handling

Thank you Joel for giving me a clue on how to resolve this problem.

I have simplified the code(without need for a GestureDetector) to achieve the same effect:

public class VerticalScrollView extends ScrollView {
    private float xDistance, yDistance, lastX, lastY;

    public VerticalScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                xDistance = yDistance = 0f;
                lastX = ev.getX();
                lastY = ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                final float curX = ev.getX();
                final float curY = ev.getY();
                xDistance += Math.abs(curX - lastX);
                yDistance += Math.abs(curY - lastY);
                lastX = curX;
                lastY = curY;
                if(xDistance > yDistance)
                    return false;
        }

        return super.onInterceptTouchEvent(ev);
    }
}

How to open Visual Studio Code from the command line on OSX?

I have a ~/bin/code shell script that matches the command @BengaminPasero wrote.

#!/bin/bash
VSCODE_CWD="$PWD" open -n -b "com.microsoft.VSCode" --args $*

I prefix ~/bin: to my $PATH which allows me to add a bunch of one off scripts without polluting my ~/.bash_profile script.

What is the use of the @Temporal annotation in Hibernate?

@Temporal is a JPA annotation which can be used to store in the database table on of the following column items:

  1. DATE (java.sql.Date)
  2. TIME (java.sql.Time)
  3. TIMESTAMP (java.sql.Timestamp)

Generally when we declare a Date field in the class and try to store it.
It will store as TIMESTAMP in the database.

@Temporal
private Date joinedDate;

Above code will store value looks like 08-07-17 04:33:35.870000000 PM

If we want to store only the DATE in the database,
We can use/define TemporalType.

@Temporal(TemporalType.DATE)
private Date joinedDate;

This time, it would store 08-07-17 in database

There are some other attributes as well as @Temporal which can be used based on the requirement.

Unexpected token < in first line of HTML

In my case I got this error because of a line

<script src="#"></script> 

Chrome tried to interpret the current HTML file then as javascript.

How to construct a REST API that takes an array of id's for the resources

As much as I prefer this approach:-

    api.com/users?id=id1,id2,id3,id4,id5

The correct way is

    api.com/users?ids[]=id1&ids[]=id2&ids[]=id3&ids[]=id4&ids[]=id5

or

    api.com/users?ids=id1&ids=id2&ids=id3&ids=id4&ids=id5

This is how rack does it. This is how php does it. This is how node does it as well...