Programs & Examples On #Redgreen

How to change heatmap.2 color range in R?

Here's another option for those not using heatmap.2 (aheatmap is good!)

Make a sequential vector of 100 values from min to max of your input matrix, find value closest to 0 in that, make two vector of colours to and from desired midpoint, combine and use them:

breaks <- seq(from=min(range(inputMatrix)), to=max(range(inputMatrix)), length.out=100)
midpoint <- which.min(abs(breaks - 0))
rampCol1 <- colorRampPalette(c("forestgreen", "darkgreen", "black"))(midpoint)
rampCol2 <- colorRampPalette(c("black", "darkred", "red"))(100-(midpoint+1))
rampCols <- c(rampCol1,rampCol2)

How to check if memcache or memcached is installed for PHP?

It may be relevant to see if it's running in PHP via command line as well-

<path-to-php-binary>php -i | grep memcache

How can I send large messages with Kafka (over 15MB)?

Minor changes required for Kafka 0.10 and the new consumer compared to laughing_man's answer:

  • Broker: No changes, you still need to increase properties message.max.bytes and replica.fetch.max.bytes. message.max.bytes has to be equal or smaller(*) than replica.fetch.max.bytes.
  • Producer: Increase max.request.size to send the larger message.
  • Consumer: Increase max.partition.fetch.bytes to receive larger messages.

(*) Read the comments to learn more about message.max.bytes<=replica.fetch.max.bytes

Add a new line to a text file in MS-DOS

Maybe this is what you want?

echo foo > test.txt
echo. >> test.txt
echo bar >> test.txt

results in the following within test.txt:

foo

bar

How to generate a range of numbers between two numbers?

Oracle 12c; Quick but limited:

select rownum+1000 from all_objects fetch first 50 rows only;

Note: limited to row count of all_objects view;

What are the valid Style Format Strings for a Reporting Services [SSRS] Expression?

You can check the schema at http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition/ReportDefinition.xsd

Search for xsd:complexType name="StyleType"

This will list out all the possible Styles you can use.

Specific to your question however, you can use the Format style.

Format

Specify the data format to use for values that appear in the textbox.

Valid values include Default, Number, Date, Time, Percentage, and Currency.

Link to MSDN: http://msdn.microsoft.com/en-us/library/ms251684(VS.80).aspx

Get Insert Statement for existing row in MySQL

In PHPMyAdmin you can:

  1. click copy on the row you want to know its insert statements SQL:

Select copy

  1. click Preview SQL:

Select Preview

  1. you will get the created insert statement that generates it

You can apply that on many rows at once if you select them and click copy from the bottom of the table and then Preview SQl

Insert json file into mongodb

In MS Windows, the mongoimport command has to be run in a normal Windows command prompt, not from the mongodb command prompt.

Multiple inheritance for an anonymous class

An anonymous class usually implements an interface:

new Runnable() { // implements Runnable!
   public void run() {}
}

JFrame.addWindowListener( new WindowAdapter() { // extends  class
} );

If you mean whether you can implement 2 or more interfaces, than I think that's not possible. You can then make a private interface which combines the two. Though I cannot easily imagine why you would want an anonymous class to have that:

 public class MyClass {
   private interface MyInterface extends Runnable, WindowListener { 
   }

   Runnable r = new MyInterface() {
    // your anonymous class which implements 2 interaces
   }

 }

Free Barcode API for .NET

Could the Barcode Rendering Framework at Codeplex GitHub be of help?

What is the correct value for the disabled attribute?

From MDN by setAttribute():

To set the value of a Boolean attribute, such as disabled, you can specify any value. An empty string or the name of the attribute are recommended values. All that matters is that if the attribute is present at all, regardless of its actual value, its value is considered to be true. The absence of the attribute means its value is false. By setting the value of the disabled attribute to the empty string (""), we are setting disabled to true, which results in the button being disabled.

Link to MDN

Solution

  • I mean that in XHTML Strict is right disabled="disabled",
  • and in HTML5 is only disabled, like <input name="myinput" disabled>
  • In javascript, I set the value to true via e.disabled = true;
    or to "" via setAttribute( "disabled", "" );

Test in Chrome

var f = document.querySelectorAll( "label.disabled input" );
for( var i = 0; i < f.length; i++ )
{
    // Reference
    var e = f[ i ];

    // Actions
    e.setAttribute( "disabled", false|null|undefined|""|0|"disabled" );
    /*
        <input disabled="false"|"null"|"undefined"|empty|"0"|"disabled">
        e.getAttribute( "disabled" ) === "false"|"null"|"undefined"|""|"0"|"disabled"
        e.disabled === true
    */
    
    e.removeAttribute( "disabled" );
    /*
        <input>
        e.getAttribute( "disabled" ) === null
        e.disabled === false
    */

    e.disabled = false|null|undefined|""|0;
    /*
        <input>
        e.getAttribute( "disabled" ) === null|null|null|null|null
        e.disabled === false
    */

    e.disabled = true|" "|"disabled"|1;
    /*
        <input disabled>
        e.getAttribute( "disabled" ) === ""|""|""|""
        e.disabled === true
    */
}

How to set variables in HIVE scripts

Have you tried using the dollar sign and brackets like this:

SELECT * 
FROM foo 
WHERE day >= '${CURRENT_DATE}';

Java 8 Iterable.forEach() vs foreach loop

The better practice is to use for-each. Besides violating the Keep It Simple, Stupid principle, the new-fangled forEach() has at least the following deficiencies:

  • Can't use non-final variables. So, code like the following can't be turned into a forEach lambda:
Object prev = null;
for(Object curr : list)
{
    if( prev != null )
        foo(prev, curr);
    prev = curr;
}
  • Can't handle checked exceptions. Lambdas aren't actually forbidden from throwing checked exceptions, but common functional interfaces like Consumer don't declare any. Therefore, any code that throws checked exceptions must wrap them in try-catch or Throwables.propagate(). But even if you do that, it's not always clear what happens to the thrown exception. It could get swallowed somewhere in the guts of forEach()

  • Limited flow-control. A return in a lambda equals a continue in a for-each, but there is no equivalent to a break. It's also difficult to do things like return values, short circuit, or set flags (which would have alleviated things a bit, if it wasn't a violation of the no non-final variables rule). "This is not just an optimization, but critical when you consider that some sequences (like reading the lines in a file) may have side-effects, or you may have an infinite sequence."

  • Might execute in parallel, which is a horrible, horrible thing for all but the 0.1% of your code that needs to be optimized. Any parallel code has to be thought through (even if it doesn't use locks, volatiles, and other particularly nasty aspects of traditional multi-threaded execution). Any bug will be tough to find.

  • Might hurt performance, because the JIT can't optimize forEach()+lambda to the same extent as plain loops, especially now that lambdas are new. By "optimization" I do not mean the overhead of calling lambdas (which is small), but to the sophisticated analysis and transformation that the modern JIT compiler performs on running code.

  • If you do need parallelism, it is probably much faster and not much more difficult to use an ExecutorService. Streams are both automagical (read: don't know much about your problem) and use a specialized (read: inefficient for the general case) parallelization strategy (fork-join recursive decomposition).

  • Makes debugging more confusing, because of the nested call hierarchy and, god forbid, parallel execution. The debugger may have issues displaying variables from the surrounding code, and things like step-through may not work as expected.

  • Streams in general are more difficult to code, read, and debug. Actually, this is true of complex "fluent" APIs in general. The combination of complex single statements, heavy use of generics, and lack of intermediate variables conspire to produce confusing error messages and frustrate debugging. Instead of "this method doesn't have an overload for type X" you get an error message closer to "somewhere you messed up the types, but we don't know where or how." Similarly, you can't step through and examine things in a debugger as easily as when the code is broken into multiple statements, and intermediate values are saved to variables. Finally, reading the code and understanding the types and behavior at each stage of execution may be non-trivial.

  • Sticks out like a sore thumb. The Java language already has the for-each statement. Why replace it with a function call? Why encourage hiding side-effects somewhere in expressions? Why encourage unwieldy one-liners? Mixing regular for-each and new forEach willy-nilly is bad style. Code should speak in idioms (patterns that are quick to comprehend due to their repetition), and the fewer idioms are used the clearer the code is and less time is spent deciding which idiom to use (a big time-drain for perfectionists like myself!).

As you can see, I'm not a big fan of the forEach() except in cases when it makes sense.

Particularly offensive to me is the fact that Stream does not implement Iterable (despite actually having method iterator) and cannot be used in a for-each, only with a forEach(). I recommend casting Streams into Iterables with (Iterable<T>)stream::iterator. A better alternative is to use StreamEx which fixes a number of Stream API problems, including implementing Iterable.

That said, forEach() is useful for the following:

  • Atomically iterating over a synchronized list. Prior to this, a list generated with Collections.synchronizedList() was atomic with respect to things like get or set, but was not thread-safe when iterating.

  • Parallel execution (using an appropriate parallel stream). This saves you a few lines of code vs using an ExecutorService, if your problem matches the performance assumptions built into Streams and Spliterators.

  • Specific containers which, like the synchronized list, benefit from being in control of iteration (although this is largely theoretical unless people can bring up more examples)

  • Calling a single function more cleanly by using forEach() and a method reference argument (ie, list.forEach (obj::someMethod)). However, keep in mind the points on checked exceptions, more difficult debugging, and reducing the number of idioms you use when writing code.

Articles I used for reference:

EDIT: Looks like some of the original proposals for lambdas (such as http://www.javac.info/closures-v06a.html Google Cache) solved some of the issues I mentioned (while adding their own complications, of course).

CSS text-decoration underline color

As far as I know it's not possible... but you can try something like this:

_x000D_
_x000D_
.underline _x000D_
{_x000D_
    color: blue;_x000D_
    border-bottom: 1px solid red;_x000D_
}
_x000D_
<div>_x000D_
    <span class="underline">hello world</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Best way to stress test a website

For web service testing, soap rest or WCF (including WebHttpBinding), try out SOA Cleaner. Can be downloded from:http://xyrow.com. There is a free version, and it doesn't require any installation. It can also perform load tests.

Multithreading in Bash

Bash job control involves multiple processes, not multiple threads.

You can execute a command in background with the & suffix.

You can wait for completion of a background command with the wait command.

You can execute multiple commands in parallel by separating them with |. This provides also a synchronization mechanism, since stdout of a command at left of | is connected to stdin of command at right.

How to specify a min but no max decimal using the range data annotation attribute?

[Range(0.01,100000000,ErrorMessage = "Price must be greter than zero !")]

error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65

SOLVED: Always be sure to update your Xcode folks!

Protip: And don't do it from the apple store (but always do it from an official apple website of course)

tip from: http://ericasadun.com/2016/03/22/xcode-upgrades-lessons-learned/

official apple download page: https://developer.apple.com/download/more/

For those who are unable to resolve with above method

  1. Go to project settings in Xcode. Menu File->Project Settings

  2. Go to per-User Project Settings section.

  3. Click on advanced.

  4. Select Xcode Default option. previously this used to be Legacy for my project.

I have analysed on similar lines and concluded that clean is causing the archive to fail. So, the new build system is not clearing the custom/legacy build directory.

delete the build/ folder in ios/ and rerun if that doesn't do any change then
File -> Project Settings (or WorkSpace Settings) -> Build System -> Legacy Build System
Rerun and voilà!

If it still Fails you need to clean full project

Do the following:

  • Delete ios dir manually
  • Clean cache Run npm cache clean --force
  • Run react-native eject
  • Re-install all packages npm install
  • Run the link command react-native link
  • Finally run react-native run-ios

How to change the Spyder editor background to dark?

Yes, that's the intuitive answer. Nothing in Spyder is intuitive. Go to Preferences/Editor and select the scheme you want. Then go to Preferences/Syntax Coloring and adjust the colors if you want to. tcebob

Post to another page within a PHP script

index.php

$url = 'http://[host]/test.php';
$json = json_encode(['name' => 'Jhonn', 'phone' => '128000000000']);

$options = ['http' => [
    'method' => 'POST',
    'header' => 'Content-type:application/json',
    'content' => $json
]];

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

test.php

$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
echo $data['name']; // Jhonn

How to set back button text in Swift

Solution checked and work in Swift 5

Below I put few solutions for different cases:

1. Remove text from back button

The best solution to remove text from back button is to add in viewDidLoad():

navigationItem.backBarButtonItem = UIBarButtonItem()

2. Set own text on back button

In case you want to set your own title, do it by setting title of backButton:

let backButton = UIBarButtonItem()
backButton.title = "My Title"
navigationItem.backBarButtonItem = backItem

3. Empty back button on all VC

If you want to create common style in entire app - to have just arrow back without text, create base VC for all your View Controllers:

class BaseViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.backBarButtonItem = UIBarButtonItem()
    }
}

Solution presented above let you customize back button in the future if you want to make some exception later, by adding additional variable and overriding it in specific ViewController, f.ex:

class BaseViewController: UIViewController {

    var customBackButtonTitle: String?

    override func viewDidLoad() {
        super.viewDidLoad()

        var backButton = UIBarButtonItem()
        if let text = customBackButtonTitle {
            backButton.title = text
        }
        navigationItem.backBarButtonItem = backButton
    }
}

jQuery checkbox onChange

There is no need to use :checkbox, also replace #activelist with #inactivelist:

$('#inactivelist').change(function () {
    alert('changed');
 });

iPhone App Icons - Exact Radius?

The corner radius of the 57 x 57 pixel icon is 9 pixels.

How to register multiple servlets in web.xml in one Spring application

As explained in this thread on the cxf-user mailing list, rather than having the CXFServlet load its own spring context from user-webservice-servlet.xml, you can just load the whole lot into the root context. Rename your existing user-webservice-servlet.xml to some other name (e.g. user-webservice-beans.xml) then change your contextConfigLocation parameter to something like:

<servlet>
  <servlet-name>myservlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>myservlet</servlet-name>
  <url-pattern>*.htm</url-pattern>
</servlet-mapping>

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>
    /WEB-INF/applicationContext.xml
    /WEB-INF/user-webservice-beans.xml
  </param-value>
</context-param>

<servlet>
  <servlet-name>user-webservice</servlet-name>
  <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
  <load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>user-webservice</servlet-name>
  <url-pattern>/UserService/*</url-pattern>
</servlet-mapping>

How to save a plot as image on the disk?

To add to these answers, if you have an R script containing calls that generate plots to screen (the native device), then these can all be saved to a pdf file (the default device for a non-interactive shell) "Rplots.pdf" (the default name) by redirecting the script into R from the terminal (assuming you are running linux or OS X), e.g.:

R < myscript.R --no-save

This could be converted to jpg/png as necessary

Create web service proxy in Visual Studio from a WSDL file

Try using WSDL.exe and then including the generated file (.cs) into your project.

Fire up the Visual Studio Command prompt (under visual studio/tools in the start menu) then type

>wsdl.exe [path To Your WSDL File]

That'll spit out a file, which you copy/move and include in your project. That file contains a class which is a proxy to your sevice, Fire up an instance of that class, and it'll have a URL property you can set on the fly, and a bunch of methods that you can call. It'll also generate classes for all/any complex objects passed across the service interface.

What's the most concise way to read query parameters in AngularJS?

Just a precision to Ellis Whitehead's answer. $locationProvider.html5Mode(true); won't work with new version of angularjs without specifying the base URL for the application with a <base href=""> tag or setting the parameter requireBase to false

From the doc :

If you configure $location to use html5Mode (history.pushState), you need to specify the base URL for the application with a tag or configure $locationProvider to not require a base tag by passing a definition object with requireBase:false to $locationProvider.html5Mode():

$locationProvider.html5Mode({
  enabled: true,
  requireBase: false
});

Convert a string to int using sql query

Try this one, it worked for me in Athena:

cast(MyVarcharCol as integer)

How to get MAC address of your machine using a C program?

A very portable way is to parse the output of this command.

ifconfig | awk '$0 ~ /HWaddr/ { print $5 }'

Provided ifconfig can be run as the current user (usually can) and awk is installed (it often is). This will give you the mac address of the machine.

how to parse JSONArray in android

If you're after the 'name', why does your code snippet look like an attempt to get the 'characters'?

Anyways, this is no different from any other list- or array-like operation: you just need to iterate over the dataset and grab the information you're interested in. Retrieving all the names should look somewhat like this:

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

JSONArray cast = jsonResponse.getJSONArray("abridged_cast");
for (int i=0; i<cast.length(); i++) {
    JSONObject actor = cast.getJSONObject(i);
    String name = actor.getString("name");
    allNames.add(name);
}

(typed straight into the browser, so not tested).

Best practice to return errors in ASP.NET Web API

You can use custom ActionFilter in Web Api to validate model:

public class DRFValidationFilters : ActionFilterAttribute
{

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (!actionContext.ModelState.IsValid)
        {
            actionContext.Response = actionContext.Request
                .CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);

            //BadRequest(actionContext.ModelState);
        }
    }

    public override Task OnActionExecutingAsync(HttpActionContext actionContext,
        CancellationToken cancellationToken)
    {

        return Task.Factory.StartNew(() =>
        {
            if (!actionContext.ModelState.IsValid)
            {
                actionContext.Response = actionContext.Request
                    .CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
            }
        });
    }

    public class AspirantModel
    {
        public int AspirantId { get; set; }
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
        public string AspirantType { get; set; }
        [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$",
            ErrorMessage = "Not a valid Phone number")]
        public string MobileNumber { get; set; }
        public int StateId { get; set; }
        public int CityId { get; set; }
        public int CenterId { get; set; }


        [HttpPost]
        [Route("AspirantCreate")]
        [DRFValidationFilters]
        public IHttpActionResult Create(AspirantModel aspirant)
        {
            if (aspirant != null)
            {

            }
            else
            {
                return Conflict();
            }

            return Ok();
        }
    }
}

Register CustomAttribute class in webApiConfig.cs config.Filters.Add(new DRFValidationFilters());

What is the SSIS package and what does it do?

For Latest Info About SSIS > https://docs.microsoft.com/en-us/sql/integration-services/sql-server-integration-services

From the above referenced site:

Microsoft Integration Services is a platform for building enterprise-level data integration and data transformations solutions. Use Integration Services to solve complex business problems by copying or downloading files, loading data warehouses, cleansing and mining data, and managing SQL Server objects and data.

Integration Services can extract and transform data from a wide variety of sources such as XML data files, flat files, and relational data sources, and then load the data into one or more destinations.

Integration Services includes a rich set of built-in tasks and transformations, graphical tools for building packages, and the Integration Services Catalog database, where you store, run, and manage packages.

You can use the graphical Integration Services tools to create solutions without writing a single line of code. You can also program the extensive Integration Services object model to create packages programmatically and code custom tasks and other package objects.

Getting Started with SSIS - http://msdn.microsoft.com/en-us/sqlserver/bb671393.aspx

If you are Integration Services Information Worker - http://msdn.microsoft.com/en-us/library/ms141667.aspx

If you are Integration Services Administrator - http://msdn.microsoft.com/en-us/library/ms137815.aspx

If you are Integration Services Developer - http://msdn.microsoft.com/en-us/library/ms137709.aspx

If you are Integration Services Architect - http://msdn.microsoft.com/en-us/library/ms142161.aspx

Overview of SSIS - http://msdn.microsoft.com/en-us/library/ms141263.aspx

Integration Services How-to Topics - http://msdn.microsoft.com/en-us/library/ms141767.aspx

How to get old Value with onchange() event in text box

You should use HTML5 data attributes. You can create your own attributes and save different values in them.

How to align center the text in html table row?

<td align="center" valign="center">textgoeshere</td>

Is the only correct answer imho, since your working with tables which is old functionality most common used for e-mail formatting. So your best bet is to not use just style but inline style and known table tags.

Disabling submit button until all fields have values

All variables are cached so the loop and keyup event doesn't have to create a jQuery object everytime it runs.

var $input = $('input:text'),
    $register = $('#register');    
$register.attr('disabled', true);

$input.keyup(function() {
    var trigger = false;
    $input.each(function() {
        if (!$(this).val()) {
            trigger = true;
        }
    });
    trigger ? $register.attr('disabled', true) : $register.removeAttr('disabled');
});

Check working example at http://jsfiddle.net/DKNhx/3/

jQuery returning "parsererror" for ajax request

I have encountered such error but after modifying my response before sending it to the client it worked fine.

//Server side
response = JSON.stringify('{"status": {"code": 200},"result": '+ JSON.stringify(result)+'}');
res.send(response);  // Sending to client

//Client side
success: function(res, status) {
    response = JSON.parse(res); // Getting as expected
    //Do something
}

rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

Here's the quick fix:

If you're using capistrano do this add this to your deploy.rb:

after 'deploy:update_code' do
  run "cd #{release_path}; RAILS_ENV=production rake assets:precompile"
end

cap deploy

How to detect Windows 64-bit platform with .NET?

Enjoy ;-)

Function Is64Bit() As Boolean

    Return My.Computer.FileSystem.SpecialDirectories.ProgramFiles.Contains("Program Files (x86)")

End Function

The server response was: 5.7.0 Must issue a STARTTLS command first. i16sm1806350pag.18 - gsmtp

If you are passing (like me) all the parameters like port, username, password through a system and you are not allow to modify the code, then you can do that easy change on the web.config:

<system.net>
  <mailSettings>
    <smtp>
      <network enableSsl="true"/>
    </smtp>
  </mailSettings>
</system.net>

Server.Transfer Vs. Response.Redirect

There are many differences as specified above. Apart from above all, there is one more difference. Response.Redirect() can be used to redirect user to any page which is not part of the application but Server.Transfer() can only be used to redirect user within the application.

//This will work.
Response.Redirect("http://www.google.com");

//This will not work.
Server.Transfer("http://www.google.com");

How to force ViewPager to re-instantiate its items

public class DayFlipper extends ViewPager {

private Flipperadapter adapter;
public class FlipperAdapter extends PagerAdapter {

    @Override
    public int getCount() {
        return DayFlipper.DAY_HISTORY;
    }

    @Override
    public void startUpdate(View container) {
    }

    @Override
    public Object instantiateItem(View container, int position) {
        Log.d(TAG, "instantiateItem(): " + position);

        Date d = DateHelper.getBot();
        for (int i = 0; i < position; i++) {
            d = DateHelper.getTomorrow(d);
        }

        d = DateHelper.normalize(d);

        CubbiesView cv = new CubbiesView(mContext);
        cv.setLifeDate(d);
        ((ViewPager) container).addView(cv, 0);
        // add map
        cv.setCubbieMap(mMap);
        cv.initEntries(d);
adpter = FlipperAdapter.this;
        return cv;
    }

    @Override
    public void destroyItem(View container, int position, Object object) {
        ((ViewPager) container).removeView((CubbiesView) object);
    }

    @Override
    public void finishUpdate(View container) {

    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((CubbiesView) object);
    }

    @Override
    public Parcelable saveState() {
        return null;
    }

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {

    }

}

    ...

    public void refresh() {
    adapter().notifyDataSetChanged();
}
}

try this.

Singletons vs. Application Context in Android?

Consider both at the same time:

  • having singleton objects as static instances inside the classes.
  • having a common class (Context) that returns the singleton instances for all the singelton objects in your application, which has the advantage that the method names in Context will be meaningful for example: context.getLoggedinUser() instead of User.getInstance().

Furthermore, I suggest that you expand your Context to include not only access to singleton objects but some functionalities that need to be accessed globally, like for example: context.logOffUser(), context.readSavedData(), etc. Probably renaming the Context to Facade would make sense then.

Plot different DataFrames in the same figure

Although Chang's answer explains how to plot multiple times on the same figure, in this case you might be better off in this case using a groupby and unstacking:

(Assuming you have this in dataframe, with datetime index already)

In [1]: df
Out[1]:
            value  
datetime                         
2010-01-01      1  
2010-02-01      1  
2009-01-01      1  

# create additional month and year columns for convenience
df['Month'] = map(lambda x: x.month, df.index)
df['Year'] = map(lambda x: x.year, df.index)    

In [5]: df.groupby(['Month','Year']).mean().unstack()
Out[5]:
       value      
Year    2009  2010
Month             
1          1     1
2        NaN     1

Now it's easy to plot (each year as a separate line):

df.groupby(['Month','Year']).mean().unstack().plot()

Move view with keyboard using Swift

Use following code for view Up on UITextField Clicked

func textFieldDidBeginEditing(textField: UITextField) {
    ViewUpanimateMoving(true, upValue: 100)
}
func textFieldDidEndEditing(textField: UITextField) {
    ViewUpanimateMoving(false, upValue: 100)
}
func ViewUpanimateMoving (up:Bool, upValue :CGFloat){
    var durationMovement:NSTimeInterval = 0.3
    var movement:CGFloat = ( up ? -upValue : upValue)
    UIView.beginAnimations( "animateView", context: nil)
    UIView.setAnimationBeginsFromCurrentState(true)
    UIView.setAnimationDuration(durationMovement)
    self.view.frame = CGRectOffset(self.view.frame, 0,  movement)
    UIView.commitAnimations()
}

How to reload apache configuration for a site without restarting apache?

Late answer here, but if you search /etc/init.d/apache2 for 'reload', you'll find something like this:

do_reload() {
        if apache_conftest; then
                if ! pidofproc -p $PIDFILE "$DAEMON" > /dev/null 2>&1 ; then
                        APACHE2_INIT_MESSAGE="Apache2 is not running"
                        return 2
                fi
                $APACHE2CTL graceful > /dev/null 2>&1
                return $?
        else
                APACHE2_INIT_MESSAGE="The apache2$DIR_SUFFIX configtest failed. Not doing anything."
                return 2
        fi
}

Basically, what the answers that suggest using init.d, systemctl, etc are invoking is a thin wrapper that says:

  • check the apache config
  • if it's good, run apachectl graceful (swallowing the output, and forwarding the exit code)

This suggests that @Aruman's answer is also correct, provided you are confident there are no errors in your configuration or have already run apachctl configtest manually.

The apache documentation also supplies the same command for a graceful restart (apachectl -k graceful), and some more color on the behavior thereof.

C# - What does the Assert() method do? Is it still useful?

You should use it for times when you don't want to have to breakpoint every little line of code to check variables, but you do want to get some sort of feedback if certain situations are present, for example:

Debug.Assert(someObject != null, "someObject is null! this could totally be a bug!");

Return a "NULL" object if search result not found

You can try this:

return &Type();

How to set a value for a span using jQuery

You are using jQuery(document).ready(function($) {} means here you are using jQuery instead of $. So to resolve your issue use following code.

jQuery("#submittername").text(submitter_name);

This will resolve your problem.

xcode-select active developer directory error

Simply run sudo xcode-select -r which should automatically reset the path.

 -r, --reset
              Unsets any user-specified developer directory, so that the developer directory will be found via the default search mechanism. This command must  be
              run with superuser permissions (see sudo(8)), and will affect all users on the system.

Making href (anchor tag) request POST instead of GET?

Using jQuery it is very simple assuming the URL you wish to post to is on the same server or has implemented CORS

$(function() {
  $("#employeeLink").on("click",function(e) {
    e.preventDefault(); // cancel the link itself
    $.post(this.href,function(data) {
      $("#someContainer").html(data);
    });
  });
});

If you insist on using frames which I strongly discourage, have a form and submit it with the link

<form action="employee.action" method="post" target="myFrame" id="myForm"></form>

and use (in plain JS)

 window.addEventListener("load",function() {
   document.getElementById("employeeLink").addEventListener("click",function(e) {
     e.preventDefault(); // cancel the link
     document.getElementById("myForm").submit(); // but make sure nothing has name or ID="submit"
   });
 });

Without a form we need to make one

 window.addEventListener("load",function() {
   document.getElementById("employeeLink").addEventListener("click",function(e) {
     e.preventDefault(); // cancel the actual link
     var myForm = document.createElement("form");
     myForm.action=this.href;// the href of the link
     myForm.target="myFrame";
     myForm.method="POST";
     myForm.submit();
   });
 });

Splitting templated C++ classes into .hpp/.cpp files--is it possible?

Sometimes it is possible to have most of implementation hidden in cpp file, if you can extract common functionality foo all template parameters into non-template class (possibly type-unsafe). Then header will contain redirection calls to that class. Similar approach is used, when fighting with "template bloat" problem.

Facebook Open Graph Error - Inferred Property

In my case an unexpected error notice in the source code stopped the facebook crawler from parsing the (correctly set) og-meta tags.

I was using the HTTP_ACCEPT_LANGUAGE header, which worked fine for regular browser requests but not for the crawler, as it obviously won't use/set it.

Therefore, it was crucial for me to use the facebook's debugger feature See exactly what our scraper sees for your URL, as the error notice only could only be seen there (but not through the regular 'view source code'-browser feature).

screenshot of the facebook debugger

Can you run GUI applications in a Docker container?

OSX

Jürgen Weigert has the best answer that worked for me on Ubuntu, however on OSX, docker runs inside of VirtualBox and so the solution doesn't work without some more work.

I've got it working with these additional ingredients:

  1. Xquartz (OSX no longer ships with X11 server)
  2. socket forwarding with socat (brew install socat)
  3. bash script to launch the container

I'd appreciate user comments to improve this answer for OSX, I'm not sure if socket forwarding for X is secure, but my intended use is for running the docker container locally only.

Also, the script is a bit fragile in that it's not easy to get the IP address of the machine since it's on our local wireless so it's always some random IP.

The BASH script I use to launch the container:

#!/usr/bin/env bash

CONTAINER=py3:2016-03-23-rc3
COMMAND=/bin/bash
NIC=en0

# Grab the ip address of this box
IPADDR=$(ifconfig $NIC | grep "inet " | awk '{print $2}')

DISP_NUM=$(jot -r 1 100 200)  # random display number between 100 and 200

PORT_NUM=$((6000 + DISP_NUM)) # so multiple instances of the container won't interfer with eachother

socat TCP-LISTEN:${PORT_NUM},reuseaddr,fork UNIX-CLIENT:\"$DISPLAY\" 2>&1 > /dev/null &

XSOCK=/tmp/.X11-unix
XAUTH=/tmp/.docker.xauth.$USER.$$
touch $XAUTH
xauth nlist $DISPLAY | sed -e 's/^..../ffff/' | xauth -f $XAUTH nmerge -

docker run \
    -it \
    --rm \
    --user=$USER \
    --workdir="/Users/$USER" \
    -v "/Users/$USER:/home/$USER:rw" \
    -v $XSOCK:$XSOCK:rw \
    -v $XAUTH:$XAUTH:rw \
    -e DISPLAY=$IPADDR:$DISP_NUM \
    -e XAUTHORITY=$XAUTH \
    $CONTAINER \
    $COMMAND

rm -f $XAUTH
kill %1       # kill the socat job launched above

I'm able to get xeyes and matplotlib working with this approach.

Windows 7+

It's a bit easier on Windows 7+ with MobaXterm:

  1. Install MobaXterm for windows
  2. Start MobaXterm
  3. Configure X server: Settings -> X11 (tab) -> set X11 Remote Access to full
  4. Use this BASH script to launch the container

run_docker.bash:

#!/usr/bin/env bash

CONTAINER=py3:2016-03-23-rc3
COMMAND=/bin/bash
DISPLAY="$(hostname):0"
USER=$(whoami)

docker run \
    -it \
    --rm \
    --user=$USER \
    --workdir="/home/$USER" \
    -v "/c/Users/$USER:/home/$USER:rw" \
    -e DISPLAY \
    $CONTAINER \
    $COMMAND

xeyes running on PC

SQL DELETE with INNER JOIN

if the database is InnoDB you dont need to do joins in deletion. only

DELETE FROM spawnlist WHERE spawnlist.type = "monster";

can be used to delete the all the records that linked with foreign keys in other tables, to do that you have to first linked your tables in design time.

CREATE TABLE IF NOT EXIST spawnlist (
  npc_templateid VARCHAR(20) NOT NULL PRIMARY KEY

)ENGINE=InnoDB;

CREATE TABLE IF NOT EXIST npc (
  idTemplate VARCHAR(20) NOT NULL,

  FOREIGN KEY (idTemplate) REFERENCES spawnlist(npc_templateid) ON DELETE CASCADE

)ENGINE=InnoDB;

if you uses MyISAM you can delete records joining like this

DELETE a,b
FROM `spawnlist` a
JOIN `npc` b
ON a.`npc_templateid` = b.`idTemplate`
WHERE a.`type` = 'monster';

in first line i have initialized the two temp tables for delet the record, in second line i have assigned the existance table to both a and b but here i have linked both tables together with join keyword, and i have matched the primary and foreign key for both tables that make link, in last line i have filtered the record by field to delete.

Customizing the template within a Directive

The above answers unfortunately don't quite work. In particular, the compile stage does not have access to scope, so you can't customize the field based on dynamic attributes. Using the linking stage seems to offer the most flexibility (in terms of asynchronously creating dom, etc.) The below approach addresses that:

<!-- Usage: -->
<form>
  <form-field ng-model="formModel[field.attr]" field="field" ng-repeat="field in fields">
</form>
// directive
angular.module('app')
.directive('formField', function($compile, $parse) {
  return { 
    restrict: 'E', 
    compile: function(element, attrs) {
      var fieldGetter = $parse(attrs.field);

      return function (scope, element, attrs) {
        var template, field, id;
        field = fieldGetter(scope);
        template = '..your dom structure here...'
        element.replaceWith($compile(template)(scope));
      }
    }
  }
})

I've created a gist with more complete code and a writeup of the approach.

Bash script to cd to directory with spaces in pathname

You can use any of:

cd ~/"My Code"
cd ~/M"y Code"
cd ~/My" Code"

You cannot use:

cd ~"/My Code"

The first works because the shell expands ~/ into $HOME/, and then tacks on My Code without the double quotes. The second fails because there isn't a user called '"' (double quote) for ~" to map to.

Matplotlib scatter plot legend

if you are using matplotlib version 3.1.1 or above, you can try:

import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

x = [1, 3, 4, 6, 7, 9]
y = [0, 0, 5, 8, 8, 8]
classes = ['A', 'B', 'C']
values = [0, 0, 1, 2, 2, 2]
colours = ListedColormap(['r','b','g'])
scatter = plt.scatter(x, y,c=values, cmap=colours)
plt.legend(handles=scatter.legend_elements()[0], labels=classes)

results2

PHP Function Comments

That's phpDoc syntax.

Read more here: phpDocumentor

How do I concatenate a string with a variable?

In javascript the "+" operator is used to add numbers or to concatenate strings. if one of the operands is a string "+" concatenates, and if it is only numbers it adds them.

example:

1+2+3 == 6
"1"+2+3 == "123"

How do I use raw_input in Python 3

Here's a piece of code I put in my scripts that I wan't to run in py2/3-agnostic environment:

# Thank you, python2-3 team, for making such a fantastic mess with
# input/raw_input :-)
real_raw_input = vars(__builtins__).get('raw_input',input)

Now you can use real_raw_input. It's quite expensive but short and readable. Using raw input is usually time expensive (waiting for input), so it's not important.

In theory, you can even assign raw_input instead of real_raw_input but there might be modules that check existence of raw_input and behave accordingly. It's better stay on the safe side.

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

The best solution i found out is to mute the video

HTML

<video loop muted autoplay id="videomain">
  <source src="videoname.mp4" type="video/mp4">
</video>

Convert HTML5 into standalone Android App

You can use https://appery.io/ It is the same phonegap but in very convinient wrapper

Removing underline with href attribute

Add a style with the attribute text-decoration:none;:

There are a number of different ways of doing this.

Inline style:

<a href="xxx.html" style="text-decoration:none;">goto this link</a>

Inline stylesheet:

<html>
<head>
<style type="text/css">
   a {
      text-decoration:none;
   }
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

External stylesheet:

<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

stylesheet.css:

a {
      text-decoration:none;
   }

Can you style html form buttons with css?

Yes you can target those specificaly using input[type=submit] e.g.

.myFormClass input[type=submit] {
  margin: 10px;
  color: white;
  background-color: blue;
}

SQL Server : converting varchar to INT

I would try triming the number to see what you get:

select len(rtrim(ltrim(userid))) from audit

if that return the correct value then just do:

select convert(int, rtrim(ltrim(userid))) from audit

if that doesn't return the correct value then I would do a replace to remove the empty space:

 select convert(int, replace(userid, char(0), '')) from audit

Using margin:auto to vertically-align a div

Update Aug 2020

Although the below is still worth reading for the useful info, we have had Flexbox for some time now, so just use that, as per this answer.


You can't use:

vertical-align:middle because it's not applicable to block-level elements

margin-top:auto and margin-bottom:auto because their used values would compute as zero

margin-top:-50% because percentage-based margin values are calculated relative to the width of containing block

In fact, the nature of document flow and element height calculation algorithms make it impossible to use margins for centering an element vertically inside its parent. Whenever a vertical margin's value is changed, it will trigger a parent element height re-calculation (re-flow), which would in turn trigger a re-center of the original element... making it an infinite loop.

You can use:

A few workarounds like this which work for your scenario; the three elements have to be nested like so:

_x000D_
_x000D_
.container {
    display: table;
    height: 100%;
    position: absolute;
    overflow: hidden;
    width: 100%;
}
.helper {
    #position: absolute;
    #top: 50%;
    display: table-cell;
    vertical-align: middle;
}
.content {
    #position: relative;
    #top: -50%;
    margin: 0 auto;
    width: 200px;
    border: 1px solid orange;
}
_x000D_
<div class="container">
    <div class="helper">
        <div class="content">
            <p>stuff</p>
        </div>
    </div>
</div
_x000D_
_x000D_
_x000D_

JSFiddle works fine according to Browsershot.

How to set conditional breakpoints in Visual Studio?

Just another way of doing it, (or if you are using express) add the condition in code:

if(yourCondition)
{
    System.Diagnostics.Debugger.Break();
}

Select distinct values from a table field

In addition to the still very relevant answer of jujule, I find it quite important to also be aware of the implications of order_by() on distinct("field_name") queries. This is, however, a Postgres only feature!

If you are using Postgres and if you define a field name that the query should be distinct for, then order_by() needs to begin with the same field name (or field names) in the same sequence (there may be more fields afterward).

Note

When you specify field names, you must provide an order_by() in the QuerySet, and the fields in order_by() must start with the fields in distinct(), in the same order.

For example, SELECT DISTINCT ON (a) gives you the first row for each value in column a. If you don’t specify an order, you’ll get some arbitrary row.

If you want to e-g- extract a list of cities that you know shops in , the example of jujule would have to be adapted to this:

# returns an iterable Queryset of cities.
models.Shop.objects.order_by('city').values_list('city', flat=True).distinct('city')  

Enable binary mode while restoring a Database from an SQL dump

In Windows machine, please follows the preceding steps.

  1. Open file in notepad.
  2. Click on Save as
  3. Select Encoding type UTF-8.

Now source your db.

Can I use Class.newInstance() with constructor arguments?

I think this is exactly what you want http://da2i.univ-lille1.fr/doc/tutorial-java/reflect/object/arg.html

Although it seems a dead thread, someone might find it useful

Is it still valid to use IE=edge,chrome=1?

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> serves two purposes.

  1. IE=edge: specifies that IE should run in the highest mode available to that version of IE as opposed to a compatability mode; IE8 can support up to IE8 modes, IE9 can support up to IE9 modes, and so on.
  2. chrome=1: specifies that Google Chrome frame should start if the user has it installed

The IE=edge flag is still relevant for IE versions 10 and below. IE11 sets this mode as the default.

As for the chrome flag, you can leave it if your users still use Chrome Frame. Despite support and updates for Chrome Frame ending, one can still install and use the final release. If you remove the flag, Chrome Frame will not be activated when installed. For other users, chrome=1 will do nothing more than consume a few bytes of bandwidth.

I recommend you analyze your audience and see if their browsers prohibit any needed features and then decide. Perhaps it might be better to encourage them to use a more modern, evergreen browser.

Note, the W3C validator will flag chrome=1 as an error:

Error: A meta element with an http-equiv attribute whose value is
X-UA-Compatible must have a content attribute with the value IE=edge.

How to pass props to {this.props.children}

The slickest way to do this:

    {React.cloneElement(this.props.children, this.props)}

Authenticate Jenkins CI for Github private repository

Perhaps GitHub's support for deploy keys is what you're looking for? To quote that page:

When should I use a deploy key?

Simple, when you have a server that needs pull access to a single private repo. This key is attached directly to the repository instead of to a personal user account.

If that's what you're already trying and it doesn't work, you might want to update your question with more details of the URLs being used, the names and location of the key files, etc.


Now for the technical part: How to use your SSH key with Jenkins?

If you have, say, a jenkins unix user, you can store your deploy key in ~/.ssh/id_rsa. When Jenkins tries to clone the repo via ssh, it will try to use that key.

In some setups, you cannot run Jenkins as an own user account, and possibly also cannot use the default ssh key location ~/.ssh/id_rsa. In such cases, you can create a key in a different location, e.g. ~/.ssh/deploy_key, and configure ssh to use that with an entry in ~/.ssh/config:

Host github-deploy-myproject
    HostName       github.com
    User           git
    IdentityFile   ~/.ssh/deploy_key
    IdentitiesOnly yes

Because all you authenticate to all Github repositories using [email protected] and you don't want the above key to be used for all your connections to Github, we created a host alias github-deploy-myproject. Your clone URL now becomes

git clone github-deploy-myproject:myuser/myproject

and that is also what you put as repository URL into Jenkins.

(Note that you must not put ssh:// in front in order for this to work.)

Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0

Your target SDK might be higher than SDK of the device, change that. For example, your device is running API 23 but your target SDK is 25. Change 25 to 23.

Cut Corners using CSS

With a small edit to Joseph's code, the element does not require a solid background:

div {
    height: 300px;
    background: url('http://images2.layoutsparks.com/1/190037/serene-nature-scenery-blue.jpg');
    position: relative;
}

div:before {
    content: '';
    position: absolute;
    top: 0; right: 0;
    border-top: 80px solid white;
    border-left: 80px solid rgba(0,0,0,0);
    width: 0;
}

http://jsfiddle.net/2bZAW/1921/

This use of 'rgba(0,0,0,0)' allows the inner 'corner' to be invisible .

You can also edit the 4th parameter 'a', where 0 < a < 1, to have a shadow for more of a 'folded-corner' effect:

http://jsfiddle.net/2bZAW/1922/ (with shadow)


NOTE: RGBA color values are supported in IE9+, Firefox 3+, Chrome, Safari, and in Opera 10+.

How to Iterate over a Set/HashSet without an Iterator?

Converting your set into an array may also help you for iterating over the elements:

Object[] array = set.toArray();

for(int i=0; i<array.length; i++)
   Object o = array[i];

Set a default parameter value for a JavaScript function

function helloWorld(name, symbol = '!!!') {
    name = name || 'worlds';
    console.log('hello ' + name + symbol);
}

helloWorld(); // hello worlds!!!

helloWorld('john'); // hello john!!!

helloWorld('john', '(>.<)'); // hello john(>.<)

helloWorld('john', undefined); // hello john!!!

helloWorld(undefined, undefined); // hello worlds!!!

How I can check whether a page is loaded completely or not in web driver?

You can get the HTML of the website with driver.getPageSource(). If the html does not change in a given interval of time this means that the page is done loading. One or two seconds should be enough. If you want to speed things up you can just compare the lenght of the two htmls. If their lenght is equal the htmls should be equal and that means the page is fully loaded. The JavaScript solution did not work for me.

How to export private key from a keystore of self-signed certificate

http://anandsekar.github.io/exporting-the-private-key-from-a-jks-keystore/

public class ExportPrivateKey {
        private File keystoreFile;
        private String keyStoreType;
        private char[] password;
        private String alias;
        private File exportedFile;

        public static KeyPair getPrivateKey(KeyStore keystore, String alias, char[] password) {
                try {
                        Key key=keystore.getKey(alias,password);
                        if(key instanceof PrivateKey) {
                                Certificate cert=keystore.getCertificate(alias);
                                PublicKey publicKey=cert.getPublicKey();
                                return new KeyPair(publicKey,(PrivateKey)key);
                        }
                } catch (UnrecoverableKeyException e) {
        } catch (NoSuchAlgorithmException e) {
        } catch (KeyStoreException e) {
        }
        return null;
        }

        public void export() throws Exception{
                KeyStore keystore=KeyStore.getInstance(keyStoreType);
                BASE64Encoder encoder=new BASE64Encoder();
                keystore.load(new FileInputStream(keystoreFile),password);
                KeyPair keyPair=getPrivateKey(keystore,alias,password);
                PrivateKey privateKey=keyPair.getPrivate();
                String encoded=encoder.encode(privateKey.getEncoded());
                FileWriter fw=new FileWriter(exportedFile);
                fw.write(“—–BEGIN PRIVATE KEY—–\n“);
                fw.write(encoded);
                fw.write(“\n“);
                fw.write(“—–END PRIVATE KEY—–”);
                fw.close();
        }


        public static void main(String args[]) throws Exception{
                ExportPrivateKey export=new ExportPrivateKey();
                export.keystoreFile=new File(args[0]);
                export.keyStoreType=args[1];
                export.password=args[2].toCharArray();
                export.alias=args[3];
                export.exportedFile=new File(args[4]);
                export.export();
        }
}

Python: Pandas Dataframe how to multiply entire column with a scalar

try using apply function.

df['quantity'] = df['quantity'].apply(lambda x: x*-1)

Control the size of points in an R scatterplot?

pch=20 returns a symbol sized between "." and 19.

It's a filled symbol (which is probably what you want).

Aside from that, even the base graphics system in R allows a user fine-grained control over symbol size, color, and shape. E.g.,

dfx = data.frame(ev1=1:10, ev2=sample(10:99, 10), ev3=10:1)

with(dfx, symbols(x=ev1, y=ev2, circles=ev3, inches=1/3,
                  ann=F, bg="steelblue2", fg=NULL))

Graph example

Reverse of JSON.stringify?

$("#save").click(function () {
    debugger
    var xx = [];
    var dd = { "firstname": "", "lastname": "", "address": "" };
    var otable1 = $("#table1").dataTable().fnGetData();

    for (var i = 0; i < otable1.length; i++) {
        dd.firstname = otable1[i][0];
        dd.lastname = otable1[i][1];
        dd.address = otable1[i][2];
        xx.push(dd);
        var dd = { "firstname": "", "lastname": "", "address": "" };
    }
    JSON.stringify(alert(xx));
    $.ajax({

        url: '../Home/save',
        type: 'POST',
        data: JSON.stringify({ u: xx }),
        contentType: 'application/json;',
        dataType: 'json',
        success: function (event) {
            alert(event);
            $("#table2").dataTable().fnDraw();
            location.reload();
        }
    });
});

php - How do I fix this illegal offset type error

Use trim($source) before $s[$source].

Null check in an enhanced for loop

You should better verify where you get that list from.

An empty list is all you need, because an empty list won't fail.

If you get this list from somewhere else and don't know if it is ok or not you could create a utility method and use it like this:

for( Object o : safe( list ) ) {
   // do whatever 
 }

And of course safe would be:

public static List safe( List other ) {
    return other == null ? Collections.EMPTY_LIST : other;
}

How to change the time format (12/24 hours) of an <input>?

Simple HTML trick to get this :

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="row" >_x000D_
                       _x000D_
                        <div class="col-md-6">_x000D_
                             <div class="row">_x000D_
                                <div class="col-md-4" >_x000D_
                                       <label for="hours">Hours</label>_x000D_
          <select class="form-control" required>_x000D_
                <option>  </option>_x000D_
                <option value="1"> 1 </option>_x000D_
                <option value="2"> 2 </option>_x000D_
                <option value="3"> 3 </option>_x000D_
                <option value="4"> 4 </option>_x000D_
                <option value="5"> 5 </option>_x000D_
                <option value="6"> 6 </option>_x000D_
                <option value="7"> 7 </option>_x000D_
                <option value="8"> 8 </option>_x000D_
                <option value="9"> 9 </option>_x000D_
                <option value="10"> 10 </option>_x000D_
                <option value="11"> 11 </option>_x000D_
                <option value="12"> 12 </option>_x000D_
              </select>_x000D_
             </div>_x000D_
                <div class="col-md-4" >_x000D_
                      <label for="minutes">Minutes</label>_x000D_
              <select class="form-control" required="">_x000D_
                <option selected disabled>  </option>_x000D_
                <option value="00"> 00 </option>_x000D_
                <option value="10"> 10 </option>_x000D_
                <option value="20"> 20 </option>_x000D_
                <option value="30"> 30 </option>_x000D_
                <option value="40"> 40 </option>_x000D_
                <option value="50"> 50 </option>_x000D_
              </select>_x000D_
             </div>_x000D_
                 <div class="col-md-4" >_x000D_
                       <label for="hours">Select Meridiem</label>_x000D_
              <select class="form-control" required="" >_x000D_
                <option selected="" value="AM"> AM </option>_x000D_
                <option value="PM"> PM </option>_x000D_
              </select>_x000D_
              </div>_x000D_
             </div></div>_x000D_
                    </div>
_x000D_
_x000D_
_x000D_

Close application and launch home screen on Android

I use this:

1) The parent activity call the secondary activity with the method "startActivityForResult"

2) In the secondary activity when is closing:

int exitCode = 1; // Select the number you want
setResult(exitCode);
finish();

3) And in the parent activity override the method "onActivityResult":

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    int exitCode = 1;
    if(resultCode == exitCode) {
        super.setResult(exitCode); // use this if you have more than 2 activities
        finish();
    }
}

This works fine for me.

Does file_get_contents() have a timeout setting?

It is worth noting that if changing default_socket_timeout on the fly, it might be useful to restore its value after your file_get_contents call:

$default_socket_timeout = ini_get('default_socket_timeout');
....
ini_set('default_socket_timeout', 10);
file_get_contents($url);
...
ini_set('default_socket_timeout', $default_socket_timeout);

How to run iPhone emulator WITHOUT starting Xcode?

You can get it to launch via spotlight if you create an Automator launcher for it:

  1. Open Automator.app
  2. Choose type of Application
  3. Select Actions > Library > Utilities > Launch Application
  4. Open the dropdown of applications that can be launched and choose Other
  5. You can't directly select the Simulator app because it's inside the Xcode.app package. So instead you'll have to navigate to it in a separate Finder window and drag it onto the file selector window. It will be at one of the following paths depending on your version of Xcode (oldest to newest):
    • /Applications/Xcode.app/Contents/Developer/iOS Simulator.app
    • /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iOS Simulator.app
    • /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app
  6. Finally, save this Automator app in your applications folder as iOS Simulator.app

Create Automator app

To get a nice icon for the Automator app you just made, you can do the following:

  1. Right click iOS Simulator.app and choose Get Info
  2. Click the icon in the upper left corner and do Cmd-C to copy it
  3. Right click your Automator app and choose Get Info
  4. Click the icon in the upper left corner and do Cmd-V to paste

Copy icon

How to get margin value of a div in plain JavaScript?

I found something very useful on this site when I was searching for an answer on this question. You can check it out at http://www.codingforums.com/javascript-programming/230503-how-get-margin-left-value.html. The part that helped me was the following:

_x000D_
_x000D_
/***
 * get live runtime value of an element's css style
 *   http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element
 *     note: "styleName" is in CSS form (i.e. 'font-size', not 'fontSize').
 ***/
var getStyle = function(e, styleName) {
  var styleValue = "";
  if (document.defaultView && document.defaultView.getComputedStyle) {
    styleValue = document.defaultView.getComputedStyle(e, "").getPropertyValue(styleName);
  } else if (e.currentStyle) {
    styleName = styleName.replace(/\-(\w)/g, function(strMatch, p1) {
      return p1.toUpperCase();
    });
    styleValue = e.currentStyle[styleName];
  }
  return styleValue;
}
////////////////////////////////////
var e = document.getElementById('yourElement');
var marLeft = getStyle(e, 'margin-left');
console.log(marLeft);    // 10px
_x000D_
#yourElement {
  margin-left: 10px;
}
_x000D_
<div id="yourElement"></div>
_x000D_
_x000D_
_x000D_

