Programs & Examples On #Nstask

NSTask Class on OS X API , lets you run another program as a subprocess and monitor that program’s execution

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

Not sure if this solution works for you or not but just want to heads you up on compiler and build tools version compatibility issues.

This could be because of Java and Gradle version mismatch.

distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip

Gradle 4.4 is compatible with only Java 7 and 8. So, point your global variable JAVA_HOME to Java 7 or 8.

In mac, add below line to your ~/.bash_profile

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home

You can have multiple java versions. Just change the JAVA_HOME path based on need. You can do it easily, check this

Exception : AAPT2 error: check logs for details

someone might get some help from my case I just put a hard coded color hex value without # like this by mistake android:textColor="FFA500" almost made me mad to findout. #FFA500 this solved my issue

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

In my case, I attempted to upgrade play_servicesand firebase versions to 15.0. Going back to 11.4.2 fixed my issue...

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'

I had the same issue and I could solve it like this:

1) If your minSdkVersion is set to 21 or a higher value, the only thing you need to do is to set multiDexEnabled in your build.gradle file at the module level, as shown below:

android {
    defaultConfig {
        ...
        minSdkVersion 21 
        targetSdkVersion 28
        multiDexEnabled true
    }
    ...
}

2) However, if your minSdkVersion is set to 20 or less, you should use the MultiDex compatibility library, as follows:

2.1) Modify the module-level build.gradle file to enable MultiDex and add the MultiDex library as dependency, as shown below

android {
    defaultConfig {
        ...
        minSdkVersion 15 
        targetSdkVersion 28
        multiDexEnabled true
    }
    ...
}

dependencies {
  implementation 'com.android.support:multidex:1.0.3'
}

2.2) According to the Application class or not, do one of the following actions:

2.2.1) If you do not cancel the Application class, modify your manifest file to set android: name in the <application> tag as shown below:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp">
    <application
            android:name="android.support.multidex.MultiDexApplication" >
        ...
    </application>
</manifest>

2.2.2) If you cancel the Application class, you must change it to extend MultiDexApplication (if possible) as shown below:

public class MyApplication extends MultiDexApplication { ... }

2.2.3) Also, if you override the Application class and can not change the base class, alternatively you can override the attachBaseContext () method and invoke MultiDex.install (this) to enable MultiDex:

public class MyApplication extends SomeOtherApplication {
  @Override
  protected void attachBaseContext(Context base) {
     super.attachBaseContext(base);
     MultiDex.install(this);
  }
}

Please use this link, it was really useful for me!

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

NO NEED FOR MULTIDEX, I REPEAT, NO NEEED FOR MULTIDEX


Let me elaborate: Multidex is basically a tool that comes with Android, and if you set it to true, apps with >64,000 methods are able to compile using a slightly altered build process. However you only need to use multidex if your error looks like this:

trouble writing output: Too many field references: 131000; max is 65536. You may try using --multi-dex option.

or like this

Conversion to Dalvik format failed: Unable to execute dex: method ID not in [0, 0xffff]: 65536

But that is not the case here! The problem here (for me atleast) is being caused by your build.gradle file's dependencies.

THE SOLUTION: Utilize specific dependencies—don't just import an entire section of dependencies!

For example, if you need the Play Services dependency for location, only import it for location.

DO:

compile 'com.google.android.gms:play-services-location:11.0.4'

DON'T:

compile 'com.google.android.gms:play-services'

Another issue that could be causing this may be some sort of external library you are using, that is referencing a prior version of your dependency. Follow these steps in that case:

  1. Go to SDK manager, and install any updates to your dependencies
  2. Make sure that your build.gradle file shows the latest version. To get the latest version, use this link: https://developers.google.com/android/guides/setup
  3. Edit your library (or install an updated version if that exists), to reference the latest version

I know this question is old, but I need to get this answer out there, because using multidex for no reason could potentially cause ANR's for your app! ONLY use multidex if you're sure you need it, and you understand what it is.

I myself spent hours trying to resolve this issue without multidex, and I just wanted to share my findings—hope this helps

No tests found for given includes Error, when running Parameterized Unit test in Android Studio

Found a way to run the test in Android Studio. Apparently running it using Gradle Configuration will not execute any test. Instead I use JUnit Configuration. The simple way to do so is go to Select your Test Class to run and Right Click. Then choose Run. After that you'll see 2 run options. Select the bottom one (JUnit) as per the imageenter image description here

(note: If you can't find 2 Run Configuration to select, you'll need to remove your earlier used Configuration (Gradle Configuration) first. That could be done by Clicking on the "Select Run/Debug Configuration" icon in the Top Toolbar.

Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cruncher *some file* failed, see logs

Additional to all answers, I think it could have similar problems. My Problem was caused by png.9 files. If this files, have a (in my case) too small stretching area with just a few pixels, the building failed with this error also. I have checked all these answers, but nothing helped. Giving a little bit bigger stretching area, solved the problem. I tested it many times, allways when I use small stretching areas it failed. So I am sure, it will help some poeple to make the stretch area a little bit bigger.

The second problem, but this is just an assumption, is the icon name (maybe only for png.9 files too). For examle, I used an image named folder_icon.9.png , with this one, it allways failed. Renaming it to other_folder_icon.9.png, it worked. So I think some names are used by the android system itself, maybe here is a problem too.

Gradle: Execution failed for task ':processDebugManifest'

I had the same problem and none of the other answers helped.

In my case, a comment in the manifest file was the culprit:

<manifest [...]
    android:installLocation="auto">
    <!-- change installLocation back to external after test -->

    <uses-sdk [...]

(This might be a bug, seeing how comments in other areas of the manifest dont cause any problems.)

How to display an image stored as byte array in HTML/JavaScript?

Try putting this HTML snippet into your served document:

<img id="ItemPreview" src="">

Then, on JavaScript side, you can dynamically modify image's src attribute with so-called Data URL.

document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;

Alternatively, using jQuery:

$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);

This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..." part) in the URL accordingly.

Similar Questions:

Cannot ignore .idea/workspace.xml - keeps popping up

I was facing the same issue, and it drove me up the wall. The issue ended up to be that the .idea folder was ALREADY commited into the repo previously, and so they were being tracked by git regardless of whether you ignored them or not. I would recommend the following, after closing RubyMine/IntelliJ or whatever IDE you are using:

mv .idea ../.idea_backup
rm .idea # in case you forgot to close your IDE
git rm -r .idea 
git commit -m "Remove .idea from repo"
mv ../.idea_backup .idea

After than make sure to ignore .idea in your .gitignore

Although it is sufficient to ignore it in the repository's .gitignore, I would suggest that you ignore your IDE's dotfiles globally.

Otherwise you will have to add it to every .gitgnore for every project you work on. Also, if you collaborate with other people, then its best practice not to pollute the project's .gitignore with private configuation that are not specific to the source-code of the project.

VBA - Select columns using numbers?

I was looking for a similar thing. My problem was to find the last column based on row 5 and then select 3 columns before including the last column.

Dim lColumn As Long

lColumn = ActiveSheet.Cells(5,Columns.Count).End(xlToLeft).Column
MsgBox ("The last used column is: " & lColumn)
Range(Columns(lColumn - 3), Columns(lColumn)).Select

Message box is optional as it is more of a control check. If you want to select the columns after the last column then you simply reverse the range selection

Dim lColumn As Long

lColumn = ActiveSheet.Cells(5,Columns.Count).End(xlToLeft).Column
MsgBox ("The last used column is: " & lColumn)
Range(Columns(lColumn), Columns(lColumn + 3)).Select

Which HTTP methods match up to which CRUD methods?

The whole key is whether you're doing an idempotent change or not. That is, if taking action on the message twice will result in “the same” thing being there as if it was only done once, you've got an idempotent change and it should be mapped to PUT. If not, it maps to POST. If you never permit the client to synthesize URLs, PUT is pretty close to Update and POST can handle Create just fine, but that's most certainly not the only way to do it; if the client knows that it wants to create /foo/abc and knows what content to put there, it works just fine as a PUT.

The canonical description of a POST is when you're committing to purchasing something: that's an action which nobody wants to repeat without knowing it. By contrast, setting the dispatch address for the order beforehand can be done with PUT just fine: it doesn't matter if you are told to send to 6 Anywhere Dr, Nowhereville once, twice or a hundred times: it's still the same address. Does that mean that it's an update? Could be… It all depends on how you want to write the back-end. (Note that the results might not be identical: you could report back to the user when they last did a PUT as part of the representation of the resource, which would ensure that repeated PUTs do not cause an identical result, but the result would still be “the same” in a functional sense.)

Java equivalent of unsigned long long?

Java does not have unsigned types. As already mentioned, incure the overhead of BigInteger or use JNI to access native code.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

I had the same issue. Sometimes this happens if your MySQL service is turned down.

So you have to start it:

sudo service mysql start

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

to have unit-testing AND integration-testing you can use maven-surefire-plugin and maven-failsafe-plugin with restricted includes/excludes. I was playing with CDI while getting in touch with sonar/jacoco, so i ended up in this project:

https://github.com/FibreFoX/cdi-sessionscoped-login/

Maybe it helps you a little bit. in my pom.xml i use "-javaagent" implicit by setting the argLine-option in the configuration-section of the specified testing-plugins. Explicit using ANT in MAVEN projects is something i would not give a try, for me its to much mixing two worlds.

I only have a single-module maven project, but maybe it helps you to adjust yours to work.

note: maybe not all maven-plugins are up2date, maybe some issues are fixed in later versions

How to update std::map after using the find method?

You can use std::map::at member function, it returns a reference to the mapped value of the element identified with key k.

std::map<char,int> mymap = {
                               { 'a', 0 },
                               { 'b', 0 },
                           };

  mymap.at('a') = 10;
  mymap.at('b') = 20;

C# listView, how do I add items to columns 2, 3 and 4 etc?

For your problem use like this:

ListViewItem row = new ListViewItem(); 
row.SubItems.Add(value.ToString()); 
listview1.Items.Add(row);

How to find topmost view controller on iOS

If the root controller is a navigation controller, correct way to find top visible controller is:

UIViewController *rootVC = [[UIApplication sharedApplication] keyWindow].rootViewController;
if ([rootVC respondsToSelector:@selector(visibleViewController)])
{
    UIViewController *topVC = [(UINavigationController *)rootVC visibleViewController];
    // do your thing with topVC
}

Here's an excerpt from UINavigationController.h:

@property(nonatomic,readonly,retain) UIViewController *topViewController; // The top view controller on the stack.
@property(nonatomic,readonly,retain) UIViewController *visibleViewController; // Return modal view controller if it exists. Otherwise the top view controller.

Groovy built-in REST/HTTP client?

If your needs are simple and you want to avoid adding additional dependencies you may be able to use the getText() methods that Groovy adds to the java.net.URL class:

new URL("http://stackoverflow.com").getText()

// or

new URL("http://stackoverflow.com")
        .getText(connectTimeout: 5000, 
                readTimeout: 10000, 
                useCaches: true, 
                allowUserInteraction: false, 
                requestProperties: ['Connection': 'close'])

If you are expecting binary data back there is also similar functionality provided by the newInputStream() methods.

JQuery: dynamic height() with window resize()

Okay, how about a CSS answer! We use display: table. Then each of the divs are rows, and finally we apply height of 100% to middle 'row' and voilà.

http://jsfiddle.net/NfmX3/3/

body { display: table; }
div { display: table-row; }
#content {
    width:450px; 
    margin:0 auto;
    text-align: center;
    background-color: blue;
    color: white;
    height: 100%;
}

Convert String to double in Java

Citing the quote from Robertiano above again - because this is by far the most versatile and localization adaptive version. It deserves a full post!

Another option:

DecimalFormat df = new DecimalFormat(); 
DecimalFormatSymbols sfs = new DecimalFormatSymbols();
sfs.setDecimalSeparator(','); 
df.setDecimalFormatSymbols(sfs);
double d = df.parse(number).doubleValue();

Escape double quotes in a string

Please explain your problem. You say:

But this involves adding character " to the string.

What problem is that? You can't type string foo = "Foo"bar"";, because that'll invoke a compile error. As for the adding part, in string size terms that is not true:

