Programs & Examples On #Defaultproxy

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

What causes HttpHostConnectException?

You must set proxy server for gradle at some time, you can try to change the proxy server ip address in gradle.properties which is under .gradle document

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

Probably the machine or web.config in prod has the settings in the configuration; you probably won't need the proxy tag.

<system.net>
    <defaultProxy useDefaultCredentials="true" >
        <proxy usesystemdefault="False"
               proxyaddress="http://<ProxyLocation>:<port>"
               bypassonlocal="True"
               autoDetect="False" />
    </defaultProxy>
</system.net>

How should I set the default proxy to use default credentials?

This is the new suggested method.

WebRequest.GetSystemWebProxy();

Is it possible to specify proxy credentials in your web.config?

While I haven't found a good way to specify proxy network credentials in the web.config, you might find that you can still use a non-coding solution, by including this in your web.config:

  <system.net>
    <defaultProxy useDefaultCredentials="true">
      <proxy proxyaddress="proxyAddress" usesystemdefault="True"/>
    </defaultProxy>
  </system.net>

The key ingredient in getting this going, is to change the IIS settings, ensuring the account that runs the process has access to the proxy server. If your process is running under LocalService, or NetworkService, then this probably won't work. Chances are, you'll want a domain account.

CSS Layout - Dynamic width DIV

try

<div style="width:100%;">
    <div style="width:50px; float: left;"><img src="myleftimage" /></div>
    <div style="width:50px; float: right;"><img src="myrightimage" /></div>
    <div style="display:block; margin-left:auto; margin-right: auto;">Content Goes Here</div>
</div>

or

<div style="width:100%; border:2px solid #dadada;">
    <div style="width:50px; float: left;"><img src="myleftimage" /></div>
    <div style="width:50px; float: right;"><img src="myrightimage" /></div>
    <div style="display:block; margin-left:auto; margin-right: auto;">Content Goes Here</div>
<div style="clear:both"></div>    
</div>

How to take complete backup of mysql database using mysqldump command line utility

It depends a bit on your version. Before 5.0.13 this is not possible with mysqldump.

From the mysqldump man page (v 5.1.30)

 --routines, -R

      Dump stored routines (functions and procedures) from the dumped
      databases. Use of this option requires the SELECT privilege for the
      mysql.proc table. The output generated by using --routines contains
      CREATE PROCEDURE and CREATE FUNCTION statements to re-create the
      routines. However, these statements do not include attributes such
      as the routine creation and modification timestamps. This means that
      when the routines are reloaded, they will be created with the
      timestamps equal to the reload time.
      ...

      This option was added in MySQL 5.0.13. Before that, stored routines
      are not dumped. Routine DEFINER values are not dumped until MySQL
      5.0.20. This means that before 5.0.20, when routines are reloaded,
      they will be created with the definer set to the reloading user. If
      you require routines to be re-created with their original definer,
      dump and load the contents of the mysql.proc table directly as
      described earlier.

Read only file system on Android

While I know the question is about the real device, in case someone got here with a similar issue in the emulator, with whatever tools are the latest as of Feb, 2017, the emulator needs to be launched from the command line with:

-writable-system

For anything to be writable to the /system. Without this flag no combination of remount or mount will allow one to write to /system.

After the emulator is launched with that flag, a single adb remount after adb root is sufficient to get permissions to push to /system.

Here's an example of the command line I use to run my emulator:

./emulator -writable-system -avd Nexus_5_API_25 -no-snapshot-load -qemu

The value for the -avd flags comes from:

./emulator -list-avds

Is an anchor tag without the href attribute safe?

The tag is fine to use without an href attribute. Contrary to many of the answers here, there are actually standard reasons for creating an anchor when there is no href. Semantically, "a" means an anchor or a link. If you use it for anything following that meaning, then you are fine.

One standard use of the a tag without an href is to create named links. This allows you to use an anchor with name=blah and later on you can create an anchor with href=#blah to link to the named section of the current page. However, this has been deprecated because you can also use IDs in the same manner. As an example, you could use a header tag with id=header and later you could have an anchor pointing to href=#header.

My point, however, is not to suggest using the name property. Only to provide one use case where you don't need an href, and therefore reasoning why it is not required.

How do I add items to an array in jQuery?

Since $.getJSON is async, I think your console.log(list.length); code is firing before your array has been populated. To correct this put your console.log statement inside your callback:

var list = new Array();
$.getJSON("json.js", function(data) {
    $.each(data, function(i, item) {
        console.log(item.text);
        list.push(item.text);
    });
    console.log(list.length);
});

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

I find it solution http://www.scriptscoop.net/t/7c42f9d698a4/java-create-maven-project-could-not-resolve-archetype-connection-refused.html

We can see the origin of the problem : Connection refused: connect

I have already do this :

1) Window -> Preferences -> General -> Network Connections. I put in Manual with the url and port of my proxy for HTTP protocol. It works because before this, Spring Tool Suite did not want to update. After, it's okay.

2) Window -> Preferences -> Maven -> User Settings. In Global Settings, is empty. In User Settings, I put the path to settings.xml. In this file, i have :

enter image description here

Save multiple sheets to .pdf

I recommend adding the following line after the export to PDF:

ThisWorkbook.Sheets("Sheet1").Select

(where eg. Sheet1 is the single sheet you want to be active afterwards)

Leaving multiple sheets in a selected state may cause problems executing some code. (eg. unprotect doesn't function properly when multiple sheets are actively selected.)

CS0120: An object reference is required for the nonstatic field, method, or property 'foo'

You start a thread which runs the static method SumData. However, SumData calls SetTextboxText which isn't static. Thus you need an instance of your form to call SetTextboxText.

ngFor with index as value in attribute

I would use this syntax to set the index value into an attribute of the HTML element:

Angular >= 2

You have to use let to declare the value rather than #.

<ul>
    <li *ngFor="let item of items; let i = index" [attr.data-index]="i">
        {{item}}
    </li>
</ul>

Angular = 1

<ul>
    <li *ngFor="#item of items; #i = index" [attr.data-index]="i">
        {{item}}
    </li>
</ul>

Here is the updated plunkr: http://plnkr.co/edit/LiCeyKGUapS5JKkRWnUJ?p=preview.

PHP how to get the base domain/url?

Step-1

First trim the trailing backslash (/) from the URL. For example, If the URL is http://www.google.com/ then the resultant URL will be http://www.google.com

$url= trim($url, '/');

Step-2

If scheme not included in the URL, then prepend it. So for example if the URL is www.google.com then the resultant URL will be http://www.google.com

if (!preg_match('#^http(s)?://#', $url)) {
    $url = 'http://' . $url;
}

Step-3

Get the parts of the URL.

$urlParts = parse_url($url);

Step-4

Now remove www. from the URL

$domain = preg_replace('/^www\./', '', $urlParts['host']);

Your final domain without http and www is now stored in $domain variable.

Examples:

http://www.google.com => google.com

https://www.google.com => google.com

www.google.com => google.com

http://google.com => google.com

Run a vbscript from another vbscript

See if the following works

Dim objShell
Set objShell = Wscript.CreateObject("WScript.Shell")

objShell.Run "TestScript.vbs" 

' Using Set is mandatory
Set objShell = Nothing

Get Category name from Post ID

function wp_get_post_categories( $post_id = 0, $args = array() )
{
   $post_id = (int) $post_id;
   $defaults = array('fields' => 'ids');
   $args = wp_parse_args( $args, $defaults );
   $cats = wp_get_object_terms($post_id, 'category', $args);

   return $cats;
}

Here is the second argument of function wp_get_post_categories() which you can pass the attributes of receiving data.

$category_detail = get_the_category( '4',array( 'fields' => 'names' ) ); //$post->ID
foreach( $category_detail as $cd )
{
   echo $cd->name;
}

org.springframework.web.client.HttpClientErrorException: 400 Bad Request

This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.

MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
        headers);
JSONObject jsonObject = null;

try {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> responseEntity = restTemplate.exchange(
            "https://url", HttpMethod.POST, entity,
            String.class);

    if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
        try {
            jsonObject = new JSONObject(responseEntity.getBody());
        } catch (JSONException e) {
            throw new RuntimeException("JSONException occurred");
        }
    }
  } catch (final HttpClientErrorException httpClientErrorException) {
        throw new ExternalCallBadRequestException();
  } catch (HttpServerErrorException httpServerErrorException) {
        throw new ExternalCallServerErrorException(httpServerErrorException);
  } catch (Exception exception) {
        throw new ExternalCallServerErrorException(exception);
    } 

ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.

Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.

How to add buttons dynamically to my form?

You can't add a Button to an empty list without creating a new instance of that Button. You are missing the

Button newButton = new Button();  

in your code plus get rid of the .Capacity

Delete item from array and shrink array

No use of any pre defined function as well as efficient: --- >>

public static void Delete(int d , int[] array )
{       
    Scanner in = new Scanner (System.in);

    int i , size = array.length;

    System.out.println("ENTER THE VALUE TO DELETE? ");

     d = in.nextInt();

        for ( i=0;i< size;i++)
        {
                if (array[i] == d)
                        {


                            int[] arr3 =new int[size-1];
                            int[] arr4 = new int[i];
                            int[] arr5 = new int[size-i-1];

                                    for (int a =0 ;a<i;a++)
                                    {
                                        arr4[a]=array[a];
                                        arr3[a] = arr4[a];
                                    }
                                     for (int a =i ;a<size-1;a++)
                                     {
                                         arr5[a-i] = array[a+1];
                                         arr3[a] = arr5[a-i];

                                     }


                System.out.println(Arrays.toString(arr3));

                        }
                else System.out.println("************");    


        }

}

Kotlin: How to get and set a text to TextView in Android using Kotlin?

Use textView.text for getter and setter, ex:

val textView = findViewById<TextView>(R.id.textView)
// Set text
textView.text = "Hello World!"
// Get text
val textViewString = textView.text.toString()

PHP Echo text Color

This is an old question, but no one responded to the question regarding centering text in a terminal.

/**
 * Centers a string of text in a terminal window
 *
 * @param string $text The text to center
 * @param string $pad_string If set, the string to pad with (eg. '=' for a nice header)
 *
 * @return string The padded result, ready to echo
 */
function center($text, $pad_string = ' ') {
    $window_size = (int) `tput cols`;
    return str_pad($text, $window_size, $pad_string, STR_PAD_BOTH)."\n";
}

echo center('foo');
echo center('bar baz', '=');

"The Controls collection cannot be modified because the control contains code blocks"

Tags <%= %> not works into a tag with runat="server". Move your code with <%= %> into runat="server" to an other tag (body, head, ...), or remove runat="server" from container.

Abort trap 6 error in C

Try this:

void drawInitialNim(int num1, int num2, int num3){
    int board[3][50] = {0}; // This is a local variable. It is not possible to use it after returning from this function. 

    int i, j, k;

    for(i=0; i<num1; i++)
        board[0][i] = 'O';
    for(i=0; i<num2; i++)
        board[1][i] = 'O';
    for(i=0; i<num3; i++)
        board[2][i] = 'O';

    for (j=0; j<3;j++) {
        for (k=0; k<50; k++) {
            if(board[j][k] != 0)
                printf("%c", board[j][k]);
        }
        printf("\n");
    }
}

C++ "was not declared in this scope" compile error

The first argument to nonrecursivecountcells() doesn't have a variable name. You try to reference it as grid in the function body, so you probably want to call it grid.

Check if string ends with one of the strings from a list

Though not widely known, str.endswith also accepts a tuple. You don't need to loop.

>>> 'test.mp3'.endswith(('.mp3', '.avi'))
True

Get device token for push notification

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

    let tokenParts = deviceToken.map { data -> String in
        return String(format: "%02.2hhx", data)
        }
    let token = tokenParts.joined()

    print("Token\(token)")
}

Compare 2 arrays which returns difference

This should work with unsorted arrays, double values and different orders and length, while giving you the filtered values form array1, array2, or both.

function arrayDiff(arr1, arr2) {
    var diff = {};

    diff.arr1 = arr1.filter(function(value) {
        if (arr2.indexOf(value) === -1) {
            return value;
        }
    });

    diff.arr2 = arr2.filter(function(value) {
        if (arr1.indexOf(value) === -1) {
            return value;
        }
    });

    diff.concat = diff.arr1.concat(diff.arr2);

    return diff;
};

var firstArray = [1,2,3,4];
var secondArray = [4,6,1,4];

console.log( arrayDiff(firstArray, secondArray) );
console.log( arrayDiff(firstArray, secondArray).arr1 );
// => [ 2, 3 ]
console.log( arrayDiff(firstArray, secondArray).concat );
// => [ 2, 3, 6 ]

check the null terminating character in char*

To make this complete: while others now solved your problem :) I would like to give you a piece of good advice: don't reinvent the wheel.

size_t forward_length = strlen(forward);

Hide a EditText & make it visible by clicking a menu

Try phoneNumber.setVisibility(View.GONE);