Inserting HTML into a div

And many lines may look like this. The html here is sample only.

var div = document.createElement("div");

div.innerHTML =
    '<div class="slideshow-container">\n' +
    '<div class="mySlides fade">\n' +
    '<div class="numbertext">1 / 3</div>\n' +
    '<img src="image1.jpg" style="width:100%">\n' +
    '<div class="text">Caption Text</div>\n' +
    '</div>\n' +

    '<div class="mySlides fade">\n' +
    '<div class="numbertext">2 / 3</div>\n' +
    '<img src="image2.jpg" style="width:100%">\n' +
    '<div class="text">Caption Two</div>\n' +
    '</div>\n' +

    '<div class="mySlides fade">\n' +
    '<div class="numbertext">3 / 3</div>\n' +
    '<img src="image3.jpg" style="width:100%">\n' +
    '<div class="text">Caption Three</div>\n' +
    '</div>\n' +

    '<a class="prev" onclick="plusSlides(-1)">&#10094;</a>\n' +
    '<a class="next" onclick="plusSlides(1)">&#10095;</a>\n' +
    '</div>\n' +
    '<br>\n' +

    '<div style="text-align:center">\n' +
    '<span class="dot" onclick="currentSlide(1)"></span> \n' +
    '<span class="dot" onclick="currentSlide(2)"></span> \n' +
    '<span class="dot" onclick="currentSlide(3)"></span> \n' +
    '</div>\n';

