Programs & Examples On #Mongohq

Compose (formerly MongoHQ) is a Database-as-a-Service (DBaaS) platform for securely hosting and managing databases instances including MongoDB.

TypeError: Router.use() requires middleware function but got a Object

If your are using express above 2.x, you have to declare app.router like below code. Please try to replace your code

app.use('/', routes);

with

app.use(app.router);
routes.initialize(app);

Please click here to get more details about app.router

Note:

app.router is depreciated in express 3.0+. If you are using express 3.0+, refer to Anirudh's answer below.

How to set ObjectId as a data type in mongoose

The solution provided by @dex worked for me. But I want to add something else that also worked for me: Use

let UserSchema = new Schema({
   username: {
     type: String
   },
   events: [{
     type: ObjectId,
     ref: 'Event' // Reference to some EventSchema
   }]
})

if what you want to create is an Array reference. But if what you want is an Object reference, which is what I think you might be looking for anyway, remove the brackets from the value prop, like this:

let UserSchema = new Schema({
   username: {
     type: String
   },
   events: {
     type: ObjectId,
     ref: 'Event' // Reference to some EventSchema
   }
})

Look at the 2 snippets well. In the second case, the value prop of key events does not have brackets over the object def.

Difference between DataFrame, Dataset, and RDD in Spark

A DataFrame is an RDD that has a schema. You can think of it as a relational database table, in that each column has a name and a known type. The power of DataFrames comes from the fact that, when you create a DataFrame from a structured dataset (Json, Parquet..), Spark is able to infer a schema by making a pass over the entire (Json, Parquet..) dataset that's being loaded. Then, when calculating the execution plan, Spark, can use the schema and do substantially better computation optimizations. Note that DataFrame was called SchemaRDD before Spark v1.3.0

Angular CLI SASS options

As of 3/10/2019, Anguar dropped the support of sass. No mater what option you passed to --style when running ng new, you always get .scss files generated. It's a shame that sass support was dropped without any explanation.

Access localhost from the internet

Even though you didn't provide enough information to answer this question properly, your best shots are SSH tunnels (or reverse SSH tunnels).

You only need one SSH server on your internal or remote network to provide access to your local machine.

You can use PUTTY (it has a GUI) on Windows to create your tunnel.

Linq Syntax - Selecting multiple columns

You can use anonymous types for example:

  var empData = from res in _db.EMPLOYEEs
                where res.EMAIL == givenInfo || res.USER_NAME == givenInfo
                select new { res.EMAIL, res.USER_NAME };

Where are static variables stored in C and C++?

in the "global and static" area :)

There are several memory areas in C++:

  • heap
  • free store
  • stack
  • global & static
  • const

See here for a detailed answer to your question:

The following summarizes a C++ program's major distinct memory areas. Note that some of the names (e.g., "heap") do not appear as such in the draft [standard].

     Memory Area     Characteristics and Object Lifetimes
     --------------  ------------------------------------------------

     Const Data      The const data area stores string literals and
                     other data whose values are known at compile
                     time.  No objects of class type can exist in
                     this area.  All data in this area is available
                     during the entire lifetime of the program.

                     Further, all of this data is read-only, and the
                     results of trying to modify it are undefined.
                     This is in part because even the underlying
                     storage format is subject to arbitrary
                     optimization by the implementation.  For
                     example, a particular compiler may store string
                     literals in overlapping objects if it wants to.


     Stack           The stack stores automatic variables. Typically
                     allocation is much faster than for dynamic
                     storage (heap or free store) because a memory
                     allocation involves only pointer increment
                     rather than more complex management.  Objects
                     are constructed immediately after memory is
                     allocated and destroyed immediately before
                     memory is deallocated, so there is no
                     opportunity for programmers to directly
                     manipulate allocated but uninitialized stack
                     space (barring willful tampering using explicit
                     dtors and placement new).


     Free Store      The free store is one of the two dynamic memory
                     areas, allocated/freed by new/delete.  Object
                     lifetime can be less than the time the storage
                     is allocated; that is, free store objects can
                     have memory allocated without being immediately
                     initialized, and can be destroyed without the
                     memory being immediately deallocated.  During
                     the period when the storage is allocated but
                     outside the object's lifetime, the storage may
                     be accessed and manipulated through a void* but
                     none of the proto-object's nonstatic members or
                     member functions may be accessed, have their
                     addresses taken, or be otherwise manipulated.


     Heap            The heap is the other dynamic memory area,
                     allocated/freed by malloc/free and their
                     variants.  Note that while the default global
                     new and delete might be implemented in terms of
                     malloc and free by a particular compiler, the
                     heap is not the same as free store and memory
                     allocated in one area cannot be safely
                     deallocated in the other. Memory allocated from
                     the heap can be used for objects of class type
                     by placement-new construction and explicit
                     destruction.  If so used, the notes about free
                     store object lifetime apply similarly here.


     Global/Static   Global or static variables and objects have
                     their storage allocated at program startup, but
                     may not be initialized until after the program
                     has begun executing.  For instance, a static
                     variable in a function is initialized only the
                     first time program execution passes through its
                     definition.  The order of initialization of
                     global variables across translation units is not
                     defined, and special care is needed to manage
                     dependencies between global objects (including
                     class statics).  As always, uninitialized proto-
                     objects' storage may be accessed and manipulated
                     through a void* but no nonstatic members or
                     member functions may be used or referenced
                     outside the object's actual lifetime.

In a simple to understand explanation, what is Runnable in Java?

A Runnable is basically a type of class (Runnable is an Interface) that can be put into a thread, describing what the thread is supposed to do.

The Runnable Interface requires of the class to implement the method run() like so:

public class MyRunnableTask implements Runnable {
     public void run() {
         // do stuff here
     }
}

And then use it like this:

Thread t = new Thread(new MyRunnableTask());
t.start();

If you did not have the Runnable interface, the Thread class, which is responsible to execute your stuff in the other thread, would not have the promise to find a run() method in your class, so you could get errors. That is why you need to implement the interface.

Advanced: Anonymous Type

Note that you do not need to define a class as usual, you can do all of that inline:

Thread t = new Thread(new Runnable() {
    public void run() {
        // stuff here
    }
});
t.start();

This is similar to the above, only you don't create another named class.

how can I enable scrollbars on the WPF Datagrid?

This worked for me. The key is to use * as Row height.

<Grid x:Name="grid">
        <Grid.RowDefinitions>
            <RowDefinition Height="60"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="10"/>
        </Grid.RowDefinitions>

        <TabControl  Grid.Row="1" x:Name="tabItem">
                <TabItem x:Name="ta" 
                        Header="List of all Clients">
                        <DataGrid Name="clientsgrid" AutoGenerateColumns="True" Margin="2" 
                         ></DataGrid>
                </TabItem>
        </TabControl>
    
    </Grid>

How can I generate an apk that can run without server with react-native?

If you get an error involving index.android.js. This is because you are using the new React-native version (I am using 0.55.4) Just replace the "index.android.js" to "index.js"

react-native bundle --platform android --dev false --entry-file index.js   --bundle-output android/app/src/main/assets/index.android.bundle   --assets-dest android/app/src/main/res/

Return date as ddmmyyyy in SQL Server

Try following query to format datetime in sql server

FORMAT (frr.valid_from , 'dd/MM/yyyy hh:mm:ss')

Assigning the output of a command to a variable

Try:

output=$(ps -ef | awk '/siebsvc –s siebsrvr/ && !/awk/ { a++ } END { print a }'); echo $output

Wrapping your command in $( ) tells the shell to run that command, instead of attempting to set the command itself to the variable named "output". (Note that you could also use backticks `command`.)

I can highly recommend http://tldp.org/LDP/abs/html/commandsub.html to learn more about command substitution.

Also, as 1_CR correctly points out in a comment, the extra space between the equals sign and the assignment is causing it to fail. Here is a simple example on my machine of the behavior you are experiencing:

jed@MBP:~$ foo=$(ps -ef |head -1);echo $foo
UID PID PPID C STIME TTY TIME CMD

jed@MBP:~$ foo= $(ps -ef |head -1);echo $foo
-bash: UID: command not found
UID PID PPID C STIME TTY TIME CMD

How to add a line break within echo in PHP?

You may want to try \r\n for carriage return / line feed

Convert datetime object to a String of date only in Python

You could use simple string formatting methods:

>>> dt = datetime.datetime(2012, 2, 23, 0, 0)
>>> '{0.month}/{0.day}/{0.year}'.format(dt)
'2/23/2012'
>>> '%s/%s/%s' % (dt.month, dt.day, dt.year)
'2/23/2012'

Unresolved external symbol on static class members

In my case, I was using wrong linking.
It was managed c++ (cli) but with native exporting. I have added to linker -> input -> assembly link resource the dll of the library from which the function is exported. But native c++ linking requires .lib file to "see" implementations in cpp correctly, so for me helped to add the .lib file to linker -> input -> additional dependencies.
[Usually managed code does not use dll export and import, it uses references, but that was unique situation.]

How to fix java.net.SocketException: Broken pipe?

I'd the same problem while I was developing a simple Java application that listens on a specific TCP. Usually, I had no problem, but when I run some stress test I noticed that some connection broke with error socket write exception.

After Investigation I found a solution that solves my problem. I know this question is quite old, but I prefer to share my solution, someone can find it useful.

The problem was on ServerSocket creation. I read from Javadoc there is a default limit of 50 pending sockets. If you try opening another connection, these will be refused. The solution consist simply in change this default configuration at server side. In the following case, I create a Socket server that listen at TCP port 10_000 and accept max 200 pending sockets.

new Thread(() -> {
      try (ServerSocket serverSocket = new ServerSocket(10_000, 200)) {
        logger.info("Server starts listening on TCP port {}", port);

        while (true) {
          try {
            ClientHandler clientHandler = clientHandlerProvider.getObject(serverSocket.accept(), this);
            executor.execute(clientHandler::start);
          } catch (Exception e) {
            logger.error(e.getMessage());
          }
        }

      } catch (IOException | SecurityException | IllegalArgumentException e) {
        logger.error("Could not open server on TCP port {}. Reason: {}", port, e.getMessage());
      }
    }).start();

From Javadoc of ServerSocket:

The maximum queue length for incoming connection indications (a request to connect) is set to the backlog parameter. If a connection indication arrives when the queue is full, the connection is refused.

How do you copy a record in a SQL table but swap out the unique id of the new row?

Ok, I know that it's an old issue but I post my answer anyway.

I like this solution. I only have to specify the identity column(s).

SELECT * INTO TempTable FROM MyTable_T WHERE id = 1;
ALTER TABLE TempTable DROP COLUMN id;
INSERT INTO MyTable_T SELECT * FROM TempTable;
DROP TABLE TempTable;

The "id"-column is the identity column and that's the only column I have to specify. It's better than the other way around anyway. :-)

I use SQL Server. You may want to use "CREATE TABLE" and "UPDATE TABLE" at row 1 and 2. Hmm, I saw that I did not really give the answer that he wanted. He wanted to copy the id to another column also. But this solution is nice for making a copy with a new auto-id.

I edit my solution with the idéas from Michael Dibbets.

use MyDatabase; 
SELECT * INTO #TempTable FROM [MyTable] WHERE [IndexField] = :id;
ALTER TABLE #TempTable DROP COLUMN [IndexField]; 
INSERT INTO [MyTable] SELECT * FROM #TempTable; 
DROP TABLE #TempTable;

You can drop more than one column by separating them with a ",". The :id should be replaced with the id of the row you want to copy. MyDatabase, MyTable and IndexField should be replaced with your names (of course).

"SMTP Error: Could not authenticate" in PHPMailer

I received this error because of percentage signs in the password.

How to send HTTP request in java?

Google java http client has nice API for http requests. You can easily add JSON support etc. Although for simple request it might be overkill.

import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import java.io.IOException;
import java.io.InputStream;

public class Network {

    static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

    public void getRequest(String reqUrl) throws IOException {
        GenericUrl url = new GenericUrl(reqUrl);
        HttpRequest request = HTTP_TRANSPORT.createRequestFactory().buildGetRequest(url);
        HttpResponse response = request.execute();
        System.out.println(response.getStatusCode());

        InputStream is = response.getContent();
        int ch;
        while ((ch = is.read()) != -1) {
            System.out.print((char) ch);
        }
        response.disconnect();
    }
}

Is Safari on iOS 6 caching $.ajax results?

That's the work around for GWT-RPC

class AuthenticatingRequestBuilder extends RpcRequestBuilder 
{
       @Override
       protected RequestBuilder doCreate(String serviceEntryPoint) 
       {
               RequestBuilder requestBuilder = super.doCreate(serviceEntryPoint);           
               requestBuilder.setHeader("Cache-Control", "no-cache");

               return requestBuilder;
       }
}

AuthenticatingRequestBuilder builder = new AuthenticatingRequestBuilder();
((ServiceDefTarget)myService).setRpcRequestBuilder(builder);    

How can I sharpen an image in OpenCV?

Try with this:

cv::bilateralFilter(img, 9, 75, 75);

You might find more information here.

ant build.xml file doesn't exist

Please install at ubuntu openjdk-7-jdk

sudo apt-get install openjdk-7-jdk

on Windows try find find openjdk

Access-control-allow-origin with multiple domains

Look into the Thinktecture IdentityModel library -- it has full CORS support:

http://brockallen.com/2012/06/28/cors-support-in-webapi-mvc-and-iis-with-thinktecture-identitymodel/

And it can dynamically emit the ACA-Origin you want.

How do I combine two lists into a dictionary in Python?

dict(zip([1,2,3,4], [a,b,c,d]))

If the lists are big you should use itertools.izip.

If you have more keys than values, and you want to fill in values for the extra keys, you can use itertools.izip_longest.

Here, a, b, c, and d are variables -- it will work fine (so long as they are defined), but you probably meant ['a','b','c','d'] if you want them as strings.

zip takes the first item from each iterable and makes a tuple, then the second item from each, etc. etc.

dict can take an iterable of iterables, where each inner iterable has two items -- it then uses the first as the key and the second as the value for each item.

Cannot find reference 'xxx' in __init__.py - Python / Pycharm

This is a bug in pycharm. PyCharm seems to be expecting the referenced module to be included in an __all__ = [] statement.

For proper coding etiquette, should you include the __all__ statement from your modules? ..this is actually the question we hear young Spock answering while he was being tested, to which he responded: "It is morally praiseworthy but not morally obligatory."

To get around it, you can simply disable that (extremely non-critical) (highly useful) inspection globally, or suppress it for the specific function or statement.

To do so:

  • put the caret over the erroring text ('choice', from your example above)
  • Bring up the intention menu (alt-enter by default, mine is set to alt-backspace)
  • hit the right arrow to open the submenu, and select the relevant action

PyCharm has its share of small bugs like this, but in my opinion its benefits far outweigh its drawbacks. If you'd like to try another good IDE, there's also Spyder/Spyderlib.

I know this is quite a bit after you asked your question, but I hope this helps (you, or someone else).

Edited: Originally, I thought that this was specific to checking __all__, but it looks like it's the more general 'Unresolved References' check, which can be very useful. It's probably best to use statement-level disabling of the feature, either by using the menu as mentioned above, or by specifying # noinspection PyUnresolvedReferences on the line preceding the statement.