Hibernate-sequence doesn't exist

I was getting the same error "com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mylocaldb.hibernate_sequence' doesn't exist".

Using spring mvc 4.3.7 and hibernate version 5.2.9, application is made using spring java based configuration. Now I have to add the hibernate.id.new_generator_mappings property mentioned by @Eva Mariam in my code like this:

@Autowired
    @Bean(name = "sessionFactory")
    public SessionFactory getSessionFactory(DataSource dataSource) {

        LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
        sessionBuilder.addProperties(getHibernateProperties());
        sessionBuilder.addAnnotatedClasses(User.class);

        return sessionBuilder.buildSessionFactory();
    }

    private Properties getHibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.show_sql", "true");
        properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        properties.put("hibernate.id.new_generator_mappings","false");
        return properties;
    }

And it worked like charm.

How to change the status bar background color and text color on iOS 7?

For bar color: You provide a custom background image for the bar.

For text color: Use the information in About Text Handling in iOS

How to save S3 object to a file using boto3

If you wish to download a version of a file, you need to use get_object.

import boto3

bucket = 'bucketName'
prefix = 'path/to/file/'
filename = 'fileName.ext'

s3c = boto3.client('s3')
s3r = boto3.resource('s3')

if __name__ == '__main__':
    for version in s3r.Bucket(bucket).object_versions.filter(Prefix=prefix + filename):
        file = version.get()
        version_id = file.get('VersionId')
        obj = s3c.get_object(
            Bucket=bucket,
            Key=prefix + filename,
            VersionId=version_id,
        )
        with open(f"{filename}.{version_id}", 'wb') as f:
            for chunk in obj['Body'].iter_chunks(chunk_size=4096):
                f.write(chunk)

Ref: https://botocore.amazonaws.com/v1/documentation/api/latest/reference/response.html

Convert string (without any separator) to list

A python string is a list of characters. You can iterate over it right now!

justdigits = ""
for char in string:
    if char.isdigit():
        justdigits += str(char)

How to compress a String in Java?

The ZIP algorithm is a combination of LZW and Huffman Trees. You can use one of theses algorithms separately.

The compression is based on 2 factors :

  • the repetition of substrings in your original chain (LZW): if there are a lot of repetitions, the compression will be efficient. This algorithm has good performances for compressing a long plain text, since words are often repeated
  • the number of each character in the compressed chain (Huffman): more the repartition between characters is unbalanced, more the compression will be efficient

In your case, you should try the LZW algorithm only. Used basically, the chain can be compressed without adding meta-informations: it is probably better for short strings compression.

For the Huffman algorithm, the coding tree has to be sent with the compressed text. So, for a small text, the result can be larger than the original text, because of the tree.

How to automatically start a service when running a docker container?

I have the same problem when I want to automatically start ssh service. I found that append

/etc/init.d/ssh start
to
~/.bashrc
can resolve it ,but only you open it with bash will do.

SQL Error: ORA-00913: too many values

this is a bit late.. but i have seen this problem occurs when you want to insert or delete one line from/to DB but u put/pull more than one line or more than one value ,

E.g:

you want to delete one line from DB with a specific value such as id of an item but you've queried a list of ids then you will encounter the same exception message.

regards.

How do I build a graphical user interface in C++?

I use FLTK because Qt is not free. I don't choose wxWidgets, because my first test with a simple Hello, World! program produced an executable of 24 MB, FLTK 0.8 MB...

regular expression: match any word until first space

Derived from the answer of @SilentGhost I would use:

^([\S]+)

Check out this interactive regexr.com page to see the result and explanation for the suggested solution.

How can I check if a MySQL table exists with PHP?

DO NOT USE MYSQL ANY MORE. If you must use mysqli but PDO is best:

$pdo = new PDO($dsn, $username, $pdo); // proper PDO init string here
if ($pdo->query("SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'db_name'")->fetch()) // table exists.

How do I get to IIS Manager?

You need to make sure the IIS Management Console is installed.

javascript: optional first argument in function

With ES6:

function test(a, b = 3) {
   console.log(a, ' ', b);
}

test(1);      // Output: 1 3
test(1, 2);   // Output: 1 2

How to set the From email address for mailx command?

On macOS Sierra, creating ~/.mailrc with smtp setup did the trick:

set smtp-use-starttls
set smtp=smtp://smtp.gmail.com:587
set smtp-auth=login
set [email protected]
set smtp-auth-password=yourpass

Then to send mail from CLI:

echo "your message" | mail -s "your subject" [email protected]

initializing a boolean array in java

I just need to initialize all the array elements to Boolean false.

Either use boolean[] instead so that all values defaults to false:

boolean[] array = new boolean[size];

Or use Arrays#fill() to fill the entire array with Boolean.FALSE:

Boolean[] array = new Boolean[size];
Arrays.fill(array, Boolean.FALSE);

Also note that the array index is zero based. The freq[Global.iParameter[2]] = false; line as you've there would cause ArrayIndexOutOfBoundsException. To learn more about arrays in Java, consult this basic Oracle tutorial.

C++ initial value of reference to non-const must be an lvalue

When you pass a pointer by a non-const reference, you are telling the compiler that you are going to modify that pointer's value. Your code does not do that, but the compiler thinks that it does, or plans to do it in the future.

To fix this error, either declare x constant

// This tells the compiler that you are not planning to modify the pointer
// passed by reference
void test(float * const &x){
    *x = 1000;
}

or make a variable to which you assign a pointer to nKByte before calling test:

float nKByte = 100.0;
// If "test()" decides to modify `x`, the modification will be reflected in nKBytePtr
float *nKBytePtr = &nKByte;
test(nKBytePtr);

'App not Installed' Error on Android

In case, you have your app's older version installed from Google Play and you want to test the newer release version of your app:

  1. Open Google Play Console

  2. Upload the newer release version of your app to Alpha / Beta, but do not release it yet!

enter image description here

  1. You can now download the derived apk:
    enter image description here

Install the downloaded derived apk on your phone now. The derived apk is re-signed by Google Play with a different key from the release app Android Studio generates.

What throws an IOException in Java?

Assume you were:

  1. Reading a network file and got disconnected.
  2. Reading a local file that was no longer available.
  3. Using some stream to read data and some other process closed the stream.
  4. Trying to read/write a file, but don't have permission.
  5. Trying to write to a file, but disk space was no longer available.

There are many more examples, but these are the most common, in my experience.

In SQL how to compare date values?

You could add the time component

WHERE mydate<='2008-11-25 23:59:59'

but that might fail on DST switchover dates if mydate is '2008-11-25 24:59:59', so it's probably safest to grab everything before the next date:

WHERE mydate < '2008-11-26 00:00:00'

CSS Disabled scrolling

overflow-x: hidden;
would hide any thing on the x-axis that goes outside of the element, so there would be no need for the horizontal scrollbar and it get removed.

overflow-y: hidden;
would hide any thing on the y-axis that goes outside of the element, so there would be no need for the vertical scrollbar and it get removed.

overflow: hidden;
would remove both scrollbars

Adding a css class to select using @Html.DropDownList()

There are some options in constructors look, if you don't have dropdownList and you wanna insert CSS class you can use like

@Html.DropDownList("Country", null, "Choose-Category", new {@class="form-control"})

in this case Country is the name of your dropdown, null is for you aren't passing any generic list from your controller "Choose-Category" is selected item and last one in CSS class if you don't wanna select any default option so simple replace "Choose-Category" with ""

Is there a way to specify which pytest tests to run from a file?

If you have the same method name in two different classes and you just want to run one of them, this works:

pytest tests.py -k 'TestClassName and test_method_name'

Renaming Columns in an SQL SELECT Statement

You can alias the column names one by one, like so

SELECT col1 as `MyNameForCol1`, col2 as `MyNameForCol2` 
FROM `foobar`