document.body.appendChild(div);

How can I install a CPAN module into a local directory?

I strongly recommend Perlbrew. It lets you run multiple versions of Perl, install packages, hack Perl internals if you want to, all regular user permissions.

How to add a list item to an existing unordered list?

$("#content ul").append('<li><a href="/user/messages"><span class="tab">Message Center</span></a></li>');

Here is some feedback regarding Code Readability (shameless plug for a blog). http://coderob.wordpress.com/2012/02/02/code-readability

Consider separating the declaration of your new elements from the action of adding them to your UL.. It would look something like this:

var tabSpan = $('<span/>', {
    html: 'Message Center'
});
var messageCenterAnchor = $('<a/>', {
    href='/user/messages',
    html: tabSpan
});
var newListItem = $('<li/>', {
    html: messageCenterAnchor,
    "id": "myIDGoesHere"
});    // NOTE: you have to put quotes around "id" for IE..

$("content ul").append(newListItem);

Happy coding :)

How does the Java 'for each' loop work?

It's implied by nsayer's answer, but it's worth noting that the OP's for(..) syntax will work when "someList" is anything that implements java.lang.Iterable -- it doesn't have to be a list, or some collection from java.util. Even your own types, therefore, can be used with this syntax.

Using multiple IF statements in a batch file