@"""".Length == "\"".Length == 1

MySQL user DB does not have password columns - Installing MySQL on OSX

remember password needs to be set further even after restarting mysql as below

SET PASSWORD = PASSWORD('root');

Change NULL values in Datetime format to empty string

Try to use the function DECODE

Ex: Decode(MYDATE, NULL, ' ', MYDATE)

If date is NULL then display ' ' (BLANK) else display the date.

How to get full REST request body using Jersey?

Turns out you don't have to do much at all.

See below - the parameter x will contain the full HTTP body (which is XML in our case).

@POST
public Response go(String x) throws IOException {
    ...
}

How can I create tests in Android Studio?

Add below lib inside gradle file

 androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

Create class HomeActivityTest inside androidTest directory and before running the test add flurry_api_key and sender_id string inside string resource file and change the value for failure and success case.

@RunWith(AndroidJUnit4.class)
public class HomeActivityTest
{
    private static final String SENDER_ID = "abc";
    private static final String RELEASE_FLURRY_API_KEY = "xyz";

    @Test
    public void gcmRegistrationId_isCorrect() throws Exception
    {
        // Context of the app under test.
        Context appContext = InstrumentationRegistry.getTargetContext();

        Assert.assertEquals(SENDER_ID, appContext.getString(R.string.sender_id));
    }

    @Test
    public void flurryApiKey_isCorrect() throws Exception
    {
        // Context of the app under test.
        Context appContext = InstrumentationRegistry.getTargetContext();

        Assert.assertEquals(RELEASE_FLURRY_API_KEY, appContext.getString(R.string.flurry_api_key));
    }
}

Best way to restrict a text field to numbers only?

This is a variation on Robert's answer that allows a single decimal point to be entered. If a decimal point has already been entered, only numbers are accepted as input.

JSFiddle - decimal number input

// Allow only decimal number input

$('#decimalInput').keypress(function (e) {
    var a = [];
    var k = e.which;

    for (i = 48; i < 58; i++)
    a.push(i);

    // allow a max of 1 decimal point to be entered
    if (this.value.indexOf(".") === -1) {
        a.push(46);
    }

    if (!(a.indexOf(k) >= 0)) e.preventDefault();

    $('span').text('KeyCode: ' + k);
});

How to ensure a <select> form field is submitted when it is disabled?

I whipped up a quick (Jquery only) plugin, that saves the value in a data field while an input is disabled. This just means as long as the field is being disabled programmaticly through jquery using .prop() or .attr()... then accessing the value by .val(), .serialize() or .serializeArra() will always return the value even if disabled :)

Shameless plug: https://github.com/Jezternz/jq-disabled-inputs

Python - OpenCV - imread - Displaying Image

Looks like the image is too big and the window simply doesn't fit the screen. Create window with the cv2.WINDOW_NORMAL flag, it will make it scalable. Then you can resize it to fit your screen like this:

from __future__ import division
import cv2


img = cv2.imread('1.jpg')

screen_res = 1280, 720
scale_width = screen_res[0] / img.shape[1]
scale_height = screen_res[1] / img.shape[0]
scale = min(scale_width, scale_height)
window_width = int(img.shape[1] * scale)
window_height = int(img.shape[0] * scale)

cv2.namedWindow('dst_rt', cv2.WINDOW_NORMAL)
cv2.resizeWindow('dst_rt', window_width, window_height)

cv2.imshow('dst_rt', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

According to the OpenCV documentation CV_WINDOW_KEEPRATIO flag should do the same, yet it doesn't and it's value not even presented in the python module.

History or log of commands executed in Git

If you are using CentOS or another Linux flavour then just do Ctrl+R at the prompt and type git.

If you keep hitting Ctrl+R this will do a reverse search through your history for commands that start with git

How to type a new line character in SQL Server Management Studio

You can't.

Use a "new query" window instead, and do a manual update:

UPDATE mytable
SET textvalue = 
'This text
can include
line breaks'
WHERE rowid = 1234

http://localhost/phpMyAdmin/ unable to connect

You dont start phpmyadmin from your webbrowser. When you want to start PHPMyAdmin you have to do so from the XAMPP control-panel. When you've started phpmyadmin from your control-panel you can access it from the web-browser.

Calling variable defined inside one function from another function

def anotherFunction(word):
    for letter in word:              
        print("_", end=" ")

def oneFunction(lists):
    category = random.choice(list(lists.keys()))
    word = random.choice(lists[category])
    return anotherFunction(word)

IntelliJ does not show 'Class' when we right click and select 'New'

There is another case where 'Java Class' don't show, maybe some reserved words exist in the package name, for example:

com.liuyong.package.case

com.liuyong.import.package

It's the same reason as @kuporific 's answer: the package name is invalid.

Convert INT to VARCHAR SQL

CONVERT(DATA_TYPE , Your_Column) is the syntax for CONVERT method in SQL. From this convert function we can convert the data of the Column which is on the right side of the comma (,) to the data type in the left side of the comma (,) Please see below example.

SELECT CONVERT (VARCHAR(10), ColumnName) FROM TableName

How do I remove a key from a JavaScript object?

If you are using Underscore.js or Lodash, there is a function 'omit' that will do it.
http://underscorejs.org/#omit

var thisIsObject= {
    'Cow' : 'Moo',
    'Cat' : 'Meow',
    'Dog' : 'Bark'
};
_.omit(thisIsObject,'Cow'); //It will return a new object

=> {'Cat' : 'Meow', 'Dog' : 'Bark'}  //result

If you want to modify the current object, assign the returning object to the current object.

thisIsObject = _.omit(thisIsObject,'Cow');

With pure JavaScript, use:

delete thisIsObject['Cow'];

Another option with pure JavaScript.

thisIsObject.cow = undefined;

thisIsObject = JSON.parse(JSON.stringify(thisIsObject ));

Display filename before matching line

This is a slight modification from a previous solution. My example looks for stderr redirection in bash scripts: grep '2>' $(find . -name "*.bash")

UITableView Cell selected Color?

To override UITableViewCell's setSelected also works.

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Set background color
    let view = UIView()
    view.backgroundColor = UIColor.redColor()
    selectedBackgroundView = view
}

Getting execute permission to xp_cmdshell

For users that are not members of the sysadmin role on the SQL Server instance you need to do the following actions to grant access to the xp_cmdshell extended stored procedure. In addition if you forgot one of the steps I have listed the error that will be thrown.

  1. Enable the xp_cmdshell procedure

    Msg 15281, Level 16, State 1, Procedure xp_cmdshell, Line 1 SQL Server blocked access to procedure 'sys.xp_cmdshell' of component 'xp_cmdshell' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'xp_cmdshell' by using sp_configure. For more information about enabling 'xp_cmdshell', see "Surface Area Configuration" in SQL Server Books Online.*

  2. Create a login for the non-sysadmin user that has public access to the master database

    Msg 229, Level 14, State 5, Procedure xp_cmdshell, Line 1 The EXECUTE permission was denied on the object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'.*

  3. Grant EXEC permission on the xp_cmdshell stored procedure

    Msg 229, Level 14, State 5, Procedure xp_cmdshell, Line 1 The EXECUTE permission was denied on the object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'.*

  4. Create a proxy account that xp_cmdshell will be run under using sp_xp_cmdshell_proxy_account

    Msg 15153, Level 16, State 1, Procedure xp_cmdshell, Line 1 The xp_cmdshell proxy account information cannot be retrieved or is invalid. Verify that the '##xp_cmdshell_proxy_account##' credential exists and contains valid information.*

It would seem from your error that either step 2 or 3 was missed. I am not familiar with clusters to know if there is anything particular to that setup.

Best way to make WPF ListView/GridView sort on column-header clicking?

MSDN has an easy way to perform sorting on columns with up/down glyphs. The example isn't complete, though - they don't explain how to use the data templates for the glyphs. Below is what I got to work with my ListView. This works on .Net 4.

In your ListView, you have to specify an event handler to fire for a click on the GridViewColumnHeader. My ListView looks like this:

<ListView Name="results" GridViewColumnHeader.Click="results_Click">
    <ListView.View>
        <GridView>
            <GridViewColumn DisplayMemberBinding="{Binding Path=ContactName}">
                <GridViewColumn.Header>
                    <GridViewColumnHeader Content="Contact Name" Padding="5,0,0,0" HorizontalContentAlignment="Left" MinWidth="150" Name="ContactName" />
                </GridViewColumn.Header>
            </GridViewColumn>
            <GridViewColumn DisplayMemberBinding="{Binding Path=PrimaryPhone}">
                <GridViewColumn.Header>
                    <GridViewColumnHeader Content="Contact Number" Padding="5,0,0,0" HorizontalContentAlignment="Left" MinWidth="150" Name="PrimaryPhone"/>
                </GridViewColumn.Header>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>

In your code behind, set up the code to handle the sorting:

// Global objects
BindingListCollectionView blcv;
GridViewColumnHeader _lastHeaderClicked = null;
ListSortDirection _lastDirection = ListSortDirection.Ascending;

// Header click event
void results_Click(object sender, RoutedEventArgs e)
{
    GridViewColumnHeader headerClicked =
    e.OriginalSource as GridViewColumnHeader;
    ListSortDirection direction;

    if (headerClicked != null)
    {
    if (headerClicked.Role != GridViewColumnHeaderRole.Padding)
    {
        if (headerClicked != _lastHeaderClicked)
        {
            direction = ListSortDirection.Ascending;
        }
        else
        {
            if (_lastDirection == ListSortDirection.Ascending)
            {
                direction = ListSortDirection.Descending;
            }
            else
            {
                direction = ListSortDirection.Ascending;
            }
        }

        string header = headerClicked.Column.Header as string;
        Sort(header, direction);

        if (direction == ListSortDirection.Ascending)
        {
            headerClicked.Column.HeaderTemplate =
              Resources["HeaderTemplateArrowUp"] as DataTemplate;
        }
        else
        {
            headerClicked.Column.HeaderTemplate =
              Resources["HeaderTemplateArrowDown"] as DataTemplate;
        }

        // Remove arrow from previously sorted header
        if (_lastHeaderClicked != null && _lastHeaderClicked != headerClicked)
        {
            _lastHeaderClicked.Column.HeaderTemplate = null;
        }

        _lastHeaderClicked = headerClicked;
        _lastDirection = direction;
    }
}

// Sort code
private void Sort(string sortBy, ListSortDirection direction)
{
    blcv.SortDescriptions.Clear();
    SortDescription sd = new SortDescription(sortBy, direction);
    blcv.SortDescriptions.Add(sd);
    blcv.Refresh();
}

And then in your XAML, you need to add two DataTemplates that you specified in the sorting method:

<DataTemplate x:Key="HeaderTemplateArrowUp">
    <DockPanel LastChildFill="True" Width="{Binding ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type GridViewColumnHeader}}}">
        <Path x:Name="arrowUp" StrokeThickness="1" Fill="Gray" Data="M 5,10 L 15,10 L 10,5 L 5,10" DockPanel.Dock="Right" Width="20" HorizontalAlignment="Right" Margin="5,0,5,0" SnapsToDevicePixels="True"/>
        <TextBlock Text="{Binding }" />
    </DockPanel>
</DataTemplate>

<DataTemplate x:Key="HeaderTemplateArrowDown">
    <DockPanel LastChildFill="True" Width="{Binding ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type GridViewColumnHeader}}}">
        <Path x:Name="arrowDown" StrokeThickness="1" Fill="Gray"  Data="M 5,5 L 10,10 L 15,5 L 5,5" DockPanel.Dock="Right" Width="20" HorizontalAlignment="Right" Margin="5,0,5,0" SnapsToDevicePixels="True"/>
        <TextBlock Text="{Binding }" />
    </DockPanel>
</DataTemplate>

Using the DockPanel with LastChildFill set to true will keep the glyph on the right of the header and let the label fill the rest of the space. I bound the DockPanel width to the ActualWidth of the GridViewColumnHeader because my columns have no width, which lets them autofit to the content. I did set MinWidths on the columns, though, so that the glyph doesn't cover up the column title. The TextBlock Text is set to an empty binding which displays the column name specified in the header.

Simulate a click on 'a' element using javascript/jquery

Use this code to click:

$("#gift-close").click();

Invalid self signed SSL cert - "Subject Alternative Name Missing"

If you want to run your server localhost, you need to setup CN = localhost and DNS.1 = localhost.

[req]
default_bits = 2048
default_md = sha256
distinguished_name = req_distinguished_name
prompt = no
prompt = no
x509_extensions = v3_req

[req_distinguished_name]
C = BR
CN = localhost
[email protected]
L = Sao Paulo
O = example.com
OU = example.com
ST = Sao Paulo

[v3_req]
authorityKeyIdentifier = keyid, issuer
basicConstraints = CA:FALSE
extendedKeyUsage = serverAuth
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = localhost

How can I pass a parameter to a t-sql script?

Two options save vijay.sql

declare
begin
execute immediate 
'CREATE TABLE DMS_POP_WKLY_REFRESH_'||to_char(sysdate,'YYYYMMDD')||' NOLOGGING PARALLEL AS
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
       sel.tactical_select_executive_flag,
       sel.agent_name,
       res.DMS_RESIGN_CAMPAIGN_CODE,
       pclub.tactical_select_flag
FROM   spineowner.pop_wkly_refresh_20100201 wk,
       dms_bb_coverage_102009 bbc,
       dms_select_executive_group sel,
       DMS_RESIGN_CAMPAIGN_26052009 res,
       DMS_PRIORITY_CLUB pclub
WHERE  wk.mpn = bbc.mpn(+)
AND    wk.mpn = sel.mpn (+)
AND    wk.mpn = res.mpn (+)
AND    wk.mpn = pclub.mpn (+)'
end;
/

The above will generate table names automatically based on sysdate. If you still need to pass as variable, then save vijay.sql as

declare
begin
execute immediate 
'CREATE TABLE DMS_POP_WKLY_REFRESH_'||&1||' NOLOGGING PARALLEL AS
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
       sel.tactical_select_executive_flag,
       sel.agent_name,
       res.DMS_RESIGN_CAMPAIGN_CODE,
       pclub.tactical_select_flag
FROM   spineowner.pop_wkly_refresh_20100201 wk,
       dms_bb_coverage_102009 bbc,
       dms_select_executive_group sel,
       DMS_RESIGN_CAMPAIGN_26052009 res,
       DMS_PRIORITY_CLUB pclub
WHERE  wk.mpn = bbc.mpn(+)
AND    wk.mpn = sel.mpn (+)
AND    wk.mpn = res.mpn (+)
AND    wk.mpn = pclub.mpn (+)'
end;
/

and then run as sqlplus -s username/password @vijay.sql '20100101'

How to encode the plus (+) symbol in a URL

In order to encode + value using JavaScript, you can use encodeURIComponent function.

Example:

_x000D_
_x000D_
var url = "+11";
var encoded_url = encodeURIComponent(url);
console.log(encoded_url)
_x000D_
_x000D_
_x000D_

Insert content into iFrame

This should do what you want:

$("#iframe").ready(function() {
    var body = $("#iframe").contents().find("body");
    body.append('Test');
});

Check this JSFiddle for working demo.

Edit: You can of course do it one line style:

$("#iframe").contents().find("body").append('Test');

Create a Maven project in Eclipse complains "Could not resolve archetype"

Goto Preferences: -> Maven

1. check Download Artifact Source
2. check Download Artifact JavaDoc

Remove all spaces from a string in SQL Server

It seems that everybody keeps referring to a single REPLACE function. Or even many calls of a REPLACE function. But when you have dynamic output with an unknown number of spaces, it wont work. Anybody that deals with this issue on a regular basis knows that REPLACE will only remove a single space, NOT ALL, as it should. And LTRIM and RTRIM seem to have the same issue. Leave it to Microsoft. Here's a sample output that uses a WHILE Loop to remove ALL CHAR(32) values (space).

DECLARE @INPUT_VAL  VARCHAR(8000)
DECLARE @OUTPUT_VAL VARCHAR(8000)

SET @INPUT_VAL = '      C               A                         '
SET @OUTPUT_VAL = @INPUT_VAL
WHILE CHARINDEX(CHAR(32), @OUTPUT_VAL) > 0 BEGIN
    SET @OUTPUT_VAL = REPLACE(@INPUT_VAL, CHAR(32), '')
END

PRINT 'START:' + @INPUT_VAL + ':END'
PRINT 'START:' + @OUTPUT_VAL + ':END'

Here's the output of the above code:

START:      C               A                         :END
START:CA:END

Now to take it a step further and utilize it in an UPDATE or SELECT statement, change it to a udf.

CREATE FUNCTION udf_RemoveSpaces (@INPUT_VAL    VARCHAR(8000))
RETURNS VARCHAR(8000)
AS 
BEGIN

DECLARE @OUTPUT_VAL VARCHAR(8000)
SET @OUTPUT_VAL = @INPUT_VAL
-- ITTERATE THROUGH STRING TO LOOK FOR THE ASCII VALUE OF SPACE (CHAR(32)) REPLACE IT WITH BLANK, NOT NULL
WHILE CHARINDEX(CHAR(32), @OUTPUT_VAL) > 0 BEGIN
    SET @OUTPUT_VAL = REPLACE(@INPUT_VAL, CHAR(32), '')
END

RETURN @OUTPUT_VAL
END

Then utilize the function in a SELECT or INSERT statement:

UPDATE A
SET STATUS_REASON_CODE = WHATEVER.dbo.udf_RemoveSpaces(STATUS_REASON_CODE)
FROM WHATEVER..ACCT_INFO A
WHERE A.SOMEVALUE = @SOMEVALUE

INSERT INTO SOMETABLE
(STATUS_REASON_CODE)
SELECT WHATEVER.dbo.udf_RemoveSpaces(STATUS_REASON_CODE)
FROM WHATEVER..ACCT_INFO A
WHERE A.SOMEVALUE = @SOMEVALUE

Conditional Logic on Pandas DataFrame

In [1]: df
Out[1]:
   data
0     1
1     2
2     3
3     4

You want to apply a function that conditionally returns a value based on the selected dataframe column.

In [2]: df['data'].apply(lambda x: 'true' if x <= 2.5 else 'false')
Out[2]:
0     true
1     true
2    false
3    false
Name: data

You can then assign that returned column to a new column in your dataframe:

In [3]: df['desired_output'] = df['data'].apply(lambda x: 'true' if x <= 2.5 else 'false')

In [4]: df
Out[4]:
   data desired_output
0     1           true
1     2           true
2     3          false
3     4          false

CSS Select box arrow style

Please follow the way like below:

_x000D_
_x000D_
.selectParent {_x000D_
 width:120px;_x000D_
 overflow:hidden;   _x000D_
}_x000D_
.selectParent select { _x000D_
 display: block;_x000D_
 width: 100%;_x000D_
 padding: 2px 25px 2px 2px; _x000D_
 border: none; _x000D_
 background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") right center no-repeat; _x000D_
 appearance: none; _x000D_
 -webkit-appearance: none;_x000D_
 -moz-appearance: none; _x000D_
}_x000D_
.selectParent.left select {_x000D_
 direction: rtl;_x000D_
 padding: 2px 2px 2px 25px;_x000D_
 background-position: left center;_x000D_
}_x000D_
/* for IE and Edge */ _x000D_
select::-ms-expand { _x000D_
 display: none; _x000D_
}
_x000D_
<div class="selectParent">_x000D_
  <select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
   </select>_x000D_
</div>_x000D_
<br />_x000D_
<div class="selectParent left">_x000D_
  <select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Auto-Submit Form using JavaScript

A simple solution for a delayed auto submit:

<body onload="setTimeout(function() { document.frm1.submit() }, 5000)">
   <form action="https://www.google.com" name="frm1">
      <input type="hidden" name="q" value="Hello world" />
   </form>
</body>

How can I get all a form's values that would be submitted without submitting

For those who don't use jQuery, below is my vanilla JavaScript function to create a form data object that can be accessed like any common object, unlike new FormData(form).

_x000D_
_x000D_
var oFormData = {_x000D_
  'username': 'Minnie',_x000D_
  'phone': '88889999',_x000D_
  'avatar': '',_x000D_
  'gender': 'F',_x000D_
  'private': 1,_x000D_
  'friends': ['Dick', 'Harry'],_x000D_
  'theme': 'dark',_x000D_
  'bio': 'A friendly cartoon mouse.'_x000D_
};_x000D_
_x000D_
function isObject(arg) {_x000D_
  return Object.prototype.toString.call(arg)==='[object Object]';_x000D_
}_x000D_
_x000D_
function formDataToObject(elForm) {_x000D_
  if (!elForm instanceof Element) return;_x000D_
  var fields = elForm.querySelectorAll('input, select, textarea'),_x000D_
    o = {};_x000D_
  for (var i=0, imax=fields.length; i<imax; ++i) {_x000D_
    var field = fields[i],_x000D_
      sKey = field.name || field.id;_x000D_
    if (field.type==='button' || field.type==='image' || field.type==='submit' || !sKey) continue;_x000D_
    switch (field.type) {_x000D_
      case 'checkbox':_x000D_
        o[sKey] = +field.checked;_x000D_
        break;_x000D_
      case 'radio':_x000D_
        if (o[sKey]===undefined) o[sKey] = '';_x000D_
        if (field.checked) o[sKey] = field.value;_x000D_
        break;_x000D_
      case 'select-multiple':_x000D_
        var a = [];_x000D_
        for (var j=0, jmax=field.options.length; j<jmax; ++j) {_x000D_
          if (field.options[j].selected) a.push(field.options[j].value);_x000D_
        }_x000D_
        o[sKey] = a;_x000D_
        break;_x000D_
      default:_x000D_
        o[sKey] = field.value;_x000D_
    }_x000D_
  }_x000D_
  alert('Form data:\n\n' + JSON.stringify(o, null, 2));_x000D_
  return o;_x000D_
}_x000D_
_x000D_
function populateForm(o) {_x000D_
  if (!isObject(o)) return;_x000D_
  for (var i in o) {_x000D_
    var el = document.getElementById(i) || document.querySelector('[name=' + i + ']');_x000D_
    if (el.type==='radio') el = document.querySelectorAll('[name=' + i + ']');_x000D_
    switch (typeof o[i]) {_x000D_
      case 'number':_x000D_
        el.checked = o[i];_x000D_
        break;_x000D_
      case 'object':_x000D_
        if (el.options && o[i] instanceof Array) {_x000D_
          for (var j=0, jmax=el.options.length; j<jmax; ++j) {_x000D_
            if (o[i].indexOf(el.options[j].value)>-1) el.options[j].selected = true;_x000D_
          }_x000D_
        }_x000D_
        break;_x000D_
      default:_x000D_
        if (el instanceof NodeList) {_x000D_
          for (var j=0, jmax=el.length; j<jmax; ++j) {_x000D_
            if (el[j].value===o[i]) el[j].checked = true;_x000D_
          }_x000D_
        } else {_x000D_
          el.value = o[i];_x000D_
        }_x000D_
    }_x000D_
  }_x000D_
}
_x000D_
form {_x000D_
  border: 1px solid #000;_x000D_
}_x000D_
_x000D_
tr {_x000D_
  vertical-align: top;_x000D_
}
_x000D_
<form id="profile" action="formdata.html" method="get">_x000D_
  <table>_x000D_
    <tr>_x000D_
      <td><label for="username">Username:</label></td>_x000D_
      <td><input type="text" id="username" name="username" value="Tom"></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td><label for="phone">Phone:</label></td>_x000D_
      <td><input type="number" id="phone" name="phone" value="7672676"></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td><label for="avatar">Avatar:</label></td>_x000D_
      <td><input type="file" id="avatar" name="avatar"></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td><label>Gender:</label></td>_x000D_
      <td>_x000D_
        <input type="radio" id="gender-m" name="gender" value="M"> <label for="gender-m">Male</label><br>_x000D_
        <input type="radio" id="gender-f" name="gender" value="F"> <label for="gender-f">Female</label>_x000D_
      </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td><label for="private">Private:</label></td>_x000D_
      <td><input type="checkbox" id="private" name="private"></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td><label for="friends">Friends:</label></td>_x000D_
      <td>_x000D_
        <select id="friends" name="friends" size="2" multiple>_x000D_
          <option>Dick</option>_x000D_
          <option>Harry</option>_x000D_
        </select>_x000D_
      </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td><label for="theme">Theme:</label></td>_x000D_
      <td>_x000D_
        <select id="theme" name="theme">_x000D_
          <option value="">-- Select --</option>_x000D_
          <option value="dark">Dark</option>_x000D_
          <option value="light">Light</option>_x000D_
        </select>_x000D_
      </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td><label for="bio">Bio:</label></td>_x000D_
      <td><textarea id="bio" name="bio"></textarea></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td colspan="2">_x000D_
        <input type="submit" value="Submit">_x000D_
        <button>Cancel</button>_x000D_
      </td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</form>_x000D_
<p>_x000D_
  <button onclick="formDataToObject(document.getElementById('profile'))"><strong>Convert to Object</strong></button>_x000D_
  <button onclick="populateForm(oFormData)"><strong>Populate Form</strong></button>_x000D_
</p>
_x000D_
_x000D_
_x000D_

You can also play around with it in this pen: http://codepen.io/thdoan/pen/EyawvR

UPDATE: I also added a function to populate the form with the object returned by formDataToObject().

How to change package name of Android Project in Eclipse?

This is a bug in the Eclipse Android tools.

To fix: Right click on the project, go to Android tools -> Rename application package.

And also check AndroidManifest.xml if it updated correctly. In my case it didn't, and that should solve this problem.

mkdir -p functionality in Python

mkdir -p gives you an error if the file already exists:

$ touch /tmp/foo
$ mkdir -p /tmp/foo
mkdir: cannot create directory `/tmp/foo': File exists

So a refinement to the previous suggestions would be to re-raise the exception if os.path.isdir returns False (when checking for errno.EEXIST).

(Update) See also this highly similar question; I agree with the accepted answer (and caveats) except I would recommend os.path.isdir instead of os.path.exists.

(Update) Per a suggestion in the comments, the full function would look like:

import os
def mkdirp(directory):
    if not os.path.isdir(directory):
        os.makedirs(directory) 

The given key was not present in the dictionary. Which key?

In the general case, the answer is No.

However, you can set the debugger to break at the point where the exception is first thrown. At that time, the key which was not present will be accessible as a value in the call stack.

In Visual Studio, this option is located here:

Debug → Exceptions... → Common Language Runtime Exceptions → System.Collections.Generic

There, you can check the Thrown box.


For more specific instances where information is needed at runtime, provided your code uses IDictionary<TKey, TValue> and not tied directly to Dictionary<TKey, TValue>, you can implement your own dictionary class which provides this behavior.

Formatting floats in a numpy array

In order to make numpy display float arrays in an arbitrary format, you can define a custom function that takes a float value as its input and returns a formatted string:

In [1]: float_formatter = "{:.2f}".format

The f here means fixed-point format (not 'scientific'), and the .2 means two decimal places (you can read more about string formatting here).

Let's test it out with a float value:

In [2]: float_formatter(1.234567E3)
Out[2]: '1234.57'

To make numpy print all float arrays this way, you can pass the formatter= argument to np.set_printoptions:

In [3]: np.set_printoptions(formatter={'float_kind':float_formatter})

Now numpy will print all float arrays this way:

In [4]: np.random.randn(5) * 10
Out[4]: array([5.25, 3.91, 0.04, -1.53, 6.68]

Note that this only affects numpy arrays, not scalars:

In [5]: np.pi
Out[5]: 3.141592653589793

It also won't affect non-floats, complex floats etc - you will need to define separate formatters for other scalar types.

You should also be aware that this only affects how numpy displays float values - the actual values that will be used in computations will retain their original precision.

For example:

In [6]: a = np.array([1E-9])

In [7]: a
Out[7]: array([0.00])

In [8]: a == 0
Out[8]: array([False], dtype=bool)

numpy prints a as if it were equal to 0, but it is not - it still equals 1E-9.

If you actually want to round the values in your array in a way that affects how they will be used in calculations, you should use np.round, as others have already pointed out.

Bootstrap 3 .img-responsive images are not responsive inside fieldset in FireFox

For my issue, I didn't want my images scaled to 100% when they weren't intended to be as large as the container.

For my xs container (<768px as .container), not having a fixed width drove the issue, so I put one back on to it (less the 15px col padding).

// Helps bootstrap 3.0 keep images constrained to container width when width isn't set a fixed value (below 768px), while avoiding all images at 100% width.
// NOTE: proper function relies on there being no inline styling on the element being given a defined width ( '.container'  )

function setWidth() {
    width_val = $( window ).width();
    if( width_val < 768 ) {
        $( '.container' ).width( width_val - 30 );
    } else {
        $( '.container' ).removeAttr( 'style' );
    }
}

setWidth();
$( window ).resize( setWidth );

Zoom to fit all markers in Mapbox or Leaflet

To fit to the visible markers only, I've this method.

fitMapBounds() {
    // Get all visible Markers
    const visibleMarkers = [];
    this.map.eachLayer(function (layer) {
        if (layer instanceof L.Marker) {
            visibleMarkers.push(layer);
        }
    });

    // Ensure there's at least one visible Marker
    if (visibleMarkers.length > 0) {

        // Create bounds from first Marker then extend it with the rest
        const markersBounds = L.latLngBounds([visibleMarkers[0].getLatLng()]);
        visibleMarkers.forEach((marker) => {
            markersBounds.extend(marker.getLatLng());
        });

        // Fit the map with the visible markers bounds
        this.map.flyToBounds(markersBounds, {
            padding: L.point(36, 36), animate: true,
        });
    }
}

What's a decent SFTP command-line client for windows?

WinSCP can be called from batch file:

"C:\Program Files\WinSCP\WinSCP.exe" /console

Example commands:

option batch on 
option confirm off  
option transfer binary 
open sftp://username@hostname:port -hostkey="ssh-rsa " 

C# equivalent of C++ vector, with contiguous memory?

You could use a List<T> and when T is a value type it will be allocated in contiguous memory which would not be the case if T is a reference type.

Example:

List<int> integers = new List<int>();
integers.Add(1);
integers.Add(4);
integers.Add(7);

int someElement = integers[1];

Correlation between two vectors?

To perform a linear regression between two vectors x and y follow these steps:

[p,err] = polyfit(x,y,1);   % First order polynomial
y_fit = polyval(p,x,err);   % Values on a line
y_dif = y - y_fit;          % y value difference (residuals)
SSdif = sum(y_dif.^2);      % Sum square of difference
SStot = (length(y)-1)*var(y);   % Sum square of y taken from variance
rsq = 1-SSdif/SStot;        % Correlation 'r' value. If 1.0 the correlelation is perfect

For x=[10;200;7;150] and y=[0.001;0.45;0.0007;0.2] I get rsq = 0.9181.

Reference URL: http://www.mathworks.com/help/matlab/data_analysis/linear-regression.html

How to convert DataTable to class Object?

It is Vb.Net version:

Public Class Test
Public Property id As Integer
Public Property name As String
Public Property address As String
Public Property createdDate As Date

End Class

  Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim x As Date = Now

    Debug.WriteLine("Begin: " & DateDiff(DateInterval.Second, x, Now) & "-" & Now)

    Dim dt As New DataTable
    dt.Columns.Add("id")
    dt.Columns.Add("name")
    dt.Columns.Add("address")
    dt.Columns.Add("createdDate")

    For i As Integer = 0 To 100000
        dt.Rows.Add(i, "name - " & i, "address - " & i, DateAdd(DateInterval.Second, i, Now))
    Next

    Debug.WriteLine("Datatable created: " & DateDiff(DateInterval.Second, x, Now) & "-" & Now)


    Dim items As IList(Of Test) = dt.AsEnumerable().[Select](Function(row) New _
            Test With {
                        .id = row.Field(Of String)("id"),
                        .name = row.Field(Of String)("name"),
                        .address = row.Field(Of String)("address"),
                        .createdDate = row.Field(Of String)("createdDate")
                       }).ToList()

    Debug.WriteLine("List created: " & DateDiff(DateInterval.Second, x, Now) & "-" & Now)

    Debug.WriteLine("Complated")

End Sub

How to Pass data from child to parent component Angular

Register the EventEmitter in your child component as the @Output:

@Output() onDatePicked = new EventEmitter<any>();

Emit value on click:

public pickDate(date: any): void {
    this.onDatePicked.emit(date);
}

Listen for the events in your parent component's template:

<div>
    <calendar (onDatePicked)="doSomething($event)"></calendar>
</div>

and in the parent component:

public doSomething(date: any):void {
    console.log('Picked date: ', date);
}

It's also well explained in the official docs: Component interaction.

SQL Server database restore error: specified cast is not valid. (SqlManagerUI)

Below can be 2 reasons for this issue:

  1. Backup taken on SQL 2012 and Restore Headeronly was done in SQL 2008 R2

  2. Backup media is corrupted.

If we run below command, we can find actual error always:

restore headeronly
from disk = 'C:\Users\Public\Database.bak'

Give complete location of your database file in the quot

Hope it helps

MATLAB - multiple return values from a function?

Change the function that you get one single Result=[array, listp, freep]. So there is only one result to be displayed

Use of "instanceof" in Java

instanceof can be used to determine the actual type of an object:

class A { }  
class C extends A { } 
class D extends A { } 

public static void testInstance(){
    A c = new C();
    A d = new D();
    Assert.assertTrue(c instanceof A && d instanceof A);
    Assert.assertTrue(c instanceof C && d instanceof D);
    Assert.assertFalse(c instanceof D);
    Assert.assertFalse(d instanceof C);
}

What is Activity.finish() method doing exactly?

onDestroy() is meant for final cleanup - freeing up resources that you can on your own,closing open connections,readers,writers,etc. If you don't override it, the system does what it has to.

on the other hand, finish() just lets the system know that the programmer wants the current Activity to be finished. And hence, it calls up onDestroy() after that.

Something to note:

it isn't necessary that only a call to finish() triggers a call to onDestroy(). No. As we know, the android system is free to kill activities if it feels that there are resources needed by the current Activity that are needed to be freed.

ImportError: cannot import name main when running pip --version command in windows7 32 bit

I had the same problem, but uninstall and reinstall with apt and pip didn't work for me.

I saw another solution that presents a easy way to recover pip3 path:

sudo python3 -m pip uninstall pip && sudo apt install python3-pip --reinstall

Django - iterate number in for loop of a template

Also one can use this:

{% if forloop.first %}

or

{% if forloop.last %}

Autoincrement VersionCode with gradle extra properties

A slightly tightened-up version of CommonsWare's excellent answer creates the version file if it doesn't exist:

def Properties versionProps = new Properties()
def versionPropsFile = file('version.properties')
if(versionPropsFile.exists())
    versionProps.load(new FileInputStream(versionPropsFile))
def code = (versionProps['VERSION_CODE'] ?: "0").toInteger() + 1
versionProps['VERSION_CODE'] = code.toString()
versionProps.store(versionPropsFile.newWriter(), null)

defaultConfig {
    versionCode code
    versionName "1.1"
    minSdkVersion 14
    targetSdkVersion 18
}

How enable auto-format code for Intellij IDEA?

Per the comment of Larson, this is now possible with the save-actions plugin.

How to parse JSON to receive a Date object in JavaScript?

What's wrong with:

new Date(1293034567877);

This returns for me "Wed Dec 22 2010 16:16:07 GMT+0000 (GMT Standard Time)".

Or do you need to get the number out the json?

Remove pattern from string with gsub

Just to point out that there is an approach using functions from the tidyverse, which I find more readable than gsub:

a %>% stringr::str_remove(pattern = ".*_")

tooltips for Button

Simply add a title to your button.

_x000D_
_x000D_
<button title="Hello World!">Sample Button</button>
_x000D_
_x000D_
_x000D_

Using "word-wrap: break-word" within a table

table-layout: fixed will get force the cells to fit the table (and not the other way around), e.g.:

<table style="border: 1px solid black; width: 100%; word-wrap:break-word;
              table-layout: fixed;">
  <tr>
    <td>
        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
    </td>
  </tr>
</table>

jQuery .each() index?

From the jQuery.each() documentation:

.each( function(index, Element) )
    function(index, Element)A function to execute for each matched element.

So you'll want to use:

$('#list option').each(function(i,e){
    //do stuff
});

...where index will be the index and element will be the option element in list

Can I change the viewport meta tag in mobile safari on the fly?

in your <head>

<meta id="viewport"
      name="viewport"
      content="width=1024, height=768, initial-scale=0, minimum-scale=0.25" />

somewhere in your javascript

document.getElementById("viewport").setAttribute("content",
      "initial-scale=0.5; maximum-scale=1.0; user-scalable=0;");

... but good luck with tweaking it for your device, fiddling for hours... and i'm still not there!

source

QtCreator: No valid kits found

Though OP is asking about Windows, this error also occurs on Ubuntu Linux and Google lists this result first when you search for the error"QtCreator: No valid kits found".

On Ubuntu this is solved by running:

For Qt5:

sudo apt-get install qt5-default

For Qt4:

sudo apt-get install qt4-dev-tools libqt4-dev libqt4-core libqt4-gui

This question is answered here and here, though those entries are less SEO-friendly...

Pass connection string to code-first DbContext

In your DbContext, create a default constructor for your DbContext and inherit the base like this:

    public myDbContext()
        : base("MyConnectionString")  // connectionstring name define in your web.config
    {
    }

Linux command to list all available commands and aliases

It's useful to list the commands based on the keywords associated with the command.

Use: man -k "your keyword"

feel free to combine with:| grep "another word"

for example, to find a text editor: man -k editor | grep text

How can I change property names when serializing with Json.net?

There is still another way to do it, which is using a particular NamingStrategy, which can be applied to a class or a property by decorating them with [JSonObject] or [JsonProperty].

There are predefined naming strategies like CamelCaseNamingStrategy, but you can implement your own ones.

The implementation of different naming strategies can be found here: https://github.com/JamesNK/Newtonsoft.Json/tree/master/Src/Newtonsoft.Json/Serialization

How do you add multi-line text to a UIButton?

To fix title label's spacing to the button, set titleEdgeInsets and other properties before setTitle:

    let set = UIButton()
    sut.titleLabel?.lineBreakMode = .byWordWrapping
    sut.titleLabel?.numberOfLines = 0
    sut.titleEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 20, right: 20)
    sut.setTitle("Dummy button with long long long long long long long long title", for: .normal)

P.S. I tested setting titleLabel?.textAlignment is not necessary and the title aligns in .natural.

MongoDB Aggregation: How to get total records count?

Since v.3.4 (i think) MongoDB has now a new aggregation pipeline operator named 'facet' which in their own words:

Processes multiple aggregation pipelines within a single stage on the same set of input documents. Each sub-pipeline has its own field in the output document where its results are stored as an array of documents.

In this particular case, this means that one can do something like this:

$result = $collection->aggregate([
  { ...execute queries, group, sort... },
  { ...execute queries, group, sort... },
  { ...execute queries, group, sort... },
  $facet: {
    paginatedResults: [{ $skip: skipPage }, { $limit: perPage }],
    totalCount: [
      {
        $count: 'count'
      }
    ]
  }
]);

The result will be (with for ex 100 total results):

[
  {
    "paginatedResults":[{...},{...},{...}, ...],
    "totalCount":[{"count":100}]
  }
]

Access denied for user 'root'@'localhost' while attempting to grant privileges. How do I grant privileges?

Basically this error comes when you have not specified a password, it means that you have an incorrect password listed in some option file.

Read this DOC on understanding how to assign and manage Passwords to accounts.

Also , Check if the permission on the folder /var/lib/mysql/mysql is 711 or not.

Best way to include CSS? Why use @import?

I think the key in this are the two reasons why you are actually writing multiple CSS style sheets.

  1. You write multiple sheets because the different pages of your website require different CSS definitions. Or at least not all of them require all the CSS definitions one other pages require. So you split up the CSS files in order to optimize what sheets are load on the different pages and avoid loading too many CSS definitions.
  2. The second reason that comes to mind is that your CSS is getting that large that is becomes clumsy to handle and in order to make it easier to maintain the large CSS file you split them up into multiple CSS files.

For the first reason the additional <link> tag would apply as this allows you to load different set of CSS files for different pages.

For the second reason the @import statement appears as the most handy because you get multiple CSS files but the files loaded are always the same.

From the perspective of the loading time there is no different. The browser has to check and download the seperated CSS files no matter how they are implemented.

Using git commit -a with vim

  1. In vim, you save a file with :wEnter while in the normal mode (you get to the normal mode by pressing Esc).
  2. You close your file with :q while in the normal mode.

You can combine both these actions and do Esc:wqEnter to save the commit and quit vim.

As an alternate to the above, you can also press ZZ while in the normal mode, which will save the file and exit vim. This is also easier for some people as it's the same key pressed twice.

Replace one character with another in Bash

Use parameter substitution:

string=${string// /.}

Android Studio - Unable to find valid certification path to requested target

Since this is caused by a misconfiguration of the network you are operating on just setup your smartphone to share its internet connection using USB tethering and use it to download the missing packages.

Error - replacement has [x] rows, data has [y]

You could use cut

 df$valueBin <- cut(df$value, c(-Inf, 250, 500, 1000, 2000, Inf), 
    labels=c('<=250', '250-500', '500-1,000', '1,000-2,000', '>2,000'))

data

 set.seed(24)
 df <- data.frame(value= sample(0:2500, 100, replace=TRUE))

How to check whether a Storage item is set?

I've used in my project and works perfectly for me

var returnObjName= JSON.parse(localStorage.getItem('ObjName'));
if(returnObjName && Object.keys(returnObjName).length > 0){
   //Exist data in local storage
}else{
  //Non Exist data block
}

android activity has leaked window com.android.internal.policy.impl.phonewindow$decorview Issue

I got this error but it is resolved interesting. As first, i got this error at api level 17. When i call a thread (AsyncTask or others) without progress dialog then i call an other thread method again using progress dialog, i got that crash and the reason is about usage of progress dialog.

In my case, there are two results that;

  • I took show(); method of progress dialog before first thread starts then i took dismiss(); method of progress dialog before last thread ends.

So :

ProgresDialog progressDialog = new ...

//configure progressDialog 

progressDialog.show();

start firstThread {
...
}

...

start lastThread {
...
} 

//be sure to finish threads

progressDialog.dismiss();
  • This is so strange but that error has an ability about destroy itself at least for me :)

Where is the Java SDK folder in my computer? Ubuntu 12.04

$whereis java
java: /usr/bin/java /usr/bin/X11/java /usr/share/java     /usr/share/man/man1/java.1.gz
$cd /usr/bin
$ls -l java
lrwxrwxrwx 1 root root 22 Apr 15  2014 java -> /etc/alternatives/java
$ls -l /etc/alternatives/java
lrwxrwxrwx 1 root root 39 Apr 15  2014 /etc/alternatives/java ->     /usr/lib/jvm/java-7-oracle/jre/bin/java

So,JDK's real location is /usr/lib/jvm/java-7-oracle/

How to picture "for" loop in block representation of algorithm

The Algorithm for given flow chart :

enter image description here

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Step :01

  • Start

Step :02 [Variable initialization]

  • Set counter: i<----K [Where K:Positive Number]

Step :03[Condition Check]

  • If condition True then Do your task, set i=i+N and go to Step :03 [Where N:Positive Number]
  • If condition False then go to Step :04

Step:04

  • Stop

Measuring Query Performance : "Execution Plan Query Cost" vs "Time Taken"

Use SET STATISTICS TIME ON

above your query.

Below near result tab you can see a message tab. There you can see the time.

How do you replace double quotes with a blank space in Java?

Use String#replace().

To replace them with spaces (as per your question title):

System.out.println("I don't like these \"double\" quotes".replace("\"", " "));

The above can also be done with characters:

System.out.println("I don't like these \"double\" quotes".replace('"', ' '));

To remove them (as per your example):

System.out.println("I don't like these \"double\" quotes".replace("\"", ""));

Angular EXCEPTION: No provider for Http

Import HttpModule in your app.module.ts file.

import { HttpModule } from '@angular/http';
import { YourHttpTestService } from '../services/httpTestService';

Also remember to declare HttpModule under imports like below:

imports: [
    BrowserModule,
    HttpModule
  ],

Login to website, via C#

You can continue using WebClient to POST (instead of GET, which is the HTTP verb you're currently using with DownloadString), but I think you'll find it easier to work with the (slightly) lower-level classes WebRequest and WebResponse.

There are two parts to this - the first is to post the login form, the second is recovering the "Set-cookie" header and sending that back to the server as "Cookie" along with your GET request. The server will use this cookie to identify you from now on (assuming it's using cookie-based authentication which I'm fairly confident it is as that page returns a Set-cookie header which includes "PHPSESSID").


POSTing to the login form

Form posts are easy to simulate, it's just a case of formatting your post data as follows:

field1=value1&field2=value2

Using WebRequest and code I adapted from Scott Hanselman, here's how you'd POST form data to your login form:

string formUrl = "http://www.mmoinn.com/index.do?PageModule=UsersAction&Action=UsersLogin"; // NOTE: This is the URL the form POSTs to, not the URL of the form (you can find this in the "action" attribute of the HTML's form tag
string formParams = string.Format("email_address={0}&password={1}", "your email", "your password");
string cookieHeader;
WebRequest req = WebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
    os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];

Here's an example of what you should see in the Set-cookie header for your login form:

PHPSESSID=c4812cffcf2c45e0357a5a93c137642e; path=/; domain=.mmoinn.com,wowmine_referer=directenter; path=/; domain=.mmoinn.com,lang=en; path=/;domain=.mmoinn.com,adt_usertype=other,adt_host=-

GETting the page behind the login form

Now you can perform your GET request to a page that you need to be logged in for.

string pageSource;
string getUrl = "the url of the page behind the login";
WebRequest getRequest = WebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
WebResponse getResponse = getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
    pageSource = sr.ReadToEnd();
}

EDIT:

If you need to view the results of the first POST, you can recover the HTML it returned with:

using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
    pageSource = sr.ReadToEnd();
}

Place this directly below cookieHeader = resp.Headers["Set-cookie"]; and then inspect the string held in pageSource.

findViewByID returns null

Set the activity content from a layout resource. ie.,setContentView(R.layout.basicXml);

How to select unique records by SQL

Select Eff_st from ( select EFF_ST,ROW_NUMBER() over(PARTITION BY eff_st) XYZ - from ABC.CODE_DIM

) where XYZ= 1 order by EFF_ST fetch first 5 row only

Delete files in subfolder using batch script

Use powershell inside your bat file

PowerShell Remove-Item c:\scripts\* -include *.txt -exclude *test* -force -recurse

You can also exclude from removing some specific folder or file:

PowerShell Remove-Item C:/*  -Exclude WINDOWS,autoexec.bat -force -recurse

Change WPF controls from a non-main thread using Dispatcher.Invoke

japf has answer it correctly. Just in case if you are looking at multi-line actions, you can write as below.

Application.Current.Dispatcher.BeginInvoke(
  DispatcherPriority.Background,
  new Action(() => { 
    this.progressBar.Value = 50;
  }));

Information for other users who want to know about performance:

If your code NEED to be written for high performance, you can first check if the invoke is required by using CheckAccess flag.

if(Application.Current.Dispatcher.CheckAccess())
{
    this.progressBar.Value = 50;
}
else
{
    Application.Current.Dispatcher.BeginInvoke(
      DispatcherPriority.Background,
      new Action(() => { 
        this.progressBar.Value = 50;
      }));
}

Note that method CheckAccess() is hidden from Visual Studio 2015 so just write it without expecting intellisense to show it up. Note that CheckAccess has overhead on performance (overhead in few nanoseconds). It's only better when you want to save that microsecond required to perform the 'invoke' at any cost. Also, there is always option to create two methods (on with invoke, and other without) when calling method is sure if it's in UI Thread or not. It's only rarest of rare case when you should be looking at this aspect of dispatcher.

How to resolve the "ADB server didn't ACK" error?

Try the following:

  • Close Eclipse.
  • Restart your phone.
  • End adb.exe process in Task Manager (Windows). In Mac, force close in Activity Monitor.
  • Issue kill and start command in \platform-tools\
    • C:\sdk\platform-tools>adb kill-server
    • C:\sdk\platform-tools>adb start-server
  • If it says something like 'started successfully', you are good.

Java Garbage Collection Log messages

Most of it is explained in the GC Tuning Guide (which you would do well to read anyway).

The command line option -verbose:gc causes information about the heap and garbage collection to be printed at each collection. For example, here is output from a large server application:

[GC 325407K->83000K(776768K), 0.2300771 secs]
[GC 325816K->83372K(776768K), 0.2454258 secs]
[Full GC 267628K->83769K(776768K), 1.8479984 secs]

Here we see two minor collections followed by one major collection. The numbers before and after the arrow (e.g., 325407K->83000K from the first line) indicate the combined size of live objects before and after garbage collection, respectively. After minor collections the size includes some objects that are garbage (no longer alive) but that cannot be reclaimed. These objects are either contained in the tenured generation, or referenced from the tenured or permanent generations.

The next number in parentheses (e.g., (776768K) again from the first line) is the committed size of the heap: the amount of space usable for java objects without requesting more memory from the operating system. Note that this number does not include one of the survivor spaces, since only one can be used at any given time, and also does not include the permanent generation, which holds metadata used by the virtual machine.

The last item on the line (e.g., 0.2300771 secs) indicates the time taken to perform the collection; in this case approximately a quarter of a second.

The format for the major collection in the third line is similar.

The format of the output produced by -verbose:gc is subject to change in future releases.

I'm not certain why there's a PSYoungGen in yours; did you change the garbage collector?

How to refresh page on back button click?

You can use the following to refresh the page by clicking the back button:

window.addEventListener('popstate', () => {
  location.reload();
}, false);

How can I run an external command asynchronously from Python?

subprocess.Popen does exactly what you want.

from subprocess import Popen
p = Popen(['watch', 'ls']) # something long running
# ... do other stuff while subprocess is running
p.terminate()

(Edit to complete the answer from comments)

The Popen instance can do various other things like you can poll() it to see if it is still running, and you can communicate() with it to send it data on stdin, and wait for it to terminate.

How do I remove the old history from a git repository?

Maybe it's too late to post a reply, but as this page is the first Google's result, it may still be helpful.

If you want to free some space in your git repo, but do not want to rebuild all your commits (rebase or graft), and still be able to push/pull/merge from people who has the full repo, you may use the git clone shallow clone (--depth parameter).

; Clone the original repo into limitedRepo
git clone file:///path_to/originalRepo limitedRepo --depth=10

; Remove the original repo, to free up some space
rm -rf originalRepo
cd limitedRepo
git remote rm origin

You may be able to shallow your existing repo, by following these steps:

; Shallow to last 5 commits
git rev-parse HEAD~5 > .git/shallow

; Manually remove all other branches, tags and remotes that refers to old commits

; Prune unreachable objects
git fsck --unreachable ; Will show you the list of what will be deleted
git gc --prune=now     ; Will actually delete your data

How to remove all git local tags?

Ps: Older versions of git didn't support clone/push/pull from/to shallow repos.

Why em instead of px?

Pixel is an absolute unit whereas rem/em are relative units. For more: https://drafts.csswg.org/css-values-3/

You should use the relative unit when you want the font-size to be adaptive according to the system's font size because the system provides the font-size value to the root element which is the HTML element.

In this case, where the webpage is open in google chrome, the font-size to the HTML element is set by chrome, try changing it to see the effect on webpages with fonts of rem/ em units.

enter image description here

If you use px as the unit for fonts, the fonts will not resize whereas the fonts with rem/ em unit will resize when you change the system's font size.

So use px when you want the size to be fixed and use rem/ em when you want the size to be adaptive/ dynamic to the size of the system.

Check string for nil & empty

If you are using Swift 2, here is an example my colleague came up with, which adds isNilOrEmpty property on optional Strings:

protocol OptionalString {}
extension String: OptionalString {}

extension Optional where Wrapped: OptionalString {
    var isNilOrEmpty: Bool {
        return ((self as? String) ?? "").isEmpty
    }
}

You can then use isNilOrEmpty on the optional string itself

func testNilOrEmpty() {
    let nilString:String? = nil
    XCTAssertTrue(nilString.isNilOrEmpty)

    let emptyString:String? = ""
    XCTAssertTrue(emptyString.isNilOrEmpty)

    let someText:String? = "lorem"
    XCTAssertFalse(someText.isNilOrEmpty)
}

A failure occurred while executing com.android.build.gradle.internal.tasks

Solution for:

Caused by 4: com.android.builder.internal.aapt.AaptException: Dependent features configured but no package ID was set.

All feature modules have to apply the library plugin and NOT the application plugin.

build.gradle (:androidApp:feature_A)

apply plugin: 'com.android.library'

It all depends on the stacktrace of each one. Cause 1 WorkExecutionException may be the consequence of other causes. So I suggest reading the full stacktrace from the last cause printed towards the first cause. So if we solve the last cause, it is very likely that we will have fixed the chain of causes from the last to the first.

I attach an example of my stacktrace where the original or concrete problem was in the last cause:

Caused by: org.gradle.workers.internal.DefaultWorkerExecutor$WorkExecutionException: A failure occurred while executing com.android.build.gradle.internal.res.LinkApplicationAndroidResourcesTask$TaskAction

Caused by: com.android.builder.internal.aapt.v2.Aapt2InternalException: AAPT2 aapt2-4.2.0-alpha16-6840111-linux Daemon #0: Unexpected error during link, attempting to stop daemon.

Caused by: java.io.IOException: Unable to make AAPT link command.

Caused by 4: com.android.builder.internal.aapt.AaptException: Dependent features configured but no package ID was set.

GL

Feature Package ID was not set

How to multiply individual elements of a list with a number?

Here is a functional approach using map, itertools.repeat and operator.mul:

import operator
from itertools import repeat


def scalar_multiplication(vector, scalar):
    yield from map(operator.mul, vector, repeat(scalar))

Example of usage:

>>> v = [1, 2, 3, 4]
>>> c = 3
>>> list(scalar_multiplication(v, c))
[3, 6, 9, 12]

What does it mean when an HTTP request returns status code 0?

wininet.dll returns both standard and non-standard status codes that are listed below.

401 - Unauthorized file
403 - Forbidden file
404 - File Not Found
500 - some inclusion or functions may missed
200 - Completed

12002 - Server timeout
12029,12030, 12031 - dropped connections (either web server or DB server)
12152 - Connection closed by server.
13030 - StatusText properties are unavailable, and a query attempt throws an exception

For the status code "zero" are you trying to do a request on a local webpage running on a webserver or without a webserver?

XMLHttpRequest status = 0 and XMLHttpRequest statusText = unknown can help you if you are not running your script on a webserver.

What is the difference between Java RMI and RPC?

The main difference between RPC and RMI is that RMI involves objects. Instead of calling procedures remotely by use of a proxy function, we instead use a proxy object.

There is greater transparency with RMI, namely due the exploitation of objects, references, inheritance, polymorphism, and exceptions as the technology is integrated into the language.

RMI is also more advanced than RPC, allowing for dynamic invocation, where interfaces can change at runtime, and object adaption, which provides an additional layer of abstraction.

How do I revert back to an OpenWrt router configuration?

Some addition to previous comments: 'firstboot' won't be available until you run 'mount_root' command.

So here is a full recap of what needs to be done. All manipulations I did on Windows 8.1.

  • Enter Failsafe mode (hold the reset button on boot for a few seconds)
  • Assign a static IP address, 192.168.1.2, to your PC. Example of a command: netsh interface ip set address name="Ethernet" static 192.168.1.2 255.255.255.0 192.168.1.1
  • Connect to address 192.168.1.1 from telnet (I use PuTTY) and login/password isn't required).
  • Run 'mount_root' (otherwise 'firstboot' won't be available).
  • Run 'firstboot' to reset.
  • Run 'reboot -f' to reboot.

Now you can enter to the router console from a browser. Also don't forget to return your PC from static to DHCP address assignment. Example: netsh interface ip set address name="Ethernet" source=dhcp

Image vs Bitmap class

This is a clarification because I have seen things done in code which are honestly confusing - I think the following example might assist others.

As others have said before - Bitmap inherits from the Abstract Image class

Abstract effectively means you cannot create a New() instance of it.

    Image imgBad1 = new Image();        // Bad - won't compile
    Image imgBad2 = new Image(200,200); // Bad - won't compile

But you can do the following:

    Image imgGood;  // Not instantiated object!
    // Now you can do this
    imgGood = new Bitmap(200, 200);

You can now use imgGood as you would the same bitmap object if you had done the following:

    Bitmap bmpGood = new Bitmap(200,200);

The nice thing here is you can draw the imgGood object using a Graphics object

    Graphics gr = default(Graphics);
    gr = Graphics.FromImage(new Bitmap(1000, 1000));
    Rectangle rect = new Rectangle(50, 50, imgGood.Width, imgGood.Height); // where to draw
    gr.DrawImage(imgGood, rect);

Here imgGood can be any Image object - Bitmap, Metafile, or anything else that inherits from Image!

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

Box shadows can use commas to have multiple effects, just like with background images (in CSS3).

Playing a video in VideoView in Android

To confirm you video is in the correct format (resolution, bitrate, codec, etc.) check with the official documentation - extract below:

Standard definition (Low quality)
Video codec - H.264
Video resolution - 176 x 144 px
Video frame rate - 12 fps
Video bitrate - 56 Kbps
Audio codec - AAC-LC
Audio channels - (mono)
Audio bitrate - 24 Kbps

Standard definition (High quality)
Video codec - H.264
Video resolution - 480 x 360 px
Video frame rate - 30 fps
Video bitrate - 500 Kbps
Audio codec - AAC-LC
Audio channels - 2 (stereo)
Audio bitrate - 128 Kbps

High definition 720p (N/A on all devices)
Video codec - H.264
Video resolution - 1280 x 720 px
Video frame rate - 30 fps
Video bitrate - 2 Mbps
Audio codec - AAC-LC
Audio channels - 2 (stereo)
Audio bitrate - 192 Kbps

Angular HTML binding

If you want that in Angular 2 or Angular 4 and also want to keep inline CSS then you can use

<div [innerHTML]="theHtmlString | keepHtml"></div>

Table with 100% width with equal size columns

<table width="400px">
  <tr>
  <td width="100px"></td>
  <td width="100px"></td>
  <td width="100px"></td>
  <td width="100px"></td>
  </tr>
</table>

For variable number of columns use %

<table width="100%">
  <tr>
  <td width="(100/x)%"></td>
  </tr>
</table>

where 'x' is number of columns

jQuery Set Selected Option Using Next

$('your_select option:selected').next('option').prop('selected', true)

Python's "in" set operator

Sets behave different than dicts, you need to use set operations like issubset():

>>> k
{'ip': '123.123.123.123', 'pw': 'test1234', 'port': 1234, 'debug': True}
>>> set('ip,port,pw'.split(',')).issubset(set(k.keys()))
True
>>> set('ip,port,pw'.split(',')) in set(k.keys())
False

JS search in object values

Came across this problem today and using a modified version of the provided code by epascarello in this thread did the trick, because that version had trouble when the object contained some values others than strings (like a number of booleans for example).

console.log('find: ', findIn(arrayOfObjects, searchKey));

const findIn = (arr, searchKey) => {
 return arr.filter(obj => 
  Object.keys(obj).some(key => {
   if (typeof obj[key] === 'string') {
    return obj[key].includes(searchKey);
   }
  })
 );
};

What is the JavaScript equivalent of var_dump or print_r in PHP?

I wrote this JS function dump() to work like PHP's var_dump(). To show the contents of the variable in an alert window: dump(variable) To show the contents of the variable in the web page: dump(variable, 'body') To just get a string of the variable: dump(variable, 'none')

/* repeatString() returns a string which has been repeated a set number of times */
function repeatString(str, num) {
    out = '';
    for (var i = 0; i < num; i++) {
        out += str;
    }
    return out;
}

/*
dump() displays the contents of a variable like var_dump() does in PHP. dump() is
better than typeof, because it can distinguish between array, null and object.
Parameters:
    v:              The variable
    howDisplay:     "none", "body", "alert" (default)
    recursionLevel: Number of times the function has recursed when entering nested
                    objects or arrays. Each level of recursion adds extra space to the
                    output to indicate level. Set to 0 by default.
Return Value:
    A string of the variable's contents
Limitations:
    Can't pass an undefined variable to dump(). 
    dump() can't distinguish between int and float.
    dump() can't tell the original variable type of a member variable of an object.
    These limitations can't be fixed because these are *features* of JS. However, dump()
*/
function dump(v, howDisplay, recursionLevel) {
    howDisplay = (typeof howDisplay === 'undefined') ? "alert" : howDisplay;
    recursionLevel = (typeof recursionLevel !== 'number') ? 0 : recursionLevel;

    var vType = typeof v;
    var out = vType;

    switch (vType) {
        case "number":
        /* there is absolutely no way in JS to distinguish 2 from 2.0
           so 'number' is the best that you can do. The following doesn't work:
           var er = /^[0-9]+$/;
           if (!isNaN(v) && v % 1 === 0 && er.test(3.0)) {
               out = 'int';
           }
        */
        break;
    case "boolean":
        out += ": " + v;
        break;
    case "string":
        out += "(" + v.length + '): "' + v + '"';
        break;
    case "object":
        //check if null
        if (v === null) {
            out = "null";
        }
        //If using jQuery: if ($.isArray(v))
        //If using IE: if (isArray(v))
        //this should work for all browsers according to the ECMAScript standard:
        else if (Object.prototype.toString.call(v) === '[object Array]') {
            out = 'array(' + v.length + '): {\n';
            for (var i = 0; i < v.length; i++) {
                out += repeatString('   ', recursionLevel) + "   [" + i + "]:  " +
                    dump(v[i], "none", recursionLevel + 1) + "\n";
            }
            out += repeatString('   ', recursionLevel) + "}";
        }
        else {
            //if object
            let sContents = "{\n";
            let cnt = 0;
            for (var member in v) {
                //No way to know the original data type of member, since JS
                //always converts it to a string and no other way to parse objects.
                sContents += repeatString('   ', recursionLevel) + "   " + member +
                    ":  " + dump(v[member], "none", recursionLevel + 1) + "\n";
                cnt++;
            }
            sContents += repeatString('   ', recursionLevel) + "}";
            out += "(" + cnt + "): " + sContents;
        }
        break;
    default:
        out = v;
        break;
    }

    if (howDisplay == 'body') {
        var pre = document.createElement('pre');
        pre.innerHTML = out;
        document.body.appendChild(pre);
    }
    else if (howDisplay == 'alert') {
        alert(out);
    }

    return out;
}

How can I turn a List of Lists into a List in Java 8?

You can use flatMap to flatten the internal lists (after converting them to Streams) into a single Stream, and then collect the result into a list:

List<List<Object>> list = ...
List<Object> flat = 
    list.stream()
        .flatMap(List::stream)
        .collect(Collectors.toList());

Bash scripting missing ']'

You're missing a space after "p1":

if [ -s "p1" ];

R multiple conditions in if statement

Read this thread R - boolean operators && and ||.

Basically, the & is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. && is not, returning a single logical.

What exactly is the meaning of an API?

Conaider this situation:

Mark and Lisa are secretly a couple, and because of age difference they are not allowed to be together. Mark and Lisa meet every night when nobody is watching. They have estabilished their own set of rules how to comunicate when the time comes. He stands in her garden and throws the small rock at her window. Lisa knows that it is time, and responds by waving from the window and opening it afterwards so Mark can climb in. That was example how the API works. The rock is initial request to another end. Another end waves, opens the window which basicaly means "Welcome in!".

API is almost like human language but for computers.

C++: Converting Hexadecimal to Decimal

Well, the C way might be something like ...

#include <stdlib.h>
#include <stdio.h>

int main()
{
        int n;
        scanf("%d", &n);
        printf("%X", n);

        exit(0);
}

What's a concise way to check that environment variables are set in a Unix shell script?

Rather than using external shell scripts I tend to load in functions in my login shell. I use something like this as a helper function to check for environment variables rather than any set variable:

is_this_an_env_variable ()
    local var="$1"
    if env |grep -q "^$var"; then
       return 0
    else
       return 1
    fi
 }

How to get ID of the last updated row in MySQL?

I've found an answer to this problem :)

SET @update_id := 0;
UPDATE some_table SET column_name = 'value', id = (SELECT @update_id := id)
WHERE some_other_column = 'blah' LIMIT 1; 
SELECT @update_id;

EDIT by aefxx

This technique can be further expanded to retrieve the ID of every row affected by an update statement:

SET @uids := null;
UPDATE footable
   SET foo = 'bar'
 WHERE fooid > 5
   AND ( SELECT @uids := CONCAT_WS(',', fooid, @uids) );
SELECT @uids;

This will return a string with all the IDs concatenated by a comma.

Passing string to a function in C - with or without pointers?

Assuming that you meant to write

char *functionname(char *string[256])

Here you are declaring a function that takes an array of 256 pointers to char as argument and returns a pointer to char. Here, on the other hand,

char functionname(char string[256])

You are declaring a function that takes an array of 256 chars as argument and returns a char.

In other words the first function takes an array of strings and returns a string, while the second takes a string and returns a character.

How to change color of Android ListView separator line?

For a single color line use:

list.setDivider(new ColorDrawable(0x99F10529));   //0xAARRGGBB
list.setDividerHeight(1);

It's important that DividerHeight is set after the divider, else you won't get anything.

Passing an array of parameters to a stored procedure

You could use a temp table which the stored procedure expects to exist. This will work on older versions of SQL Server, which do not support XML etc.

CREATE TABLE #temp
(INT myid)
GO
CREATE PROC myproc
AS
BEGIN
    DELETE YourTable
    FROM YourTable                    
    LEFT OUTER JOIN #temp T ON T.myid=s.id
    WHERE s.id IS NULL
END

Java, How to get number of messages in a topic in apache kafka

Use https://prestodb.io/docs/current/connector/kafka-tutorial.html

A super SQL engine, provided by Facebook, that connects on several data sources (Cassandra, Kafka, JMX, Redis ...).

PrestoDB is running as a server with optional workers (there is a standalone mode without extra workers), then you use a small executable JAR (called presto CLI) to make queries.

Once you have configured well the Presto server , you can use traditionnal SQL:

SELECT count(*) FROM TOPIC_NAME;

Fill remaining vertical space - only CSS

You can just add the overflow:auto option:

#second
{
   width:300px;
   height:100%;
   overflow: auto;
   background-color:#9ACD32;
}

What are the time complexities of various data structures?

Arrays

  • Set, Check element at a particular index: O(1)
  • Searching: O(n) if array is unsorted and O(log n) if array is sorted and something like a binary search is used,
  • As pointed out by Aivean, there is no Delete operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirements
  • Similarly, Insert for arrays is basically Set as mentioned in the beginning

ArrayList:

  • Add: Amortized O(1)
  • Remove: O(n)
  • Contains: O(n)
  • Size: O(1)

Linked List:

  • Inserting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Doubly-Linked List:

  • Inserting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Stack:

  • Push: O(1)
  • Pop: O(1)
  • Top: O(1)
  • Search (Something like lookup, as a special operation): O(n) (I guess so)

Queue/Deque/Circular Queue:

  • Insert: O(1)
  • Remove: O(1)
  • Size: O(1)

Binary Search Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(n)

Red-Black Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(log n)

Heap/PriorityQueue (min/max):

  • Find Min/Find Max: O(1)
  • Insert: O(log n)
  • Delete Min/Delete Max: O(log n)
  • Extract Min/Extract Max: O(log n)
  • Lookup, Delete (if at all provided): O(n), we will have to scan all the elements as they are not ordered like BST

HashMap/Hashtable/HashSet:

  • Insert/Delete: O(1) amortized
  • Re-size/hash: O(n)
  • Contains: O(1)

How to find a string inside a entire database?

create procedure usp_find_string(@string as varchar(1000))
as
begin
declare @mincounter as int
declare @maxcounter as int
declare @stmtquery as varchar(1000)
set @stmtquery=''
create table #tmp(tablename varchar(128),columnname varchar(128),rowid int identity)
create table #tablelist(tablename varchar(128),columnname varchar(128))
declare @tmp table(name varchar(128))
declare @tablename as varchar(128)
declare @columnname as varchar(128)

insert into #tmp(tablename,columnname)
select a.name,b.name as columnname from sysobjects a
inner join syscolumns b on a.name=object_name(b.id)
where a.type='u'
and b.xtype in(select xtype from systypes
    where name='text' or name='ntext' or name='varchar' or name='nvarchar' or name='char' or name='nchar')
order by a.name

select @maxcounter=max(rowid),@mincounter=min(rowid) from #tmp 
while(@mincounter <= @maxcounter )
begin
 select @tablename=tablename, @columnname=columnname from #tmp where rowid=@mincounter
 set @stmtquery ='select top 1  ' + '[' +@columnname+']' + ' from ' + '['+@tablename+']' + ' where ' + '['+@columnname+']' + ' like ' + '''%' + @string + '%'''
 insert into @tmp(name) exec(@stmtquery)
 if @@rowcount >0
 insert into #tablelist values(@tablename,@columnname)
 set @mincounter=@mincounter +1
end
select * from #tablelist
end

How to export html table to excel or pdf in php

Either you can use CSV functions or PHPExcel

or you can try like below

<?php
$file="demo.xls";
$test="<table  ><tr><td>Cell 1</td><td>Cell 2</td></tr></table>";
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$file");
echo $test;
?>

The header for .xlsx files is Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

How to create a date and time picker in Android?

Call the time picker dialog in the DatePicker update time method. It'll not be called at the same time but when you press DatePicker set button. The time picker dialog will open. The method is given below.

package com.android.date;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;

public class datepicker extends Activity {

    private TextView mDateDisplay;
    private Button mPickDate;
    private int mYear;
    private int mMonth;
    private int mDay;
    private TextView mTimeDisplay;
    private Button mPickTime;

    private int mhour;
    private int mminute;

    static final int TIME_DIALOG_ID = 1;

    static final int DATE_DIALOG_ID = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mDateDisplay =(TextView)findViewById(R.id.date);
        mPickDate =(Button)findViewById(R.id.datepicker);
        mTimeDisplay = (TextView) findViewById(R.id.time);
        mPickTime = (Button) findViewById(R.id.timepicker);

        //Pick time's click event listener
        mPickTime.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                showDialog(TIME_DIALOG_ID);
            }
        });

        //PickDate's click event listener 
        mPickDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });

        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        mhour = c.get(Calendar.HOUR_OF_DAY);
        mminute = c.get(Calendar.MINUTE);
    }

    //-------------------------------------------update date---//    
    private void updateDate() {
        mDateDisplay.setText(
            new StringBuilder()
                    // Month is 0 based so add 1
                    .append(mDay).append("/")
                    .append(mMonth + 1).append("/")
                    .append(mYear).append(" "));
        showDialog(TIME_DIALOG_ID);
    }

      //-------------------------------------------update time---//    
    public void updatetime() {
        mTimeDisplay.setText(
                new StringBuilder()
                        .append(pad(mhour)).append(":")
                        .append(pad(mminute))); 
    }

    private static String pad(int c) {
        if (c >= 10)
            return String.valueOf(c);
        else
            return "0" + String.valueOf(c);


    //Datepicker dialog generation  

    private DatePickerDialog.OnDateSetListener mDateSetListener =
        new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, 
                                  int monthOfYear, int dayOfMonth) {
                mYear = year;
                mMonth = monthOfYear;
                mDay = dayOfMonth;
                updateDate();
            }
        };


     // Timepicker dialog generation
        private TimePickerDialog.OnTimeSetListener mTimeSetListener =
            new TimePickerDialog.OnTimeSetListener() {
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    mhour = hourOfDay;
                    mminute = minute;
                    updatetime();
                }
            };

        @Override
        protected Dialog onCreateDialog(int id) {
            switch (id) {
            case DATE_DIALOG_ID:
                return new DatePickerDialog(this,
                            mDateSetListener,
                            mYear, mMonth, mDay);

            case TIME_DIALOG_ID:
                return new TimePickerDialog(this,
                        mTimeSetListener, mhour, mminute, false);

            }
            return null;
        }
}

the main.xml is given below

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="@string/hello"/>

    <TextView android:id="@+id/time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""/>

    <Button
        android:id="@+id/timepicker"
        android:text="Change Time" 
        android:layout_height="wrap_content" 
        android:layout_width="wrap_content"/>

    <TextView 
        android:id="@+id/date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""/>

    <Button android:id="@+id/datepicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="200dp"
        android:text="Change the date"/>

</LinearLayout>

A Windows equivalent of the Unix tail command

The tail command and many others are available in the Windows Resource Kit Tools package.

Tools to search for strings inside files without indexing

I'm a fan of the Find-In-Files dialog in Notepad++. Bonus: It's free.

enter image description here

Adding a directory to the PATH environment variable in Windows

As trivial as it may be, I had to restart Windows when faced with this problem.

I am running Windows 7 x64. I did a manual update to the system PATH variable. This worked okay if I ran cmd.exe from the stat menu. But if I type "cmd" in the Windows Explorer address bar, it seems to load the PATH from elsewhere, which doesn't have my manual changes.

(To avoid doubt - yes, I did close and rerun cmd a couple of times before I restarted and it didn't help.)

how to overlap two div in css?

I edited you fiddle you just need to add z-index to the front element and position it accordingly.

How do I add my bot to a channel?

As of now:

  • Only the creator of the channel can add a bot.
  • Other administrators can't add bots to channels.
  • Channel can be public or private (doesn't matter)
  • bots can be added only as admins, not members.*

To add the bot to your channel:

  • click on the channel name: enter image description here

  • click on admins: enter image description here

  • click on Add Admin: enter image description here

  • search for your bot like @your_bot_name, and click add:** enter image description here

* In some platforms like mac native telegram client it may look like that you can add bot as a member, but at the end it won't work.
** the bot doesn't need to be in your contact list.

Format date to MM/dd/yyyy in JavaScript

ISO compliant dateString

If your dateString is RFC282 and ISO8601 compliant:
pass your string into the Date Constructor:

const dateString = "2020-10-30T12:52:27+05:30"; // ISO8601 compliant dateString
const D = new Date(dateString);                 // {object Date}

from here you can extract the desired values by using Date Getters:

D.getMonth() + 1  // 10 (PS: +1 since Month is 0-based)
D.getDate()       // 30
D.getFullYear()   // 2020

Non-standard date string

If you use a non standard date string:
destructure the string into known parts, and than pass the variables to the Date Constructor:

new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])

const dateString = "30/10/2020 12:52:27";
const [d, M, y, h, m, s] = dateString.match(/\d+/g);

// PS: M-1 since Month is 0-based
const D = new Date(y, M-1, d, h, m, s);  // {object Date}


D.getMonth() + 1  // 10 (PS: +1 since Month is 0-based)
D.getDate()       // 30
D.getFullYear()   // 2020

Date to milliseconds and back to date in Swift

@Travis solution is right, but it loses milliseconds when a Date is generated. I have added a line to include the milliseconds into the date:

If you don't need this precision, use the Travis solution because it will be faster.

extension Date {

    func toMillis() -> Int64! {
        return Int64(self.timeIntervalSince1970 * 1000)
    }

    init(millis: Int64) {
        self = Date(timeIntervalSince1970: TimeInterval(millis / 1000))
        self.addTimeInterval(TimeInterval(Double(millis % 1000) / 1000 ))
    }

}

Why is there an unexplainable gap between these inline-block div elements?

You need to add

#container
{
    display:inline-block;
    position:relative;
    background:rgb(255,100,0);
    margin:0px;
    width:40%;
    height:100px;
    margin-right:-4px;
}

because whenever you write display:inline-block it takes an additional margin-right:4px. So, you need to remove it.

How to apply bold text style for an entire row using Apache POI?

A worked, completed and simple example:

package io.github.baijifeilong.excel;

import lombok.SneakyThrows;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;

/**
 * Created by [email protected] at 2019/12/6 11:41
 */
public class ExcelBoldTextDemo {

    @SneakyThrows
    public static void main(String[] args) {

        new XSSFWorkbook() {{
            XSSFRow row = createSheet().createRow(0);
            row.setRowStyle(createCellStyle());
            row.getRowStyle().getFont().setBold(true);
            row.createCell(0).setCellValue("Alpha");
            row.createCell(1).setCellValue("Beta");
            row.createCell(2).setCellValue("Gamma");
        }}.write(new FileOutputStream("demo.xlsx"));
    }
}

how to make div click-able?

If this div is a function I suggest use cursor:pointer in your style like style="cursor:pointer" and can use onclick function.

like this

<div onclick="myfunction()" style="cursor:pointer"></div>

but I suggest you use a JS framework like jquery or extjs

PostgreSQL Error: Relation already exists

Another reason why you might get errors like "relation already exists" is if the DROP command did not execute correctly.

One reason this can happen is if there are other sessions connected to the database which you need to close first.

Does it make sense to use Require.js with Angular.js?

Yes it makes sense to use requireJS with Angular, I spent several days to test several technical solutions.

I made an Angular Seed with RequireJS on Server Side. Very simple one. I use SHIM notation for no AMD module and not AMD because I think it's very difficult to deal with two different Dependency injection system.

I use grunt and r.js to concatenate js files on server depends on the SHIM configuration (dependency) file. So I refer only one js file in my app.

For more information go on my github Angular Seed : https://github.com/matohawk/angular-seed-requirejs

Datatable select with multiple conditions

Yes, the DataTable.Select method supports boolean operators in the same way that you would use them in a "real" SQL statement:

DataRow[] results = table.Select("A = 'foo' AND B = 'bar' AND C = 'baz'");

See DataColumn.Expression in MSDN for the syntax supported by DataTable's Select method.

Decoding a Base64 string in Java

Modify the package you're using:

import org.apache.commons.codec.binary.Base64;

And then use it like this:

byte[] decoded = Base64.decodeBase64("YWJjZGVmZw==");
System.out.println(new String(decoded, "UTF-8") + "\n");

How to change the decimal separator of DecimalFormat from comma to dot/point?

you could just use replace function before you return the string in the method

return df.format(bd).replace(",", ".")

Request UAC elevation from within a Python script?

You can make a shortcut somewhere and as the target use: python yourscript.py then under properties and advanced select run as administrator.

When the user executes the shortcut it will ask them to elevate the application.

Counting number of lines, words, and characters in a text file

You could use regular expressions to count for you.

String subject = "First Line\n Second Line\nThird Line";  
Matcher wordM = Pattern.compile("\\b\\S+?\\b").matcher(subject); //matches a word
Matcher charM = Pattern.compile(".").matcher(subject); //matches a character
Matcher newLineM = Pattern.compile("\\r?\\n").matcher(subject); //matches a linebreak

int words=0,chars=0,newLines=1; //newLines is initially 1 because the first line has no corresponding linebreak

while(wordM.find()) words++;
while(charM.find()) chars++;
while(newLineM.find()) newLines++;

System.out.println("Words: "+words);
System.out.println("Chars: "+chars);
System.out.println("Lines: "+newLines);

Batch file: Find if substring is in string (not in a file)

I usually do something like this:

Echo.%1 | findstr /C:"%2">nul && (
    REM TRUE
) || (
    REM FALSE
)

Example:

Echo.Hello world | findstr /C:"world">nul && (
    Echo.TRUE
) || (
    Echo.FALSE
)

Echo.Hello world | findstr /C:"World">nul && (Echo.TRUE) || (Echo.FALSE)

Output:

TRUE
FALSE

I don't know if this is the best way.

No module named 'openpyxl' - Python 3.4 - Ubuntu

In order to keep track of dependency issues, I like to use the conda installer, which simply boils down to:

conda install openpyxl

Use sudo with password as parameter

# Make sure only root can run our script
if [ "$(id -u)" != "0" ]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi

How to use the TextWatcher class in Android?

Supplemental answer

Here is a visual supplement to the other answers. My fuller answer with the code and explanations is here.

  • Red: text about to be deleted (replaced)
  • Green: text that was just added (replacing the old red text)

enter image description here

Do fragments really need an empty constructor?

Here is my simple solution:

1 - Define your fragment

public class MyFragment extends Fragment {

    private String parameter;

    public MyFragment() {
    }

    public void setParameter(String parameter) {
        this.parameter = parameter;
    } 
}

2 - Create your new fragment and populate the parameter

    myfragment = new MyFragment();
    myfragment.setParameter("here the value of my parameter");

3 - Enjoy it!

Obviously you can change the type and the number of parameters. Quick and easy.

How to print object array in JavaScript?

There is a wonderful print_r implementation for JavaScript in php.js library.

Note, you should also add echo support in the code.

DEMO: http://jsbin.com/esexiw/1

How can I kill all sessions connecting to my oracle database?

Try trigger on logon

Insted of trying disconnect users you should not allow them to connect.

There is and example of such trigger.

CREATE OR REPLACE TRIGGER rds_logon_trigger
AFTER LOGON ON DATABASE
BEGIN
  IF SYS_CONTEXT('USERENV','IP_ADDRESS') not in ('192.168.2.121','192.168.2.123','192.168.2.233') THEN
    RAISE_APPLICATION_ERROR(-20003,'You are not allowed to connect to the database');
  END IF;

  IF (to_number(to_char(sysdate,'HH24'))< 6) and (to_number(to_char(sysdate,'HH24')) >18) THEN
    RAISE_APPLICATION_ERROR(-20005,'Logon only allowed during business hours');
  END IF;

END;

How can I scroll up more (increase the scroll buffer) in iTerm2?

Solution: In order to increase your buffer history on iterm bash terminal you've got two options:

Go to iterm -> Preferences -> Profiles -> Terminal Tab -> Scrollback Buffer (section)

Option 1. select the checkbox Unlimited scrollback

Option 2. type the selected Scrollback lines numbers you'd like your terminal buffer to cache (See image below)

enter image description here

How do I make a stored procedure in MS Access?

Access 2010 has both stored procedures, and also has table triggers. And, both features are available even when you not using a server (so, in 100% file based mode).

If you using SQL Server with Access, then of course the stored procedures are built using SQL Server and not Access.

For Access 2010, you open up the table (non-design view), and then choose the table tab. You see options there to create store procedures and table triggers.

For example:

screenshot

Note that the stored procedure language is its own flavor just like Oracle or SQL Server (T-SQL). Here is example code to update an inventory of fruits as a result of an update in the fruit order table alt text

Keep in mind these are true engine-level table triggers. In fact if you open up that table with VB6, VB.NET, FoxPro or even modify the table on a computer WITHOUT Access having been installed, the procedural code and the trigger at the table level will execute. So, this is a new feature of the data engine jet (now called ACE) for Access 2010. As noted, this is procedural code that runs, not just a single statement.

How to Diff between local uncommitted changes and origin

I know it's not an answer to the exact question asked, but I found this question looking to diff a file in a branch and a local uncommitted file and I figured I would share

Syntax:

git diff <commit-ish>:./ -- <path>

Examples:

git diff origin/master:./ -- README.md
git diff HEAD^:./ -- README.md
git diff stash@{0}:./ -- README.md
git diff 1A2B3C4D:./ -- README.md

(Thanks Eric Boehs for a way to not have to type the filename twice)

update one table with data from another

Try following code. It is working for me....

UPDATE TableOne 
SET 
field1 =(SELECT TableTwo.field1 FROM TableTwo WHERE TableOne.id=TableTwo.id),
field2 =(SELECT TableTwo.field2 FROM TableTwo WHERE TableOne.id=TableTwo.id)
WHERE TableOne.id = (SELECT  TableTwo.id 
                             FROM   TableTwo 
                             WHERE  TableOne.id = TableTwo.id) 

how to change language for DataTable

There are language files uploaded in a CDN on the dataTables website https://datatables.net/plug-ins/i18n/ So you only have to replace "Spanish" with whatever language you are using in the following example.

https://datatables.net/plug-ins/i18n/Spanish

$('table.dataTable').DataTable( {
    language: {
        url: '//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json'
    }
});

What is a difference between unsigned int and signed int in C?

ISO C states what the differences are.

The int data type is signed and has a minimum range of at least -32767 through 32767 inclusive. The actual values are given in limits.h as INT_MIN and INT_MAX respectively.

An unsigned int has a minimal range of 0 through 65535 inclusive with the actual maximum value being UINT_MAX from that same header file.

Beyond that, the standard does not mandate twos complement notation for encoding the values, that's just one of the possibilities. The three allowed types would have encodings of the following for 5 and -5 (using 16-bit data types):

        two's complement  |  ones' complement   |   sign/magnitude
    +---------------------+---------------------+---------------------+
 5  | 0000 0000 0000 0101 | 0000 0000 0000 0101 | 0000 0000 0000 0101 |
-5  | 1111 1111 1111 1011 | 1111 1111 1111 1010 | 1000 0000 0000 0101 |
    +---------------------+---------------------+---------------------+
  • In two's complement, you get a negative of a number by inverting all bits then adding 1.
  • In ones' complement, you get a negative of a number by inverting all bits.
  • In sign/magnitude, the top bit is the sign so you just invert that to get the negative.

Note that positive values have the same encoding for all representations, only the negative values are different.

Note further that, for unsigned values, you do not need to use one of the bits for a sign. That means you get more range on the positive side (at the cost of no negative encodings, of course).

And no, 5 and -5 cannot have the same encoding regardless of which representation you use. Otherwise, there'd be no way to tell the difference.


As an aside, there are currently moves underway, in both C and C++ standards, to nominate two's complement as the only encoding for negative integers.

Redeploy alternatives to JRebel

You might want to take a look this:

HotSwap support: the object-oriented architecture of the Java HotSpot VM enables advanced features such as on-the-fly class redefinition, or "HotSwap". This feature provides the ability to substitute modified code in a running application through the debugger APIs. HotSwap adds functionality to the Java Platform Debugger Architecture, enabling a class to be updated during execution while under the control of a debugger. It also allows profiling operations to be performed by hotswapping in versions of methods in which profiling code has been inserted.

For the moment, this only allows for newly compiled method body to be redeployed without restarting the application. All you have to do is to run it with a debugger. I tried it in Eclipse and it works splendidly.

Also, as Emmanuel Bourg mentioned in his answer (JEP 159), there is hope to have support for the addition of supertypes and the addition and removal of methods and fields.

Reference: Java Whitepaper 135217: Reliability, Availability and Serviceability

Table column sizing

Using d-flex class works well but some other attributes don't work anymore like vertical-align: middle property.

The best way I found to size columns very easily is to use the width attribute with percentage only in thead cells.

<table class="table">
    <thead>
        <tr>
            <th width="25%">25%</th>
            <th width="25%">25%</th>
            <th width="50%">50%</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>25%</td>
            <td>25%</td>
            <td>50%</td>
        </tr>
    </tbody>
</table>

Android Failed to install HelloWorld.apk on device (null) Error

@Bolton 's answer worked for me. Some details...

I got my phone a few weeks ago. I tried the HelloAndroid sample app right away (after installing req'd software, etc.). The app worked in the emulator AND on the phone--right away!

Shortly after that, I rooted my phone but did not flash any roms or kernels. I was only experimenting on the emulator until yesterday (writing a simple notepad app). When I tried debugging the app on the phone, here's what I observed:

  1. Eclipse console reported the "...failed to install on device...(null)" message. BUT

  2. The HelloAndroid app DID get pushed to the phone! (It appeared in the apps drawer AND I was able to launch it.)

  3. It simply would not launch on the phone from the Eclipse run.

I searched around here and elsewhere last night (including this thread) with no luck. Finally, I rebooted my phone--which I never tried (doh!) 'cause I didn't think it would make a difference--and the app launched from an Eclipse start!

Still don't know the cause, but I'll come back here if I figure it out.

curl: (35) SSL connect error

If updating cURL doesn't fix it, updating NSS should do the trick.

What are the special dollar sign shell variables?

  • $1, $2, $3, ... are the positional parameters.
  • "$@" is an array-like construct of all positional parameters, {$1, $2, $3 ...}.
  • "$*" is the IFS expansion of all positional parameters, $1 $2 $3 ....
  • $# is the number of positional parameters.
  • $- current options set for the shell.
  • $$ pid of the current shell (not subshell).
  • $_ most recent parameter (or the abs path of the command to start the current shell immediately after startup).
  • $IFS is the (input) field separator.
  • $? is the most recent foreground pipeline exit status.
  • $! is the PID of the most recent background command.
  • $0 is the name of the shell or shell script.

Most of the above can be found under Special Parameters in the Bash Reference Manual. There are all the environment variables set by the shell.

For a comprehensive index, please see the Reference Manual Variable Index.

Check if cookie exists else set cookie to Expire in 10 days

if (/(^|;)\s*visited=/.test(document.cookie)) {
    alert("Hello again!");
} else {
    document.cookie = "visited=true; max-age=" + 60 * 60 * 24 * 10; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 10 days.
    alert("This is your first time!");
}

is one way to do it. Note that document.cookie is a magic property, so you don't have to worry about overwriting anything, either.

There are also more convenient libraries to work with cookies, and if you don’t need the information you’re storing sent to the server on every request, HTML5’s localStorage and friends are convenient and useful.

Asynchronous Process inside a javascript for loop

async await is here (ES7), so you can do this kind of things very easily now.

  var i;
  var j = 10;
  for (i = 0; i < j; i++) {
    await asycronouseProcess();
    alert(i);
  }

Remember, this works only if asycronouseProcess is returning a Promise

If asycronouseProcess is not in your control then you can make it return a Promise by yourself like this

function asyncProcess() {
  return new Promise((resolve, reject) => {
    asycronouseProcess(()=>{
      resolve();
    })
  })
}

Then replace this line await asycronouseProcess(); by await asyncProcess();

Understanding Promises before even looking into async await is must (Also read about support for async await)

ImportError: No module named Crypto.Cipher

Try with pip3:

sudo pip3 install pycrypto

Customize UITableView header section

If you just want to add title to the tableView header dont add a view. In swift 3.x the code goes like this:

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    var lblStr = ""
    if section == 0 {
        lblStr = "Some String 1"
    }
    else if section == 1{
        lblStr = "Some String 2"
    }
    else{
        lblStr = "Some String 3"
    }
    return lblStr
}

You may implement an array to fetch the title for the headers.

Equivalent of jQuery .hide() to set visibility: hidden

If you only need the standard functionality of hide only with visibility:hidden to keep the current layout you can use the callback function of hide to alter the css in the tag. Hide docs in jquery

An example :

$('#subs_selection_box').fadeOut('slow', function() {
      $(this).css({"visibility":"hidden"});
      $(this).css({"display":"block"});
});

This will use the normal cool animation to hide the div, but after the animation finish you set the visibility to hidden and display to block.

An example : http://jsfiddle.net/bTkKG/1/

I know you didnt want the $("#aa").css() solution, but you did not specify if it was because using only the css() method you lose the animation.

best way to preserve numpy arrays on disk

The lookup time is slow because when you use mmap to does not load content of array to memory when you invoke load method. Data is lazy loaded when particular data is needed. And this happens in lookup in your case. But second lookup won`t be so slow.

This is nice feature of mmap when you have a big array you do not have to load whole data into memory.

To solve your can use joblib you can dump any object you want using joblib.dump even two or more numpy arrays, see the example

firstArray = np.arange(100)
secondArray = np.arange(50)
# I will put two arrays in dictionary and save to one file
my_dict = {'first' : firstArray, 'second' : secondArray}
joblib.dump(my_dict, 'file_name.dat')

Does a VPN Hide my Location on Android?

Your question can be conveniently divided into several parts:

Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.

How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.

You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):

  1. Download and install a trusted VPN.

  2. Install the VPN on your Android device.

  3. Open the application and connect to a server in a different country.

  4. Your Android location will now be successfully changed!

Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.

Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.

Column order manipulation using col-lg-push and col-lg-pull in Twitter Bootstrap 3

Misconception Common misconception with column ordering is that, I should (or could) do the pushing and pulling on mobile devices, and that the desktop views should render in the natural order of the markup. This is wrong.

Reality Bootstrap is a mobile first framework. This means that the order of the columns in your HTML markup should represent the order in which you want them displayed on mobile devices. This mean that the pushing and pulling is done on the larger desktop views. not on mobile devices view..

Brandon Schmalz - Full Stack Web Developer Have a look at full description here

CSS div 100% height

I have another suggestion. When you want myDiv to have a height of 100%, use these extra 3 attributes on your div:

myDiv {
    min-height: 100%;
    overflow-y: hidden;
    position: relative;
}

That should do the job!

How to calculate UILabel width based on text length?

CGRect rect = label.frame;
rect.size = [label.text sizeWithAttributes:@{NSFontAttributeName : [UIFont fontWithName:label.font.fontName size:label.font.pointSize]}];
label.frame = rect;

Android: show/hide status bar/power bar

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //hide status bar
    requestWindowFeature( Window.FEATURE_NO_TITLE );
    getWindow().setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN );


    setContentView(R.layout.activity_main);
}

Prevent text selection after double click

In plain javascript:

element.addEventListener('mousedown', function(e){ e.preventDefault(); }, false);

Or with jQuery:

jQuery(element).mousedown(function(e){ e.preventDefault(); });

Change selected value of kendo ui dropdownlist

It's possible to "natively" select by value:

dropdownlist.select(1);

Disable browsers vertical and horizontal scrollbars

In case you also need support for Internet Explorer 6, just overflow the html

$("html").css("overflow", "hidden");

and

$("html").css("overflow", "auto");

Change DataGrid cell colour based on values

To do this in the Code Behind (VB.NET)

Dim txtCol As New DataGridTextColumn

Dim style As New Style(GetType(TextBlock))
Dim tri As New Trigger With {.Property = TextBlock.TextProperty, .Value = "John"}
tri.Setters.Add(New Setter With {.Property = TextBlock.BackgroundProperty, .Value = Brushes.Green})
style.Triggers.Add(tri)

xtCol.ElementStyle = style

Namenode not getting started

If anyone using hadoop1.2.1 version and not able to run namenode, go to core-site.xml, and change dfs.default.name to fs.default.name.

And then format the namenode using $hadoop namenode -format.

Finally run the hdfs using start-dfs.sh and check for service using jps..

Apply .gitignore on an existing repository already tracking large number of files

I think this is an easy way for adding a .gitignore file to an existing repository.

Prerequisite:

You need a browser to access your github account.

Steps

  1. Create a new file in your required (existing) project and name it .gitignore. You will a get suggestive prompt for .gitignore templates as soon as you name the file as .gitignore. Either use these templates or use gitignore.io to generate the content of your gitignore file.
  2. Commit the changes.
  3. Now clone this repository.

Have fun!

WPF Timer Like C# Timer

The timer has special functions.

  1. Call an asynchronous timer or synchronous timer.
  2. Change the time interval
  3. Ability to cancel and resume  

if you use StartAsync () or Start (), the thread does not block the user interface element

     namespace UITimer


     {
        using thread = System.Threading;
        public class Timer
        {

        public event Action<thread::SynchronizationContext> TaskAsyncTick;
        public event Action Tick;
        public event Action AsyncTick;
        public int Interval { get; set; } = 1;
        private bool canceled = false;
        private bool canceling = false;
        public async void Start()
        {
            while(true)
            {

                if (!canceled)
                {
                    if (!canceling)
                    {
                        await Task.Delay(Interval);
                        Tick.Invoke();
                    }
                }
                else
                {
                    canceled = false;
                    break;
                }
            }


        }
        public void Resume()
        {
            canceling = false;
        }
        public void Cancel()
        {
            canceling = true;
        }
        public async void StartAsyncTask(thread::SynchronizationContext 
        context)
        {

                while (true)
                {
                    if (!canceled)
                    {
                    if (!canceling)
                    {
                        await Task.Delay(Interval).ConfigureAwait(false);

                        TaskAsyncTick.Invoke(context);
                    }
                    }
                    else
                    {
                        canceled = false;
                        break;
                    }
                }

        }
        public void StartAsync()
        {
            thread::ThreadPool.QueueUserWorkItem((x) =>
            {
                while (true)
                {

                    if (!canceled)
                    {
                        if (!canceling)
                        {
                            thread::Thread.Sleep(Interval);

                    Application.Current.Dispatcher.Invoke(AsyncTick);
                        }
                    }
                    else
                    {
                        canceled = false;
                        break;
                    }
                }
            });
        }

        public void StartAsync(thread::SynchronizationContext context)
        {
            thread::ThreadPool.QueueUserWorkItem((x) =>
            {
                while(true)
                 {

                    if (!canceled)
                    {
                        if (!canceling)
                        {
                            thread::Thread.Sleep(Interval);
                            context.Post((xfail) => { AsyncTick.Invoke(); }, null);
                        }
                    }
                    else
                    {
                        canceled = false;
                        break;
                    }
                }
            });
        }
        public void Abort()
        {
            canceled = true;
        }
    }


     }

Add an incremental number in a field in INSERT INTO SELECT query in SQL Server

You can use the row_number() function for this.

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
            row_number() over (order by (select NULL))
    FROM PM_Ingrediants 
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

If you want to start with the maximum already in the table then do:

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
           coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
    FROM PM_Ingrediants cross join
         (select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

Finally, you can just make the sequence column an auto-incrementing identity column. This saves the need to increment it each time:

create table PM_Ingrediants_Arrangement_Temp ( . . .
    sequence int identity(1, 1) -- and might consider making this a primary key too
    . . .
)

Setting dynamic scope variables in AngularJs - scope.<some_string>

If you are using Lodash library below is the way to set a dynamic variable in the angular scope.

To set the value in the angular scope.

_.set($scope, the_string, 'life.meaning')

To get the value from the angular scope.

_.get($scope, 'life.meaning')

Saving and Reading Bitmaps/Images from Internal memory in Android

Make sure to use WEBP as your media format to save more space with same quality:

fun saveImage(context: Context, bitmap: Bitmap, name: String): String {
        context.openFileOutput(name, Context.MODE_PRIVATE).use { fos ->
            bitmap.compress(Bitmap.CompressFormat.WEBP, 25, fos)
        }
    return context.filesDir.absolutePath
 }

ORA-01438: value larger than specified precision allows for this column

This indicates you are trying to put something too big into a column. For example, you have a VARCHAR2(10) column and you are putting in 11 characters. Same thing with number.

This is happening at line 176 of package UMAIN. You would need to go and have a look at that to see what it is up to. Hopefully you can look it up in your source control (or from user_source). Later versions of Oracle report this error better, telling you which column and what value.

How I could add dir to $PATH in Makefile?

What I usually do is supply the path to the executable explicitly:

EXE=./bin/
...
test all:
    $(EXE)x

I also use this technique to run non-native binaries under an emulator like QEMU if I'm cross compiling:

EXE = qemu-mips ./bin/

If make is using the sh shell, this should work:

test all:
    PATH=bin:$PATH x

Sending HTML mail using a shell script

Another option is using msmtp.

What you need is to set up your .msmtprc with something like this (example is using gmail):

account default
host smtp.gmail.com
port 587
from [email protected]
tls on
tls_starttls on
tls_trust_file ~/.certs/equifax.pem
auth on
user [email protected]
password <password>
logfile ~/.msmtp.log

Then just call:

(echo "Subject: <subject>"; echo; echo "<message>") | msmtp <[email protected]>

in your script

Update: For HTML mail you have to put the headers as well, so you might want to make a file like this:

From: [email protected]
To: [email protected]
Subject: Important message
Mime-Version: 1.0
Content-Type: text/html

<h1>Mail body will be here</h1>
The mail body <b>should</b> start after one blank line from the header.

And mail it like

cat email-template | msmtp [email protected]

The same can be done via command line as well, but it might be easier using a file.

How to get the parents of a Python class?

New-style classes have an mro method you can call which returns a list of parent classes in method resolution order.

Adding horizontal spacing between divs in Bootstrap 3

From what I understand you want to make a navigation bar or something similar to it. What I recommend doing is making a list and editing the items from there. Just try this;

<ul>
    <li class='item col-md-12 panel' id='gameplay-title'>Title</li>
    <li class='item col-md-6 col-md-offset-3 panel' id='gameplay-scoreboard'>Scoreboard</li>
</ul>

And so on... To add more categories add another ul in there. Now, for the CSS you just need this;

ul {
    list-style: none;
}
.item {
    display: inline;
    padding-right: 20px;
}

What is a provisioning profile used for when developing iPhone applications?

Apple cares about security and as you know it is not possible to install any application on a real iOS device. Apple has several legal ways to do it:

  • When you need to test/debug an app on a real device the Development Provisioning Profile allows you to do it
  • When you publish an app you send a Distribution Provisioning Profile[About] and Apple after review reassign it by they own key

Development Provisioning Profile is stored on device and contains:

  • Application ID - application which are going to run
  • List of Development certificates - who can debug the app
  • List of devices - which devices can run this app

Xcode by default take cares about

Which loop is faster, while or for?

In C#, the For loop is slightly faster.

For loop average about 2.95 to 3.02 ms.

The While loop averaged about 3.05 to 3.37 ms.

Quick little console app to prove:

 class Program
    {
        static void Main(string[] args)
        {
            int max = 1000000000;
            Stopwatch stopWatch = new Stopwatch();

            if (args.Length == 1 && args[0].ToString() == "While")
            {
                Console.WriteLine("While Loop: ");
                stopWatch.Start();
                WhileLoop(max);
                stopWatch.Stop();
                DisplayElapsedTime(stopWatch.Elapsed);
            }
            else
            {
                Console.WriteLine("For Loop: ");
                stopWatch.Start();
                ForLoop(max);
                stopWatch.Stop();
                DisplayElapsedTime(stopWatch.Elapsed);
            }
        }

        private static void WhileLoop(int max)
        {
            int i = 0;
            while (i <= max)
            {
                //Console.WriteLine(i);
                i++;
            };
        }

        private static void ForLoop(int max)
        {
            for (int i = 0; i <= max; i++)
            {
                //Console.WriteLine(i);
            }
        }

        private static void DisplayElapsedTime(TimeSpan ts)
        {
            // Format and display the TimeSpan value.
            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                ts.Hours, ts.Minutes, ts.Seconds,
                ts.Milliseconds / 10);
            Console.WriteLine(elapsedTime, "RunTime");
        }
    }

C# generic list <T> how to get the type of T?

Given an object which I suspect to be some kind of IList<>, how can I determine of what it's an IList<>?

Here's a reliable solution. My apologies for length - C#'s introspection API makes this suprisingly difficult.

/// <summary>
/// Test if a type implements IList of T, and if so, determine T.
/// </summary>
public static bool TryListOfWhat(Type type, out Type innerType)
{
    Contract.Requires(type != null);

    var interfaceTest = new Func<Type, Type>(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>) ? i.GetGenericArguments().Single() : null);

    innerType = interfaceTest(type);
    if (innerType != null)
    {
        return true;
    }

    foreach (var i in type.GetInterfaces())
    {
        innerType = interfaceTest(i);
        if (innerType != null)
        {
            return true;
        }
    }

    return false;
}

Example usage:

    object value = new ObservableCollection<int>();
Type innerType;
TryListOfWhat(value.GetType(), out innerType).Dump();
innerType.Dump();

Returns

True
typeof(Int32)

jQuery UI dialog positioning

above solutions are very true...but the UI dialog does not retain the position after window is resized. below code does this

            $(document).ready(function(){

                $(".test").click(function(){
                            var posX = $(".test").offset().left - $(document).scrollLeft() + $(".test").outerWidth();
                            var posY = $(".test").offset().top - $(document).scrollTop() + $(".test").outerHeight();
                            console.log("in click function");
                            $(".abc").dialog({
                                position:[posX,posY]
                            });

                        })

            })

            $(window).resize(function(){
                var posX=$(".test").offset().left - $(document).scrollLeft() + $(".test").outerWidth();
                var posY = $(".test").offset().top - $(document).scrollTop() + $(".test").outerHeight();

            $(".abc").dialog({
                                position:[posX,posY]
                            });
            })

SQL is null and = null

I think that equality is something that can be absolutely determined. The trouble with null is that it's inherently unknown. Null combined with any other value is null - unknown. Asking SQL "Is my value equal to null?" would be unknown every single time, even if the input is null. I think the implementation of IS NULL makes it clear.

Read the current full URL with React?

this.props.location is a react-router feature, you'll have to install if you want to use it.

Note: doesn't return the full url.

img onclick call to JavaScript function

You should probably be using a more unobtrusive approach. Here's the benefits

  • Separation of functionality (the "behavior layer") from a Web page's structure/content and presentation
  • Best practices to avoid the problems of traditional JavaScript programming (such as browser inconsistencies and lack of scalability)
  • Progressive enhancement to support user agents that may not support advanced JavaScript functionality

Here's a jsfiddle demo

Your JavaScript

function exportToForm(a, b, c, d, e) {
  console.log(a, b, c, d, e);
}

var images = document.getElementsByTagName("img");

for (var i=0, len=images.length, img; i<len; i++) {
  img = images[i];
  img.addEventListener("click", function() {
    var a = img.getAttribute("data-a"),
        b = img.getAttribute("data-b"),
        c = img.getAttribute("data-c"),
        d = img.getAttribute("data-d"),
        e = img.getAttribute("data-e");

    exportToForm(a, b, c, d, e);
  });
}

Your images will look like this

<img data-a="1" data-b="2" data-c="3" data-d="4" data-e="5" src="image.jpg">

How to count how many values per level in a given factor?

One more approach would be to apply n() function which is counting the number of observations

library(dplyr)
library(magrittr)
data %>% 
  group_by(columnName) %>%
  summarise(Count = n())

PHP cURL not working - WAMP on Windows 7 64 bit

This work for me: http://www.mediafire.com/?3ay381k3cq59cm2 download a paste the file in ext folder PHP 5.4.3