Programs & Examples On #Mediator

The mediator pattern defines an object that encapsulates how a set of objects interact. It is one of the Gang of Four's behavioral design patterns.

UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only

The answer of Shyam was right. I already faced with this issue before. It's not a problem, it's a SPRING feature. "Transaction rolled back because it has been marked as rollback-only" is acceptable.

Conclusion

  • USE REQUIRES_NEW if you want to commit what did you do before exception (Local commit)
  • USE REQUIRED if you want to commit only when all processes are done (Global commit) And you just need to ignore "Transaction rolled back because it has been marked as rollback-only" exception. But you need to try-catch out side the caller processNextRegistrationMessage() to have a meaning log.

Let's me explain more detail:

Question: How many Transaction we have? Answer: Only one

Because you config the PROPAGATION is PROPAGATION_REQUIRED so that the @Transaction persist() is using the same transaction with the caller-processNextRegistrationMessage(). Actually, when we get an exception, the Spring will set rollBackOnly for the TransactionManager so the Spring will rollback just only one Transaction.

Question: But we have a try-catch outside (), why does it happen this exception? Answer Because of unique Transaction

  1. When persist() method has an exception
  2. Go to the catch outside

    Spring will set the rollBackOnly to true -> it determine we must 
    rollback the caller (processNextRegistrationMessage) also.
    
  3. The persist() will rollback itself first.

  4. Throw an UnexpectedRollbackException to inform that, we need to rollback the caller also.
  5. The try-catch in run() will catch UnexpectedRollbackException and print the stack trace

Question: Why we change PROPAGATION to REQUIRES_NEW, it works?

Answer: Because now the processNextRegistrationMessage() and persist() are in the different transaction so that they only rollback their transaction.

Thanks

java.net.MalformedURLException: no protocol

Try instead of db.parse(xml):

Document doc = db.parse(new InputSource(new StringReader(**xml**)));

Column name or number of supplied values does not match table definition

Beware of triggers. Maybe the issue is with some operation in the trigger for inserted rows.

I just discovered why all ASP.Net websites are slow, and I am trying to work out what to do about it

For ASPNET MVC, we did the following:

  1. By default, set SessionStateBehavior.ReadOnly on all controller's action by overriding DefaultControllerFactory
  2. On controller actions that need writing to session state, mark with attribute to set it to SessionStateBehavior.Required

Create custom ControllerFactory and override GetControllerSessionBehavior.

    protected override SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, Type controllerType)
    {
        var DefaultSessionStateBehaviour = SessionStateBehaviour.ReadOnly;

        if (controllerType == null)
            return DefaultSessionStateBehaviour;

        var isRequireSessionWrite =
            controllerType.GetCustomAttributes<AcquireSessionLock>(inherit: true).FirstOrDefault() != null;

        if (isRequireSessionWrite)
            return SessionStateBehavior.Required;

        var actionName = requestContext.RouteData.Values["action"].ToString();
        MethodInfo actionMethodInfo;

        try
        {
            actionMethodInfo = controllerType.GetMethod(actionName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
        }
        catch (AmbiguousMatchException)
        {
            var httpRequestTypeAttr = GetHttpRequestTypeAttr(requestContext.HttpContext.Request.HttpMethod);

            actionMethodInfo =
                controllerType.GetMethods().FirstOrDefault(
                    mi => mi.Name.Equals(actionName, StringComparison.CurrentCultureIgnoreCase) && mi.GetCustomAttributes(httpRequestTypeAttr, false).Length > 0);
        }

        if (actionMethodInfo == null)
            return DefaultSessionStateBehaviour;

        isRequireSessionWrite = actionMethodInfo.GetCustomAttributes<AcquireSessionLock>(inherit: false).FirstOrDefault() != null;

         return isRequireSessionWrite ? SessionStateBehavior.Required : DefaultSessionStateBehaviour;
    }

    private static Type GetHttpRequestTypeAttr(string httpMethod) 
    {
        switch (httpMethod)
        {
            case "GET":
                return typeof(HttpGetAttribute);
            case "POST":
                return typeof(HttpPostAttribute);
            case "PUT":
                return typeof(HttpPutAttribute);
            case "DELETE":
                return typeof(HttpDeleteAttribute);
            case "HEAD":
                return typeof(HttpHeadAttribute);
            case "PATCH":
                return typeof(HttpPatchAttribute);
            case "OPTIONS":
                return typeof(HttpOptionsAttribute);
        }

        throw new NotSupportedException("unable to determine http method");
    }

AcquireSessionLockAttribute

[AttributeUsage(AttributeTargets.Method)]
public sealed class AcquireSessionLock : Attribute
{ }

Hook up the created controller factory in global.asax.cs

ControllerBuilder.Current.SetControllerFactory(typeof(DefaultReadOnlySessionStateControllerFactory));

Now, we can have both read-only and read-write session state in a single Controller.

public class TestController : Controller 
{
    [AcquireSessionLock]
    public ActionResult WriteSession()
    {
        var timeNow = DateTimeOffset.UtcNow.ToString();
        Session["key"] = timeNow;
        return Json(timeNow, JsonRequestBehavior.AllowGet);
    }

    public ActionResult ReadSession()
    {
        var timeNow = Session["key"];
        return Json(timeNow ?? "empty", JsonRequestBehavior.AllowGet);
    }
}

Note: ASPNET session state can still be written to even in readonly mode and will not throw any form of exception (It just doesn't lock to guarantee consistency) so we have to be careful to mark AcquireSessionLock in controller's actions that require writing session state.

Defined Edges With CSS3 Filter Blur

You can also keep the whole video, you do not have to cut something away.
You can overlay inset shadows over the white-blurred edges.

This looks really nice as well :)

Just paste this code to your videos' parent:

.parent {
    -webkit-box-shadow: inset 0 0 200px #000000;
       -moz-box-shadow: inset 0 0 200px #000000;
            box-shadow: inset 0 0 200px #000000;
}

Neither BindingResult nor plain target object for bean name available as request attribute

Just add

model.addAttribute("login", new Login());

to your method ..

it will work..

Better way to check if a Path is a File or a Directory?

How about using these?

File.Exists();
Directory.Exists();

Full Screen DialogFragment in Android

the following solution worked for me other solution gave me some space in the sides i.e not full screen

You need to make changes in onStart and onCreate method

@Override
public void onStart() {
    super.onStart();
    Dialog dialog = getDialog();
    if (dialog != null)
    {
        int width = ViewGroup.LayoutParams.MATCH_PARENT;
        int height = ViewGroup.LayoutParams.MATCH_PARENT;
        dialog.getWindow().setLayout(width, height);
    }
}


 public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
    final Dialog dialog = new Dialog(requireContext());
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
 }


   

Error in finding last used cell in Excel with VBA

Since the original question is about problems with finding the last cell, in this answer I will list the various ways you can get unexpected results; see my answer to "How can I find last row that contains data in the Excel sheet with a macro?" for my take on solving this.

I'll start by expanding on the answer by sancho.s and the comment by GlennFromIowa, adding even more detail:

[...] one has first to decide what is considered used. I see at least 6 meanings. Cell has:

  • 1) data, i.e., a formula, possibly resulting in a blank value;
  • 2) a value, i.e., a non-blank formula or constant;
  • 3) formatting;
  • 4) conditional formatting;
  • 5) a shape (including Comment) overlapping the cell;
  • 6) involvement in a Table (List Object).

Which combination do you want to test for? Some (such as Tables) may be more difficult to test for, and some may be rare (such as a shape outside of data range), but others may vary based on the situation (e.g., formulas with blank values).

Other things you might want to consider:

  • A) Can there be hidden rows (e.g. autofilter), blank cells or blank rows?
  • B) What kind of performance is acceptable?
  • C) Can the VBA macro affect the workbook or the application settings in any way?

With that in mind, let's see how the common ways of getting the "last cell" can produce unexpected results:

  • The .End(xlDown) code from the question will break most easily (e.g. with a single non-empty cell or when there are blank cells in between) for the reasons explained in the answer by Siddharth Rout here (search for "xlDown is equally unreliable.")
  • Any solution based on Counting (CountA or Cells*.Count) or .CurrentRegion will also break in presence of blank cells or rows
  • A solution involving .End(xlUp) to search backwards from the end of a column will, just as CTRL+UP, look for data (formulas producing a blank value are considered "data") in visible rows (so using it with autofilter enabled might produce incorrect results ??).

    You have to take care to avoid the standard pitfalls (for details I'll again refer to the answer by Siddharth Rout here, look for the "Find Last Row in a Column" section), such as hard-coding the last row (Range("A65536").End(xlUp)) instead of relying on sht.Rows.Count.

  • .SpecialCells(xlLastCell) is equivalent to CTRL+END, returning the bottom-most and right-most cell of the "used range", so all caveats that apply to relying on the "used range", apply to this method as well. In addition, the "used range" is only reset when saving the workbook and when accessing worksheet.UsedRange, so xlLastCell might produce stale results?? with unsaved modifications (e.g. after some rows were deleted). See the nearby answer by dotNET.
  • sht.UsedRange (described in detail in the answer by sancho.s here) considers both data and formatting (though not conditional formatting) and resets the "used range" of the worksheet, which may or may not be what you want.

    Note that a common mistake ?is to use .UsedRange.Rows.Count??, which returns the number of rows in the used range, not the last row number (they will be different if the first few rows are blank), for details see newguy's answer to How can I find last row that contains data in the Excel sheet with a macro?

  • .Find allows you to find the last row with any data (including formulas) or a non-blank value in any column. You can choose whether you're interested in formulas or values, but the catch is that it resets the defaults in the Excel's Find dialog ????, which can be highly confusing to your users. It also needs to be used carefully, see the answer by Siddharth Rout here (section "Find Last Row in a Sheet")
  • More explicit solutions that check individual Cells' in a loop are generally slower than re-using an Excel function (although can still be performant), but let you specify exactly what you want to find. See my solution based on UsedRange and VBA arrays to find the last cell with data in the given column -- it handles hidden rows, filters, blanks, does not modify the Find defaults and is quite performant.

Whatever solution you pick, be careful

  • to use Long instead of Integer to store the row numbers (to avoid getting Overflow with more than 65k rows) and
  • to always specify the worksheet you're working with (i.e. Dim ws As Worksheet ... ws.Range(...) instead of Range(...))
  • when using .Value (which is a Variant) avoid implicit casts like .Value <> "" as they will fail if the cell contains an error value.

PHP ternary operator vs null coalescing operator

class a
{
    public $a = 'aaa';
}

$a = new a();

echo $a->a;  // Writes 'aaa'
echo $a->b;  // Notice: Undefined property: a::$b

echo $a->a ?? '$a->a does not exists';  // Writes 'aaa'

// Does not throw an error although $a->b does not exist.
echo $a->b ?? '$a->b does not exist.';  // Writes $a->b does not exist.

// Does not throw an error although $a->b and also $a->b->c does not exist.
echo $a->b->c ?? '$a->b->c does not exist.';  // Writes $a->b->c does not exist.

How to detect if JavaScript is disabled?

People have already posted examples that are good options for detection, but based on your requirement of "give warning that the site is not able to function properly without the browser having JS enabled". You basically add an element that appears somehow on the page, for example the 'pop-ups' on Stack Overflow when you earn a badge, with an appropriate message, then remove this with some Javascript that runs as soon as the page is loaded (and I mean the DOM, not the whole page).

Multiple Forms or Multiple Submits in a Page?

Best practice: one form per product is definitely the way to go.

Benefits:

  • It will save you the hassle of having to parse the data to figure out which product was clicked
  • It will reduce the size of data being posted

In your specific situation

If you only ever intend to have one form element, in this case a submit button, one form for all should work just fine.


My recommendation Do one form per product, and change your markup to something like:

<form method="post" action="">
    <input type="hidden" name="product_id" value="123">
    <button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>

This will give you a much cleaner and usable POST. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).

Note: There's no technical benefit to using <button> vs. <input>, but as a programmer I find it cooler to work with action=='add_to_cart' than action=='Add to Cart'. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.

Converting NumPy array into Python List structure?

tolist() works fine even if encountered a nested array, say a pandas DataFrame;

my_list = [0,1,2,3,4,5,4,3,2,1,0]
my_dt = pd.DataFrame(my_list)
new_list = [i[0] for i in my_dt.values.tolist()]

print(type(my_list),type(my_dt),type(new_list))

How to make Regular expression into non-greedy?

I believe it would be like this

takedata.match(/(\[.+\])/g);

the g at the end means global, so it doesn't stop at the first match.

Converting newline formatting from Mac to Windows

vim also can convert files from UNIX to DOS format. For example:

vim hello.txt <<EOF
:set fileformat=dos
:wq
EOF

How to print pandas DataFrame without index

To answer the "How to print dataframe without an index" question, you can set the index to be an array of empty strings (one for each row in the dataframe), like this:

blankIndex=[''] * len(df)
df.index=blankIndex

If we use the data from your post:

row1 = (123, '2014-07-08 00:09:00', 1411)
row2 = (123, '2014-07-08 00:49:00', 1041)
row3 = (123, '2014-07-08 00:09:00', 1411)
data = [row1, row2, row3]
#set up dataframe
df = pd.DataFrame(data, columns=('User ID', 'Enter Time', 'Activity Number'))
print(df)

which would normally print out as:

   User ID           Enter Time  Activity Number
0      123  2014-07-08 00:09:00             1411
1      123  2014-07-08 00:49:00             1041
2      123  2014-07-08 00:09:00             1411

By creating an array with as many empty strings as there are rows in the data frame:

blankIndex=[''] * len(df)
df.index=blankIndex
print(df)

It will remove the index from the output:

  User ID           Enter Time  Activity Number
      123  2014-07-08 00:09:00             1411
      123  2014-07-08 00:49:00             1041
      123  2014-07-08 00:09:00             1411

And in Jupyter Notebooks would render as per this screenshot: Juptyer Notebooks dataframe with no index column

Lightweight workflow engine for Java

Java based workflow engines like Activiti, Bonita or jBPM support a wide range of the BPMN 2.0 specification. Therefore, you can model processes in a graphical way. In addition, some of those engines have simulation capabilities like Activiti (with Activiti Crystalball). If you code the processes on your own, you aren´t as flexible when you need to change the process. Therefore, I would also advice to use a java based BPM engine.

I did a research concerning BPMN 2.0 based Open Source Engines. Here are the key-points which were relevant for our concrete use case:

1. Bonita:

Bonita has a zero-coding approach which means that they provide an easy to use IDE to build your processes without the need for coding. To achieve that, Bonita has the concept of connectors. For example, if you want to consume a web service, they provide you with a graphical wizzard. The downside is that you have to write the plain XML SOAP-envelope manually and copy it in a graphical textbox. The problem with this approach is that you only can realize use cases which are intended by Bonita. If you want to integrate a system which Bonita did not developed a connector for, you have to code such a connector on your own which is very painful. For example, Bonita offers a SOAP connector for consuming SOAP web services. This connector only works with SOAP 1.2, but not for SOAP 1.1 (http://community.bonitasoft.com/answers/consume-soap-11-webservices-bonita-secure-web-service-connector). If you have a legacy application with SOAP 1.1, you cannot integrate this system easily in your process. The same is true for databases. There are only a few database connectors for dedicated database versions. If you have a version not matching to a connector, you have to code this on your own.

In addition, Bonita has no support for LDAP or Active Directory Sync in the free community edition which is quite a showstopper for a production environment. Another thing to consider is that Bonita is licensed under the GPL / LGPL license which could cause problems when you want to integrate Bonita in another enterprise application. In addition, the community support is very weak. There are several posts which are more than 2 years old and those posts are still not answered.

Another important thing is Business-IT-Alignment. Modelling processes is a collaborative discipline in which IT AND the business analysts are involed. That is why you need adequate tools for both user groups (e.g. an Eclipse Plugin for the developers and an easy to use web modeler for the business people). Bonita only offers Bonita Studio, which needs to be installed on your machine. This IDE is quite technical and not suitable for business users. Therefore, it is very hard to realize Business-IT-Alignment with Bonita.

Bonita is a BPM tool for very trivial and easy processes. Because of the zero-coding approach, the lerning curve is very low and you can start modelling very fast. You need less programming skills and you are able to realize your processes without the need of coding. But as soon as your processes become very complex, Bonita might not be the best solution because of the lack of flexibility. You only can realize use cases which are intended by Bonita.

2. jBPM:

jBPM is a very powerful Open Source BPM Engine which has a lot of features. The web modeler even supports prefabricated models of some van der Aalst workflow patterns (workflowpatterns.com). Business-IT-Alignment is realizable because jBPM offers an Eclipse integration as well as a web-based modeler. A bit tricky is that you only can define forms in the web modeler, but not in the Eclipse Plugin, as far as I know. To sum up, jBPM is a good candidate for using in a company. Our showstopper was the scalability. jBPM is based on the Rules-Engine Drools. This leads to the fact that whole process instances are persisted as BLOBS in the database. This is a critial showstopper when you consider searching and scalability.

In addition, the learning curve is very high because of the complexity. jBPM does not offer a Service Task like the BPMN-Standard suggests In contrast, you have to define your own Java Service tasks and you have to register them manually in the engine, which results in quite low level programming.

3. Activiti:

In the end, we went with Activiti because this is a very easy to use framework-based engine. It offers an Eclipse Plugin as well as a modern AngularJS Web-Modeler. In this way, you can realize Business-IT-Alignment. The REST-API is secured by Spring Security which means that you can extend the Engine very easily with Single Sign-on features. Because of the Apache License 2.0, there is no copyleft which means you are completely free in terms of usage and extensibility which is very important in a productive environment.

In addition, the BPMN-coverage is very good. Not all BPMN-elements are realized, but I do not know any engine which does that.

The Activiti Explorer is a demo frontend which demonstrates the usage of the Activiti APIs. Since this frontend is based on VAADIN, it can be extended very easily. The community is very active which means that you can get help very fast if you have any problems.

Activiti offers good integration points for external form-technologies which is very important for a productive usage. The form-technologies of all candidates are very restrictive. Therefore, it makes sense to use a standard form-technology like XForms in combination with the Engine. Even such more complex things are realizable via the formKey-Attribute.

Activiti does not follow the zero-coding approach which means that you will need a bit of coding if you want to orchestrate services. But even the communication with SOAP services can be achieved by using a Java Service Task and Apache CXF. The coding effort is low.

I hope that my key points can help by taking a decision. To be clear, this is no advertisment for Activiti. The right product choice depends on the concrete use cases. I only want to point out the most important points in our project

How to convert list of key-value tuples into dictionary?

If Tuple has no key repetitions, it's Simple.

tup = [("A",0),("B",3),("C",5)]
dic = dict(tup)
print(dic)

If tuple has key repetitions.

tup = [("A",0),("B",3),("C",5),("A",9),("B",4)]
dic = {}
for i, j in tup:
    dic.setdefault(i,[]).append(j)
print(dic)

Call Python function from JavaScript code

You cannot run .py files from JavaScript without the Python program like you cannot open .txt files without a text editor. But the whole thing becomes a breath with a help of a Web API Server (IIS in the example below).

  1. Install python and create a sample file test.py

    import sys
    # print sys.argv[0] prints test.py
    # print sys.argv[1] prints your_var_1
    
    def hello():
        print "Hi" + " " + sys.argv[1]
    
    if __name__ == "__main__":
        hello()
    
  2. Create a method in your Web API Server

    [HttpGet]
    public string SayHi(string id)
    {
        string fileName = HostingEnvironment.MapPath("~/Pyphon") + "\\" + "test.py";          
    
        Process p = new Process();
        p.StartInfo = new ProcessStartInfo(@"C:\Python27\python.exe", fileName + " " + id)
        {
            RedirectStandardOutput = true,
            UseShellExecute = false,
            CreateNoWindow = true
        };
        p.Start();
    
        return p.StandardOutput.ReadToEnd();                  
    }
    
  3. And now for your JavaScript:

    function processSayingHi() {          
       var your_param = 'abc';
       $.ajax({
           url: '/api/your_controller_name/SayHi/' + your_param,
           type: 'GET',
           success: function (response) {
               console.log(response);
           },
           error: function (error) {
               console.log(error);
           }
        });
    }
    

Remember that your .py file won't run on your user's computer, but instead on the server.

How to remove specific value from array using jQuery

There is a simple solution with splice. According to W3School splice syntax is following;

array.splice(index, howmany, item1, ....., itemX)

index Required. An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array

howmany Required. The number of items to be removed. If set to 0, no items will be removed

item1, ..., itemX Optional. The new item(s) to be added to the array

Keep that in mind, the following js will pop one or more matched item from the given array if found, otherwise wouldn't remove the last item of the array.

var x = [1,2,3,4,5,4,4,6,7];
var item = 4;
var startItemIndex = $.inArray(item, x);
var itemsFound = x.filter(function(elem){
                            return elem == item;
                          }).length;

Or

var itemsFound = $.grep(x, function (elem) {
                              return elem == item;
                           }).length;

So the final should look like the following

x.splice( startItemIndex , itemsFound );

Hope this helps.

MySQL 1062 - Duplicate entry '0' for key 'PRIMARY'

For me, i forget to add AUTO_INCREMENT to my primary field and inserted data without id.

LEFT OUTER JOIN in LINQ

Here's an example if you need to join more than 2 tables:

from d in context.dc_tpatient_bookingd
join bookingm in context.dc_tpatient_bookingm 
     on d.bookingid equals bookingm.bookingid into bookingmGroup
from m in bookingmGroup.DefaultIfEmpty()
join patient in dc_tpatient
     on m.prid equals patient.prid into patientGroup
from p in patientGroup.DefaultIfEmpty()

Ref: https://stackoverflow.com/a/17142392/2343

How to make an Android device vibrate? with different frequency?

Vibrating in Patterns/Waves:

import android.os.Vibrator;
...
// Vibrate for 500ms, pause for 500ms, then start again
private static final long[] VIBRATE_PATTERN = { 500, 500 };

mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    // API 26 and above
    mVibrator.vibrate(VibrationEffect.createWaveform(VIBRATE_PATTERN, 0));
} else {
    // Below API 26
    mVibrator.vibrate(VIBRATE_PATTERN, 0);
}

Plus

The necessary permission in AndroidManifest.xml:

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

MySQL add days to a date

You can leave date_add function.

UPDATE `table` 
SET `yourdatefield` = `yourdatefield` + INTERVAL 2 DAY
WHERE ...

TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT maximum storage sizes

This is nice but doesn't answer the question:

"A VARCHAR should always be used instead of TINYTEXT." Tinytext is useful if you have wide rows - since the data is stored off the record. There is a performance overhead, but it does have a use.

SFTP in Python? (platform independent)

If you want easy and simple, you might also want to look at Fabric. It's an automated deployment tool like Ruby's Capistrano, but simpler and of course for Python. It's build on top of Paramiko.

You might not want to do 'automated deployment' but Fabric would suit your use case perfectly none the less. To show you how simple Fabric is: the fab file and command for your script would look like this (not tested, but 99% sure it will work):

fab_putfile.py:

from fabric.api import *

env.hosts = ['THEHOST.com']
env.user = 'THEUSER'
env.password = 'THEPASSWORD'

def put_file(file):
    put(file, './THETARGETDIRECTORY/') # it's copied into the target directory

Then run the file with the fab command:

fab -f fab_putfile.py put_file:file=./path/to/my/file

And you're done! :)

How to make CREATE OR REPLACE VIEW work in SQL Server?

Edit: Although this question has been marked as a duplicate, it has still been getting attention. The answer provided by @JaKXz is correct and should be the accepted answer.


You'll need to check for the existence of the view. Then do a CREATE VIEW or ALTER VIEW depending on the result.

IF OBJECT_ID('dbo.data_VVVV') IS NULL
BEGIN
    CREATE VIEW dbo.data_VVVV
    AS
    SELECT VCV.xxxx, VCV.yyyy AS yyyy, VCV.zzzz AS zzzz FROM TABLE_A VCV
END
ELSE
    ALTER VIEW dbo.data_VVVV
    AS
    SELECT VCV.xxxx, VCV.yyyy AS yyyy, VCV.zzzz AS zzzz FROM TABLE_A VCV
BEGIN
END

How to use UIScrollView in Storyboard

In iOS7 I found that if I had a View inside a UIScrollView on a FreeForm-sized ViewController it would not scroll in the app, no matter what I did. I played around and found the following seemed to work, which uses no FreeForms:

  1. Insert a UIScrollView inside the main View of a ViewController

  2. Set the Autolayout constraints on the ScrollView as appropriate. For me I used 0 to Top Layout guide and 0 to Bottom layout Guide

  3. Inside the ScrollView, place a Container View. Set its height to whatever you want (e.g. 1000)

  4. Add a Height constraint (1000) to the Container so it doesn't resize. The bottom will be past the end of the form.

  5. Add the line [self.scrollView setContentSize:CGSizeMake(320, 1000)]; to the ViewController that contains the scrollView (which you've hooked up as a IBOutlet)

The ViewController (automatically added) that is associated with the Container will have the desired height (1000) in Interface Builder and will also scroll properly in the original view controller. You can now use the container's ViewController to layout your controls.

Trigger function when date is selected with jQuery UI datepicker

$(".datepicker").datepicker().on("changeDate", function(e) {
   console.log("Date changed: ", e.date);
});

how to define variable in jquery

Remember jQuery is a JavaScript library, i.e. like an extension. That means you can use both jQuery and JavaScript in the same function (restrictions apply).

You declare/create variables in the same way as in Javascript: var example;

However, you can use jQuery for assigning values to variables:

var example = $("#unique_product_code").html();

Instead of pure JavaScript:

var example = document.getElementById("unique_product_code").innerHTML;

How to initialize weights in PyTorch?

Single layer

To initialize the weights of a single layer, use a function from torch.nn.init. For instance:

conv1 = torch.nn.Conv2d(...)
torch.nn.init.xavier_uniform(conv1.weight)

Alternatively, you can modify the parameters by writing to conv1.weight.data (which is a torch.Tensor). Example:

conv1.weight.data.fill_(0.01)

The same applies for biases:

conv1.bias.data.fill_(0.01)

nn.Sequential or custom nn.Module

Pass an initialization function to torch.nn.Module.apply. It will initialize the weights in the entire nn.Module recursively.

apply(fn): Applies fn recursively to every submodule (as returned by .children()) as well as self. Typical use includes initializing the parameters of a model (see also torch-nn-init).

Example:

def init_weights(m):
    if type(m) == nn.Linear:
        torch.nn.init.xavier_uniform(m.weight)
        m.bias.data.fill_(0.01)

net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))
net.apply(init_weights)

How to Execute a Python File in Notepad ++?

In case someone is interested in passing arguments to cmd.exe and running the python script in a Virtual Environment, these are the steps I used:

On the Notepad++ -> Run -> Run , I enter the following:

cmd /C cd $(CURRENT_DIRECTORY) && "PATH_to_.bat_file" $(FULL_CURRENT_PATH)

Here I cd into the directory in which the .py file exists, so that it enables accessing any other relevant files which are in the directory of the .py code.

And on the .bat file I have:

@ECHO off
set File_Path=%1

call activate Venv
python %File_Path%
pause

How to switch to another domain and get-aduser

best solution TNX to Drew Chapin and all of you too:

I just want to add that if you don't inheritently know the name of a domain controller, you can get the closest one, pass it's hostname to the -Server argument.

$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite

Get-ADUser -Server $dc.HostName[0] `
    -Filter { EmailAddress -Like "*Smith_Karla*" } `
    -Properties EmailAddress

my script:

$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
 Get-ADUser -Server $dc.HostName[0] ` -Filter { EmailAddress -Like "*Smith_Karla*" } `  -Properties EmailAddress | Export-CSV "C:\Scripts\Email.csv

Inherit CSS class

You can create another class with the properties you want and add this class to your class attribute:

.classA
{
  margin: 0;
  text-align: left;
}

.classB
{
  background-color: Gray;
  border: 1px solid black;
}

<div class="classA classB">My div</div>

How to create a private class method?

Ruby seems to provide a poor solution. To explain, start with a simple C++ example that shows access to private class methods:

#include <iostream>

class C
{
    public:
        void instance_method(void)
        {
            std::cout << "instance method\n";
            class_method();  // !!! LOOK !!! no 'send' required. We can access it
                             // because 'private' allows access within the class
        }
    private:
        void static class_method(void) { std::cout << "class method\n"; }
};

int main()
{
    C c;

    c.instance_method(); // works
    // C::class_method() does not compile - it's properly private
    return 0;
}

Running the above

   % ./a.out
   instance method
   class method

Now Ruby does not seem to provide the equivalent. Ruby's rules, I think, are that private methods must not be accessed with a receiver. That is,

inst.pvt_method  # FAILS
pvt_method # WORKS only within the class (good)

That's OK for private instance methods, but causes problems with private class methods.

I would like Ruby to function this way:

class C
    def instance_method
        STDOUT << "instance method\n"

        # Simple access to the private class method would be nice:
        class_method   # DOES NOT WORK. RUBY WON'T FIND THE METHOD
        C.class_method # DOES NOT WORK. RUBY WON'T ALLOW IT

        # ONLY THIS WORKS. While I am happy such capability exists I think
        # the way 'send' should be used is when the coder knows he/she is
        # doing a no-no.  The semantic load on the coder for this is also
        # remarkably clumsy for an elegant language like ruby.
        self.class.send(:class_method)
    end

    private_class_method def self.class_method() STDOUT << "class method\n"; end
end

But, alas, the above does not work. Does someone know a better way?

When I see 'send' prior to a method, it's a clear sign the code is violating the intent of the API's designer, but in this case the design is specifically to have an instance method of the class call the private class method.

Extract substring using regexp in plain bash

    echo "US/Central - 10:26 PM (CST)" | sed -n "s/^.*-\s*\(\S*\).*$/\1/p"

-n      suppress printing
s       substitute
^.*     anything at the beginning
-       up until the dash
\s*     any space characters (any whitespace character)
\(      start capture group
\S*     any non-space characters
\)      end capture group
.*$     anything at the end
\1      substitute 1st capture group for everything on line
p       print it

Difference between == and ===

== is used to check if two variables are equal i.e 2 == 2. But in case of === it stands for equality i.e if two instances referring to the same object example in case of classes a reference is created which is held by many other instances.

Python - How to convert JSON File to Dataframe

jsondata = '{"0001":{"FirstName":"John","LastName":"Mark","MiddleName":"Lewis","username":"johnlewis2","password":"2910"}}'
import json
import pandas as pd
jdata = json.loads(jsondata)
df = pd.DataFrame(jdata)
print df.T

This should look like this:.

         FirstName LastName MiddleName password    username
0001      John     Mark      Lewis     2910  johnlewis2

Jquery: Checking to see if div contains text, then action

Your code contains two problems:

  • The equality operator in JavaScript is ==, not =.
  • jQuery.text() joins all text nodes of matched elements into a single string. If you have two successive elements, of which the first contains 'some' and the second contains 'Text', then your code will incorrectly think that there exists an element that contains 'someText'.

I suggest the following instead:

if ($('#field > div.field-item:contains("someText")').length > 0) {
    $("#somediv").addClass("thisClass");
}

android.content.Context.getPackageName()' on a null object reference

The answers to this question helped me find my problem, but my source was different, so hopefully this can shed light on someone finding this page searching for answers to the 'random' context crash:

I had specified a SharedPreferences object, and tried to instantiate it at it's class-level declaration, like so:

public class MyFragment extends FragmentActivity {
    private SharedPreferences sharedPref =
        PreferenceManager.getDefaultSharedPreferences(this);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //...

Referencing this before the onCreate caused the "java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference" error for me.

Instantiating the object inside the onCreate() solved my problem, like so:

public class MyFragment extends FragmentActivity {
    private SharedPreferences sharedPref;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //...
        sharedPref = PreferenceManager.getDefaultSharedPreferences(this);

Hope that helps.

How do I find the location of my Python site-packages directory?

An additional note to the get_python_lib function mentioned already: on some platforms different directories are used for platform specific modules (eg: modules that require compilation). If you pass plat_specific=True to the function you get the site packages for platform specific packages.

How to check for a Null value in VB.NET

If you are using a strongly-typed dataset then you should do this:

If Not ediTransactionRow.Ispay_id1Null Then
    'Do processing here
End If

You are getting the error because a strongly-typed data set retrieves the underlying value and exposes the conversion through the property. For instance, here is essentially what is happening:

Public Property pay_Id1 Then
   Get
     return DirectCast(me.GetValue("pay_Id1", short)
   End Get
   'Abbreviated for clarity
End Property

The GetValue method is returning DBNull which cannot be converted to a short.

Cannot install packages using node package manager in Ubuntu

You can also install Nodejs using NVM or Nodejs Version Manager There are a lot of benefits to using a version manager. One of them being you don't have to worry about this issue.


Instructions:


sudo apt-get update
sudo apt-get install build-essential libssl-dev

Once the prerequisite packages are installed, you can pull down the nvm installation script from the project's GitHub page. The version number may be different, but in general, you can download and install it with the following syntax:

curl https://raw.githubusercontent.com/creationix/nvm/v0.16.1/install.sh | sh

This will download the script and run it. It will install the software into a subdirectory of your home directory at ~/.nvm. It will also add the necessary lines to your ~/.profile file to use the file.

To gain access to the nvm functionality, you'll need to log out and log back in again, or you can source the ~/.profile file so that your current session knows about the changes:

source ~/.profile

Now that you have nvm installed, you can install isolated Node.js versions.

To find out the versions of Node.js that are available for installation, you can type:

nvm ls-remote
. . .

v0.11.10
v0.11.11
v0.11.12
v0.11.13
v0.11.14

As you can see, the newest version at the time of this writing is v0.11.14. You can install that by typing:

nvm install 0.11.14

Usually, nvm will switch to use the most recently installed version. You can explicitly tell nvm to use the version we just downloaded by typing:

nvm use 0.11.14

When you install Node.js using nvm, the executable is called node. You can see the version currently being used by the shell by typing:

node -v

The comeplete tutorial can be found here

Why should I use a pointer rather than the object itself?

"Necessity is the mother of invention." The most of important difference that I would like to point out is the outcome of my own experience of coding. Sometimes you need to pass objects to functions. In that case, if your object is of a very big class then passing it as an object will copy its state (which you might not want ..AND CAN BE BIG OVERHEAD) thus resulting in an overhead of copying object .while pointer is fixed 4-byte size (assuming 32 bit). Other reasons are already mentioned above...

How to programmatically set cell value in DataGridView?

private void btn_Addtoreciept_Click(object sender, EventArgs e)
{            
    serial_number++;
    dataGridView_inventory.Rows[serial_number - 1].Cells[0].Value = serial_number;
    dataGridView_inventory.Rows[serial_number - 1].Cells[1].Value =comboBox_Reciept_name.Text;
    dataGridView_inventory.Rows[serial_number - 1].Cells[2].Value = numericUpDown_recieptprice.Value;
    dataGridView_inventory.Rows[serial_number - 1].Cells[3].Value = numericUpDown_Recieptpieces.Value;
    dataGridView_inventory.Rows[serial_number - 1].Cells[4].Value = numericUpDown_recieptprice.Value * numericUpDown_Recieptpieces.Value;
    numericUpDown_RecieptTotal.Value = serial_number;
}

on first time it goes well but pressing 2nd time it gives me error "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index" but when i click on the cell another row appears and then it works for the next row, and carry on ...

How do you add a scroll bar to a div?

<div class="scrollingDiv">foo</div> 

div.scrollingDiv
{
   overflow:scroll;
}

Ant task to run an Ant target only if a file exists?

You can do it by ordering to do the operation with a list of files with names equal to the name(s) you need. It is much easier and direct than to create a special target. And you needn't any additional tools, just pure Ant.

<delete>
    <fileset includes="name or names of file or files you need to delete"/>
</delete>

See: FileSet.

How to get current language code with Swift?

Swift 3 & 4 & 4.2 & 5

Locale.current.languageCode does not compile regularly. Because you did not implemented localization for your project.

You have two possible solutions

1) String(Locale.preferredLanguages[0].prefix(2)) It returns phone lang properly.

If you want to get the type en-En, you can use Locale.preferredLanguages[0]

2) Select Project(MyApp)->Project (not Target)-> press + button into Localizations, then add language which you want.

ByRef argument type mismatch in Excel VBA

It looks like ByRef needs to know the size of the parameter. A declaration of Dim last_name as string doesn't specify the size of the string so it takes it as an error. Before using Worksheets(data_sheet).Range("C2").Value = ProcessString(last_name) The last_name has to be declared as Dim last_name as string *10 ' size of string is up to you but must be a fix length

No need to change the function. Function doesn't take a fix length declaration.

Programmatically change input type of the EditText from PASSWORD to NORMAL & vice versa

Since the Support Library v24.2.0. you can achivie this very easy

What you need to do is just:

  1. Add the design library to your dependecies

    dependencies {
         compile "com.android.support:design:25.1.0"
    }
    
  2. Use TextInputEditText in conjunction with TextInputLayout

    <android.support.design.widget.TextInputLayout
        android:id="@+id/etPasswordLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:passwordToggleEnabled="true">
    
        <android.support.design.widget.TextInputEditText
            android:id="@+id/etPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/password_hint"
            android:inputType="textPassword"/>
    </android.support.design.widget.TextInputLayout>
    

passwordToggleEnabled attribute will make the password toggle appear

  1. In your root layout don't forget to add xmlns:app="http://schemas.android.com/apk/res-auto"

  2. You can customize your password toggle by using:

app:passwordToggleDrawable - Drawable to use as the password input visibility toggle icon.
app:passwordToggleTint - Icon to use for the password input visibility toggle.
app:passwordToggleTintMode - Blending mode used to apply the background tint.

More details in TextInputLayout documentation. enter image description here

Undefined reference to vtable

I tried all the detailed steps by JaMIT and still got stumped by this error. After a good amount of head-banging, I figured it out. I was careless. You should be able to reproduce this painful-to-look-at error w/ the following sample code.

[jaswantp@jaswant-arch build]$ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-pc-linux-gnu/10.2.0/lto-wrapper
Target: x86_64-pc-linux-gnu
Configured with: /build/gcc/src/gcc/configure --prefix=/usr --libdir=/usr/lib --libexecdir=/usr/lib --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=https://bugs.archlinux.org/ --enable-languages=c,c++,ada,fortran,go,lto,objc,obj-c++,d --with-isl --with-linker-hash-style=gnu --with-system-zlib --enable-__cxa_atexit --enable-cet=auto --enable-checking=release --enable-clocale=gnu --enable-default-pie --enable-default-ssp --enable-gnu-indirect-function --enable-gnu-unique-object --enable-install-libiberty --enable-linker-build-id --enable-lto --enable-multilib --enable-plugin --enable-shared --enable-threads=posix --disable-libssp --disable-libstdcxx-pch --disable-libunwind-exceptions --disable-werror gdc_include_dir=/usr/include/dlang/gdc
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 10.2.0 (GCC) 

// CelesetialBody.h
class CelestialBody{
public:
    virtual void Print();
protected:
    CelestialBody();
    virtual ~CelestialBody();
};
// CelestialBody.cpp
#include "CelestialBody.h"

CelestialBody::CelestialBody() {}

CelestialBody::~CelestialBody() = default;

void CelestialBody::Print() {}
// Planet.h
#include "CelestialBody.h"

class Planet : public CelestialBody
{
public:
    void Print() override;
protected:
    Planet();
    ~Planet() override;
};
// Planet.cpp
#include "Planet.h"

Planet::Planet() {}
Planet::~Planet() {}

void Print() {} // Deliberately forgot to prefix `Planet::`
# CMakeLists.txt
cmake_minimum_required(VERSION 3.12)
project (space_engine)
add_library (CelestialBody SHARED CelestialBody.cpp)
add_library (Planet SHARED Planet.cpp)
target_include_directories (CelestialBody PRIVATE ${CMAKE_CURRENT_LIST_DIR})  
target_include_directories (Planet PRIVATE ${CMAKE_CURRENT_LIST_DIR})    
target_link_libraries (Planet PUBLIC CelestialBody)

# hardened linker flags to catch undefined symbols
target_link_options(Planet 
    PRIVATE 
    -Wl,--as-needed
    -Wl,--no-undefined
)

And we get our favourite error.

$ mkdir build
$ cd build
$ cmake ..
$ make
[ 50%] Built target CelestialBody
Scanning dependencies of target Planet
[ 75%] Building CXX object CMakeFiles/Planet.dir/Planet.cpp.o
[100%] Linking CXX shared library libPlanet.so
/usr/bin/ld: CMakeFiles/Planet.dir/Planet.cpp.o: in function `Planet::Planet()':
Planet.cpp:(.text+0x1b): undefined reference to `vtable for Planet'
/usr/bin/ld: CMakeFiles/Planet.dir/Planet.cpp.o: in function `Planet::~Planet()':
Planet.cpp:(.text+0x3d): undefined reference to `vtable for Planet'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/Planet.dir/build.make:104: libPlanet.so] Error 1
make[1]: *** [CMakeFiles/Makefile2:97: CMakeFiles/Planet.dir/all] Error 2
make: *** [Makefile:103: all] Error 2

What I've done in Planet.cpp should of course be resolved with this tip

  1. Look at your class definition. Find the first non-inline virtual function that is not pure virtual (not "= 0") and whose definition you provide (not "= default").

from JaMIT's answer. If there is anyone else who tried all the above and nothing worked, maybe you too, like me, carelessly forgot to prefix <ClassName>:: to one or more member functions.

Either I need to get my eyes checked or I need to get some sleep.

Compare dates with javascript

If your dates are strings in a strict yyyy-mm-dd format as shown in the question then your code will work as is without converting to date objects or numbers:

if(first > second){

...will do a lexographic (i.e., alphanumeric "dictionary order") string comparison - which will compare the first characters of each string, then the second characters of each string, etc. Which will give the result you want...

Python: Differentiating between row and column vectors

row vectors are (1,0) tensor, vectors are (0, 1) tensor. if using v = np.array([[1,2,3]]), v become (0,2) tensor. Sorry, i am confused.

How to reference a .css file on a razor view?

I prefer to use the razor html helper from Client Dependency dll

Html.RequireCss("yourfile", 9999); // 9999 is loading priority 

Changing an element's ID with jQuery

$('#id-you-want-to-change').attr('id', 'id-you-want-it-to-be');

jquery save json data object in cookie

Now there is already no need to use JSON.stringify explicitly. Just execute this line of code

$.cookie.json = true;

After that you can save any object in cookie, which will be automatically converted to JSON and back from JSON when reading cookie.

var user = { name: "name", age: 25 }
$.cookie('user', user);
...

var currentUser = $.cookie('user');
alert('User name is ' + currentUser.name);

But JSON library does not come with jquery.cookie, so you have to download it by yourself and include into html page before jquery.cookie.js

Presenting a UIAlertController properly on an iPad using iOS 8

2018 Update

I just had an app rejected for this reason and a very quick resolution was simply to change from using an action sheet to an alert.

Worked a charm and passed the App Store testers just fine.

May not be a suitable answer for everyone but I hope this helps some of you out of a pickle quickly.

CSS text-align: center; is not centering things

Use display: block; margin: auto; it will center the div

Copy existing project with a new name in Android Studio

Go to the source folder where your project is.

  1. Copy the project and past and change the name.
  2. Open Android Studio and refresh.
  3. Go to ->Settings.gradle.
  4. Include ':your new project name '

Android Studio - debug keystore

If you use Windows, probably the location is like this:

C:\User\YourUser\.android\debug.keystore

Compare two folders which has many files inside contents

diff -r will do this, telling you both if any files have been added or deleted, and what's changed in the files that have been modified.

Scatter plots in Pandas/Pyplot: How to plot by category

From matplotlib 3.1 onwards you can use .legend_elements(). An example is shown in Automated legend creation. The advantage is that a single scatter call can be used.

In this case:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.normal(10,1,30).reshape(10,3), 
                  index = pd.date_range('2010-01-01', freq = 'M', periods = 10), 
                  columns = ('one', 'two', 'three'))
df['key1'] = (4,4,4,6,6,6,8,8,8,8)


fig, ax = plt.subplots()
sc = ax.scatter(df['one'], df['two'], marker = 'o', c = df['key1'], alpha = 0.8)
ax.legend(*sc.legend_elements())
plt.show()

enter image description here

In case the keys were not directly given as numbers, it would look as

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.normal(10,1,30).reshape(10,3), 
                  index = pd.date_range('2010-01-01', freq = 'M', periods = 10), 
                  columns = ('one', 'two', 'three'))
df['key1'] = list("AAABBBCCCC")

labels, index = np.unique(df["key1"], return_inverse=True)

fig, ax = plt.subplots()
sc = ax.scatter(df['one'], df['two'], marker = 'o', c = index, alpha = 0.8)
ax.legend(sc.legend_elements()[0], labels)
plt.show()

enter image description here

How to format numbers?

If you want to use built-in code, you can use toLocaleString() with minimumFractionDigits. Browser compatibility for the extended options on toLocaleString() was limited when I first wrote this answer, but the current status looks good.

_x000D_
_x000D_
var n = 100000;
var value = n.toLocaleString(
  undefined, // leave undefined to use the browser's locale,
             // or use a string like 'en-US' to override it.
  { minimumFractionDigits: 2 }
);
console.log(value);
// In en-US, logs '100,000.00'
// In de-DE, logs '100.000,00'
// In hi-IN, logs '1,00,000.00'
_x000D_
_x000D_
_x000D_

If you're using Node.js, you will need to npm install the intl package.

How do I launch a program from command line without opening a new cmd window?

Add /B, as documented in the command-line help for start:

C:\>start /?
Starts a separate window to run a specified program or command.

START ["title"] [/D path] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED]
  [/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL]
  [/NODE <NUMA node>] [/AFFINITY <hex affinity mask>] [/WAIT] [/B]
  [command/program] [parameters]

"title"     Title to display in window title bar.
path        Starting directory.
B           Start application without creating a new window. The
            application has ^C handling ignored. Unless the application
            enables ^C processing, ^Break is the only way to interrupt
            the application.

Java List.add() UnsupportedOperationException

instead of using add() we can use addall()

{ seeAlso.addall(groupDn); }

add adds a single item, while addAll adds each item from the collection one by one. In the end, both methods return true if the collection has been modified. In case of ArrayList this is trivial, because the collection is always modified, but other collections, such as Set, may return false if items being added are already there.

Confused by python file mode "w+"

I suspect there are two ways to handle what I think you'r trying to achieve.

1) which is obvious, is open the file for reading only, read it into memory then open the file with t, then write your changes.

2) use the low level file handling routines:

# Open file in RW , create if it doesn't exist. *Don't* pass O_TRUNC
 fd = os.open(filename, os.O_RDWR | os.O_CREAT)

Hope this helps..

Split string into array of character strings

for(int i=0;i<str.length();i++)
{
System.out.println(str.charAt(i));
}

Difference between checkout and export in SVN

svn export simply extracts all the files from a revision and does not allow revision control on it. It also does not litter each directory with .svn directories.

svn checkout allows you to use version control in the directory made, e.g. your standard commands such as svn update and svn commit.

What are the differences between json and simplejson Python modules?

simplejson module is simply 1,5 times faster than json (On my computer, with simplejson 2.1.1 and Python 2.7 x86).

If you want, you can try the benchmark: http://abral.altervista.org/jsonpickle-bench.zip On my PC simplejson is faster than cPickle. I would like to know also your benchmarks!

Probably, as said Coady, the difference between simplejson and json is that simplejson includes _speedups.c. So, why don't python developers use simplejson?

Align an element to bottom with flexbox

Try This

_x000D_
_x000D_
.content {_x000D_
      display: flex;_x000D_
      flex-direction: column;_x000D_
      height: 250px;_x000D_
      width: 200px;_x000D_
      border: solid;_x000D_
      word-wrap: break-word;_x000D_
    }_x000D_
_x000D_
   .content h1 , .content h2 {_x000D_
     margin-bottom: 0px;_x000D_
    }_x000D_
_x000D_
   .content p {_x000D_
     flex: 1;_x000D_
    }
_x000D_
   <div class="content">_x000D_
  <h1>heading 1</h1>_x000D_
  <h2>heading 2</h2>_x000D_
  <p>Some more or less text</p>_x000D_
  <a href="/" class="button">Click me</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I remove the "No file chosen" tooltip from a file input in Chrome?

This is a tricky one. I could not find a way to select the 'no file chosen' element so I created a mask using the :after pseudo selector.

My solution also requires the use of the following pseudo selector to style the button:

::-webkit-file-upload-button

Try this: http://jsfiddle.net/J8Wfx/1/

FYI: This will only work in webkit browsers.

P.S if anyone knows how to view webkit pseudo selectors like the one above in the webkit inspector please let me know

Hibernate: ids for this class must be manually assigned before calling save()

your id attribute is not set. this MAY be due to the fact that the DB field is not set to auto increment? what DB are you using? MySQL? is your field set to AUTO INCREMENT?

Can clearInterval() be called inside setInterval()?

Yes you can. You can even test it:

_x000D_
_x000D_
var i = 0;_x000D_
var timer = setInterval(function() {_x000D_
  console.log(++i);_x000D_
  if (i === 5) clearInterval(timer);_x000D_
  console.log('post-interval'); //this will still run after clearing_x000D_
}, 200);
_x000D_
_x000D_
_x000D_

In this example, this timer clears when i reaches 5.

Get request URL in JSP which is forwarded by Servlet

Same as @axtavt, but you can use also the RequestDispatcher constant.

request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);

How can I connect to MySQL in Python 3 on Windows?

On my mac os maverick i try this:

After that, enter in the python3 interpreter and type:

  1. import pymysql. If there is no error your installation is ok. For verification write a script to connect to mysql with this form:

  2. # a simple script for MySQL connection import pymysql db = pymysql.connect(host="localhost", user="root", passwd="*", db="biblioteca") #Sure, this is information for my db # close the connection db.close ()*

Give it a name ("con.py" for example) and save it on desktop. In Terminal type "cd desktop" and then $python con.py If there is no error, you are connected with MySQL server. Good luck!

This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available

In my case, the error occured in phpmyadmin version 4.5.1 when i set lower_case_table_names = 2 and had a table name with uppercase characters, The table had a primary key set to auto increment but still showed the error. The issue stopped when i changed the table name to all lowercase.

Is Safari on iOS 6 caching $.ajax results?

I suggest a workaround to modify the function signature to be something like this:

getNewRecordID(intRecordType, strTimestamp) and then always pass in a TimeStamp parameter as well, and just discard that value on the server side. This works around the issue.

WCF Exception: Could not find a base address that matches scheme http for the endpoint

In my case the binding name in under protocol mapping did not match the binding name on the endpoint. They match in the example below.

<endpoint address="" binding="basicHttpsBinding" contract="serviceName" />

and

    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    

Error message "Linter pylint is not installed"

Try doing this if you're running Visual Studio Code on a Windows machine and getting this error (I'm using Windows 10).

Go to the settings and change the Python path to the location of YOUR python installation.

I.e.,

Change: "python.pythonPath": "python"

To: "python.pythonPath": "C:\\Python36\\python.exe"

And then: Save and reload Visual Studio Code.

Now when you get the prompt telling you that "Linter pylint is not installed", just select the option to 'install pylint'.

Since you've now provided the correct path to your Python installation, the Pylint installation will be successfully completed in the Windows PowerShell Terminal.

Can I redirect the stdout in python into some sort of string buffer?

This method restores sys.stdout even if there's an exception. It also gets any output before the exception.

import io
import sys

real_stdout = sys.stdout
fake_stdout = io.BytesIO()   # or perhaps io.StringIO()
try:
    sys.stdout = fake_stdout
    # do what you have to do to create some output
finally:
    sys.stdout = real_stdout
    output_string = fake_stdout.getvalue()
    fake_stdout.close()
    # do what you want with the output_string

Tested in Python 2.7.10 using io.BytesIO()

Tested in Python 3.6.4 using io.StringIO()


Bob, added for a case if you feel anything from the modified / extended code experimentation might get interesting in any sense, otherwise feel free to delete it

Ad informandum ... a few remarks from extended experimentation during finding some viable mechanics to "grab" outputs, directed by numexpr.print_versions() directly to the <stdout> ( upon a need to clean GUI and collecting details into debugging-report )