is there a special guideline that should be followed

There is no "standard" way to do batch files, because the vast majority of their authors and maintainers either don't understand programming concepts, or they think they don't apply to batch files.

But I am a programmer. I'm used to compiling, and I'm used to debuggers. Batch files aren't compiled, and you can't run them through a debugger, so they make me nervous. I suggest you be extra strict on what you write, so you can be very sure it will do what you think it does.

There are some coding standards that say: If you write an if statement, you must use braces, even if you don't have an else clause. This saves you from subtle, hard-to-debug problems, and is unambiguously readable. I see no reason you couldn't apply this reasoning to batch files.

Let's take a look at your code.

IF EXIST somefile.txt IF EXIST someotherfile.txt SET var=somefile.txt,someotherfile.txt

And the IF syntax, from the command, HELP IF:

IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXISTS filename command

...

IF EXIST filename (
  command
) ELSE (
  other command
)

So you are chaining IF's as commands.

If you use the common coding-standard rule I mentioned above, you would always want to use parens. Here is how you would do so for your example code:

IF EXIST "somefile.txt" (
  IF EXIST "someotherfile.txt" (
    SET var="somefile.txt,someotherfile.txt"
  )
)

Make sure you cleanly format, and do some form of indentation. You do it in code, and you should do it in your batch scripts.

Also, you should also get in the habit of always quoting your file names, and getting the quoting right. There is some verbiage under HELP FOR and HELP SET that will help you with removing extra quotes when re-quoting strings.

Edit

From your comments, and re-reading your original question, it seems like you want to build a comma separated list of files that exist. For this case, you could simply use a bunch of if/else statements, but that would result in a bunch of duplicated logic, and would not be at all clean if you had more than two files.

A better way is to write a sub-routine that checks for a single file's existence, and appends to a variable if the file specified exists. Then just call that subroutine for each file you want to check for:

@ECHO OFF
SETLOCAL

REM Todo: Set global script variables here
CALL :MainScript
GOTO :EOF

REM MainScript()
:MainScript
  SETLOCAL

  CALL :AddIfExists "somefile.txt" "%files%" "files"
  CALL :AddIfExists "someotherfile.txt" "%files%" "files"

  ECHO.Files: %files%

  ENDLOCAL
GOTO :EOF

REM AddIfExists(filename, existingFilenames, returnVariableName)
:AddIfExists
  SETLOCAL

  IF EXIST "%~1" (
    SET "result=%~1"
  ) ELSE (
    SET "result="
  )

  (
    REM Cleanup, and return result - concatenate if necessary
    ENDLOCAL

    IF "%~2"=="" (
      SET "%~3=%result%"
    ) ELSE (
      SET "%~3=%~2,%result%"
    )
  )
GOTO :EOF

append option to select menu?

HTML

<select id="mySelect">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
</select>

JavaScript

 var mySelect = document.getElementById('mySelect'),
    newOption = document.createElement('option');

newOption.value = 'bmw';

// Not all browsers support textContent (W3C-compliant)
// When available, textContent is faster (see http://stackoverflow.com/a/1359822/139010)
if (typeof newOption.textContent === 'undefined')
{
    newOption.innerText = 'BMW';
}
else
{
    newOption.textContent = 'BMW';
}

mySelect.appendChild(newOption);

Demo →

What is a regular expression for a MAC Address?

for PHP developer

filter_var($value, FILTER_VALIDATE_MAC)

How to apply !important using .css()?

I would assume you tried it without adding !important?

Inline CSS (which is how JavaScript adds styling) overrides the stylesheet CSS. I'm pretty sure that's the case even when the stylesheet CSS rule has !important.

Another question (maybe a stupid question but must be asked.): Is the element you are trying to work on display:block; or display:inline-block;?

Not knowing your expertise in CSS... inline elements don't always behave as you would expect.

Validate SSL certificates with Python

I was having the same problem but wanted to minimize 3rd party dependencies (because this one-off script was to be executed by many users). My solution was to wrap a curl call and make sure that the exit code was 0. Worked like a charm.

How to hide the Google Invisible reCAPTCHA badge

Recaptcha contact form 7 and Recaptcha v3 solution.

body:not(.page-id-20) .grecaptcha-badge {
    display: none;
}

More Than One Contact Form Page?

body:not(.page-id-12):not(.page-id-43) .grecaptcha-badge {
    display: none;
}

You can add more “nots” if you have more contact form pages.

body:not(.page-id-45):not(.page-id-78):not(.page-id-98) .grecaptcha-badge {
    display: none;
}

Make sure that your body section will like this:

<body>

Change it so that it looks like this:

 <body <?php body_class(); ?>>

Modifying a file inside a jar

Yes you can, using SQLite you can read from or write to a database from within the jar file, so that you won't have to extract and then re jar it, follow my post http://shoaibinamdar.in/blog/?p=313

using the syntax "jdbc:sqlite::resource:" you would be able to read and write to a database from within the jar file

Print empty line?

Python 2.x: Prints a newline

print      

Python 3.x: You must call the function

print() 

Source: https://docs.python.org/3.0/whatsnew/3.0.html

Is it a good practice to use an empty URL for a HTML form's action attribute? (action="")

I think it's best to explicitly state where the form posts. If you want to be totally safe, enter the same URL the form is on in the action attribute if you want it to submit back to itself. Although mainstream browsers evaluate "" to the same page, you can't guarantee that non-mainstream browsers will.

And of course, the entire URL including GET data like Juddling points out.

How to convert text column to datetime in SQL

In SQL Server , cast text as datetime

select cast('5/21/2013 9:45:48' as datetime)

How to add new activity to existing project in Android Studio?

I think natually do it is straightforward, whether Intellij IDEA or Android Studio, I always click new Java class menu, and then typing the class name, press Enter to create. after that, I manually typing "extends Activity" in the class file, and then import the class by shortcut key. finally, I also manually override the onCreate() method and invoke the setContentView() method.

How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time?

Liam's link looks great, but also check out pandas.Timedelta - looks like it plays nicely with NumPy's and Python's time deltas.

https://pandas.pydata.org/pandas-docs/stable/timedeltas.html

pd.date_range('2014-01-01', periods=10) + pd.Timedelta(days=1)

Is it possible to disable scrolling on a ViewPager

How about this :
I used CustomViewPager
and next, override scrollTo method
I checked the movement when doing a lot of small swipes, it doesn't scroll to other pages.

public class CustomViewPager extends ViewPager {

    private boolean enabled;

    public CustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.enabled = true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (this.enabled) {
            return super.onTouchEvent(event);
        }

        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        if (this.enabled) {
            return super.onInterceptTouchEvent(event);
        }

        return false;
    }

    public void setPagingEnabled(boolean enabled) {
        this.enabled = enabled;
    } 

    @Override
    public void scrollTo(int x, int y) {
       if(enabled) {
          super.scrollTo(x, y);
       }
    }
}

Loading context in Spring using web.xml

You can also specify context location relatively to current classpath, which may be preferable

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:applicationContext*.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

How to remove all click event handlers using jQuery?

Is there a way to remove all previous click events that have been assigned to a button?

$('#saveBtn').unbind('click').click(function(){saveQuestion(id)});

How to set UICollectionViewCell Width and Height programmatically

Use this method to set custom cell height width.

Make sure to add this protocols

UICollectionViewDelegate

UICollectionViewDataSource

UICollectionViewDelegateFlowLayout

If you are using swift 5 or xcode 11 and later you need to set Estimate Size to none using storyboard in order to make it work properly. If you will not set that than below code will not work as expected.

enter image description here

Swift 4 or Later

extension YourViewController: UICollectionViewDelegate {
    //Write Delegate Code Here
}

extension YourViewController: UICollectionViewDataSource {
    //Write DataSource Code Here
}

extension YourViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: screenWidth, height: screenWidth)
    }
}

Objective-C

@interface YourViewController : UIViewController<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(CGRectGetWidth(collectionView.frame), (CGRectGetHeight(collectionView.frame)));
}

SQLite "INSERT OR REPLACE INTO" vs. "UPDATE ... WHERE"

UPDATE will not do anything if the row does not exist.

Where as the INSERT OR REPLACE would insert if the row does not exist, or replace the values if it does.

header location not working in my php code

It took me some time to figure this out: My php-file was encoded in UTF-8. And the BOM prevented header location to work properly. In Notepad++ I set the file encoding to "UTF-8 without BOM" and the problem was gone.

How to find the minimum value in an ArrayList, along with the index number? (Java)

You have to traverse the whole array and keep two auxiliary values:

  • The minimum value you find (on your way towards the end)
  • The index of the place where you found the min value

Suppose your array is called myArray. At the end of this code minIndex has the index of the smallest value.

var min = Number.MAX_VALUE; //the largest number possible in JavaScript
var minIndex = -1;

