Programs & Examples On #Allowmultiple

Call a child class method from a parent class object

A parent class should not have knowledge of child classes. You can implement a method calculate() and override it in every subclass:

class Person {
    String name;
    void getName(){...}
    void calculate();
}

and then

class Student extends Person{
    String class;
    void getClass(){...}

    @Override
    void calculate() {
        // do something with a Student
    }
}

and

class Teacher extends Person{
    String experience;
    void getExperience(){...}

    @Override
    void calculate() {
        // do something with a Student
    }

}

By the way. Your statement about abstract classes is confusing. You can call methods defined in an abstract class, but of course only of instances of subclasses.

In your example you can make Person abstract and the use getName() on instanced of Student and Teacher.

How to get a list of properties with a given attribute?

There's always LINQ:

t.GetProperties().Where(
    p=>p.GetCustomAttributes(typeof(MyAttribute), true).Length != 0)

Basic Apache commands for a local Windows machine

For frequent uses of this command I found it easy to add the location of C:\xampp\apache\bin to the PATH. Use whatever directory you have this installed in.

Then you can run from any directory in command line:

httpd -k restart

The answer above that suggests httpd -k -restart is actually a typo. You can see the commands by running httpd /?

'NoneType' object is not subscriptable?

The indexing e.g. [0] should occour inside of the print...

Turn off enclosing <p> tags in CKEditor 3.0

Found it!

ckeditor.js line #91 ... search for

B.config.enterMode==3?'div':'p'

change to

B.config.enterMode==3?'div':'' (NO P!)

Dump your cache and BAM!

Min and max value of input in angular4 application

Most simple approach in Template driven forms for min/max validation with out using reactive forms and building any directive, would be to use pattern attribute of html. This has already been explained and answered here please look https://stackoverflow.com/a/63312336/14069524

How do you do block comments in YAML?

In Azure Devops browser(pipeline yaml editor),

Ctrl + K + C Comment Block

Ctrl + K + U Uncomment Block

There also a 'Toggle Block Comment' option but this did not work for me. enter image description here

There are other 'wierd' ways too: right click to see 'Command Palette' or F1

enter image description here

Then choose a cursor option. enter image description here

Now it is just a matter of #

or even smarter [Ctrl + k] + [Ctrl + c]

How do I request and process JSON with python?

For anything with requests to URLs you might want to check out requests. For JSON in particular:

>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...

Foreach with JSONArray and JSONObject

Make sure you are using this org.json: https://mvnrepository.com/artifact/org.json/json

if you are using Java 8 then you can use

import org.json.JSONArray;
import org.json.JSONObject;

JSONArray array = ...;

array.forEach(item -> {
    JSONObject obj = (JSONObject) item;
    parse(obj);
});

Just added a simple test to prove that it works:

Add the following dependency into your pom.xml file (To prove that it works, I have used the old jar which was there when I have posted this answer)

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20160810</version>
</dependency>

And the simple test code snippet will be:

import org.json.JSONArray;
import org.json.JSONObject;

public class Test {
    public static void main(String args[]) {
        JSONArray array = new JSONArray();

        JSONObject object = new JSONObject();
        object.put("key1", "value1");

        array.put(object);

        array.forEach(item -> {
            System.out.println(item.toString());
        });
    }
}

output:

{"key1":"value1"}

How do you run a .exe with parameters using vba's shell()?

This works for me (Excel 2013):

Public Sub StartExeWithArgument()
    Dim strProgramName As String
    Dim strArgument As String

    strProgramName = "C:\Program Files\Test\foobar.exe"
    strArgument = "/G"

    Call Shell("""" & strProgramName & """ """ & strArgument & """", vbNormalFocus)
End Sub

With inspiration from here https://stackoverflow.com/a/3448682.

ASP.Net Download file to client browser

Try changing it to.

 Response.Clear();
 Response.ClearHeaders();
 Response.ClearContent();
 Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
 Response.AddHeader("Content-Length", file.Length.ToString());
 Response.ContentType = "text/plain";
 Response.Flush();
 Response.TransmitFile(file.FullName);
 Response.End();

Visual Studio 2017 errors on standard headers

This problem may also happen if you have a unit test project that has a different C++ version than the project you want to test.

Example:

  • EXE with C++ 17 enabled explicitly
  • Unit Test with C++ version set to "Default"

Solution: change the Unit Test to C++17 as well.

Screenshot

Are dictionaries ordered in Python 3.6+?

To fully answer this question in 2020, let me quote several statements from official Python docs:

Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.

Changed in version 3.7: Dictionary order is guaranteed to be insertion order.

Changed in version 3.8: Dictionaries are now reversible.

Dictionaries and dictionary views are reversible.

A statement regarding OrderedDict vs Dict:

Ordered dictionaries are just like regular dictionaries but have some extra capabilities relating to ordering operations. They have become less important now that the built-in dict class gained the ability to remember insertion order (this new behavior became guaranteed in Python 3.7).

groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding

in my case I have used - (Hyphen) in my script name in case of Jenkinsfile Library. Got resolved after replacing Hyphen(-) with Underscore(_)

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

take look at my example

<tocheading language="EN"> 
     <subj-group> 
         <subject>Editors Choice</subject> 
         <subject>creative common</subject> 
     </subj-group> 
</tocheading> 

now how to check if creative common is exist

tocheading/subj-group/subject/text() = 'creative common'

hope this help you

make image( not background img) in div repeat?

It would probably be easier to just fake it by using a div. Just make sure you set the height if its empty so that it can actually appear. Say for instance you want it to be 50px tall set the div height to 50px.

<div id="rightflower">
<div id="divImg"></div> 
</div>

And in your style sheet just add the background and its properties, height and width, and what ever positioning you had in mind.

How to restart tomcat 6 in ubuntu

if you are using extracted tomcat then,

startup.sh and shutdown.sh are two script located in TOMCAT/bin/ to start and shutdown tomcat, You could use that

if tomcat is installed then

/etc/init.d/tomcat5.5 start
/etc/init.d/tomcat5.5 stop
/etc/init.d/tomcat5.5 restart

How to create circular ProgressBar in android?

It's easy to create this yourself

In your layout include the following ProgressBar with a specific drawable (note you should get the width from dimensions instead). The max value is important here:

<ProgressBar
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:max="500"
    android:progress="0"
    android:progressDrawable="@drawable/circular" />

Now create the drawable in your resources with the following shape. Play with the radius (you can use innerRadius instead of innerRadiusRatio) and thickness values.

circular (Pre Lollipop OR API Level < 21)

   <shape
        android:innerRadiusRatio="2.3"
        android:shape="ring"
        android:thickness="3.8sp" >
        <solid android:color="@color/yourColor" />
   </shape>

circular ( >= Lollipop OR API Level >= 21)

    <shape
        android:useLevel="true"
        android:innerRadiusRatio="2.3"
        android:shape="ring"
        android:thickness="3.8sp" >
        <solid android:color="@color/yourColor" />
     </shape>

useLevel is "false" by default in API Level 21 (Lollipop) .

Start Animation

Next in your code use an ObjectAnimator to animate the progress field of the ProgessBar of your layout.

ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
ObjectAnimator animation = ObjectAnimator.ofInt(progressBar, "progress", 0, 500); // see this max value coming back here, we animate towards that value
animation.setDuration(5000); // in milliseconds
animation.setInterpolator(new DecelerateInterpolator());
animation.start();

Stop Animation

progressBar.clearAnimation();

P.S. unlike examples above, it give smooth animation.

How to empty a Heroku database

I always do this with the one-liner 'heroku pg:reset DATABASE'.

Awk if else issues

Try the code

awk '{s=($3==0)?"-":$3/$4; print s}'

Visual Studio debugging/loading very slow

Do you have enabled FusionLog?

My VisualStudio was very slow to start, open solution and load symbols when start debugging. It was slow only on my machine, but not on other machines.

FusionLog writes tons of log stuff to disk. Just disabling it on RegEdit solved everything, on my case.

This is the FusionLog key on registry:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion

Check ForceLog value (1 enabled, 0 disabled).

Python Create unix timestamp five minutes in the future

The key is to ensure all the dates you are using are in the utc timezone before you start converting. See http://pytz.sourceforge.net/ to learn how to do that properly. By normalizing to utc, you eliminate the ambiguity of daylight savings transitions. Then you can safely use timedelta to calculate distance from the unix epoch, and then convert to seconds or milliseconds.

Note that the resulting unix timestamp is itself in the UTC timezone. If you wish to see the timestamp in a localized timezone, you will need to make another conversion.

Also note that this will only work for dates after 1970.

   import datetime
   import pytz

   UNIX_EPOCH = datetime.datetime(1970, 1, 1, 0, 0, tzinfo = pytz.utc)
   def EPOCH(utc_datetime):
      delta = utc_datetime - UNIX_EPOCH
      seconds = delta.total_seconds()
      ms = seconds * 1000
      return ms

PHP substring extraction. Get the string before the first '/' or the whole string

Using current on explode would ease the process.

 $str = current(explode("/", $str, 2));

Difference between System.DateTime.Now and System.DateTime.Today

DateTime.Now.ToShortDateString() will display only the date part

How do I count a JavaScript object's attributes?

There's no easy answer, because Object — which every object in JavaScript derives from — includes many attributes automatically, and the exact set of attributes you get depends on the particular interpreter and what code has executed before yours. So, you somehow have to separate the ones you defined from those you got "for free."

Here's one way:

var foo = {"key1": "value1", "key2": "value2", "key3": "value3"};
Object.prototype.foobie = 'bletch'; // add property to foo that won't be counted

var count = 0;
for (var k in foo) {
    if (foo.hasOwnProperty(k)) {
       ++count;
    }
}
alert("Found " + count + " properties specific to foo");

The second line shows how other code can add properties to all Object derivatives. If you remove the hasOwnProperty() check inside the loop, the property count will go up to at least 4. On a page with other JavaScript besides this code, it could be higher than 4, if that other code also modifies the Object prototype.

Handling file renames in git

Let's think about your files from git perspective.

Keep in mind git doesn't track any metadata about your files

Your repository has (among others)

$ cd repo
$ ls
...
iphone.css
...

and it is under git control:

$ git ls-files --error-unmatch iphone.css &>/dev/null && echo file is tracked
file is tracked

Test this with:

$ touch newfile
$ git ls-files --error-unmatch newfile &>/dev/null && echo file is tracked
(no output, it is not tracked)
$ rm newfile

When you do

$ mv iphone.css mobile.css

From git perspective,

  • there is no iphone.css (it is deleted -git warns about that-).
  • there is a new file mobile.css.
  • Those files are totally unrelated.

So, git advises about files it already knows (iphone.css) and new files it detects (mobile.css) but only when files are in index or HEAD git starts to check their contents.

At this moment, neither "iphone.css deletion" nor mobile.css are on index.

Add iphone.css deletion to index

$ git rm iphone.css

git tells you exactly what has happened: (iphone.css is deleted. Nothing more happened)

then add new file mobile.css

$ git add mobile.css

This time both deletion and new file are on index. Now git detects context are the same and expose it as a rename. In fact if files are 50% similar it will detect that as a rename, that let you change mobile.css a bit while keeping the operation as a rename.

See this is reproducible on git diff. Now that your files are on index you must use --cached. Edit mobile.css a bit, add that to index and see the difference between:

$ git diff --cached 

and

$ git diff --cached -M

-M is the "detect renames" option for git diff. -M stands for -M50% (50% or more similarity will make git express it as a rename) but you can reduce this to -M20% (20%) if you edit mobile.css a lot.

pdftk compression option

In case you want to compress a PDF which contains a lot of selectable text, on Windows you can use NicePDF Compressor - choose "Flate" option. After trying everything (cpdf, pdftk, gs) it finally helped me to compress my 1360 pages PDF from 500 MB down to 10 MB.

Convert ascii char[] to hexadecimal char[] in C

replace this

printf("%c",word[i]);

by

printf("%02X",word[i]);

input type=file show only button

my solution is just to set it within a div like "druveen" said, however i ad my own button style to the div (make it look like a button with a:hover) and i just set the style "opacity:0;" to the input. Works a charm for me, hope it does the same for you.

Why do we need virtual functions in C++?

Why do we need Virtual Methods in C++?

Quick Answer:

  1. It provides us with one of the needed "ingredients"1 for object oriented programming.

In Bjarne Stroustrup C++ Programming: Principles and Practice, (14.3):

The virtual function provides the ability to define a function in a base class and have a function of the same name and type in a derived class called when a user calls the base class function. That is often called run-time polymorphism, dynamic dispatch, or run-time dispatch because the function called is determined at run time based on the type of the object used.

  1. It is the fastest more efficient implementation if you need a virtual function call 2.

To handle a virtual call, one needs one or more pieces of data related to the derived object 3. The way that is usually done is to add the address of table of functions. This table is usually referred to as virtual table or virtual function table and its address is often called the virtual pointer. Each virtual function gets a slot in the virtual table. Depending of the caller's object (derived) type, the virtual function, in its turn, invokes the respective override.


1.The use of inheritance, run-time polymorphism, and encapsulation is the most common definition of object-oriented programming.

2. You can't code functionality to be any faster or to use less memory using other language features to select among alternatives at run time. Bjarne Stroustrup C++ Programming: Principles and Practice.(14.3.1).

3. Something to tell which function is really invoked when we call the base class containing the virtual function.

Hide separator line on one UITableViewCell

The much more simple and logical is to do this:

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [[UIView alloc] initWithFrame:CGRectZero];
}