# THIS WORKS AS HELL: as Bob Stein proposed years ago:
#  py2 SURPRISEDaBIT:
#
import io
import sys
#
real_stdout = sys.stdout                        #           PUSH <stdout> ( store to REAL_ )
fake_stdout = io.BytesIO()                      #           .DEF FAKE_
try:                                            # FUSED .TRY:
    sys.stdout.flush()                          #           .flush() before
    sys.stdout = fake_stdout                    #           .SET <stdout> to use FAKE_
    # ----------------------------------------- #           +    do what you gotta do to create some output
    print 123456789                             #           + 
    import  numexpr                             #           + 
    QuantFX.numexpr.__version__                 #           + [3] via fake_stdout re-assignment, as was bufferred + "late" deferred .get_value()-read into print, to finally reach -> real_stdout
    QuantFX.numexpr.print_versions()            #           + [4] via fake_stdout re-assignment, as was bufferred + "late" deferred .get_value()-read into print, to finally reach -> real_stdout
    _ = os.system( 'echo os.system() redir-ed' )#           + [1] via real_stdout                                 + "late" deferred .get_value()-read into print, to finally reach -> real_stdout, if not ( _ = )-caught from RET-d "byteswritten" / avoided from being injected int fake_stdout
    _ = os.write(  sys.stderr.fileno(),         #           + [2] via      stderr                                 + "late" deferred .get_value()-read into print, to finally reach -> real_stdout, if not ( _ = )-caught from RET-d "byteswritten" / avoided from being injected int fake_stdout
                       b'os.write()  redir-ed' )#  *OTHERWISE, if via fake_stdout, EXC <_io.BytesIO object at 0x02C0BB10> Traceback (most recent call last):
    # ----------------------------------------- #           ?                              io.UnsupportedOperation: fileno
    #'''                                                    ? YET:        <_io.BytesIO object at 0x02C0BB10> has a .fileno() method listed
    #>>> 'fileno' in dir( sys.stdout )       -> True        ? HAS IT ADVERTISED,
    #>>> pass;            sys.stdout.fileno  -> <built-in method fileno of _io.BytesIO object at 0x02C0BB10>
    #>>> pass;            sys.stdout.fileno()-> Traceback (most recent call last):
    #                                             File "<stdin>", line 1, in <module>
    #                                           io.UnsupportedOperation: fileno
    #                                                       ? BUT REFUSES TO USE IT
    #'''
finally:                                        # == FINALLY:
    sys.stdout.flush()                          #           .flush() before ret'd back REAL_
    sys.stdout = real_stdout                    #           .SET <stdout> to use POP'd REAL_
    sys.stdout.flush()                          #           .flush() after  ret'd back REAL_
    out_string = fake_stdout.getvalue()         #           .GET string           from FAKE_
    fake_stdout.close()                         #                <FD>.close()
    # +++++++++++++++++++++++++++++++++++++     # do what you want with the out_string
    #
    print "\n{0:}\n{1:}{0:}".format( 60 * "/\\",# "LATE" deferred print the out_string at the very end reached -> real_stdout
                                     out_string #                   
                                     )
'''
PASS'd:::::
...
os.system() redir-ed
os.write()  redir-ed
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
123456789
'2.5'
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Numexpr version:   2.5
NumPy version:     1.10.4
Python version:    2.7.13 |Anaconda 4.0.0 (32-bit)| (default, May 11 2017, 14:07:41) [MSC v.1500 32 bit (Intel)]
AMD/Intel CPU?     True
VML available?     True
VML/MKL version:   Intel(R) Math Kernel Library Version 11.3.1 Product Build 20151021 for 32-bit applications
Number of threads used by default: 4 (out of 4 detected cores)
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
>>>

EXC'd :::::
...
os.system() redir-ed
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
123456789
'2.5'
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Numexpr version:   2.5
NumPy version:     1.10.4
Python version:    2.7.13 |Anaconda 4.0.0 (32-bit)| (default, May 11 2017, 14:07:41) [MSC v.1500 32 bit (Intel)]
AMD/Intel CPU?     True
VML available?     True
VML/MKL version:   Intel(R) Math Kernel Library Version 11.3.1 Product Build 20151021 for 32-bit applications
Number of threads used by default: 4 (out of 4 detected cores)
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\

Traceback (most recent call last):
  File "<stdin>", line 9, in <module>
io.UnsupportedOperation: fileno
'''

Correctly determine if date string is a valid date in that format

/*********************************************************************************
Returns TRUE if the input parameter is a valid date string in "YYYY-MM-DD" format (aka "MySQL date format")
The date separator can be only the '-' character.
*********************************************************************************/
function isMysqlDate($yyyymmdd)
{
    return checkdate(substr($yyyymmdd, 5, 2), substr($yyyymmdd, 8), substr($yyyymmdd, 0, 4)) 
        && (substr($yyyymmdd, 4, 1) === '-') 
        && (substr($yyyymmdd, 7, 1) === '-');
}

How do I prevent Eclipse from hanging on startup?

In my case similar symptoms were caused by some rogue git repository with a ton of junk system files.

Universal remedy, as mentioned above, is to use Process Monitor to discover offending files. It's useful to set the following 2-line filter:

  • Process Name is eclipse.exe
  • Process Name is javaw.exe

Extend contigency table with proportions (percentages)

If it's conciseness you're after, you might like:

prop.table(table(tips$smoker))

and then scale by 100 and round if you like. Or more like your exact output:

tbl <- table(tips$smoker)
cbind(tbl,prop.table(tbl))

If you wanted to do this for multiple columns, there are lots of different directions you could go depending on what your tastes tell you is clean looking output, but here's one option:

tblFun <- function(x){
    tbl <- table(x)
    res <- cbind(tbl,round(prop.table(tbl)*100,2))
    colnames(res) <- c('Count','Percentage')
    res
}

do.call(rbind,lapply(tips[3:6],tblFun))
       Count Percentage
Female    87      35.66
Male     157      64.34
No       151      61.89
Yes       93      38.11
Fri       19       7.79
Sat       87      35.66
Sun       76      31.15
Thur      62      25.41
Dinner   176      72.13
Lunch     68      27.87

If you don't like stack the different tables on top of each other, you can ditch the do.call and leave them in a list.

toggle show/hide div with button?

Here's a plain Javascript way of doing toggle:

<script>
  var toggle = function() {
  var mydiv = document.getElementById('newpost');
  if (mydiv.style.display === 'block' || mydiv.style.display === '')
    mydiv.style.display = 'none';
  else
    mydiv.style.display = 'block'
  }
</script>

<div id="newpost">asdf</div>
<input type="button" value="btn" onclick="toggle();">

Access Form - Syntax error (missing operator) in query expression

I had this on a form where the Recordsource is dynamic.

The Sql was fine, answer is to trap the error!

Private Sub Form_Error(DataErr As Integer, Response As Integer)
'    Debug.Print DataErr

    If DataErr = 3075 Then
        Response = acDataErrContinue
    End If

End Sub

Selecting multiple items in ListView

In listView you can use it by Adapter

ArrayAdapter<String> adapterChannels = new ArrayAdapter<>(this, android.R.layout.simple_list_item_multiple_choice);

How to install the Raspberry Pi cross compiler on my Linux host machine?

there is a CDP Studio IDE available that makes cross compile and deploy quite simple from both windows and linux and you can just check the raspberry toolchain checkbox during the installation. (PS. it has GPIO and I2C support so no code is needed to access those)

The IDE demo of raspberry use is up here: https://youtu.be/4SVZ68sQz5U

and you can download the IDE here: https://cdpstudio.com/home-edition

What is the default Precision and Scale for a Number in Oracle?

Actually, you can always test it by yourself.

CREATE TABLE CUSTOMERS ( CUSTOMER_ID NUMBER NOT NULL, JOIN_DATE DATE NOT NULL, CUSTOMER_STATUS VARCHAR2(8) NOT NULL, CUSTOMER_NAME VARCHAR2(20) NOT NULL, CREDITRATING VARCHAR2(10) ) ;

select column_name, data_type, nullable, data_length, data_precision, data_scale from user_tab_columns where table_name ='CUSTOMERS';

AngularJS - get element attributes values

the .data() method is from jQuery. If you want to use this method you need to include the jQuery library and access the method like this:

function doStuff(item) {
  var id = $(item).data('id');
}

I also updated your jsFiffle

UPDATE

with pure angularjs and the jqlite you can achieve the goal like this:

function doStuff(item) {
  var id = angular.element(item).data('id');
}

You must not access the element with [] because then you get the pure DOM element without all the jQuery or jqlite extra methods.

What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?

__func__ is an implicitly declared identifier that expands to a character array variable containing the function name when it is used inside of a function. It was added to C in C99. From C99 §6.4.2.2/1:

The identifier __func__ is implicitly declared by the translator as if, immediately following the opening brace of each function definition, the declaration

static const char __func__[] = "function-name";

appeared, where function-name is the name of the lexically-enclosing function. This name is the unadorned name of the function.

Note that it is not a macro and it has no special meaning during preprocessing.

__func__ was added to C++ in C++11, where it is specified as containing "an implementation-de?ned string" (C++11 §8.4.1[dcl.fct.def.general]/8), which is not quite as useful as the specification in C. (The original proposal to add __func__ to C++ was N1642).

__FUNCTION__ is a pre-standard extension that some C compilers support (including gcc and Visual C++); in general, you should use __func__ where it is supported and only use __FUNCTION__ if you are using a compiler that does not support it (for example, Visual C++, which does not support C99 and does not yet support all of C++0x, does not provide __func__).

__PRETTY_FUNCTION__ is a gcc extension that is mostly the same as __FUNCTION__, except that for C++ functions it contains the "pretty" name of the function including the signature of the function. Visual C++ has a similar (but not quite identical) extension, __FUNCSIG__.

For the nonstandard macros, you will want to consult your compiler's documentation. The Visual C++ extensions are included in the MSDN documentation of the C++ compiler's "Predefined Macros". The gcc documentation extensions are described in the gcc documentation page "Function Names as Strings."

Restore a deleted file in the Visual Studio Code Recycle Bin

If you just deleted the file, know that VSCode 1.52 (Dec. 2020) will support:

Undo file operations in Explorer

Explorer now supports Undo and Redo for all file operations: delete, rename, copy, move, new file and new folder.

Make sure the focus is in the Explorer and trigger the Undo or Redo commands and your last file operation will be undone or redone respectively.
Keep in mind that we have separate undo stacks for the editor and the explorer and we choose which one to undo based on focus.

Explorer Undo -- https://media.githubusercontent.com/media/microsoft/vscode-docs/vnext/release-notes/images/1_52/explorer-undo.gif

Java Runtime.getRuntime(): getting output from executing a command line program

At the time of this writing, all other answers that include code may result in deadlocks.

Processes have a limited buffer for stdout and stderr output. If you don't listen to them concurrently, one of them will fill up while you are trying reading the other. For example, you could be waiting to read from stdout while the process is waiting to write to stderr. You cannot read from the stdout buffer because it is empty and the process cannot write to the stderr buffer because it is full. You are each waiting on each other forever.

Here is a possible way to read the output of a process without a risk of deadlocks:

public final class Processes
{
    private static final String NEWLINE = System.getProperty("line.separator");

    /**
     * @param command the command to run
     * @return the output of the command
     * @throws IOException if an I/O error occurs
     */
    public static String run(String... command) throws IOException
    {
        ProcessBuilder pb = new ProcessBuilder(command).redirectErrorStream(true);
        Process process = pb.start();
        StringBuilder result = new StringBuilder(80);
        try (BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())))
        {
            while (true)
            {
                String line = in.readLine();
                if (line == null)
                    break;
                result.append(line).append(NEWLINE);
            }
        }
        return result.toString();
    }

    /**
     * Prevent construction.
     */
    private Processes()
    {
    }
}

The key is to use ProcessBuilder.redirectErrorStream(true) which will redirect stderr into the stdout stream. This allows you to read a single stream without having to alternate between stdout and stderr. If you want to implement this manually, you will have to consume the streams in two different threads to make sure you never block.

Sorting HTML table with JavaScript

Here is a complete example using pure JavaScript. The algorithm used for sorting is basically BubbleSort. Here is a Fiddle.

   <!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">

<script type="text/javascript">
    function sort(ascending, columnClassName, tableId) {
        var tbody = document.getElementById(tableId).getElementsByTagName(
                "tbody")[0];
        var rows = tbody.getElementsByTagName("tr");

        var unsorted = true;

        while (unsorted) {
            unsorted = false

            for (var r = 0; r < rows.length - 1; r++) {
                var row = rows[r];
                var nextRow = rows[r + 1];

                var value = row.getElementsByClassName(columnClassName)[0].innerHTML;
                var nextValue = nextRow.getElementsByClassName(columnClassName)[0].innerHTML;

                value = value.replace(',', '.'); // in case a comma is used in float number
                nextValue = nextValue.replace(',', '.');

                if (!isNaN(value)) {
                    value = parseFloat(value);
                    nextValue = parseFloat(nextValue);
                }

                if (ascending ? value > nextValue : value < nextValue) {
                    tbody.insertBefore(nextRow, row);
                    unsorted = true;
                }
            }
        }
    };
</script>
</head>
<body>
    <table id="content-table">
        <thead>
            <tr>
                <th class="id">ID <a
                    href="javascript:sort(true, 'id', 'content-table');">asc</a> <a
                    href="javascript:sort(false, 'id', 'content-table');">des</a>
                </th>
                <th class="country">Country <a
                    href="javascript:sort(true, 'country', 'content-table');">asc</a> <a
                    href="javascript:sort(false, 'country', 'content-table');">des</a>
                </th>
                <th class="some-fact">Some fact <a
                    href="javascript:sort(true, 'some-fact', 'content-table');">asc</a>
                    <a href="javascript:sort(false, 'some-fact', 'content-table');">des</a>
                <th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td class="id">001</td>
                <td class="country">Germany</td>
                <td class="some-fact">16.405</td>
            </tr>
            <tr>
                <td class="id">002</td>
                <td class="country">France</td>
                <td class="some-fact">10.625</td>
            </tr>
            <tr>
                <td class="id">003</td>
                <td class="country">UK</td>
                <td class="some-fact">15.04</td>
            </tr>
            <tr>
                <td class="id">004</td>
                <td class="country">China</td>
                <td class="some-fact">13.536</td>
            </tr>
        </tbody>
    </table>
</body>
</html>

You can also check out the source from here: https://github.com/wmentzel/table-sort

New Array from Index Range Swift

subscript

extension Array where Element : Equatable {
  public subscript(safe bounds: Range<Int>) -> ArraySlice<Element> {
    if bounds.lowerBound > count { return [] }
    let lower = Swift.max(0, bounds.lowerBound)
    let upper = Swift.max(0, Swift.min(count, bounds.upperBound))
    return self[lower..<upper]
  }
  
  public subscript(safe lower: Int?, _ upper: Int?) -> ArraySlice<Element> {
    let lower = lower ?? 0
    let upper = upper ?? count
    if lower > upper { return [] }
    return self[safe: lower..<upper]
  }
}

returns a copy of this range clamped to the given limiting range.

var arr = [1, 2, 3]
    
arr[safe: 0..<1]    // returns [1]  assert(arr[safe: 0..<1] == [1])
arr[safe: 2..<100]  // returns [3]  assert(arr[safe: 2..<100] == [3])
arr[safe: -100..<0] // returns []   assert(arr[safe: -100..<0] == [])

arr[safe: 0, 1]     // returns [1]  assert(arr[safe: 0, 1] == [1])
arr[safe: 2, 100]   // returns [3]  assert(arr[safe: 2, 100] == [3])
arr[safe: -100, 0]  // returns []   assert(arr[safe: -100, 0] == [])

How can I export data to an Excel file

I was also struggling with a similar issue dealing with exporting data into an Excel spreadsheet using C#. I tried many different methods working with external DLLs and had no luck.

For the export functionality you do not need to use anything dealing with the external DLLs. Instead, just maintain the header and content type of the response.

Here is an article that I found rather helpful. The article talks about how to export data to Excel spreadsheets using ASP.NET.

http://www.icodefor.net/2016/07/export-data-to-excel-sheet-in-asp-dot-net-c-sharp.html

Android Studio-No Module

If you have imported the project, you may have to re-import it the proper way.
Steps :

  1. Close Android Studio. Take backup of the project from C:\Users\UserName\AndroidStudioProjects\YourProject to some other folder . Now delete the project.
  2. Launch Android Studio and click "Import Non-AndroidStudio Project (even if the project to be imported is an AndroidStudio project).
  3. Select only the root folder of the project to be imported. Set the destination directory. Keep all the options checked. AndroidStudio will prompt to make some changes, click Ok for all prompts.
  4. Now you can see the Module pre-defined at the top and you can launch the app to the emulator.

Tested on AndroidStudio version 1.0.1

Can I pass variable to select statement as column name in SQL Server

You can't use variable names to bind columns or other system objects, you need dynamic sql

DECLARE @value varchar(10)  
SET @value = 'intStep'  
DECLARE @sqlText nvarchar(1000); 

SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)

Django Cookies, how can I set them?

Using Django's session framework should cover most scenarios, but Django also now provide direct cookie manipulation methods on the request and response objects (so you don't need a helper function).

Setting a cookie:

def view(request):
  response = HttpResponse('blah')
  response.set_cookie('cookie_name', 'cookie_value')

Retrieving a cookie:

def view(request):
  value = request.COOKIES.get('cookie_name')
  if value is None:
    # Cookie is not set

  # OR

  try:
    value = request.COOKIES['cookie_name']
  except KeyError:
    # Cookie is not set