for (int i=0; i<myArray.length; i++){
   if (myArray[i] < min){
      min = myArray[i];
      minIndex = i;
   }
}

This is assuming the worst case scenario: a totally random array. It is an O(n) algorithm or order n algorithm, meaning that if you have n elements in your array, then you have to look at all of them before knowing your answer. O(n) algorithms are the worst ones because they take a lot of time to solve the problem.

If your array is sorted or has any other specific structure, then the algorithm can be optimized to be faster.

Having said that, though, unless you have a huge array of thousands of values then don't worry about optimization since the difference between an O(n) algorithm and a faster one would not be noticeable.

How to check python anaconda version installed on Windows 10 PC?

If you want to check the python version in a particular cond environment you can also use conda list python

Selenium -- How to wait until page is completely loaded

3 answers, which you can combine:

  1. Set implicit wait immediately after creating the web driver instance:

    _ = driver.Manage().Timeouts().ImplicitWait;

    This will try to wait until the page is fully loaded on every page navigation or page reload.

  2. After page navigation, call JavaScript return document.readyState until "complete" is returned. The web driver instance can serve as JavaScript executor. Sample code:

    C#

    new WebDriverWait(driver, MyDefaultTimeout).Until(
    d => ((IJavaScriptExecutor) d).ExecuteScript("return document.readyState").Equals("complete"));
    

    Java

    new WebDriverWait(firefoxDriver, pageLoadTimeout).until(
          webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));
    
  3. Check if the URL matches the pattern you expect.

Concatenating Files And Insert New Line In Between Files

If you have few enough files that you can list each one, then you can use process substitution in Bash, inserting a newline between each pair of files:

cat File1.txt <(echo) File2.txt <(echo) File3.txt > finalfile.txt

MySQL load NULL values from CSV data

show variables

Show variables like "`secure_file_priv`";

Note: keep your csv file in location given by the above command.

create table assessments (course_code varchar(5),batch_code varchar(7),id_assessment int, assessment_type varchar(10), date int , weight int);

Note: here the 'date' column has some blank values in the csv file.

LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/assessments.csv' 
INTO TABLE assessments
FIELDS TERMINATED BY ',' 
OPTIONALLY ENCLOSED BY '' 
LINES TERMINATED BY '\n' 
IGNORE 1 ROWS 
(course_code,batch_code,id_assessment,assessment_type,@date,weight)
SET date = IF(@date = '', NULL, @date);

How can I open a .db file generated by eclipse(android) form DDMS-->File explorer-->data--->data-->packagename-->database?

If I Understood correctly you need to view the .db file that you extracted from internal storage of Emulator. If that's the case use this

http://sourceforge.net/projects/sqlitebrowser/

to view the db.

You can also use a firefox extension

https://addons.mozilla.org/en-us/firefox/addon/sqlite-manager/

EDIT: For online tool use : https://sqliteonline.com/

Process escape sequences in a string in Python

The (currently) accepted answer by Jerub is correct for python2, but incorrect and may produce garbled results (as Apalala points out in a comment to that solution), for python3. That's because the unicode_escape codec requires its source to be coded in latin-1, not utf-8, as per the official python docs. Hence, in python3 use:

>>> myString="špåm\\nëðþ\\x73"
>>> print(myString)
špåm\nëðþ\x73
>>> decoded_string = myString.encode('latin-1','backslashreplace').decode('unicode_escape')
>>> print(decoded_string)
špåm
ëðþs

This method also avoids the extra unnecessary roundtrip between strings and bytes in metatoaster's comments to Jerub's solution (but hats off to metatoaster for recognizing the bug in that solution).

Update UI from Thread in Android

The most simplest solution I have seen to supply a short execution to the UI thread is via the post() method of a view. This is needed since UI methods are not re-entrant. The method for this is:

package android.view;

public class View;

public boolean post(Runnable action);

The post() method corresponds to the SwingUtilities.invokeLater(). Unfortunately I didn't find something simple that corresponds to the SwingUtilities.invokeAndWait(), but one can build the later based on the former with a monitor and a flag.

So what you save by this is creating a handler. You simply need to find your view and then post on it. You can find your view via findViewById() if you tend to work with id-ed resources. The resulting code is very simple:

/* inside your non-UI thread */

view.post(new Runnable() {
        public void run() {
            /* the desired UI update */
        }
    });
}

Note: Compared to SwingUtilities.invokeLater() the method View.post() does return a boolean, indicating whether the view has an associated event queue. Since I used the invokeLater() resp. post() anyway only for fire and forget, I did not check the result value. Basically you should call post() only after onAttachedToWindow() has been called on the view.

Best Regards

How to create an android app using HTML 5

Here is a starting point for developing Android apps with HTML5. The HTML code will be stored in the "assets/www" folder in your Android project.

https://github.com/jakewp11/HTML5_Android_Template.git

TypeError: unsupported operand type(s) for -: 'str' and 'int'

  1. The reason this is failing is because (Python 3) input returns a string. To convert it to an integer, use int(some_string).

  2. You do not typically keep track of indices manually in Python. A better way to implement such a function would be

    def cat_n_times(s, n):
        for i in range(n):
            print(s) 
    
    text = input("What would you like the computer to repeat back to you: ")
    num = int(input("How many times: ")) # Convert to an int immediately.
    
    cat_n_times(text, num)
    
  3. I changed your API above a bit. It seems to me that n should be the number of times and s should be the string.

Get the string representation of a DOM node

Use element.outerHTML to get full representation of element, including outer tags and attributes.

"Object doesn't support property or method 'find'" in IE

Here is a work around. You can use filter instead of find; but filter returns an array of matching objects. find only returns the first match inside an array. So, why not use filter as following;

data.filter(function (x) {
         return x.Id === e
    })[0];

ArrayList or List declaration in Java

The difference is that variant 1 forces you to use an ArrayList while variant 2 only guarantees you have anything that implements List<String>.

Later on you could change that to List<String> arrayList = new LinkedList<String>(); without much hassle. Variant 1 might require you to change not only that line but other parts as well if they rely on working with an ArrayList<String>.

Thus I'd use List<String> in almost any case, except when I'd need to call the additional methods that ArrayList provides (which was never the case so far): ensureCapacity(int) and trimToSize().

Java heap terminology: young, old and permanent generations?

The Heap is divided into young and old generations as follows :

Young Generation : It is place where lived for short period and divided into two spaces:

  • Eden Space : When object created using new keyword memory allocated on this space.
  • Survivor Space : This is the pool which contains objects which have survived after java garbage collection from Eden space.

Old Generation : This pool basically contains tenured and virtual (reserved) space and will be holding those objects which survived after garbage collection from Young Generation.

  • Tenured Space: This memory pool contains objects which survived after multiple garbage collection means object which survived after garbage collection from Survivor space.

Permanent Generation : This memory pool as name also says contain permanent class metadata and descriptors information so PermGen space always reserved for classes and those that is tied to the classes for example static members.

Java8 Update: PermGen is replaced with Metaspace which is very similar.
Main difference is that Metaspace re-sizes dynamically i.e., It can expand at runtime.
Java Metaspace space: unbounded (default)

Code Cache (Virtual or reserved) : If you are using HotSpot Java VM this includes code cache area that containing memory which will be used for compilation and storage of native code.

enter image description here

Courtesy

How to add files/folders to .gitignore in IntelliJ IDEA?

I'm using intelliJ 15 community edition and I'm able to right click a file and select 'add to .gitignore'

JDK on OSX 10.7 Lion

You can download jdk6 here http://support.apple.com/kb/DL1573

Wish it helps

How to extract a single value from JSON response?

Extract single value from JSON response Python

Try this

import json
import sys

#load the data into an element
data={"test1" : "1", "test2" : "2", "test3" : "3"}

#dumps the json object into an element
json_str = json.dumps(data)

#load the json to a string
resp = json.loads(json_str)

#print the resp
print (resp)

#extract an element in the response
print (resp['test1'])

How do I remove a single breakpoint with GDB?

You can delete all breakpoints using

del <start_breakpoint_num> - <end_breakpoint_num>

To view the start_breakpoint_num and end_breakpoint_num use:

info break

How to read a file into a variable in shell?

As Ciro Santilli notes using command substitutions will drop trailing newlines. Their workaround adding trailing characters is great, but after using it for quite some time I decided I needed a solution that didn't use command substitution at all.

My approach now uses read along with the printf builtin's -v flag in order to read the contents of stdin directly into a variable.

# Reads stdin into a variable, accounting for trailing newlines. Avoids
# needing a subshell or command substitution.
# Note that NUL bytes are still unsupported, as Bash variables don't allow NULs.
# See https://stackoverflow.com/a/22607352/113632
read_input() {
  # Use unusual variable names to avoid colliding with a variable name
  # the user might pass in (notably "contents")
  : "${1:?Must provide a variable to read into}"
  if [[ "$1" == '_line' || "$1" == '_contents' ]]; then
    echo "Cannot store contents to $1, use a different name." >&2
    return 1
  fi

  local _line _contents=()
   while IFS='' read -r _line; do
     _contents+=("$_line"$'\n')
   done
   # include $_line once more to capture any content after the last newline
   printf -v "$1" '%s' "${_contents[@]}" "$_line"
}

This supports inputs with or without trailing newlines.

Example usage:

$ read_input file_contents < /tmp/file
# $file_contents now contains the contents of /tmp/file

jQuery append() and remove() element

You can call a reset function before appending. Something like this:

    function resetNewReviewBoardForm() {
    $("#Description").val('');
    $("#PersonName").text('');
    $("#members").empty(); //this one what worked in my case
    $("#EmailNotification").val('False');
}

How to find the location of the Scheduled Tasks folder

For Windows 7 and up, scheduled tasks are not run by cmd.exe, but rather by MMC (Microsoft Management Console). %SystemRoot%\Tasks should work on any other Windows version though.

Rails: Missing host to link to! Please provide :host parameter or set default_url_options[:host]

You need to add the following line at every environment:

config.action_mailer.default_url_options = { :host => "yourhost" }

That way, it can work in all environments and could be different from environment to environment. For example:

development.rb

config.action_mailer.default_url_options = { :host => "dev.yourhost.com" }

test.rb

config.action_mailer.default_url_options = { :host => "test.yourhost.com" }

production.rb

config.action_mailer.default_url_options = { :host => "www.yourhost.com" }

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

This post is high up when you google that error message, which I got when installing security patch KB4505224 on SQL Server 2017 Express i.e. None of the above worked for me, but did consume several hours trying.

The solution for me, partly from here was:

  1. uninstall SQL Server
  2. in Regional Settings / Management / System Locale, "Beta: UTF-8 support" should be OFF
  3. re-install SQL Server
  4. Let Windows install the patch.

And all was well.

More on this here.

Refreshing all the pivot tables in my excel workbook with a macro

In certain circumstances you might want to differentiate between a PivotTable and its PivotCache. The Cache has it's own refresh method and its own collections. So we could have refreshed all the PivotCaches instead of the PivotTables.

The difference? When you create a new Pivot Table you are asked if you want it based on a previous table. If you say no, this Pivot Table gets its own cache and doubles the size of the source data. If you say yes, you keep your WorkBook small, but you add to a collection of Pivot Tables that share a single cache. The entire collection gets refreshed when you refresh any single Pivot Table in that collection. You can imagine therefore what the difference might be between refreshing every cache in the WorkBook, compared to refreshing every Pivot Table in the WorkBook.

How to update a git clone --mirror?

Regarding commits, refs, branches and "et cetera", Magnus answer just works (git remote update).

But unfortunately there is no way to clone / mirror / update the hooks, as I wanted...

I have found this very interesting thread about cloning/mirroring the hooks:

http://kerneltrap.org/mailarchive/git/2007/8/28/256180/thread

I learned:

  • The hooks are not considered part of the repository contents.

  • There is more data, like the .git/description folder, which does not get cloned, just as the hooks.

  • The default hooks that appear in the hooks dir comes from the TEMPLATE_DIR

  • There is this interesting template feature on git.

So, I may either ignore this "clone the hooks thing", or go for a rsync strategy, given the purposes of my mirror (backup + source for other clones, only).

Well... I will just forget about hooks cloning, and stick to the git remote update way.

  • Sehe has just pointed out that not only "hooks" aren't managed by the clone / update process, but also stashes, rerere, etc... So, for a strict backup, rsync or equivalent would really be the way to go. As this is not really necessary in my case (I can afford not having hooks, stashes, and so on), like I said, I will stick to the remote update.

Thanks! Improved a bit of my own "git-fu"... :-)

Print all day-dates between two dates

I came up with this:

from datetime import date, timedelta

sdate = date(2008, 8, 15)   # start date
edate = date(2008, 9, 15)   # end date

delta = edate - sdate       # as timedelta