SMTPAuthenticationError when sending mail using gmail and python

Your code looks correct. Try logging in through your browser and if you are able to access your account come back and try your code again. Just make sure that you have typed your username and password correct

EDIT: Google blocks sign-in attempts from apps which do not use modern security standards (mentioned on their support page). You can however, turn on/off this safety feature by going to the link below:

Go to this link and select Turn On
https://www.google.com/settings/security/lesssecureapps

Send JSON data via POST (ajax) and receive json response from Controller (MVC)

You don't need to call $.toJSON and add traditional = true

data: { sendInfo: array },
traditional: true

would do.

Find out who is locking a file on a network share

Just in case someone looking for a solution to this for a Windows based system or NAS:

There is a built-in function in Windows that shows you what files on the local computer are open/locked by remote computer (which has the file open through a file share):

  • Select "Manage Computer" (Open "Computer Management")
  • click "Shared Folders"
  • choose "Open Files"

There you can even close the file forcefully.

Increase JVM max heap size for Eclipse

Try to modify the eclipse.ini so that both Xms and Xmx are of the same value:

-Xms6000m
-Xmx6000m

This should force the Eclipse's VM to allocate 6GB of heap right from the beginning.

But be careful about either using the eclipse.ini or the command-line ./eclipse/eclipse -vmargs .... It should work in both cases but pick one and try to stick with it.

Android How to adjust layout in Full Screen Mode when softkeyboard is visible

I tried Joseph Johnson's class, and it worked, but didn't quite meet my needs. Rather than emulating android:windowSoftInputMode="adjustResize", I needed to emulate android:windowSoftInputMode="adjustPan".

I am using this for a full screen webview. To pan the content view to the correct position, I need to use a javascript interface which provides details on the position of the page element which has focus and thus is receiving the keyboard input. I have omitted those details, but provided my rewrite of Joseph Johnson's class. It will provide a very solid base for you to implement a custom pan vs. his resize.

package some.package.name;

import some.package.name.JavaScriptObject;

import android.app.Activity;
import android.graphics.Rect;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;

//-------------------------------------------------------
// ActivityPanner Class
//
// Convenience class to handle Activity attributes bug.
// Use this class instead of windowSoftInputMode="adjustPan".
//
// To implement, call enable() and pass a reference
// to an Activity which already has its content view set.
// Example:
//      setContentView( R.layout.someview );
//      ActivityPanner.enable( this );
//-------------------------------------------------------
//
// Notes:
//
// The standard method for handling screen panning
// when the virtual keyboard appears is to set an activity
// attribute in the manifest.
// Example:
// <activity
//      ...
//      android:windowSoftInputMode="adjustPan"
//      ... >
// Unfortunately, this is ignored when using the fullscreen attribute:
//      android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
//
//-------------------------------------------------------
public class ActivityPanner {

    private View contentView_;
    private int priorVisibleHeight_;

    public static void enable( Activity activity ) {
        new ActivityPanner( activity );
    }

    private ActivityPanner( Activity activity ) {
        FrameLayout content = (FrameLayout)
            activity.findViewById( android.R.id.content );
        contentView_ = content.getChildAt( 0 );
        contentView_.getViewTreeObserver().addOnGlobalLayoutListener(
            new ViewTreeObserver.OnGlobalLayoutListener() {
                public void onGlobalLayout() { panAsNeeded(); }
        });
    }

    private void panAsNeeded() {

        // Get current visible height
        int currentVisibleHeight = visibleHeight();

        // Determine if visible height changed
        if( currentVisibleHeight != priorVisibleHeight_ ) {

            // Determine if keyboard visiblity changed
            int screenHeight =
                contentView_.getRootView().getHeight();
            int coveredHeight =
                screenHeight - currentVisibleHeight;
            if( coveredHeight > (screenHeight/4) ) {
                // Keyboard probably just became visible

                // Get the current focus elements top & bottom
                // using a ratio to convert the values
                // to the native scale.
                float ratio = (float) screenHeight / viewPortHeight();
                int elTop = focusElementTop( ratio );
                int elBottom = focusElementBottom( ratio );

                // Determine the amount of the focus element covered
                // by the keyboard
                int elPixelsCovered = elBottom - currentVisibleHeight;

                // If any amount is covered
                if( elPixelsCovered > 0 ) {

                    // Pan by the amount of coverage
                    int panUpPixels = elPixelsCovered;

                    // Prevent panning so much the top of the element
                    // becomes hidden
                    panUpPixels = ( panUpPixels > elTop ?
                                    elTop : panUpPixels );

                    // Prevent panning more than the keyboard height
                    // (which produces an empty gap in the screen)
                    panUpPixels = ( panUpPixels > coveredHeight ?
                                    coveredHeight : panUpPixels );

                    // Pan up
                    contentView_.setY( -panUpPixels );
                }
            }
            else {
                // Keyboard probably just became hidden

                // Reset pan
                contentView_.setY( 0 );
            }

            // Save usabale height for the next comparison
            priorVisibleHeight_ = currentVisibleHeight;
        }
    }

    private int visibleHeight() {
        Rect r = new Rect();
        contentView_.getWindowVisibleDisplayFrame( r );
        return r.bottom - r.top;
    }

    // Customize this as needed...
    private int viewPortHeight() { return JavaScriptObject.viewPortHeight(); }
    private int focusElementTop( final float ratio ) {
        return (int) (ratio * JavaScriptObject.focusElementTop());
    }
    private int focusElementBottom( final float ratio ) {
        return (int) (ratio * JavaScriptObject.focusElementBottom());
    }

}

React native text going off my screen, refusing to wrap. What to do?

I found solution from below link.

[Text] Text doesn't wrap #1438

<View style={{flexDirection:'row'}}> 
   <Text style={{flex: 1, flexWrap: 'wrap'}}> You miss fdddddd dddddddd 
     You miss fdd
   </Text>
</View>

Output

Below is the Github profile user link if you want to thank him.

Ally Rippley


Edit: Tue Apr 09 2019

As @sudoPlz mentioned in comments it works with flexShrink: 1 updating this answer.

enter image description here

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

It usually happens because one of the following reasons:

  • Entity Set is mapped from Database view
  • A custom Database query
  • Database table doesn't have a primary key

After doing so, you may still need to update in the Entity Framework designer (or alternatively delete the entity and then add it) before you stop getting the error.

Benefits of EBS vs. instance-store (and vice-versa)

The bottom line is you should almost always use EBS backed instances.

Here's why

  • EBS backed instances can be set so that they cannot be (accidentally) terminated through the API.
  • EBS backed instances can be stopped when you're not using them and resumed when you need them again (like pausing a Virtual PC), at least with my usage patterns saving much more money than I spend on a few dozen GB of EBS storage.
  • EBS backed instances don't lose their instance storage when they crash (not a requirement for all users, but makes recovery much faster)
  • You can dynamically resize EBS instance storage.
  • You can transfer the EBS instance storage to a brand new instance (useful if the hardware at Amazon you were running on gets flaky or dies, which does happen from time to time)
  • It is faster to launch an EBS backed instance because the image does not have to be fetched from S3.
  • If the hardware your EBS-backed instance is scheduled for maintenance, stopping and starting the instance automatically migrates to new hardware. I was also able to move an EBS-backed instance on failed hardware by force-stopping the instance and launching it again (your mileage may vary on failed hardware).

I'm a heavy user of Amazon and switched all of my instances to EBS backed storage as soon as the technology came out of beta. I've been very happy with the result.

EBS can still fail - not a silver bullet

Keep in mind that any piece of cloud-based infrastructure can fail at any time. Plan your infrastructure accordingly. While EBS-backed instances provide certain level of durability compared to ephemeral storage instances, they can and do fail. Have an AMI from which you can launch new instances as needed in any availability zone, back up your important data (e.g. databases), and if your budget allows it, run multiple instances of servers for load balancing and redundancy (ideally in multiple availability zones).

When Not To