IIS7 Permissions Overview - ApplicationPoolIdentity

Remember to use the server's local name, not the domain name, when resolving the name

IIS AppPool\DefaultAppPool

(just a reminder because this tripped me up for a bit):enter image description here

MongoDB not equal to

From the Mongo docs:

The $not operator only affects other operators and cannot check fields and documents independently. So, use the $not operator for logical disjunctions and the $ne operator to test the contents of fields directly.

Since you are testing the field directly $ne is the right operator to use here.

Edit:

A situation where you would like to use $not is:

db.inventory.find( { price: { $not: { $gt: 1.99 } } } )

That would select all documents where:

  • The price field value is less than or equal to 1.99 or the price
  • Field does not exist

Remove part of a string

Maybe the most intuitive solution is probably to use the stringr function str_remove which is even easier than str_replace as it has only 1 argument instead of 2.

The only tricky part in your example is that you want to keep the underscore but its possible: You must match the regular expression until it finds the specified string pattern (?=pattern).

See example:

strings = c("TGAS_1121", "MGAS_1432", "ATGAS_1121")
strings %>% stringr::str_remove(".+?(?=_)")

[1] "_1121" "_1432" "_1121"

Send SMTP email using System.Net.Mail via Exchange Online (Office 365)

Here is a side note for some that may be searching this thread for an answer to this problem. (Be sure to read cautions at the bottom before implementing this solution.) I was having trouble sending emails for a client to which my MS Office 365 subscription did not have a user or domain for. I was trying to SMTP through my [email protected] 365 account but the .NET mail message was addressed from [email protected]. This is when the "5.7.1 Client does not have permissions" error popped up for me. To remedy, the MailMessage class needed to have the Sender property set to an email address that my supplied SMTP credentials had permission in O365 to "Send As". I chose to use my main account email ([email protected]) as seen in the code below. Keep in mind I could have used ANY email address my O365 account had permission to "send as" (i.e. [email protected], [email protected], etc.)

using System;
using System.Net.Mail;

namespace ConsoleApplication1
{
   class Program
   {
      static void Main(string[] args)
      {
         using (
            MailMessage message = new MailMessage
            {
               To = { new MailAddress("[email protected]", "Recipient 1") },
               Sender = new MailAddress("[email protected]", "Me"),
               From = new MailAddress("[email protected]", "Client"),
               Subject=".net Testing"
               Body="Testing .net emailing",
               IsBodyHtml=true,
            }
         )
         {
            using (
               SmtpClient smtp = new SmtpClient
               {
                  Host = "smtp.office365.com",
                  Port = 587,
                  Credentials = new System.Net.NetworkCredential("[email protected]", "Pa55w0rd"),
                  EnableSsl = true
               }
            )
            {
               try { smtp.Send(message); }
               catch (Exception excp)
               {
                  Console.Write(excp.Message);
                  Console.ReadKey();
               }
            }
         }
      }
   }
}

Please note SmtpClient is only disposable and able to use the Using block in .NET Framework 4
Users of .NET Framework 2 through 3.5 should use SmtpClient as such...

SmtpClient smtp = new SmtpClient
{
   Host = "smtp.office365.com",
   Port = 587,
   Credentials = new System.Net.NetworkCredential("[email protected]", "Pa55w0rd"),
   EnableSsl = true
};
try { smtp.Send(message); }
catch (Exception excp)
{
   Console.Write(excp.Message);
   Console.ReadKey();
}

The resulting email's header will look something like this:

Authentication-Results: spf=none (sender IP is )  
   [email protected];  
Received: from MyPC (192.168.1.1) by  
   BLUPR13MB0036.namprd13.prod.outlook.com (10.161.123.150) with Microsoft SMTP  
   Server (TLS) id 15.1.318.9; Mon, 9 Nov 2015 16:06:58 +0000  
MIME-Version: 1.0  
From: Client <[email protected]>  
Sender: Me <[email protected]>  
To: Recipient 1 <[email protected]>  

-- Be Cautious --
Be aware some mail clients may display the Sender address as a note. For example Outlook will display something along these lines in the Reading Pane's header:

Me <[email protected]> on behalf of Client <[email protected]>

However, so long as the email client the recipient uses isn't total garbage, this shouldn't effect the Reply To address. Reply To should still use the From address. To cover all your bases, you can also utilize the MailMessage.ReplyToList property to afford every opportunity to the client to use the correct reply address.

Also, be aware that some email servers may flat out reject any emails that are Sent On Behalf of another company siting Domain Owner Policy Restrictions. Be sure to test thoroughly and look for any bounce backs. I can tell you that my personal Hotmail (mail.live.com) email account is one that will reject messages I send on behalf of a certain client of mine but others clients go through fine. Although I suspect that it has something to do with my client's domain TXT "spf1" records, I do not have an answer as to why it will reject emails sent on behalf of one domain versus another. Maybe someone who knows can shed some light on the subject?

Comparing two maps

Quick Answer

You should use the equals method since this is implemented to perform the comparison you want. toString() itself uses an iterator just like equals but it is a more inefficient approach. Additionally, as @Teepeemm pointed out, toString is affected by order of elements (basically iterator return order) hence is not guaranteed to provide the same output for 2 different maps (especially if we compare two different maps).

Note/Warning: Your question and my answer assume that classes implementing the map interface respect expected toString and equals behavior. The default java classes do so, but a custom map class needs to be examined to verify expected behavior.

See: http://docs.oracle.com/javase/7/docs/api/java/util/Map.html

boolean equals(Object o)

Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings. More formally, two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.

Implementation in Java Source (java.util.AbstractMap)

Additionally, java itself takes care of iterating through all elements and making the comparison so you don't have to. Have a look at the implementation of AbstractMap which is used by classes such as HashMap:

 // Comparison and hashing

    /**
     * Compares the specified object with this map for equality.  Returns
     * <tt>true</tt> if the given object is also a map and the two maps
     * represent the same mappings.  More formally, two maps <tt>m1</tt> and
     * <tt>m2</tt> represent the same mappings if
     * <tt>m1.entrySet().equals(m2.entrySet())</tt>.  This ensures that the
     * <tt>equals</tt> method works properly across different implementations
     * of the <tt>Map</tt> interface.
     *
     * <p>This implementation first checks if the specified object is this map;
     * if so it returns <tt>true</tt>.  Then, it checks if the specified
     * object is a map whose size is identical to the size of this map; if
     * not, it returns <tt>false</tt>.  If so, it iterates over this map's
     * <tt>entrySet</tt> collection, and checks that the specified map
     * contains each mapping that this map contains.  If the specified map
     * fails to contain such a mapping, <tt>false</tt> is returned.  If the
     * iteration completes, <tt>true</tt> is returned.
     *
     * @param o object to be compared for equality with this map
     * @return <tt>true</tt> if the specified object is equal to this map
     */
    public boolean equals(Object o) {
        if (o == this)
            return true;

        if (!(o instanceof Map))
            return false;
        Map<K,V> m = (Map<K,V>) o;
        if (m.size() != size())
            return false;

        try {
            Iterator<Entry<K,V>> i = entrySet().iterator();
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                K key = e.getKey();
                V value = e.getValue();
                if (value == null) {
                    if (!(m.get(key)==null && m.containsKey(key)))
                        return false;
                } else {
                    if (!value.equals(m.get(key)))
                        return false;
                }
            }
        } catch (ClassCastException unused) {
            return false;
        } catch (NullPointerException unused) {
            return false;
        }

        return true;
    }

Comparing two different types of Maps

toString fails miserably when comparing a TreeMap and HashMap though equals does compare contents correctly.

Code:

public static void main(String args[]) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("2", "whatever2");
map.put("1", "whatever1");
TreeMap<String, Object> map2 = new TreeMap<String, Object>();
map2.put("2", "whatever2");
map2.put("1", "whatever1");

System.out.println("Are maps equal (using equals):" + map.equals(map2));
System.out.println("Are maps equal (using toString().equals()):"
        + map.toString().equals(map2.toString()));

System.out.println("Map1:"+map.toString());
System.out.println("Map2:"+map2.toString());
}

Output:

Are maps equal (using equals):true
Are maps equal (using toString().equals()):false
Map1:{2=whatever2, 1=whatever1}
Map2:{1=whatever1, 2=whatever2}

How to create a new schema/new user in Oracle Database 11g?

It's a working example:

CREATE USER auto_exchange IDENTIFIED BY 123456;
GRANT RESOURCE TO auto_exchange;
GRANT CONNECT TO auto_exchange;
GRANT CREATE VIEW TO auto_exchange;
GRANT CREATE SESSION TO auto_exchange;
GRANT UNLIMITED TABLESPACE TO auto_exchange;

C# Java HashMap equivalent

Check out the documentation on MSDN for the Hashtable class.

Represents a collection of key-and-value pairs that are organized based on the hash code of the key.

Also, keep in mind that this is not thread-safe.

Set environment variables from file of key/value pairs

set -a
. ./env.txt
set +a

If env.txt is like:

VAR1=1
VAR2=2
VAR3=3
...

Explanations -a is equivalent to allexport. In other words, every variable assignment in the shell is exported into the environment (to be used by multiple child processes). More information can be found in the Set builtin documentation:

-a     Each variable or function that is created or modified is given the export attribute and marked for export to the environment of subsequent commands.

Using ‘+’ rather than ‘-’ causes these options to be turned off. The options can also be used upon invocation of the shell. The current set of options may be found in $-.

Hide axis and gridlines Highcharts

Just add

xAxis: {
   ...  
   lineWidth: 0,
   minorGridLineWidth: 0,
   lineColor: 'transparent',
   ...          
   labels: {
       enabled: false
   },
   minorTickLength: 0,
   tickLength: 0
}

to the xAxis definition.

Since Version 4.1.9 you can simply use the axis attribute visible:

xAxis: {
    visible: false,
}

How can I remove the last character of a string in python?

As you say, you don't need to use a regex for this. You can use rstrip.

my_file_path = my_file_path.rstrip('/')

If there is more than one / at the end, this will remove all of them, e.g. '/file.jpg//' -> '/file.jpg'. From your question, I assume that would be ok.

How to change a table name using an SQL query?

In MySQL :

RENAME TABLE template_function TO business_function;

Run/install/debug Android applications over Wi-Fi?

See forum post Any way to view Android screen remotely without root? - Post #9.

  1. Connect the device via USB and make sure debugging is working;
  2. adb tcpip 5555. This makes the device to start listening for connections on port 5555;
  3. Look up the device IP address with adb shell netcfg or adb shell ifconfig with 6.0 and higher;
  4. You can disconnect the USB now;
  5. adb connect <DEVICE_IP_ADDRESS>:5555. This connects to the server we set up on the device on step 2;
  6. Now you have a device over the network with which you can debug as usual.

To switch the server back to the USB mode, run adb usb, which will put the server on your phone back to the USB mode. If you have more than one device, you can specify the device with the -s option: adb -s <DEVICE_IP_ADDRESS>:5555 usb.

No root required!

To find the IP address of the device: run adb shell and then netcfg. You'll see it there. To find the IP address while using OSX run the command adb shell ip route.


WARNING: leaving the option enabled is dangerous, anyone in your network can connect to your device in debug, even if you are in data network. Do it only when connected to a trusted Wi-Fi and remember to disconnect it when done!


@Sergei suggested that line 2 should be modified, commenting: "-d option needed to connect to the USB device when the other connection persists (for example, emulator connected or other Wi-Fi device)".

This information may prove valuable to future readers, but I rolled-back to the original version that had received 178 upvotes.


On some device you can do the same thing even if you do not have an USB cable:

  1. Enable ADB over network in developer setting Screenshot Showing the option on It should show the IP address
  2. adb connect <DEVICE_IP_ADDRESS>:5555
  3. Disable the setting when done

Using Android Studio there is a plugin allowing you to connect USB Debugging without the need of using any ADB command from a terminal.

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

There are several ways to synchronize access to a static variable.

  1. Use a synchronized static method. This synchronizes on the class object.

    public class Test {
        private static int count = 0;
    
        public static synchronized void incrementCount() {
            count++;
        }
    } 
    
  2. Explicitly synchronize on the class object.

    public class Test {
        private static int count = 0;
    
        public void incrementCount() {
            synchronized (Test.class) {
                count++;
            }
        }
    } 
    
  3. Synchronize on some other static object.

    public class Test {
        private static int count = 0;
        private static final Object countLock = new Object();
    
        public void incrementCount() {
            synchronized (countLock) {
                count++;
            }
        }
    } 
    

Method 3 is the best in many cases because the lock object is not exposed outside of your class.

How do I find out what keystore my JVM is using?

In addition to all answers above:

If updating the cacerts file in JRE directory doesn't help, try to update it in JDK.

C:\Program Files\Java\jdk1.8.0_192\jre\lib\security

Remove Identity from a column in a table

I just had this same problem. 4 statements in SSMS instead of using the GUI and it was very fast.

  • Make a new column

    alter table users add newusernum int;

  • Copy values over

    update users set newusernum=usernum;

  • Drop the old column

    alter table users drop column usernum;

  • Rename the new column to the old column name

    EXEC sp_RENAME 'users.newusernum' , 'usernum', 'COLUMN';

How to add a single item to a Pandas Series

  • ser1 = pd.Sereis(np.linspace(1, 10, 2))
  • element = np.nan
  • ser1 = ser1.append(pd.Series(element))

Right Align button in horizontal LinearLayout

try this one

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

  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
   android:layout_height="wrap_content"   
   android:orientation="horizontal" >

<TextView
    android:id="@+id/lblExpenseCancel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    android:layout_marginTop="9dp"
    android:text="cancel"
    android:textColor="#ffff0000"
    android:textSize="20sp" />

<Button
    android:id="@+id/btnAddExpense"
    android:layout_width="wrap_content"
    android:layout_height="45dp"
    android:layout_alignParentRight="true"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="15dp"
     android:textColor="#ff0000ff"
    android:text="add" />

 </RelativeLayout>
  </LinearLayout>

How do I write out a text file in C# with a code page other than UTF-8?

Wrap your StreamWriter with FileStream, this way:

string fileName = "test.txt";
string textToAdd = "Example text in file";
Encoding encoding = Encoding.GetEncoding("ISO-8859-1"); //Or any other Encoding

using (FileStream fs = new FileStream(fileName, FileMode.CreateNew))
{
    using (StreamWriter writer = new StreamWriter(fs, encoding))
    {
        writer.Write(textToAdd);
    }
}

Look at MSDN

What are all the common ways to read a file in Ruby?

An even more efficient way is streaming by asking the operating system’s kernel to open a file, then read bytes from it bit by bit. When reading a file per line in Ruby, data is taken from the file 512 bytes at a time and split up in “lines” after that.

By buffering the file’s content, the number of I/O calls is reduced while dividing the file in logical chunks.

Example:

Add this class to your app as a service object:

class MyIO
  def initialize(filename)
    fd = IO.sysopen(filename)
    @io = IO.new(fd)
    @buffer = ""
  end

  def each(&block)
    @buffer << @io.sysread(512) until @buffer.include?($/)

    line, @buffer = @buffer.split($/, 2)

    block.call(line)
    each(&block)
  rescue EOFError
    @io.close
 end
end

Call it and pass the :each method a block:

filename = './somewhere/large-file-4gb.txt'
MyIO.new(filename).each{|x| puts x }

Read about it here in this detailed post:

Ruby Magic Slurping & Streaming Files By AppSignal

Java string split with "." (dot)

I believe you should escape the dot. Try:

String filename = "D:/some folder/001.docx";
String extensionRemoved = filename.split("\\.")[0];

Otherwise dot is interpreted as any character in regular expressions.

How to check if one DateTime is greater than the other in C#

I'd like to demonstrate that if you convert to .Date that you don't need to worry about hours/mins/seconds etc:

    [Test]
    public void ConvertToDateWillHaveTwoDatesEqual()
    {
        DateTime d1 = new DateTime(2008, 1, 1);
        DateTime d2 = new DateTime(2008, 1, 2);
        Assert.IsTrue(d1 < d2);

        DateTime d3 = new DateTime(2008, 1, 1,7,0,0);
        DateTime d4 = new DateTime(2008, 1, 1,10,0,0);
        Assert.IsTrue(d3 < d4);
        Assert.IsFalse(d3.Date < d4.Date);
    }

How to check if an element is in an array

Swift 2, 3, 4, 5:

let elements = [1, 2, 3, 4, 5]
if elements.contains(5) {
    print("yes")
}

contains() is a protocol extension method of SequenceType (for sequences of Equatable elements) and not a global method as in earlier releases.

Remarks:

Swift older versions:

let elements = [1,2,3,4,5]
if contains(elements, 5) {
    println("yes")
}

What HTTP traffic monitor would you recommend for Windows?

I use Wireshark in most cases, but I have found Fiddler to be less of a hassle when dealing with encrypted data.

Android - SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length

Masood Moshref is right, this error occur because the option menu of Menu is not well prepared by lacking "return super.onCreateOptionsMenu(menu)" in onCreate() method.

Difference between View and table in sql

Table: Table is a preliminary storage for storing data and information in RDBMS. A table is a collection of related data entries and it consists of columns and rows.

View: A view is a virtual table whose contents are defined by a query. Unless indexed, a view does not exist as a stored set of data values in a database. Advantages over table are

  • We can combine columns/rows from multiple table or another view and have a consolidated view.
  • Views can be used as security mechanisms by letting users access data through the view, without granting the users permissions to directly access the underlying base tables of the view
  • It acts as abstract layer to downstream systems, so any change in schema is not exposed and hence the downstream systems doesn't get affected.