In most cases you don't want to see only the last table view cell separator. And this approach removes only the last table view cell separator, and you don't need to think about Auto Layout issues (i.e. rotating device) or hardcode values to set up separator insets.

Padding between ActionBar's home icon and title

<string name="app_name">"    "Brick Industry</string>

Just add " " for your app name It will add space between icon and title

Equivalent of String.format in jQuery

I have a plunker that adds it to the string prototype: string.format It is not just as short as some of the other examples, but a lot more flexible.

Usage is similar to c# version:

var str2 = "Meet you on {0}, ask for {1}";
var result2 = str2.format("Friday", "Suzy"); 
//result: Meet you on Friday, ask for Suzy
//NB: also accepts an array

Also, added support for using names & object properties

var str1 = "Meet you on {day}, ask for {Person}";
var result1 = str1.format({day: "Thursday", person: "Frank"}); 
//result: Meet you on Thursday, ask for Frank

ERROR 2013 (HY000): Lost connection to MySQL server at 'reading authorization packet', system error: 0

I have a mac but would assume all linux are the same for this part...

In my case I got this:

2018-12-03 11:13:27 - Start server: 
2018-12-03 11:13:27 - Server start done.
2018-12-03 11:13:27 - Checking server status...
2018-12-03 11:13:27 - Trying to connect to MySQL...
2018-12-03 11:13:27 - Lost connection to MySQL server at 'reading authorization packet', system error: 0 (2013)
2018-12-03 11:13:27 - Assuming server is not running

I ran this:

sudo killall mysqld

And then started the mysql again through mysqlworkbench although in your case it might be like this:

mysql.server start

*sidenote: I tried running mysql.server stop and got this Shutting down MySQL .... SUCCESS! but after running ps aux | grep mysql I saw that it hasn't really shut down...

unique object identifier in javascript

I faced the same problem and here's the solution I implemented with ES6

code
let id = 0; // This is a kind of global variable accessible for every instance 

class Animal {
constructor(name){
this.name = name;
this.id = id++; 
}

foo(){}
 // Executes some cool stuff
}

cat = new Animal("Catty");


console.log(cat.id) // 1 

How to get values from IGrouping

From definition of IGrouping :

IGrouping<out TKey, out TElement> : IEnumerable<TElement>, IEnumerable

you can just iterate through elements like this:

IEnumerable<IGrouping<int, smth>> groups = list.GroupBy(x => x.ID)
foreach(IEnumerable<smth> element in groups)
{
//do something
}

How to use a wildcard in the classpath to add multiple jars?

This works on Windows:

java -cp "lib/*" %MAINCLASS%

where %MAINCLASS% of course is the class containing your main method.

Alternatively:

java -cp "lib/*" -jar %MAINJAR%

where %MAINJAR% is the jar file to launch via its internal manifest.

DateTime.MinValue and SqlDateTime overflow

Very simple avoid using DateTime.MinValue use System.Data.SqlTypes.SqlDateTime.MinValue instead.

asp.net mvc3 return raw html to view

public ActionResult Questionnaire()
{
    return Redirect("~/MedicalHistory.html");
}

Conditionally displaying JSF components

In addition to previous post you can have

<h:form rendered="#{!bean.boolvalue}" />
<h:form rendered="#{bean.textvalue == 'value'}" />

Jsf 2.0

How to send file contents as body entity using cURL

In my case, @ caused some sort of encoding problem, I still prefer my old way:

curl -d "$(cat /path/to/file)" https://example.com

When is each sorting algorithm used?

What the provided links to comparisons/animations do not consider is when the amount of data exceed available memory --- at which point the number of passes over the data, i.e. I/O-costs, dominate the runtime. If you need to do that, read up on "external sorting" which usually cover variants of merge- and heap sorts.

http://corte.si/posts/code/visualisingsorting/index.html and http://corte.si/posts/code/timsort/index.html also have some cool images comparing various sorting algorithms.

How to save a bitmap on internal storage

Modify onClick() as follows:

@Override
public void onClick(View v) {
    if(v == btn) {
        canvas=sv.getHolder().lockCanvas();
        if(canvas!=null) {
            canvas.drawBitmap(bitmap, 100, 100, null);
            sv.getHolder().unlockCanvasAndPost(canvas);
        }
    } else if(v == btn1) {
        saveBitmapToInternalStorage(bitmap);
    }
}

There are several ways to enforce that btn must be pressed before btn1 so that the bitmap is painted before you attempt to save it.

I suggest that you initially disable btn1, and that you enable it when btn is clicked, like this:

if(v == btn) {
    ...
    btn1.setEnabled(true);
}

When are static variables initialized?

The static variable can be intialize in the following three ways as follow choose any one you like

  1. you can intialize it at the time of declaration
  2. or you can do by making static block eg:

    static {
            // whatever code is needed for initialization goes here
        }
    
  3. There is an alternative to static blocks — you can write a private static method

    class name {
        public static varType myVar = initializeVar();
    
        private static varType initializeVar() {
            // initialization code goes here
        }
    }
    

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

You can rollback the statements you've executed within a transaction. Instead of commiting the transaction, rollback the transaction.

If you have updated something and want to rollback those updates, and you haven't done this inside a (not-yet-commited) transaction, then I think it's though luck ...

(Manually repair, or, restore backups)

Alphanumeric, dash and underscore but no spaces regular expression check JavaScript

This is the most concise syntax I could find for a regex expression to be used for this check:

const regex = /^[\w-]+$/;

Error message "No exports were found that match the constraint contract name"

This issue is because of a MEF cache corruption. Installing the feedback extension (or installing any extension) will invalidate the cache causing VS to rebuild it.

click for source.

Find methods calls in Eclipse project

You can also search for specific methods. For e.g. If you want to search for isEmpty() method of the string class you have to got to - Search -> Java -> type java.lang.String.isEmpty() and in the 'Search For' option use Method.

You can then select the scope that you require.

Group by with multiple columns using lambda

var query = source.GroupBy(x => new { x.Column1, x.Column2 });

What does .pack() do?

The pack method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location). In general, using pack is preferable to calling setSize, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.

From Java tutorial

You should also refer to Javadocs any time you need additional information on any Java API

Check if all elements in a list are identical

lambda lst: reduce(lambda a,b:(b,b==a[0] and a[1]), lst, (lst[0], True))[1]

The next one will short short circuit:

all(itertools.imap(lambda i:yourlist[i]==yourlist[i+1], xrange(len(yourlist)-1)))

Could not load file or assembly Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0

I am running VS 2012, and SQL Server 2008 R2 SP2, Developer Edition. I ended up having to install items from the Microsoft® SQL Server® 2012 Feature Pack. I think that the install instructions noted that these items work for SQL Server 2005 through 2012. I don't know what the exact requirements are to fix this error, but I installed the three items, and the error stopped appearing.

Microsoft® SQL Server® 2012 Feature Pack Items

  • Microsoft® SQL Server® 2012 Shared Management Objects : x86 , x64
  • Microsoft® System CLR Types for Microsoft® SQL Server® 2012 : x86 , x64
  • Microsoft® SQL Server® 2012 Native Client : x86 , x64

Based on threads elsewhere, you may not end up needing the last item or two. Good luck!

C# ASP.NET MVC Return to Previous Page

I know this is very late, but maybe this will help someone else.

I use a Cancel button to return to the referring url. In the View, try adding this:

@{
  ViewBag.Title = "Page title";
  Layout = "~/Views/Shared/_Layout.cshtml";

  if (Request.UrlReferrer != null)
  {
    string returnURL = Request.UrlReferrer.ToString();
    ViewBag.ReturnURL = returnURL;
  }
}

Then you can set your buttons href like this:

<a href="@ViewBag.ReturnURL" class="btn btn-danger">Cancel</a>

Other than that, the update by Jason Enochs works great!

WCF vs ASP.NET Web API

The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).

WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.


For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:

enter image description here


ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.

Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.


In the scenarios listed below you should go for WCF:

  1. If you need to send data on protocols like TCP, MSMQ or MIME
  2. If the consuming client just knows how to consume SOAP messages

WEB API is a framework for developing RESTful/HTTP services.

There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.

HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.

Combining paste() and expression() functions in plot labels

Use substitute instead.

labNames <- c('xLab','yLab')
plot(c(1:10),
     xlab=substitute(paste(nn, x^2), list(nn=labNames[1])),
     ylab=substitute(paste(nn, y^2), list(nn=labNames[2])))

RVM is not a function, selecting rubies with 'rvm use ...' will not work

For me in Ubuntu(18.08), I have added below line in .bashrc and it works.

 source /home/username/.rvm/scripts/rvm

Please add this line.

How can one run multiple versions of PHP 5.x on a development LAMP server?

Note: The following method will work on windows.

An alternative method (if it is ok to run a single version of PHP at a time) is to define multiple Apache services, each of which will use a different PHP version.

First of all use conditions in the Apache configuration file:

 <ifdefine php54>
    SetEnv PHPRC C:/apache/php54/
    ScriptAlias /php/ "C:/apache/php54/"
    AddType application/x-httpd-php .php
    Action application/x-httpd-php "/php/php-cgi.exe"
</ifdefine>

<ifdefine php55>
    SetEnv PHPRC C:/apache/php55/
    ScriptAlias /php/ "C:/apache/php55/"
    AddType application/x-httpd-php .php
    Action application/x-httpd-php "/php/php-cgi.exe"
</ifdefine>

Now using the httpd.exe create two separate services from command line (elevated to administrator):

httpd.exe -k install -n Apache224_php54 -D php54

httpd.exe -k install -n Apache224_php55 -D php55

Now you can start one of the above services at a time (should shutdown one before starting the other).

If you have previously installed Apache as service you can remove that using below command (replace the service name with the one you have used):

apache -k uninstall -n Apache224

One further note is that I personally use a "notification area icon program" called "Seobiseu" to start and stop services as needed. I have added the two above services to it.

How to make bootstrap 3 fluid layout without horizontal scrollbar

This is a known issue in BS 3 - https://github.com/twbs/bootstrap/issues/9862?source=cc

I have tested on Bootply using the latest build, so keep watching GitHub for the latest updates/fix.

In Bootstrap 3, .row is must be used inside a .container or .container-fluid to counteract the negative margins on the row. This will eliminate the horizontal scrollbar.

From the docs...

"Rows must be placed within a .container (fixed-width) or .container-fluid (full-width) for proper alignment and padding."

Bootstrap 4

The container>row>col relationship work the same way as 3.x...

"Containers are the most basic layout element in Bootstrap and are required when using our default grid system"

How to throw std::exceptions with variable messages?

Maybe this?

throw std::runtime_error(
    (std::ostringstream()
        << "Could not load config file '"
        << configfile
        << "'"
    ).str()
);

It creates a temporary ostringstream, calls the << operators as necessary and then you wrap that in round brackets and call the .str() function on the evaluated result (which is an ostringstream) to pass a temporary std::string to the constructor of runtime_error.

Note: the ostringstream and the string are r-value temporaries and so go out of scope after this line ends. Your exception object's constructor MUST take the input string using either copy or (better) move semantics.

Additional: I don't necessarily consider this approach "best practice", but it does work and can be used at a pinch. One of the biggest issues is that this method requires heap allocations and so the operator << can throw. You probably don't want that happening; however, if your get into that state your probably have way more issues to worry about!

Warning: DOMDocument::loadHTML(): htmlParseEntityRef: expecting ';' in Entity,

I know this is an old question, but if you ever want ot fix the malformed '&' signs in your HTML. You can use code similar to this:

$page = file_get_contents('http://www.example.com');
$page = preg_replace('/\s+/', ' ', trim($page));
fixAmps($page, 0);
$dom->loadHTML($page);


function fixAmps(&$html, $offset) {
    $positionAmp = strpos($html, '&', $offset);
    $positionSemiColumn = strpos($html, ';', $positionAmp+1);

    $string = substr($html, $positionAmp, $positionSemiColumn-$positionAmp+1);

    if ($positionAmp !== false) { // If an '&' can be found.
        if ($positionSemiColumn === false) { // If no ';' can be found.
            $html = substr_replace($html, '&amp;', $positionAmp, 1); // Replace straight away.
        } else if (preg_match('/&(#[0-9]+|[A-Z|a-z|0-9]+);/', $string) === 0) { // If a standard escape cannot be found.
            $html = substr_replace($html, '&amp;', $positionAmp, 1); // This mean we need to escape the '&' sign.
            fixAmps($html, $positionAmp+5); // Recursive call from the new position.
        } else {
            fixAmps($html, $positionAmp+1); // Recursive call from the new position.
        }
    }
}

How to break out of multiple loops?

This isn't the prettiest way to do it, but in my opinion, it's the best way.

def loop():
    while True:
    #snip: print out current state
        while True:
            ok = get_input("Is this ok? (y/n)")
            if ok == "y" or ok == "Y": return
            if ok == "n" or ok == "N": break
        #do more processing with menus and stuff

I'm pretty sure you could work out something using recursion here as well, but I don't know if that's a good option for you.