At some points in time, it may be cheaper to achieve faster IO on Instance Store instances. There was a time when it was certainly true. Now there are many options for EBS storage, catering to many needs. The options and their pricing evolve constantly as technology changes. If you have a significant amount of instances that are truly disposable (they don't affect your business much if they just go away), do the math on cost vs. performance. EBS-backed instances can also die at any point in time, but my practical experience is that EBS is more durable.

Arithmetic overflow error converting numeric to data type numeric

If you want to reduce the size to decimal(7,2) from decimal(9,2) you will have to account for the existing data with values greater to fit into decimal(7,2). Either you will have to delete those numbers are truncate it down to fit into your new size. If there was no data for the field you are trying to update it will do it automatically without issues

How to figure out the SMTP server host?

You could send yourself an email an look in the email header (In Outlook: Open the mail, View->Options, there is 'Internet headers)

Connection failed: SQLState: '01000' SQL Server Error: 10061

I had the same error which was coming and dont need to worry about this error, just restart the server and restart the SQL services. This issue comes when there is low disk space issue and system will go into hung state and then the sql services will stop automatically.

How to import other Python files?

Just to import python file in another python file

lets say I have helper.py python file which has a display function like,

def display():
    print("I'm working sundar gsv")

Now in app.py, you can use the display function,

import helper
helper.display()

The output,

I'm working sundar gsv

NOTE: No need to specify the .py extension.

java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

This problem is because of your classpath miss hamcrest-core-1.3.jar. To resolve this add hamcrest-core-1.3.jar as you add junit-4.XX.jar into your classpath.

At first, I encounter this problem too, but after I refer to the official site and add hamcrest-core-1.3.jar into classpath with command line, it works properly finally.

javac -d ../../../../bin/ -cp ~/libs/junit-4.12.jar:/home/limxtop/projects/algorithms/bin  MaxHeapTest.java 

java -cp ../../../../bin/:/home/limxtop/libs/junit-4.12.jar:/home/limxtop/libs/hamcrest-core-1.3.jar org.junit.runner.JUnitCore com.limxtop.heap.MaxHeapTest

what does mysql_real_escape_string() really do?

The function adds an escape character, the backslash, \, before certain potentially dangerous characters in a string passed in to the function. The characters escaped are

\x00, \n, \r, \, ', " and \x1a.

This can help prevent SQL injection attacks which are often performed by using the ' character to append malicious code to an SQL query.

Spark DataFrame groupBy and sort in the descending order (pyspark)

In PySpark 1.3 sort method doesn't take ascending parameter. You can use desc method instead:

from pyspark.sql.functions import col

(group_by_dataframe
    .count()
    .filter("`count` >= 10")
    .sort(col("count").desc()))

or desc function:

from pyspark.sql.functions import desc

(group_by_dataframe
    .count()
    .filter("`count` >= 10")
    .sort(desc("count"))

Both methods can be used with with Spark >= 1.3 (including Spark 2.x).

CSS hide scroll bar, but have element scrollable

Similar to Kiloumap L'artélon's answer,

::-webkit-scrollbar {
    display:none;
}

works too

How do I script a "yes" response for installing programs?

If you want to just accept defaults you can use:

\n | ./shell_being_run

How to convert a python numpy array to an RGB image with Opencv 2.4?

You don't need to convert NumPy array to Mat because OpenCV cv2 module can accept NumPyarray. The only thing you need to care for is that {0,1} is mapped to {0,255} and any value bigger than 1 in NumPy array is equal to 255. So you should divide by 255 in your code, as shown below.

img = numpy.zeros([5,5,3])

img[:,:,0] = numpy.ones([5,5])*64/255.0
img[:,:,1] = numpy.ones([5,5])*128/255.0
img[:,:,2] = numpy.ones([5,5])*192/255.0

cv2.imwrite('color_img.jpg', img)
cv2.imshow("image", img)
cv2.waitKey()

How do I run a Python script from C#?

I ran into the same problem and Master Morality's answer didn't do it for me. The following, which is based on the previous answer, worked:

private void run_cmd(string cmd, string args)
{
 ProcessStartInfo start = new ProcessStartInfo();
 start.FileName = cmd;//cmd is full path to python.exe
 start.Arguments = args;//args is path to .py file and any cmd line args
 start.UseShellExecute = false;
 start.RedirectStandardOutput = true;
 using(Process process = Process.Start(start))
 {
     using(StreamReader reader = process.StandardOutput)
     {
         string result = reader.ReadToEnd();
         Console.Write(result);
     }
 }
}

As an example, cmd would be @C:/Python26/python.exe and args would be C://Python26//test.py 100 if you wanted to execute test.py with cmd line argument 100. Note that the path the .py file does not have the @ symbol.

How can one see the structure of a table in SQLite?

If you are using PHP you can get it this way:

<?php
    $dbname = 'base.db';
    $db = new SQLite3($dbname);
    $sturturequery = $db->query("SELECT sql FROM sqlite_master WHERE name='foo'");

    $table = $sturturequery->fetchArray();
    echo '<pre>' . $table['sql'] . '</pre>';

    $db->close();
?>

Get value of Span Text

_x000D_
_x000D_
var span_Text = document.getElementById("span_Id").innerText;_x000D_
_x000D_
console.log(span_Text)
_x000D_
<span id="span_Id">I am the Text </span>
_x000D_
_x000D_
_x000D_

C++ printing spaces or tabs given a user input integer

You just need a loop that iterates the number of times given by n and prints a space each time. This would do:

while (n--) {
  std::cout << ' ';
}

Design DFA accepting binary strings divisible by a number 'n'

You can build DFA using simple modular arithmetics. We can interpret w which is a string of k-ary numbers using a following rule

V[0] = 0
V[i] = (S[i-1] * k) + to_number(str[i])

V[|w|] is a number that w is representing. If modify this rule to find w mod N, the rule becomes this.

V[0] = 0
V[i] = ((S[i-1] * k) + to_number(str[i])) mod N

and each V[i] is one of a number from 0 to N-1, which corresponds to each state in DFA. We can use this as the state transition.

See an example.

k = 2, N = 5

| V | (V*2 + 0) mod 5     | (V*2 + 1) mod 5     |
+---+---------------------+---------------------+
| 0 | (0*2 + 0) mod 5 = 0 | (0*2 + 1) mod 5 = 1 |
| 1 | (1*2 + 0) mod 5 = 2 | (1*2 + 1) mod 5 = 3 |
| 2 | (2*2 + 0) mod 5 = 4 | (2*2 + 1) mod 5 = 0 |
| 3 | (3*2 + 0) mod 5 = 1 | (3*2 + 1) mod 5 = 2 |
| 4 | (4*2 + 0) mod 5 = 3 | (4*2 + 1) mod 5 = 4 |

k = 3, N = 5

| V | 0 | 1 | 2 |
+---+---+---+---+
| 0 | 0 | 1 | 2 |
| 1 | 3 | 4 | 0 |
| 2 | 1 | 2 | 3 |
| 3 | 4 | 0 | 1 |
| 4 | 2 | 3 | 4 |

Now you can see a very simple pattern. You can actually build a DFA transition just write repeating numbers from left to right, from top to bottom, from 0 to N-1.

How to 'bulk update' with Django?

If you want to set the same value on a collection of rows, you can use the update() method combined with any query term to update all rows in one query:

some_list = ModelClass.objects.filter(some condition).values('id')
ModelClass.objects.filter(pk__in=some_list).update(foo=bar)

If you want to update a collection of rows with different values depending on some condition, you can in best case batch the updates according to values. Let's say you have 1000 rows where you want to set a column to one of X values, then you could prepare the batches beforehand and then only run X update-queries (each essentially having the form of the first example above) + the initial SELECT-query.

If every row requires a unique value there is no way to avoid one query per update. Perhaps look into other architectures like CQRS/Event sourcing if you need performance in this latter case.

how can get index & count in vuejs

Why its printing 0,1,2...?

Because those are indexes of the items in array, and index always starts from 0 to array.length-1.

To print the item count instead of index, use index+1. Like this:

<li v-for="(catalog, index) in catalogs">this index : {{index + 1}}</li>

And to show the total count use array.length, Like this:

<p>Total Count: {{ catalogs.length }}</p>

As per DOC:

v-for also supports an optional second argument (not first) for the index of the current item.

Set default host and port for ng serve in config file

Another option is to run ng serve command with the --port option e.g

ng serve --port 5050 (i.e for port 5050)

Alternatively, the command: ng serve --port 0, will auto assign an available port for use.

Python popen command. Wait until the command is finished

Depending on how you want to work your script you have two options. If you want the commands to block and not do anything while it is executing, you can just use subprocess.call.

#start and block until done
subprocess.call([data["om_points"], ">", diz['d']+"/points.xml"])

If you want to do things while it is executing or feed things into stdin, you can use communicate after the popen call.

#start and process things, then wait
p = subprocess.Popen([data["om_points"], ">", diz['d']+"/points.xml"])
print "Happens while running"
p.communicate() #now wait plus that you can send commands to process

As stated in the documentation, wait can deadlock, so communicate is advisable.

How to upgrade OpenSSL in CentOS 6.5 / Linux / Unix from source?

You can also check the local changelog to verify whether or not OpenSSL is patched against the vulnerability with the following command:

rpm -q --changelog openssl | grep CVE-2014-0224

If a result is not returned, then you must patch OpenSSL.

http://www.liquidweb.com/kb/update-and-patch-openssl-for-the-ccs-injection-vulnerability/

Why does Java have transient fields?

transient is used to indicate that a class field doesn't need to be serialized. Probably the best example is a Thread field. There's usually no reason to serialize a Thread, as its state is very 'flow specific'.

What is the maximum size of a web browser's cookie's key?

Not completely entirely a direct answer to the original question, but relevant for the curious quickly trying to visually understand their cookie information storage planning without implementing a complex limiter algorithm, this string is 4096 ASCII character bytes:

"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmn"

How can a Jenkins user authentication details be "passed" to a script which uses Jenkins API to create jobs?

If you want to write a script to automate creation of jobs using the Jenkins API, you can use one of the API clients to do that. A ruby client for Jenkins is available at https://github.com/arangamani/jenkins_api_client

gem install jenkins_api_client

require "rubygems"
require "jenkins_api_client"

# Initialize the client by passing in the server information
# and credentials to communicate with the server
client = JenkinsApi::Client.new(
  :server_ip => "127.0.0.1",
  :username => "awesomeuser",
  :password => "awesomepassword"
)

# The following block will create 10 jobs in Jenkins
# test_job_0, test_job_1, test_job_2, ...
10.times do |num|
  client.job.create_freestyle(:name => "test_job_#{num}")
end

# The jobs in Jenkins can be listed using
client.job.list_all

The API client can be used to perform a lot of operations.

You are trying to add a non-nullable field 'new_field' to userprofile without a default

I honestly fount the best way to get around this was to just create another model with all the fields that you require and named slightly different. Run migrations. Delete unused model and run migrations again. Voila.

Reference list item by index within Django template?

@jennifer06262016, you can definitely add another filter to return the objects inside a django Queryset.

@register.filter 
def get_item(Queryset):
    return Queryset.your_item_key

In that case, you would type something like this {{ Queryset|index:x|get_item }} into your template to access some dictionary object. It works for me.

How to change value of process.env.PORT in node.js?

EDIT: Per @sshow's comment, if you're trying to run your node app on port 80, the below is not the best way to do it. Here's a better answer: How do I run Node.js on port 80?

Original Answer:

If you want to do this to run on port 80 (or want to set the env variable more permanently),

  1. Open up your bash profile vim ~/.bash_profile
  2. Add the environment variable to the file export PORT=80
  3. Open up the sudoers config file sudo visudo
  4. Add the following line to the file exactly as so Defaults env_keep +="PORT"

Now when you run sudo node app.js it should work as desired.

How can I remove Nan from list Python/NumPy

Using your example where...

countries= [nan, 'USA', 'UK', 'France']

Since nan is not equal to nan (nan != nan) and countries[0] = nan, you should observe the following:

countries[0] == countries[0]
False

However,

countries[1] == countries[1]
True
countries[2] == countries[2]
True
countries[3] == countries[3]
True

Therefore, the following should work:

cleanedList = [x for x in countries if x == x]

How do I set the background color of Excel cells using VBA?

It doesn't work if you use Function, but works if you Sub. However, you cannot call a sub from a cell using formula.

multiple plot in one figure in Python

This is very simple to do:

import matplotlib.pyplot as plt

plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.legend(loc='best')
plt.show()

You can keep adding plt.plot as many times as you like. As for line type, you need to first specify the color. So for blue, it's b. And for a normal line it's -. An example would be:

plt.plot(total_lengths, sort_times_heap, 'b-', label="Heap")

Java verify void method calls n times with Mockito

The necessary method is Mockito#verify:

public static <T> T verify(T mock,
                           VerificationMode mode)

mock is your mocked object and mode is the VerificationMode that describes how the mock should be verified. Possible modes are:

verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");

You'll need these static imports from the Mockito class in order to use the verify method and these verification modes:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

So in your case the correct syntax will be:

Mockito.verify(mock, times(4)).send()

This verifies that the method send was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.


If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode. A simple

verify(mock).someMethod("was called once");

would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");.


It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");, but we can write

verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");

instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.

Pure CSS multi-level drop-down menu

_x000D_
_x000D_
.third-level-menu_x000D_
{_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    right: -150px;_x000D_
    width: 150px;_x000D_
    list-style: none;_x000D_
    padding: 0;_x000D_
    margin: 0;_x000D_
    display: none;_x000D_
}_x000D_
_x000D_
.third-level-menu > li_x000D_
{_x000D_
    height: 30px;_x000D_
    background: #999999;_x000D_
}_x000D_
.third-level-menu > li:hover { background: #CCCCCC; }_x000D_
_x000D_
.second-level-menu_x000D_
{_x000D_
    position: absolute;_x000D_
    top: 30px;_x000D_
    left: 0;_x000D_
    width: 150px;_x000D_
    list-style: none;_x000D_
    padding: 0;_x000D_
    margin: 0;_x000D_
    display: none;_x000D_
}_x000D_
_x000D_
.second-level-menu > li_x000D_
{_x000D_
    position: relative;_x000D_
    height: 30px;_x000D_
    background: #999999;_x000D_
}_x000D_
.second-level-menu > li:hover { background: #CCCCCC; }_x000D_
_x000D_
.top-level-menu_x000D_
{_x000D_
    list-style: none;_x000D_
    padding: 0;_x000D_
    margin: 0;_x000D_
}_x000D_
_x000D_
.top-level-menu > li_x000D_
{_x000D_
    position: relative;_x000D_
    float: left;_x000D_
    height: 30px;_x000D_
    width: 150px;_x000D_
    background: #999999;_x000D_
}_x000D_
.top-level-menu > li:hover { background: #CCCCCC; }_x000D_
_x000D_
.top-level-menu li:hover > ul_x000D_
{_x000D_
    /* On hover, display the next level's menu */_x000D_
    display: inline;_x000D_
}_x000D_
_x000D_
_x000D_
/* Menu Link Styles */_x000D_
_x000D_
.top-level-menu a /* Apply to all links inside the multi-level menu */_x000D_
{_x000D_
    font: bold 14px Arial, Helvetica, sans-serif;_x000D_
    color: #FFFFFF;_x000D_
    text-decoration: none;_x000D_
    padding: 0 0 0 10px;_x000D_
_x000D_
    /* Make the link cover the entire list item-container */_x000D_
    display: block;_x000D_
    line-height: 30px;_x000D_
}_x000D_
.top-level-menu a:hover { color: #000000; }
_x000D_
<ul class="top-level-menu">_x000D_
    <li><a href="#">About</a></li>_x000D_
    <li><a href="#">Services</a></li>_x000D_
    <li>_x000D_
        <a href="#">Offices</a>_x000D_
        <ul class="second-level-menu">_x000D_
            <li><a href="#">Chicago</a></li>_x000D_
            <li><a href="#">Los Angeles</a></li>_x000D_
            <li>_x000D_
                <a href="#">New York</a>_x000D_
                <ul class="third-level-menu">_x000D_
                    <li><a href="#">Information</a></li>_x000D_
                    <li><a href="#">Book a Meeting</a></li>_x000D_
                    <li><a href="#">Testimonials</a></li>_x000D_
                    <li><a href="#">Jobs</a></li>_x000D_
                </ul>_x000D_
            </li>_x000D_
            <li><a href="#">Seattle</a></li>_x000D_
        </ul>_x000D_
    </li>_x000D_
    <li><a href="#">Contact</a></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_


I have also put together a live demo that's available to play with HERE

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

The accepted convention of passing C-strings to functions is to use a pointer:

void function(char* name)

When the function modifies the string you should also pass in the length:

void function(char* name, size_t name_length)

Your first example:

char *functionname(char *string name[256])

passes an array of pointers to strings which is not what you need at all.

Your second example:

char functionname(char string[256])

passes an array of chars. The size of the array here doesn't matter and the parameter will decay to a pointer anyway, so this is equivalent to:

char functionname(char *string)

See also this question for more details on array arguments in C.

How to remove the bottom border of a box with CSS

You could just set the width to auto. Then the width of the div will equal 0 if it has no content.

width:auto;

Python virtualenv questions

in my project wsgi.py file i have this code (it works with virtualenv,django,apache2 in windows and python 3.4)

import os
import sys
DJANGO_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)),'..')
sys.path.append(DJANGO_PATH)
sys.path.append('c:/myproject/env/Scripts')
sys.path.append('c:/myproject/env/Lib/site-packages')
activate_this = 'c:/myproject/env/scripts/activate_this.py'
exec(open(activate_this).read())
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
application = get_wsgi_application()

in virtualhost file conf i have

<VirtualHost *:80>
    ServerName mysite
    WSGIScriptAlias / c:/myproject/myproject/myproject/wsgi.py
    DocumentRoot c:/myproject/myproject/
    <Directory  "c:/myproject/myproject/myproject/">
       Options +Indexes +FollowSymLinks +MultiViews
       AllowOverride All
      Require local
   </Directory>
</VirtualHost>

pandas read_csv index_col=None not working with delimiters at the end of each line

Re: craigts's response, for anyone having trouble with using either False or None parameters for index_col, such as in cases where you're trying to get rid of a range index, you can instead use an integer to specify the column you want to use as the index. For example:

df = pd.read_csv('file.csv', index_col=0)

The above will set the first column as the index (and not add a range index in my "common case").

Update

Given the popularity of this answer, I thought i'd add some context/ a demo:

# Setting up the dummy data
In [1]: df = pd.DataFrame({"A":[1, 2, 3], "B":[4, 5, 6]})

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

In [3]: df.to_csv('file.csv', index=None)
File[3]:
A  B
1  4
2  5
3  6

Reading without index_col or with None/False will all result in a range index:

In [4]: pd.read_csv('file.csv')
Out[4]:
   A  B
0  1  4
1  2  5
2  3  6

# Note that this is the default behavior, so the same as In [4]
In [5]: pd.read_csv('file.csv', index_col=None)
Out[5]:
   A  B
0  1  4
1  2  5
2  3  6

In [6]: pd.read_csv('file.csv', index_col=False)
Out[6]:
   A  B
0  1  4
1  2  5
2  3  6

However, if we specify that "A" (the 0th column) is actually the index, we can avoid the range index:

In [7]: pd.read_csv('file.csv', index_col=0)
Out[7]:
   B
A
1  4
2  5
3  6

How to make a phone call using intent in Android?

11-25 14:47:01.681: ERROR/AndroidRuntime(302): blah blah...requires android.permission.CALL_PHONE

^ The answer lies in the exception output "requires android.permission.CALL_PHONE" :)

How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

If you are getting an error with the other MemoryStream examples here, then you need to set the Position to 0.

public static Stream ToStream(this bytes[] bytes) 
{
    return new MemoryStream(bytes) 
    {
        Position = 0
    };
}

Compiling/Executing a C# Source File in Command Prompt

You can build your class files within the VS Command prompt (so that all required environment variables are loaded), not the default Windows command window.

To know more about command line building with csc.exe (the compiler), see this article.

How to set default values in Rails?

The suggestion to override new/initialize is probably incomplete. Rails will (frequently) call allocate for ActiveRecord objects, and calls to allocate won't result in calls to initialize.

If you're talking about ActiveRecord objects, take a look at overriding after_initialize.

These blog posts (not mine) are useful:

Default values Default constructors not called

[Edit: SFEley points out that Rails actually does look at the default in the database when it instantiates a new object in memory - I hadn't realized that.]

Get current value selected in dropdown using jQuery

The options discussed above won't work because they are not part of the CSS specification (it is jQuery extension). Having spent 2-3 days digging around for information, I found that the only way to select the Text of the selected option from the drop down is:

{ $("select", id:"Some_ID").find("option[selected='selected']")}

Refer to additional notes below: Because :selected is a jQuery extension and not part of the CSS specification, queries using :selected cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :selected to select elements, first select the elements using a pure CSS selector, then use .filter(":selected"). (copied from: http://api.jquery.com/selected-selector/)

How to get < span > value?

var test = document.getElementById( 'test' );

// To get the text only, you can use "textContent"
console.log( test.textContent ); // "1 2 3 4"

textContent is the standard way. innerText is the property to use for legacy IE. If you want something as cross browser as possible, recursively use nodeValue.

Create a <ul> and fill it based on a passed array

You may also consider the following solution:

let sum = options.set0.concat(options.set1);
const codeHTML = '<ol>' + sum.reduce((html, item) => {
    return html + "<li>" + item + "</li>";
        }, "") + '</ol>';
document.querySelector("#list").innerHTML = codeHTML;

JavaScript: Parsing a string Boolean value?

I like the solution provided by RoToRa (try to parse given value, if it has any boolean meaning, otherwise - don't). Nevertheless I'd like to provide small modification, to have it working more or less like Boolean.TryParse in C#, which supports out params. In JavaScript it can be implemented in the following manner:

var BoolHelpers = {
    tryParse: function (value) {
        if (typeof value == 'boolean' || value instanceof Boolean)
            return value;
        if (typeof value == 'string' || value instanceof String) {
            value = value.trim().toLowerCase();
            if (value === 'true' || value === 'false')
                return value === 'true';
        }
        return { error: true, msg: 'Parsing error. Given value has no boolean meaning.' }
    }
}

The usage:

var result = BoolHelpers.tryParse("false");
if (result.error) alert(result.msg);

500 internal server error, how to debug

You can turn on your PHP errors with error_reporting:

error_reporting(E_ALL);
ini_set('display_errors', 'on');

Edit: It's possible that even after putting this, errors still don't show up. This can be caused if there is a fatal error in the script. From PHP Runtime Configuration:

Although display_errors may be set at runtime (with ini_set()), it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.

You should set display_errors = 1 in your php.ini file and restart the server.

Android disable screen timeout while app is running

Its importante to note that these methods all must be run from the UI thread to work. See changing KeepScreenOn from javascript in Android cordova app

How to vertically align <li> elements in <ul>?

You can use flexbox for this.

ul {
    display: flex;
    align-items: center;
}

A detailed explanation of how to use flexbox can be found here.

Error when checking Java version: could not find java.dll

Reinstall JDK and set system variable JAVA_HOME on your JDK. (e.g. C:\tools\jdk7)
And add JAVA_HOME variable to your PATH system variable

Type in command line

echo %JAVA_HOME%

and

java -version

To verify whether your installation was done successfully.


This problem generally occurs in Windows when your "Java Runtime Environment" registry entry is missing or mismatched with the installed JDK. The mismatch can be due to multiple JDKs.

Steps to resolve:

  1. Open the Run window:

    Press windows+R

  2. Open registry window:

    Type regedit and enter.

  3. Go to: \HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\

  4. If Java Runtime Environment is not present inside JavaSoft, then create a new Key and give the name Java Runtime Environment.

  5. For Java Runtime Environment create "CurrentVersion" String Key and give appropriate version as value:

JRE regedit entry

  1. Create a new subkey of 1.8.

  2. For 1.8 create a String Key with name JavaHome with the value of JRE home:

    JRE regedit entry 2

Ref: https://mybindirectory.blogspot.com/2019/05/error-could-not-find-javadll.html

How do I extract Month and Year in a MySQL date and compare them?

You may want to check out the mySQL docs in regard to the date functions. http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html

There is a YEAR() function just as there is a MONTH() function. If you're doing a comparison though is there a reason to chop up the date? Are you truly interested in ignoring day based differences and if so is this how you want to do it?

No numeric types to aggregate - change in groupby() behaviour?

How are you generating your data?

See how the output shows that your data is of 'object' type? the groupby operations specifically check whether each column is a numeric dtype first.

In [31]: data
Out[31]: 
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 2557 entries, 2004-01-01 00:00:00 to 2010-12-31 00:00:00
Freq: <1 DateOffset>
Columns: 360 entries, -89.75 to 89.75
dtypes: object(360)

look ?


Did you initialize an empty DataFrame first and then filled it? If so that's probably why it changed with the new version as before 0.9 empty DataFrames were initialized to float type but now they are of object type. If so you can change the initialization to DataFrame(dtype=float).

You can also call frame.astype(float)

PHP to write Tab Characters inside a file?

The tab character is \t. Notice the use of " instead of '.

$chunk = "abc\tdef\tghi";

PHP Strings - Double quoted

If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:

...

\t horizontal tab (HT or 0x09 (9) in ASCII)


Also, let me recommend the fputcsv() function which is for the purpose of writing CSV files.

What is the C++ function to raise a number to a power?

std::pow in the <cmath> header has these overloads:

pow(float, float);
pow(float, int);
pow(double, double); // taken over from C
pow(double, int);
pow(long double, long double);
pow(long double, int);

Now you can't just do

pow(2, N)

with N being an int, because it doesn't know which of float, double, or long double version it should take, and you would get an ambiguity error. All three would need a conversion from int to floating point, and all three are equally costly!

Therefore, be sure to have the first argument typed so it matches one of those three perfectly. I usually use double

pow(2.0, N)

Some lawyer crap from me again. I've often fallen in this pitfall myself, so I'm going to warn you about it.

Convert java.time.LocalDate into java.util.Date type

java.util.Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());

How to dismiss AlertDialog in android

Here is How I close my alertDialog

lv_three.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                GetTalebeDataUser clickedObj = (GetTalebeDataUser) parent.getItemAtPosition(position);
                alertDialog.setTitle(clickedObj.getAd());
                alertDialog.setMessage("Ögrenci Bilgileri Güncelle?");
                alertDialog.setIcon(R.drawable.ic_info);
                // Setting Positive "Yes" Button
                alertDialog.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // User pressed YES button. Write Logic Here
                    }
                });
                alertDialog.setNegativeButton("Iptal", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //alertDialog.
                        alertDialog.setCancelable(true); // HERE

                    }
                });
                alertDialog.show();
                return true;
            }
        });