ReactJS SyntheticEvent stopPropagation() only works with React events?

From the React documentation: The event handlers below are triggered by an event in the bubbling phase. To register an event handler for the capture phase, append Capture. (emphasis added)

If you have a click event listener in your React code and you don't want it to bubble up, I think what you want to do is use onClickCapture instead of onClick. Then you would pass the event to the handler and do event.nativeEvent.stopPropagation() to keep the native event from bubbling up to a vanilla JS event listener (or anything that's not react).

CodeIgniter - Correct way to link to another page in a view

I assume you are meaning "internally" within your application.

you can create your own <a> tag and insert a url in the href like this

<a href="<?php echo site_url('controller/function/uri') ?>">Link</a>

OR you can use the URL helper this way to generate an <a> tag

anchor(uri segments, text, attributes)

So... to use it...

<?php echo anchor('controller/function/uri', 'Link', 'class="link-class"') ?>

and that will generate

<a href="http://domain.com/index.php/controller/function/uri" class="link-class">Link</a>

For the additional commented question

I would use my first example

so...

<a href="<?php echo site_url('controller/function') ?>"><img src="<?php echo base_url() ?>img/path/file.jpg" /></a>

for images (and other assets) I wouldn't put the file path within the php, I would just echo the base_url() and then add the path normally.

HTML5 - mp4 video does not play in IE9

If any of these answers above don't work, and you're on an apache server, adding the following to your .htaccess file:

//most of the common formats, add any that apply
AddType video/mp4 .mp4 
AddType audio/mp4 .m4a
AddType video/mp4 .m4v
AddType video/ogg .ogv 
AddType video/ogg .ogg
AddType video/webm .webm

I had a similar problem and adding this solved all my playback issues.

How to convert a Collection to List?

I believe you can write it as such:

coll.stream().collect(Collectors.toList())

Amazon S3 exception: "The specified key does not exist"

I also ran into this issue, but in my case I was inadvertently changing the internal state of my source object key when constructing the destination key:

  source_objects.each do |item|
    key = item.key.sub!(source_prefix, dest_prefix)
    item.copy_to(bucket: dest_bucket, key: key)
  end

I'm new to Ruby and missed that sub! has side effects and sub should have been used instead.

Close application and launch home screen on Android

You should really think about not exiting the application. This is not how Android apps usually work.

Vertically aligning a checkbox

The most effective solution that I found is to define the parent element with display:flex and align-items:center

LIVE DEMO

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <style>
      .myclass{
        display:flex;
        align-items:center;
        background-color:grey;
        color:#fff;
        height:50px;
      }
    </style>
  </head>
  <body>
    <div class="myclass">
      <input type="checkbox">
      <label>do you love Ananas?
      </label>
    </div>
  </body>
</html>

OUTPUT:

enter image description here

datetime.parse and making it work with a specific format

DateTime.ParseExact(input,"yyyyMMdd HH:mm",null);

assuming you meant to say that minutes followed the hours, not seconds - your example is a little confusing.

The ParseExact documentation details other overloads, in case you want to have the parse automatically convert to Universal Time or something like that.

As @Joel Coehoorn mentions, there's also the option of using TryParseExact, which will return a Boolean value indicating success or failure of the operation - I'm still on .Net 1.1, so I often forget this one.

If you need to parse other formats, you can check out the Standard DateTime Format Strings.

Restore the mysql database from .frm files

After much trial and error I was able to get this working based on user359187 answer and this blog post.

To get my old .frm and .ibd transferred to a new MySQL database after copying the files over and assigning MySQL ownership, the key for me was to then log into MySQL and connect to the new database then let MySQL do the work by importing the tablespace.

mysql> connect test;
mysql> ALTER TABLE t1 IMPORT TABLESPACE;

This will import the data using the copied .frm and .ibd files.

I had to run the Alter command for each table separately but this worked and I was able to recover the tables and data.

Passing parameters to a Bash function

Knowledge of high level programming languages (C/C++, Java, PHP, Python, Perl, etc.) would suggest to the layman that Bourne Again Shell (Bash) functions should work like they do in those other languages.

Instead, Bash functions work like shell commands and expect arguments to be passed to them in the same way one might pass an option to a shell command (e.g. ls -l). In effect, function arguments in Bash are treated as positional parameters ($1, $2..$9, ${10}, ${11}, and so on). This is no surprise considering how getopts works. Do not use parentheses to call a function in Bash.


(Note: I happen to be working on OpenSolaris at the moment.)

# Bash style declaration for all you PHP/JavaScript junkies. :-)
# $1 is the directory to archive
# $2 is the name of the tar and zipped file when all is done.
function backupWebRoot ()
{
    tar -cvf - "$1" | zip -n .jpg:.gif:.png "$2" - 2>> $errorlog &&
        echo -e "\nTarball created!\n"
}


# sh style declaration for the purist in you. ;-)
# $1 is the directory to archive
# $2 is the name of the tar and zipped file when all is done.
backupWebRoot ()
{
    tar -cvf - "$1" | zip -n .jpg:.gif:.png "$2" - 2>> $errorlog &&
        echo -e "\nTarball created!\n"
}


# In the actual shell script
# $0               $1            $2

backupWebRoot ~/public/www/ webSite.tar.zip

Want to use names for variables? Just do something this.

local filename=$1 # The keyword declare can be used, but local is semantically more specific.

Be careful, though. If an argument to a function has a space in it, you may want to do this instead! Otherwise, $1 might not be what you think it is.

local filename="$1" # Just to be on the safe side. Although, if $1 was an integer, then what? Is that even possible? Humm.

Want to pass an array to a function?

callingSomeFunction "${someArray[@]}" # Expands to all array elements.

Inside the function, handle the arguments like this.

function callingSomeFunction ()
{
    for value in "$@" # You want to use "$@" here, not "$*" !!!!!
    do
        :
    done
}

Need to pass a value and an array, but still use "$@" inside the function?

function linearSearch ()
{
    local myVar="$1"

    shift 1 # Removes $1 from the parameter list

    for value in "$@" # Represents the remaining parameters.
    do
        if [[ $value == $myVar ]]
        then
            echo -e "Found it!\t... after a while."
            return 0
        fi
    done

    return 1
}

linearSearch $someStringValue "${someArray[@]}"

How can I wait for a thread to finish with .NET?

Try this:

List<Thread> myThreads = new List<Thread>();

foreach (Thread curThread in myThreads)
{
    curThread.Start();
}

foreach (Thread curThread in myThreads)
{
    curThread.Join();
}

Count multiple columns with group by in one query

You didn't say which database server you are using, but if temp tables are available they may be the best approach.

// table is a temp table
select ... into #table ....
SELECT COUNT(column1),column1 FROM #table GROUP BY column1  
SELECT COUNT(column2),column2 FROM #table GROUP BY column2  
SELECT COUNT(column3),column3 FROM #table GROUP BY column3  
// drop may not be required
drop table #table

Why is visible="false" not working for a plain html table?

Use display: none instead. Besides, this is probably what you need, because this also truncates the page by removing the space the table occupies, whereas visibility: hidden leaves the white space left by the table.

Select From all tables - MySQL

You get all tables containing the column product using this statment:

SELECT DISTINCT TABLE_NAME 
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE COLUMN_NAME IN ('Product')
        AND TABLE_SCHEMA='YourDatabase';

Then you have to run a cursor on these tables so you select eachtime:

Select * from OneTable where product like '%XYZ%'

The results should be entered into a 3rd table or view, take a look here.

Notice: This can work only if the structure of all table is similar, otherwise aou will have to see which columns are united for all these tables and create your result table / View to contain only these columns.

How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?

With IE6 / IE7 one can tweak the number of concurrent requests in the registry. Here's how to set it to four each.

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings]
"MaxConnectionsPerServer"=dword:00000004
"MaxConnectionsPer1_0Server"=dword:00000004

How to deselect all selected rows in a DataGridView control?

i have ran into the same problem and found a solution (not totally by myself, but there is the internet for)

Color blue  = ColorTranslator.FromHtml("#CCFFFF");
Color red = ColorTranslator.FromHtml("#FFCCFF");
Color letters = Color.Black;

foreach (DataGridViewRow r in datagridIncome.Rows)
{
    if (r.Cells[5].Value.ToString().Contains("1")) { 
        r.DefaultCellStyle.BackColor = blue;
        r.DefaultCellStyle.SelectionBackColor = blue;
        r.DefaultCellStyle.SelectionForeColor = letters;
    }
    else { 
        r.DefaultCellStyle.BackColor = red;
        r.DefaultCellStyle.SelectionBackColor = red;
        r.DefaultCellStyle.SelectionForeColor = letters;
    }
}

This is a small trick, the only way you can see a row is selected, is by the very first column (not column[0], but the one therefore). When you click another row, you will not see the blue selection anymore, only the arrow indicates which row have selected. As you understand, I use rowSelection in my gridview.

Deny access to one specific folder in .htaccess

You can also put this IndexIgnore * at your root .htaccess file to disable file listing of all of your website directories including sub-dir

Cocoa Autolayout: content hugging vs content compression resistance priority

contentCompressionResistancePriority – The view with the lowest value gets truncated when there is not enough space to fit everything’s intrinsicContentSize

contentHuggingPriority – The view with the lowest value gets expanded beyond its intrinsicContentSize when there is leftover space to fill

What is the (best) way to manage permissions for Docker shared volumes?

The same as you, I was looking for a way to map users/groups from host to docker containers and this is the shortest way I've found so far:

  version: "3"
    services:
      my-service:
        .....
        volumes:
          # take uid/gid lists from host
          - /etc/passwd:/etc/passwd:ro
          - /etc/group:/etc/group:ro
          # mount config folder
          - path-to-my-configs/my-service:/etc/my-service:ro
        .....

This is an extract from my docker-compose.yml.

The idea is to mount (in read-only mode) users/groups lists from the host to the container thus after the container starts up it will have the same uid->username (as well as for groups) matchings with the host. Now you can configure user/group settings for your service inside the container as if it was working on your host system.

When you decide to move your container to another host you just need to change user name in service config file to what you have on that host.

How to find the Git commit that introduced a string in any branch?

Messing around with the same answers:

$ git config --global alias.find '!git log --color -p -S '
  • ! is needed because other way, git do not pass argument correctly to -S. See this response
  • --color and -p helps to show exactly "whatchanged"

Now you can do

$ git find <whatever>

or

$ git find <whatever> --all
$ git find <whatever> master develop

Click a button programmatically

Let say button 1 has an event called

Button1_Click(Sender, eventarg)

If you want to call it in Button2 then call this function directly.

Button1_Click(Nothing, Nothing)

Basic HTML - how to set relative path to current folder?

<html>
    <head>
        <title>Page</title>
    </head>
    <body>
       <a href="./">Folder directory</a> 
    </body>
</html>

How does JavaScript .prototype work?

The seven Koans of prototype

As Ciro San descended Mount Fire Fox after deep meditation, his mind was clear and peaceful.

His hand however, was restless, and by itself grabbed a brush and jotted down the following notes.


0) Two different things can be called "prototype":

  • the prototype property, as in obj.prototype

  • the prototype internal property, denoted as [[Prototype]] in ES5.

    It can be retrieved via the ES5 Object.getPrototypeOf().

    Firefox makes it accessible through the __proto__ property as an extension. ES6 now mentions some optional requirements for __proto__.


1) Those concepts exist to answer the question:

When I do obj.property, where does JS look for .property?

Intuitively, classical inheritance should affect property lookup.


2)

  • __proto__ is used for the dot . property lookup as in obj.property.
  • .prototype is not used for lookup directly, only indirectly as it determines __proto__ at object creation with new.

Lookup order is:

  • obj properties added with obj.p = ... or Object.defineProperty(obj, ...)
  • properties of obj.__proto__
  • properties of obj.__proto__.__proto__, and so on
  • if some __proto__ is null, return undefined.

This is the so-called prototype chain.

You can avoid . lookup with obj.hasOwnProperty('key') and Object.getOwnPropertyNames(f)


3) There are two main ways to set obj.__proto__:

  • new:

    var F = function() {}
    var f = new F()
    

    then new has set:

    f.__proto__ === F.prototype
    

    This is where .prototype gets used.

  • Object.create:

     f = Object.create(proto)
    

    sets:

    f.__proto__ === proto
    

4) The code:

var F = function(i) { this.i = i }
var f = new F(1)

Corresponds to the following diagram (some Number stuff is omitted):

(Function)       (  F  )                                      (f)----->(1)
 |  ^             | | ^                                        |   i    |
 |  |             | | |                                        |        |
 |  |             | | +-------------------------+              |        |
 |  |constructor  | |                           |              |        |
 |  |             | +--------------+            |              |        |
 |  |             |                |            |              |        |
 |  |             |                |            |              |        |
 |[[Prototype]]   |[[Prototype]]   |prototype   |constructor   |[[Prototype]]
 |  |             |                |            |              |        |
 |  |             |                |            |              |        |
 |  |             |                | +----------+              |        |
 |  |             |                | |                         |        |
 |  |             |                | | +-----------------------+        |
 |  |             |                | | |                                |
 v  |             v                v | v                                |
(Function.prototype)              (F.prototype)                         |
 |                                 |                                    |
 |                                 |                                    |
 |[[Prototype]]                    |[[Prototype]]          [[Prototype]]|
 |                                 |                                    |
 |                                 |                                    |
 | +-------------------------------+                                    |
 | |                                                                    |
 v v                                                                    v
(Object.prototype)                                       (Number.prototype)
 | | ^
 | | |
 | | +---------------------------+
 | |                             |
 | +--------------+              |
 |                |              |
 |                |              |
 |[[Prototype]]   |constructor   |prototype
 |                |              |
 |                |              |
 |                | -------------+
 |                | |
 v                v |
(null)           (Object)

This diagram shows many language predefined object nodes:

  • null
  • Object
  • Object.prototype
  • Function
  • Function.prototype
  • 1
  • Number.prototype (can be found with (1).__proto__, parenthesis mandatory to satisfy syntax)

Our 2 lines of code only created the following new objects:

  • f
  • F
  • F.prototype

i is now a property of f because when you do:

var f = new F(1)

it evaluates F with this being the value that new will return, which then gets assigned to f.


5) .constructor normally comes from F.prototype through the . lookup:

f.constructor === F
!f.hasOwnProperty('constructor')
Object.getPrototypeOf(f) === F.prototype
F.prototype.hasOwnProperty('constructor')
F.prototype.constructor === f.constructor

When we write f.constructor, JavaScript does the . lookup as:

  • f does not have .constructor
  • f.__proto__ === F.prototype has .constructor === F, so take it

The result f.constructor == F is intuitively correct, since F is used to construct f, e.g. set fields, much like in classic OOP languages.


6) Classical inheritance syntax can be achieved by manipulating prototypes chains.

ES6 adds the class and extends keywords, which are mostly syntax sugar for previously possible prototype manipulation madness.

class C {
    constructor(i) {
        this.i = i
    }
    inc() {
        return this.i + 1
    }
}

class D extends C {
    constructor(i) {
        super(i)
    }
    inc2() {
        return this.i + 2
    }
}
// Inheritance syntax works as expected.
c = new C(1)
c.inc() === 2
(new D(1)).inc() === 2
(new D(1)).inc2() === 3
// "Classes" are just function objects.
C.constructor === Function
C.__proto__ === Function.prototype
D.constructor === Function
// D is a function "indirectly" through the chain.
D.__proto__ === C
D.__proto__.__proto__ === Function.prototype
// "extends" sets up the prototype chain so that base class
// lookups will work as expected
var d = new D(1)
d.__proto__ === D.prototype
D.prototype.__proto__ === C.prototype
// This is what `d.inc` actually does.
d.__proto__.__proto__.inc === C.prototype.inc
// Class variables
// No ES6 syntax sugar apparently:
// http://stackoverflow.com/questions/22528967/es6-class-variable-alternatives
C.c = 1
C.c === 1
// Because `D.__proto__ === C`.
D.c === 1
// Nothing makes this work.
d.c === undefined

Simplified diagram without all predefined objects:

(c)----->(1)
 |   i
 |
 |
 |[[Prototype]]
 |
 |
 v    __proto__
(C)<--------------(D)         (d)
| |                |           |
| |                |           |
| |prototype       |prototype  |[[Prototype]] 
| |                |           |
| |                |           |
| |                | +---------+
| |                | |
| |                | |
| |                v v
|[[Prototype]]    (D.prototype)--------> (inc2 function object)
| |                |             inc2
| |                |
| |                |[[Prototype]]
| |                |
| |                |
| | +--------------+
| | |
| | |
| v v
| (C.prototype)------->(inc function object)
|                inc
v
Function.prototype

Let's take a moment to study how the following works:

c = new C(1)
c.inc() === 2

The first line sets c.i to 1 as explained in "4)".

On the second line, when we do:

c.inc()
  • .inc is found through the [[Prototype]] chain: c -> C -> C.prototype -> inc
  • when we call a function in Javascript as X.Y(), JavaScript automatically sets this to equal X inside the Y() function call!

The exact same logic also explains d.inc and d.inc2.

This article https://javascript.info/class#not-just-a-syntax-sugar mentions further effects of class worth knowing. Some of them may not be achievable without the class keyword (TODO check which):

Throwing exceptions from constructors

#include <iostream>

class bar
{
public:
  bar()
  {
    std::cout << "bar() called" << std::endl;
  }

  ~bar()
  {
    std::cout << "~bar() called" << std::endl;

  }
};
class foo
{
public:
  foo()
    : b(new bar())
  {
    std::cout << "foo() called" << std::endl;
    throw "throw something";
  }