How do I enable index downloads in Eclipse for Maven dependency search?

  1. In Eclipse, click on Windows > Preferences, and then choose Maven in the left side.
  2. Check the box "Download repository index updates on startup".
    • Optionally, check the boxes Download Artifact Sources and Download Artifact JavaDoc.
  3. Click OK. The warning won't appear anymore.
  4. Restart Eclipse.

http://i.imgur.com/IJ2T3vc.png

Python way to clone a git repository

Here's a way to print progress while cloning a repo with GitPython

import time
import git
from git import RemoteProgress

class CloneProgress(RemoteProgress):
    def update(self, op_code, cur_count, max_count=None, message=''):
        if message:
            print(message)

print('Cloning into %s' % git_root)
git.Repo.clone_from('https://github.com/your-repo', '/your/repo/dir', 
        branch='master', progress=CloneProgress())

How to find out the number of CPUs using python

In Python 3.4+: os.cpu_count().

multiprocessing.cpu_count() is implemented in terms of this function but raises NotImplementedError if os.cpu_count() returns None ("can't determine number of CPUs").

Converting NSString to NSDictionary / JSON

I think you get the array from response so you have to assign response to array.

NSError *err = nil;
NSArray *array = [NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
NSDictionary *dictionary = [array objectAtIndex:0];
NSString *test = [dictionary objectForKey:@"ID"];
NSLog(@"Test is %@",test);

Communication between multiple docker-compose projects

The previous posts information is correct, but it does not have details on how to link containers, which should be connected as "external_links".

Hope this example make more clear to you:

  • Suppose you have app1/docker-compose.yml, with two services (svc11 and svc12), and app2/docker-compose.yml with two more services (svc21 and svc22) and suppose you need to connect in a crossed fashion:

  • svc11 needs to connect to svc22's container

  • svc21 needs to connect to svc11's container.

So the configuration should be like this:

this is app1/docker-compose.yml:


version: '2'
services:
    svc11:
        container_name: container11
        [..]
        networks:
            - default # this network
            - app2_default # external network
        external_links:
            - container22:container22
        [..]
    svc12:
       container_name: container12
       [..]

networks:
    default: # this network (app1)
        driver: bridge
    app2_default: # external network (app2)
        external: true

this is app2/docker-compose.yml:


version: '2'
services:
    svc21:
        container_name: container21
        [..]
        networks:
            - default # this network (app2)
            - app1_default # external network (app1)
        external_links:
            - container11:container11
        [..]
    svc22:
       container_name: container22
       [..]

networks:
    default: # this network (app2)
        driver: bridge
    app1_default: # external network (app1)
        external: true

Aligning two divs side-by-side

If you wrapped your divs, like this:

<div id="main">
  <div id="sidebar"></div>
  <div id="page-wrap"></div>
</div>

You could use this styling:

#main { 
    width: 800px;
    margin: 0 auto;
}
#sidebar    {
    width: 200px;
    height: 400px;
    background: red;
    float: left;
}

#page-wrap  {
    width: 600px;
    background: #ffffff;
    height: 400px;
    margin-left: 200px;
}

This is a slightly different look though, so I'm not sure it's what you're after. This would center all 800px as a unit, not the 600px centered with the 200px on the left side. The basic approach is your sidebar floats left, but inside the main div, and the #page-wrap has the width of your sidebar as it's left margin to move that far over.

Update based on comments: For this off-centered look, you can do this:

<div id="page-wrap">
  <div id="sidebar"></div>
</div>

With this styling:

#sidebar    {
    position: absolute;
    left: -200px;
    width: 200px;
    height: 400px;
    background: red;    
}

#page-wrap  {
    position: relative;
    width: 600px;
    background: #ffffff;
    height: 400px;
    margin: 0 auto;
}

How to check if command line tools is installed

Yosemite

Below are a few extra steps on a fresh Mac that some people might need. This adds a little to @jnovack's excellent answer.

Update: A few other notes when setting this up:

Make sure your admin user has a password. A blank password won't work when trying to enable a root user.

System Preferences > Users and Groups > (select user) > Change password

Then to enable root, run dsenableroot in a terminal:

$ dsenableroot
username = mac_admin_user
user password:
root password:
verify root password:

dsenableroot:: ***Successfully enabled root user.

Type in the admin user's password, then the new enabled root password twice.

Next type:

sudo gcc

or

sudo make

It will respond with something like the following:

WARNING: Improper use of the sudo command could lead to data loss
or the deletion of important system files. Please double-check your
typing when using sudo. Type "man sudo" for more information.

To proceed, enter your password, or type Ctrl-C to abort.

Password:


You have not agreed to the Xcode license agreements. You must agree to 
both license agreements below in order to use Xcode.

Press enter when it prompts to show you the license agreement.

Hit the Enter key to view the license agreements at 
'/Applications/Xcode.app/Contents/Resources/English.lproj/License.rtf'

IMPORTANT: BY USING THIS SOFTWARE, YOU ARE AGREEING TO BE BOUND BY THE 
FOLLOWING APPLE TERMS:

//...

Press q to exit the license agreement view.

By typing 'agree' you are agreeing to the terms of the software license 
agreements. Type 'print' to print them or anything else to cancel, 
[agree, print, cancel]

Type agree. And then it will end with:

clang: error: no input files 

Which basically means that you didn't give make or gcc any input files.

Here is what the check looked like:

$ xcode-select -p
/Applications/Xcode.app/Contents/Developer

Mavericks

With Mavericks, it is a little different now.

When the tools were NOT found, this is what the command pkgutil command returned:

$ pkgutil --pkg-info=com.apple.pkg.CLTools_Executables
No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.

To install the command line tools, this works nicely from the Terminal, with a nice gui and everything.

$ xcode-select --install

http://macops.ca/installing-command-line-tools-automatically-on-mavericks/

When they were found, this is what the pkgutil command returned:

$ pkgutil --pkg-info=com.apple.pkg.CLTools_Executables
package-id: com.apple.pkg.CLTools_Executables
version: 5.0.1.0.1.1382131676
volume: /
location: /
install-time: 1384149984
groups: com.apple.FindSystemFiles.pkg-group com.apple.DevToolsBoth.pkg-group com.apple.DevToolsNonRelocatableShared.pkg-group 

This command returned the same before and after the install.

$ pkgutil --pkg-info=com.apple.pkg.DeveloperToolsCLI
No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'.

Also I had the component for the CLT selected and installed in xcode's downloads section before, but it seems like it didn't make it to the terminal...

Hope that helps.

Cannot make Project Lombok work on Eclipse

Don't forget to do to Project->Clean in eclipse to make sure that your classes are recompiled.

Why do I get an UnsupportedOperationException when trying to remove an element from a List?

Yes, on Arrays.asList, returning a fixed-size list.

Other than using a linked list, simply use addAll method list.

Example:

String idList = "123,222,333,444";

List<String> parentRecepeIdList = new ArrayList<String>();

parentRecepeIdList.addAll(Arrays.asList(idList.split(","))); 

parentRecepeIdList.add("555");

Counter increment in Bash loop not working

There were two conditions that caused the expression ((var++)) to fail for me:

  1. If I set bash to strict mode (set -euo pipefail) and if I start my increment at zero (0).

  2. Starting at one (1) is fine but zero causes the increment to return "1" when evaluating "++" which is a non-zero return code failure in strict mode.

I can either use ((var+=1)) or var=$((var+1)) to escape this behavior

VB.NET 'If' statement with 'Or' conditional has both sides evaluated?

It's your "fault" in that that's how Or is defined, so it's the behaviour you should expect:

In a Boolean comparison, the Or operator always evaluates both expressions, which could include making procedure calls. The OrElse Operator (Visual Basic) performs short-circuiting, which means that if expression1 is True, then expression2 is not evaluated.

But you don't have to endure it. You can use OrElse to get short-circuiting behaviour.

So you probably want:

If (example Is Nothing OrElse Not example.Item = compare.Item) Then
    'Proceed
End If

I can't say it reads terribly nicely, but it should work...

xlrd.biffh.XLRDError: Excel xlsx file; not supported

As noted in the release email, linked to from the release tweet and noted in large orange warning that appears on the front page of the documentation, and less orange, but still present, in the readme on the repository and the release on pypi:

xlrd has explicitly removed support for anything other than xls files.

In your case, the solution is to:

  • make sure you are on a recent version of Pandas, at least 1.0.1, and preferably the latest release. 1.2 will make his even clearer.
  • install openpyxl: https://openpyxl.readthedocs.io/en/stable/
  • change your Pandas code to be:
    df1 = pd.read_excel(
         os.path.join(APP_PATH, "Data", "aug_latest.xlsm"),
         engine='openpyxl',
    )
    

How to find the php.ini file used by the command line?

From what I remember when I used to use EasyPHP, the php.ini file is either in C:\Windows\ or C:\Windows\System32

When and how should I use a ThreadLocal variable?

The documentation says it very well: "each thread that accesses [a thread-local variable] (via its get or set method) has its own, independently initialized copy of the variable".

You use one when each thread must have its own copy of something. By default, data is shared between threads.

Equivalent of "continue" in Ruby

Inside for-loops and iterator methods like each and map the next keyword in ruby will have the effect of jumping to the next iteration of the loop (same as continue in C).

However what it actually does is just to return from the current block. So you can use it with any method that takes a block - even if it has nothing to do with iteration.

How to fully clean bin and obj folders within Visual Studio?

If you are using git and have a correct .gitignore in your project, you can

git clean -xdf --dry-run

to remove absolutely every file on the .gitignore list, i.e. it will clean obj, and bin folders (the x triggers this behavior)

how to access parent window object using jquery?

Here is a more literal answer (parent window as opposed to opener) to the original question that can be used within an iframe, assuming the domain name in the iframe matches that of the parent window:

window.parent.$("#serverMsg")

How do I copy folder with files to another folder in Unix/Linux?

The option you're looking for is -R.

cp -R path_to_source path_to_destination/
  • If destination doesn't exist, it will be created.
  • -R means copy directories recursively. You can also use -r since it's case-insensitive.
  • Note the nuances with adding the trailing / as per @muni764's comment.

Where is SQL Profiler in my SQL Server 2008?

Also ensure that "client tools" are selected in the install options. However if SQL Managment Studio 2008 exists then it is likely that you installed the express edition.

How to Count Duplicates in List with LINQ

Slightly shorter version using methods chain:

var list = new List<string> {"a", "b", "a", "c", "a", "b"};
var q = list.GroupBy(x => x)
            .Select(g => new {Value = g.Key, Count = g.Count()})
            .OrderByDescending(x=>x.Count);

foreach (var x in q)
{
    Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}

Passing string parameter in JavaScript function

You can pass string parameters to JavaScript functions like below code:

I passed three parameters where the third one is a string parameter.

var btn ="<input type='button' onclick='RoomIsReadyFunc(" + ID + "," + RefId + ",\"" + YourString + "\");'  value='Room is Ready' />";

// Your JavaScript function

function RoomIsReadyFunc(ID, RefId, YourString)
{
    alert(ID);
    alert(RefId);
    alert(YourString);
}

Remove all child elements of a DOM node in JavaScript

Using a range loop feels the most natural to me:

for (var child of node.childNodes) {
    child.remove();
}

According to my measurements in Chrome and Firefox, it is about 1.3x slower. In normal circumstances, this will perhaps not matter.

How to ignore user's time zone and force Date() use specific time zone

My solutions is to determine timezone adjustment the browser applies, and reverse it:

var timestamp = 1600913205;  //retrieved from unix, that is why it is in seconds

//uncomment below line if you want to apply Pacific timezone
//timestamp += -25200;

//determine the timezone offset the browser applies to Date()
var offset = (new Date()).getTimezoneOffset() * 60;   

//re-initialize the Date function to reverse the timezone adjustment
var date = new Date((timestamp + offset) * 1000);

//here continue using date functions.

This point the date will be timezone free and always UTC, You can apply your own offset to timestamp to produce any timezone.

SQL Update Multiple Fields FROM via a SELECT Statement

I would write it this way

UPDATE s
SET    OrgAddress1 = bd.OrgAddress1,    OrgAddress2 = bd.OrgAddress2,    
     ...    DestZip = bd.DestZip
--select s.OrgAddress1, bd.OrgAddress1, s.OrgAddress2, bd.OrgAddress2, etc 
FROM    Shipment s
JOIN ProfilerTest.dbo.BookingDetails bd on  bd.MyID =s.MyID2
WHERE    bd.MyID = @MyId 