for i in range(delta.days + 1):
    day = sdate + timedelta(days=i)
    print(day)

The output:

2008-08-15
2008-08-16
...
2008-09-13
2008-09-14
2008-09-15

Your question asks for dates in-between but I believe you meant including the start and end points, so they are included. To remove the end date, delete the "+ 1" at the end of the range function. To remove the start date, insert a 1 argument to the beginning of the range function.

What is the difference between Html.Hidden and Html.HiddenFor

Every method in HtmlHelper class has a twin with For suffix. Html.Hidden takes a string as an argument that you must provide but Html.HiddenFor takes an Expression that if you view is a strongly typed view you can benefit from this and feed that method a lambda expression like this

o=>o.SomeProperty 

instead of "SomeProperty" in the case of using Html.Hidden method.

Display only 10 characters of a long string?

var example = "I am too long string";
var result;

// Slice is JS function
result = example.slice(0, 10)+'...'; //if you need dots after the string you can add

Result variable contains "I am too l..."

dyld: Library not loaded ... Reason: Image not found

If you're using Xcode 11 onwards:

Go to General tab and add the framework in Frameworks, Libraries, and Embedded Content section.

Important: By default it might be marked as Do Not Embed, change it to Embed Without Signing like shown in the image and you are good to go.

enter image description here

For Xcode versions below 11:

Just add the framework in Embedded Binaries section and you are done.

Cheers!

SQL: How to get the id of values I just INSERTed?

sql = "INSERT INTO MyTable (Name) VALUES (@Name);" +
      "SELECT CAST(scope_identity() AS int)";
SqlCommand cmd = new SqlCommand(sql, conn);
int newId = (int)cmd.ExecuteScalar();

How to use PDO to fetch results array in PHP?

$st = $data->prepare("SELECT * FROM exampleWHERE example LIKE :search LIMIT 10"); 

convert strtotime to date time format in php

$unixtime = 1307595105;
echo $time = date("m/d/Y h:i:s A T",$unixtime);

Where

http://php.net/manual/en/function.date.php

How to switch from the default ConstraintLayout to RelativeLayout in Android Studio

Android 3.0

In activity_main.xml

Replace in this tag i.e <android.support.constraint.ConstraintLayout>

android.support.constraint.ConstraintLayout

with

RelativeLayout

Npm install failed with "cannot run in wd"

I have experienced the same problem when trying to publish my nodejs app in a private server running CentOs using root user. The same error is fired by "postinstall": "./node_modules/bower/bin/bower install" in my package.json file so the only solution that was working for me is to use both options to avoid the error:

1: use --allow-root option for bower install command

"postinstall": "./node_modules/bower/bin/bower --allow-root install"

2: use --unsafe-perm option for npm install command

npm install --unsafe-perm

Getting Cannot read property 'offsetWidth' of undefined with bootstrap carousel script

I got same error. Because i used v4 alpha class names like carousel-control-next When i changed with v3, problem solved.

How to compare two Carbon Timestamps?

Carbon has a bunch of comparison functions with mnemonic names:

  • equalTo()
  • notEqualTo()
  • greaterThan()
  • greaterThanOrEqualTo()
  • lessThan()
  • lessThanOrEqualTo()

Usage:

 if($model->edited_at->greaterThan($model->created_at)){
     // edited at is newer than created at
 }

Valid for nesbot/carbon 1.36.2

if you are not sure what Carbon version you are on, run this

$composer show "nesbot/carbon"

documentation: https://carbon.nesbot.com/docs/#api-comparison

How to handle change of checkbox using jQuery?

$("input[type=checkbox]").on("change", function() { 

    if (this.checked) {

      //do your stuff

     }
});

Is the sizeof(some pointer) always equal to four?

In addition to the 16/32/64 bit differences even odder things can occur.

There have been machines where sizeof(int *) will be one value, probably 4 but where sizeof(char *) is larger. Machines that naturally address words instead of bytes have to "augment" character pointers to specify what portion of the word you really want in order to properly implement the C/C++ standard.

This is now very unusual as hardware designers have learned the value of byte addressability.

Could not complete the operation due to error 80020101. IE

Switch off compatibility view if you use IE9.

Increment a value in Postgres

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill';

If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill'
  AND total = 203;

Proper way to catch exception from JSON.parse

This promise will not resolve if the argument of JSON.parse() can not be parsed into a JSON object.

Promise.resolve(JSON.parse('{"key":"value"}')).then(json => {
    console.log(json);
}).catch(err => {
    console.log(err);
});

How to Merge Two Eloquent Collections?

The merge method returns the merged collection, it doesn't mutate the original collection, thus you need to do the following

$original = new Collection(['foo']);

$latest = new Collection(['bar']);

$merged = $original->merge($latest); // Contains foo and bar.

Applying the example to your code

$related = new Collection();

foreach ($question->tags as $tag)
{
    $related = $related->merge($tag->questions);
}

Python DNS module import error

I solved this by uninstalling and then re-installing the dnspython module with PIP.

$ pip uninstall dnspython

After the long list of files within pycache, type y to continue with the uninstall. After complete type:

$ pip install dnspython

I then ran my script and the errors were resolved.

PHP: HTML: send HTML select option attribute in POST

just combine the value and the stud_name e.g. 1_sre and split the value when get it into php. Javascript seems like hammer to crack a nut. N.B. this method assumes you can edit the the html. Here is what the html might look like:

<form name='add'>
Age: <select name='age'>
     <option value='1_sre'>23</option>
     <option value='2_sam>24</option>
     <option value='5_john>25</option>
     </select>
<input type='submit' name='submit'/>
</form>

What is the &#xA; character?

It is the equivalent to \n -> LF (Line Feed).

Sometimes it is used in HTML and JavaScript. Otherwise in .NET environments, use Environment.NewLine.

Only allow specific characters in textbox

You can probably use the KeyDown event, KeyPress event or KeyUp event. I would first try the KeyDown event I think.

You can set the Handled property of the event args to stop handling the event.

Does not contain a definition for and no extension method accepting a first argument of type could be found

There are two cases in which this error is raised.

  1. You didn't declare the variable which is used
  2. You didn't create the instances of the class

Call a Vue.js component method from outside the component

This is a simple way to access a component's methods from other component

// This is external shared (reusable) component, so you can call its methods from other components

export default {
   name: 'SharedBase',
   methods: {
      fetchLocalData: function(module, page){
          // .....fetches some data
          return { jsonData }
      }
   }
}

// This is your component where you can call SharedBased component's method(s)
import SharedBase from '[your path to component]';
var sections = [];

export default {
   name: 'History',
   created: function(){
       this.sections = SharedBase.methods['fetchLocalData']('intro', 'history');
   }
}

Modify XML existing content in C#

Using LINQ to xml if you are using framework 3.5

using System.Xml.Linq;

XDocument xmlFile = XDocument.Load("books.xml"); 
var query = from c in xmlFile.Elements("catalog").Elements("book")    
            select c; 
foreach (XElement book in query) 
{
    book.Attribute("attr1").Value = "MyNewValue";
}
xmlFile.Save("books.xml");

ALTER DATABASE failed because a lock could not be placed on database

I know this is an old post but I recently ran into a very similar problem. Unfortunately I wasn't able to use any of the alter database commands because an exclusive lock couldn't be placed. But I was never able to find an open connection to the db. I eventually had to forcefully delete the health state of the database to force it into a restoring state instead of in recovery.

Jackson and generic type reference

'JavaType' works !! I was trying to unmarshall (deserialize) a List in json String to ArrayList java Objects and was struggling to find a solution since days.
Below is the code that finally gave me solution. Code:

JsonMarshallerUnmarshaller<T> {
    T targetClass;

    public ArrayList<T> unmarshal(String jsonString) {
        ObjectMapper mapper = new ObjectMapper();

        AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();
        mapper.getDeserializationConfig()
            .withAnnotationIntrospector(introspector);

        mapper.getSerializationConfig()
            .withAnnotationIntrospector(introspector);
        JavaType type = mapper.getTypeFactory().
            constructCollectionType(
                ArrayList.class, 
                targetclass.getClass());

        try {
            Class c1 = this.targetclass.getClass();
            Class c2 = this.targetclass1.getClass();
            ArrayList<T> temp = (ArrayList<T>) 
                mapper.readValue(jsonString,  type);
            return temp ;
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null ;
    }  
}

How Should I Set Default Python Version In Windows?

Nothing above worked, this is what worked for me:

ftype Python.File=C:\Path\to\python.exe "%1" %*

This command should be run in Command prompt launched as administrator

Warning: even if the path in this command is set to python35, if you have python36 installed it's going to set the default to python36. To prevent this, you can temporarily change the folder name from Python36 to xxPython36, run the command and then remove the change to the Python 36 folder.

How to run Conda?

The main point is that as of December 2018 it's Scripts not bin.


Updating $PATH in "git bash for windows"

Use one of these:
export PATH=$USERPROFILE/AppData/Local/Continuum/anaconda2/Scripts/:$PATH
export PATH=$USERPROFILE/AppData/Local/Continuum/anaconda3/Scripts/:$PATH


Updating $PATH in the windows default command line

Use one of these:
SET PATH=%USERPROFILE%\AppData\Local\Continuum\anaconda2\Scripts\;%PATH%
SET PATH=%USERPROFILE%\AppData\Local\Continuum\anaconda3\Scripts\;%PATH%


Updating $PATH in Linux

Change /app to your installation location. If you installed anaconda change Miniconda to Anaconda. Also, check for Script vs. bin,.

export PATH="/app/Miniconda/bin:$PATH"

You may need to run set -a before setting the path, I think this is important if you're setting the path in a script. For example if you have your export command in a file called set_my_path.sh, I think you'd need to do set -a; source("set_my_path.sh").

The set -a will make your changes to the path persist for your session, but they are still not permanent.

For a more permanent solution add the command to ~/.bashrc. The installers may offer to add something like this to your ~/.bashrc file, but you can do it too (or comment it out to undo it).


General Observations:

Background: I installed the 64 bit versions of Anaconda 2 and 3 recently on my Windows 10 machine following the recommended installation steps in December of 2018.

  • Adding conda also enables ipython, which works much better in the native Windows command line
  • Following the strongly recommended installation does not add conda or ipython to the path
  • Anaconda 3 doesn't seem to install a command prompt application, but Anaconda 2 did have a command prompt application
  • The /bin folder seems to have been replaced with Scripts
  • Poking around in the Scripts folder is interesting, maybe the Anaconda command prompt application is in there somewhere.

How to make execution pause, sleep, wait for X seconds in R?

See help(Sys.sleep).

For example, from ?Sys.sleep

testit <- function(x)
{
    p1 <- proc.time()
    Sys.sleep(x)
    proc.time() - p1 # The cpu usage should be negligible
}
testit(3.7)

Yielding

> testit(3.7)
   user  system elapsed 
  0.000   0.000   3.704 

How do I read / convert an InputStream into a String in Java?

Here is the complete method for converting InputStream into String without using any third party library. Use StringBuilder for single threaded environment otherwise use StringBuffer.

public static String getString( InputStream is) throws IOException {
    int ch;
    StringBuilder sb = new StringBuilder();
    while((ch = is.read()) != -1)
        sb.append((char)ch);
    return sb.toString();
}

if condition in sql server update query

DECLARE @JCnt int=null
SEt @JCnt=(SELECT COUNT( ISNUll(EmpCode,0)) FROM tbl_Employees WHERE EmpCode=1  )

UPDATE #TempCode
SET janCA= CASE WHEN @JCnt>0 THEN (SELECT SUM (ISNUll(Amount,0)) FROM tbl_Salary WHERE Code=1 )ELSE 0 END
WHERE code=1

How can I get onclick event on webview in android?

Hamidreza's solution almost worked for me.

I noticed from experimentation that a simple tap usually has 2-5 action move events. Checking the time between action down and up was simpler and behaved more like what I expected.

private class CheckForClickTouchLister implements View.OnTouchListener {
    private final static long MAX_TOUCH_DURATION = 100;

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:
                m_DownTime = event.getEventTime(); //init time

                break;

            case MotionEvent.ACTION_UP:
                if(event.getEventTime() - m_DownTime <= MAX_TOUCH_DURATION)
                    //On click action

                break;

            default:
                break; //No-Op

        }
        return false;
    }

Sites not accepting wget user agent header

It seems Yahoo server does some heuristic based on User-Agent in a case Accept header is set to */*.

Accept: text/html

did the trick for me.

e.g.

wget  --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0"  http://yahoo.com

Note: if you don't declare Accept header then wget automatically adds Accept:*/* which means give me anything you have.

How to increment a datetime by one day?

Most Simplest solution

from datetime import timedelta, datetime
date = datetime(2003,8,1,12,4,5)
for i in range(5):
    date += timedelta(days=1)
    print(date)

Best way to simulate "group by" from bash?

I'd have done it like this:

perl -e 'while (<>) {chop; $h{$_}++;} for $k (keys %h) {print "$k $h{$k}\n";}' ip_addresses

but uniq might work for you.

How can I remove the top and right axis in matplotlib?

If you don't need ticks and such (e.g. for plotting qualitative illustrations) you could also use this quick workaround:

Make the axis invisible (e.g. with plt.gca().axison = False) and then draw them manually with plt.arrow.

How to abort a Task like aborting a Thread (Thread.Abort method)?

You can "abort" a task by running it on a thread you control and aborting that thread. This causes the task to complete in a faulted state with a ThreadAbortException. You can control thread creation with a custom task scheduler, as described in this answer. Note that the caveat about aborting a thread applies.

(If you don't ensure the task is created on its own thread, aborting it would abort either a thread-pool thread or the thread initiating the task, neither of which you typically want to do.)

How can I reduce the waiting (ttfb) time

The TTFB is not the time to first byte of the body of the response (i.e., the useful data, such as: json, xml, etc.), but rather the time to first byte of the response received from the server. This byte is the start of the response headers.

For example, if the server sends the headers before doing the hard work (like heavy SQL), you will get a very low TTFB, but it isn't "true".

In your case, TTFB represents the time you spend processing data on the server.

To reduce the TTFB, you need to do the server-side work faster.

DTO and DAO concepts and MVC

DTO is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.

  • DTO should only contain private fields for your data, getters, setters, and constructors.
  • DTO is not recommended to add business logic methods to such classes, but it is OK to add some util methods.

DAO is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).

Here is an example of how the DAO and DTO interfaces would look like:

interface PersonDTO {
    String getName();
    void setName(String name);
    //.....
}

interface PersonDAO {
    PersonDTO findById(long id);
    void save(PersonDTO person);
    //.....
}

The MVC is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.

As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.

Gradle does not find tools.jar

I had this problem when I was trying to run commands through CLI.

It was a problem with system looking at the JRE folder i.e. D:\Program Files\Java\jre8\bin. If we look in there, there is no Tools.jar, hence the error.

You need to find where the JDK is, in my case: D:\Program Files\Java\jdk1.8.0_11, and if you look in the lib directory, you will see Tools.jar.

What I did I created a new environment variable JAVA_HOME: enter image description here

And then you need to edit your PATH variable to include JAVA_HOME, i.e. %JAVA_HOME%/bin; enter image description here

Re-open command prompt and should run.

Spring profiles and testing

Can I recommend doing it this way, define your test like this:

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
    TestPreperationExecutionListener.class
    })
@Transactional
@ActiveProfiles(profiles = "localtest")
@ContextConfiguration
public class TestContext {

  @Test
  public void testContext(){

  }

  @Configuration
  @PropertySource("classpath:/myprops.properties")
  @ImportResource({"classpath:context.xml" })
  public static class MyContextConfiguration{

  }
}

with the following content in myprops.properties file:

spring.profiles.active=localtest

With this your second properties file should get resolved:

META-INF/spring/config_${spring.profiles.active}.properties

How to get the Power of some Integer in Swift language?

little detail more

   infix operator ^^ { associativity left precedence 160 }
   func ^^ (radix: Int, power: Int) -> Int {
       return Int(pow(CGFloat(radix), CGFloat(power)))
   }

swift - Binary Expressions

How to check if a file exists in Documents folder?

check if file exist in side the document/catchimage path :

NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *tempName = [NSString stringWithFormat:@"%@/catchimage/%@.png",stringPath,@"file name"];
NSLog(@"%@",temName);
if([[NSFileManager defaultManager] fileExistsAtPath:temName]){
    // ur code here
} else {
    // ur code here** 
}

Expected response code 220 but got code "", with message "" in Laravel

i was facing this problem and i checked all the answers and nothing worked for me, but then i reset mail.php and didn't touch it and set the mail server from .env file and it worked perfectly, hope this will save the time for someone :).

Parameter "stratify" from method "train_test_split" (scikit Learn)

For my future self who comes here via Google:

train_test_split is now in model_selection, hence:

from sklearn.model_selection import train_test_split

# given:
# features: xs
# ground truth: ys

x_train, x_test, y_train, y_test = train_test_split(xs, ys,
                                                    test_size=0.33,
                                                    random_state=0,
                                                    stratify=ys)

is the way to use it. Setting the random_state is desirable for reproducibility.

How to sort an associative array by its values in Javascript?

@commonpike's answer is "the right one", but as he goes on to comment...

most browsers nowadays just support Object.keys()

Yeah.. Object.keys() is WAY better.

But what's even better? Duh, it's it in coffeescript!

sortedKeys = (x) -> Object.keys(x).sort (a,b) -> x[a] - x[b]

sortedKeys
  'a' :  1
  'b' :  3
  'c' :  4
  'd' : -1

[ 'd', 'a', 'b', 'c' ]

How to convert an array to object in PHP?

use this function that i've made:

function buildObject($class,$data){
    $object = new $class;
    foreach($data as $key=>$value){
        if(property_exists($class,$key)){
            $object->{'set'.ucfirst($key)}($value);
        }
    }
    return $object;
}

Usage:

$myObject = buildObject('MyClassName',$myArray);

Passing an array of parameters to a stored procedure

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

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

Java 8 Lambda function that throws exception?

This problem has been bothering me as well; this is why I have created this project.

With it you can do:

final ThrowingFunction<String, Integer> f = yourMethodReferenceHere;

There are a totla of 39 interfaces defined by the JDK which have such a Throwing equivalent; those are all @FunctionalInterfaces used in streams (the base Stream but also IntStream, LongStream and DoubleStream).

And as each of them extend their non throwing counterpart, you can directly use them in lambdas as well:

myStringStream.map(f) // <-- works

The default behavior is that when your throwing lambda throws a checked exception, a ThrownByLambdaException is thrown with the checked exception as the cause. You can therefore capture that and get the cause.

Other features are available as well.

What is the best way to generate a unique and short file name in Java

Look at the File javadoc, the method createNewFile will create the file only if it doesn't exist, and will return a boolean to say if the file was created.

You may also use the exists() method:

int i = 0;
String filename = Integer.toString(i);
File f = new File(filename);
while (f.exists()) {
    i++;
    filename = Integer.toString(i);
    f = new File(filename);
}
f.createNewFile();
System.out.println("File in use: " + f);

Read binary file as string in Ruby

If you need binary mode, you'll need to do it the hard way:

s = File.open(filename, 'rb') { |f| f.read }

If not, shorter and sweeter is:

s = IO.read(filename)

python multithreading wait till all threads finished

Put the threads in a list and then use the Join method

 threads = []

 t = Thread(...)
 threads.append(t)

 ...repeat as often as necessary...

 # Start all threads
 for x in threads:
     x.start()

 # Wait for all of them to finish
 for x in threads:
     x.join()

Split string with PowerShell and do something with each token

To complement Justus Thane's helpful answer:

  • As Joey notes in a comment, PowerShell has a powerful, regex-based -split operator.

    • In its unary form (-split '...'), -split behaves like awk's default field splitting, which means that:
      • Leading and trailing whitespace is ignored.
      • Any run of whitespace (e.g., multiple adjacent spaces) is treated as a single separator.
  • In PowerShell v4+ an expression-based - and therefore faster - alternative to the ForEach-Object cmdlet became available: the .ForEach() array (collection) method, as described in this blog post (alongside the .Where() method, a more powerful, expression-based alternative to Where-Object).

Here's a solution based on these features:

PS> (-split '   One      for the money   ').ForEach({ "token: [$_]" })
token: [One]
token: [for]
token: [the]
token: [money]

Note that the leading and trailing whitespace was ignored, and that the multiple spaces between One and for were treated as a single separator.

Creating a folder if it does not exists - "Item already exists"

I was not even concentrating, here is how to do it

$DOCDIR = [Environment]::GetFolderPath("MyDocuments")
$TARGETDIR = '$DOCDIR\MatchedLog'
if(!(Test-Path -Path $TARGETDIR )){
    New-Item -ItemType directory -Path $TARGETDIR
}

Which is preferred: Nullable<T>.HasValue or Nullable<T> != null?

If you use linq and want to keep your code short, I recommand to always use !=null

And this is why:

Let imagine we have some class Foo with a nullable double variable SomeDouble

public class Foo
{
    public double? SomeDouble;
    //some other properties
}   

If somewhere in our code we want to get all Foo with a non null SomeDouble values from a collection of Foo (assuming some foos in the collection can be null too), we end up with at least three way to write our function (if we use C# 6) :

public IEnumerable<Foo> GetNonNullFoosWithSomeDoubleValues(IEnumerable<Foo> foos)
{
     return foos.Where(foo => foo?.SomeDouble != null);
     return foos.Where(foo=>foo?.SomeDouble.HasValue); // compile time error
     return foos.Where(foo=>foo?.SomeDouble.HasValue == true); 
     return foos.Where(foo=>foo != null && foo.SomeDouble.HasValue); //if we don't use C#6
}

And in this kind of situation I recommand to always go for the shorter one

Getting SyntaxError for print with keyword argument end=' '

It looks like you're just missing an opening double-quote. Try:

if Verbose:
   print("Building internam Index for %d tile(s) ..." % len(inputTiles), end=' ')

GIT: Checkout to a specific folder

Use git archive branch-index | tar -x -C your-folder-on-PC to clone a branch to another folder. I think, then you can copy any file that you need

Angular ReactiveForms: Producing an array of checkbox values?

With the help of silentsod answer, I wrote a solution to get values instead of states in my formBuilder.

I use a method to add or remove values in the formArray. It may be a bad approch, but it works !

component.html

<div *ngFor="let choice of checks; let i=index" class="col-md-2">
  <label>
    <input type="checkbox" [value]="choice.value" (change)="onCheckChange($event)">
    {{choice.description}}
  </label>
</div>

component.ts

// For example, an array of choices
public checks: Array<ChoiceClass> = [
  {description: 'descr1', value: 'value1'},
  {description: "descr2", value: 'value2'},
  {description: "descr3", value: 'value3'}
];

initModelForm(): FormGroup{
  return this._fb.group({
    otherControls: [''],
    // The formArray, empty 
    myChoices: new FormArray([]),
  }
}

onCheckChange(event) {
  const formArray: FormArray = this.myForm.get('myChoices') as FormArray;

  /* Selected */
  if(event.target.checked){
    // Add a new control in the arrayForm
    formArray.push(new FormControl(event.target.value));
  }
  /* unselected */
  else{
    // find the unselected element
    let i: number = 0;

    formArray.controls.forEach((ctrl: FormControl) => {
      if(ctrl.value == event.target.value) {
        // Remove the unselected element from the arrayForm
        formArray.removeAt(i);
        return;
      }

      i++;
    });
  }
}

When I submit my form, for example my model looks like:

  otherControls : "foo",
  myChoices : ['value1', 'value2']

Only one thing is missing, a function to fill the formArray if your model already has checked values.

In which conda environment is Jupyter executing?

Because none of the answers above worked for me, I write here the solution that finally solved my problem on Ubuntu. My problem was:
I did the following steps:

  1. Activate my environment: conda activate MyEnv
  2. Start jupyter notebook:jupyter notebook

Although MyEnv was active in the terminal and had an asterix when writing conda env list, but jupyter notebook was started with the base environment. Installing nb_conda and ipykernel didn't solve the problem for me either. Additionally, the conda tab wasn't appearing in jupyter notebook and also clicking on the kernels or going to the menu Kernel->Change Kernel didn't show the kernel MyEnv.
Solution was: install the jupyter_environment_kernel in MyEnv environment:

pip install environment_kernels

After that when starting jupyter notebook, it is started with the right environment. You can also switch between environments without stopping the kernel, by going to the menu Kernel->Change Kernel and selecting the desired kernel.

How to write PNG image to string with the PIL?

sth's solution didn't work for me
because in ...

Imaging/PIL/Image.pyc line 1423 -> raise KeyError(ext) # unknown extension

It was trying to detect the format from the extension in the filename , which doesn't exist in StringIO case

You can bypass the format detection by setting the format yourself in a parameter

import StringIO
output = StringIO.StringIO()
format = 'PNG' # or 'JPEG' or whatever you want
image.save(output, format)
contents = output.getvalue()
output.close()

Regular expression to extract numbers from a string

we can use \b as a word boundary and then; \b\d+\b

TypeError: a bytes-like object is required, not 'str' in python and CSV

just change wb to w

outfile=open('./immates.csv','wb')

to

outfile=open('./immates.csv','w')

Log4j, configuring a Web App to use a relative path

My suggestion is the log file should always be logged above the root context of the webApp, so in case we redeploy the webApp, we don't want to override the existing log files.

How to disable phone number linking in Mobile Safari?

Add this, I think it is what you're looking for:

<meta name = "format-detection" content = "telephone=no">