  ~foo()
  {
    delete b;
    std::cout << "~foo() called" << std::endl;
  }

private:
  bar *b;
};


int main(void)
{
  try {
    std::cout << "heap: new foo" << std::endl;
    foo *f = new foo();
  } catch (const char *e) {
    std::cout << "heap exception: " << e << std::endl;
  }

  try {
    std::cout << "stack: foo" << std::endl;
    foo f;
  } catch (const char *e) {
    std::cout << "stack exception: " << e << std::endl;
  }

  return 0;
}

the output:

heap: new foo
bar() called
foo() called
heap exception: throw something
stack: foo
bar() called
foo() called
stack exception: throw something

the destructors are not called, so if a exception need to be thrown in a constructor, a lot of stuff(e.g. clean up?) to do.

set up device for development (???????????? no permissions)

You could also try editing adb_usb.ini file, located at /home/username/.android/. This file contains id vendor list of devices you want to connect. You just add your device's id vendor in new line (it's one id per line). Then restart adb server and replug your device.

It worked for me on Ubuntu 12.10.

how to hide the content of the div in css

_x000D_
_x000D_
.button {_x000D_
        width: 40px;_x000D_
        height: 40px;_x000D_
        font-size: 0;_x000D_
        background: url("data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%221284%20207%2024%2024%22%3E%3Cg%20fill%3D%22none%22%3E%3Cpath%20d%3D%22M1298.5%20222.9C1297.5%20223.6%201296.3%20224%201295%20224%201291.7%20224%201289%20221.3%201289%20218%201289%20214.7%201291.7%20212%201295%20212%201298.3%20212%201301%20214.7%201301%20218%201301%20219.3%201300.6%20220.5%201299.9%20221.5L1302.7%20224.2C1303%20224.6%201303.1%20225.3%201302.7%20225.7%201302.3%20226%201301.6%20226%201301.2%20225.7L1298.5%20222.9ZM1295%20222C1297.2%20222%201299%20220.2%201299%20218%201299%20215.8%201297.2%20214%201295%20214%201292.8%20214%201291%20215.8%201291%20218%201291%20220.2%201292.8%20222%201295%20222Z%22%20fill%3D%22%239299A6%22%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E") #f0f2f5 no-repeat 50%;_x000D_
    }
_x000D_
<button class="button">?????</button>
_x000D_
_x000D_
_x000D_

Is it possible to use Visual Studio on macOS?

Yes! You can use the new Visual Studio for Mac, which Microsoft launched in November.

Read about it here: https://msdn.microsoft.com/magazine/mt790182

Download a preview version here: https://www.visualstudio.com/vs/visual-studio-mac/

How to get user agent in PHP

You can use the jQuery ajax method link if you want to pass data from client to server. In this case you can use $_SERVER['HTTP_USER_AGENT'] variable to found browser user agent.

How to run multiple .BAT files within a .BAT file

Running multiple scripts in one I had the same issue. I kept having it die on the first one not realizing that it was exiting on the first script.

:: OneScriptToRunThemAll.bat
CALL ScriptA.bat
CALL ScriptB.bat
EXIT

:: ScriptA.bat
Do Foo
EXIT
::ScriptB.bat
Do bar
EXIT

I removed all 11 of my scripts EXIT lines and tried again and all 11 ran in order one at a time in the same command window.

:: OneScriptToRunThemAll.bat
CALL ScriptA.bat
CALL ScriptB.bat
EXIT

::ScriptA.bat
Do Foo

::ScriptB.bat
Do bar

How to build an APK file in Eclipse?

The APK file is in the /workspace/PROJECT_FOLDER/bin directory. To install the APK file in a real device:

  1. Connect your real device with a PC/laptop.

  2. Go to sdk/tools/ using a terminal or command prompt.

  3. adb install <FILE PATH OF .APK FILE>

That's it...

Limit Decimal Places in Android EditText

A very late response: We can do it simply like this:

etv.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.toString().length() > 3 && s.toString().contains(".")) {
                if (s.toString().length() - s.toString().indexOf(".") > 3) {
                    etv.setText(s.toString().substring(0, s.length() - 1));
                    etv.setSelection(edtSendMoney.getText().length());
                }
            }
        }

        @Override
        public void afterTextChanged(Editable arg0) {
        }
}

How to convert/parse from String to char in java?

An Essay way :

public class CharToInt{  
public static void main(String[] poo){  
String ss="toyota";
for(int i=0;i<ss.length();i++)
  {
     char c = ss.charAt(i); 
    // int a=c;  
     System.out.println(c); } } 
} 

For Output see this link: Click here

Thanks :-)

Jquery : Refresh/Reload the page on clicking a button

Use this line simply inside your head with

       window.location.reload(true);

It will load your current page or view.

How do I use hexadecimal color strings in Flutter?

There is another solution. If you store your color as normal hex string and don't want to add opacity to it (leading FF): 1) Convert your hex string to int To convert a hex-string to an integer, do one of the following:

var myInt = int.parse(hexString, radix: 16);

or

var myInt = int.parse("0x$hexString");

as a prefix of 0x (or -0x) will make int.parse default to radix of 16.

2) Add opacity to your color via code

Color color = new Color(myInt).withOpacity(1.0);

How to redirect verbose garbage collection output to a file?

From the output of java -X:

    -Xloggc:<file>    log GC status to a file with time stamps

Documented here:

-Xloggc:filename

Sets the file to which verbose GC events information should be redirected for logging. The information written to this file is similar to the output of -verbose:gc with the time elapsed since the first GC event preceding each logged event. The -Xloggc option overrides -verbose:gc if both are given with the same java command.

Example:

    -Xloggc:garbage-collection.log

So the output looks something like this:

0.590: [GC 896K->278K(5056K), 0.0096650 secs]
0.906: [GC 1174K->774K(5056K), 0.0106856 secs]
1.320: [GC 1670K->1009K(5056K), 0.0101132 secs]
1.459: [GC 1902K->1055K(5056K), 0.0030196 secs]
1.600: [GC 1951K->1161K(5056K), 0.0032375 secs]
1.686: [GC 1805K->1238K(5056K), 0.0034732 secs]
1.690: [Full GC 1238K->1238K(5056K), 0.0631661 secs]
1.874: [GC 62133K->61257K(65060K), 0.0014464 secs]

Passing a varchar full of comma delimited values to a SQL Server IN function

The simplest way i found was to use FIND_IN_SET

FIND_IN_SET(column_name, values)

values=(1,2,3)

SELECT name WHERE FIND_IN_SET(id, values)

Initializing select with AngularJS and ng-repeat

The fact that angular is injecting an empty option element to the select is that the model object binded to it by default comes with an empty value in when initialized.

If you want to select a default option then you can probably can set it on the scope in the controller

$scope.filterCondition.operator = "your value here";

If you want to an empty option placeholder, this works for me

<select ng-model="filterCondition.operator" ng-options="operator.id as operator.name for operator in operators">
  <option value="">Choose Operator</option>
</select>

How to read and write INI file with Python3?

Use nested dictionaries. Take a look:

INI File: example.ini

[Section]
Key = Value

Code:

class IniOpen:
    def __init__(self, file):
        self.parse = {}
        self.file = file
        self.open = open(file, "r")
        self.f_read = self.open.read()
        split_content = self.f_read.split("\n")

        section = ""
        pairs = ""

        for i in range(len(split_content)):
            if split_content[i].find("[") != -1:
                section = split_content[i]
                section = string_between(section, "[", "]")  # define your own function
                self.parse.update({section: {}})
            elif split_content[i].find("[") == -1 and split_content[i].find("="):
                pairs = split_content[i]
                split_pairs = pairs.split("=")
                key = split_pairs[0].trim()
                value = split_pairs[1].trim()
                self.parse[section].update({key: value})

    def read(self, section, key):
        try:
            return self.parse[section][key]
        except KeyError:
            return "Sepcified Key Not Found!"

    def write(self, section, key, value):
        if self.parse.get(section) is  None:
            self.parse.update({section: {}})
        elif self.parse.get(section) is not None:
            if self.parse[section].get(key) is None:
                self.parse[section].update({key: value})
            elif self.parse[section].get(key) is not None:
                return "Content Already Exists"

Apply code like so:

ini_file = IniOpen("example.ini")
print(ini_file.parse) # prints the entire nested dictionary
print(ini_file.read("Section", "Key") # >> Returns Value
ini_file.write("NewSection", "NewKey", "New Value"

What is the difference between JavaScript and jQuery?

jQuery was written using JavaScript, and is a library to be used by JavaScript. You cannot learn jQuery without learning JavaScript.

Likely, you'll want to learn and use both of them. go through following breif diffrence http://www.slideshare.net/umarali1981/difference-between-java-script-and-jquery

Javascript Image Resize

Here is my cover fill solution (similar to background-size: cover, but it supports old IE browser)

<div class="imgContainer" style="height:100px; width:500px; overflow:hidden; background-color: black">
    <img src="http://dev.isaacsonwebdevelopment.com/sites/development/files/views-slideshow-settings-jquery-cycle-custom-options-message.png" id="imgCat">
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>
<script>
    $(window).load(function() {
        var heightRate =$("#imgCat").height() / $("#imgCat").parent(".imgContainer").height();
        var widthRate = $("#imgCat").width() / $("#imgCat").parent(".imgContainer").width();

        if (window.console) {
            console.log($("#imgCat").height());
            console.log(heightRate);
            console.log(widthRate);
            console.log(heightRate > widthRate);
        }
        if (heightRate <= widthRate) {
            $("#imgCat").height($("#imgCat").parent(".imgContainer").height());
        } else {
            $("#imgCat").width($("#imgCat").parent(".imgContainer").width());
        }
    });
</script>

How do I perform HTML decoding/encoding using Python/Django?

Given the Django use case, there are two answers to this. Here is its django.utils.html.escape function, for reference:

def escape(html):
    """Returns the given HTML with ampersands, quotes and carets encoded."""
    return mark_safe(force_unicode(html).replace('&', '&amp;').replace('<', '&l
t;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;'))

To reverse this, the Cheetah function described in Jake's answer should work, but is missing the single-quote. This version includes an updated tuple, with the order of replacement reversed to avoid symmetric problems:

def html_decode(s):
    """
    Returns the ASCII decoded version of the given HTML string. This does
    NOT remove normal HTML tags like <p>.
    """
    htmlCodes = (
            ("'", '&#39;'),
            ('"', '&quot;'),
            ('>', '&gt;'),
            ('<', '&lt;'),
            ('&', '&amp;')
        )
    for code in htmlCodes:
        s = s.replace(code[1], code[0])
    return s

unescaped = html_decode(my_string)

This, however, is not a general solution; it is only appropriate for strings encoded with django.utils.html.escape. More generally, it is a good idea to stick with the standard library:

# Python 2.x:
import HTMLParser
html_parser = HTMLParser.HTMLParser()
unescaped = html_parser.unescape(my_string)

# Python 3.x:
import html.parser
html_parser = html.parser.HTMLParser()
unescaped = html_parser.unescape(my_string)

# >= Python 3.5:
from html import unescape
unescaped = unescape(my_string)

As a suggestion: it may make more sense to store the HTML unescaped in your database. It'd be worth looking into getting unescaped results back from BeautifulSoup if possible, and avoiding this process altogether.

With Django, escaping only occurs during template rendering; so to prevent escaping you just tell the templating engine not to escape your string. To do that, use one of these options in your template:

{{ context_var|safe }}
{% autoescape off %}
    {{ context_var }}
{% endautoescape %}

Failed to Connect to MySQL at localhost:3306 with user root

It failed because there is no server install on your computer. You need to Download 'MySQL Community Server 8.0.17' & restart your server.

Is there a limit on number of tcp/ip connections between machines on linux?

There is a limit, yes. See ulimit.

Also you need to consider the TIMED_WAIT state. Once a TCP socket is closed (by default) the port remains occupied in TIMED_WAIT status for 2 minutes. This value is tunable. This will also "run you out of sockets" even though they are closed.

Run netstat to see the TIMED_WAIT stuff in action.

P.S. The reason for TIMED_WAIT is to handle the case of packets arriving after the socket is closed. This can happen because packets are delayed or the other side just doesn't know that the socket has been closed yet. This allows the OS to silently drop those packets without a chance of "infecting" a different, unrelated socket connection.

What is the HTML5 equivalent to the align attribute in table cells?

If they're block level elements they won't be affected by text-align: center;. Someone may have set img { display: block; } and that's throwing it out of whack. You can try:

td { text-align: center; }
td * { display: inline; }

and if it looks as desired you should definitely replace * with the desired elements like:

td img, td foo { display: inline; }

Remove warning messages in PHP

For ignoring all warnings use this sample, on the top of your code :

error_reporting(0);

Fastest way to remove non-numeric characters from a VARCHAR in SQL Server

Working with varchars is fundamentally slow and inefficient compared to working with numerics, for obvious reasons. The functions you link to in the original post will indeed be quite slow, as they loop through each character in the string to determine whether or not it's a number. Do that for thousands of records and the process is bound to be slow. This is the perfect job for Regular Expressions, but they're not natively supported in SQL Server. You can add support using a CLR function, but it's hard to say how slow this will be without trying it I would definitely expect it to be significantly faster than looping through each character of each phone number, however!

Once you get the phone numbers formatted in your database so that they're only numbers, you could switch to a numeric type in SQL which would yield lightning-fast comparisons against other numeric types. You might find that, depending on how fast your new data is coming in, doing the trimming and conversion to numeric on the database side is plenty fast enough once what you're comparing to is properly formatted, but if possible, you would be better off writing an import utility in a .NET language that would take care of these formatting issues before hitting the database.

Either way though, you're going to have a big problem regarding optional formatting. Even if your numbers are guaranteed to be only North American in origin, some people will put the 1 in front of a fully area-code qualified phone number and others will not, which will cause the potential for multiple entries of the same phone number. Furthermore, depending on what your data represents, some people will be using their home phone number which might have several people living there, so a unique constraint on it would only allow one database member per household. Some would use their work number and have the same problem, and some would or wouldn't include the extension which would cause artificial uniqueness potential again.

All of that may or may not impact you, depending on your particular data and usages, but it's important to keep in mind!

Variable length (Dynamic) Arrays in Java

Simple code for dynamic array. In below code then array will become full of size we copy all element to new double size array(variable size array).sample code is below 

public class DynamicArray {
 static   int []increaseSizeOfArray(int []arr){
          int []brr=new int[(arr.length*2)];
          for (int i = 0; i < arr.length; i++) {
         brr[i]=arr[i];     
          }
          return brr;
     }
public static void main(String[] args) {
     int []arr=new int[5];
      for (int i = 0; i < 11; i++) {
          if (i<arr.length) {
              arr[i]=i+100;
          }
          else {
              arr=increaseSizeOfArray(arr);
              arr[i]=i+100;
          }        
     }

for (int i = 0; i < arr.length; i++) {
     System.out.println("arr="+arr[i]);
}    
}

}

Source : How to make dynamic array

Retina displays, high-res background images

If you are planing to use the same image for retina and non-retina screen then here is the solution. Say that you have a image of 200x200 and have two icons in top row and two icon in bottom row. So, it's four quadrants.

.sprite-of-icons {
  background: url("../images/icons-in-four-quad-of-200by200.png") no-repeat;
  background-size: 100px 100px /* Scale it down to 50% rather using 200x200 */
}

.sp-logo-1 { background-position: 0 0; }

/* Reduce positioning of the icons down to 50% rather using -50px */
.sp-logo-2 { background-position: -25px 0 }
.sp-logo-3 { background-position: 0 -25px }
.sp-logo-3 { background-position: -25px -25px }

Scaling and positioning of the sprite icons to 50% than actual value, you can get the expected result.


Another handy SCSS mixin solution by Ryan Benhase.

/****************************
 HIGH PPI DISPLAY BACKGROUNDS
*****************************/

@mixin background-2x($path, $ext: "png", $w: auto, $h: auto, $pos: left top, $repeat: no-repeat) {

  $at1x_path: "#{$path}.#{$ext}";
  $at2x_path: "#{$path}@2x.#{$ext}";

  background-image: url("#{$at1x_path}");
  background-size: $w $h;
  background-position: $pos;
  background-repeat: $repeat;

  @media all and (-webkit-min-device-pixel-ratio : 1.5),
  all and (-o-min-device-pixel-ratio: 3/2),
  all and (min--moz-device-pixel-ratio: 1.5),
  all and (min-device-pixel-ratio: 1.5) {
    background-image: url("#{$at2x_path}"); 
  }
}

div.background {
  @include background-2x( 'path/to/image', 'jpg', 100px, 100px, center center, repeat-x );
}

For more info about above mixin READ HERE.

How to get Rails.logger printing to the console/stdout when running rspec?

Tail the log as a background job (&) and it will interleave with rspec output.

tail -f log/test.log &
bundle exec rspec

Safely override C++ virtual functions

C++11 override keyword when used with the function declaration inside the derived class, it forces the compiler to check that the declared function is actually overriding some base class function. Otherwise, the compiler will throw an error.

Hence you can use override specifier to ensure dynamic polymorphism (function overriding).

class derived: public base{
public:
  virtual void func_name(int var_name) override {
    // statement
  }
};

CSS: Center block, but align contents to the left

THIS works

<div style="display:inline-block;margin:10px auto;">
    <ul style="list-style-type:none;">
        <li style="text-align:left;"><span class="red">?</span> YouTube AutoComplete Keyword Scraper software <em>root keyword text box</em>.</li>
        <li style="text-align:left;"><span class="red">?</span> YouTube.com website <em>video search text box</em>.</li>
        <li style="text-align:left;"><span class="red">?</span> YouTube AutoComplete Keyword Scraper software <em>scraped keywords listbox</em>.</li>
        <li style="text-align:left;"><span class="red">?</span> YouTube AutoComplete Keyword Scraper software <em>right click context menu</em>.</li>
    </ul>
</div>

Finding the source code for built-in Python functions?

The iPython shell makes this easy: function? will give you the documentation. function?? shows also the code. BUT this only works for pure python functions.

Then you can always download the source code for the (c)Python.

If you're interested in pythonic implementations of core functionality have a look at PyPy source.

Business logic in MVC

As a couple of answers have pointed out, I believe there is some some misunderstanding of multi tier vs MVC architecture.

Multi tier architecture involves breaking your application into tiers/layers (e.g. presentation, business logic, data access)

MVC is an architectural style for the presentation layer of an application. For non trivial applications, business logic/business rules/data access should not be placed directly into Models, Views, or Controllers. To do so would be placing business logic in your presentation layer and thus reducing reuse and maintainability of your code.

The model is a very reasonable choice choice to place business logic, but a better/more maintainable approach is to separate your presentation layer from your business logic layer and create a business logic layer and simply call the business logic layer from your models when needed. The business logic layer will in turn call into the data access layer.

I would like to point out that it is not uncommon to find code that mixes business logic and data access in one of the MVC components, especially if the application was not architected using multiple tiers. However, in most enterprise applications, you will commonly find multi tier architectures with an MVC architecture in place within the presentation layer.

Python 2: AttributeError: 'list' object has no attribute 'strip'

What you want to do is -

strtemp = ";".join(l)

The first line adds a ; to the end of MySpace so that while splitting, it does not give out MySpaceApple This will join l into one string and then you can just-

l1 = strtemp.split(";")

This works because strtemp is a string which has .split()

Getting error: Peer authentication failed for user "postgres", when trying to get pgsql working with rails

My issue was that I did not type any server. I thought it is a default because of placeholder but when I typed localhost it did work.

Make Bootstrap Popover Appear/Disappear on Hover instead of Click

If you want to hover the popover itself as well you have to use a manual trigger.

This is what i came up with:

function enableThumbPopover() {
    var counter;

    $('.thumbcontainer').popover({
        trigger: 'manual',
        animation: false,
        html: true,
        title: function () {
            return $(this).parent().find('.thumbPopover > .title').html();
        },
        content: function () {
            return $(this).parent().find('.thumbPopover > .body').html();
        },
        container: 'body',
        placement: 'auto'
    }).on("mouseenter",function () {
        var _this = this; // thumbcontainer

        console.log('thumbcontainer mouseenter')
        // clear the counter
        clearTimeout(counter);
        // Close all other Popovers
        $('.thumbcontainer').not(_this).popover('hide');

        // start new timeout to show popover
        counter = setTimeout(function(){
            if($(_this).is(':hover'))
            {
                $(_this).popover("show");
            }
            $(".popover").on("mouseleave", function () {
                $('.thumbcontainer').popover('hide');
            });
        }, 400);

    }).on("mouseleave", function () {
        var _this = this;

        setTimeout(function () {
            if (!$(".popover:hover").length) {
                if(!$(_this).is(':hover')) // change $(this) to $(_this) 
                {
                    $(_this).popover('hide');
                }
            }
        }, 200);
    });
}

How to convert a list into data table

Just add this function and call it, it will convert List to DataTable.

public static DataTable ToDataTable<T>(List<T> items)
{
        DataTable dataTable = new DataTable(typeof(T).Name);

        //Get all the properties
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo prop in Props)
        {
            //Defining type of data column gives proper data table 
            var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
            //Setting column names as Property names
            dataTable.Columns.Add(prop.Name, type);
        }
        foreach (T item in items)
        {
           var values = new object[Props.Length];
           for (int i = 0; i < Props.Length; i++)
           {
                //inserting property values to datatable rows
                values[i] = Props[i].GetValue(item, null);
           }
           dataTable.Rows.Add(values);
      }
      //put a breakpoint here and check datatable
      return dataTable;
}

How to increase time in web.config for executing sql query

I realise I'm a litle late to the game, but just spent over a day on trying to change the timeout of a webservice. It seemed to have a default timeout of 30 seconds. I after changing evry other timeout value I could find, including:

  • DB connection string Connect Timeout
  • httpRuntime executionTimeout
  • basicHttpBinding binding closeTimeout
  • basicHttpBinding binding sendTimeout
  • basicHttpBinding binding receiveTimeout
  • basicHttpBinding binding openTimeout

Finaley I found that it was the SqlCommand timeout that was defaulting to 30 seconds.

I decided to just duplicate the timeout of the connection string to the command. The connection string is configured in the web.config.

Some code:

namespace ROS.WebService.Common
{
  using System;
  using System.Configuration;
  using System.Data;
  using System.Data.SqlClient;

  public static class DataAccess
  {
    public static string ConnectionString { get; private set; }

    static DataAccess()
    {
      ConnectionString = ConfigurationManager.ConnectionStrings["ROSdb"].ConnectionString;
    }

    public static int ExecuteNonQuery(string cmdText, CommandType cmdType, params SqlParameter[] sqlParams)
    {
      using (SqlConnection conn = new SqlConnection(DataAccess.ConnectionString))
      {
        using (SqlCommand cmd = new SqlCommand(cmdText, conn) { CommandType = cmdType, CommandTimeout = conn.ConnectionTimeout })
        {
          foreach (var p in sqlParams) cmd.Parameters.Add(p);
          cmd.Connection.Open();
          return cmd.ExecuteNonQuery();
        }
      }
    }
  }
}

Change introduced to "duplicate" the timeout value from the connection string:CommandTimeout = conn.ConnectionTimeout

How to get resources directory path programmatically

I'm assuming the contents of src/main/resources/ is copied to WEB-INF/classes/ inside your .war at build time. If that is the case you can just do (substituting real values for the classname and the path being loaded).

URL sqlScriptUrl = MyServletContextListener.class
                       .getClassLoader().getResource("sql/script.sql");

Angular2 @Input to a property with get/set

You could set the @Input on the setter directly, as described below:

_allowDay: boolean;
get allowDay(): boolean {
    return this._allowDay;
}
@Input() set allowDay(value: boolean) {
    this._allowDay = value;
    this.updatePeriodTypes();
}

See this Plunkr: https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview.

How can I "disable" zoom on a mobile web page?

You can use:

<head>
  <meta name="viewport" content="target-densitydpi=device-dpi, initial-scale=1.0, user-scalable=no" />
  ...
</head>

But please note that with Android 4.4 the property target-densitydpi is no longer supported. So for Android 4.4 and later the following is suggested as best practice:

<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />

Max length UITextField

You need to check whether the existing string plus the input is greater than 10.

   func textField(textField: UITextField!,shouldChangeCharactersInRange range: NSRange,    replacementString string: String!) -> Bool {
      NSUInteger newLength = textField.text.length + string.length - range.length;
      return !(newLength > 10)
   }

How do you get the process ID of a program in Unix or Linux using Python?

Try pgrep. Its output format is much simpler and therefore easier to parse.

Send private messages to friends

You cannot. Facebook API has read_mailbox but no write_mailbox extended permission. I'm guessing this is done to prevent spammy apps from flooding friend's inboxes.

Onclick CSS button effect

Push down the whole button. I suggest this it is looking nice in button.

#button:active {
    position: relative;
    top: 1px;
}

if you only want to push text increase top-padding and decrease bottom padding. You can also use line-height.

Which to use <div class="name"> or <div id="name">?

class is used when u want to set properties for a group of elements, but id can be set for only one element.

.NET Console Application Exit Event

Here is a complete, very simple .Net solution that works in all versions of windows. Simply paste it into a new project, run it and try CTRL-C to view how it handles it:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;

namespace TestTrapCtrlC{
    public class Program{
        static bool exitSystem = false;

        #region Trap application termination
        [DllImport("Kernel32")]
        private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);

        private delegate bool EventHandler(CtrlType sig);
        static EventHandler _handler;

        enum CtrlType {
         CTRL_C_EVENT = 0,
         CTRL_BREAK_EVENT = 1,
         CTRL_CLOSE_EVENT = 2,
         CTRL_LOGOFF_EVENT = 5,
         CTRL_SHUTDOWN_EVENT = 6
         }

        private static bool Handler(CtrlType sig) {
            Console.WriteLine("Exiting system due to external CTRL-C, or process kill, or shutdown");

            //do your cleanup here
            Thread.Sleep(5000); //simulate some cleanup delay

            Console.WriteLine("Cleanup complete");

            //allow main to run off
             exitSystem = true;

            //shutdown right away so there are no lingering threads
            Environment.Exit(-1);

            return true;
        }
        #endregion

        static void Main(string[] args) {
            // Some biolerplate to react to close window event, CTRL-C, kill, etc
            _handler += new EventHandler(Handler);
            SetConsoleCtrlHandler(_handler, true);

            //start your multi threaded program here
            Program p = new Program();
            p.Start();

            //hold the console so it doesn’t run off the end
            while(!exitSystem) {
                Thread.Sleep(500);
            }
        }

        public void Start() {
            // start a thread and start doing some processing
            Console.WriteLine("Thread started, processing..");
        }
    }
 }

Making the iPhone vibrate

I had great trouble with this for devices that had vibration turned off in some manner, but we needed it to work regardless, because it is critical to our application functioning, and since it is just an integer to a documented method call, it will pass validation. So I have tried some sounds that were outside of the well documented ones here: TUNER88/iOSSystemSoundsLibrary

I have then stumbled upon 1352, which is working regardless of the silent switch or the settings on the device (Settings->vibrate on ring, vibrate on silent).

- (void)vibratePhone;
{
     if([[UIDevice currentDevice].model isEqualToString:@"iPhone"])
     {
         AudioServicesPlaySystemSound (1352); //works ALWAYS as of this post
     }
     else
     {
          // Not an iPhone, so doesn't have vibrate
          // play the less annoying tick noise or one of your own
          AudioServicesPlayAlertSound (1105);
     }
}

MySQL Great Circle Distance (Haversine formula)

From Google Code FAQ - Creating a Store Locator with PHP, MySQL & Google Maps:

Here's the SQL statement that will find the closest 20 locations that are within a radius of 25 miles to the 37, -122 coordinate. It calculates the distance based on the latitude/longitude of that row and the target latitude/longitude, and then asks for only rows where the distance value is less than 25, orders the whole query by distance, and limits it to 20 results. To search by kilometers instead of miles, replace 3959 with 6371.

SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) 
* cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin(radians(lat)) ) ) AS distance 
FROM markers 
HAVING distance < 25 
ORDER BY distance 
LIMIT 0 , 20;

How does functools partial do what it does?

partials are incredibly useful.

For instance, in a 'pipe-lined' sequence of function calls (in which the returned value from one function is the argument passed to the next).

Sometimes a function in such a pipeline requires a single argument, but the function immediately upstream from it returns two values.

In this scenario, functools.partial might allow you to keep this function pipeline intact.

Here's a specific, isolated example: suppose you want to sort some data by each data point's distance from some target:

# create some data
import random as RND
fnx = lambda: RND.randint(0, 10)
data = [ (fnx(), fnx()) for c in range(10) ]
target = (2, 4)

import math
def euclid_dist(v1, v2):
    x1, y1 = v1
    x2, y2 = v2
    return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)

To sort this data by distance from the target, what you would like to do of course is this:

data.sort(key=euclid_dist)

but you can't--the sort method's key parameter only accepts functions that take a single argument.

so re-write euclid_dist as a function taking a single parameter:

from functools import partial

p_euclid_dist = partial(euclid_dist, target)

p_euclid_dist now accepts a single argument,

>>> p_euclid_dist((3, 3))
  1.4142135623730951

so now you can sort your data by passing in the partial function for the sort method's key argument:

data.sort(key=p_euclid_dist)

# verify that it works:
for p in data:
    print(round(p_euclid_dist(p), 3))

    1.0
    2.236
    2.236
    3.606
    4.243
    5.0
    5.831
    6.325
    7.071
    8.602

Or for instance, one of the function's arguments changes in an outer loop but is fixed during iteration in the inner loop. By using a partial, you don't have to pass in the additional parameter during iteration of the inner loop, because the modified (partial) function doesn't require it.

>>> from functools import partial

>>> def fnx(a, b, c):
      return a + b + c

>>> fnx(3, 4, 5)
      12

create a partial function (using keyword arg)

>>> pfnx = partial(fnx, a=12)

>>> pfnx(b=4, c=5)
     21

you can also create a partial function with a positional argument

>>> pfnx = partial(fnx, 12)

>>> pfnx(4, 5)
      21

but this will throw (e.g., creating partial with keyword argument then calling using positional arguments)

>>> pfnx = partial(fnx, a=12)

>>> pfnx(4, 5)
      Traceback (most recent call last):
      File "<pyshell#80>", line 1, in <module>
      pfnx(4, 5)
      TypeError: fnx() got multiple values for keyword argument 'a'

another use case: writing distributed code using python's multiprocessing library. A pool of processes is created using the Pool method:

>>> import multiprocessing as MP

>>> # create a process pool:
>>> ppool = MP.Pool()

Pool has a map method, but it only takes a single iterable, so if you need to pass in a function with a longer parameter list, re-define the function as a partial, to fix all but one:

>>> ppool.map(pfnx, [4, 6, 7, 8])

How do I temporarily disable triggers in PostgreSQL?

You can also disable triggers in pgAdmin (III):

  1. Find your table
  2. Expand the +
  3. Find your trigger in Triggers
  4. Right-click, uncheck "Trigger Enabled?"

How to assign the output of a Bash command to a variable?

In this specific case, note that bash has a variable called PWD that contains the current directory: $PWD is equivalent to `pwd`. (So do other shells, this is a standard feature.) So you can write your script like this:

#!/bin/bash
until [ "$PWD" = "/" ]; do
  echo "$PWD"
  ls && cd .. && ls 
done

Note the use of double quotes around the variable references. They are necessary if the variable (here, the current directory) contains whitespace or wildcards (\[?*), because the shell splits the result of variable expansions into words and performs globbing on these words. Always double-quote variable expansions "$foo" and command substitutions "$(foo)" (unless you specifically know you have not to).

In the general case, as other answers have mentioned already:

  • You can't use whitespace around the equal sign in an assignment: var=value, not var = value
  • The $ means “take the value of this variable”, so you don't use it when assigning: var=value, not $var=value.

How do you redirect to a page using the POST verb?

try this one

return Content("<form action='actionname' id='frmTest' method='post'><input type='hidden' name='someValue' value='" + someValue + "' /><input type='hidden' name='anotherValue' value='" + anotherValue + "' /></form><script>document.getElementById('frmTest').submit();</script>");

Encode String to UTF-8

A Java String is internally always encoded in UTF-16 - but you really should think about it like this: an encoding is a way to translate between Strings and bytes.

So if you have an encoding problem, by the time you have String, it's too late to fix. You need to fix the place where you create that String from a file, DB or network connection.

How to redirect to logon page when session State time out is completed in asp.net mvc

I discover very simple way to redirect Login Page When session end in MVC. I have already tested it and this works without problems.

In short, I catch session end in _Layout 1 minute before and make redirection.

I try to explain everything step by step.

If we want to session end 30 minute after and redirect to loginPage see this steps:

  1. Change the web config like this (set 31 minute):

     <system.web>
        <sessionState timeout="31"></sessionState>
     </system.web>
    
  2. Add this JavaScript in _Layout (when session end 1 minute before this code makes redirect, it makes count time after user last action, not first visit on site)

    <script>
        //session end 
        var sessionTimeoutWarning = @Session.Timeout- 1;
    
        var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
        setTimeout('SessionEnd()', sTimeout);
    
        function SessionEnd() {
            window.location = "/Account/LogOff";
        }
    </script>
    
  3. Here is my LogOff Action, which makes only LogOff and redirect LoginIn Page

    public ActionResult LogOff()
    {
        Session["User"] = null; //it's my session variable
        Session.Clear();
        Session.Abandon();
        FormsAuthentication.SignOut(); //you write this when you use FormsAuthentication
        return RedirectToAction("Login", "Account");
    } 
    

I hope this is a very useful code for you.

cast a List to a Collection

Casting never needs a new:

Collection<T> collection = myList;

You don't even make the cast explicit, because Collection is a super-type of List, so it will work just like this.

git commit error: pathspec 'commit' did not match any file(s) known to git

In my case, the problem was I used wrong alias for git commit -m. I used gcalias which dit not meant git commit -m

Subscript out of bounds - general definition and solution?

This came from standford's sna free tutorial and it states that ...

# Reachability can only be computed on one vertex at a time. To # get graph-wide statistics, change the value of "vertex" # manually or write a for loop. (Remember that, unlike R objects, # igraph objects are numbered from 0.)

ok, so when ever using igraph, the first roll/column is 0 other than 1, but matrix starts at 1, thus for any calculation under igraph, you would need x-1, shown at

this_node_reach <- subcomponent(g, (i - 1), mode = m)

but for the alter calculation, there is a typo here

alter = this_node_reach[j] + 1

delete +1 and it will work alright

Format an Integer using Java String Format

String.format("%03d", 1)  // => "001"
//              ¦¦¦   +-- print the number one
//              ¦¦+------ ... as a decimal integer
//              ¦+------- ... minimum of 3 characters wide
//              +-------- ... pad with zeroes instead of spaces

See java.util.Formatter for more information.