This way the join is explicit as implicit joins are a bad thing IMHO. You can run the commented out select (usually I specify the fields I'm updating old and new values next to each other) to make sure that what I am going to update is exactly what I meant to update.

How can I erase all inline styles with javascript and leave only the styles specified in the css style sheet?

If you need to just empty the style of an element then:
element.style.cssText = null;
This should do good. Hope it helps!

Returning a value even if no result

if you want both always a return value but never a null value you can combine count with coalesce :

select count(field1), coalesce(field1,'any_other_default_value') from table;

that because count, will force mysql to always return a value (0 if there is no values to count) and coalesce will force mysql to always put a value that is not null

What does random.sample() method in python do?

random.sample(population, k)

It is used for randomly sampling a sample of length 'k' from a population. returns a 'k' length list of unique elements chosen from the population sequence or set

it returns a new list and leaves the original population unchanged and the resulting list is in selection order so that all sub-slices will also be valid random samples

I am putting up an example in which I am splitting a dataset randomly. It is basically a function in which you pass x_train(population) as an argument and return indices of 60% of the data as D_test.

import random

def randomly_select_70_percent_of_data_from_1_to_length(x_train):
    return random.sample(range(0, len(x_train)), int(0.6*len(x_train)))

How to align two elements on the same line without changing HTML

Change your css as below

#element1 {float:left;margin-right:10px;} 
#element2 {float:left;} 

Here is the JSFiddle http://jsfiddle.net/a4aME/

Access props inside quotes in React JSX

Best practices are to add getter method for that :

getImageURI() {
  return "images/" + this.props.image;
}

<img className="image" src={this.getImageURI()} />

Then , if you have more logic later on, you can maintain the code smoothly.

What is JavaScript's highest integer value that a number can go to without losing precision?

I did a simple test with a formula, X-(X+1)=-1, and the largest value of X I can get to work on Safari, Opera and Firefox (tested on OS X) is 9e15. Here is the code I used for testing:

javascript: alert(9e15-(9e15+1));

How to submit a form using Enter key in react.js?

import React, { useEffect, useRef } from 'react';

function Example() {

    let inp = useRef();
    useEffect(() => {
        if (!inp && !inp.current) return;
        inp.current.focus();
        return () => inp = null;
    });

    const handleSubmit = () => {
        //...
    }

    return (
        <form
            onSubmit={e => {
                e.preventDefault();
                handleSubmit(e);
            }}
        >
            <input
                name="fakename"
                defaultValue="...."
                ref={inp}
                type="radio"
                style={{
                    position: "absolute",
                    opacity: 0
                }}
            />
            <button type="submit">
                submit
            </button>
        </form>
    )
}

Enter code here sometimes in popups it would not work to binding just a form and passing the onSubmit to the form because form may not have any input.

In this case if you bind the event to the document by doing document.addEventListener it will cause problem in another parts of the application.

For solving this issue we should wrap a form and should put a input with what is hidden by css, then you focus on that input by ref it will be work correctly.

Execute another jar in a Java program

The following works by starting the jar with a batch file, in case the program runs as a stand alone:

public static void startExtJarProgram(){
        String extJar = Paths.get("C:\\absolute\\path\\to\\batchfile.bat").toString();
        ProcessBuilder processBuilder = new ProcessBuilder(extJar);
        processBuilder.redirectError(new File(Paths.get("C:\\path\\to\\JavaProcessOutput\\extJar_out_put.txt").toString()));
        processBuilder.redirectInput();
        try {
           final Process process = processBuilder.start();
            try {
                final int exitStatus = process.waitFor();
                if(exitStatus==0){
                    System.out.println("External Jar Started Successfully.");
                    System.exit(0); //or whatever suits 
                }else{
                    System.out.println("There was an error starting external Jar. Perhaps path issues. Use exit code "+exitStatus+" for details.");
                    System.out.println("Check also C:\\path\\to\\JavaProcessOutput\\extJar_out_put.txt file for additional details.");
                    System.exit(1);//whatever
                }
            } catch (InterruptedException ex) {
                System.out.println("InterruptedException: "+ex.getMessage());
            }
        } catch (IOException ex) {
            System.out.println("IOException. Faild to start process. Reason: "+ex.getMessage());
        }
        System.out.println("Process Terminated.");
        System.exit(0);
    }

In the batchfile.bat then we can say:

@echo off
start /min C:\path\to\jarprogram.jar

How do I delay a function call for 5 seconds?

You can use plain javascript, this will call your_func once, after 5 seconds:

setTimeout(function() { your_func(); }, 5000);

If your function has no parameters and no explicit receiver you can call directly setTimeout(func, 5000)

There is also a plugin I've used once. It has oneTime and everyTime methods.

How can I time a code segment for testing performance with Pythons timeit?

The testing suite doesn't make an attempt at using the imported timeit so it's hard to tell what the intent was. Nonetheless, this is a canonical answer so a complete example of timeit seems in order, elaborating on Martijn's answer.

The docs for timeit offer many examples and flags worth checking out. The basic usage on the command line is:

$ python -mtimeit "all(True for _ in range(1000))"
2000 loops, best of 5: 161 usec per loop
$ python -mtimeit "all([True for _ in range(1000)])"
2000 loops, best of 5: 116 usec per loop

Run with -h to see all options. Python MOTW has a great section on timeit that shows how to run modules via import and multiline code strings from the command line.

In script form, I typically use it like this:

import argparse
import copy
import dis
import inspect
import random
import sys
import timeit

def test_slice(L):
    L[:]

def test_copy(L):
    L.copy()

def test_deepcopy(L):
    copy.deepcopy(L)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--n", type=int, default=10 ** 5)
    parser.add_argument("--trials", type=int, default=100)
    parser.add_argument("--dis", action="store_true")
    args = parser.parse_args()
    n = args.n
    trials = args.trials
    namespace = dict(L = random.sample(range(n), k=n))
    funcs_to_test = [x for x in locals().values() 
                     if callable(x) and x.__module__ == __name__]
    print(f"{'-' * 30}\nn = {n}, {trials} trials\n{'-' * 30}\n")

    for func in funcs_to_test:
        fname = func.__name__
        fargs = ", ".join(inspect.signature(func).parameters)
        stmt = f"{fname}({fargs})"
        setup = f"from __main__ import {fname}"
        time = timeit.timeit(stmt, setup, number=trials, globals=namespace)
        print(inspect.getsource(globals().get(fname)))

        if args.dis:
            dis.dis(globals().get(fname))

        print(f"time (s) => {time}\n{'-' * 30}\n")

You can pretty easily drop in the functions and arguments you need. Use caution when using impure functions and take care of state.

Sample output:

$ python benchmark.py --n 10000
------------------------------
n = 10000, 100 trials
------------------------------

def test_slice(L):
    L[:]

time (s) => 0.015502399999999972
------------------------------

def test_copy(L):
    L.copy()

time (s) => 0.01651419999999998
------------------------------

def test_deepcopy(L):
    copy.deepcopy(L)

time (s) => 2.136012
------------------------------

import module from string variable

importlib.import_module is what you are looking for. It returns the imported module. (Only available for Python >= 2.7 or 3.x):

import importlib

mymodule = importlib.import_module('matplotlib.text')

You can thereafter access anything in the module as mymodule.myclass, etc.

How to completely remove Python from a Windows machine?

Run ASSOC and FTYPE to see what your py files are associated to. (These commands are internal to cmd.exe so if you use a different command processor ymmv.)

C:> assoc .py
.py=Python.File

C:> ftype Python.File
Python.File="C:\Python26.w64\python.exe" "%1" %*

C:> assoc .pyw
.pyw=Python.NoConFile

C:> ftype Python.NoConFile
Python.NoConFile="C:\Python26.w64\pythonw.exe" "%1" %*

(I have both 32- and 64-bit installs of Python, hence my local directory name.)

How to replace a whole line with sed?

Like this:

sed 's/aaa=.*/aaa=xxx/'

If you want to guarantee that the aaa= is at the start of the line, make it:

sed 's/^aaa=.*/aaa=xxx/'

How to parse XML to R data frame

Here's a partial solution using xml2. Breaking the solution up into smaller pieces generally makes it easier to ensure everything is lined up:

library(xml2)
data <- read_xml("http://forecast.weather.gov/MapClick.php?lat=29.803&lon=-82.411&FcstType=digitalDWML")

# Point locations
point <- data %>% xml_find_all("//point")
point %>% xml_attr("latitude") %>% as.numeric()
point %>% xml_attr("longitude") %>% as.numeric()

# Start time
data %>% 
  xml_find_all("//start-valid-time") %>% 
  xml_text()

# Temperature
data %>% 
  xml_find_all("//temperature[@type='hourly']/value") %>% 
  xml_text() %>% 
  as.integer()

How to deal with "data of class uneval" error from ggplot2?

when you add a new data set to a geom you need to use the data= argument. Or put the arguments in the proper order mapping=..., data=.... Take a look at the arguments for ?geom_line.

Thus:

p + geom_line(data=df.last, aes(HrEnd, MWh, group=factor(Date)), color="red") 

Or:

p + geom_line(aes(HrEnd, MWh, group=factor(Date)), df.last, color="red") 

What is the difference between onBlur and onChange attribute in HTML?

I think it's important to note here that onBlur() fires regardless.

This is a helpful thread but the only thing it doesn't clarify is that onBlur() will fire every single time.

onChange() will only fire when the value is changed.

Difference between mkdir() and mkdirs() in java for java.io.File

mkdirs() will create the specified directory path in its entirety where mkdir() will only create the bottom most directory, failing if it can't find the parent directory of the directory it is trying to create.

In other words mkdir() is like mkdir and mkdirs() is like mkdir -p.

For example, imagine we have an empty /tmp directory. The following code

new File("/tmp/one/two/three").mkdirs();

would create the following directories:

  • /tmp/one
  • /tmp/one/two
  • /tmp/one/two/three

Where this code:

new File("/tmp/one/two/three").mkdir();

would not create any directories - as it wouldn't find /tmp/one/two - and would return false.

How to Multi-thread an Operation Within a Loop in Python

First, in Python, if your code is CPU-bound, multithreading won't help, because only one thread can hold the Global Interpreter Lock, and therefore run Python code, at a time. So, you need to use processes, not threads.

This is not true if your operation "takes forever to return" because it's IO-bound—that is, waiting on the network or disk copies or the like. I'll come back to that later.


Next, the way to process 5 or 10 or 100 items at once is to create a pool of 5 or 10 or 100 workers, and put the items into a queue that the workers service. Fortunately, the stdlib multiprocessing and concurrent.futures libraries both wraps up most of the details for you.

The former is more powerful and flexible for traditional programming; the latter is simpler if you need to compose future-waiting; for trivial cases, it really doesn't matter which you choose. (In this case, the most obvious implementation with each takes 3 lines with futures, 4 lines with multiprocessing.)

If you're using 2.6-2.7 or 3.0-3.1, futures isn't built in, but you can install it from PyPI (pip install futures).


Finally, it's usually a lot simpler to parallelize things if you can turn the entire loop iteration into a function call (something you could, e.g., pass to map), so let's do that first:

def try_my_operation(item):
    try:
        api.my_operation(item)
    except:
        print('error with item')

Putting it all together:

executor = concurrent.futures.ProcessPoolExecutor(10)
futures = [executor.submit(try_my_operation, item) for item in items]
concurrent.futures.wait(futures)

If you have lots of relatively small jobs, the overhead of multiprocessing might swamp the gains. The way to solve that is to batch up the work into larger jobs. For example (using grouper from the itertools recipes, which you can copy and paste into your code, or get from the more-itertools project on PyPI):

def try_multiple_operations(items):
    for item in items:
        try:
            api.my_operation(item)
        except:
            print('error with item')

executor = concurrent.futures.ProcessPoolExecutor(10)
futures = [executor.submit(try_multiple_operations, group) 
           for group in grouper(5, items)]
concurrent.futures.wait(futures)

Finally, what if your code is IO bound? Then threads are just as good as processes, and with less overhead (and fewer limitations, but those limitations usually won't affect you in cases like this). Sometimes that "less overhead" is enough to mean you don't need batching with threads, but you do with processes, which is a nice win.

So, how do you use threads instead of processes? Just change ProcessPoolExecutor to ThreadPoolExecutor.

If you're not sure whether your code is CPU-bound or IO-bound, just try it both ways.


Can I do this for multiple functions in my python script? For example, if I had another for loop elsewhere in the code that I wanted to parallelize. Is it possible to do two multi threaded functions in the same script?

Yes. In fact, there are two different ways to do it.

First, you can share the same (thread or process) executor and use it from multiple places with no problem. The whole point of tasks and futures is that they're self-contained; you don't care where they run, just that you queue them up and eventually get the answer back.

Alternatively, you can have two executors in the same program with no problem. This has a performance cost—if you're using both executors at the same time, you'll end up trying to run (for example) 16 busy threads on 8 cores, which means there's going to be some context switching. But sometimes it's worth doing because, say, the two executors are rarely busy at the same time, and it makes your code a lot simpler. Or maybe one executor is running very large tasks that can take a while to complete, and the other is running very small tasks that need to complete as quickly as possible, because responsiveness is more important than throughput for part of your program.

If you don't know which is appropriate for your program, usually it's the first.

Convert List<T> to ObservableCollection<T> in WP7

ObservableCollection has several constructors which have input parameter of List<T> or IEnumerable<T>:
List<T> list = new List<T>();
ObservableCollection<T> collection = new ObservableCollection<T>(list);

Remove all stylings (border, glow) from textarea

try this:

textarea {
        border-style: none;
        border-color: Transparent;
        overflow: auto;
        outline: none;
      }

jsbin: http://jsbin.com/orozon/2/

How to use onClick() or onSelect() on option tag in a JSP page?

<html>
<head>
<title>Cars</title>
</head>
<body >

<h1>Cars</h1>
    <p>Name </p>
        <select id="selectBox" onchange="myFunction(value);">
            <option value="volvo" >Volvo</option>
            <option value="saab"  >Saab</option>
            <option value="mercedes">Mercedes</option>
        </select>        
<p id="result"> Price : </p>
<script>
function myFunction($value)
{       
    if($value=="volvo")
    {document.getElementById("result").innerHTML = "30L";}
    else if($value=="saab")
    {document.getElementById("result").innerHTML = "40L";}
     else if($value=="mercedes")
    {document.getElementById("result").innerHTML = "50L";}
}
</script>
</body>
</html>```

How to shutdown a Spring Boot Application in a correct way?

As to @Jean-Philippe Bond 's answer ,

here is a maven quick example for maven user to configure HTTP endpoint to shutdown a spring boot web app using spring-boot-starter-actuator so that you can copy and paste:

1.Maven pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

2.application.properties:

#No auth  protected 
endpoints.shutdown.sensitive=false

#Enable shutdown endpoint
endpoints.shutdown.enabled=true

All endpoints are listed here:

3.Send a post method to shutdown the app:

curl -X POST localhost:port/shutdown

Security Note:

if you need the shutdown method auth protected, you may also need

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>

configure details:

How to get summary statistics by group

The psych package has a great option for grouped summary stats:

library(psych)
    
describeBy(dt, group="grp")

produces lots of useful stats including mean, median, range, sd, se.

Could not find a base address that matches scheme https for the endpoint with binding WebHttpBinding. Registered base address schemes are [http]

Change

<serviceMetadata httpsGetEnabled="true"/>

to

<serviceMetadata httpsGetEnabled="false"/>

You're telling WCF to use https for the metadata endpoint and I see that your'e exposing your service on http, and then you get the error in the title.

You also have to set <security mode="None" /> if you want to use HTTP as your URL suggests.

How to split a number into individual digits in c#?

I'd use modulus and a loop.

int[] GetIntArray(int num)
{
    List<int> listOfInts = new List<int>();
    while(num > 0)
    {
        listOfInts.Add(num % 10);
        num = num / 10;
    }
    listOfInts.Reverse();
    return listOfInts.ToArray();
}

Showing data values on stacked bar chart in ggplot2

From ggplot 2.2.0 labels can easily be stacked by using position = position_stack(vjust = 0.5) in geom_text.

ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
  geom_bar(stat = "identity") +
  geom_text(size = 3, position = position_stack(vjust = 0.5))

enter image description here

Also note that "position_stack() and position_fill() now stack values in the reverse order of the grouping, which makes the default stack order match the legend."


Answer valid for older versions of ggplot:

Here is one approach, which calculates the midpoints of the bars.

library(ggplot2)
library(plyr)

# calculate midpoints of bars (simplified using comment by @DWin)
Data <- ddply(Data, .(Year), 
   transform, pos = cumsum(Frequency) - (0.5 * Frequency)
)

# library(dplyr) ## If using dplyr... 
# Data <- group_by(Data,Year) %>%
#    mutate(pos = cumsum(Frequency) - (0.5 * Frequency))

# plot bars and add text
p <- ggplot(Data, aes(x = Year, y = Frequency)) +
     geom_bar(aes(fill = Category), stat="identity") +
     geom_text(aes(label = Frequency, y = pos), size = 3)

Resultant chart

How to style icon color, size, and shadow of Font Awesome Icons

In FontAwesome 4.0, the classes change to 'fa-2x', 'fa-3x'.

How do I remove blank elements from an array?

Plain Ruby:

values = [1,2,3, " ", "", "", nil] - ["", " ", nil]
puts values # [1,2,3]

Apply pandas function to column to create multiple new columns?

Building off of user1827356 's answer, you can do the assignment in one pass using df.merge:

df.merge(df.textcol.apply(lambda s: pd.Series({'feature1':s+1, 'feature2':s-1})), 
    left_index=True, right_index=True)

    textcol  feature1  feature2
0  0.772692  1.772692 -0.227308
1  0.857210  1.857210 -0.142790
2  0.065639  1.065639 -0.934361
3  0.819160  1.819160 -0.180840
4  0.088212  1.088212 -0.911788

EDIT: Please be aware of the huge memory consumption and low speed: https://ys-l.github.io/posts/2015/08/28/how-not-to-use-pandas-apply/ !

Understanding [TCP ACKed unseen segment] [TCP Previous segment not captured]

That very well may be a false positive. Like the warning message says, it is common for a capture to start in the middle of a tcp session. In those cases it does not have that information. If you are really missing acks then it is time to start looking upstream from your host for where they are disappearing. It is possible that tshark can not keep up with the data and so it is dropping some metrics. At the end of your capture it will tell you if the "kernel dropped packet" and how many. By default tshark disables dns lookup, tcpdump does not. If you use tcpdump you need to pass in the "-n" switch. If you are having a disk IO issue then you can do something like write to memory /dev/shm. BUT be careful because if your captures get very large then you can cause your machine to start swapping.

My bet is that you have some very long running tcp sessions and when you start your capture you are simply missing some parts of the tcp session due to that. Having said that, here are some of the things that I have seen cause duplicate/missing acks.

  1. Switches - (very unlikely but sometimes they get in a sick state)
  2. Routers - more likely than switches, but not much
  3. Firewall - More likely than routers. Things to look for here are resource exhaustion (license, cpu, etc)
  4. Client side filtering software - antivirus, malware detection etc.

Collections sort(List<T>,Comparator<? super T>) method example

This might be simplest way -

Collections.sort(listOfStudent,new Comparator<Student>(){
                     public int compare(Student s1,Student s2){
                           // Write your logic here.
                     }});

Using Java 8(lambda expression) -

listOfStudent.sort((s1, s2) -> s1.age - s2.age); 

How to UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) in PostgreSQL?

SQLAlchemy upsert for Postgres >=9.5

Since the large post above covers many different SQL approaches for Postgres versions (not only non-9.5 as in the question), I would like to add how to do it in SQLAlchemy if you are using Postgres 9.5. Instead of implementing your own upsert, you can also use SQLAlchemy's functions (which were added in SQLAlchemy 1.1). Personally, I would recommend using these, if possible. Not only because of convenience, but also because it lets PostgreSQL handle any race conditions that might occur.

Cross-posting from another answer I gave yesterday (https://stackoverflow.com/a/44395983/2156909)

SQLAlchemy supports ON CONFLICT now with two methods on_conflict_do_update() and on_conflict_do_nothing():

Copying from the documentation:

from sqlalchemy.dialects.postgresql import insert

stmt = insert(my_table).values(user_email='[email protected]', data='inserted data')
stmt = stmt.on_conflict_do_update(
    index_elements=[my_table.c.user_email],
    index_where=my_table.c.user_email.like('%@gmail.com'),
    set_=dict(data=stmt.excluded.data)
    )
conn.execute(stmt)

http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html?highlight=conflict#insert-on-conflict-upsert

Parse date string and change format

>>> from_date="Mon Feb 15 2010"
>>> import time                
>>> conv=time.strptime(from_date,"%a %b %d %Y")
>>> time.strftime("%d/%m/%Y",conv)
'15/02/2010'

Exception : javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

This exception will come in case your server is based on JDK 7 and your client is on JDK 6 and using SSL certificates. In JDK 7 sslv2hello message handshaking is disabled by default while in JDK 6 sslv2hello message handshaking is enabled. For this reason when your client trying to connect server then a sslv2hello message will be sent towards server and due to sslv2hello message disable you will get this exception. To solve this either you have to move your client to JDK 7 or you have to use 6u91 version of JDK. But to get this version of JDK you have to get the MOS (My Oracle Support) Enterprise support. This patch is not public.

How to copy data from one table to another new table in MySQL?

This will do what you want:

INSERT INTO table2 (st_id,uid,changed,status,assign_status)
SELECT st_id,from_uid,now(),'Pending','Assigned'
FROM table1

If you want to include all rows from table1. Otherwise you can add a WHERE statement to the end if you want to add only a subset of table1.

I hope this helps.

How can we generate getters and setters in Visual Studio?

You just simply press Alt + Ins in Android Studio.

After declaring variables, you will get the getters and setters in the generated code.

How do I launch a Git Bash window with particular working directory using a script?

Let yet add up to the answer from @Drew Noakes:

Target:

"C:\Program Files\Git\git-bash.exe" --cd=C:\GitRepo

The cd param should be one of the options how to specify the working directory.

Also notice, that I have not any --login param there: Instead, I use another extra app, dedicated just for SSH keys: Pageant (PuTTY authentication agent).

Start in:

C:\GitRepo

The same possible way, as @Drew Noakes mentioned/shown here sooner, I use it too.

Shortcut key:

Ctrl + Alt + B

Such shortcuts are another less known feature in Windows. But there is a restriction: To let the shortcut take effect, it must be placed somewhere on the User's subdirectory: The Desktop is fine.

If you do not want it visible, yet still activatable, place this .lnk file i.e. to the quick launch folder, as that dir is purposed for such shortcuts. (no matter whether displayed on the desktop) #76080 #3619355

"\Application Data\Microsoft\Internet Explorer\Quick Launch\"

Move entire line up and down in Vim

If I want to swap one line with the line above I usually do the following

ddkP

Explanation

  • dd will delete the line and add it to the default register.
  • k will move up a line (j would move down a line)
  • P will paste above the current line

How to replace deprecated android.support.v4.app.ActionBarDrawerToggle

you must use import android.support.v7.app.ActionBarDrawerToggle;

and use the constructor

public CustomActionBarDrawerToggle(Activity mActivity,DrawerLayout mDrawerLayout)
{
    super(mActivity, mDrawerLayout, R.string.ns_menu_open, R.string.ns_menu_close);
}

and if the drawer toggle button becomes dark then you must use the supportActionBar provided in the support library.

You can implement supportActionbar from this link: http://developer.android.com/training/basics/actionbar/setting-up.html

How can I reorder a list?

If you use numpy there's a neat way to do it:

items = np.array(["a","b","c","d"])
indices = np.arange(items.shape[0])
np.random.shuffle(indices)
print(indices)
print(items[indices])

This code returns:

[1 3 2 0]
['b' 'd' 'c' 'a']

Vue.js dynamic images not working

Here is Very simple answer. :D

<div class="col-lg-2" v-for="pic in pics">
   <img :src="`../assets/${pic}.png`" :alt="pic">
</div>

Easy way to make a confirmation dialog in Angular?

I'm pretty late to the party, but here is another implementation using : https://stackblitz.com/edit/angular-confirmation-dialog

confirmation-dialog.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';

import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

import { ConfirmationDialogComponent } from './confirmation-dialog.component';

@Injectable()
export class ConfirmationDialogService {

  constructor(private modalService: NgbModal) { }

  public confirm(
    title: string,
    message: string,
    btnOkText: string = 'OK',
    btnCancelText: string = 'Cancel',
    dialogSize: 'sm'|'lg' = 'sm'): Promise<boolean> {
    const modalRef = this.modalService.open(ConfirmationDialogComponent, { size: dialogSize });
    modalRef.componentInstance.title = title;
    modalRef.componentInstance.message = message;
    modalRef.componentInstance.btnOkText = btnOkText;
    modalRef.componentInstance.btnCancelText = btnCancelText;

    return modalRef.result;
  }

}

confirmation-dialog.component.ts

import { Component, Input, OnInit } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-confirmation-dialog',
  templateUrl: './confirmation-dialog.component.html',
  styleUrls: ['./confirmation-dialog.component.scss'],
})
export class ConfirmationDialogComponent implements OnInit {

  @Input() title: string;
  @Input() message: string;
  @Input() btnOkText: string;
  @Input() btnCancelText: string;

  constructor(private activeModal: NgbActiveModal) { }

  ngOnInit() {
  }

  public decline() {
    this.activeModal.close(false);
  }

  public accept() {
    this.activeModal.close(true);
  }

  public dismiss() {
    this.activeModal.dismiss();
  }

}

confirmation-dialog.component.html

<div class="modal-header">
  <h4 class="modal-title">{{ title }}</h4>
    <button type="button" class="close" aria-label="Close" (click)="dismiss()">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    {{ message }}
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-danger" (click)="decline()">{{ btnCancelText }}</button>
    <button type="button" class="btn btn-primary" (click)="accept()">{{ btnOkText }}</button>
  </div>

Use the dialog like this:

public openConfirmationDialog() {
    this.confirmationDialogService.confirm('Please confirm..', 'Do you really want to ... ?')
    .then((confirmed) => console.log('User confirmed:', confirmed))
    .catch(() => console.log('User dismissed the dialog (e.g., by using ESC, clicking the cross icon, or clicking outside the dialog)'));
  }

Effective swapping of elements of an array in Java

inplace swapping (incase you already didn't know) can save a bit of space by not creating a temp variable.

arr[i] = arr[i] + arr[j];
arr[j] = arr[i] - arr[j];
arr[i] = arr[i] - arr[j];

Search a text file and print related lines in Python?

searchfile = open("file.txt", "r")
for line in searchfile:
    if "searchphrase" in line: print line
searchfile.close()

To print out multiple lines (in a simple way)

f = open("file.txt", "r")
searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
    if "searchphrase" in line: 
        for l in searchlines[i:i+3]: print l,
        print

The comma in print l, prevents extra spaces from appearing in the output; the trailing print statement demarcates results from different lines.

Or better yet (stealing back from Mark Ransom):

with open("file.txt", "r") as f:
    searchlines = f.readlines()
for i, line in enumerate(searchlines):
    if "searchphrase" in line: 
        for l in searchlines[i:i+3]: print l,
        print

MSVCP140.dll missing

That usually means that your friend does not have the Microsoft redistributable for Visual C++. I am of course assuming you are using VC++ and not MingW or another compiler. Since your friend does not have VS installed as well there is no guarantee he has the redist installed.

VC++ Distro

How can I reference a commit in an issue comment on GitHub?

Answer above is missing an example which might not be obvious (it wasn't to me).

Url could be broken down into parts

https://github.com/liufa/Tuplinator/commit/f36e3c5b3aba23a6c9cf7c01e7485028a23c3811
                  \_____/\________/       \_______________________________________/
                   |        |                              |
            Account name    |                      Hash of revision
                        Project name              

Hash can be found here (you can click it and will get the url from browser).

enter image description here

Hope this saves you some time.

TypeError: unhashable type: 'dict', when dict used as a key for another dict

From the error, I infer that referenceElement is a dictionary (see repro below). A dictionary cannot be hashed and therefore cannot be used as a key to another dictionary (or itself for that matter!).

>>> d1, d2 = {}, {}
>>> d1[d2] = 1
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unhashable type: 'dict'

You probably meant either for element in referenceElement.keys() or for element in json['referenceElement'].keys(). With more context on what types json and referenceElement are and what they contain, we will be able to better help you if neither solution works.

How to convert any Object to String?

To convert any object to string there are several methods in Java

String convertedToString = String.valueOf(Object);  //method 1

String convertedToString = "" + Object;   //method 2

String convertedToString = Object.toString();  //method 3

I would prefer the first and third

EDIT
If working in kotlin, the official android language

val number: Int = 12345
String convertAndAppendToString = "number = $number"   //method 1

String convertObjectMemberToString = "number = ${Object.number}" //method 2

String convertedToString = Object.toString()  //method 3

What is the Python equivalent of static variables inside a function?

Soulution n +=1

def foo():
  foo.__dict__.setdefault('count', 0)
  foo.count += 1
  return foo.count

What is the best way to calculate a checksum for a file that is on my machine?

I personally use Cygwin, which puts the entire smörgåsbord of Linux utilities at my fingertip --- there's md5sum and all the cryptographic digests supported by OpenSSL. Alternatively, you can also use a Windows distribution of OpenSSL (the "light" version is only a 1 MB installer).

What is the minimum length of a valid international phone number?

The minimum length is 4 for Saint Helena (Format: +290 XXXX) and Niue (Format: +683 XXXX).

How to use bluetooth to connect two iPhone?

If I remember correctly, Bluetooth defines certain roles that devices can take. Most cell phones only support a certain number of roles. For instance, I can have a Bluetooth stereo headset that connects to my phone to receive audio, but just because my cell phone has Bluetooth does mean that it supports BEING a speaker for a different device - it doesn't advertise its capabilities of having a speaker for use by other Bluetooth devices.

I assume you want to transfer files between two iPhones? Transferring files via Bluetooth does seem like functionality that I would put in the iPhone, but I'm not Apple so I don't know for sure. In fact, yes, it seems that file transfer is not supported except in jailbroken phones:

http://gizmodo.com/5138797/iphone-bluetooth-file-transfer-coming-soon-yes

You'll probably get similar answers for Bluetooth Dial-Up Networking. I'd imagine they kept the Bluetooth commands out of the SDK for various reasons and you'll have to jailbreak your phone to get the functionality back.

SQL Server SELECT into existing table

There are two different ways to implement inserting data from one table to another table.

For Existing Table - INSERT INTO SELECT

This method is used when the table is already created in the database earlier and the data is to be inserted into this table from another table. If columns listed in insert clause and select clause are same, they are not required to list them. It is good practice to always list them for readability and scalability purpose.

----Create testable
CREATE TABLE TestTable (FirstName VARCHAR(100), LastName VARCHAR(100))
----INSERT INTO TestTable using SELECT
INSERT INTO TestTable (FirstName, LastName)
SELECT FirstName, LastName
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
----Clean Up Database
DROP TABLE TestTable

For Non-Existing Table - SELECT INTO

This method is used when the table is not created earlier and needs to be created when data from one table is to be inserted into the newly created table from another table. The new table is created with the same data types as selected columns.

----Create a new table and insert into table using SELECT INSERT
SELECT FirstName, LastName
INTO TestTable
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
----Clean Up Database
DROP TABLE TestTable

Ref 1 2

Rendering JSON in controller

For the instance of

render :json => @projects, :include => :tasks

You are stating that you want to render @projects as JSON, and include the association tasks on the Project model in the exported data.

For the instance of

render :json => @projects, :callback => 'updateRecordDisplay'

You are stating that you want to render @projects as JSON, and wrap that data in a javascript call that will render somewhat like:

updateRecordDisplay({'projects' => []})

This allows the data to be sent to the parent window and bypass cross-site forgery issues.

rewrite a folder name using .htaccess

mod_rewrite can only rewrite/redirect requested URIs. So you would need to request /apple/… to get it rewritten to a corresponding /folder1/….

Try this:

RewriteEngine on
RewriteRule ^apple/(.*) folder1/$1

This rule will rewrite every request that starts with the URI path /apple/… internally to /folder1/….


Edit    As you are actually looking for the other way round:

RewriteCond %{THE_REQUEST} ^GET\ /folder1/
RewriteRule ^folder1/(.*) /apple/$1 [L,R=301]

This rule is designed to work together with the other rule above. Requests of /folder1/… will be redirected externally to /apple/… and requests of /apple/… will then be rewritten internally back to /folder1/….

Align DIV's to bottom or baseline

The answer posted by Y. Shoham (using absolute positioning) seems to be the simplest solution in most cases where the container is a fixed height, but if the parent DIV has to contain multiple DIVs and auto adjust it's height based on dynamic content, then there can be a problem. I needed to have two blocks of dynamic content; one aligned to the top of the container and one to the bottom and although I could get the container to adjust to the size of the top DIV, if the DIV aligned to the bottom was taller, it would not resize the container but would extend outside. The method outlined above by romiem using table style positioning, although a bit more complicated, is more robust in this respect and allowed alignment to the bottom and correct auto height of the container.

CSS

#container {
        display: table;
        height: auto;
}

#top {
    display: table-cell;
    width:50%;
    height: 100%;
}

#bottom {
    display: table-cell;
    width:50%;
    vertical-align: bottom;
    height: 100%;
}

HTML

<div id=“container”>
    <div id=“top”>Dynamic content aligned to top of #container</div>
    <div id=“bottom”>Dynamic content aligned to botttom of #container</div>
</div>

Example

I realise this is not a new answer but I wanted to comment on this approach as it lead me to find my solution but as a newbie I was not allowed to comment, only post.

How can I compile and run c# program without using visual studio?

There are different ways for this:

1.Building C# Applications Using csc.exe

While it is true that you might never decide to build a large-scale application using nothing but the C# command-line compiler, it is important to understand the basics of how to compile your code files by hand.

2.Building .NET Applications Using Notepad++

Another simple text editor I’d like to quickly point out is the freely downloadable Notepad++ application. This tool can be obtained from http://notepad-plus.sourceforge.net. Unlike the primitive Windows Notepad application, Notepad++ allows you to author code in a variety of languages and supports

3.Building .NET Applications Using SharpDevelop

As you might agree, authoring C# code with Notepad++ is a step in the right direction, compared to Notepad. However, these tools do not provide rich IntelliSense capabilities for C# code, designers for building graphical user interfaces, project templates, or database manipulation utilities. To address such needs, allow me to introduce the next .NET development option: SharpDevelop (also known as "#Develop").You can download it from http://www.sharpdevelop.com.

How to determine if a list of polygon points are in clockwise order?

A much computationally simpler method, if you already know a point inside the polygon:

  1. Choose any line segment from the original polygon, points and their coordinates in that order.

  2. Add a known "inside" point, and form a triangle.

  3. Calculate CW or CCW as suggested here with those three points.

C++11 rvalues and move semantics confusion (return statement)

First example

std::vector<int> return_vector(void)
{
    std::vector<int> tmp {1,2,3,4,5};
    return tmp;
}

std::vector<int> &&rval_ref = return_vector();

The first example returns a temporary which is caught by rval_ref. That temporary will have its life extended beyond the rval_ref definition and you can use it as if you had caught it by value. This is very similar to the following:

const std::vector<int>& rval_ref = return_vector();

except that in my rewrite you obviously can't use rval_ref in a non-const manner.

Second example

std::vector<int>&& return_vector(void)
{
    std::vector<int> tmp {1,2,3,4,5};
    return std::move(tmp);
}

std::vector<int> &&rval_ref = return_vector();

In the second example you have created a run time error. rval_ref now holds a reference to the destructed tmp inside the function. With any luck, this code would immediately crash.

Third example

std::vector<int> return_vector(void)
{
    std::vector<int> tmp {1,2,3,4,5};
    return std::move(tmp);
}

std::vector<int> &&rval_ref = return_vector();

Your third example is roughly equivalent to your first. The std::move on tmp is unnecessary and can actually be a performance pessimization as it will inhibit return value optimization.

The best way to code what you're doing is:

Best practice

std::vector<int> return_vector(void)
{
    std::vector<int> tmp {1,2,3,4,5};
    return tmp;
}

std::vector<int> rval_ref = return_vector();

I.e. just as you would in C++03. tmp is implicitly treated as an rvalue in the return statement. It will either be returned via return-value-optimization (no copy, no move), or if the compiler decides it can not perform RVO, then it will use vector's move constructor to do the return. Only if RVO is not performed, and if the returned type did not have a move constructor would the copy constructor be used for the return.

How to add a char/int to an char array in C?

Suggest replacing this:

char str[1024];
char tmp = '.';

strcat(str, tmp);

with this:

char str[1024] = {'\0'}; // set array to initial all NUL bytes
char tmp[] = "."; // create a string for the call to strcat()

strcat(str, tmp); // 

How to enable PHP short tags?

This can be done by enabling short_open_tag in php.ini:

1.To locate php.ini file,on comment line execute

 php --ini

you will get some thing like this,

Configuration File (php.ini) Path: /etc
Loaded Configuration File:         /etc/php.ini
Scan for additional .ini files in: /etc/php.d
Additional .ini files parsed:      /etc/php.d/curl.ini,
/etc/php.d/fileinfo.ini,
/etc/php.d/gd.ini,
/etc/php.d/json.ini,
/etc/php.d/mcrypt.ini,
/etc/php.d/mysql.ini,
/etc/php.d/mysqli.ini,
/etc/php.d/pdo.ini,
/etc/php.d/pdo_mysql.ini,
/etc/php.d/pdo_sqlite.ini,
/etc/php.d/phar.ini,
/etc/php.d/sqlite3.ini,
/etc/php.d/zip.ini

See 2nd line from the comment output.The file will be in the mentioned path.

2.Open php.ini file and find short_open_tag. By default it is in off change it to on.

3.Restart the server,execute this comment

service httpd restart

Thanks

Python & Matplotlib: Make 3D plot interactive in Jupyter Notebook

You may go with Plotly library. It can render interactive 3D plots directly in Jupyter Notebooks.

To do so you first need to install Plotly by running:

pip install plotly

You might also want to upgrade the library by running:

pip install plotly --upgrade

After that in you Jupyter Notebook you may write something like:

# Import dependencies
import plotly
import plotly.graph_objs as go

# Configure Plotly to be rendered inline in the notebook.
plotly.offline.init_notebook_mode()

# Configure the trace.
trace = go.Scatter3d(
    x=[1, 2, 3],  # <-- Put your data instead
    y=[4, 5, 6],  # <-- Put your data instead
    z=[7, 8, 9],  # <-- Put your data instead
    mode='markers',
    marker={
        'size': 10,
        'opacity': 0.8,
    }
)

# Configure the layout.
layout = go.Layout(
    margin={'l': 0, 'r': 0, 'b': 0, 't': 0}
)

data = [trace]

plot_figure = go.Figure(data=data, layout=layout)

# Render the plot.
plotly.offline.iplot(plot_figure)

As a result the following chart will be plotted for you in Jupyter Notebook and you'll be able to interact with it. Of course you will need to provide your specific data instead of suggeseted one.

enter image description here

How to get a DOM Element from a JQuery Selector

If you need to interact directly with the DOM element, why not just use document.getElementById since, if you are trying to interact with a specific element you will probably know the id, as assuming that the classname is on only one element or some other option tends to be risky.

But, I tend to agree with the others, that in most cases you should learn to do what you need using what jQuery gives you, as it is very flexible.

UPDATE: Based on a comment: Here is a post with a nice explanation: http://www.mail-archive.com/[email protected]/msg04461.html

$(this).attr("checked") ? $(this).val() : 0

This will return the value if it's checked, or 0 if it's not.

$(this).val() is just reaching into the dom and getting the attribute "value" of the element, whether or not it's checked.

Select folder dialog WPF

Microsoft.Win32.OpenFileDialog is the standard dialog that any application on Windows uses. Your user won't be surprised by its appearance when you use WPF in .NET 4.0

The dialog was altered in Vista. WPF in .NET 3.0 and 3.5 still used the legacy dialog but that was fixed in .NET 4.0. I can only guess that you started this thread because you are seeing that old dialog. Which probably means you're actually running a program that is targeting 3.5. Yes, the Winforms wrapper did get the upgrade and shows the Vista version. System.Windows.Forms.OpenFileDialog class, you'll need to add a reference to System.Windows.Forms.

Responsive Bootstrap Jumbotron Background Image

This is how I do :

_x000D_
_x000D_
<div class="jumbotron" style="background: url(img/bg.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover;">_x000D_
  <h1>Hello</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why do I need to do `--set-upstream` all the time?

All i wanted was doing something like this:

git checkout -b my-branch
git commit -a -m "my commit"
git push

Since i didn't found a better solution, i've just created an bash alias on ~/.bashrc:

alias push="git push -u origin HEAD"

now just doing a push command does the job (you can add this alias on ~/.gitconfig too with another name, such as pushup)

How to exclude particular class name in CSS selector?

One way is to use the multiple class selector (no space as that is the descendant selector):

_x000D_
_x000D_
.reMode_hover:not(.reMode_selected):hover _x000D_
{_x000D_
   background-color: #f0ac00;_x000D_
}
_x000D_
<a href="" title="Design" class="reMode_design  reMode_hover">_x000D_
    <span>Design</span>_x000D_
</a>_x000D_
_x000D_
<a href="" title="Design" _x000D_
 class="reMode_design  reMode_hover reMode_selected">_x000D_
    <span>Design</span>_x000D_
</a>
_x000D_
_x000D_
_x000D_

efficient way to implement paging

LinqToSql will automatically convert a .Skip(N1).Take(N2) into the TSQL syntax for you. In fact, every "query" you do in Linq, is actually just creating a SQL query for you in the background. To test this, just run SQL Profiler while your application is running.

The skip/take methodology has worked very well for me, and others from what I read.

Out of curiosity, what type of self-paging query do you have, that you believe is more efficient than Linq's skip/take?

Using braces with dynamic variable names in PHP

I was in a position where I had 6 identical arrays and I needed to pick the right one depending on another variable and then assign values to it. In the case shown here $comp_cat was 'a' so I needed to pick my 'a' array ( I also of course had 'b' to 'f' arrays)

Note that the values for the position of the variable in the array go after the closing brace.

${'comp_cat_'.$comp_cat.'_arr'}[1][0] = "FRED BLOGGS";

${'comp_cat_'.$comp_cat.'_arr'}[1][1] = $file_tidy;

echo 'First array value is '.$comp_cat_a_arr[1][0].' and the second value is .$comp_cat_a_arr[1][1];

Determine function name from within that function (without using traceback)

Here's a future-proof approach.

Combining @CamHart's and @Yuval's suggestions with @RoshOxymoron's accepted answer has the benefit of avoiding:

  • _hidden and potentially deprecated methods
  • indexing into the stack (which could be reordered in future pythons)

So I think this plays nice with future python versions (tested on 2.7.3 and 3.3.2):

from __future__ import print_function
import inspect

def bar():
    print("my name is '{}'".format(inspect.currentframe().f_code.co_name))

Transition color fade on hover?

For having a trasition effect like a highlighter just to highlight the text and fade off the bg color, we used the following:

_x000D_
_x000D_
.field-error {_x000D_
    color: #f44336;_x000D_
    padding: 2px 5px;_x000D_
    position: absolute;_x000D_
    font-size: small;_x000D_
    background-color: white;_x000D_
}_x000D_
_x000D_
.highlighter {_x000D_
    animation: fadeoutBg 3s; /***Transition delay 3s fadeout is class***/_x000D_
    -moz-animation: fadeoutBg 3s; /* Firefox */_x000D_
    -webkit-animation: fadeoutBg 3s; /* Safari and Chrome */_x000D_
    -o-animation: fadeoutBg 3s; /* Opera */_x000D_
}_x000D_
_x000D_
@keyframes fadeoutBg {_x000D_
    from { background-color: lightgreen; } /** from color **/_x000D_
    to { background-color: white; } /** to color **/_x000D_
}_x000D_
_x000D_
@-moz-keyframes fadeoutBg { /* Firefox */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes fadeoutBg { /* Safari and Chrome */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-o-keyframes fadeoutBg { /* Opera */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}
_x000D_
<div class="field-error highlighter">File name already exists.</div>
_x000D_
_x000D_
_x000D_

Best way to test if a row exists in a MySQL table

I'd go with COUNT(1). It is faster than COUNT(*) because COUNT(*) tests to see if at least one column in that row is != NULL. You don't need that, especially because you already have a condition in place (the WHERE clause). COUNT(1) instead tests the validity of 1, which is always valid and takes a lot less time to test.

R plot: size and resolution

If you'd like to use base graphics, you may have a look at this. An extract:

You can correct this with the res= argument to png, which specifies the number of pixels per inch. The smaller this number, the larger the plot area in inches, and the smaller the text relative to the graph itself.

Does this app use the Advertising Identifier (IDFA)? - AdMob 6.8.0

In app store connect now if we are using ads in our app then we will answer as yes to Does this app use the Advertising Identifier (IDFA)?

further 3 questions will be asked as

enter image description here

if your using just admob then check the first one and leave other two unchecked. Other two options (2nd , 3rd ) will be checked if your using app flyer to show ads. all options are explained with detail here

What does "xmlns" in XML mean?

It defines an XML Namespace.

In your example, the Namespace Prefix is "android" and the Namespace URI is "http://schemas.android.com/apk/res/android"

In the document, you see elements like: <android:foo />

Think of the namespace prefix as a variable with a short name alias for the full namespace URI. It is the equivalent of writing <http://schemas.android.com/apk/res/android:foo /> with regards to what it "means" when an XML parser reads the document.

NOTE: You cannot actually use the full namespace URI in place of the namespace prefix in an XML instance document.

Check out this tutorial on namespaces: http://www.sitepoint.com/xml-namespaces-explained/

Initializing a static std::map<int, int> in C++

Just wanted to share a pure C++ 98 work around:

#include <map>

std::map<std::string, std::string> aka;

struct akaInit
{
    akaInit()
    {
        aka[ "George" ] = "John";
        aka[ "Joe" ] = "Al";
        aka[ "Phil" ] = "Sue";
        aka[ "Smitty" ] = "Yando";
    }
} AkaInit;

jQuery get the id/value of <li> element after click function

If you change your html code a bit - remove the ids

<ul id='myid'>  
<li>First</li>
<li>Second</li>
<li>Third</li>
<li>Fourth</li>
<li>Fifth</li>
</ul>

Then the jquery code you want is...

$("#myid li").click(function() {
    alert($(this).prevAll().length+1);
});?

You don't need to place any ids, just keep on adding li items.

Take a look at demo

Useful links

MySQL Trigger: Delete From Table AFTER DELETE

create trigger doct_trigger
after delete on doctor
for each row
delete from patient where patient.PrimaryDoctor_SSN=doctor.SSN ;

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I recommend to use SMO (Enable TCP/IP Network Protocol for SQL Server). However, it was not available in my case.

I rewrote the WMI commands from Krzysztof Kozielczyk to PowerShell.

# Enable TCP/IP

Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocol -Filter "InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'" |
Invoke-CimMethod -Name SetEnable

# Open the right ports in the firewall
New-NetFirewallRule -DisplayName 'MSSQL$SQLEXPRESS' -Direction Inbound -Action Allow -Protocol TCP -LocalPort 1433

# Modify TCP/IP properties to enable an IP address

$properties = Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocolProperty -Filter "InstanceName='SQLEXPRESS' and ProtocolName = 'Tcp' and IPAddressName='IPAll'"
$properties | ? { $_.PropertyName -eq 'TcpPort' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '1433' }
$properties | ? { $_.PropertyName -eq 'TcpPortDynamic' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '' }

# Restart SQL Server

Restart-Service 'MSSQL$SQLEXPRESS'

pypi UserWarning: Unknown distribution option: 'install_requires'

In conclusion:

distutils doesn't support install_requires or entry_points, setuptools does.

change from distutils.core import setup in setup.py to from setuptools import setup or refactor your setup.py to use only distutils features.

I came here because I hadn't realized entry_points was only a setuptools feature.

If you are here wanting to convert setuptools to distutils like me:

  1. remove install_requires from setup.py and just use requirements.txt with pip
  2. change entry_points to scripts (doc) and refactor any modules relying on entry_points to be full scripts with shebangs and an entry point.

Confused about stdin, stdout and stderr?

As a complement of the answers above, here is a sum up about Redirections: Redirections cheatsheet

EDIT: This graphic is not entirely correct.

The first example does not use stdin at all, it's passing "hello" as an argument to the echo command.

The graphic also says 2>&1 has the same effect as &> however

ls Documents ABC > dirlist 2>&1
#does not give the same output as 
ls Documents ABC > dirlist &>

This is because &> requires a file to redirect to, and 2>&1 is simply sending stderr into stdout

error: ORA-65096: invalid common user or role name in oracle

99.9% of the time the error ORA-65096: invalid common user or role name means you are logged into the CDB when you should be logged into a PDB.

But if you insist on creating users the wrong way, follow the steps below.

DANGER

Setting undocumented parameters like this (as indicated by the leading underscore) should only be done under the direction of Oracle Support. Changing such parameters without such guidance may invalidate your support contract. So do this at your own risk.

Specifically, if you set "_ORACLE_SCRIPT"=true, some data dictionary changes will be made with the column ORACLE_MAINTAINED set to 'Y'. Those users and objects will be incorrectly excluded from some DBA scripts. And they may be incorrectly included in some system scripts.

If you are OK with the above risks, and don't want to create common users the correct way, use the below answer.


Before creating the user run:

alter session set "_ORACLE_SCRIPT"=true;  

I found the answer here

What is an "index out of range" exception, and how do I fix it?

Why does this error occur?

Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.

The first element in a collection is generally located at index 0. The last element is at index n-1, where n is the Size of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1, you're going to get an error.

How indexing arrays works

When you declare an array like this:

var array = new int[6]

The first and last elements in the array are

var firstElement = array[0];
var lastElement = array[5];

So when you write:

var element = array[5];

you are retrieving the sixth element in the array, not the fifth one.

Typically, you would loop over an array like this:

for (int index = 0; index < array.Length; index++)
{
    Console.WriteLine(array[index]);
}

This works, because the loop starts at zero, and ends at Length-1 because index is no longer less than Length.

This, however, will throw an exception:

for (int index = 0; index <= array.Length; index++)
{
    Console.WriteLine(array[index]);
}

Notice the <= there? index will now be out of range in the last loop iteration, because the loop thinks that Length is a valid index, but it is not.

How other collections work

Lists work the same way, except that you generally use Count instead of Length. They still start at zero, and end at Count - 1.

for (int index = 0; i < list.Count; index++)
{
    Console.WriteLine(list[index]);
} 

However, you can also iterate through a list using foreach, avoiding the whole problem of indexing entirely:

foreach (var element in list)
{
    Console.WriteLine(element.ToString());
}

You cannot index an element that hasn't been added to a collection yet.

var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]);  // Throws exception.

Simple line plots using seaborn

Yes, you can do the same in Seaborn directly. This is done with tsplot() which allows either a single array as input, or two arrays where the other is 'time' i.e. x-axis.

import seaborn as sns

data =  [1,5,3,2,6] * 20
time = range(100)

sns.tsplot(data, time)

enter image description here

Replace comma with newline in sed on MacOS?

Apparently \r is the key!

$ sed 's/, /\r/g' file3.txt > file4.txt

Transformed this:

ABFS, AIRM, AMED, BOSC, CALI, ECPG, FRGI, GERN, GTIV, HSON, IQNT, JRCC, LTRE,
MACK, MIDD, NKTR, NPSP, PME, PTIX, REFR, RSOL, UBNT, UPI, YONG, ZEUS

To this:

ABFS
AIRM
AMED
BOSC
CALI
ECPG
FRGI
GERN
GTIV
HSON
IQNT
JRCC
LTRE
MACK
MIDD
NKTR
NPSP
PME
PTIX
REFR
RSOL
UBNT
UPI
YONG
ZEUS

HTML 'td' width and height

Following width worked well in HTML5: -

<table >
  <tr>
    <th style="min-width:120px">Month</th>
    <th style="min-width:60px">Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
</table>

Please note that

  • TD tag is without CSS style.

SQL query to select distinct row with minimum value

Try:

select id, game, min(point) from t
group by id 

What is an HttpHandler in ASP.NET

In the simplest terms, an ASP.NET HttpHandler is a class that implements the System.Web.IHttpHandler interface.

ASP.NET HTTPHandlers are responsible for intercepting requests made to your ASP.NET web application server. They run as processes in response to a request made to the ASP.NET Site. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler.

ASP.NET offers a few default HTTP handlers:

  • Page Handler (.aspx): handles Web pages
  • User Control Handler (.ascx): handles Web user control pages
  • Web Service Handler (.asmx): handles Web service pages
  • Trace Handler (trace.axd): handles trace functionality

You can create your own custom HTTP handlers that render custom output to the browser. Typical scenarios for HTTP Handlers in ASP.NET are for example

  • delivery of dynamically created images (charts for example) or resized pictures.
  • RSS feeds which emit RSS-formated XML

You implement the IHttpHandler interface to create a synchronous handler and the IHttpAsyncHandler interface to create an asynchronous handler. The interfaces require you to implement the ProcessRequest method and the IsReusable property.

The ProcessRequest method handles the actual processing for requests made, while the Boolean IsReusable property specifies whether your handler can be pooled for reuse (to increase performance) or whether a new handler is required for each request.

jQuery Mobile how to check if button is disabled?

I had the same problem and I found this is working:

if ($("#deliveryNext").attr('disabled')) {
  // do sth if disabled
} else {
  // do sth if enabled 
}

If this gives you undefined then you can use if condition also.

When you evaluate undefined it will return false.

Get the cell value of a GridView row

Try changing your code to

// Get the currently selected row using the SelectedRow property.
GridViewRow row = dgCustomer.SelectedRow;

// And you respective cell's value
TextBox1.Text = row.Cells[1].Text

UPDATE: (based on my comment) If all what you are trying to get is the primary key value for the selected row then an alternate approach is to set

datakeynames="yourprimarykey"

for the gridview definition which can be accessed from the code behind like below.

TextBox1.Text = CustomersGridView.SelectedValue.ToString();

How to check if a char is equal to an empty space?

At first glance, your code will not compile. Since the nested if statement doesn't have any braces, it will consider the next line the code that it should execute. Also, you are comparing a char against a String, " ". Try comparing the values as chars instead. I think the correct syntax would be:

if(c == ' '){
   //do something here
}

But then again, I am not familiar with the "Equal" class

Error 'tunneling socket' while executing npm install

Removing the proxy settings resolved the issue:

If you are no using any proxy:

npm config rm proxy
npm config rm https-proxy

If you are using Proxy:

npm config set proxy http://proxyhostname:proxyport
npm config set https-proxy https://proxyhostname:proxyport

Hopefully this will solve your problem :)

How to delete and recreate from scratch an existing EF Code First database

Since this question is gonna be clicked some day by new EF Core users and I find the top answers somewhat unnecessarily destructive, I will show you a way to start "fresh". Beware, this deletes all of your data.

  1. Delete all tables on your MS SQL server. Also delete the __EFMigrations table.
  2. Type dotnet ef database update
  3. EF Core will now recreate the database from zero up until your latest migration.

Refresh Page and Keep Scroll Position

this will do the magic

    <script>
        document.addEventListener("DOMContentLoaded", function(event) { 
            var scrollpos = localStorage.getItem('scrollpos');
            if (scrollpos) window.scrollTo(0, scrollpos);
        });

        window.onbeforeunload = function(e) {
            localStorage.setItem('scrollpos', window.scrollY);
        };
    </script>

Tried to Load Angular More Than Once

Another case is with Webpack which concating angular into the bundle.js, beside the angular that is loaded from index.html <script> tag.

this was because we used explicit importing of angular in many files:

define(['angular', ...], function(angular, ...){

so, webpack decided to bundle it too. cleaning all of those into:

define([...], function(...){

was fixing Tried to Load Angular More Than Once for once and all.

How to sign an android apk file

Don't worry...! Follow these below steps and you will get your signed .apk file. I was also worry about that, but these step get ride me off from the frustration. Steps to sign your application:

  1. Export the unsigned package:

Right click on the project in Eclipse -> Android Tools -> Export Unsigned Application Package (like here we export our GoogleDriveApp.apk to Desktop)

Sign the application using your keystore and the jarsigner tool (follow below steps):

Open cmd-->change directory where your "jarsigner.exe" exist (like here in my system it exist at "C:\Program Files\Java\jdk1.6.0_17\bin"

Now enter belwo command in cmd:

jarsigner -verbose -keystore c:\users\android\debug.keystore c:\users\pir fahim\Desktops\GoogleDriveApp.apk my_keystore_alias

It will ask you to provide your password: Enter Passphrase for keystore: It will sign your apk.To verify that the signing is successful you can run:

jarsigner -verify c:\users\pir fahim\Desktops\GoogleDriveApp.apk

It should come back with: jar verified.

Method 2

If you are using eclipse with ADT, then it is simple to compiled, signed, aligned, and ready the file for distribution.what you have to do just follow this steps.

  • File > Export.
  • Export android application
  • Browse-->select your project
  • Next-->Next

These steps will compiled, signed and zip aligned your project and now you are ready to distribute your project or upload at Google Play store.

What is the correct XPath for choosing attributes that contain "foo"?

descendant-or-self::*[contains(@prop,'Foo')]

Or:

/bla/a[contains(@prop,'Foo')]

Or:

/bla/a[position() <= 3]

Dissected:

descendant-or-self::

The Axis - search through every node underneath and the node itself. It is often better to say this than //. I have encountered some implementations where // means anywhere (decendant or self of the root node). The other use the default axis.

* or /bla/a

The Tag - a wildcard match, and /bla/a is an absolute path.

[contains(@prop,'Foo')] or [position() <= 3]

The condition within [ ]. @prop is shorthand for attribute::prop, as attribute is another search axis. Alternatively you can select the first 3 by using the position() function.

how to insert date and time in oracle?

Try this:

...(to_date('2011/04/22 08:30:00', 'yyyy/mm/dd hh24:mi:ss'));

Composer - the requested PHP extension mbstring is missing from your system

I set the PHPRC variable and uncommented zend_extension=php_opcache.dll in php.ini and all works well.

What's the difference between ASCII and Unicode?

ASCII has 128 code positions, allocated to graphic characters and control characters (control codes).

Unicode has 1,114,112 code positions. About 100,000 of them have currently been allocated to characters, and many code points have been made permanently noncharacters (i.e. not used to encode any character ever), and most code points are not yet assigned.

The only things that ASCII and Unicode have in common are: 1) They are character codes. 2) The 128 first code positions of Unicode have been defined to have the same meanings as in ASCII, except that the code positions of ASCII control characters are just defined as denoting control characters, with names corresponding to their ASCII names, but their meanings are not defined in Unicode.

Sometimes, however, Unicode is characterized (even in the Unicode standard!) as “wide ASCII”. This is a slogan that mainly tries to convey the idea that Unicode is meant to be a universal character code the same way as ASCII once was (though the character repertoire of ASCII was hopelessly insufficient for universal use), as opposite to using different codes in different systems and applications and for different languages.

Unicode as such defines only the “logical size” of characters: Each character has a code number in a specific range. These code numbers can be presented using different transfer encodings, and internally, in memory, Unicode characters are usually represented using one or two 16-bit quantities per character, depending on character range, sometimes using one 32-bit quantity per character.

Open new Terminal Tab from command line (Mac OS X)

With X installed (e.g. from homebrew, or Quartz), a simple "xterm &" does (nearly) the trick, it opens a new terminal window (not a tab, though).

Save string to the NSUserDefaults?

For saving use this :

[[NSUserDefaults standardUserDefaults]setObject:@"YES" forKey:@"KTerminated"];
[[NSUserDefaults standardUserDefaults]synchronize];

For Retriveing use this :

[[[NSUserDefaults standardUserDefaults]stringForKey:@"KTerminated"] isEqualToString:@"YES"];

List<T> or IList<T>

The most important case for using interfaces over implementations is in the parameters to your API. If your API takes a List parameter, then anyone who uses it has to use List. If the parameter type is IList, then the caller has much more freedom, and can use classes you never heard about, which may not even have existed when your code was written.

Youtube - downloading a playlist - youtube-dl

Your link is not a playlist.

A proper playlist URL looks like this:

https://www.youtube.com/playlist?list=PLHSdFJ8BDqEyvUUzm6R0HxawSWniP2c9K

Your URL is just the first video OF a certain playlist. It contains https://www.youtube.com/watch? instead of https://www.youtube.com/playlist?.

Pick the playlist by clicking on the title of the playlist on the right side in the list of videos and use this URL.

What is the correct way of reading from a TCP socket in C/C++?

This is an article that I always refer to when working with sockets..

THE WORLD OF SELECT()

It will show you how to reliably use 'select()' and contains some other useful links at the bottom for further info on sockets.

A server is already running. Check …/tmp/pids/server.pid. Exiting - rails

SOLVING

Address already in use — bind(2)” 500 error in Ruby on Rails

Recently I tried running a Rails app on a production server. Not only did it not work, but it broke my localhost:3000 development server as well. Localhost would only load a blank white page or a 500 error.

To solve this, I used two quick commands. If these don’t return a result, you may need to look elsewhere for a solution, but this is a good quick fix.

lsof -wni tcp:3000


ruby    52179 rachelchervin   50u  IPv6 0x...7aa3      0t0  TCP [::1]:hbci (LISTEN)
ruby    52179 rachelchervin   51u  IPv4 0x...c7bb      0t0  TCP 127.0.0.1:hbci (LISTEN)
ruby    52180 rachelchervin   50u  IPv6 0x...7aa3      0t0  TCP [::1]:hbci (LISTEN)
ruby    52180 rachelchervin   51u  IPv4 0x...c7bb      0t0  TCP 127.0.0.1:hbci (LISTEN)

This command shows all of my currently running processes and their PIDs (process IDs) on the 3000 port. Because there are existing running processes that did not close correctly, my new :3000 server can’t start, hence the 500 error.

kill 52179

kill 52180

rails s

I used the Linux kill command to manually stop the offending processes. If you have more than 4, simply use kill on any PIDs until the first command comes back blank. Then, try restarting your localhost:3000 server again. This will not damage your computer! It simply kills existing ruby processes on your localhost port. A new server will start these processes all over again. Good luck!

How to show Bootstrap table with sort icon

You could try using FontAwesome. It contains a sort-icon (http://fontawesome.io/icon/sort/).

To do so, you would

  1. need to include fontawesome:

    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
    
  2. and then simply use the fontawesome-icon instead of the default-bootstrap-icons in your th's:

    <th><b>#</b> <i class="fa fa-fw fa-sort"></i></th>
    

Hope that helps.

Twitter Bootstrap vs jQuery UI?

We have used both and we like Bootstrap for its simplicity and the pace at which it's being developed and enhanced. The problem with jQuery UI is that it's moving at a snail's pace. It's taking years to roll out common features like Menubar, Tree control and DataGrid which are in planning/development stage for ever. We waited waited waited and finally given up and used other libraries like ExtJS for our product http://dblite.com.

Bootstrap has come up with quite a comprehensive set of features in a very short period of time and I am sure it will outpace jQuery UI pretty soon.

So I see no point in using something that will eventually be outdated...

jQuery lose focus event

If the 'Cool Options' are hidden from the view before the field is focused then you would want to create this in JQuery instead of having it in the DOM so anyone using a screen reader wouldn't see unnecessary information. Why should they have to listen to it when we don't have to see it?

So you can setup variables like so:

var $coolOptions= $("<div id='options'></div>").text("Some cool options");

and then append (or prepend) on focus

$("input[name='input_name']").focus(function() {
    $(this).append($coolOptions);
});

and then remove when the focus ends

$("input[name='input_name']").focusout(function() {
    $('#options').remove();
});

Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website

Solved by doing the following in my windows 10:

mklink "C:\Users\hal\AppData\Local\Continuum\anaconda3\DLLs\libssl-1_1-x64.dll" "C:\Users\hal\AppData\Local\Continuum\anaconda3\Library\bin\libssl-1_1-x64.dll"

mklink "C:\ProgramData\Anaconda3\DLLs\libcrypto-1_1-x64.dll" "C:\ProgramData\Anaconda3\Library\bin\libcrypto-1_1-x64.dll"

Git error when trying to push -- pre-receive hook declined

You should look at the logs. I just ran into the same error and realized from the logs it was because I had a yarn.lock and package-lock.json

Is there a way to use use text as the background with CSS?

Ciro's solution about an SVG Data URI background containing the text is very clever.

However, it won't work in IE if you just add the plain SVG source to the data URI.

In order to get around this and make it work in IE9 and up, encode the SVG to base64. This is a great tool.

So this:

background:url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"><text x="5%" y="5%" font-size="30" fill="red">I love SVG!</text></svg>');

Becomes this:

background:url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjx0ZXh0IHg9IjUlIiB5PSI1JSIgZm9udC1zaXplPSIzMCIgZmlsbD0icmVkIj5JIGxvdmUgU1ZHITwvdGV4dD48L3N2Zz4=');

Tested and it works in IE9-10-11, WebKit (Chrome 37, Opera 23) and Gecko (Firefox 31).

http://jsfiddle.net/qapp5dLn/

generate a random number between 1 and 10 in c

Here is a ready to run source code for random number generator using c taken from this site: http://www.random-number.com/random-number-c/ . The implementation here is more general (a function that gets 3 parameters: min,max and number of random numbers to generate)

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

// the random function
void RandomNumberGenerator(const int nMin, const int nMax, const int  nNumOfNumsToGenerate)
{
  int nRandonNumber = 0;
  for (int i = 0; i < nNumOfNumsToGenerate; i++)
  {
    nRandonNumber = rand()%(nMax-nMin) + nMin;
    printf("%d ", nRandonNumber);
  }
  printf("\n");
}

void main()
{
  srand(time(NULL));
  RandomNumberGenerator(1,70,5);
}

Remove #N/A in vlookup result

If you only want to return a blank when B2 is blank you can use an additional IF function for that scenario specifically, i.e.

=IF(B2="","",VLOOKUP(B2,Index!A1:B12,2,FALSE))

or to return a blank with any error from the VLOOKUP (e.g. including if B2 is populated but that value isn't found by the VLOOKUP) you can use IFERROR function if you have Excel 2007 or later, i.e.

=IFERROR(VLOOKUP(B2,Index!A1:B12,2,FALSE),"")

in earlier versions you need to repeat the VLOOKUP, e.g.

=IF(ISNA(VLOOKUP(B2,Index!A1:B12,2,FALSE)),"",VLOOKUP(B2,Index!A1:B12,2,FALSE))