Is an empty href valid?

Although this question is already answered (tl;dr: yes, an empty href value is valid), none of the existing answers references the relevant specifications.

An empty string can’t be a URI. However, the href attribute doesn’t only take URIs as value, but also URI references. An empty string may be a URI reference.

HTML 4.01

HTML 4.01 uses RFC 2396, where it says in section 4.2. Same-document References (bold emphasis mine):

A URI reference that does not contain a URI is a reference to the current document. In other words, an empty URI reference within a document is interpreted as a reference to the start of that document, and a reference containing only a fragment identifier is a reference to the identified fragment of that document.

RFC 2396 is obsoleted by RFC 3986 (which is currently IETF’s URI standard), which essentially says the same.

HTML5

HTML5 uses (valid URL potentially surrounded by spaces ? valid URL) W3C’s URL spec, which has been discontinued. WHATWG’s URL Standard should be used instead (see the last section).

HTML 5.1

HTML 5.1 uses (valid URL potentially surrounded by spaces ? valid URL) WHATWG’s URL Standard (see the next section).

WHATWG HTML

WHATWG’s HTML uses (valid URL potentially surrounded by spaces) the definition of valid URL string from WHATWG’s URL Standard, where it says that it can be a relative-URL-with-fragment string, which must at least be a relative-URL string, which can be a path-relative-scheme-less-URL string, which is a path-relative-URL string that doesn’t start with a scheme string followed by :, and its definition says (bold emphasis mine):

A path-relative-URL string must be zero or more URL-path-segment strings, separated from each other by U+002F (/), and not start with U+002F (/).

Difference between const reference and normal parameter

The difference is more prominent when you are passing a big struct/class.

struct MyData {
    int a,b,c,d,e,f,g,h;
    long array[1234];
};
void DoWork(MyData md);
void DoWork(const MyData& md);

when you use use 'normal' parameter, you pass the parameter by value and hence creating a copy of the parameter you pass. if you are using const reference, you pass it by reference and the original data is not copied.

in both cases, the original data cannot be modified from inside the function.

EDIT:
In certain cases, the original data might be able to get modified as pointed out by Charles Bailey in his answer.

MongoDB: update every document on one field

You can use updateMany() methods of mongodb to update multiple document

Simple query is like this

db.collection.updateMany(filter, update, options)

For more doc of uppdateMany read here

As per your requirement the update code will be like this:

User.updateMany({"created": false}, {"$set":{"created": true}});

here you need to use $set because you just want to change created from true to false. For ref. If you want to change entire doc then you don't need to use $set

Add CSS3 transition expand/collapse

Here's a solution that doesn't use JS at all. It uses checkboxes instead.

You can hide the checkbox by adding this to your CSS:

.container input{
    display: none;
}

And then add some styling to make it look like a button.

Here's the source code that I modded.

How do I tar a directory of files and folders without including the directory itself?

This Answer should work in most situations. Notice however how the filenames are stored in the tar file as, for example, ./file1 rather than just file1. I found that this caused problems when using this method to manipulate tarballs used as package files in BuildRoot.

One solution is to use some Bash globs to list all files except for .. like this:

tar -C my_dir -zcvf my_dir.tar.gz .[^.]* ..?* *

This is a trick I learnt from this answer.

Now tar will return an error if there are no files matching ..?* or .[^.]* , but it will still work. If the error is a problem (you are checking for success in a script), this works:

shopt -s nullglob
tar -C my_dir -zcvf my_dir.tar.gz .[^.]* ..?* *
shopt -u nullglob

Though now we are messing with shell options, we might decide that it is neater to have * match hidden files:

shopt -s dotglob
tar -C my_dir -zcvf my_dir.tar.gz *
shopt -u dotglob

This might not work where your shell globs * in the current directory, so alternatively, use:

shopt -s dotglob
cd my_dir
tar -zcvf ../my_dir.tar.gz *
cd ..
shopt -u dotglob

How can I get a list of locally installed Python modules?

This will help

In terminal or IPython, type:

help('modules')

then

In [1]: import                      #import press-TAB
Display all 631 possibilities? (y or n)
ANSI                   audiodev               markupbase
AptUrl                 audioop                markupsafe
ArgImagePlugin         avahi                  marshal
BaseHTTPServer         axi                    math
Bastion                base64                 md5
BdfFontFile            bdb                    mhlib
BmpImagePlugin         binascii               mimetools
BufrStubImagePlugin    binhex                 mimetypes
CDDB                   bisect                 mimify
CDROM                  bonobo                 mmap
CGIHTTPServer          brlapi                 mmkeys
Canvas                 bsddb                  modulefinder
CommandNotFound        butterfly              multifile
ConfigParser           bz2                    multiprocessing
ContainerIO            cPickle                musicbrainz2
Cookie                 cProfile               mutagen
Crypto                 cStringIO              mutex
CurImagePlugin         cairo                  mx
DLFCN                  calendar               netrc
DcxImagePlugin         cdrom                  new
Dialog                 cgi                    nis
DiscID                 cgitb                  nntplib
DistUpgrade            checkbox               ntpath

php how to go one level up on dirname(__FILE__)

For PHP < 5.3 use:

$upOne = realpath(dirname(__FILE__) . '/..');

In PHP 5.3 to 5.6 use:

$upOne = realpath(__DIR__ . '/..');

In PHP >= 7.0 use:

$upOne = dirname(__DIR__, 1);

Maven Jacoco Configuration - Exclude classes/packages from report not working

Here is the working sample in pom.xml file.

    <plugin>
        <groupId>org.jacoco</groupId>
        <artifactId>jacoco-maven-plugin</artifactId>
        <version>${jacoco.version}</version>


        <executions>
            <execution>
                <id>prepare-agent</id>
                <goals>
                    <goal>prepare-agent</goal>
                </goals>
            </execution>
            <execution>
                <id>post-unit-test</id>
                <phase>test</phase>
                <goals>
                    <goal>report</goal>
                </goals>

            </execution>

            <execution>
                <id>default-check</id>
                <goals>
                    <goal>check</goal>
                </goals>

            </execution>
        </executions>
        <configuration>
            <dataFile>target/jacoco.exec</dataFile>
            <!-- Sets the output directory for the code coverage report. -->
            <outputDirectory>target/jacoco-ut</outputDirectory>
            <rules>
                <rule implementation="org.jacoco.maven.RuleConfiguration">
                    <element>PACKAGE</element>
                    <limits>
                        <limit implementation="org.jacoco.report.check.Limit">
                            <counter>COMPLEXITY</counter>
                            <value>COVEREDRATIO</value>
                            <minimum>0.00</minimum>
                        </limit>
                    </limits>
                </rule>
            </rules>
            <excludes>
                <exclude>com/pfj/fleet/dao/model/**/*</exclude>
            </excludes>
            <systemPropertyVariables>

                <jacoco-agent.destfile>target/jacoco.exec</jacoco-agent.destfile>
            </systemPropertyVariables>
        </configuration>
    </plugin>

R Markdown - changing font size and font type in html output

I think fontsize: command in YAML only works for LaTeX / pdf. Apart, in standard latex classes (article, book, and report) only three font sizes are accepted (10pt, 11pt, and 12pt).

Regarding appearance (different font types and colors), you can specify a theme:. See Appearance and Style.

I guess, what you are looking for is your own css. Make a file called style.css, save it in the same folder as your .Rmd and include it in the YAML header:

---
output:
  html_document:
    css: style.css
---

In the css-file you define your font-type and size:

/* Whole document: */
body{
  font-family: Helvetica;
  font-size: 16pt;
}
/* Headers */
h1,h2,h3,h4,h5,h6{
  font-size: 24pt;
}

Receive result from DialogFragment

As you can see here there is a very simple way to do that.

In your DialogFragment add an interface listener like:

public interface EditNameDialogListener {
    void onFinishEditDialog(String inputText);
}

Then, add a reference to that listener:

private EditNameDialogListener listener;

This will be used to "activate" the listener method(s), and also to check if the parent Activity/Fragment implements this interface (see below).

In the Activity/FragmentActivity/Fragment that "called" the DialogFragment simply implement this interface.

In your DialogFragment all you need to add at the point where you'd like to dismiss the DialogFragment and return the result is this:

listener.onFinishEditDialog(mEditText.getText().toString());
this.dismiss();

Where mEditText.getText().toString() is what will be passed back to the calling Activity.

Note that if you want to return something else simply change the arguments the listener takes.

Finally, you should check whether the interface was actually implemented by the parent activity/fragment:

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    // Verify that the host activity implements the callback interface
    try {
        // Instantiate the EditNameDialogListener so we can send events to the host
        listener = (EditNameDialogListener) context;
    } catch (ClassCastException e) {
        // The activity doesn't implement the interface, throw exception
        throw new ClassCastException(context.toString()
                + " must implement EditNameDialogListener");
    }
}

This technique is very flexible and allow calling back with the result even if your don;t want to dismiss the dialog just yet.

c#: getter/setter

These are called auto properties.

http://msdn.microsoft.com/en-us/library/bb384054.aspx

Functionally (and in terms of the compiled IL), they are the same as properties with backing fields.

Equivalent of *Nix 'which' command in PowerShell?

If you want a comamnd that both accepts input from pipeline or as paramater, you should try this:

function which($name) {
    if ($name) { $input = $name }
    Get-Command $input | Select-Object -ExpandProperty Path
}

copy-paste the command to your profile (notepad $profile).

Examples:

? echo clang.exe | which
C:\Program Files\LLVM\bin\clang.exe

? which clang.exe
C:\Program Files\LLVM\bin\clang.exe

Eclipse returns error message "Java was started but returned exit code = 1"

I tried to change the path in the parameter -vm, but it did not help. Then I deleted the parameter -vm and -vmargs from the eclipse.ini. It worked for me

How to create loading dialogs in Android?

It's a ProgressDialog, with setIndeterminate(true).

From http://developer.android.com/guide/topics/ui/dialogs.html#ProgressDialog

ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "", 
                    "Loading. Please wait...", true);

An indeterminate progress bar doesn't actually show a bar, it shows a spinning activity circle thing. I'm sure you know what I mean :)

Update multiple rows using select statement

I have used this one on MySQL, MS Access and SQL Server. The id fields are the fields on wich the tables coincide, not necesarily the primary index.

UPDATE DestTable INNER JOIN SourceTable ON DestTable.idField = SourceTable.idField SET DestTable.Field1 = SourceTable.Field1, DestTable.Field2 = SourceTable.Field2...

How to use && in EL boolean expressions in Facelets?

Facelets is a XML based view technology. The & is a special character in XML representing the start of an entity like &amp; which ends with the ; character. You'd need to either escape it, which is ugly:

rendered="#{beanA.prompt == true &amp;&amp; beanB.currentBase != null}"

or to use the and keyword instead, which is preferred as to readability and maintainability:

rendered="#{beanA.prompt == true and beanB.currentBase != null}"

See also:


Unrelated to the concrete problem, comparing booleans with booleans makes little sense when the expression expects a boolean outcome already. I'd get rid of == true:

rendered="#{beanA.prompt and beanB.currentBase != null}"

PreparedStatement with Statement.RETURN_GENERATED_KEYS

private void alarmEventInsert(DriveDetail driveDetail, String vehicleRegNo, int organizationId) {

    final String ALARM_EVENT_INS_SQL = "INSERT INTO alarm_event (event_code,param1,param2,org_id,created_time) VALUES (?,?,?,?,?)";
    CachedConnection conn = JDatabaseManager.getConnection();
    PreparedStatement ps = null;
    ResultSet generatedKeys = null;
    try {
        ps = conn.prepareStatement(ALARM_EVENT_INS_SQL, ps.RETURN_GENERATED_KEYS);
        ps.setInt(1, driveDetail.getEventCode());
        ps.setString(2, vehicleRegNo);
        ps.setString(3, null);
        ps.setInt(4, organizationId);
        ps.setString(5, driveDetail.getCreateTime());
        ps.execute();
        generatedKeys = ps.getGeneratedKeys();
        if (generatedKeys.next()) {
            driveDetail.setStopDuration(generatedKeys.getInt(1));
        }
    } catch (SQLException e) {
        e.printStackTrace();
        logger.error("Error inserting into alarm_event : {}", e
                .getMessage());
        logger.info(ps.toString());
    } finally {
        if (ps != null) {
            try {

                if (ps != null)
                    ps.close();
            } catch (SQLException e) {
                logger.error("Error closing prepared statements : {}", e
                        .getMessage());
            }
        }
    }
    JDatabaseManager.freeConnection(conn);
}

Count number of files within a directory in Linux?

this is one:

ls -l . | egrep -c '^-'

Note:

ls -1 | wc -l

Which means: ls: list files in dir

-1: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too

|: pipe output onto...

wc: "wordcount"

-l: count lines.

AJAX POST and Plus Sign ( + ) -- How to Encode?

In JavaScript try:

encodeURIComponent() 

and in PHP:

urldecode($_POST['field']);

error LNK2005, already defined?

If you want both to reference the same variable, one of them should have int k;, and the other should have extern int k;

For this situation, you typically put the definition (int k;) in one .cpp file, and put the declaration (extern int k;) in a header, to be included wherever you need access to that variable.

If you want each k to be a separate variable that just happen to have the same name, you can either mark them as static, like: static int k; (in all files, or at least all but one file). Alternatively, you can us an anonymous namespace:

namespace { 
   int k;
};

Again, in all but at most one of the files.

In C, the compiler generally isn't quite so picky about this. Specifically, C has a concept of a "tentative definition", so if you have something like int k; twice (in either the same or separate source files) each will be treated as a tentative definition, and there won't be a conflict between them. This can be a bit confusing, however, because you still can't have two definitions that both include initializers--a definition with an initializer is always a full definition, not a tentative definition. In other words, int k = 1; appearing twice would be an error, but int k; in one place and int k = 1; in another would not. In this case, the int k; would be treated as a tentative definition and the int k = 1; as a definition (and both refer to the same variable).

How to find Control in TemplateField of GridView?

Try this:

foreach(GridViewRow row in GridView1.Rows) {
    if(row.RowType == DataControlRowType.DataRow) {
        HyperLink myHyperLink = row.FindControl("myHyperLinkID") as HyperLink;
    }
}

If you are handling RowDataBound event, it's like this:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        HyperLink myHyperLink = e.Row.FindControl("myHyperLinkID") as HyperLink;
    }
}

Ionic 2: Cordova is not available. Make sure to include cordova.js or run in a device/simulator (running in emulator)

This is quite late but anyone going through the same problem might benefit from this answer.First try to add browser by running below command ionic platform add browser and then run command ionic run browser.

which is the difference between ionic serve and ionic run browser?