Edit You can access INFORMATION_SCHEMA.COLUMNS directly to mangle a new alias like so. However, how you fit this into a query is beyond my MySql skills :(

select CONCAT('Foobar_', COLUMN_NAME)
from INFORMATION_SCHEMA.COLUMNS 
where TABLE_NAME = 'Foobar'

MS SQL 2008 - get all table names and their row counts in a DB

to get all tables in a database:

select * from INFORMATION_SCHEMA.TABLES

to get all columns in a database:

select * from INFORMATION_SCHEMA.columns

to get all views in a db:

select * from INFORMATION_SCHEMA.TABLES where table_type = 'view'

awk - concatenate two string variable and assign to a third

Could use sprintf to accomplish this:

awk '{str = sprintf("%s %s", $1, $2)} END {print str}' file

compilation error: identifier expected

You have not defined a method around your code.

import java.io.*;

public class details
{
    public static void main( String[] args )
    {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

In this case, I have assumed that you want your code to be executed in the main method of the class. It is, of course, possible that this code goes in any other method.

How do I clear my Jenkins/Hudson build history?

Go to the %HUDSON_HOME%\jobs\<projectname> remove builds dir and remove lastStable, lastSuccessful links, and remove nextBuildNumber file.

After doing above steps go to below link from UI
Jenkins-> Manage Jenkins -> Reload Configuration from Disk

It will do as you need

Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one?

You can use LOG such as :

Log.e(String, String) (error)
Log.w(String, String) (warning)
Log.i(String, String) (information)
Log.d(String, String) (debug)
Log.v(String, String) (verbose)

example code:

private static final String TAG = "MyActivity";
...
Log.i(TAG, "MyClass.getView() — get item number " + position);

What is the best open source help ticket system?

"Best" helpdesk system is very subjective, of course, but I recommend Request Tracker (aka RT).

It has a default workflow built in, but is easily configured for alternate workflows using the "Scrips" and templates. Very extensible if you want.

How do I increase the contrast of an image in Python OpenCV

img = cv2.imread("/x2.jpeg")

image = cv2.resize(img, (1800, 1800))

alpha=1.5
beta=20

new_image=cv2.addWeighted(image,alpha,np.zeros(image.shape, image.dtype),0,beta)

cv2.imshow("new",new_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Show Image View from file path?

Most of the answers are working but no one mentioned that the high resolution image will slow down the app , In my case i used images RecyclerView which was taking 0.9 GB of device memory In Just 30 Images.

I/Choreographer: Skipped 73 frames! The application may be doing too much work on its main thread.

The solution is Sipmle you can degrade the quality like here : Reduce resolution of Bitmap

But I use Simple way , Glide handles the rest of work

fanContext?.let {
            Glide.with(it)
                .load(Uri.fromFile(File(item.filePath)))
                .into(viewHolder.imagePreview)
        }

How to install Cmake C compiler and CXX compiler

Those errors :

"CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage

CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage"

means you haven't installed mingw32-base.

Go to http://sourceforge.net/projects/mingw/files/latest/download?source=files

and then make sure you select "mingw32-base"

Make sure you set up environment variables correctly in PATH section. "C:\MinGW\bin"

After that open CMake and Select Installation --> Delete Cache.

And click configure button again. I solved the problem this way, hope you solve the problem.

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

I Don't know why, but in my case, even if I remove bin folder from project, when I build project it copies old version of newtonsoft.json, I copied new version's dll from packages folder and It solves for now.

Gradle Build Android Project "Could not resolve all dependencies" error

I had this message in Android Studio 2.1.1 in the Gradle Build tab. I installed a lot of files from the SDK Manager but it did not help.

I needed to click the next tab "Gradle Sync". There was a link "Install Repository and sync project" which installed the "Android Support Repository".

Opening a CHM file produces: "navigation to the webpage was canceled"

Summary

Microsoft Security Updates 896358 & 840315 block display of CHM file contents when opened from a network drive (or a UNC path). This is Windows' attempt to stop attack vectors for viruses/malware from infecting your computer and has blocked out the .chm file that draw data over the "InfoTech" protocol, which this chm file uses.

Microsoft's summary of the problem: http://support.microsoft.com/kb/896054

Solutions

  1. If you are using Windows Server 2008, Windows 7, windows has created a quick fix. Right click the chm file, and you will get the "yourfile.chm Properties" dialog box, at the bottom, a button called "Unblock" appears. Click Unblock and press OK, and try to open the chm file again, it works correctly. This option is not available for earlier versions of Windows before WindowsXP (SP3).

  2. Solve the problem by moving your chm file OFF the network drive. You may be unaware you are using a network drive, double check now: Right click your .chm file, click properties and look at the "location" field. If it starts with two backslashes like this: \\epicserver\blah\, then you are using a networked drive. So to fix it, Copy the chm file, and paste it into a local drive, like C:\ or E:. Then try to reopen the chm file, windows does not freak out.

  3. Last resort, if you can't copy/move the file off the networked drive. If you must open it where it sits, and you are using a lesser version of windows like XP, Vista, ME or other, you will have to manually tell Windows not to freak out over this .chm file. HHReg (HTML Help Registration Utility) Utility Automates this Task. Basically you download the HHReg utility, load your .chm file, press OK, and it will create the necessary registry keys to tell Windows not to block it. For more info: http://www.winhelponline.com/blog/fix-cannot-view-chm-files-network-xp-2003-vista/

Windows 8 or 10? --> Upgrade to Windows XP.

What is the difference between And and AndAlso in VB.NET?

AndAlso is much like And, except it works like && in C#, C++, etc.

The difference is that if the first clause (the one before AndAlso) is true, the second clause is never evaluated - the compound logical expression is "short circuited".

This is sometimes very useful, e.g. in an expression such as:

If Not IsNull(myObj) AndAlso myObj.SomeProperty = 3 Then
   ...
End If

Using the old And in the above expression would throw a NullReferenceException if myObj were null.

How do I break out of a loop in Perl?

Additional data (in case you have more questions):

FOO: {
       for my $i ( @listone ){
          for my $j ( @listtwo ){
                 if ( cond( $i,$j ) ){

                    last FOO;  # --->
                                   # |
                 }                 # |
          }                        # |
       }                           # |
 } # <-------------------------------

How to uninstall a package installed with pip install --user

Be careful though, for those who using pip install --user some_pkg inside a virtual environment.

$ path/to/python -m venv ~/my_py_venv
$ source ~/my_py_venv/bin/activate
(my_py_venv) $ pip install --user some_pkg
(my_py_venv) $ pip uninstall some_pkg
WARNING: Skipping some_pkg as it is not installed.
(my_py_venv) $ pip list
# Even `pip list` will not properly list the `some_pkg` in this case

In this case, you have to deactivate the current virtual environment, then use the corresponding python/pip executable to list or uninstall the user site packages:

(my_py_venv) $ deactivate
$ path/to/python -m pip list
$ path/to/python -m pip uninstall some_pkg

Note that this issue was reported few years ago. And it seems that the current conclusion is: --user is not valid inside a virtual env's pip, since a user location doesn't really make sense for a virtual environment.

How can I rollback an UPDATE query in SQL server 2005?

You can use implicit transactions for this

SET IMPLICIT_TRANSACTIONS ON

update Staff set staff_Name='jas' where staff_id=7

ROLLBACK

As you request-- You can SET this setting ( SET IMPLICIT_TRANSACTIONS ON) from a stored procedure by setting that stored procedure as the start up procedure.

But SET IMPLICIT TRANSACTION ON command is connection specific. So any connection other than the one which running the start up stored procedure will not benefit from the setting you set.

SQL Server stored procedure parameters

Why would you pass a parameter to a stored procedure that doesn't use it?

It sounds to me like you might be better of building dynamic SQL statements and then executing them. What you are trying to do with the SP won't work, and even if you could change what you are doing in such a way to accommodate varying numbers of parameters, you would then essentially be using dynamically generated SQL you are defeating the purpose of having/using a SP in the first place. SP's have a role, but there are not the solution in all cases.

How to make a promise from setTimeout

const setTimeoutAsync = (cb, delay) =>
  new Promise((resolve) => {
    setTimeout(() => {
      resolve(cb());
    }, delay);
  });

We can pass custom 'cb fxn' like this one

How to check if an element exists in the xml using xpath?

Normally when you try to select a node using xpath your xpath-engine will return null or equivalent if the node doesn't exists.

xpath: "/Consumers/Consumer/DataSources/Credit/CreditReport/AttachedXml"

If your using xsl check out this question for an answer:

xpath find if node exists

"Debug certificate expired" error in Eclipse Android plugins

To fix this problem, simply delete the debug.keystore file.

The default storage location for AVDs is

In ~/.android/ on OS X and Linux.

In C:\Documents and Settings\.android\ on Windows XP

In C:\Users\.android\ on Windows Vista and Windows 7.

Also see this link, which can be helpful.

http://developer.android.com/tools/publishing/app-signing.html

How to return first 5 objects of Array in Swift?

For an array of objects you can create an extension from Sequence.

extension Sequence {
    func limit(_ max: Int) -> [Element] {
        return self.enumerated()
            .filter { $0.offset < max }
            .map { $0.element }
    }
}

Usage:

struct Apple {}

let apples: [Apple] = [Apple(), Apple(), Apple()]
let limitTwoApples = apples.limit(2)

// limitTwoApples: [Apple(), Apple()]

RichTextBox (WPF) does not have string property "Text"

According to this it does have a Text property

http://msdn.microsoft.com/en-us/library/system.windows.forms.richtextbox_members.aspx

You can also try the "Lines" property if you want the text broken up as lines.

End-line characters from lines read from text file, using Python

Simple. Use splitlines()

L = open("myFile.txt", "r").read().splitlines();
for line in L: 
    process(line) # this 'line' will not have '\n' character at the end

Python element-wise tuple operations like sum

simple solution without class definition that returns tuple

import operator
tuple(map(operator.add,a,b))

How to change the URI (URL) for a remote Git repository?

Change Host for a Git Origin Server

from: http://pseudofish.com/blog/2010/06/28/change-host-for-a-git-origin-server/

Hopefully this isn’t something you need to do. The server that I’ve been using to collaborate on a few git projects with had the domain name expire. This meant finding a way of migrating the local repositories to get back in sync.

Update: Thanks to @mawolf for pointing out there is an easy way with recent git versions (post Feb, 2010):

git remote set-url origin ssh://newhost.com/usr/local/gitroot/myproject.git

See the man page for details.

If you’re on an older version, then try this:

As a caveat, this works only as it is the same server, just with different names.

Assuming that the new hostname is newhost.com, and the old one was oldhost.com, the change is quite simple.

Edit the .git/config file in your working directory. You should see something like:

[remote "origin"]
fetch = +refs/heads/*:refs/remotes/origin/*
url = ssh://oldhost.com/usr/local/gitroot/myproject.git

Change oldhost.com to newhost.com, save the file and you’re done.

From my limited testing (git pull origin; git push origin; gitx) everything seems in order. And yes, I know it is bad form to mess with git internals.

Hibernate, @SequenceGenerator and allocationSize

I too faced this issue in Hibernate 5:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = SEQUENCE)
@SequenceGenerator(name = SEQUENCE, sequenceName = SEQUENCE)
private Long titId;

Got a warning like this below:

Found use of deprecated [org.hibernate.id.SequenceHiLoGenerator] sequence-based id generator; use org.hibernate.id.enhanced.SequenceStyleGenerator instead. See Hibernate Domain Model Mapping Guide for details.

Then changed my code to SequenceStyleGenerator:

@Id
@GenericGenerator(name="cmrSeq", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
        parameters = {
                @Parameter(name = "sequence_name", value = "SEQUENCE")}
)
@GeneratedValue(generator = "sequence_name")
private Long titId;

This solved my two issues:

  1. The deprecated warning is fixed
  2. Now the id is generated as per the oracle sequence.

How to connect to a remote Windows machine to execute commands using python?

Many answers already, but one more option

PyPSExec https://pypi.org/project/pypsexec/

It's a python clone of the famous psexec. Works without any installation on the remote windows machine.

Illegal character in path at index 16

Did you try this?

new File("<PATH OF YOUR FILE>").toURI().toString();

How to enable copy paste from between host machine and virtual machine in vmware, virtual machine is ubuntu

the mremote option offers more automation and almost replicates the vmware workstation graphical experience plus major benefits: NO DPI (guest resolution) hassle no copy pose hassle Automation = starting vms and suspending them automatically plus more if you look deeper

:last-child not working as expected?

I encounter similar situation. I would like to have background of the last .item to be yellow in the elements that look like...

<div class="container">
  <div class="item">item 1</div>
  <div class="item">item 2</div>
  <div class="item">item 3</div>
  ...
  <div class="item">item x</div>
  <div class="other">I'm here for some reasons</div>
</div>

I use nth-last-child(2) to achieve it.

.item:nth-last-child(2) {
  background-color: yellow;
}

It strange to me because nth-last-child of item suppose to be the second of the last item but it works and I got the result as I expect. I found this helpful trick from CSS Trick

Convert output of MySQL query to utf8

You can use CAST and CONVERT to switch between different types of encodings. See: http://dev.mysql.com/doc/refman/5.0/en/charset-convert.html

SELECT column1, CONVERT(column2 USING utf8)
FROM my_table 
WHERE my_condition;

The best node module for XML parsing

You can try xml2js. It's a simple XML to JavaScript object converter. It gets your XML converted to a JS object so that you can access its content with ease.

Here are some other options:

  1. libxmljs
  2. xml-stream
  3. xmldoc
  4. cheerio – implements a subset of core jQuery for XML (and HTML)

I have used xml2js and it has worked fine for me. The rest you might have to try out for yourself.

How can I divide one column of a data frame through another?

Hadley Wickham

dplyr

packages is always a saver in case of data wrangling. To add the desired division as a third variable I would use mutate()

d <- mutate(d, new = min / count2.freq)

Excel - match data from one range to another and get the value from the cell to the right of the matched data

Thanks a bundle, guys. You are great.

I used Chuff's answer and modified it a little to do what I wanted.

I have 2 worksheets in the same workbook.

On 1st worksheet I have a list of SMS in 3 columns: phone number, date & time, message

Then I inserted a new blank column next to the phone number

On worksheet 2 I have two columns: phone number, name of person

Used the formula to check the cell on the left, and match against the range in worksheet 2, pick the name corresponding to the number and input it into the blank cell in worksheet 1.

Then just copy the formula down the whole column until last sms It worked beautifully.

=VLOOKUP(A3,Sheet2!$A$1:$B$31,2,0)

C++ Fatal Error LNK1120: 1 unresolved externals

You must reference it. To do this, open the shortcut menu for the project in Solution Explorer, and then choose References. In the Property Pages dialog box, expand the Common Properties node, select Framework and References, and then choose the Add New Reference button.

How to round up integer division and have int result in Java?

If you want to calculate a divided by b rounded up you can use (a+(-a%b))/b

Undefined Reference to

Try to remove the constructor and destructors, it's working for me....

Use custom build output folder when using create-react-app

You can update the configuration with a little hack, under your root directory:

  1. npm run eject
  2. config/webpack.config.prod.js - line 61 - change path to: __dirname + './../--your directory of choice--'
  3. config/paths.js - line 68 - update to resolveApp('./--your directory of choice--')

replace --your directory of choice-- with the folder directory you want it to build on

note the path I provided can be a bit dirty, but this is all you need to do to modify the configuration.

Difference between save and saveAndFlush in Spring data jpa

Depending on the hibernate flush mode that you are using (AUTO is the default) save may or may not write your changes to the DB straight away. When you call saveAndFlush you are enforcing the synchronization of your model state with the DB.

If you use flush mode AUTO and you are using your application to first save and then select the data again, you will not see a difference in bahvior between save() and saveAndFlush() because the select triggers a flush first. See the documention.

set the width of select2 input (through Angular-ui directive)

select2 V4.0.3

<select class="smartsearch" name="search" id="search" style="width:100%;"></select>

Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)

If you really need to transform a date to a LocalDateTime object, you could use the LocalDate.atStartOfDay(). This will give you a LocalDateTime object at the specified date, having the hour, minute and second fields set to 0:

final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDateTime time = LocalDate.parse("20140218", formatter).atStartOfDay();

AlertDialog.Builder with custom layout and EditText; cannot access view

Use this one

   AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    // Get the layout inflater
    LayoutInflater inflater = (activity).getLayoutInflater();
    // Inflate and set the layout for the dialog
    // Pass null as the parent view because its going in the
    // dialog layout
    builder.setTitle(title);
    builder.setCancelable(false);
    builder.setIcon(R.drawable.galleryalart);
    builder.setView(inflater.inflate(R.layout.dialogue, null))
    // Add action buttons
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {

                    }
                }
            });
    builder.create();
    builder.show();

How to install "ifconfig" command in my ubuntu docker image?

I came here because I was trying to use ifconfig on the container to find its IPAaddress and there was no ifconfig. If you really need ifconfig on the container go with @vishnu-narayanan answer above, however you may be able to get the information you need by using docker inspect on the host:

docker inspect <containerid>

There is lots of good stuff in the output including IPAddress of container:

"Networks": {
    "bridge": {
        "IPAMConfig": null,
        "Links": null,
        "Aliases": null,
        "NetworkID": "12345FAKEID",
        "EndpointID": "12345FAKEENDPOINTID",
        "Gateway": "172.17.0.1",
        "IPAddress": "172.17.0.3",
        "IPPrefixLen": 16,
        "IPv6Gateway": "",
        "GlobalIPv6Address": "",
        "GlobalIPv6PrefixLen": 0,
        "MacAddress": "01:02:03:04:05:06",
        "DriverOpts": null
    }
}

How to set a value to a file input in HTML?

Actually we can do it. we can set the file value default by using webbrowser control in c# using FormToMultipartPostData Library.We have to download and include this Library in our project. Webbrowser enables the user to navigate Web pages inside form. Once the web page loaded , the script inside the webBrowser1_DocumentCompleted will be executed. So,

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
       FormToMultipartPostData postData = 
            new FormToMultipartPostData(webBrowser1, form);
        postData.SetFile("fileField", @"C:\windows\win.ini");
        postData.Submit();
    }

Refer the below link for downloading and complete reference.

https://www.codeproject.com/Articles/28917/Setting-a-file-to-upload-inside-the-WebBrowser-com

Getting "TypeError: failed to fetch" when the request hasn't actually failed

If your are invoking fetch on a localhost server, use non-SSL unless you have a valid certificate for localhost. fetch will fail on an invalid or self signed certificate especially on localhost.

Total width of element (including padding and border) in jQuery

Anyone else stumbling upon this answer should note that jQuery now (>=1.3) has outerHeight/outerWidth functions to retrieve the width including padding/borders, e.g.

$(elem).outerWidth(); // Returns the width + padding + borders

To include the margin as well, simply pass true:

$(elem).outerWidth( true ); // Returns the width + padding + borders + margins

How To: Best way to draw table in console app (C#)

You could do something like the following:

static int tableWidth = 73;

static void Main(string[] args)
{
    Console.Clear();
    PrintLine();
    PrintRow("Column 1", "Column 2", "Column 3", "Column 4");
    PrintLine();
    PrintRow("", "", "", "");
    PrintRow("", "", "", "");
    PrintLine();
    Console.ReadLine();
}

static void PrintLine()
{
    Console.WriteLine(new string('-', tableWidth));
}

static void PrintRow(params string[] columns)
{
    int width = (tableWidth - columns.Length) / columns.Length;
    string row = "|";

    foreach (string column in columns)
    {
        row += AlignCentre(column, width) + "|";
    }

    Console.WriteLine(row);
}

static string AlignCentre(string text, int width)
{
    text = text.Length > width ? text.Substring(0, width - 3) + "..." : text;

    if (string.IsNullOrEmpty(text))
    {
        return new string(' ', width);
    }
    else
    {
        return text.PadRight(width - (width - text.Length) / 2).PadLeft(width);
    }
}

Integer.valueOf() vs. Integer.parseInt()

Actually, valueOf uses parseInt internally. The difference is parseInt returns an int primitive while valueOf returns an Integer object. Consider from the Integer.class source:

public static int parseInt(String s) throws NumberFormatException {
    return parseInt(s, 10);
}

public static Integer valueOf(String s, int radix) throws NumberFormatException {
    return Integer.valueOf(parseInt(s, radix));
}

public static Integer valueOf(String s) throws NumberFormatException {
    return Integer.valueOf(parseInt(s, 10));
}

As for parsing with a comma, I'm not familiar with one. I would sanitize them.

int million = Integer.parseInt("1,000,000".replace(",", ""));

Check whether an input string contains a number in javascript

You can do this using javascript. No need for Jquery or Regex

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

While implementing

var val = $('yourinputelement').val();
if(isNumeric(val)) { alert('number'); } 
else { alert('not number'); }

Update: To check if a string has numbers in them, you can use regular expressions to do that

var matches = val.match(/\d+/g);
if (matches != null) {
    alert('number');
}

Get the row(s) which have the max value in groups using groupby

For me, the easiest solution would be keep value when count is equal to the maximum. Therefore, the following one line command is enough :

df[df['count'] == df.groupby(['Mt'])['count'].transform(max)]

Creating files and directories via Python

    import os
    os.mkdir('directory name') #### this command for creating directory
    os.mknod('file name') #### this for creating files
    os.system('touch filename') ###this is another method for creating file by using unix commands in os modules 

How do I make Java register a string input with spaces?

I found a very weird thing in Java today, so it goes like -

If you are inputting more than 1 thing from the user, say

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
String s = sc.nextLine();

System.out.println(i);
System.out.println(d);
System.out.println(s);

So, it might look like if we run this program, it will ask for these 3 inputs and say our input values are 10, 2.5, "Welcome to java" The program should print these 3 values as it is, as we have used nextLine() so it shouldn't ignore the text after spaces that we have entered in our variable s

But, the output that you will get is -

10
2.5

And that's it, it doesn't even prompt for the String input. Now I was reading about it and to be very honest there are still some gaps in my understanding, all I could figure out was after taking the int input and then the double input when we press enter, it considers that as the prompt and ignores the nextLine().

So changing my code to something like this -

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();

System.out.println(i);
System.out.println(d);
System.out.println(s);

does the job perfectly, so it is related to something like "\n" being stored in the keyboard buffer in the previous example which we can bypass using this.

Please if anybody knows help me with an explanation for this.

C# : 'is' keyword and checking for Not

Ugly? I disagree. The only other way (I personally think this is "uglier"):

var obj = child as IContainer;
if(obj == null)
{
   //child "aint" IContainer
}

Kafka consumer list

Kafka stores all the information in zookeeper. You can see all the topic related information under brokers->topics. If you wish to get all the topics programmatically you can do that using Zookeeper API.

It is explained in detail in below links Tutorialspoint, Zookeeper Programmer guide

How to fix the Eclipse executable launcher was unable to locate its companion shared library for windows 7?

In my case eclipse.ini entry for --launcher.library was :

--launcher.library C:\Users\UserName\.p2\pool\plugins\org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.551.v20171108-1834

and on my machine 'C:\Users\UserName\.p2\' folder was missing hence installed the eclipse again which created the .p2 folder structure at required location and now I am able to login successfully.

Entityframework Join using join method and lambdas

Generally i prefer the lambda syntax with LINQ, but Join is one example where i prefer the query syntax - purely for readability.

Nonetheless, here is the equivalent of your above query (i think, untested):

var query = db.Categories         // source
   .Join(db.CategoryMaps,         // target
      c => c.CategoryId,          // FK
      cm => cm.ChildCategoryId,   // PK
      (c, cm) => new { Category = c, CategoryMaps = cm }) // project result
   .Select(x => x.Category);  // select result

You might have to fiddle with the projection depending on what you want to return, but that's the jist of it.

How to permanently remove few commits from remote branch

If you want to delete for example the last 3 commits, run the following command to remove the changes from the file system (working tree) and commit history (index) on your local branch:

git reset --hard HEAD~3

Then run the following command (on your local machine) to force the remote branch to rewrite its history:

git push --force

Congratulations! All DONE!

Some notes:

You can retrieve the desired commit id by running

git log

Then you can replace HEAD~N with <desired-commit-id> like this:

git reset --hard <desired-commit-id>

If you want to keep changes on file system and just modify index (commit history), use --soft flag like git reset --soft HEAD~3. Then you have chance to check your latest changes and keep or drop all or parts of them. In the latter case runnig git status shows the files changed since <desired-commit-id>. If you use --hard option, git status will tell you that your local branch is exactly the same as the remote one. If you don't use --hard nor --soft, the default mode is used that is --mixed. In this mode, git help reset says:

Resets the index but not the working tree (i.e., the changed files are preserved but not marked for commit) and reports what has not been updated.

Escape double quote in VB string

Did you try using double-quotes? Regardless, no one in 2011 should be limited by the native VB6 shell command. Here's a function that uses ShellExecuteEx, much more versatile.

Option Explicit

Private Const SEE_MASK_DEFAULT = &H0

Public Enum EShellShowConstants
        essSW_HIDE = 0
        essSW_SHOWNORMAL = 1
        essSW_SHOWMINIMIZED = 2
        essSW_MAXIMIZE = 3
        essSW_SHOWMAXIMIZED = 3
        essSW_SHOWNOACTIVATE = 4
        essSW_SHOW = 5
        essSW_MINIMIZE = 6
        essSW_SHOWMINNOACTIVE = 7
        essSW_SHOWNA = 8
        essSW_RESTORE = 9
        essSW_SHOWDEFAULT = 10
End Enum

Private Type SHELLEXECUTEINFO
        cbSize        As Long
        fMask         As Long
        hwnd          As Long
        lpVerb        As String
        lpFile        As String
        lpParameters  As String
        lpDirectory   As String
        nShow         As Long
        hInstApp      As Long
        lpIDList      As Long     'Optional
        lpClass       As String   'Optional
        hkeyClass     As Long     'Optional
        dwHotKey      As Long     'Optional
        hIcon         As Long     'Optional
        hProcess      As Long     'Optional
End Type

Private Declare Function ShellExecuteEx Lib "shell32.dll" Alias "ShellExecuteExA" (lpSEI As SHELLEXECUTEINFO) As Long

Public Function ExecuteProcess(ByVal FilePath As String, ByVal hWndOwner As Long, ShellShowType As EShellShowConstants, Optional EXEParameters As String = "", Optional LaunchElevated As Boolean = False) As Boolean
    Dim SEI As SHELLEXECUTEINFO

    On Error GoTo Err

    'Fill the SEI structure
    With SEI
        .cbSize = Len(SEI)                  ' Bytes of the structure
        .fMask = SEE_MASK_DEFAULT           ' Check MSDN for more info on Mask
        .lpFile = FilePath                  ' Program Path
        .nShow = ShellShowType              ' How the program will be displayed
        .lpDirectory = PathGetFolder(FilePath)
        .lpParameters = EXEParameters       ' Each parameter must be separated by space. If the lpFile member specifies a document file, lpParameters should be NULL.
        .hwnd = hWndOwner                   ' Owner window handle

        ' Determine launch type (would recommend checking for Vista or greater here also)
        If LaunchElevated = True Then ' And m_OpSys.IsVistaOrGreater = True
            .lpVerb = "runas"
        Else
            .lpVerb = "Open"
        End If
    End With

     ExecuteProcess = ShellExecuteEx(SEI)   ' Execute the program, return success or failure

    Exit Function
Err:
    ' TODO: Log Error
    ExecuteProcess = False
End Function

Private Function PathGetFolder(psPath As String) As String
    On Error Resume Next
    Dim lPos As Long
    lPos = InStrRev(psPath, "\")
    PathGetFolder = Left$(psPath, lPos - 1)
End Function

Returning a C string from a function

Or how about this one:

void print_month(int month)
{
    switch (month)
    {
        case 0:
            printf("January");
            break;
        case 1:
            printf("february");
            break;
        ...etc...
    }
}

And call that with the month you compute somewhere else.

INSERT INTO...SELECT for all MySQL columns

Addition to Mark Byers answer :

Sometimes you also want to insert Hardcoded details else there may be Unique constraint fail etc. So use following in such situation where you override some values of the columns.

INSERT INTO matrimony_domain_details (domain, type, logo_path)
SELECT 'www.example.com', type, logo_path
FROM matrimony_domain_details
WHERE id = 367

Here domain value is added by me me in Hardcoded way to get rid from Unique constraint.

Creating and Update Laravel Eloquent

Isn't this the same as updateOrCreate()?

It is similar but not the same. The updateOrCreate() will only work for one row at a time which doesn't allow bulk insert. InsertOnDuplicateKey will work on many rows.

https://github.com/yadakhov/insert-on-duplicate-key

How to draw a circle with given X and Y coordinates as the middle spot of the circle?

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Graphics;
import javax.swing.JFrame;

public class Graphiic
{   
    public Graphics GClass;
    public Graphics2D G2D;
    public  void Draw_Circle(JFrame jf,int radius , int  xLocation, int yLocation)
    {
        GClass = jf.getGraphics();
        GClass.setPaintMode();
        GClass.setColor(Color.MAGENTA);
        GClass.fillArc(xLocation, yLocation, radius, radius, 0, 360);
        GClass.drawLine(100, 100, 200, 200);    
    }

}

How do I stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?

If you can simply change the href value, you should use:

<a href="javascript:void(0);">Link Title</a>

Another neat solution I just came up with is to use jQuery to stop the click action from occurring and causing the page to scroll, but only for href="#" links.

<script type="text/javascript">
    /* Stop page jumping when links are pressed */
    $('a[href="#"]').live("click", function(e) {
         return false; // prevent default click action from happening!
         e.preventDefault(); // same thing as above
    });
</script>

Get file size, image width and height before upload

Multiple images upload with info data preview

Using HTML5 and the File API

Example using URL API

The images sources will be a URL representing the Blob object
<img src="blob:null/026cceb9-edr4-4281-babb-b56cbf759a3d">

_x000D_
_x000D_
const EL_browse  = document.getElementById('browse');_x000D_
const EL_preview = document.getElementById('preview');_x000D_
_x000D_
const readImage  = file => {_x000D_
  if ( !(/^image\/(png|jpe?g|gif)$/).test(file.type) )_x000D_
    return EL_preview.insertAdjacentHTML('beforeend', `Unsupported format ${file.type}: ${file.name}<br>`);_x000D_
_x000D_
  const img = new Image();_x000D_
  img.addEventListener('load', () => {_x000D_
    EL_preview.appendChild(img);_x000D_
    EL_preview.insertAdjacentHTML('beforeend', `<div>${file.name} ${img.width}×${img.height} ${file.type} ${Math.round(file.size/1024)}KB<div>`);_x000D_
    window.URL.revokeObjectURL(img.src); // Free some memory_x000D_
  });_x000D_
  img.src = window.URL.createObjectURL(file);_x000D_
}_x000D_
_x000D_
EL_browse.addEventListener('change', ev => {_x000D_
  EL_preview.innerHTML = ''; // Remove old images and data_x000D_
  const files = ev.target.files;_x000D_
  if (!files || !files[0]) return alert('File upload not supported');_x000D_
  [...files].forEach( readImage );_x000D_
});
_x000D_
#preview img { max-height: 100px; }
_x000D_
<input id="browse" type="file" multiple>_x000D_
<div id="preview"></div>
_x000D_
_x000D_
_x000D_

Example using FileReader API

In case you need images sources as long Base64 encoded data strings
<img src="data:image/png;base64,iVBORw0KGg... ...lF/++TkSuQmCC=">

_x000D_
_x000D_
const EL_browse  = document.getElementById('browse');_x000D_
const EL_preview = document.getElementById('preview');_x000D_
_x000D_
const readImage = file => {_x000D_
  if ( !(/^image\/(png|jpe?g|gif)$/).test(file.type) )_x000D_
    return EL_preview.insertAdjacentHTML('beforeend', `<div>Unsupported format ${file.type}: ${file.name}</div>`);_x000D_
_x000D_
  const reader = new FileReader();_x000D_
  reader.addEventListener('load', () => {_x000D_
    const img  = new Image();_x000D_
    img.addEventListener('load', () => {_x000D_
      EL_preview.appendChild(img);_x000D_
      EL_preview.insertAdjacentHTML('beforeend', `<div>${file.name} ${img.width}×${img.height} ${file.type} ${Math.round(file.size/1024)}KB</div>`);_x000D_
    });_x000D_
    img.src = reader.result;_x000D_
  });_x000D_
  reader.readAsDataURL(file);  _x000D_
};_x000D_
_x000D_
EL_browse.addEventListener('change', ev => {_x000D_
  EL_preview.innerHTML = ''; // Clear Preview_x000D_
  const files = ev.target.files;_x000D_
  if (!files || !files[0]) return alert('File upload not supported');_x000D_
  [...files].forEach( readImage );_x000D_
});
_x000D_
#preview img { max-height: 100px; }
_x000D_
<input id="browse" type="file"  multiple>_x000D_
<div id="preview"></div>_x000D_
  
_x000D_
_x000D_
_x000D_

How to convert an array of strings to an array of floats in numpy?

You can use this as well

import numpy as np
x=np.array(['1.1', '2.2', '3.3'])
x=np.asfarray(x,float)

Where should I put <script> tags in HTML markup?

If you are using JQuery then put the javascript wherever you find it best and use $(document).ready() to ensure that things are loaded properly before executing any functions.

On a side note: I like all my script tags in the <head> section as that seems to be the cleanest place.

java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

It is simple just write java -XshowSettings:properties on your command line in windows and then paste all the files in the path shown by the java.library.path.

ExecuteNonQuery: Connection property has not been initialized.

You need to assign the connection to the SqlCommand, you can use the constructor or the property:

cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ");
cmd.InsertCommand.Connection = connection1;

I strongly recommend to use the using-statement for any type implementing IDisposable like SqlConnection, it'll also close the connection:

using(var connection1 = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=syslog2;Integrated Security=True"))
using(var cmd = new SqlDataAdapter())
using(var insertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) "))
{
    insertCommand.Connection = connection1;
    cmd.InsertCommand = insertCommand;
    //.....
    connection1.Open();
    // .... you don't need to close the connection explicitely
}

Apart from that you don't need to create a new connection and DataAdapter for every entry in the foreach, even if creating, opening and closing a connection does not mean that ADO.NET will create, open and close a physical connection but just looks into the connection-pool for an available connection. Nevertheless it's an unnecessary overhead.

Semaphore vs. Monitors - what's the difference?

Following explanation actually explains how wait() and signal() of monitor differ from P and V of semaphore.

The wait() and signal() operations on condition variables in a monitor are similar to P and V operations on counting semaphores.

A wait statement can block a process's execution, while a signal statement can cause another process to be unblocked. However, there are some differences between them. When a process executes a P operation, it does not necessarily block that process because the counting semaphore may be greater than zero. In contrast, when a wait statement is executed, it always blocks the process. When a task executes a V operation on a semaphore, it either unblocks a task waiting on that semaphore or increments the semaphore counter if there is no task to unlock. On the other hand, if a process executes a signal statement when there is no other process to unblock, there is no effect on the condition variable. Another difference between semaphores and monitors is that users awaken by a V operation can resume execution without delay. Contrarily, users awaken by a signal operation are restarted only when the monitor is unlocked. In addition, a monitor solution is more structured than the one with semaphores because the data and procedures are encapsulated in a single module and that the mutual exclusion is provided automatically by the implementation.

Link: here for further reading. Hope it helps.

IntelliJ inspection gives "Cannot resolve symbol" but still compiles code

In my case, a colleague added Lombok to the project, and I had to install the Idea Lombok plug-in. In your case, it may be something else that requires a plug-in.

Jackson with JSON: Unrecognized field, not marked as ignorable

using Jackson 2.6.0, this worked for me:

private static final ObjectMapper objectMapper = 
    new ObjectMapper()
        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

and with setting:

@JsonIgnoreProperties(ignoreUnknown = true)

How does Java resolve a relative path in new File()?

There is a concept of a working directory.
This directory is represented by a . (dot).
In relative paths, everything else is relative to it.

Simply put the . (the working directory) is where you run your program.
In some cases the working directory can be changed but in general this is
what the dot represents. I think this is C:\JavaForTesters\ in your case.

So test\..\test.txt means: the sub-directory test
in my working directory, then one level up, then the
file test.txt. This is basically the same as just test.txt.

For more details check here.

http://docs.oracle.com/javase/7/docs/api/java/io/File.html

http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html

In android app Toolbar.setTitle method has no effect – application name is shown as title

The answer is in the documentation (which you can find here):

To use the ActionBar utility methods, call the activity's getSupportActionBar() method. This method returns a reference to an appcompat ActionBar object. Once you have that reference, you can call any of the ActionBar methods to adjust the app bar. For example, to hide the app bar, call ActionBar.hide().

That is the solution you actually found. Just thought of giving a reference to the official documentation (which apparently few tend to read).

Adding a new entry to the PATH variable in ZSH

Here, add this line to .zshrc:

export PATH=/home/david/pear/bin:$PATH

EDIT: This does work, but ony's answer below is better, as it takes advantage of the structured interface ZSH provides for variables like $PATH. This approach is standard for bash, but as far as I know, there is no reason to use it when ZSH provides better alternatives.

jQuery.getJSON - Access-Control-Allow-Origin Issue

It's simple, use $.getJSON() function and in your URL just include

callback=?

as a parameter. That will convert the call to JSONP which is necessary to make cross-domain calls. More info: http://api.jquery.com/jQuery.getJSON/

ios simulator: how to close an app

You can use this command to quit an app in iOS Simulator

xcrun simctl terminate booted com.apple.mobilesafari

You will need to know the bundle id of the app you have installed in the simulator. You can refer to this link

How do I use LINQ Contains(string[]) instead of Contains(string)

Linq extension method. Will work with any IEnumerable object:

    public static bool ContainsAny<T>(this IEnumerable<T> Collection, IEnumerable<T> Values)
    {
        return Collection.Any(x=> Values.Contains(x));
    }

Usage:

string[] Array1 = {"1", "2"};
string[] Array2 = {"2", "4"};

bool Array2ItemsInArray1 = List1.ContainsAny(List2);

AttributeError: 'numpy.ndarray' object has no attribute 'append'

I got this error after change a loop in my program, let`s see:

for ...
  for ... 
     x_batch.append(one_hot(int_word, vocab_size))
     y_batch.append(one_hot(int_nb, vocab_size, value))
  ...
  ...
  if ...
        x_batch = np.asarray(x_batch)
        y_batch = np.asarray(y_batch)
...

In fact, I was reusing the variable and forgot to reset them inside the external loop, like the comment of John Lyon:

for ...
  x_batch = []
  y_batch = []
  for ... 
     x_batch.append(one_hot(int_word, vocab_size))
     y_batch.append(one_hot(int_nb, vocab_size, value))
  ...
  ...
  if ...
        x_batch = np.asarray(x_batch)
        y_batch = np.asarray(y_batch)
...

Then, check if you are using np.asarray() or something like that.

How can I set a website image that will show as preview on Facebook?

1. Include the Open Graph XML namespace extension to your HTML declaration

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:fb="http://ogp.me/ns/fb#">

2. Inside your <head></head> use the following meta tag to define the image you want to use

<meta property="og:image" content="fully_qualified_image_url_here" />

Read more about open graph protocol here.

After doing the above, use the Facebook "Object Debugger" if the image does not show up correctly. Also note the first time shared it still won't show up unless height and width are also specified, see Share on Facebook - Thumbnail not showing for the first time

Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740]

For me the error was caused by wrong type hint of url string. I used:

export class TodoService {

  apiUrl: String = 'https://jsonplaceholder.typicode.com/todos' // wrong uppercase String

  constructor(private httpClient: HttpClient) { }

  getTodos(): Observable<Todo[]> {
    return this.httpClient.get<Todo[]>(this.apiUrl)
  }
}

where I should have used

export class TodoService {

  apiUrl: string = 'https://jsonplaceholder.typicode.com/todos' // lowercase string!

  constructor(private httpClient: HttpClient) { }

  getTodos(): Observable<Todo[]> {
    return this.httpClient.get<Todo[]>(this.apiUrl)
  }
}

Initialising a multidimensional array in Java

Try replacing the appropriate lines with:

myStringArray[0][x-1] = "a string";
myStringArray[0][y-1] = "another string";

Your code is incorrect because the sub-arrays have a length of y, and indexing starts at 0. So setting to myStringArray[0][y] or myStringArray[0][x] will fail because the indices x and y are out of bounds.

String[][] myStringArray = new String [x][y]; is the correct way to initialise a rectangular multidimensional array. If you want it to be jagged (each sub-array potentially has a different length) then you can use code similar to this answer. Note however that John's assertion that you have to create the sub-arrays manually is incorrect in the case where you want a perfectly rectangular multidimensional array.

Display an array in a readable/hierarchical format

Try this:

foreach($data[0] as $child) {
   echo $child . "\n";
}

in place of print_r($data)

How do you round UP a number in Python?

I think you are confusing the working mechanisms between int() and round().

int() always truncates the decimal numbers if a floating number is given; whereas round(), in case of 2.5 where 2 and 3 are both within equal distance from 2.5, Python returns whichever that is more away from the 0 point.

round(2.5) = 3
int(2.5) = 2

SVG rounded corner

<?php
$radius = 20;
$thichness = 4;
$size = 200;

if($s == 'circle'){
  echo '<svg width="' . $size . '" height="' . $size . '">';
  echo '<circle cx="' . ($size/2) . '" cy="' . ($size/2) . '" r="' . (($size/2)-$thichness) . '" stroke="black" stroke-width="' . $thichness . '" fill="none" />';
  echo '</svg>';
}elseif($s == 'square'){
  echo '<svg width="' . $size . '" height="' . $size . '">';
  echo '<path d="M' . ($radius+$thichness) . ',' . ($thichness) . ' h' . ($size-($radius*2)-($thichness*2)) . ' a' . $radius . ',' . $radius . ' 0 0 1 ' . $radius . ',' . $radius . ' v' . ($size-($radius*2)-($thichness*2)) . ' a' . $radius . ',' . $radius . ' 0 0 1 -' . $radius . ',' . $radius . ' h-' . ($size-($radius*2)-($thichness*2)) . ' a' . $radius . ',' . $radius . ' 0 0 1 -' . $radius . ',-' . $radius . ' v-' . ($size-($radius*2)-($thichness*2)) . ' a' . $radius . ',' . $radius . ' 0 0 1 ' . $radius . ',-' . $radius . ' z" fill="none" stroke="black" stroke-width="' . $thichness . '" />';
  echo '</svg>';
}
?>

How can I make sticky headers in RecyclerView? (Without external lib)

Yo,

This is how you do it if you want just one type of holder stick when it starts getting out of the screen (we are not caring about any sections). There is only one way without breaking the internal RecyclerView logic of recycling items and that is to inflate additional view on top of the recyclerView's header item and pass data into it. I'll let the code speak.

import android.graphics.Canvas
import android.graphics.Rect
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.RecyclerView

class StickyHeaderItemDecoration(@LayoutRes private val headerId: Int, private val HEADER_TYPE: Int) : RecyclerView.ItemDecoration() {

private lateinit var stickyHeaderView: View
private lateinit var headerView: View

private var sticked = false

// executes on each bind and sets the stickyHeaderView
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
    super.getItemOffsets(outRect, view, parent, state)

    val position = parent.getChildAdapterPosition(view)

    val adapter = parent.adapter ?: return
    val viewType = adapter.getItemViewType(position)

    if (viewType == HEADER_TYPE) {
        headerView = view
    }
}

override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
    super.onDrawOver(c, parent, state)
    if (::headerView.isInitialized) {

        if (headerView.y <= 0 && !sticked) {
            stickyHeaderView = createHeaderView(parent)
            fixLayoutSize(parent, stickyHeaderView)
            sticked = true
        }

        if (headerView.y > 0 && sticked) {
            sticked = false
        }

        if (sticked) {
            drawStickedHeader(c)
        }
    }
}

private fun createHeaderView(parent: RecyclerView) = LayoutInflater.from(parent.context).inflate(headerId, parent, false)

private fun drawStickedHeader(c: Canvas) {
    c.save()
    c.translate(0f, Math.max(0f, stickyHeaderView.top.toFloat() - stickyHeaderView.height.toFloat()))
    headerView.draw(c)
    c.restore()
}

private fun fixLayoutSize(parent: ViewGroup, view: View) {

    // Specs for parent (RecyclerView)
    val widthSpec = View.MeasureSpec.makeMeasureSpec(parent.width, View.MeasureSpec.EXACTLY)
    val heightSpec = View.MeasureSpec.makeMeasureSpec(parent.height, View.MeasureSpec.UNSPECIFIED)

    // Specs for children (headers)
    val childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec, parent.paddingLeft + parent.paddingRight, view.getLayoutParams().width)
    val childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec, parent.paddingTop + parent.paddingBottom, view.getLayoutParams().height)

    view.measure(childWidthSpec, childHeightSpec)

    view.layout(0, 0, view.measuredWidth, view.measuredHeight)
}

}

And then you just do this in your adapter:

override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
    super.onAttachedToRecyclerView(recyclerView)
    recyclerView.addItemDecoration(StickyHeaderItemDecoration(R.layout.item_time_filter, YOUR_STICKY_VIEW_HOLDER_TYPE))
}

Where YOUR_STICKY_VIEW_HOLDER_TYPE is viewType of your what is supposed to be sticky holder.

_csv.Error: field larger than field limit (131072)

Sometimes, a row contain double quote column. When csv reader try read this row, not understood end of column and fire this raise. Solution is below:

reader = csv.reader(cf, quoting=csv.QUOTE_MINIMAL)

How to turn off Wifi via ADB?

use with quotes

ex: adb shell "svc wifi enable"

this will work :)

python selenium click on button

I had the same problem using Phantomjs as browser, so I solved in the following way:

driver.find_element_by_css_selector('div.button.c_button.s_button').click()

Essentially I have added the name of the DIV tag into the quote.

Running Selenium Webdriver with a proxy in Python

My solution:

def my_proxy(PROXY_HOST,PROXY_PORT):
        fp = webdriver.FirefoxProfile()
        # Direct = 0, Manual = 1, PAC = 2, AUTODETECT = 4, SYSTEM = 5
        print PROXY_PORT
        print PROXY_HOST
        fp.set_preference("network.proxy.type", 1)
        fp.set_preference("network.proxy.http",PROXY_HOST)
        fp.set_preference("network.proxy.http_port",int(PROXY_PORT))
        fp.set_preference("general.useragent.override","whater_useragent")
        fp.update_preferences()
        return webdriver.Firefox(firefox_profile=fp)

Then call in your code:

my_proxy(PROXY_HOST,PROXY_PORT)

I had issues with this code because I was passing a string as a port #:

 PROXY_PORT="31280"

This is important:

int("31280")

You must pass an integer instead of a string or your firefox profile will not be set to a properly port and connection through proxy will not work.

Adding a directory to the PATH environment variable in Windows

Regarding point 2 I'm using a simple batch file that is populating PATH or other environment variables for me. Therefore, there is no pollution of environment variables by default. This batch file is accessible from everywhere so I can type:

c:\>mybatchfile
-- here all env. are available
c:\>php file.php

How to create an Observable from static data similar to http one in Angular?

As of July 2018 and the release of RxJS 6, the new way to get an Observable from a value is to import the of operator like so:

import { of } from 'rxjs';

and then create the observable from the value, like so:

of(someValue);

Note, that you used to have to do Observable.of(someValue) like in the currently accepted answer. There is a good article on the other RxJS 6 changes here.

printing a value of a variable in postgresql

You can raise a notice in Postgres as follows:

raise notice 'Value: %', deletedContactId;

Read here

Simple pagination in javascript

You can use the code from this minimal plugin. https://www.npmjs.com/package/paginator-js

Array.prototype.paginate = function(pageNumber, itemsPerPage){
  pageNumber   = Number(pageNumber)
  itemsPerPage = Number(itemsPerPage)
  pageNumber   = (pageNumber   < 1 || isNaN(pageNumber))   ? 1 : pageNumber
  itemsPerPage = (itemsPerPage < 1 || isNaN(itemsPerPage)) ? 1 : itemsPerPage

  var start     = ((pageNumber - 1) * itemsPerPage)
  var end       = start + itemsPerPage
  var loopCount = 0
  var result    = {
    data: [],
    end: false
  }

  for(loopCount = start; loopCount < end; loopCount++){
    this[loopCount] && result.data.push(this[loopCount]);
  }

  if(loopCount == this.length){
    result.end = true
  }

  return result
}

Getting a POST variable

Use the

Request.Form[]

for POST variables,

Request.QueryString[]

for GET.

How to Create a script via batch file that will uninstall a program if it was installed on windows 7 64-bit or 32-bit

wmic can call an uninstaller. I haven't tried this, but I think it might work.

wmic /node:computername /user:adminuser /password:password product where name="name of application" call uninstall

If you don't know exactly what the program calls itself, do

wmic product get name | sort

and look for it. You can also uninstall using SQL-ish wildcards.

wmic /node:computername /user:adminuser /password:password product where "name like '%j2se%'" call uninstall

... for example would perform a case-insensitive search for *j2se* and uninstall "J2SE Runtime Environment 5.0 Update 12". (Note that in the example above, %j2se% is not an environment variable, but simply the word "j2se" with a SQL-ish wildcard on each end. If your search string could conflict with an environment or script variable, use double percents to specify literal percent signs, like %%j2se%%.)

If wmic prompts for y/n confirmation before completing the uninstall, try this:

echo y | wmic /node:computername /user:adminuser /password:password product where name="whatever" call uninstall

... to pass a y to it before it even asks.

I haven't tested this, but it's worth a shot anyway. If it works on one computer, then you can just loop through a text file containing all the computer names within your organization using a for loop, or put it in a domain policy logon script.

VBA code to show Message Box popup if the formula in the target cell exceeds a certain value

Essentially you want to add code to the Calculate event of the relevant Worksheet.

In the Project window of the VBA editor, double-click the sheet you want to add code to and from the drop-downs at the top of the editor window, choose 'Worksheet' and 'Calculate' on the left and right respectively.

Alternatively, copy the code below into the editor of the sheet you want to use:

Private Sub Worksheet_Calculate()

If Sheets("MySheet").Range("A1").Value > 0.5 Then
    MsgBox "Over 50%!", vbOKOnly
End If

End Sub

This way, every time the worksheet recalculates it will check to see if the value is > 0.5 or 50%.

Static way to get 'Context' in Android?

in Kotlin, putting Context/App Context in companion object still produce warning Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)

or if you use something like this:

    companion object {
        lateinit var instance: MyApp
    }

It's simply fooling the lint to not discover the memory leak, the App instance still can produce memory leak, since Application class and its descendant is a Context.

Alternatively, you can use functional interface or Functional properties to help you get your app context.

Simply create an object class:

object CoreHelper {
    lateinit var contextGetter: () -> Context
}

or you could use it more safely using nullable type:

object CoreHelper {
    var contextGetter: (() -> Context)? = null
}

and in your App class add this line:


class MyApp: Application() {

    override fun onCreate() {
        super.onCreate()
        CoreHelper.contextGetter = {
            this
        }
    }
}

and in your manifest declare the app name to . MyApp


    <application
            android:name=".MyApp"

When you wanna get the context simply call:

CoreHelper.contextGetter()

// or if you use the nullable version
CoreHelper.contextGetter?.invoke()

Hope it will help.

Getting "java.nio.file.AccessDeniedException" when trying to write to a folder

Ok it turns out I was doing something stupid. I hadn't appended the new file name to the path.

I had

rootDirectory = "C:\\safesite_documents"

but it should have been

rootDirectory = "C:\\safesite_documents\\newFile.jpg" 

Sorry it was a stupid mistake as always.

How to install both Python 2.x and Python 3.x in Windows

I use a simple solution to switch from a version to another version of python, you can install all version you want. All you have to do is creating some variable environment. In my case, I have installed python 2.7 and python 3.8.1, so I have created this environment variables:

PYTHON_HOME_2.7=<path_python_2.7> PYTHON_HOME_3.8.1=<path_python_3.8.1> PYTHON_HOME=%PYTHON_HOME_2.7%

then in my PATH environment variable I put only %PYTHON_HOME% and %PYTHON_HOME%\Scripts. In the example above I'm using the version 2.7, when I want to switch to the other version I have only to set the PYTHON_HOME=%PYTHON_HOME_3.8.1%. I use this method to switch quickly from a version to another also for JAVA, MAVEN, GRADLE,ANT, and so on.

Algorithm/Data Structure Design Interview Questions

Graphs are tough, because most non-trivial graph problems tend to require a decent amount of actual code to implement, if more than a sketch of an algorithm is required. A lot of it tends to come down to whether or not the candidate knows the shortest path and graph traversal algorithms, is familiar with cycle types and detection, and whether they know the complexity bounds. I think a lot of questions about this stuff comes down to trivia more than on the spot creative thinking ability.

I think problems related to trees tend to cover most of the difficulties of graph questions, but without as much code complexity.

I like the Project Euler problem that asks to find the most expensive path down a tree (16/67); common ancestor is a good warm up, but a lot of people have seen it. Asking somebody to design a tree class, perform traversals, and then figure out from which traversals they could rebuild a tree also gives some insight into data structure and algorithm implementation. The Stern-Brocot programming challenge is also interesting and quick to develop on a board (http://online-judge.uva.es/p/v100/10077.html).

Detect change to selected date with bootstrap-datepicker

All others answers are related to jQuery UI datepicker, but the question is about bootstrap-datepicker.

You can use the on changeDate event to trigger a change event on the related input, and then handle both ways of changing the date from the onChange handler:

changeDate

Fired when the date is changed.

Example:

$('#dp3').datepicker().on('changeDate', function (ev) {
    $('#date-daily').change();
});
$('#date-daily').val('0000-00-00');
$('#date-daily').change(function () {
    console.log($('#date-daily').val());
});

Here is a working fiddle: http://jsfiddle.net/IrvinDominin/frjhgpn8/

How to Correctly handle Weak Self in Swift Blocks with Arguments

From Swift 5.3, you do not have to unwrap self in closure if you pass [self] before in in closure.

Refer someFunctionWithEscapingClosure { [self] in x = 100 } in this swift doc

How can I alter a primary key constraint using SQL syntax?

Performance wise there is no point to keep non clustered indexes during this as they will get re-updated on drop and create. If it is a big data set you should consider renaming the table (if possible , any security settings on it?), re-creating an empty table with the correct keys migrate all data there. You have to make sure you have enough space for this.

./configure : /bin/sh^M : bad interpreter

When you write your script on windows environment and you want to run it on unix environnement you need to be careful about the encodage :

dos2unix $filePath

Forward declaration of a typedef in C++

For those of you like me, who are looking to forward declare a C-style struct that was defined using typedef, in some c++ code, I have found a solution that goes as follows...

// a.h
 typedef struct _bah {
    int a;
    int b;
 } bah;

// b.h
 struct _bah;
 typedef _bah bah;

 class foo {
   foo(bah * b);
   foo(bah b);
   bah * mBah;
 };

// b.cpp
 #include "b.h"
 #include "a.h"

 foo::foo(bah * b) {
   mBah = b;
 }

 foo::foo(bah b) {
   mBah = &b;
 }

What is Hash and Range Primary Key?

@vnr you can retrieve all the sort keys associated with a partition key by just using the query using partion key. No need of scan. The point here is partition key is compulsory in a query . Sort key are used only to get range of data

Remove "whitespace" between div element

You can remove extra space inside DIv by using below property of CSS in a parent (container) div element

display:inline-flex

Before Adding dislay:inline-flex;

After Adding display:inline-flex; in css

What is lazy loading in Hibernate?

Lazy setting decides whether to load child objects while loading the Parent Object.You need to do this setting respective hibernate mapping file of the parent class.Lazy = true (means not to load child)By default the lazy loading of the child objects is true. This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent.In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object.But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database.Exampleslazy=true (default)Address child of User class can be made lazy if it is not required frequently.lazy=falseBut you may need to load the Author object for Book parent whenever you deal with the book for online bookshop.

Google Chrome: This setting is enforced by your administrator

On Linux, you can get rid of "Managed by your organization" Chrome policies, by removing these directories (as sudo probably):

/etc/opt/chrome/policies
/etc/opt/chrome/policies/managed
/etc/opt/chrome/policies/recommended

How to check empty object in angular 2 template using *ngIf

This worked for me:

Check the length property and use ? to avoid undefined errors.

So your example would be:

<div class="comeBack_up" *ngIf="previous_info?.length">

UPDATE

The length property only exists on arrays. Since the question was about objects, use Object.getOwnPropertyNames(obj) to get an array of properties from the object. The example becomes:

<div class="comeBack_up" *ngIf="previous_info  && Object.getOwnPropertyNames(previous_info).length > 0">

The previous_info && is added to check if the object exists. If it evaluates to true the next statement checks if the object has at least on proporty. It does not check whether the property has a value.

How to break out of nested loops?

Caution: This answer shows a truly obscure construction.

If you are using GCC, check out this library. Like in PHP, break can accept the number of nested loops you want to exit. You can write something like this:

for(int i = 0; i < 1000; i++) {
   for(int j = 0; j < 1000; j++) {
       if(condition) {
            // break two nested enclosing loops
            break(2);
       }
   }
}

Is there an eval() function in Java?

With Java 9, we get access to jshell, so one can write something like this:

import jdk.jshell.JShell;
import java.lang.StringBuilder;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Eval {
    public static void main(String[] args) throws IOException {
        try(JShell js = JShell.create(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {

            js.onSnippetEvent(snip -> {
                if (snip.status() == jdk.jshell.Snippet.Status.VALID) {
                    System.out.println("? " + snip.value());
                }
            });

            System.out.print("> ");
            for (String line = br.readLine(); line != null; line = br.readLine()) {
                js.eval(js.sourceCodeAnalysis().analyzeCompletion(line).source());
                System.out.print("> ");
            }
        }
    }
}

Sample run:

> 1 + 2 / 4 * 3
? 1
> 32 * 121
? 3872
> 4 * 5
? 20
> 121 * 51
? 6171
>

Slightly op, but that's what Java currently has to offer

MVC - Set selected value of SelectList

I wanted the dropdown to select the matching value of the id in the action method. The trick is to set the Selected property when creating the SelectListItem Collection. It would not work any other way, perhaps I missed something but in end, it is more elegant in my option.

You can write any method that returns a boolean to set the Selected value based on your requirements, in my case I used the existing Equal Method

public ActionResult History(long id)
        {
            var app = new AppLogic();
            var historyVM = new ActivityHistoryViewModel();

            historyVM.ProcessHistory = app.GetActivity(id);
            historyVM.Process = app.GetProcess(id);
            var processlist = app.GetProcessList();

            historyVM.ProcessList = from process in processlist
                                    select new SelectListItem
                                    {
                                        Text = process.ProcessName,
                                        Value = process.ID.ToString(),
                                        Selected = long.Equals(process.ID, id)                                    

                                    };

            var listitems = new List<SelectListItem>();

            return View(historyVM);
        }

How to get css background color on <tr> tag to span entire row

Have you tried setting the spacing to zero?

/*alternating row*/
table, tr, td, th {margin:0;border:0;padding:0;spacing:0;}
tr.rowhighlight {background-color:#f0f8ff;margin:0;border:0;padding:0;spacing:0;}

Example of a strong and weak entity types

Weak entity exists to solve the multi-valued attributes problem.

There are two types of multi-valued attributes. One is the simply many values for an objects such as a "hobby" as an attribute for a student. The student can have many different hobbies. If we leave the hobbies in the student entity set, "hobby" would not be unique any more. We create a separate entity set as hobby. Then we link the hobby and the student as we need. The hobby entity set is now an associative entity set. As to whether it is weak or not, we need to check whether each entity has enough unique identifiers to identify it. In many opinion, a hobby name can be enough to identify it.

The other type of multi-valued attribute problem does need a weak entity to fix it. Let's say an item entity set in a grocery inventory system. Is the item a category item or the actually item? It is an important question, because a customer can buy the same item at one time and at a certain amount, but he can also buy the same item at a different time with a different amount. Can you see it the same item but of different objects. The item now is a multi-valued attribute. We solve it by first separate the category item with the actual item. The two are now different entity sets. Category item has descriptive attributes of the item, just like the item you usually think of. Actual item can not have descriptive attributes any more because we can not have redundant problem. Actual item can only have date time and amount of the item. You can link them as you need. Now, let's talk about whether one is a weak entity of the other. The descriptive attributes are more than enough to identify each entity in the category item entity set. The actual item only has date time and amount. Even if we pull out all the attributes in a record, we still cannot identify the entity. Think about it is just time and amount. The actual item entity set is a weak entity set. We identify each entity in the set with the help of duplicate prime key from the category item entity set.

Finding the indices of matching elements in list in Python

>>> average =  [1,3,2,1,1,0,24,23,7,2,727,2,7,68,7,83,2]
>>> matches = [i for i in range(0,len(average)) if average[i]<2 or average[i]>4]
>>> matches
[0, 3, 4, 5, 6, 7, 8, 10, 12, 13, 14, 15]

How do I count a JavaScript object's attributes?

For those which will read this question/answers, here is a JavaScript implementation of Dictionary collection very similar as functionality as .NET one: JavaScript Dictionary

How to select element using XPATH syntax on Selenium for Python?

HTML

<div id='a'>
  <div>
    <a class='click'>abc</a>
  </div>
</div>

You could use the XPATH as :

//div[@id='a']//a[@class='click']

output

<a class="click">abc</a>

That said your Python code should be as :

driver.find_element_by_xpath("//div[@id='a']//a[@class='click']")

Expression ___ has changed after it was checked

First, note that this exception will only be thrown when you're running your app in dev mode (which is the case by default as of beta-0): If you call enableProdMode() when bootstrapping the app, it won't get thrown (see updated plunk).

Second, don't do that because this exception is being thrown for good reason: In short, when in dev mode, every round of change detection is followed immediately by a second round that verifies no bindings have changed since the end of the first, as this would indicate that changes are being caused by change detection itself.

In your plunk, the binding {{message}} is changed by your call to setMessage(), which happens in the ngAfterViewInit hook, which occurs as a part of the initial change detection turn. That in itself isn't problematic though - the problem is that setMessage() changes the binding but does not trigger a new round of change detection, meaning that this change won't be detected until some future round of change detection is triggered somewhere else.

The takeaway: Anything that changes a binding needs to trigger a round of change detection when it does.

Update in response to all the requests for an example of how to do that: @Tycho's solution works, as do the three methods in the answer @MarkRajcok pointed out. But frankly, they all feel ugly and wrong to me, like the sort of hacks we got used to leaning on in ng1.

To be sure, there are occasional circumstances where these hacks are appropriate, but if you're using them on anything more than a very occasional basis, it's a sign that you're fighting the framework rather than fully embracing its reactive nature.

IMHO, a more idiomatic, "Angular2 way" of approaching this is something along the lines of: (plunk)

@Component({
  selector: 'my-app',
  template: `<div>I'm {{message | async}} </div>`
})
export class App {
  message:Subject<string> = new BehaviorSubject('loading :(');

  ngAfterViewInit() {
    this.message.next('all done loading :)')
  }
}

Binding multiple events to a listener (without JQuery)?

ES2015:

let el = document.getElementById("el");
let handler =()=> console.log("changed");
['change', 'keyup', 'cut'].forEach(event => el.addEventListener(event, handler));

HttpRequest maximum allowable size in tomcat?

Just to add to the answers, App Server Apache Geronimo 3.0 uses Tomcat 7 as the web server, and in that environment the file server.xml is located at <%GERONIMO_HOME%>/var/catalina/server.xml.

The configuration does take effect even when the Geronimo Console at Application Server->WebServer->TomcatWebConnector->maxPostSize still displays 2097152 (the default value)

What is the cause for "angular is not defined"

I had the same problem as deke. I forgot to include the most important script: angular.js :)

<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>

How do I drop a MongoDB database from the command line?

You could also use a "heredoc":

mongo localhost/db <<EOF
db.dropDatabase()
EOF

Results in output like:

mongo localhost/db <<EOF
db.dropDatabase()
EOF
MongoDB shell version: 2.2.2
connecting to: localhost/db
{ "dropped" : "db", "ok" : 1 }    
bye

I like to use heredocs for things like this, in case you want more complex sequence of commands.

MySQL: NOT LIKE

categories_posts and categories_news start with substring 'categories_' then it is enough to check that developer_configurations_cms.cfg_name_unique starts with 'categories' instead of check if it contains the given substring. Translating all that into a query:

SELECT *
    FROM developer_configurations_cms

    WHERE developer_configurations_cms.cat_id = '1'
    AND developer_configurations_cms.cfg_variables LIKE '%parent_id=2%'
    AND developer_configurations_cms.cfg_name_unique NOT LIKE 'categories%'

How do I create a pause/wait function using Qt?

we can use following method QT_Delay:

QTimer::singleShot(2000,this,SLOT(print_lcd()));

This will wait for 2 seconds before calling print_lcd().

SQL Server, How to set auto increment after creating a table without data loss?

If you don't want to add a new column, and you can guarantee that your current int column is unique, you could select all of the data out into a temporary table, drop the table and recreate with the IDENTITY column specified. Then using SET IDENTITY INSERT ON you can insert all of your data in the temporary table into the new table.

Query grants for a table in postgres

\z mytable from psql gives you all the grants from a table, but you'd then have to split it up by individual user.

Variable name as a string in Javascript

In ES6, you could write something like:

let myVar = 'something';
let nameObject = {myVar};
let getVarNameFromObject = (nameObject) => {
  for(let varName in nameObject) {
    return varName;
  }
}
let varName = getVarNameFromObject(nameObject);

Not really the best looking thing, but it gets the job done.

This leverages ES6's object destructuring.

More info here: https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/

git undo all uncommitted or unsaved changes

What I do is

git add . (adding everything)
git stash 
git stash drop

One liner: git add . && git stash && git stash drop

Run / Open VSCode from Mac Terminal

I simply created a file called code:

#!/bin/bash

open /Applications/Visual\ Studio\ Code.app $1

Make it executable:

$ chmod 755 code

Then put that in /usr/local/bin

$ sudo mv code /usr/local/bin

As long as the file sits someplace that is in your path you can open a file by just typing: code

Delete item from state array in react

To remove an element from an array, just do:

array.splice(index, 1);

In your case:

removePeople(e) {
  var array = [...this.state.people]; // make a separate copy of the array
  var index = array.indexOf(e.target.value)
  if (index !== -1) {
    array.splice(index, 1);
    this.setState({people: array});
  }
},

C - function inside struct

As others have noted, embedding function pointers directly inside your structure is usually reserved for special purposes, like a callback function.

What you probably want is something more like a virtual method table.

typedef struct client_ops_t client_ops_t;
typedef struct client_t client_t, *pno;

struct client_t {
    /* ... */
    client_ops_t *ops;
};

struct client_ops_t {
    pno (*AddClient)(client_t *);
    pno (*RemoveClient)(client_t *);
};

pno AddClient (client_t *client) { return client->ops->AddClient(client); }
pno RemoveClient (client_t *client) { return client->ops->RemoveClient(client); }

Now, adding more operations does not change the size of the client_t structure. Now, this kind of flexibility is only useful if you need to define many kinds of clients, or want to allow users of your client_t interface to be able to augment how the operations behave.

This kind of structure does appear in real code. The OpenSSL BIO layer looks similar to this, and also UNIX device driver interfaces have a layer like this.

Java : Cannot format given Object as a Date

You have one DateFormat, but you need two: one for the input, and another for the output.

You've got one for the output, but I don't see anything that would match your input. When you give the input string to the output format, it's no surprise that you see that exception.

DateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-ddhh:mm:ss.SSS-Z");

How do I include a JavaScript file in another JavaScript file?

My usual method is:

var require = function (src, cb) {
    cb = cb || function () {};

    var newScriptTag = document.createElement('script'),
        firstScriptTag = document.getElementsByTagName('script')[0];
    newScriptTag.src = src;
    newScriptTag.async = true;
    newScriptTag.onload = newScriptTag.onreadystatechange = function () {
        (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') && (cb());
    };
    firstScriptTag.parentNode.insertBefore(newScriptTag, firstScriptTag);
}

It works great and uses no page-reloads for me. I've tried the AJAX method (one of the other answers) but it doesn't seem to work as nicely for me.

Here's an explanation of how the code works for those that are curious: essentially, it creates a new script tag (after the first one) of the URL. It sets it to asynchronous mode so it doesn't block the rest of the code, but calls a callback when the readyState (the state of the content to be loaded) changes to 'loaded'.

Getting index value on razor foreach

Very Simple:

     @{
         int i = 0;
         foreach (var item in Model)
         {
          <tr>
          <td>@(i = i + 1)</td>`
          </tr>
         }
      }`

Disable Logback in SpringBoot

It might help if you say what your preferred logger is exactly, and what you did to try and install it. Anyway, Spring Boot tries to work with whatever is in the classpath, so if you don't want logback, take it off the classpath. There are instructions for log4j in the docs, but the same thing would apply to other supported logging systems (anything slf4j, log4j or java util).

jquery: $(window).scrollTop() but no $(window).scrollBottom()

var scrollBottom =
    $(document).height() - $(window).height() - $(window).scrollTop();

I think it is better to get bottom scroll.

jQuery checkbox checked state changed event

Try this jQuery validation

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#myform').validate({ // initialize the plugin_x000D_
    rules: {_x000D_
      agree: {_x000D_
        required: true_x000D_
      }_x000D_
_x000D_
    },_x000D_
    submitHandler: function(form) {_x000D_
      alert('valid form submitted');_x000D_
      return false;_x000D_
    }_x000D_
  });_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>_x000D_
_x000D_
<form id="myform" action="" method="post">_x000D_
  <div class="buttons">_x000D_
    <div class="pull-right">_x000D_
      <input type="checkbox" name="agree" /><br/>_x000D_
      <label>I have read and agree to the <a href="https://stackexchange.com/legal/terms-of-service">Terms of services</a> </label>_x000D_
    </div>_x000D_
  </div>_x000D_
  <button type="submit">Agree</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Xcode 6 Bug: Unknown class in Interface Builder file

Project with Multiple Targets

In my case I am working on Project with multiple Targets and the issue was "inherit from Target" was unchecked. Selecting "inherit from target" solved my problem

enter image description here

Converting a pointer into an integer

Several answers have pointed at uintptr_t and #include <stdint.h> as 'the' solution. That is, I suggest, part of the answer, but not the whole answer. You also need to look at where the function is called with the message ID of FOO.

Consider this code and compilation:

$ cat kk.c
#include <stdio.h>
static void function(int n, void *p)
{
    unsigned long z = *(unsigned long *)p;
    printf("%d - %lu\n", n, z);
}

int main(void)
{
    function(1, 2);
    return(0);
}
$ rmk kk
        gcc -m64 -g -O -std=c99 -pedantic -Wall -Wshadow -Wpointer-arith \
            -Wcast-qual -Wstrict-prototypes -Wmissing-prototypes \
            -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE kk.c -o kk 
kk.c: In function 'main':
kk.c:10: warning: passing argument 2 of 'func' makes pointer from integer without a cast
$

You will observe that there is a problem at the calling location (in main()) — converting an integer to a pointer without a cast. You are going to need to analyze your function() in all its usages to see how values are passed to it. The code inside my function() would work if the calls were written:

unsigned long i = 0x2341;
function(1, &i);

Since yours are probably written differently, you need to review the points where the function is called to ensure that it makes sense to use the value as shown. Don't forget, you may be finding a latent bug.

Also, if you are going to format the value of the void * parameter (as converted), look carefully at the <inttypes.h> header (instead of stdint.hinttypes.h provides the services of stdint.h, which is unusual, but the C99 standard says [t]he header <inttypes.h> includes the header <stdint.h> and extends it with additional facilities provided by hosted implementations) and use the PRIxxx macros in your format strings.

Also, my comments are strictly applicable to C rather than C++, but your code is in the subset of C++ that is portable between C and C++. The chances are fair to good that my comments apply.

How to add local jar files to a Maven project?

Also take a look at...

<scope>compile</scope>

Maven Dependencies. This is the default but I've found in some cases explicitly setting that scope also Maven to find local libraries in the local repository.

Fatal error: Call to undefined function imap_open() in PHP

For Xampp 7.3.9

PHP.ini line 913:

;extension=imap

You should remove the semicolon.

Update all objects in a collection using LINQ

I wrote some extension methods to help me out with that.

namespace System.Linq
{
    /// <summary>
    /// Class to hold extension methods to Linq.
    /// </summary>
    public static class LinqExtensions
    {
        /// <summary>
        /// Changes all elements of IEnumerable by the change function
        /// </summary>
        /// <param name="enumerable">The enumerable where you want to change stuff</param>
        /// <param name="change">The way you want to change the stuff</param>
        /// <returns>An IEnumerable with all changes applied</returns>
        public static IEnumerable<T> Change<T>(this IEnumerable<T> enumerable, Func<T, T> change  )
        {
            ArgumentCheck.IsNullorWhiteSpace(enumerable, "enumerable");
            ArgumentCheck.IsNullorWhiteSpace(change, "change");

            foreach (var item in enumerable)
            {
                yield return change(item);
            }
        }

        /// <summary>
        /// Changes all elements of IEnumerable by the change function, that fullfill the where function
        /// </summary>
        /// <param name="enumerable">The enumerable where you want to change stuff</param>
        /// <param name="change">The way you want to change the stuff</param>
        /// <param name="where">The function to check where changes should be made</param>
        /// <returns>
        /// An IEnumerable with all changes applied
        /// </returns>
        public static IEnumerable<T> ChangeWhere<T>(this IEnumerable<T> enumerable, 
                                                    Func<T, T> change,
                                                    Func<T, bool> @where)
        {
            ArgumentCheck.IsNullorWhiteSpace(enumerable, "enumerable");
            ArgumentCheck.IsNullorWhiteSpace(change, "change");
            ArgumentCheck.IsNullorWhiteSpace(@where, "where");

            foreach (var item in enumerable)
            {
                if (@where(item))
                {
                    yield return change(item);
                }
                else
                {
                    yield return item;
                }
            }
        }

        /// <summary>
        /// Changes all elements of IEnumerable by the change function that do not fullfill the except function
        /// </summary>
        /// <param name="enumerable">The enumerable where you want to change stuff</param>
        /// <param name="change">The way you want to change the stuff</param>
        /// <param name="where">The function to check where changes should not be made</param>
        /// <returns>
        /// An IEnumerable with all changes applied
        /// </returns>
        public static IEnumerable<T> ChangeExcept<T>(this IEnumerable<T> enumerable,
                                                     Func<T, T> change,
                                                     Func<T, bool> @where)
        {
            ArgumentCheck.IsNullorWhiteSpace(enumerable, "enumerable");
            ArgumentCheck.IsNullorWhiteSpace(change, "change");
            ArgumentCheck.IsNullorWhiteSpace(@where, "where");

            foreach (var item in enumerable)
            {
                if (!@where(item))
                {
                    yield return change(item);
                }
                else
                {
                    yield return item;
                }
            }
        }

        /// <summary>
        /// Update all elements of IEnumerable by the update function (only works with reference types)
        /// </summary>
        /// <param name="enumerable">The enumerable where you want to change stuff</param>
        /// <param name="update">The way you want to change the stuff</param>
        /// <returns>
        /// The same enumerable you passed in
        /// </returns>
        public static IEnumerable<T> Update<T>(this IEnumerable<T> enumerable,
                                               Action<T> update) where T : class
        {
            ArgumentCheck.IsNullorWhiteSpace(enumerable, "enumerable");
            ArgumentCheck.IsNullorWhiteSpace(update, "update");
            foreach (var item in enumerable)
            {
                update(item);
            }
            return enumerable;
        }

        /// <summary>
        /// Update all elements of IEnumerable by the update function (only works with reference types)
        /// where the where function returns true
        /// </summary>
        /// <param name="enumerable">The enumerable where you want to change stuff</param>
        /// <param name="update">The way you want to change the stuff</param>
        /// <param name="where">The function to check where updates should be made</param>
        /// <returns>
        /// The same enumerable you passed in
        /// </returns>
        public static IEnumerable<T> UpdateWhere<T>(this IEnumerable<T> enumerable,
                                               Action<T> update, Func<T, bool> where) where T : class
        {
            ArgumentCheck.IsNullorWhiteSpace(enumerable, "enumerable");
            ArgumentCheck.IsNullorWhiteSpace(update, "update");
            foreach (var item in enumerable)
            {
                if (where(item))
                {
                    update(item);
                }
            }
            return enumerable;
        }

        /// <summary>
        /// Update all elements of IEnumerable by the update function (only works with reference types)
        /// Except the elements from the where function
        /// </summary>
        /// <param name="enumerable">The enumerable where you want to change stuff</param>
        /// <param name="update">The way you want to change the stuff</param>
        /// <param name="where">The function to check where changes should not be made</param>
        /// <returns>
        /// The same enumerable you passed in
        /// </returns>
        public static IEnumerable<T> UpdateExcept<T>(this IEnumerable<T> enumerable,
                                               Action<T> update, Func<T, bool> where) where T : class
        {
            ArgumentCheck.IsNullorWhiteSpace(enumerable, "enumerable");
            ArgumentCheck.IsNullorWhiteSpace(update, "update");

            foreach (var item in enumerable)
            {
                if (!where(item))
                {
                    update(item);
                }
            }
            return enumerable;
        }
    }
}

I am using it like this:

        List<int> exampleList = new List<int>()
            {
                1, 2 , 3
            };

        //2 , 3 , 4
        var updated1 = exampleList.Change(x => x + 1);

        //10, 2, 3
        var updated2 = exampleList
            .ChangeWhere(   changeItem => changeItem * 10,          // change you want to make
                            conditionItem => conditionItem < 2);    // where you want to make the change

        //1, 0, 0
        var updated3 = exampleList
            .ChangeExcept(changeItem => 0,                          //Change elements to 0
                          conditionItem => conditionItem == 1);     //everywhere but where element is 1

For reference the argument check:

/// <summary>
/// Class for doing argument checks
/// </summary>
public static class ArgumentCheck
{


    /// <summary>
    /// Checks if a value is string or any other object if it is string
    /// it checks for nullorwhitespace otherwhise it checks for null only
    /// </summary>
    /// <typeparam name="T">Type of the item you want to check</typeparam>
    /// <param name="item">The item you want to check</param>
    /// <param name="nameOfTheArgument">Name of the argument</param>
    public static void IsNullorWhiteSpace<T>(T item, string nameOfTheArgument = "")
    {

        Type type = typeof(T);
        if (type == typeof(string) ||
            type == typeof(String))
        {
            if (string.IsNullOrWhiteSpace(item as string))
            {
                throw new ArgumentException(nameOfTheArgument + " is null or Whitespace");
            }
        }
        else
        {
            if (item == null)
            {
                throw new ArgumentException(nameOfTheArgument + " is null");
            }
        }

    }
}

How to get main window handle from process id?

Just to make sure you are not confusing the tid (thread id) and the pid (process id):

DWORD pid;
DWORD tid = GetWindowThreadProcessId( this->m_hWnd, &pid);

Metadata file '.dll' could not be found

I also met this problem. Firstly you have to manually build you DLL project, by right-click, Build. Then it will work.

Change :hover CSS properties with JavaScript

Declare a global var:

var td

Then select your guiena pig <td> getting it by its id, if you want to change all of them then

window.onload = function () {
  td = document.getElementsByTagName("td"); 
}

Make a function to be triggered and a loop to change all of your desired td's

function trigger() {
    for(var x = 0; x < td.length; x++) { 
      td[x].className = "yournewclass"; 
    }
}

Go to your CSS Sheet:

.yournewclass:hover { background-color: #00ff00; }

And that is it, with this you are able to to make all your <td> tags get a background-color: #00ff00; when hovered by changing its css propriety directly (switching between css classes).

NodeJS / Express: what is "app.use"?

Bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions, where METHOD is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.

Cannot import scipy.misc.imread

If you have Pillow installed with scipy and it is still giving you error then check your scipy version because it has been removed from scipy since 1.3.0rc1.

rather install scipy 1.1.0 by :

pip install scipy==1.1.0

check https://github.com/scipy/scipy/issues/6212


The method imread in scipy.misc requires the forked package of PIL named Pillow. If you are having problem installing the right version of PIL try using imread in other packages:

from matplotlib.pyplot import imread
im = imread(image.png)

To read jpg images without PIL use:

import cv2 as cv
im = cv.imread(image.jpg)

You can try from scipy.misc.pilutil import imread instead of from scipy.misc import imread

Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.

How to save data in an android app

Please don't forget one thing - Internal Storage data are deleted when you uninstall the app. In some cases it can be "unexpected feature". Then it's good to use external storage.

Google docs about storage - Please look in particular at getExternalStoragePublicDirectory

Batch file FOR /f tokens

for /f "tokens=* delims= " %%f in (myfile) do

This reads a file line-by-line, removing leading spaces (thanks, jeb).

set line=%%f

sets then the line variable to the line just read and

call :procesToken

calls a subroutine that does something with the line

:processToken

is the start of the subroutine mentioned above.

for /f "tokens=1* delims=/" %%a in ("%line%") do

will then split the line at /, but stopping tokenization after the first token.

echo Got one token: %%a

will output that first token and

set line=%%b

will set the line variable to the rest of the line.

if not "%line%" == "" goto :processToken

And if line isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.