Ionic serve - runs your app as a website (meaning it doesn't have any Cordova capabilities). Ionic run browser - runs your app in the Cordova browser platform, which will inject cordova.js and any plugins that have browser capabilities

You can refer this link to know more difference between ionic serve and ionic run browser command

Update

From Ionic 3 this command has been changed. Use the command below instead;

ionic cordova platform add browser

ionic cordova run browser

You can find out which version of ionic you are using by running: ionic --version

Mysql password expired. Can't connect

i have faced this issue few days ago. For best solution for 5.7 version of MySQL; login your mysql console and alter your password with the following command:

ALTER USER `root`@`localhost` IDENTIFIED BY 'new_password', `root`@`localhost` PASSWORD EXPIRE NEVER;

How eliminate the tab space in the column in SQL Server 2008

Use the Below Code for that

UPDATE Table1 SET Column1 = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(Column1, CHAR(9), ''), CHAR(10), ''), CHAR(13), '')))`

How to disable RecyclerView scrolling?

I know this already has an accepted answer, but the solution doesn't take into account a use-case that I came across.

I specifically needed a header item that was still clickable, yet disabled the scrolling mechanism of the RecyclerView. This can be accomplished with the following code:

recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
                            @Override
     public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
         return e.getAction() == MotionEvent.ACTION_MOVE;
     }

     @Override
     public void onTouchEvent(RecyclerView rv, MotionEvent e) {

     }

     @Override
     public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }
});

WooCommerce return product object by id

Another easy way is to use the WC_Product_Factory class and then call function get_product(ID)

http://docs.woothemes.com/wc-apidocs/source-class-WC_Product_Factory.html#16-63

sample:

// assuming the list of product IDs is are stored in an array called IDs;
$_pf = new WC_Product_Factory();  
foreach ($IDs as $id) {

    $_product = $_pf->get_product($id);

    // from here $_product will be a fully functional WC Product object, 
    // you can use all functions as listed in their api
}

You can then use all the function calls as listed in their api: http://docs.woothemes.com/wc-apidocs/class-WC_Product.html

ggplot2 plot area margins?

You can adjust the plot margins with plot.margin in theme() and then move your axis labels and title with the vjust argument of element_text(). For example :

library(ggplot2)
library(grid)
qplot(rnorm(100)) +
    ggtitle("Title") +
    theme(axis.title.x=element_text(vjust=-2)) +
    theme(axis.title.y=element_text(angle=90, vjust=-0.5)) +
    theme(plot.title=element_text(size=15, vjust=3)) +
    theme(plot.margin = unit(c(1,1,1,1), "cm"))

will give you something like this :

enter image description here

If you want more informations about the different theme() parameters and their arguments, you can just enter ?theme at the R prompt.

SyntaxError: Unexpected token function - Async Await Nodejs

Async functions are not supported by Node versions older than version 7.6.

You'll need to transpile your code (e.g. using Babel) to a version of JS that Node understands if you are using an older version.

That said, the current (2018) LTS version of Node.js is 8.x, so if you are using an earlier version you should very strongly consider upgrading.

Check whether user has a Chrome extension installed

Another possible solution if you own the website is to use inline installation.

if (chrome.app.isInstalled) {
  // extension is installed.
}

I know this an old question but this way was introduced in Chrome 15 and so I thought Id list it for anyone only now looking for an answer.

Get HTML5 localStorage keys

for (var key in localStorage){
   console.log(key)
}

EDIT: this answer is getting a lot of upvotes, so I guess it's a common question. I feel like I owe it to anyone who might stumble on my answer and think that it's "right" just because it was accepted to make an update. Truth is, the example above isn't really the right way to do this. The best and safest way is to do it like this:

for ( var i = 0, len = localStorage.length; i < len; ++i ) {
  console.log( localStorage.getItem( localStorage.key( i ) ) );
}

Convert json to a C# array?

Yes, Json.Net is what you need. You basically want to deserialize a Json string into an array of objects.

See their examples:

string myJsonString = @"{
  "Name": "Apple",
  "Expiry": "\/Date(1230375600000+1300)\/",
  "Price": 3.99,
  "Sizes": [
    "Small",
    "Medium",
    "Large"
  ]
}";

// Deserializes the string into a Product object
Product myProduct = JsonConvert.DeserializeObject<Product>(myJsonString);

REST API - Use the "Accept: application/json" HTTP Header

Here's a handy site to test out your headers. You can see your browser headers and also use cURL to reflect back whatever headers you send.

For example, you can validate the content negotiation like this.

This Accept header prefers plain text so returns in that format:-

$ curl -H "Accept: application/json;q=0.9,text/plain" http://gethttp.info/Accept
application/json;q=0.9,text/plain

Whereas this one prefers JSON and so returns in that format:-

$ curl -H "Accept: application/json,text/*;q=0.99" http://gethttp.info/Accept
{
   "Accept": "application/json,text/*;q=0.99"
}

For Loop on Lua

Your problem is simple:

names = {'John', 'Joe', 'Steve'}
for names = 1, 3 do
  print (names)
end

This code first declares a global variable called names. Then, you start a for loop. The for loop declares a local variable that just happens to be called names too; the fact that a variable had previously been defined with names is entirely irrelevant. Any use of names inside the for loop will refer to the local one, not the global one.

The for loop says that the inner part of the loop will be called with names = 1, then names = 2, and finally names = 3. The for loop declares a counter that counts from the first number to the last, and it will call the inner code once for each value it counts.

What you actually wanted was something like this:

names = {'John', 'Joe', 'Steve'}
for nameCount = 1, 3 do
  print (names[nameCount])
end

The [] syntax is how you access the members of a Lua table. Lua tables map "keys" to "values". Your array automatically creates keys of integer type, which increase. So the key associated with "Joe" in the table is 2 (Lua indices always start at 1).

Therefore, you need a for loop that counts from 1 to 3, which you get. You use the count variable to access the element from the table.

However, this has a flaw. What happens if you remove one of the elements from the list?

names = {'John', 'Joe'}
for nameCount = 1, 3 do
  print (names[nameCount])
end

Now, we get John Joe nil, because attempting to access values from a table that don't exist results in nil. To prevent this, we need to count from 1 to the length of the table:

names = {'John', 'Joe'}
for nameCount = 1, #names do
  print (names[nameCount])
end

The # is the length operator. It works on tables and strings, returning the length of either. Now, no matter how large or small names gets, this will always work.

However, there is a more convenient way to iterate through an array of items:

names = {'John', 'Joe', 'Steve'}
for i, name in ipairs(names) do
  print (name)
end

ipairs is a Lua standard function that iterates over a list. This style of for loop, the iterator for loop, uses this kind of iterator function. The i value is the index of the entry in the array. The name value is the value at that index. So it basically does a lot of grunt work for you.

"CSV file does not exist" for a filename with embedded quotes

Have you tried?

df = pd.read_csv("Users/alekseinabatov/Documents/Python/FBI-CRIME11.csv")

or maybe

df = pd.read_csv('Users/alekseinabatov/Documents/Python/"FBI-CRIME11.csv"')

(If the file name has quotes)

Programmatically change the src of an img tag

Give your img tag an id, then you can

document.getElementById("imageid").src="../template/save.png";

Select a dummy column with a dummy value in SQL?

If you meant just ABC as simple value, answer above is the one that works fine.

If you meant concatenation of values of rows that are not selected by your main query, you will need to use a subquery.

Something like this may work:

SELECT t1.col1, 
t1.col2, 
(SELECT GROUP_CONCAT(col2 SEPARATOR '') FROM  Table1 t2 WHERE t2.col1 != 0) as col3 
FROM Table1 t1
WHERE t1.col1 = 0;

Actual syntax maybe a bit off though

POST data to a URL in PHP

If you're looking to post data to a URL from PHP code itself (without using an html form) it can be done with curl. It will look like this:

$url = 'http://www.someurl.com';
$myvars = 'myvar1=' . $myvar1 . '&myvar2=' . $myvar2;

$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec( $ch );

This will send the post variables to the specified url, and what the page returns will be in $response.

Linux shell script for database backup

As a DBA, You must schedule the backup of MySQL Database in case of any issues so that you can recover your databases from the current backup.

Here, we are using mysqldump to take the backup of mysql databases and the same you can put into the script.

[orahow@oradbdb DB_Backup]$ cat .backup_script.sh

#!/bin/bash
# Database credentials
user="root"
password="1Loginxx"
db_name="orahowdb"
v_cnt=0
logfile_path=/DB_Backup
touch "$logfile_path/orahowdb_backup.log"
# Other options
backup_path="/DB_Backup"
date=$(date +"%d-%b-%Y-%H-%M-%p")
# Set default file permissions

Continue Reading .... MySQL Backup

Access index of the parent ng-repeat from child ng-repeat

According to ng-repeat docs http://docs.angularjs.org/api/ng.directive:ngRepeat, you can store the key or array index in the variable of your choice. (indexVar, valueVar) in values

so you can write

<div ng-repeat="(fIndex, f) in foos">
  <div>
    <div ng-repeat="b in foos.bars">
      <a ng-click="addSomething(fIndex)">Add Something</a>
    </div>
  </div>
</div>

One level up is still quite clean with $parent.$index but several parents up, things can get messy.

Note: $index will continue to be defined at each scope, it is not replaced by fIndex.

How to conditional format based on multiple specific text in Excel

Suppose your "Don't Check" list is on Sheet2 in cells A1:A100, say, and your current client IDs are in Sheet1 in Column A.

What you would do is:

  1. Select the whole data table you want conditionally formatted in Sheet1
  2. Click Conditional Formatting > New Rule > Use a Formula to determine which cells to format
  3. In the formula bar, type in =ISNUMBER(MATCH($A1,Sheet2!$A$1:$A$100,0)) and select how you want those rows formatted

And that should do the trick.

Phone number formatting an EditText in Android

You can accept only numbers and phone number type using java code

 EditText number1 = (EditText) layout.findViewById(R.id.edittext); 
    number1.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_CLASS_PHONE);
     number1.setKeyListener(DigitsKeyListener.getInstance("0123456789”));
      number1.setFilters(new InputFilter[] {new InputFilter.LengthFilter(14)}); // 14 is max digits

This code will avoid lot of validations after reading input

Flutter: Run method on Widget build complete

UPDATE: Flutter v1.8.4

Both mentioned codes are working now:

Working:

WidgetsBinding.instance
        .addPostFrameCallback((_) => yourFunction(context));

Working

import 'package:flutter/scheduler.dart';

SchedulerBinding.instance.addPostFrameCallback((_) => yourFunction(context));

Using (Ana)conda within PyCharm

Change the project interpreter to ~/anaconda2/python/bin by going to File -> Settings -> Project -> Project Interpreter. Also update the run configuration to use the project default Python interpreter via Run -> Edit Configurations. This makes PyCharm use Anaconda instead of the default Python interpreter under usr/bin/python27.

How to change colors of a Drawable in Android?

Too late but in case someone need it:

   fun setDrawableColor(drawable: Drawable, color: Int) :Drawable {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            drawable.colorFilter = BlendModeColorFilter(color, BlendMode.SRC_ATOP)
            return drawable
        } else {
            drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
            return drawable
        }
    }

Convert array to JSON string in swift

For Swift 3.0 you have to use this:

var postString = ""
    do {
        let data =  try JSONSerialization.data(withJSONObject: self.arrayNParcel, options: .prettyPrinted)
        let string1:String = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String

        postString = "arrayData=\(string1)&user_id=\(userId)&markupSrcReport=\(markup)"
    } catch {
        print(error.localizedDescription)
    }
    request.httpBody = postString.data(using: .utf8)

100% working TESTED

Adding elements to a collection during iteration

In general, it's not safe, though for some collections it may be. The obvious alternative is to use some kind of for loop. But you didn't say what collection you're using, so that may or may not be possible.

Django gives Bad Request (400) when DEBUG = False

I had the same problem and I fixed it by setting ALLOWED_HOSTS = ['*'] and to solve the problem with the static images you have to change the virtual paths in the environment configuration like this:

Virtual Path                 Directory

/static/                          /opt/python/current/app/yourpj/static/
/media/                        /opt/python/current/app/Nuevo/media/

I hope it helps you.

PD: sorry for my bad english.

Merge two rows in SQL

SELECT Q.FK
      ,ISNULL(T1.Field1, T2.Field2) AS Field
FROM (SELECT FK FROM Table1
        UNION
      SELECT FK FROM Table2) AS Q
LEFT JOIN Table1 AS T1 ON T1.FK = Q.FK
LEFT JOIN Table2 AS T2 ON T2.FK = Q.FK

If there is one table, write Table1 instead of Table2

When do you use Git rebase instead of Git merge?

I just created a FAQ for my team in my own words which answers this question. Let me share:

What is a merge?

A commit, that combines all changes of a different branch into the current.

What is a rebase?

Re-comitting all commits of the current branch onto a different base commit.

What are the main differences between merge and rebase?

  1. merge executes only one new commit. rebase typically executes multiple (number of commits in current branch).
  2. merge produces a new generated commit (the so called merge-commit). rebase only moves existing commits.

In which situations should we use a merge?

Use merge whenever you want to add changes of a branched out branch back into the base branch.

Typically, you do this by clicking the "Merge" button on Pull/Merge Requests, e.g. on GitHub.

In which situations should we use a rebase?

Use rebase whenever you want to add changes of a base branch back to a branched out branch.

Typically, you do this in feature branches whenever there's a change in the main branch.

Why not use merge to merge changes from the base branch into a feature branch?

  1. The git history will include many unnecessary merge commits. If multiple merges were needed in a feature branch, then the feature branch might even hold more merge commits than actual commits!

  2. This creates a loop which destroys the mental model that Git was designed by which causes troubles in any visualization of the Git history.

    Imagine there's a river (e.g. the "Nile"). Water is flowing in one direction (direction of time in Git history). Now and then, imagine there's a branch to that river and suppose most of those branches merge back into the river. That's what the flow of a river might look like naturally. It makes sense.

    But then imagine there's a small branch of that river. Then, for some reason, the river merges into the branch and the branch continues from there. The river has now technically disappeared, it's now in the branch. But then, somehow magically, that branch is merged back into the river. Which river you ask? I don't know. The river should actually be in the branch now, but somehow it still continues to exist and I can merge the branch back into the river. So, the river is in the river. Kind of doesn't make sense.

    This is exactly what happens when you merge the base branch into a feature branch and then when the feature branch is done, you merge that back into the base branch again. The mental model is broken. And because of that, you end up with a branch visualization that's not very helpful.

Example Git History when using merge:

Example Git History when using merge

Note the many commits starting with Merge branch 'develop' into .... They don't even exist if you rebase (there, you will only have pull request merge commits). Also many visual branch merge loops (develop into feature into develop).

Example Git History when using rebase:

Example Git History when using rebase

Much cleaner Git history with much less merge commits and no cluttered visual branch merge loops whatsoever.

Are there any downsides / pitfalls with rebase?

Yes:

  1. Because a rebase moves commits (technically re-executes them), the commit date of all moved commits will be the time of the rebase and the git history loses the initial commit time. So, if the exact date of a commit is needed for some reason, then merge is the better option. But typically, a clean git history is much more useful than exact commit dates.
  2. If the rebased branch has multiple commits that change the same line and that line was also changed in the base branch, you might need to solve merge conflicts for that same line multiple times, which you never need to do when merging. So, on average, there's more merge conflicts to solve.

Tips to reduce merge conflicts when using rebase:

  1. Rebase often. I typically recommend doing it at least once a day.
  2. Try to squash changes on the same line into one commit as much as possible.

How to use OpenFileDialog to select a folder?

As a note for future users who would like to avoid using FolderBrowserDialog, Microsoft once released an API called the WindowsAPICodePack that had a helpful dialog called CommonOpenFileDialog, that could be set into a IsFolderPicker mode. The API is available from Microsoft as a NuGet package.

This is all I needed to install and use the CommonOpenFileDialog. (NuGet handled the dependencies)

Install-Package Microsoft.WindowsAPICodePack-Shell

For the include line:

using Microsoft.WindowsAPICodePack.Dialogs;

Usage:

CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.InitialDirectory = "C:\\Users";
dialog.IsFolderPicker = true;
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
    MessageBox.Show("You selected: " + dialog.FileName);
}

How do I uniquely identify computers visiting my web site?

Introduction

I don't know if there is or ever will be a way to uniquely identify machines using a browser alone. The main reasons are:

  • You will need to save data on the users computer. This data can be deleted by the user any time. Unless you have a way to recreate this data which is unique for each and every machine then your stuck.
  • Validation. You need to guard against spoofing, session hijacking, etc.

Even if there are ways to track a computer without using cookies there will always be a way to bypass it and software that will do this automatically. If you really need to track something based on a computer you will have to write a native application (Apple Store / Android Store / Windows Program / etc).

I might not be able to give you an answer to the question you asked but I can show you how to implement session tracking. With session tracking you try to track the browsing session instead of the computer visiting your site. By tracking the session, your database schema will look like this:

sesssion:
  sessionID: string
  // Global session data goes here

  computers: [{
     BrowserID: string
     ComputerID: string
     FingerprintID: string
     userID: string
     authToken: string
     ipAddresses: ["203.525....", "203.525...", ...]
     // Computer session data goes here
  }, ...]

Advantages of session based tracking:

  1. For logged in users, you can always generate the same session id from the users username / password / email.
  2. You can still track guest users using sessionID.
  3. Even if several people use the same computer (ie cybercafe) you can track them separately if they log in.

Disadvantages of session based tracking:

  1. Sessions are browser based and not computer based. If a user uses 2 different browsers it will result in 2 different sessions. If this is a problem you can stop reading here.
  2. Sessions expire if user is not logged in. If a user is not logged in, then they will use a guest session which will be invalidated if user deletes cookies and browser cache.

Implementation

There are many ways of implementing this. I don't think I can cover them all I'll just list my favorite which would make this an opinionated answer. Bear that in mind.

Basics

I will track the session by using what is known as a forever cookie. This is data which will automagically recreate itself even if the user deletes his cookies or updates his browser. It will not however survive the user deleting both their cookies and their browsing cache.

To implement this I will use the browsers caching mechanism (RFC), WebStorage API (MDN) and browser cookies (RFC, Google Analytics).

Legal

In order to utilize tracking ids you need to add them to both your privacy policy and your terms of use preferably under the sub-heading Tracking. We will use the following keys on both document.cookie and window.localStorage:

  • _ga: Google Analytics data
  • __utma: Google Analytics tracking cookie
  • sid: SessionID

Make sure you include links to your Privacy policy and terms of use on all pages that use tracking.

Where do I store my session data?

You can either store your session data in your website database or on the users computer. Since I normally work on smaller sites (let than 10 thousand continuous connections) that use 3rd party applications (Google Analytics / Clicky / etc) it's best for me to store data on clients computer. This has the following advantages:

  1. No database lookup / overhead / load / latency / space / etc.
  2. User can delete their data whenever they want without the need to write me annoying emails.

and disadvantages:

  1. Data has to be encrypted / decrypted and signed / verified which creates cpu overhead on client (not so bad) and server (bah!).
  2. Data is deleted when user deletes their cookies and cache. (this is what I want really)
  3. Data is unavailable for analytics when users go off-line. (analytics for currently browsing users only)

UUIDS

  • BrowserID: Unique id generated from the browsers user agent string. Browser|BrowserVersion|OS|OSVersion|Processor|MozzilaMajorVersion|GeckoMajorVersion
  • ComputerID: Generated from users IP Address and HTTPS session key. getISP(requestIP)|getHTTPSClientKey()
  • FingerPrintID: JavaScript based fingerprinting based on a modified fingerprint.js. FingerPrint.get()
  • SessionID: Random key generated when user 1st visits site. BrowserID|ComputerID|randombytes(256)
  • GoogleID: Generated from __utma cookie. getCookie(__utma).uniqueid

Mechanism

The other day I was watching the wendy williams show with my girlfriend and was completely horrified when the host advised her viewers to delete their browser history at least once a month. Deleting browser history normally has the following effects:

  1. Deletes history of visited websites.
  2. Deletes cookies and window.localStorage (aww man).

Most modern browsers make this option readily available but fear not friends. For there is a solution. The browser has a caching mechanism to store scripts / images and other things. Usually even if we delete our history, this browser cache still remains. All we need is a way to store our data here. There are 2 methods of doing this. The better one is to use a SVG image and store our data inside its tags. This way data can still be extracted even if JavaScript is disabled using flash. However since that is a bit complicated I will demonstrate the other approach which uses JSONP (Wikipedia)

example.com/assets/js/tracking.js (actually tracking.php)

var now = new Date();
var window.__sid = "SessionID"; // Server generated

setCookie("sid", window.__sid, now.setFullYear(now.getFullYear() + 1, now.getMonth(), now.getDate() - 1));

if( "localStorage" in window ) {
  window.localStorage.setItem("sid", window.__sid);
}

Now we can get our session key any time:

window.__sid || window.localStorage.getItem("sid") || getCookie("sid") || ""

How do I make tracking.js stick in browser?

We can achieve this using Cache-Control, Last-Modified and ETag HTTP headers. We can use the SessionID as value for etag header:

setHeaders({
  "ETag": SessionID,
  "Last-Modified": new Date(0).toUTCString(),
  "Cache-Control": "private, max-age=31536000, s-max-age=31536000, must-revalidate"
})

Last-Modified header tells the browser that this file is basically never modified. Cache-Control tells proxies and gateways not to cache the document but tells the browser to cache it for 1 year.

The next time the browser requests the document, it will send If-Modified-Since and If-None-Match headers. We can use these to return a 304 Not Modified response.

example.com/assets/js/tracking.php

$sid = getHeader("If-None-Match") ?: getHeader("if-none-match") ?: getHeader("IF-NONE-MATCH") ?: ""; 
$ifModifiedSince = hasHeader("If-Modified-Since") ?: hasHeader("if-modified-since") ?: hasHeader("IF-MODIFIED-SINCE");

if( validateSession($sid) ) {
  if( sessionExists($sid) ) {
    continueSession($sid);
    send304();
  } else {
    startSession($sid);
    send304();
  }
} else if( $ifModifiedSince ) {
  send304();
} else {
  startSession();
  send200();
}

Now every time the browser requests tracking.js our server will respond with a 304 Not Modified result and force an execute of the local copy of tracking.js.

I still don't understand. Explain it to me

Lets suppose the user clears their browsing history and refreshes the page. The only thing left on the users computer is a copy of tracking.js in browser cache. When the browser requests tracking.js it recieves a 304 Not Modified response which causes it to execute the 1st version of tracking.js it recieved. tracking.js executes and restores the SessionID that was deleted.

Validation

Suppose Haxor X steals our customers cookies while they are still logged in. How do we protect them? Cryptography and Browser fingerprinting to the rescue. Remember our original definition for SessionID was:

BrowserID|ComputerID|randomBytes(256)

We can change this to:

Timestamp|BrowserID|ComputerID|encrypt(randomBytes(256), hk)|sign(Timestamp|BrowserID|ComputerID|randomBytes(256), hk)

Where hk = sign(Timestamp|BrowserID|ComputerID, serverKey).

Now we can validate our SessionID using the following algorithm:

if( getTimestamp($sid) is older than 1 year ) return false;
if( getBrowserID($sid) !== createBrowserID($_Request, $_Server) ) return false;
if( getComputerID($sid) !== createComputerID($_Request, $_Server) return false;

$hk = sign(getTimestamp($sid) + getBrowserID($sid) + getComputerID($sid), $SERVER["key"]);

if( !verify(getTimestamp($sid) + getBrowserID($sid) + getComputerID($sid) + decrypt(getRandomBytes($sid), hk), getSignature($sid), $hk) ) return false;

return true; 

Now in order for Haxor's attack to work they must:

  1. Have same ComputerID. That means they have to have the same ISP provider as victim (Tricky). This will give our victim the opportunity to take legal action in their own country. Haxor must also obtain HTTPS session key from victim (Hard).
  2. Have same BrowserID. Anyone can spoof User-Agent string (Annoying).
  3. Be able to create their own fake SessionID (Very Hard). Volume atacks won't work because we use a time-stamp to generate encryption / signing key so basically its like generating a new key for each session. On top of that we encrypt random bytes so a simple dictionary attack is also out of the question.

We can improve validation by forwarding GoogleID and FingerprintID (via ajax or hidden fields) and matching against those.

if( GoogleID != getStoredGoodleID($sid) ) return false;
if( byte_difference(FingerPrintID, getStoredFingerprint($sid) > 10%) return false;

Eclipse Optimize Imports to Include Static Imports

I'm using Eclipse Europa, which also has the Favorite preference section:

Window > Preferences > Java > Editor > Content Assist > Favorites

In mine, I have the following entries (when adding, use "New Type" and omit the .*):

org.hamcrest.Matchers.*
org.hamcrest.CoreMatchers.*
org.junit.*
org.junit.Assert.*
org.junit.Assume.*
org.junit.matchers.JUnitMatchers.*

All but the third of those are static imports. By having those as favorites, if I type "assertT" and hit Ctrl+Space, Eclipse offers up assertThat as a suggestion, and if I pick it, it will add the proper static import to the file.

ASP.NET MVC 3 Razor - Adding class to EditorFor

Using jQuery, you can do it easily:

$("input").addClass("class-name")

Here is your input tag

@Html.EditorFor(model => model.Name)

For DropDownlist you can use this one:

$("select").addClass("class-name")

For Dropdownlist:

@Html.DropDownlistFor(model=>model.Name)

How to turn a String into a JavaScript function call?

While I like the first answer and I hate eval, I'd like to add that there's another way (similar to eval) so if you can go around it and not use it, you better do. But in some cases you may want to call some javascript code before or after some ajax call and if you have this code in a custom attribute instead of ajax you could use this:

    var executeBefore = $(el).attr("data-execute-before-ajax");
    if (executeBefore != "") {
        var fn = new Function(executeBefore);
        fn();
    }

Or eventually store this in a function cache if you may need to call it multiple times.

Again - don't use eval or this method if you have another way to do that.

Index of duplicates items in a python list

a= [2,3,4,5,6,2,3,2,4,2]
search=2
pos=0
positions=[]

while (search in a):
    pos+=a.index(search)
    positions.append(pos)
    a=a[a.index(search)+1:]
    pos+=1

print "search found at:",positions

Git Commit Messages: 50/72 Formatting

Regarding “thought leaders”: Linus emphatically advocates line wrapping for the full commit message:

[…] we use 72-character columns for word-wrapping, except for quoted material that has a specific line format.

The exceptions refers mainly to “non-prose” text, that is, text that was not typed by a human for the commit — for example, compiler error messages.

Get Date in YYYYMMDD format in windows batch file

If, after reading the other questions and viewing the links mentioned in the comment sections, you still can't figure it out, read on.

First of all, where you're going wrong is the offset.

It should look more like this...

set mydate=%date:~10,4%%date:~6,2%/%date:~4,2%
echo %mydate%

If the date was Tue 12/02/2013 then it would display it as 2013/02/12.

To remove the slashes, the code would look more like

set mydate=%date:~10,4%%date:~7,2%%date:~4,2%
echo %mydate%

which would output 20130212

And a hint for doing it in the future, if mydate equals something like %date:~10,4%%date:~7,2% or the like, you probably forgot a tilde (~).

Best way to "negate" an instanceof

If you find it more understandable, you can do something like this with Java 8 :

public static final Predicate<Object> isInstanceOfTheClass = 
    objectToTest -> objectToTest instanceof TheClass;

public static final Predicate<Object> isNotInstanceOfTheClass = 
    isInstanceOfTheClass.negate(); // or objectToTest -> !(objectToTest instanceof TheClass)

if (isNotInstanceOfTheClass.test(myObject)) {
    // do something
}

Background color in input and text fields

input[type="text"], textarea {

  background-color : #d1d1d1; 

}

Hope that helps :)

Edit: working example, http://jsfiddle.net/C5WxK/

Should Jquery code go in header or footer?

Although almost all web sites still place Jquery and other javascript on header :D , even check stackoverflow.com .

I also suggest you to put on before end tag of body. You can check loading time after placing on either places. Script tag will pause your webpage to load further.

and after placing javascript on footer, you may get unusual looks of your webpage until it loads javascript, so place css on your header section.

How to auto-scroll to end of div when data is added?

If you don't know when data will be added to #data, you could set an interval to update the element's scrollTop to its scrollHeight every couple of seconds. If you are controlling when data is added, just call the internal of the following function after the data has been added.

window.setInterval(function() {
  var elem = document.getElementById('data');
  elem.scrollTop = elem.scrollHeight;
}, 5000);

Firebase TIMESTAMP to date and Time

Iterating through this is the precise code that worked for me.

querySnapshot.docs.forEach((e) => {
   var readableDate = e.data().date.toDate();
   console.log(readableDate);
}

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

As others have answered, the "standards" all leave most of the details as "implementation defined" and only state that type "char" is at leat "char_bis" wide, and that "char <= short <= int <= long <= long long" (float and double are pretty much consistent with the IEEE floating point standards, and long double is typically same as double--but may be larger on more current implementations).

Part of the reasons for not having very specific and exact values is because languages like C/C++ were designed to be portable to a large number of hardware platforms--Including computer systems in which the "char" word-size may be 4-bits or 7-bits, or even some value other than the "8-/16-/32-/64-bit" computers the average home computer user is exposed to. (Word-size here meaning how many bits wide the system normally operates on--Again, it's not always 8-bits as home computer users may expect.)

If you really need a object (in the sense of a series of bits representing an integral value) of a specific number of bits, most compilers have some method of specifying that; But it's generally not portable, even between compilers made by the ame company but for different platforms. Some standards and practices (especially limits.h and the like) are common enough that most compilers will have support for determining at the best-fit type for a specific range of values, but not the number of bits used. (That is, if you know you need to hold values between 0 and 127, you can determine that your compiler supports an "int8" type of 8-bits which will be large enought to hold the full range desired, but not something like an "int7" type which would be an exact match for 7-bits.)

Note: Many Un*x source packages used "./configure" script which will probe the compiler/system's capabilities and output a suitable Makefile and config.h. You might examine some of these scripts to see how they work and how they probe the comiler/system capabilities, and follow their lead.

case statement in where clause - SQL Server

A CASE statement is an expression, just like a boolean comparison. That means the 'AND' needs to go before the 'CASE' statement, not within it.:

Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date)

AND -- Added the "AND" here

CASE WHEN @day = 'Monday' THEN (Monday = 1)   -- Removed "AND" 
    WHEN @day = 'Tuesday' THEN (Tuesday = 1)  -- Removed "AND" 
    ELSE AND (Wednesday = 1) 
END

Excel - Combine multiple columns into one column

I created an example spreadsheet here of how to do this with simple Excel formulae, and without use of macros (you will need to make your own adjustments for getting rid of the first row, but this should be easy once you figure out how my example spreadsheet works):

https://docs.google.com/a/umich.edu/spreadsheet/ccc?key=0AuSyDFZlcRtHdGJOSnFwREotRzFfM28tWElpZ1FaR2c#gid=0

MySQL - UPDATE query based on SELECT Query

For same table,

UPDATE PHA_BILL_SEGMENT AS PHA,
     (SELECT BILL_ID, COUNT(REGISTRATION_NUMBER) AS REG 
       FROM PHA_BILL_SEGMENT
        GROUP BY REGISTRATION_NUMBER, BILL_DATE, BILL_AMOUNT
        HAVING REG > 1) T
    SET PHA.BILL_DATE = PHA.BILL_DATE + 2
 WHERE PHA.BILL_ID = T.BILL_ID;

Why can templates only be implemented in the header file?

Plenty correct answers here, but I wanted to add this (for completeness):

If you, at the bottom of the implementation cpp file, do explicit instantiation of all the types the template will be used with, the linker will be able to find them as usual.

Edit: Adding example of explicit template instantiation. Used after the template has been defined, and all member functions has been defined.

template class vector<int>;

This will instantiate (and thus make available to the linker) the class and all its member functions (only). Similar syntax works for template functions, so if you have non-member operator overloads you may need to do the same for those.

The above example is fairly useless since vector is fully defined in headers, except when a common include file (precompiled header?) uses extern template class vector<int> so as to keep it from instantiating it in all the other (1000?) files that use vector.

Unused arguments in R

I had the same problem as you. I had a long list of arguments, most of which were irrelevant. I didn't want to hard code them in. This is what I came up with

library(magrittr)
do_func_ignore_things <- function(data, what){
    acceptable_args <- data[names(data) %in% (formals(what) %>% names)]
    do.call(what, acceptable_args %>% as.list)
}

do_func_ignore_things(c(n = 3, hello = 12, mean = -10), "rnorm")
# -9.230675 -10.503509 -10.927077

Determine .NET Framework version for dll

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

Can you see this screenshot? im not:(

Numpy array dimensions

rows = a.shape[0] # 2 
cols = a.shape[1] # 2
a.shape #(2,2)
a.size # rows * cols = 4

Using `date` command to get previous, current and next month

The problem is that date takes your request quite literally and tries to use a date of 31st September (being 31st October minus one month) and then because that doesn't exist it moves to the next day which does. The date documentation (from info date) has the following advice:

The fuzz in units can cause problems with relative items. For example, `2003-07-31 -1 month' might evaluate to 2003-07-01, because 2003-06-31 is an invalid date. To determine the previous month more reliably, you can ask for the month before the 15th of the current month. For example:

 $ date -R
 Thu, 31 Jul 2003 13:02:39 -0700
 $ date --date='-1 month' +'Last month was %B?'
 Last month was July?
 $ date --date="$(date +%Y-%m-15) -1 month" +'Last month was %B!'
 Last month was June!

How to parseInt in Angular.js

This are to way to bind add too numbers

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>_x000D_
<script>_x000D_
_x000D_
var app = angular.module("myApp", []);_x000D_
_x000D_
app.controller("myCtrl", function($scope) {_x000D_
$scope.total = function() { _x000D_
  return parseInt($scope.num1) + parseInt($scope.num2) _x000D_
}_x000D_
})_x000D_
</script>_x000D_
<body ng-app='myApp' ng-controller='myCtrl'>_x000D_
_x000D_
<input type="number" ng-model="num1">_x000D_
<input type="number" ng-model="num2">_x000D_
Total:{{num1+num2}}_x000D_
_x000D_
Total: {{total() }}_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How can I generate an HTML report for Junit results?

I found xunit-viewer, which has deprecated junit-viewer mentioned by @daniel-kristof-kiss.

It is very simple, automatically recursively collects all relevant files in ANT Junit XML format and creates a single html-file with filtering and other sweet features.

I use it to upload test results from Travis builds as Travis has no other support for collecting standard formatted test results output.

Pass mouse events through absolutely-positioned element

The reason you are not receiving the event is because the absolutely positioned element is not a child of the element you are wanting to "click" (blue div). The cleanest way I can think of is to put the absolute element as a child of the one you want clicked, but I'm assuming you can't do that or you wouldn't have posted this question here :)

Another option would be to register a click event handler for the absolute element and call the click handler for the blue div, causing them both to flash.

Due to the way events bubble up through the DOM I'm not sure there is a simpler answer for you, but I'm very curious if anyone else has any tricks I don't know about!

Get max and min value from array in JavaScript

arr = [9,4,2,93,6,2,4,61,1];
ArrMax = Math.max.apply(Math, arr);

Android Studio Google JAR file causing GC overhead limit exceeded error

In my case, to increase the heap-size looks like this:

Using Android Studio 1.1.0

android {
    dexOptions {
        incremental true
        javaMaxHeapSize "2048M"
    }
}

Put the above code in your Build.gradle file.

How to install mscomct2.ocx file from .cab file (Excel User Form and VBA)

You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.

  1. Just extract the .ocx file from the .cab file (it is similar to a zip)
  2. Copy to the system folder (c:\windows\sysWOW64 for 64 bit systems and c:\windows\system32 for 32 bit)
  3. Use regsvr32 through the command prompt to register the file (e.g. "regsvr32 c:\windows\sysWOW64\mscomct2.ocx")

References

Proper usage of .net MVC Html.CheckBoxFor

None of the above answers worked for me when binding back on POST, until I added the following in CSHTML

<div class="checkbox c-checkbox">
    <label>
        <input type="checkbox" id="xPrinting" name="xPrinting" value="true"  @Html.Raw( Model.xPrinting ? "checked" : "")>
        <span class=""></span>Printing
    </label>
</div>


// POST: Index

[HttpPost]
public ActionResult Index([Bind(Include = "dateInHands,dateFrom,dateTo,pgStatus,gpStatus,vwStatus,freeSearch,xPrinting,xEmbroidery,xPersonalization,sortOrder,radioOperator")] ProductionDashboardViewModel model)

Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C

You can do it with drop_duplicates as you wanted

# initialisation
d = pd.DataFrame({'A' : [1,1,2,3,3], 'B' : [2,2,7,4,4],  'C' : [1,4,1,0,8]})

d = d.sort_values("C", ascending=False)
d = d.drop_duplicates(["A","B"])

If it's important to get the same order

d = d.sort_index()

How can I set the PATH variable for javac so I can manually compile my .java works?

Follow the steps given here

http://www.javaandme.com/

after setting variable, just navigate to your java file directory in your cmd and type javac "xyx.java"

or if you don't navigate to the directory, then simply specify the full path of java file

javac "/xyz.java"

pySerial write() won't take my string

You have found the root cause. Alternately do like this:

ser.write(bytes(b'your_commands'))

Passing Objects By Reference or Value in C#

Lots of good answers had been added. I still want to contribute, might be it will clarify slightly more.

When you pass an instance as an argument to the method it passes the copy of the instance. Now, if the instance you pass is a value type(resides in the stack) you pass the copy of that value, so if you modify it, it won't be reflected in the caller. If the instance is a reference type you pass the copy of the reference(again resides in the stack) to the object. So you got two references to the same object. Both of them can modify the object. But if within the method body, you instantiate new object your copy of the reference will no longer refer to the original object, it will refer to the new object you just created. So you will end up having 2 references and 2 objects.

What is the difference between application server and web server?

IMO, it's mostly about separating concerns.

From a purely technical point of view, you can do everything (web content + business logic) in a single web server. If you'd do that, then the information would be embedded inside requested the HTML content. What would be the impact?

For example, imagine you have 2 different apps which renders entirely different HTML content on the browser. If you would separate the business logic into an app-server than you could provide different web-servers looking up the same data in the app-server via scripts. However, If you wouldn't separate the logic and keep it in the web-server, whenever you change your business model, you would end up changing it in every single web-server you have which would take more time, be less reliable and error-prone.

How to list all tags along with the full message in git?

git tag -n99

Short and sweet. This will list up to 99 lines from each tag annotation/commit message. Here is a link to the official documentation for git tag.

I now think the limitation of only showing up to 99 lines per tag is actually a good thing as most of the time, if there were really more than 99 lines for a single tag, you wouldn't really want to see all the rest of the lines would you? If you did want to see more than 99 lines per tag, you could always increase this to a larger number.

I mean, I guess there could be a specific situation or reason to want to see massive tag messages, but at what point do you not want to see the whole message? When it has more than 999 lines? 10,000? 1,000,000? My point is, it typically makes sense to have a cap on how many lines you would see, and this number allows you to set that.

Since I am making an argument for what you generally want to see when looking at your tags, it probably makes sense to set something like this as an alias (from Iulian Onofrei's comment below):

git config --global alias.tags 'tag -n99'

I mean, you don't really want to have to type in git tag -n99 every time you just want to see your tags do you? Once that alias is configured, whenever you want to see your tags, you would just type git tags into your terminal. Personally, I prefer to take things a step further than this and create even more abbreviated bash aliases for all my commonly used commands. For that purpose, you could add something like this to your .bashrc file (works on Linux and similar environments):

alias gtag='git tag -n99'

Then whenever you want to see your tags, you just type gtag. Another advantage of going down the alias path (either git aliases or bash aliases or whatever) is you now have a spot already in place where you can add further customizations to how you personally, generally want to have your tags shown to you (like sorting them in certain ways as in my comment below, etc). Once you get over the hurtle of creating your first alias, you will now realize how easy it is to create more of them for other things you like to work in a customized way, like git log, but let's save that one for a different question/answer.

self.tableView.reloadData() not working in Swift

You must reload your TableView in main thread only. Otherwise your app will be crashed or will be updated after some time. For every UI update it is recommended to use main thread.

//To update UI only this below code is enough
//If you want to do changes in UI use this
DispatchQueue.main.async(execute: {
    //Update UI
    self.tableView.reloadData()//Your tableView here
})

//Perform some task and update UI immediately.
DispatchQueue.global(qos: .userInitiated).async {  
    // Call your function here
    DispatchQueue.main.async {  
        // Update UI
        self.tableView.reloadData()  
    }
}

//To call or execute function after some time and update UI
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
    //Here call your function
    //If you want to do changes in UI use this
    DispatchQueue.main.async(execute: {
        //Update UI
        self.tableView.reloadData()
    })
}

PostgreSQL unnest() with element number

Postgres 9.4 or later

Use WITH ORDINALITY for set-returning functions:

When a function in the FROM clause is suffixed by WITH ORDINALITY, a bigint column is appended to the output which starts from 1 and increments by 1 for each row of the function's output. This is most useful in the case of set returning functions such as unnest().

In combination with the LATERAL feature in pg 9.3+, and according to this thread on pgsql-hackers, the above query can now be written as:

SELECT t.id, a.elem, a.nr
FROM   tbl AS t
LEFT   JOIN LATERAL unnest(string_to_array(t.elements, ','))
                    WITH ORDINALITY AS a(elem, nr) ON TRUE;

LEFT JOIN ... ON TRUE preserves all rows in the left table, even if the table expression to the right returns no rows. If that's of no concern you can use this otherwise equivalent, less verbose form with an implicit CROSS JOIN LATERAL:

SELECT t.id, a.elem, a.nr
FROM   tbl t, unnest(string_to_array(t.elements, ',')) WITH ORDINALITY a(elem, nr);

Or simpler if based off an actual array (arr being an array column):

SELECT t.id, a.elem, a.nr
FROM   tbl t, unnest(t.arr) WITH ORDINALITY a(elem, nr);

Or even, with minimal syntax:

SELECT id, a, ordinality
FROM   tbl, unnest(arr) WITH ORDINALITY a;

a is automatically table and column alias. The default name of the added ordinality column is ordinality. But it's better (safer, cleaner) to add explicit column aliases and table-qualify columns.

Postgres 8.4 - 9.3

With row_number() OVER (PARTITION BY id ORDER BY elem) you get numbers according to the sort order, not the ordinal number of the original ordinal position in the string.

You can simply omit ORDER BY:

SELECT *, row_number() OVER (PARTITION by id) AS nr
FROM  (SELECT id, regexp_split_to_table(elements, ',') AS elem FROM tbl) t;

While this normally works and I have never seen it fail in simple queries, PostgreSQL asserts nothing concerning the order of rows without ORDER BY. It happens to work due to an implementation detail.

To guarantee ordinal numbers of elements in the blank-separated string:

SELECT id, arr[nr] AS elem, nr
FROM  (
   SELECT *, generate_subscripts(arr, 1) AS nr
   FROM  (SELECT id, string_to_array(elements, ' ') AS arr FROM tbl) t
   ) sub;

Or simpler if based off an actual array:

SELECT id, arr[nr] AS elem, nr
FROM  (SELECT *, generate_subscripts(arr, 1) AS nr FROM tbl) t;

Related answer on dba.SE:

Postgres 8.1 - 8.4

None of these features are available, yet: RETURNS TABLE, generate_subscripts(), unnest(), array_length(). But this works:

CREATE FUNCTION f_unnest_ord(anyarray, OUT val anyelement, OUT ordinality integer)
  RETURNS SETOF record
  LANGUAGE sql IMMUTABLE AS
'SELECT $1[i], i - array_lower($1,1) + 1
 FROM   generate_series(array_lower($1,1), array_upper($1,1)) i';

Note in particular, that the array index can differ from ordinal positions of elements. Consider this demo with an extended function:

CREATE FUNCTION f_unnest_ord_idx(anyarray, OUT val anyelement, OUT ordinality int, OUT idx int)
  RETURNS SETOF record
  LANGUAGE sql IMMUTABLE AS
'SELECT $1[i], i - array_lower($1,1) + 1, i
 FROM   generate_series(array_lower($1,1), array_upper($1,1)) i';

SELECT id, arr, (rec).*
FROM  (
   SELECT *, f_unnest_ord_idx(arr) AS rec
   FROM  (VALUES (1, '{a,b,c}'::text[])  --  short for: '[1:3]={a,b,c}'
               , (2, '[5:7]={a,b,c}')
               , (3, '[-9:-7]={a,b,c}')
      ) t(id, arr)
   ) sub;

 id |       arr       | val | ordinality | idx
----+-----------------+-----+------------+-----
  1 | {a,b,c}         | a   |          1 |   1
  1 | {a,b,c}         | b   |          2 |   2
  1 | {a,b,c}         | c   |          3 |   3
  2 | [5:7]={a,b,c}   | a   |          1 |   5
  2 | [5:7]={a,b,c}   | b   |          2 |   6
  2 | [5:7]={a,b,c}   | c   |          3 |   7
  3 | [-9:-7]={a,b,c} | a   |          1 |  -9
  3 | [-9:-7]={a,b,c} | b   |          2 |  -8
  3 | [-9:-7]={a,b,c} | c   |          3 |  -7

Compare:

Unix command to check the filesize

stat -c %s file.txt

This command will give you the size of the file in bytes. You can learn more about why you should avoid parsing output of ls command over here: http://mywiki.wooledge.org/ParsingLs

Constantly print Subprocess output while process is running

There is actually a really simple way to do this when you just want to print the output:

import subprocess
import sys

def execute(command):
    subprocess.check_call(command, stdout=sys.stdout, stderr=subprocess.STDOUT)

Here we're simply pointing the subprocess to our own stdout, and using existing succeed or exception api.

What is middleware exactly?

Simply put Middleware is a software component which provides services to integrate disparate systems together.

In an complex enterprise environment, there are a number of challenges when you need to integrate two or more enterprise systems together to talk to each other. Normally these systems do not understand each others language as they are developed on different platforms using different languages (like C++, Java, Cobol, etc.).

So here comes middleware software in picture which provides services like

  • transformation of messages formats from one app to other,
  • routing and enriching messages besides taking care of security,
  • encryption,
  • validation and
  • applying different business rules to these messages.

A typical example of middleware is an ESB products like IBM message broker (WMB/IIB), WESB, Datapower XI50, Oracle Fusion, Mule and many others.

Therefore, middleware sits mostly in between the service consuming apps and services provider apps and help these apps to talk to each other.

How to reference image resources in XAML?

One of the benefit of using the resource file is accessing the resources by names, so the image can change, the image name can change, as long as the resource is kept up to date correct image will show up.

Here is a cleaner approach to accomplish this: Assuming Resources.resx is in 'UI.Images' namespace, add the namespace reference in your xaml like this:

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:UI="clr-namespace:UI.Images" 

Set your Image source like this:

<Image Source={Binding {x:Static UI:Resources.Search}} /> where 'Search' is name of the resource.

Getting all request parameters in Symfony 2

Since you are in a controller, the action method is given a Request parameter.

You can access all POST data with $request->request->all();. This returns a key-value pair array.

When using GET requests you access data using $request->query->all();

Just disable scroll not hide it?

Another solution to get rid of content jump on fixed modal, when removing body scroll is to normalize page width:

body {width: 100vw; overflow-x: hidden;}

Then you can play with fixed position or overflow:hidden for body when the modal is open. But it will hide horizontal scrollbars - usually they're not needed on responsive website.

C++ Convert string (or char*) to wstring (or wchar_t*)

std::string -> wchar_t[] with safe mbstowcs_s function:

auto ws = std::make_unique<wchar_t[]>(s.size() + 1);
mbstowcs_s(nullptr, ws.get(), s.size() + 1, s.c_str(), s.size());

This is from my sample code

Swift add icon/image in UITextField

I Just want to add some more thing here:

If you want to add the image on UITextField on left side use leftView property of UITextField

NOTE: Don't forget to set leftViewMode to UITextFieldViewMode.Always and for right rightViewMode to UITextFieldViewMode.Always anddefault is UITextFieldViewModeNever

for e.g

For adding an image on left side

textField.leftViewMode = UITextFieldViewMode.Always
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
let image = UIImage(named: imageName)
imageView.image = image
textField.leftView = imageView

For adding an image on right side

textField.rightViewMode = UITextFieldViewMode.Always
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
let image = UIImage(named: imageName)
imageView.image = image
textField.rightView = imageView

NOTE: some things you need to take care while adding an image on UITextField either on the left side or right side.

  • Don't forget to give a frame of ImageView which are you going to add on UITextField

    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))

  • if your image background is white then image won't visible on UITextField

  • if you want to add an image to the specific position you need to add ImageView as the subview of UITextField.

Update For Swift 3.0

@Mark Moeykens Beautifully expended it and make it @IBDesignable.

I modified and added some more features (add Bottom Line and padding for right image) in this.

NOTE if you want to add an image on the right side you can select the Force Right-to-Left option in semantic in interface builder(But for right image padding won't work until you will override rightViewRect method ).

enter image description here

I have modified this and can download the source from here ImageTextField

enter image description here

How to enable CORS in ASP.net Core WebAPI

I got MindingData's answer above to work, but I had to use Microsoft.AspNet.Cors instead of Microsoft.AspNetCore.Cors. I am using .NetCore Web Application API project in Visual Studio 2019

How to check Oracle database for long running queries

v$session_longops

If you look for sofar != totalwork you'll see ones that haven't completed, but the entries aren't removed when the operation completes so you can see a lot of history there too.

c# razor url parameter from view

You can use the following:

Request.Params["paramName"]

See also: When do Request.Params and Request.Form differ?

Dump a list in a pickle file and retrieve it back later

Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.

So, first build a list, then use pickle.dump to send it to a file...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>> 
>>> import pickle
>>> 
>>> with open('parrot.pkl', 'wb') as f:
...   pickle.dump(mylist, f)
... 
>>> 

Then quit and come back later… and open with pickle.load...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
...   mynewlist = pickle.load(f)
... 
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>

how to iterate through dictionary in a dictionary in django template?

This answer didn't work for me, but I found the answer myself. No one, however, has posted my question. I'm too lazy to ask it and then answer it, so will just put it here.

This is for the following query:

data = Leaderboard.objects.filter(id=custom_user.id).values(
    'value1',
    'value2',
    'value3')

In template:

{% for dictionary in data %}
  {% for key, value in dictionary.items %}
    <p>{{ key }} : {{ value }}</p>
  {% endfor %}
{% endfor %}

How to represent e^(-t^2) in MATLAB?

If t is a matrix, you need to use the element-wise multiplication or exponentiation. Note the dot.

x = exp( -t.^2 )

or

x = exp( -t.*t )

How to speed up insertion performance in PostgreSQL

For optimal Insertion performance disable the index if that's an option for you. Other than that, better hardware (disk, memory) is also helpful

'pip' is not recognized as an internal or external command

Try going to Windows PowerShell or cmd prompt and typing:

python -m pip install openpyxl

What is the difference between a mutable and immutable string in C#?

Mutable and immutable are English words meaning "can change" and "cannot change" respectively. The meaning of the words is the same in the IT context; i.e.

  • a mutable string can be changed, and
  • an immutable string cannot be changed.

The meanings of these words are the same in C# / .NET as in other programming languages / environments, though (obviously) the names of the types may differ, as may other details.


For the record:

  • String is the standard C# / .Net immutable string type
  • StringBuilder is the standard C# / .Net mutable string type

To "effect a change" on a string represented as a C# String, you actually create a new String object. The original String is not changed ... because it is unchangeable.

In most cases it is better to use String because it is easier reason about them; e.g. you don't need to consider the possibility that some other thread might "change my string".

However, when you need to construct or modify a string using a sequence of operations, it may be more efficient to use a StringBuilder. An example is when you are concatenating many string fragments to form a large string:

  • If you do this as a sequence of String concatenations, you copy O(N^2) characters, where N is the number of component strings.
  • If use a StringBuilder you only copy O(N) characters.

And finally, for those people who assert that a StringBuilder is not a string because it is not immutable, the Microsoft documentation describes StringBuilder thus:

"Represents a mutable string of characters. This class cannot be inherited."

Python convert tuple to string

Use str.join:

>>> tup = ('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')
>>> ''.join(tup)
'abcdgxre'
>>>
>>> help(str.join)
Help on method_descriptor:

join(...)
    S.join(iterable) -> str

    Return a string which is the concatenation of the strings in the
    iterable.  The separator between elements is S.

>>>

How do you check if a selector matches something in jQuery?

Alternatively:

if( jQuery('#elem').get(0) ) {}

create unique id with javascript

Like others said you can use a running index, or if you don't like the idea of using a variable just pull the id of the last city in the list and add 1 to its id.

How to create and download a csv file from php script?

Try... csv download.

<?php 
mysql_connect('hostname', 'username', 'password');
mysql_select_db('dbname');
$qry = mysql_query("SELECT * FROM tablename");
$data = "";
while($row = mysql_fetch_array($qry)) {
  $data .= $row['field1'].",".$row['field2'].",".$row['field3'].",".$row['field4']."\n";
}

header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="filename.csv"');
echo $data; exit();
?>

Iterate through dictionary values?

You can just look for the value that corresponds with the key and then check if the input is equal to the key.

for key in PIX0:
    NUM = input("Which standard has a resolution of %s " % PIX0[key])
    if NUM == key:

Also, you will have to change the last line to fit in, so it will print the key instead of the value if you get the wrong answer.

print("I'm sorry but thats wrong. The correct answer was: %s." % key )

Also, I would recommend using str.format for string formatting instead of the % syntax.

Your full code should look like this (after adding in string formatting)

PIX0 = {"QVGA":"320x240", "VGA":"640x480", "SVGA":"800x600"}

for key in PIX0:
    NUM = input("Which standard has a resolution of {}".format(PIX0[key]))
    if NUM == key:
        print ("Nice Job!")
        count = count + 1
    else:
        print("I'm sorry but that's wrong. The correct answer was: {}.".format(key))

Difference between using Throwable and Exception in a try catch

I have seen people use Throwable to catch some errors that might happen due to infra failure/ non availability.

How do I check if a variable is of a certain type (compare two types) in C?

For that purpose I have written a simple C program for that... It is in github...GitHub Link

Here how it works... First convert your double into a char string named s..

char s[50];
sprintf(s,"%.2f", yo);

Then use my dtype function to determine the type... My function will return a single character...You can use it like this...

char type=dtype(s);
//Return types are :
//i for integer
//f for float or decimals
//c for character...

Then you can use comparison to check it... That's it...

Forcing anti-aliasing using css: Is this a myth?

I found a really awkward solution using the zoom and filter ms-only properties Example (try with no aa, standard and cleartype): http://nadycoon.hu/special/archive/internet-explorer-force-antialias.html

How it works:

-zoom up text with zoom:x, x>1

-apply some blur(s) (or any other filter)

-zoom down with zoom:1/x

It's a bit slow, and very! memory-hungry method, and on non-white backgrounds it has some slight dark halo.

CSS:

.insane-aa-4b                  { zoom:0.25; }
.insane-aa-4b .insane-aa-inner { zoom:4; }
.insane-aa-4b .insane-aa-blur  { zoom:1;
  filter:progid:DXImageTransform.Microsoft.Blur(pixelRadius=2);
}

HTML:

<div class="insane-aa-4b">
<div class="insane-aa-blur">
<div class="insane-aa-inner">
  <div style="font-size:12px;">Lorem Ipsum</div>
</div></div></div>

You can use this short jQuery to force anti-aliasing, just add the ieaa class to anything:

$(function(){ $('.ieaa').wrap(
'<div style="zoom:0.25;"><div style="zoom:1;filter:progid:DXImageTransform.Microsoft.Blur(pixelRadius=2);"><div style="zoom:4;"><'+'/div><'+'/div><'+'/div>'
); });

Byte[] to InputStream or OutputStream

we can convert byte[] array into input stream by using ByteArrayInputStream

String str = "Welcome to awesome Java World";
    byte[] content = str.getBytes();
    int size = content.length;
    InputStream is = null;
    byte[] b = new byte[size];
    is = new ByteArrayInputStream(content);

For full example please check here http://www.onlinecodegeek.com/2015/09/how-to-convert-byte-into-inputstream.html