Programs & Examples On #Non interactive

Passing arguments to an interactive program non-interactively

You can put the data in a file and re-direct it like this:

$ cat file.sh
#!/bin/bash

read x
read y
echo $x
echo $y

Data for the script:

$ cat data.txt
2
3

Executing the script:

$ file.sh < data.txt
2
3

In SSRS, why do I get the error "item with same key has already been added" , when I'm making a new report?

I face the same issue. After debug I fixed the same. if the column name in your sql query has multiple times then this issue occur. Hence use alias in sql query to differ the column name. Ex: The below query will work proper in sql query but create issue in SSRS report:

Select P.ID, P.FirstName, P.LastName, D.ID, D.City, D.Area, D.Address From PersonalDetails P Left Join CommunicationDetails D On P.ID = D.PersonalDetailsID

Reason : ID has mentioned twice (Multiple Times)

Correct Query:

Select P.ID As PersonalDetailsID, P.FirstName, P.LastName, D.ID, D.City, D.Area, D.Address From PersonalDetails P Left Join CommunicationDetails D On P.ID = D.PersonalDetailsID

What do raw.githubusercontent.com URLs represent?

The raw.githubusercontent.com domain is used to serve unprocessed versions of files stored in GitHub repositories. If you browse to a file on GitHub and then click the Raw link, that's where you'll go.

The URL in your question references the install file in the master branch of the Homebrew/install repository. The rest of that command just retrieves the file and runs ruby on its contents.

Using a Loop to add objects to a list(python)

Auto-incrementing the index in a loop:

myArr[(len(myArr)+1)]={"key":"val"}

Writing binary number system in C code

Use BOOST_BINARY (Yes, you can use it in C).

#include <boost/utility/binary.hpp>
...
int bin = BOOST_BINARY(110101);

This macro is expanded to an octal literal during preprocessing.

JAX-RS / Jersey how to customize error handling?

@QueryParam documentation says

" The type T of the annotated parameter, field or property must either:

1) Be a primitive type
2) Have a constructor that accepts a single String argument
3) Have a static method named valueOf or fromString that accepts a single String argument (see, for example, Integer.valueOf(String))
4) Have a registered implementation of javax.ws.rs.ext.ParamConverterProvider JAX-RS extension SPI that returns a javax.ws.rs.ext.ParamConverter instance capable of a "from string" conversion for the type.
5) Be List, Set or SortedSet, where T satisfies 2, 3 or 4 above. The resulting collection is read-only. "

If you want to control what response goes to user when query parameter in String form can't be converted to your type T, you can throw WebApplicationException. Dropwizard comes with following *Param classes you can use for your needs.

BooleanParam, DateTimeParam, IntParam, LongParam, LocalDateParam, NonEmptyStringParam, UUIDParam. See https://github.com/dropwizard/dropwizard/tree/master/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params

If you need Joda DateTime, just use Dropwizard DateTimeParam.

If the above list does not suit your needs, define your own by extending AbstractParam. Override parse method. If you need control over error response body, override error method.

Good article from Coda Hale on this is at http://codahale.com/what-makes-jersey-interesting-parameter-classes/

import io.dropwizard.jersey.params.AbstractParam;

import java.util.Date;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

public class DateParam extends AbstractParam<Date> {

    public DateParam(String input) {
        super(input);
    }

    @Override
    protected Date parse(String input) throws Exception {
        return new Date(input);
    }

    @Override
    protected Response error(String input, Exception e) {
        // customize response body if you like here by specifying entity
        return Response.status(Status.BAD_REQUEST).build();
    }
}

Date(String arg) constructor is deprecated. I would use Java 8 date classes if you are on Java 8. Otherwise joda date time is recommended.

PHP - Getting the index of a element from a array

You should use the key() function.

key($array)

should return the current key.

If you need the position of the current key:

array_search($key, array_keys($array));

Adding header for HttpURLConnection

Just cause I don't see this bit of information in the answers above, the reason the code snippet originally posted doesn't work correctly is because the encodedBytes variable is a byte[] and not a String value. If you pass the byte[] to a new String() as below, the code snippet works perfectly.

encodedBytes = Base64.encode(authorization.getBytes(), 0);
authorization = "Basic " + new String(encodedBytes);

Bootstrap get div to align in the center

When I align elements in center I use the bootstrap class text-center:

<div class="text-center">Centered content goes here</div>

how to convert integer to string?

NSArray *myArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3]];

Update for new Objective-C syntax:

NSArray *myArray = @[@1, @2, @3];

Those two declarations are identical from the compiler's perspective.

if you're just wanting to use an integer in a string for putting into a textbox or something:

int myInteger = 5;
NSString* myNewString = [NSString stringWithFormat:@"%i", myInteger];

Missing MVC template in Visual Studio 2015

Visual studio 2015 does not show MVC project template if you select .Net 4.0 or below. Select .Net 4.5 or above, and you will be able to see MVC project.

This is what showed when you select .NET Framework 4:

enter image description here

and this when you select .NET Framework 4.5:

enter image description here

However, make sure you have installed web developers tools. To do so, go to Add / remove programs -> Visual 2015 -> Modify --> Web developer tools : Check and proceed with the installation.

spark submit add multiple jars in classpath

Pass --jars with the path of jar files separated by , to spark-submit.

For reference:

--driver-class-path is used to mention "extra" jars to add to the "driver" of the spark job

--driver-library-path is used to "change" the default library path for the jars needed for the spark driver

--driver-class-path will only push the jars to the driver machine. If you want to send the jars to "executors", you need to use --jars

And to set the jars programatically set the following config: spark.yarn.dist.jars with comma-separated list of jars.

Eg:

from pyspark.sql import SparkSession

spark = SparkSession \
        .builder \
        .appName("Spark config example") \
        .config("spark.yarn.dist.jars", "<path-to-jar/test1.jar>,<path-to-jar/test2.jar>") \
        .getOrCreate()

How to loop and render elements in React-native?

render() {
  return (
    <View style={...}>
       {initialArr.map((prop, key) => {
         return (
           <Button style={{borderColor: prop[0]}}  key={key}>{prop[1]}</Button>
         );
      })}
     </View>
  )
}

should do the trick

Remove element by id

You can simply use

document.getElementById("elementID").outerHTML="";

It works in all browsers, even on Internet Explorer.

Reading *.wav files in Python

Here's a Python 3 solution using the built in wave module [1], that works for n channels, and 8,16,24... bits.

import sys
import wave

def read_wav(path):
    with wave.open(path, "rb") as wav:
        nchannels, sampwidth, framerate, nframes, _, _ = wav.getparams()
        print(wav.getparams(), "\nBits per sample =", sampwidth * 8)

        signed = sampwidth > 1  # 8 bit wavs are unsigned
        byteorder = sys.byteorder  # wave module uses sys.byteorder for bytes

        values = []  # e.g. for stereo, values[i] = [left_val, right_val]
        for _ in range(nframes):
            frame = wav.readframes(1)  # read next frame
            channel_vals = []  # mono has 1 channel, stereo 2, etc.
            for channel in range(nchannels):
                as_bytes = frame[channel * sampwidth: (channel + 1) * sampwidth]
                as_int = int.from_bytes(as_bytes, byteorder, signed=signed)
                channel_vals.append(as_int)
            values.append(channel_vals)

    return values, framerate

You can turn the result into a NumPy array.

import numpy as np

data, rate = read_wav(path)
data = np.array(data)

Note, I've tried to make it readable rather than fast. I found reading all the data at once was almost 2x faster. E.g.

with wave.open(path, "rb") as wav:
    nchannels, sampwidth, framerate, nframes, _, _ = wav.getparams()
    all_bytes = wav.readframes(-1)

framewidth = sampwidth * nchannels
frames = (all_bytes[i * framewidth: (i + 1) * framewidth]
            for i in range(nframes))

for frame in frames:
    ...

Although python-soundfile is roughly 2 orders of magnitude faster (hard to approach this speed with pure CPython).

[1] https://docs.python.org/3/library/wave.html

SSIS expression: convert date to string

For SSIS you could go with:

RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" +  (DT_STR, 4, 1252) DATEPART("yy" , GETDATE())

Expression builder screen:

Expression builder screen

android - How to get view from context?

first use this:

LayoutInflater inflater = (LayoutInflater) Read_file.this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

Read file is current activity in which you want your context.

View layout = inflater.inflate(R.layout.your_layout_name,(ViewGroup)findViewById(R.id.layout_name_id));

then you can use this to find any element in layout.

ImageView myImage = (ImageView) layout.findViewById(R.id.my_image);

Installing Java 7 on Ubuntu

flup's answer is the best but it did not work for me completely. I had to do the following as well to get it working:

  1. export JAVA_HOME=/usr/lib/jvm/java-7-oracle/jre/
  2. chmod 777 on the folder
  3. ./gradlew build - Building Hibernate

Appending pandas dataframes generated in a for loop

you can try this.

data_you_need=pd.DataFrame()
for infile in glob.glob("*.xlsx"):
    data = pandas.read_excel(infile)
    data_you_need=data_you_need.append(data,ignore_index=True)

I hope it can help.

ASP.Net MVC 4 Form with 2 submit buttons/actions

That's what we have in our applications:
Attribute

public class HttpParamActionAttribute : ActionNameSelectorAttribute
{
    public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
    {
        if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
            return true;

        var request = controllerContext.RequestContext.HttpContext.Request;
        return request[methodInfo.Name] != null;
    }
}

Actions decorated with it:


[HttpParamAction]
public ActionResult Save(MyModel model)
{
    // ...
}

[HttpParamAction]
public ActionResult Publish(MyModel model)
{
    // ...
}

HTML/Razor

@using (@Html.BeginForm())
{
    <!-- form content here -->
    <input type="submit" name="Save" value="Save" />
    <input type="submit" name="Publish" value="Publish" />
}

name attribute of submit button should match action/method name

This way you do not have to hard-code urls in javascript

How to pass an object from one activity to another on Android

I had always wondered why this can't be as simple as calling into a method of the other activity. I recently wrote a utility library that makes it almost as simple as that. You can check it out here(https://github.com/noxiouswinter/gnlib_android/wiki/gnlauncher).

GNLauncher makes sending objects/data to an Activity from another Activity etc as easy as calling a function in tha Activity with the required data as parameters. It introduces type safety and removes all the hastles of having to serialize, attaching to the intent using string keys and undoing the same at the other end.

Usage

Define an interface with the methods you want to call on the Activity to launch.

public interface IPayload {
    public void sayHello(String name, int age);
}

Implement the above interface on the Activity to launch into. Also notify GNLauncher when the activity is ready.

public class Activity_1 extends Activity implements IPayload {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Notify GNLauncher when the Activity is ready. 
        GNLauncher.get().ping(this);
    }

    @Override
    public void sayHello(String name, int age) {
        Log.d("gnlib_test", "Hello " + name + "! \nYour age is: " + age);
    }
}

In the other Activity, get a proxy to the above Activity and call any method with the desired parameters.

public class Activity_2 extends Activity {
    public void onClick(View v) {
        ((IPayload)GNLauncher.get().getProxy(this, IPayload.class, Activity_1.class)).sayHello(name, age);
    }
}

The first activity will be launched and the method called into with the required parameters.

Prerequisites

Please refer to https://github.com/noxiouswinter/gnlib_android/wiki#prerequisites for information on how to add the dependencies.

Error in installation a R package

After using the wrong quotation mark characters in install.packages(), correcting the quote marks yielded the "cannot remove prior installation" error. Closing and restarting R worked.

Extract subset of key-value pairs from Python dictionary object?

A bit shorter, at least:

wanted_keys = ['l', 'm', 'n'] # The keys you want
dict((k, bigdict[k]) for k in wanted_keys if k in bigdict)

Which ChromeDriver version is compatible with which Chrome Browser version?

The Chrome Browser versión should matches with the chromeDriver versión. Go to : chrome://settings/help

How do I confirm I'm using the right chromedriver?

  • Go to the folder where you have chromeDriver
  • Open command prompt pointing the folder
  • run: chromeDriver -v

findAll() in yii

$id = 101;

$sql = 'SELECT * FROM ur_tbl t WHERE t.email_id = '. $id;
$email = Yii::app()->db->createCommand($sql)->queryAll();

var_dump($email);

How to make UIButton's text alignment center? Using IB

For ios 8 and Swift

btn.titleLabel.textAlignment = NSTextAlignment.Center

or

btn.titleLabel.textAlignment = .Center

Wait for async task to finish

How about calling a function from within your callback instead of returning a value in sync_call()?

function sync_call(input) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) {
        value = result;
        use_value(value);
    } );
}

How can a LEFT OUTER JOIN return more records than exist in the left table?

LEFT OUTER JOIN just like INNER JOIN (normal join) will return as many results for each row in left table as many matches it finds in the right table. Hence you can have a lot of results - up to N x M, where N is number of rows in left table and M is number of rows in right table.

It's the minimum number of results is always guaranteed in LEFT OUTER JOIN to be at least N.

Change default date time format on a single database in SQL Server

For SQL Server 2008 run:

EXEC sp_defaultlanguage 'username', 'british'

Set default value of an integer column SQLite

Use the SQLite keyword default

db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" 
    + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
    + KEY_NAME + " TEXT NOT NULL, "
    + KEY_WORKED + " INTEGER, "
    + KEY_NOTE + " INTEGER DEFAULT 0);");

This link is useful: http://www.sqlite.org/lang_createtable.html

Image height and width not working?

You must write

<img src="theSource" style="width:30px;height:30px;" />

Inline styling will always take precedence over CSS styling. The width and height attributes are being overridden by your stylesheet, so you need to switch to this format.

sed edit file in place

Note that on OS X you might get strange errors like "invalid command code" or other strange errors when running this command. To fix this issue try

sed -i '' -e "s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g" <file>

This is because on the OSX version of sed, the -i option expects an extension argument so your command is actually parsed as the extension argument and the file path is interpreted as the command code. Source: https://stackoverflow.com/a/19457213

How to return a file (FileContentResult) in ASP.NET WebAPI

If you want to return IHttpActionResult you can do it like this:

[HttpGet]
public IHttpActionResult Test()
{
    var stream = new MemoryStream();

    var result = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new ByteArrayContent(stream.GetBuffer())
    };
    result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = "test.pdf"
    };
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

    var response = ResponseMessage(result);

    return response;
}

How to get script of SQL Server data?

If you want to script all table rows then Go with Generate Scripts as described by Daniel Vassallo. You can’t go wrong here

Else Use third party tools such as ApexSQL Script or SSMS Toolpack for more advanced scripting that includes some preprocessing, selective scripting and more.

NameError: name 'datetime' is not defined

You need to import the module datetime first:

>>> import datetime

After that it works:

>>> import datetime
>>> date = datetime.date.today()
>>> date
datetime.date(2013, 11, 12)

How to set time delay in javascript

setTimeout(function(){


}, 500); 

Place your code inside of the { }

500 = 0.5 seconds

2200 = 2.2 seconds

etc.

How to change the application launcher icon on Flutter?

I use few methods for chaging flutter app lancher icon but only the manuall method is a bit easy and good. Because you will know how it work.

So to change flutter ios icon. First get copy of your icon 1024×1024 pixel and generate set of icons for android and ios using appicon.co generator. When you get zip file it work contact two folder ios and android open ios folder and copy folder and replace the one in your ios/runner directory.

For android copy all folder present in android folder and replace the ones present in the android/app/src/main/res/drawable here.

After replacing folder on both ios and android stop the app and re run and your icons will be changed.

Spark: Add column to dataframe conditionally

My bad, I had missed one part of the question.

Best, cleanest way is to use a UDF. Explanation within the code.

// create some example data...BY DataFrame
// note, third record has an empty string
case class Stuff(a:String,b:Int)
val d= sc.parallelize(Seq( ("a",1),("b",2),
     ("",3) ,("d",4)).map { x => Stuff(x._1,x._2)  }).toDF

// now the good stuff.
import org.apache.spark.sql.functions.udf
// function that returns 0 is string empty 
val func = udf( (s:String) => if(s.isEmpty) 0 else 1 )
// create new dataframe with added column named "notempty"
val r = d.select( $"a", $"b", func($"a").as("notempty") )

    scala> r.show
+---+---+--------+
|  a|  b|notempty|
+---+---+--------+
|  a|  1|    1111|
|  b|  2|    1111|
|   |  3|       0|
|  d|  4|    1111|
+---+---+--------+

How to get start and end of previous month in VB

The first day of the previous month is always 1, to get the last day of the previous month, use 0 with DateSerial:

''Today is 20/03/2013 in dd/mm/yyyy
DateSerial(Year(Date),Month(Date),0) = 28/02/2013 
DateSerial(Year(Date),1,0) = 31/12/2012 

You can get the first day from the above like so:

LastDay = DateSerial(Year(Date),Month(Date),0)
FirstDay = LastDay-Day(LastDay)+1

See also: How to caculate last business day of month in VBScript

How to get text box value in JavaScript

Your element does not have an ID but just a name. So you could either use getElementsByName() method to get a list of all elements with this name:

var jobValue = document.getElementsByName('txtJob')[0].value  // first element in DOM  (index 0) with name="txtJob"

Or you assign an ID to the element:

<input type="text" name="txtJob" id="txtJob" value="software engineer">

How do I find the MySQL my.cnf location

As noted by konyak you can get the list of places mysql will look for your my.cnf file by running mysqladmin --help. Since this is pretty verbose you can get to the part you care about quickly with:

$ mysqladmin --help | grep -A1 'Default options'

This will give you output similar to:

Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/local/etc/my.cnf ~/.my.cnf

Depending on how you installed mysql it is possible that none of these files are present yet. You can cat them in order to see how your config is being built and create your own my.cnf if needed at your preferred location.

Find and replace Android studio

ctrl + H ..... its give option to replace word from class.

How to use struct timeval to get the execution time?

Change:

struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to
                                          delcare a variable with
                                          no name. */

to:

struct timeval tvalBefore, tvalAfter;

It is less likely (IMO) to make this mistake if there is a single declaration per line:

struct timeval tvalBefore;
struct timeval tvalAfter;

It becomes more error prone when declaring pointers to types on a single line:

struct timeval* tvalBefore, tvalAfter;

tvalBefore is a struct timeval* but tvalAfter is a struct timeval.

Should I declare Jackson's ObjectMapper as a static field?

Yes, that is safe and recommended.

The only caveat from the page you referred is that you can't be modifying configuration of the mapper once it is shared; but you are not changing configuration so that is fine. If you did need to change configuration, you would do that from the static block and it would be fine as well.

EDIT: (2013/10)

With 2.0 and above, above can be augmented by noting that there is an even better way: use ObjectWriter and ObjectReader objects, which can be constructed by ObjectMapper. They are fully immutable, thread-safe, meaning that it is not even theoretically possible to cause thread-safety issues (which can occur with ObjectMapper if code tries to re-configure instance).

Change text from "Submit" on input tag

The value attribute is used to determine the rendered label of a submit input.

<input type="submit" class="like" value="Like" />

Note that if the control is successful (this one won't be as it has no name) this will also be the submitted value for it.

To have a different submitted value and label you need to use a button element, in which the textNode inside the element determines the label. You can include other elements (including <img> here).

<button type="submit" class="like" name="foo" value="bar">Like</button>

Note that support for <button> is dodgy in older versions of Internet Explorer.

Get Value of a Edit Text field

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

  Button  rtn = (Button)findViewById(R.id.button);
  EditText edit_text   = (EditText)findViewById(R.id.edittext1);

    rtn .setOnClickListener(
        new View.OnClickListener()
        {
            public void onClick(View view)
            {
                Log.v("EditText value=", edit_text.getText().toString());
            }
        });
}

Set textarea width to 100% in bootstrap modal

Try add min-width: 100% to style of your textarea:

<textarea class="form-control" style="min-width: 100%"></textarea>

How to center a "position: absolute" element

    <div class="centered_content"> content </div>
    <style type="text/css">
    .centered_content {
       text-align: center;
       position: absolute;
       left: 0;
       right: 0;
    }
    </style>

see demo on: http://jsfiddle.net/MohammadDayeh/HrZLC/

text-align: center; works with a position: absolute element when adding left: 0; right: 0;

How to make my layout able to scroll down?

Yes, it is very Simple. Just Put your Code Inside this:

<androidx.core.widget.NestedScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" 
    android:layout_height="match_parent">

//YOUR CODE

</androidx.core.widget.NestedScrollView>

Get fragment (value after hash '#') from a URL in php

I've been searching for a workaround for this for a bit - and the only thing I have found is to use URL rewrites to read the "anchor". I found in the apache docs here http://httpd.apache.org/docs/2.2/rewrite/advanced.html the following...

By default, redirecting to an HTML anchor doesn't work, because mod_rewrite escapes the # character, turning it into %23. This, in turn, breaks the redirection.

Solution: Use the [NE] flag on the RewriteRule. NE stands for No Escape.

Discussion: This technique will of course also work with other special characters that mod_rewrite, by default, URL-encodes.

It may have other caveats and what not ... but I think that at least doing something with the # on the server is possible.

What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

In addition to keeping the variables local, one very handy use is when writing a library using a global variable, you can give it a shorter variable name to use within the library. It's often used in writing jQuery plugins, since jQuery allows you to disable the $ variable pointing to jQuery, using jQuery.noConflict(). In case it is disabled, your code can still use $ and not break if you just do:

(function($) { ...code...})(jQuery);

How different is Scrum practice from Agile Practice?

Scrum comes under bigger umbrella called Agile. Kanban, eXtreme Programming (XP), Lean are said to come under Agile too.

My personal experience is: there is no separate word called "Agile Practice". Best practices exercised in SCRUM, XP may be cumulatively called as Agile Practice.

The following practices are visible in both XP and SCRUM, hence in Agile.

  1. User Story as Client requirement
  2. Pair Programming
  3. Test Driven Development (TDD)
  4. Team based estimation
  5. Refactoring
  6. Simple Design
  7. Evolutionary Design
  8. Retrospective
  9. Daily Stand up meeting
  10. Continuous Integration of code
  11. Client Demo etc.

For more details, you may wish to go through my blog: http://chandrimachoudhury.blogspot.in/

how to set the default value to the drop down list control?

if you know the index of the item of default value,just

lstDepartment.SelectedIndex = 1;//the second item

or if you know the value you want to set, just

lstDepartment.SelectedValue = "the value you want to set";

How can I check if char* variable points to empty string?

An empty string has one single null byte. So test if (s[0] == (char)0)

Unit Tests not discovered in Visual Studio 2017

Sometimes, I find if you have stackoverflow exceptions in your unit test code, visual studio will mark that unit test case as not run and will stop running other test cases that follow this case.

In this case, you have to find out which case is causing the stackoverflow exception.

Virtualbox shared folder permissions

In my case the following was necessary:

sudo chgrp vboxsf /media/sf_sharedFolder

How to automatically update an application without ClickOnce?

There are a lot of questions already about this, so I will refer you to those.

One thing you want to make sure to prevent the need for uninstallation, is that you use the same upgrade code on every release, but change the product code. These values are located in the Installshield project properties.

Some references:

How do I close a tkinter window?

You should use destroy() to close a tkinter window.

from Tkinter import *

root = Tk()
Button(root, text="Quit", command=root.destroy).pack()
root.mainloop()

Explanation:

root.quit()

The above line just Bypasses the root.mainloop() i.e root.mainloop() will still be running in background if quit() command is executed.

root.destroy()

While destroy() command vanish out root.mainloop() i.e root.mainloop() stops.

So as you just want to quit the program so you should use root.destroy() as it will it stop the mainloop().

But if you want to run some infinite loop and you don't want to destroy your Tk window and want to execute some code after root.mainloop() line then you should use root.quit(). Ex:

from Tkinter import *
def quit():
    global root
    root.quit()

root = Tk()
while True:
    Button(root, text="Quit", command=quit).pack()
    root.mainloop()
    #do something

Java stack overflow error - how to increase the stack size in Eclipse?

You need to have a launch configuration inside Eclipse in order to adjust the JVM parameters.

After running your program with either F11 or Ctrl-F11, open the launch configurations in Run -> Run Configurations... and open your program under "Java Applications". Select the Arguments pane, where you will find "VM arguments".

This is where -Xss1024k goes.

If you want the launch configuration to be a file in your workspace (so you can right click and run it), select the Common pane, and check the Save as -> Shared File checkbox and browse to the location you want the launch file. I usually have them in a separate folder, as we check them into CVS.

How to declare a variable in SQL Server and use it in the same Stored Procedure

What's going wrong with what you have? What error do you get, or what result do or don't you get that doesn't match your expectations?

I can see the following issues with that SP, which may or may not relate to your problem:

  • You have an extraneous ) after @BrandName in your SELECT (at the end)
  • You're not setting @CategoryID or @BrandName to anything anywhere (they're local variables, but you don't assign values to them)

Edit Responding to your comment: The error is telling you that you haven't declared any parameters for the SP (and you haven't), but you called it with parameters. Based on your reply about @CategoryID, I'm guessing you wanted it to be a parameter rather than a local variable. Try this:

CREATE PROCEDURE AddBrand
   @BrandName nvarchar(50),
   @CategoryID int
AS
BEGIN
   DECLARE @BrandID int

   SELECT @BrandID = BrandID FROM tblBrand WHERE BrandName = @BrandName

   INSERT INTO tblBrandinCategory (CategoryID, BrandID) VALUES (@CategoryID, @BrandID)
END

You would then call this like this:

EXEC AddBrand 'Gucci', 23

...assuming the brand name was 'Gucci' and category ID was 23.

How to undo "git commit --amend" done instead of "git commit"

Almost 9 years late to this but didn't see this variation mentioned accomplishing the same thing (it's kind of a combination of a few of these, similar to to top answer (https://stackoverflow.com/a/1459264/4642530).

Search all detached heads on branch

git reflog show origin/BRANCH_NAME --date=relative

Then find the SHA1 hash

Reset to old SHA1

git reset --hard SHA1

Then push it back up.

git push origin BRANCH_NAME

Done.

This will revert you back to the old commit entirely.

(Including the date of the prior overwritten detached commit head)

TypeError: cannot perform reduce with flexible type

It looks like your 'trainData' is a list of strings:

['-214' '-153' '-58' ..., '36' '191' '-37']

Change your 'trainData' to a numeric type.

 import numpy as np
 np.array(['1','2','3']).astype(np.float)

How to fit a smooth curve to my data in R?

In ggplot2 you can do smooths in a number of ways, for example:

library(ggplot2)
ggplot(mtcars, aes(wt, mpg)) + geom_point() +
  geom_smooth(method = "gam", formula = y ~ poly(x, 2)) 
ggplot(mtcars, aes(wt, mpg)) + geom_point() +
  geom_smooth(method = "loess", span = 0.3, se = FALSE) 

enter image description here enter image description here

rsync - mkstemp failed: Permission denied (13)

I had the same issue, so I first SSH into the server to confirm that I able to log in to the server by using the command:

ssh -i /Users/Desktop/mypemfile.pem [email protected]

Then in New Terminal

I copied a small file to the server by using SCP, to make sure I am able to make a connection:

scp -i /Users/Desktop/mypemfile.pem /Users/Desktop/test.file [email protected]:/home/user/test/

Then In the same new terminal, I tried running rsync:

rsync -avz -e "ssh -i /Users/Desktop/mypemfile.pem" /Users/Desktop/backup/image.img.gz [email protected]:

Interface vs Base class

When I first started learning about object-oriented programming, I made the easy and probably common mistake of using inheritance to share common behavior - even where that behavior was not essential to the nature of the object.

To further build on an example much used in this particular question, there are lots of things that are petable - girlfriends, cars, fuzzy blankets... - so I might have had a Petable class that provided this common behavior, and various classes inheriting from it.

However, being petable is not part of the nature of any of these objects. There are vastly more important concepts that are essential to their nature - the girlfriend is a person, the car is a land vehicle, the cat is a mammal...

Behaviors should be assigned first to interfaces (including the default interface of the class), and promoted to a base class only if they are (a) common to a large group of classes that are subsets of a larger class - in the same sense that "cat" and "person" are subsets of "mammal".

The catch is, after you understand object-oriented design sufficiently better than I did at first, you'll normally do this automatically without even thinking about it. So the bare truth of the statement "code to an interface, not an abstract class" becomes so obvious you have a hard time believing anyone would bother to say it - and start trying to read other meanings into it.

Another thing I'd add is that if a class is purely abstract - with no non-abstract, non-inherited members or methods exposed to child, parent, or client - then why is it a class? It could be replaced, in some cases by an interface and in other cases by Null.

Modifying list while iterating

This slice syntax makes a copy of the list and does what you want:

l  = range(100)  
for i in l[:]:  
    print i,  
    print l.pop(0),  
    print l.pop(0)

How to create EditText with cross(x) button at end of it?

Here is complete library with the widget: https://github.com/opprime/EditTextField

To use it you should add the dependency:

compile 'com.optimus:editTextField:0.2.0'

In the layout.xml file you can play with the widget settings:

xmlns:app="http://schemas.android.com/apk/res-auto"
  • app:clearButtonMode,can has such values: never always whileEditing unlessEditing

  • app:clearButtonDrawable

Sample in action:

enter image description here

Add vertical scroll bar to panel

Try this instead for 'only' scrolling vertical.
(auto scroll needs to be false before it will accept changes)

mypanel.AutoScroll = false;
mypanel.HorizontalScroll.Enabled = false;
mypanel.HorizontalScroll.Visible = false;
mypanel.HorizontalScroll.Maximum = 0;
mypanel.AutoScroll = true;

JavaScript Extending Class

Try this:

Function.prototype.extends = function(parent) {
  this.prototype = Object.create(parent.prototype);
};

Monkey.extends(Monster);
function Monkey() {
  Monster.apply(this, arguments); // call super
}

Edit: I put a quick demo here http://jsbin.com/anekew/1/edit. Note that extends is a reserved word in JS and you may get warnings when linting your code, you can simply name it inherits, that's what I usually do.

With this helper in place and using an object props as only parameter, inheritance in JS becomes a bit simpler:

Function.prototype.inherits = function(parent) {
  this.prototype = Object.create(parent.prototype);
};

function Monster(props) {
  this.health = props.health || 100;
}

Monster.prototype = {
  growl: function() {
    return 'Grrrrr';
  }
};

Monkey.inherits(Monster);
function Monkey() {
  Monster.apply(this, arguments);
}

var monkey = new Monkey({ health: 200 });

console.log(monkey.health); //=> 200
console.log(monkey.growl()); //=> "Grrrr"

CSS flex, how to display one item on first line and two on the next line

The answer given by Nico O is correct. However this doesn't get the desired result on Internet Explorer 10 to 11 and Firefox.

For IE, I found that changing

.flex > div
{
   flex: 1 0 50%;
}

to

.flex > div
{
   flex: 1 0 45%;
}

seems to do the trick. Don't ask me why, I haven't gone any further into this but it might have something to do with how IE renders the border-box or something.

In the case of Firefox I solved it by adding

display: inline-block;

to the items.

How do I fix "Expected to return a value at the end of arrow function" warning?

A map() creates an array, so a return is expected for all code paths (if/elses).

If you don't want an array or to return data, use forEach instead.

How to bind DataTable to Datagrid

In .cs file

grid.DataContext = table.DefaultView;

In xaml file

<DataGrid Name="grid" ItemsSource="{Binding}">

Getting "method not valid without suitable object" error when trying to make a HTTP request in VBA?

Check out this one:

https://github.com/VBA-tools/VBA-Web

It's a high level library for dealing with REST. It's OOP, works with JSON, but also works with any other format.

How to disable EditText in Android

Set inputType attribute to none in your layout.xml file under EditText

Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings

Here's some future-proof code for browsers that may lack escape/unescape(). Note that IE 9 and older don't support atob/btoa(), so you'd need to use custom base64 functions for them.

// Polyfill for escape/unescape
if( !window.unescape ){
    window.unescape = function( s ){
        return s.replace( /%([0-9A-F]{2})/g, function( m, p ) {
            return String.fromCharCode( '0x' + p );
        } );
    };
}
if( !window.escape ){
    window.escape = function( s ){
        var chr, hex, i = 0, l = s.length, out = '';
        for( ; i < l; i ++ ){
            chr = s.charAt( i );
            if( chr.search( /[A-Za-z0-9\@\*\_\+\-\.\/]/ ) > -1 ){
                out += chr; continue; }
            hex = s.charCodeAt( i ).toString( 16 );
            out += '%' + ( hex.length % 2 != 0 ? '0' : '' ) + hex;
        }
        return out;
    };
}

// Base64 encoding of UTF-8 strings
var utf8ToB64 = function( s ){
    return btoa( unescape( encodeURIComponent( s ) ) );
};
var b64ToUtf8 = function( s ){
    return decodeURIComponent( escape( atob( s ) ) );
};

A more comprehensive example for UTF-8 encoding and decoding can be found here: http://jsfiddle.net/47zwb41o/

How is TeamViewer so fast?

A bit late answer, but I suggest you have a look at a not well known project on codeplex called ConferenceXP

ConferenceXP is an open source research platform that provides simple, flexible, and extensible conferencing and collaboration using high-bandwidth networks and the advanced multimedia capabilities of Microsoft Windows. ConferenceXP helps researchers and educators develop innovative applications and solutions that feature broadcast-quality audio and video in support of real-time distributed collaboration and distance learning environments.

Full source (it's huge!) is provided. It implements the RTP protocol.

Modify SVG fill color when being served as Background-Image

It's possible with Sass! The only thing you have to do is to url-encode your svg code. And this is possible with a helper function in Sass. I've made a codepen for this. Look at this:

http://codepen.io/philippkuehn/pen/zGEjxB

// choose a color

$icon-color: #F84830;


// functions to urlencode the svg string

@function str-replace($string, $search, $replace: '') {
  $index: str-index($string, $search);
  @if $index {
    @return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
  }
  @return $string;
}

@function url-encode($string) {
  $map: (
    "%": "%25",
    "<": "%3C",
    ">": "%3E",
    " ": "%20",
    "!": "%21",
    "*": "%2A",
    "'": "%27",
    '"': "%22",
    "(": "%28",
    ")": "%29",
    ";": "%3B",
    ":": "%3A",
    "@": "%40",
    "&": "%26",
    "=": "%3D",
    "+": "%2B",
    "$": "%24",
    ",": "%2C",
    "/": "%2F",
    "?": "%3F",
    "#": "%23",
    "[": "%5B",
    "]": "%5D"
  );
  $new: $string;
  @each $search, $replace in $map {
    $new: str-replace($new, $search, $replace);
  }
  @return $new;
}

@function inline-svg($string) {
  @return url('data:image/svg+xml;utf8,#{url-encode($string)}');
}


// icon styles
// note the fill="' + $icon-color + '"

.icon {
  display: inline-block;
  width: 50px;
  height: 50px;
  background: inline-svg('<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
   viewBox="0 0 30 30" enable-background="new 0 0 30 30" xml:space="preserve">
<path fill="' + $icon-color + '" d="M18.7,10.1c-0.6,0.7-1,1.6-0.9,2.6c0,0.7-0.6,0.8-0.9,0.3c-1.1-2.1-0.4-5.1,0.7-7.2c0.2-0.4,0-0.8-0.5-0.7
  c-5.8,0.8-9,6.4-6.4,12c0.1,0.3-0.2,0.6-0.5,0.5c-0.6-0.3-1.1-0.7-1.6-1.3c-0.2-0.3-0.4-0.5-0.6-0.8c-0.2-0.4-0.7-0.3-0.8,0.3
  c-0.5,2.5,0.3,5.3,2.1,7.1c4.4,4.5,13.9,1.7,13.4-5.1c-0.2-2.9-3.2-4.2-3.3-7.1C19.6,10,19.1,9.6,18.7,10.1z"/>
</svg>');
}

How do I sort a list of dictionaries by a value of the dictionary?

Sometimes we need to use lower(). For example,

lists = [{'name':'Homer', 'age':39},
  {'name':'Bart', 'age':10},
  {'name':'abby', 'age':9}]

lists = sorted(lists, key=lambda k: k['name'])
print(lists)
# [{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}, {'name':'abby', 'age':9}]

lists = sorted(lists, key=lambda k: k['name'].lower())
print(lists)
# [ {'name':'abby', 'age':9}, {'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]

How to build PDF file from binary string returned from a web-service using javascript

Is there any solution like building a pdf file on file system in order to let the user download it?

Try setting responseType of XMLHttpRequest to blob , substituting download attribute at a element for window.open to allow download of response from XMLHttpRequest as .pdf file

var request = new XMLHttpRequest();
request.open("GET", "/path/to/pdf", true); 
request.responseType = "blob";
request.onload = function (e) {
    if (this.status === 200) {
        // `blob` response
        console.log(this.response);
        // create `objectURL` of `this.response` : `.pdf` as `Blob`
        var file = window.URL.createObjectURL(this.response);
        var a = document.createElement("a");
        a.href = file;
        a.download = this.response.name || "detailPDF";
        document.body.appendChild(a);
        a.click();
        // remove `a` following `Save As` dialog, 
        // `window` regains `focus`
        window.onfocus = function () {                     
          document.body.removeChild(a)
        }
    };
};
request.send();

Best way to detect Mac OS X or Windows computers with JavaScript or jQuery

The window.navigator.platform property is not spoofed when the userAgent string is changed. I tested on my Mac if I change the userAgent to iPhone or Chrome Windows, navigator.platform remains MacIntel.

navigator.platform is not spoofed when the userAgent string is changed

The property is also read-only

navigator.platform is read-only


I could came up with the following table

Mac Computers

Mac68K Macintosh 68K system.
MacPPC Macintosh PowerPC system.
MacIntel Macintosh Intel system.

iOS Devices

iPhone iPhone.
iPod iPod Touch.
iPad iPad.


Modern macs returns navigator.platform == "MacIntel" but to give some "future proof" don't use exact matching, hopefully they will change to something like MacARM or MacQuantum in future.

var isMac = navigator.platform.toUpperCase().indexOf('MAC')>=0;

To include iOS that also use the "left side"

var isMacLike = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);
var isIOS = /(iPhone|iPod|iPad)/i.test(navigator.platform);

_x000D_
_x000D_
var is_OSX = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);_x000D_
var is_iOS = /(iPhone|iPod|iPad)/i.test(navigator.platform);_x000D_
_x000D_
var is_Mac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;_x000D_
var is_iPhone = navigator.platform == "iPhone";_x000D_
var is_iPod = navigator.platform == "iPod";_x000D_
var is_iPad = navigator.platform == "iPad";_x000D_
_x000D_
/* Output */_x000D_
var out = document.getElementById('out');_x000D_
if (!is_OSX) out.innerHTML += "This NOT a Mac or an iOS Device!";_x000D_
if (is_Mac) out.innerHTML += "This is a Mac Computer!\n";_x000D_
if (is_iOS) out.innerHTML += "You're using an iOS Device!\n";_x000D_
if (is_iPhone) out.innerHTML += "This is an iPhone!";_x000D_
if (is_iPod) out.innerHTML += "This is an iPod Touch!";_x000D_
if (is_iPad) out.innerHTML += "This is an iPad!";_x000D_
out.innerHTML += "\nPlatform: " + navigator.platform;
_x000D_
<pre id="out"></pre>
_x000D_
_x000D_
_x000D_


Since most O.S. use the close button on the right, you can just move the close button to the left when the user is on a MacLike O.S., otherwise isn't a problem if you put it on the most common side, the right.

_x000D_
_x000D_
setTimeout(test, 1000); //delay for demonstration_x000D_
_x000D_
function test() {_x000D_
_x000D_
  var mac = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);_x000D_
_x000D_
  if (mac) {_x000D_
    document.getElementById('close').classList.add("left");_x000D_
  }_x000D_
}
_x000D_
#window {_x000D_
  position: absolute;_x000D_
  margin: 1em;_x000D_
  width: 300px;_x000D_
  padding: 10px;_x000D_
  border: 1px solid gray;_x000D_
  background-color: #DDD;_x000D_
  text-align: center;_x000D_
  box-shadow: 0px 1px 3px #000;_x000D_
}_x000D_
#close {_x000D_
  position: absolute;_x000D_
  top: 0px;_x000D_
  right: 0px;_x000D_
  width: 22px;_x000D_
  height: 22px;_x000D_
  margin: -12px;_x000D_
  box-shadow: 0px 1px 3px #000;_x000D_
  background-color: #000;_x000D_
  border: 2px solid #FFF;_x000D_
  border-radius: 22px;_x000D_
  color: #FFF;_x000D_
  text-align: center;_x000D_
  font: 14px"Comic Sans MS", Monaco;_x000D_
}_x000D_
#close.left{_x000D_
  left: 0px;_x000D_
}
_x000D_
<div id="window">_x000D_
  <div id="close">x</div>_x000D_
  <p>Hello!</p>_x000D_
  <p>If the "close button" change to the left side</p>_x000D_
  <p>you're on a Mac like system!</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://www.nczonline.net/blog/2007/12/17/don-t-forget-navigator-platform/

Fastest way to check if a file exist using standard C++/C++11/C?

Although there are several ways to do this the most efficient solution to your problem would probably be to use one of the fstream's predefined method such as good(). With this method you can check whether the file you've specified exist or not.

fstream file("file_name.txt");

if (file.good()) 
{
    std::cout << "file is good." << endl;
}
else 
{
    std::cout << "file isnt good" << endl;
}

I hope you find this useful.

Getting only Month and Year from SQL DATE

CONCAT (datepart (yy,DATE), FORMAT (DATE,'MM')) 

gives you eg 201601 if you want a six digit result

Unable to open a file with fopen()

Try using an absolute path for the filename. And if you are using Windows, use getlasterror() to see the actual error message.

Create list of object from another using Java 8 Streams

I prefer to solve this in the classic way, creating a new array of my desired data type:

List<MyNewType> newArray = new ArrayList<>();
myOldArray.forEach(info -> newArray.add(objectMapper.convertValue(info, MyNewType.class)));

How to check if an NSDictionary or NSMutableDictionary contains a key?

One very nasty gotcha which just wasted a bit of my time debugging - you may find yourself prompted by auto-complete to try using doesContain which seems to work.

Except, doesContain uses an id comparison instead of the hash comparison used by objectForKey so if you have a dictionary with string keys it will return NO to a doesContain.

NSMutableDictionary* keysByName = [[NSMutableDictionary alloc] init];
keysByName[@"fred"] = @1;
NSString* test = @"fred";

if ([keysByName objectForKey:test] != nil)
    NSLog(@"\nit works for key lookups");  // OK
else
    NSLog(@"\nsod it");

if (keysByName[test] != nil)
    NSLog(@"\nit works for key lookups using indexed syntax");  // OK
else
    NSLog(@"\nsod it");

if ([keysByName doesContain:@"fred"])
    NSLog(@"\n doesContain works literally");
else
    NSLog(@"\nsod it");  // this one fails because of id comparison used by doesContain

scrollTop jquery, scrolling to div with id?

if you want to scroll just only some div, can use the div id instead of 'html, body'

$('html, body').animate(...

use

$('#mydivid').animate(...

How can I change the color of my prompt in zsh (different from normal text)?

To complement all of the above answers another convenient trick is to place the coloured prompt settings into a zsh function. There you may define local variables to alias longer commands, e.g. rc=$reset_color or define your own colour variables. Don't forget to place it into your .zshrc file and call the function you have defined:

# Coloured prompt
autoload -U colors && colors
function myprompt {
  local rc=$reset_color
  export PS1="%F{cyan}%n%{$rc%}@%F{green}%m%{$rc%}:%F{magenta}%~%{$rc%}%# "
}
myprompt

Function for Factorial in Python

On Python 2.6 and up, try:

import math
math.factorial(n)

Can we locate a user via user's phone number in Android?

Quick answer: No, at least not with native SMS service.

Long answer: Sure, but the receiver's phone should have the correct setup first. An app that detects incoming sms, and if a keyword matches, reports its current location to your server, which then pushes that info to the sender.

How is attr_accessible used in Rails 4?

1) Update Devise so that it can handle Rails 4.0 by adding this line to your application's Gemfile:

gem 'devise', '3.0.0.rc' 

Then execute:

$ bundle

2) Add the old functionality of attr_accessible again to rails 4.0

Try to use attr_accessible and don't comment this out.

Add this line to your application's Gemfile:

gem 'protected_attributes'

Then execute:

$ bundle

The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'

  1. Open SQL Management Studio
  2. Expand your database
  3. Expand the "Security" Folder
  4. Expand "Users"
  5. Right click the user (the one that's trying to perform the query) and select Properties.
  6. Select page Membership.
  7. Make sure you uncheck

    db_denydatareader

    db_denydatawriter

enter image description here

This should go without saying, but only grant the permissions to what the user needs. An easy lazy fix is to check db_owner like I have, but this is not the best security practice.

How to copy data from one HDFS to another HDFS?

DistCp (distributed copy) is a tool used for copying data between clusters. It uses MapReduce to effect its distribution, error handling and recovery, and reporting. It expands a list of files and directories into input to map tasks, each of which will copy a partition of the files specified in the source list.

Usage: $ hadoop distcp <src> <dst>

example: $ hadoop distcp hdfs://nn1:8020/file1 hdfs://nn2:8020/file2

file1 from nn1 is copied to nn2 with filename file2

Distcp is the best tool as of now. Sqoop is used to copy data from relational database to HDFS and vice versa, but not between HDFS to HDFS.

More info:

There are two versions available - runtime performance in distcp2 is more compared to distcp

JQuery, select first row of table

Actually, if you try to use function "children" it will not be succesfull because it's possible to the table has a first child like 'th'. So you have to use function 'find' instead.

Wrong way:

var $row = $(this).closest('table').children('tr:first');

Correct way:

 var $row = $(this).closest('table').find('tr:first');

PUT vs. POST in REST

In addition to differences suggested by others, I want to add one more.

In POST method you can send body params in form-data

In PUT method you have to send body params in x-www-form-urlencoded

Header Content-Type:application/x-www-form-urlencoded

According to this, you cannot send files or multipart data in the PUT method

EDIT

The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

Which means if you have to submit

files, non-ASCII data, and binary data

you should use POST method

How to print register values in GDB?

info registers shows all the registers; info registers eax shows just the register eax. The command can be abbreviated as i r

What is Inversion of Control?

A very simple written explanation can be found here

http://binstock.blogspot.in/2008/01/excellent-explanation-of-dependency.html

It says -

"Any nontrivial application is made up of two or more classes that collaborate with each other to perform some business logic. Traditionally, each object is responsible for obtaining its own references to the objects it collaborates with (its dependencies). When applying DI, the objects are given their dependencies at creation time by some external entity that coordinates each object in the system. In other words, dependencies are injected into objects."

How do you modify the web.config appSettings at runtime?

You need to use WebConfigurationManager.OpenWebConfiguration(): For Example:

Dim myConfiguration As Configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~")
myConfiguration.ConnectionStrings.ConnectionStrings("myDatabaseName").ConnectionString = txtConnectionString.Text
myConfiguration.AppSettings.Settings.Item("myKey").Value = txtmyKey.Text
myConfiguration.Save()

I think you might also need to set AllowLocation in machine.config. This is a boolean value that indicates whether individual pages can be configured using the element. If the "allowLocation" is false, it cannot be configured in individual elements.

Finally, it makes a difference if you run your application in IIS and run your test sample from Visual Studio. The ASP.NET process identity is the IIS account, ASPNET or NETWORK SERVICES (depending on IIS version).

Might need to grant ASPNET or NETWORK SERVICES Modify access on the folder where web.config resides.

nodemon command is not recognized in terminal for node js server

This may come to late, But better to say somthing :)

If you don't want to install nodemon globbaly you can use npx, it installs the package at run-time and will behave as global package (keep in mind that it's just available at the moment and does not exist globally!).

So all you need is npx nodemon server.js.

How to add local jar files to a Maven project?

Install the JAR into your local Maven repository as follows:

mvn install:install-file \
   -Dfile=<path-to-file> \
   -DgroupId=<group-id> \
   -DartifactId=<artifact-id> \
   -Dversion=<version> \
   -Dpackaging=<packaging> \
   -DgeneratePom=true

Where each refers to:

<path-to-file>: the path to the file to load e.g ? c:\kaptcha-2.3.jar

<group-id>: the group that the file should be registered under e.g ? com.google.code

<artifact-id>: the artifact name for the file e.g ? kaptcha

<version>: the version of the file e.g ? 2.3

<packaging>: the packaging of the file e.g. ? jar

Reference

How to validate IP address in Python?

The IPy module (a module designed for dealing with IP addresses) will throw a ValueError exception for invalid addresses.

>>> from IPy import IP
>>> IP('127.0.0.1')
IP('127.0.0.1')
>>> IP('277.0.0.1')
Traceback (most recent call last):
 ...
ValueError: '277.0.0.1': single byte must be 0 <= byte < 256
>>> IP('foobar')
Traceback (most recent call last):
 ...
ValueError: invalid literal for long() with base 10: 'foobar'

However, like Dustin's answer, it will accept things like "4" and "192.168" since, as mentioned, these are valid representations of IP addresses.

If you're using Python 3.3 or later, it now includes the ipaddress module:

>>> import ipaddress
>>> ipaddress.ip_address('127.0.0.1')
IPv4Address('127.0.0.1')
>>> ipaddress.ip_address('277.0.0.1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.3/ipaddress.py", line 54, in ip_address
    address)
ValueError: '277.0.0.1' does not appear to be an IPv4 or IPv6 address
>>> ipaddress.ip_address('foobar')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.3/ipaddress.py", line 54, in ip_address
    address)
ValueError: 'foobar' does not appear to be an IPv4 or IPv6 address

For Python 2, you can get the same functionality using ipaddress if you install python-ipaddress:

pip install ipaddress

This module is compatible with Python 2 and provides a very similar API to that of the ipaddress module included in the Python Standard Library since Python 3.3. More details here. In Python 2 you will need to explicitly convert the IP address string to unicode: ipaddress.ip_address(u'127.0.0.1').

Cannot execute RUN mkdir in a Dockerfile

You can also simply use

WORKDIR /var/www/app

It will automatically create the folders if they don't exist.

Then switch back to the directory you need to be in.

Is a URL allowed to contain a space?

URLs are defined in RFC 3986, though other RFCs are relevant as well but RFC 1738 is obsolete.

They may not have spaces in them, along with many other characters. Since those forbidden characters often need to be represented somehow, there is a scheme for encoding them into a URL by translating them to their ASCII hexadecimal equivalent with a "%" prefix.

Most programming languages/platforms provide functions for encoding and decoding URLs, though they may not properly adhere to the RFC standards. For example, I know that PHP does not.

Including a .js file within a .js file

I use @gnarf's method, though I fall back on document.writelning a <script> tag for IE<7 as I couldn't get DOM creation to work reliably in IE6 (and TBH didn't care enough to put much effort into it). The core of my code is:

if (horus.script.broken) {
    document.writeln('<script type="text/javascript" src="'+script+'"></script>');   
    horus.script.loaded(script);
} else {
    var s=document.createElement('script');
    s.type='text/javascript';
    s.src=script;
    s.async=true;

    if (horus.brokenDOM){
        s.onreadystatechange=
            function () {
                if (this.readyState=='loaded' || this.readyState=='complete'){
                    horus.script.loaded(script);
                }
        }
    }else{
        s.onload=function () { horus.script.loaded(script) };
    }

    document.head.appendChild(s);
}

where horus.script.loaded() notes that the javascript file is loaded, and calls any pending uncalled routines (saved by autoloader code).

Split a string into array in Perl

I found this one to be very simple!

my $line = "file1.gz file2.gz file3.gz";

my @abc =  ($line =~ /(\w+[.]\w+)/g);

print $abc[0],"\n";
print $abc[1],"\n";
print $abc[2],"\n";

output:

file1.gz 
file2.gz 
file3.gz

Here take a look at this tutorial to find more on Perl regular expression and scroll down to More matching section.

Loading inline content using FancyBox

The solution is very simple, but took me about 2 hours and half the hair on my head to find it.

Simply wrap your content with a (redundant) div that has display: none and Bob is your uncle.

<div style="display: none">
    <div id="content-div">Some content here</div>
</div>

Voila

How to remove from a map while iterating it?

Pretty sad, eh? The way I usually do it is build up a container of iterators instead of deleting during traversal. Then loop through the container and use map.erase()

std::map<K,V> map;
std::list< std::map<K,V>::iterator > iteratorList;

for(auto i : map ){
    if ( needs_removing(i)){
        iteratorList.push_back(i);
    }
}
for(auto i : iteratorList){
    map.erase(*i)
}

Plot two graphs in same plot in R

tl;dr: You want to use curve (with add=TRUE) or lines.


I disagree with par(new=TRUE) because that will double-print tick-marks and axis labels. Eg

sine and parabola

The output of plot(sin); par(new=T); plot( function(x) x**2 ).

Look how messed up the vertical axis labels are! Since the ranges are different you would need to set ylim=c(lowest point between the two functions, highest point between the two functions), which is less easy than what I'm about to show you---and way less easy if you want to add not just two curves, but many.


What always confused me about plotting is the difference between curve and lines. (If you can't remember that these are the names of the two important plotting commands, just sing it.)

Here's the big difference between curve and lines.

curve will plot a function, like curve(sin). lines plots points with x and y values, like: lines( x=0:10, y=sin(0:10) ).

And here's a minor difference: curve needs to be called with add=TRUE for what you're trying to do, while lines already assumes you're adding to an existing plot.

id & sine

Here's the result of calling plot(0:2); curve(sin).


Behind the scenes, check out methods(plot). And check body( plot.function )[[5]]. When you call plot(sin) R figures out that sin is a function (not y values) and uses the plot.function method, which ends up calling curve. So curve is the tool meant to handle functions.

Python Matplotlib Y-Axis ticks on Right Side of Plot

For right labels use ax.yaxis.set_label_position("right"), i.e.:

f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
ax.yaxis.set_label_position("right")
plt.plot([2,3,4,5])
ax.set_xlabel("$x$ /mm")
ax.set_ylabel("$y$ /mm")
plt.show()

Selecting distinct values from a JSON

Give this a go:

var distinct_list 

  = data.DATA.map(function (d) {return d[x];}).filter((v, i, a) => a.indexOf(v) === i)

Get current cursor position in a textbox

Here's one possible method.

function isMouseInBox(e) {
  var textbox = document.getElementById('textbox');

  // Box position & sizes
  var boxX = textbox.offsetLeft;
  var boxY = textbox.offsetTop;
  var boxWidth = textbox.offsetWidth;
  var boxHeight = textbox.offsetHeight;

  // Mouse position comes from the 'mousemove' event
  var mouseX = e.pageX;
  var mouseY = e.pageY;
  if(mouseX>=boxX && mouseX<=boxX+boxWidth) {
    if(mouseY>=boxY && mouseY<=boxY+boxHeight){
       // Mouse is in the box
       return true;
    }
  }
}

document.addEventListener('mousemove', function(e){
    isMouseInBox(e);
})

Jquery array.push() not working

Your HTML should include quotes for attributes : http://jsfiddle.net/dKWnb/4/

Not required when using a HTML5 doctype - thanks @bazmegakapa

You create the array each time and add a value to it ... its working as expected ?

Moving the array outside of the live() function works fine :

var myarray = []; // more efficient than new Array()
$("#test").live("click",function() {
        myarray.push($("#drop").val());
        alert(myarray);
});

http://jsfiddle.net/dKWnb/5/

Also note that in later versions of jQuery v1.7 -> the live() method is deprecated and replaced by the on() method.

Bootstrap onClick button event

There is no show event in js - you need to bind your button either to the click event:

$('#id').on('click', function (e) {

     //your awesome code here

})

Mind that if your button is inside a form, you may prefer to bind the whole form to the submit event.

How to get a file directory path from file path?

Here is a script I used for recursive trimming. Replace $1 with the directory you want, of course.

BASEDIR="$1"
IFS=$'\n'
cd $BASEDIR
 for f in $(find . -type f -name ' *')
 do 
    DIR=$(dirname "$f")
    DIR=${DIR:1}
    cd $BASEDIR$DIR
    rename 's/^ *//' *
 done

Adding Google Translate to a web site

<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'ko', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

Should I use != or <> for not equal in T-SQL?

They are both accepted in T-SQL. However, it seems that using <> works a lot faster than !=. I just ran a complex query that was using !=, and it took about 16 seconds on average to run. I changed those to <> and the query now takes about 4 seconds on average to run. That's a huge improvement!

Entity Framework Join 3 Tables

I think it will be easier using syntax-based query:

var entryPoint = (from ep in dbContext.tbl_EntryPoint
                 join e in dbContext.tbl_Entry on ep.EID equals e.EID
                 join t in dbContext.tbl_Title on e.TID equals t.TID
                 where e.OwnerID == user.UID
                 select new {
                     UID = e.OwnerID,
                     TID = e.TID,
                     Title = t.Title,
                     EID = e.EID
                 }).Take(10);

And you should probably add orderby clause, to make sure Top(10) returns correct top ten items.

What Vim command(s) can be used to quote/unquote words?

In addition to the other commands, this will enclose all words in a line in double quotes (as per your comment)

:s/\(\S\+\)/"\1"/

or if you want to reduce the number of backslashes, you can put a \v (very-magic) modifier at the start of the pattern

:s/\v(\S+)/"\1"/

svn cleanup: sqlite: database disk image is malformed

During app development I found that the messages come from the frequent and massive INSERT and UPDATE operations. Make sure to INSERT and UPDATE multiple rows or data in one single operation.

var updateStatementString : String! = ""

for item in cardids {

let newstring = "UPDATE "+TABLE_NAME+" SET pendingImages = '\(pendingImage)\' WHERE cardId = '\(item)\';"
            updateStatementString.append(newstring)

        }


        print(updateStatementString)
        let results = dbManager.sharedInstance.update(updateStatementString: updateStatementString)

        return Int64(results)

Handling a timeout error in python sockets

from foo import * 

adds all the names without leading underscores (or only the names defined in the modules __all__ attribute) in foo into your current module.

In the above code with from socket import * you just want to catch timeout as you've pulled timeout into your current namespace.

from socket import * pulls in the definitions of everything inside of socket but doesn't add socket itself.

try:
    # socketstuff
except timeout:
    print 'caught a timeout'

Many people consider import * problematic and try to avoid it. This is because common variable names in 2 or more modules that are imported in this way will clobber one another.

For example, consider the following three python files:

# a.py
def foo():
    print "this is a's foo function"

# b.py
def foo():
    print "this is b's foo function"

# yourcode.py
from a import *
from b import *
foo()

If you run yourcode.py you'll see just the output "this is b's foo function".

For this reason I'd suggest either importing the module and using it or importing specific names from the module:

For example, your code would look like this with explicit imports:

import socket
from socket import AF_INET, SOCK_DGRAM

def main():
    client_socket = socket.socket(AF_INET, SOCK_DGRAM)
    client_socket.settimeout(1)
    server_host = 'localhost'
    server_port = 1234
    while(True):
        client_socket.sendto('Message', (server_host, server_port))
        try:
            reply, server_address_info = client_socket.recvfrom(1024)
            print reply
        except socket.timeout:
            #more code

Just a tiny bit more typing but everything's explicit and it's pretty obvious to the reader where everything comes from.

ld cannot find an existing library

As just formulated by grepsedawk, the answer lies in the -l option of g++, calling ld. If you look at the man page of this command, you can either do:

  • g++ -l:libmagic.so.1 [...]
  • or: g++ -lmagic [...] , if you have a symlink named libmagic.so in your libs path

Loop through files in a folder using VBA?

Here's my interpretation as a Function Instead:

'#######################################################################
'# LoopThroughFiles
'# Function to Loop through files in current directory and return filenames
'# Usage: LoopThroughFiles ActiveWorkbook.Path, "txt" 'inputDirectoryToScanForFile
'# https://stackoverflow.com/questions/10380312/loop-through-files-in-a-folder-using-vba
'#######################################################################
Function LoopThroughFiles(inputDirectoryToScanForFile, filenameCriteria) As String

    Dim StrFile As String
    'Debug.Print "in LoopThroughFiles. inputDirectoryToScanForFile: ", inputDirectoryToScanForFile

    StrFile = Dir(inputDirectoryToScanForFile & "\*" & filenameCriteria)
    Do While Len(StrFile) > 0
        Debug.Print StrFile
        StrFile = Dir

    Loop

End Function

Setting the Vim background colors

In a terminal emulator like konsole or gnome-terminal, you should to set a 256 color setting for vim.

:set  t_Co=256

After that you can to change your background.

How to set up file permissions for Laravel?

The Laravel 5.4 docs say:

After installing Laravel, you may need to configure some permissions. Directories within the storage and the bootstrap/cache directories should be writable by your web server or Laravel will not run. If you are using the Homestead virtual machine, these permissions should already be set.

There are a lot of answers on this page that mention using 777 permissions. Don't do that. You'd be exposing yourself to hackers.

Instead, follow the suggestions by others about how to set permissions of 755 (or more restrictive). You may need to figure out which user your app is running as by running whoami in the terminal and then change ownership of certain directories using chown -R.

If you do not have permission to use sudo as so many other answers require...

Your server is probably a shared host such as Cloudways.

(In my case, I had cloned my Laravel application into a second Cloudways server of mine, and it wasn't completely working because the permissions of the storage and bootstrap/cache directories were messed up.)

I needed to use:

Cloudways Platform > Server > Application Settings > Reset Permission

Then I could run php artisan cache:clear in the terminal.

PHP header() redirect with POST variables

It would be beneficial to verify the form's data before sending it via POST. You should create a JavaScript function to check the form for errors and then send the form. This would prevent the data from being sent over and over again, possibly slowing the browser and using transfer volume on the server.

Edit:

If security is a concern, performing an AJAX request to verify the data would be the best way. The response from the AJAX request would determine whether the form should be submitted.

Error "The goal you specified requires a project to execute but there is no POM in this directory" after executing maven command

1.create a lib folder in your project file,

2.copy your jarFiles to the lib folder

3.right click on to your jarFile go to build path>Add to build path (now your jar file is part of your refrerenced libraries )

4.open command prompt and navigate to your project directory and write

mvn install: install-file "-Dfile=<yourJarFileName>.jar" "-DgroupId=<yourGroupID>" "-DartifactId=<yourArtifactId>" "-Dversion=<yourVersion>" "-Dpackaging=jar" 

6.Rebuild your local repository index by opening in eclipse- go to window>show view>other>maven>maven Repositories. Right click on local Repositores and hit "RebuildIndex"

5.open your pom.xml file and add your dependency

    <dependency>
        <groupId><yourGroupID></groupId>
        <artifactId><yourArtifactId></artifactId>
        <version><yourVersion></version>
    </dependency>

and run

mvn clean
mvn compile 
mvn test 

How To Convert A Number To an ASCII Character?

To get ascii to a number, you would just cast your char value into an integer.

char ascii = 'a'
int value = (int)ascii

Variable value will now have 97 which corresponds to the value of that ascii character

(Use this link for reference) http://www.asciitable.com/index/asciifull.gif

php: check if an array has duplicates

$hasDuplicates = count($array) > count(array_unique($array)); 

Will be true if duplicates, or false if no duplicates.

node.js: read a text file into an array. (Each line an item in the array.)

This is a variation on the answer above by @mtomis.

It creates a stream of lines. It emits 'data' and 'end' events, allowing you to handle the end of the stream.

var events = require('events');

var LineStream = function (input) {
    var remaining = '';

    input.on('data', function (data) {
        remaining += data;
        var index = remaining.indexOf('\n');
        var last = 0;
        while (index > -1) {
            var line = remaining.substring(last, index);
            last = index + 1;
            this.emit('data', line);
            index = remaining.indexOf('\n', last);
        }
        remaining = remaining.substring(last);
    }.bind(this));

    input.on('end', function() {
        if (remaining.length > 0) {
            this.emit('data', remaining);
        }
        this.emit('end');
    }.bind(this));
}

LineStream.prototype = new events.EventEmitter;

Use it as a wrapper:

var lineInput = new LineStream(input);

lineInput.on('data', function (line) {
    // handle line
});

lineInput.on('end', function() {
    // wrap it up
});

Declare variable MySQL trigger

All DECLAREs need to be at the top. ie.

delimiter //

CREATE TRIGGER pgl_new_user 
AFTER INSERT ON users FOR EACH ROW
BEGIN
    DECLARE m_user_team_id integer;
    DECLARE m_projects_id integer;
    DECLARE cur CURSOR FOR SELECT project_id FROM user_team_project_relationships WHERE user_team_id = m_user_team_id;

    SET @m_user_team_id := (SELECT id FROM user_teams WHERE name = "pgl_reporters");

    OPEN cur;
        ins_loop: LOOP
            FETCH cur INTO m_projects_id;
            IF done THEN
                LEAVE ins_loop;
            END IF;
            INSERT INTO users_projects (user_id, project_id, created_at, updated_at, project_access) 
            VALUES (NEW.id, m_projects_id, now(), now(), 20);
        END LOOP;
    CLOSE cur;
END//

How do I free memory in C?

You have to free() the allocated memory in exact reverse order of how it was allocated using malloc().

Note that You should free the memory only after you are done with your usage of the allocated pointers.

memory allocation for 1D arrays:

    buffer = malloc(num_items*sizeof(double));

memory deallocation for 1D arrays:

    free(buffer);

memory allocation for 2D arrays:

    double **cross_norm=(double**)malloc(150 * sizeof(double *));
    for(i=0; i<150;i++)
    {
        cross_norm[i]=(double*)malloc(num_items*sizeof(double));
    }

memory deallocation for 2D arrays:

    for(i=0; i<150;i++)
    {
        free(cross_norm[i]);
    }

    free(cross_norm);

Trigger standard HTML5 validation (form) without using submit button?

As stated in the other answers use event.preventDefault() to prevent form submitting.

To check the form before I wrote a little jQuery function you may use (note that the element needs an ID!)

(function( $ ){
    $.fn.isValid = function() {
        return document.getElementById(this[0].id).checkValidity();
    };
})( jQuery );

example usage

 $('#submitBtn').click( function(e){

        if ($('#registerForm').isValid()){
            // do the request
        } else {
            e.preventDefault();
        }
    });

Programmatically find the number of cores on a machine

you can use WMI in .net too but you're then dependent on the wmi service running etc. Sometimes it works locally, but then fail when the same code is run on servers. I believe that's a namespace issue, related to the "names" whose values you're reading.

How can I define an array of objects?

What you really want may simply be an enumeration

If you're looking for something that behaves like an enumeration (because I see you are defining an object and attaching a sequential ID 0, 1, 2 and contains a name field that you don't want to misspell (e.g. name vs naaame), you're better off defining an enumeration because the sequential ID is taken care of automatically, and provides type verification for you out of the box.

enum TestStatus {
    Available,     // 0
    Ready,         // 1
    Started,       // 2
}

class Test {
    status: TestStatus
}

var test = new Test();
test.status = TestStatus.Available; // type and spelling is checked for you,
                                    // and the sequence ID is automatic

The values above will be automatically mapped, e.g. "0" for "Available", and you can access them using TestStatus.Available. And Typescript will enforce the type when you pass those around.

If you insist on defining a new type as an array of your custom type

You wanted an array of objects, (not exactly an object with keys "0", "1" and "2"), so let's define the type of the object, first, then a type of a containing array.

class TestStatus {
    id: number
    name: string

    constructor(id, name){
        this.id = id;
        this.name = name;
    }
}

type Statuses = Array<TestStatus>;

var statuses: Statuses = [
    new TestStatus(0, "Available"),
    new TestStatus(1, "Ready"),
    new TestStatus(2, "Started")
]

Remove elements from collection while iterating

why not this?

for( int i = 0; i < Foo.size(); i++ )
{
   if( Foo.get(i).equals( some test ) )
   {
      Foo.remove(i);
   }
}

And if it's a map, not a list, you can use keyset()

How do I change data-type of pandas data frame to string with a defined format?

If you could reload this, you might be able to use dtypes argument.

pd.read_csv(..., dtype={'COL_NAME':'str'})

Server configuration by allow_url_fopen=0 in

Using relative instead of absolute file path solved the problem for me. I had the same issue and setting allow_url_fopen=on did not help. This means for instance :

use $file="folder/file.ext"; instead of $file="https://website.com/folder/file.ext"; in

$f=fopen($file,"r+");

Test if a variable is a list or tuple

Document the argument as needing to be a sequence, and use it as a sequence. Don't check the type.

Pointer to a string in C?

The string is basically bounded from the place where it is pointed to (char *ptrChar;), to the null character (\0).

The char *ptrChar; actually points to the beginning of the string (char array), and thus that is the pointer to that string, so when you do like ptrChar[x] for example, you actually access the memory location x times after the beginning of the char (aka from where ptrChar is pointing to).

Are PostgreSQL column names case-sensitive?

The column names which are mixed case or uppercase have to be double quoted in PostgresQL. So best convention will be to follow all small case with underscore.

How to specify a port number in SQL Server connection string?

For JDBC the proper format is slightly different and as follows:

jdbc:microsoft:sqlserver://mycomputer.test.xxx.com:49843

Note the colon instead of the comma.

Laravel where on relationship object

The correct syntax to do this on your relations is:

Event::whereHas('participants', function ($query) {
    return $query->where('IDUser', '=', 1);
})->get();

Read more at https://laravel.com/docs/5.8/eloquent-relationships#eager-loading

NSUserDefaults - How to tell if a key exists

The objectForKey: method will return nil if the value does not exist. Here's a simple IF / THEN test that will tell you if the value is nil:

if([[NSUserDefaults standardUserDefaults] objectForKey:@"YOUR_KEY"] != nil) {
    ...
}

Text that shows an underline on hover

You just need to specify text-decoration: underline; with pseudo-class :hover.

HTML

<span class="underline-on-hover">Hello world</span>

CSS

.underline-on-hover:hover {
    text-decoration: underline;
}

I have whipped up a working Code Pen Demo.

JS map return object

You're very close already, you just need to return the new object that you want. In this case, the same one except with the launches value incremented by 10:

_x000D_
_x000D_
var rockets = [_x000D_
    { country:'Russia', launches:32 },_x000D_
    { country:'US', launches:23 },_x000D_
    { country:'China', launches:16 },_x000D_
    { country:'Europe(ESA)', launches:7 },_x000D_
    { country:'India', launches:4 },_x000D_
    { country:'Japan', launches:3 }_x000D_
];_x000D_
_x000D_
var launchOptimistic = rockets.map(function(elem) {_x000D_
  return {_x000D_
    country: elem.country,_x000D_
    launches: elem.launches+10,_x000D_
  } _x000D_
});_x000D_
_x000D_
console.log(launchOptimistic);
_x000D_
_x000D_
_x000D_

Is it possible to make abstract classes in Python?

Use the abc module to create abstract classes. Use the abstractmethod decorator to declare a method abstract, and declare a class abstract using one of three ways, depending upon your Python version.

In Python 3.4 and above, you can inherit from ABC. In earlier versions of Python, you need to specify your class's metaclass as ABCMeta. Specifying the metaclass has different syntax in Python 3 and Python 2. The three possibilities are shown below:

# Python 3.4+
from abc import ABC, abstractmethod
class Abstract(ABC):
    @abstractmethod
    def foo(self):
        pass
# Python 3.0+
from abc import ABCMeta, abstractmethod
class Abstract(metaclass=ABCMeta):
    @abstractmethod
    def foo(self):
        pass
# Python 2
from abc import ABCMeta, abstractmethod
class Abstract:
    __metaclass__ = ABCMeta

    @abstractmethod
    def foo(self):
        pass

Whichever way you use, you won't be able to instantiate an abstract class that has abstract methods, but will be able to instantiate a subclass that provides concrete definitions of those methods:

>>> Abstract()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Abstract with abstract methods foo
>>> class StillAbstract(Abstract):
...     pass
... 
>>> StillAbstract()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class StillAbstract with abstract methods foo
>>> class Concrete(Abstract):
...     def foo(self):
...         print('Hello, World')
... 
>>> Concrete()
<__main__.Concrete object at 0x7fc935d28898>

How to disable registration new users in Laravel

All I did was replace register blade code with login blade code. That way register still goes to login.

resources/views/auth/register.blade.php is replaced with resources/views/auth/login.blade.php

How to crop an image using C#?

This is another way. In my case I have:

  • 2 numeric updown controls (called LeftMargin and TopMargin)
  • 1 Picture box (pictureBox1)
  • 1 button that I called generate
  • 1 image on C:\imagenes\myImage.gif

Inside the button I have this code:

Image myImage = Image.FromFile(@"C:\imagenes\myImage.gif");
Bitmap croppedBitmap = new Bitmap(myImage);
croppedBitmap = croppedBitmap.Clone(
            new Rectangle(
                (int)LeftMargin.Value, (int)TopMargin.Value,
                myImage.Width - (int)LeftMargin.Value,
                myImage.Height - (int)TopMargin.Value),
            System.Drawing.Imaging.PixelFormat.DontCare);
pictureBox1.Image = croppedBitmap;

I tried it in Visual studio 2012 using C#. I found this solution from this page

Inserting an image with PHP and FPDF

$image="img_name.jpg";
$pdf =new FPDF();
$pdf-> AddPage();
$pdf-> SetFont("Arial","B",10);
$pdf-> Image('profileimage/'.$image,100,15,35,35);

showing that a date is greater than current date

Select * from table where date > 'Today's date(mm/dd/yyyy)'

You can also add time in the single quotes(00:00:00AM)

For example:

Select * from Receipts where Sales_date > '08/28/2014 11:59:59PM'

How can I check for Python version in a program that uses new language features?

Have a wrapper around your program that does the following.

import sys

req_version = (2,5)
cur_version = sys.version_info

if cur_version >= req_version:
   import myApp
   myApp.run()
else:
   print "Your Python interpreter is too old. Please consider upgrading."

You can also consider using sys.version(), if you plan to encounter people who are using pre-2.0 Python interpreters, but then you have some regular expressions to do.

And there might be more elegant ways to do this.

Fixing Xcode 9 issue: "iPhone is busy: Preparing debugger support for iPhone"

In my case, iTunes was open, so

1 - open iTunes

2 - access you phone

enter image description here

3 - click to disconnect your phone enter image description here

Now the device is ready on XCode

enter image description here

Hope it helps....

How do I modify the URL without reloading the page?

Any changes of the loction (either window.location or document.location) will cause a request on that new URL, if you’re not just changing the URL fragment. If you change the URL, you change the URL.

Use server-side URL rewrite techniques like Apache’s mod_rewrite if you don’t like the URLs you are currently using.

How do I access named capturing groups in a .NET Regex?

You specify the named capture group string by passing it to the indexer of the Groups property of a resulting Match object.

Here is a small example:

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        String sample = "hello-world-";
        Regex regex = new Regex("-(?<test>[^-]*)-");

        Match match = regex.Match(sample);

        if (match.Success)
        {
            Console.WriteLine(match.Groups["test"].Value);
        }
    }
}

How to terminate process from Python using pid?

Using the awesome psutil library it's pretty simple:

p = psutil.Process(pid)
p.terminate()  #or p.kill()

If you don't want to install a new library, you can use the os module:

import os
import signal

os.kill(pid, signal.SIGTERM) #or signal.SIGKILL 

See also the os.kill documentation.


If you are interested in starting the command python StripCore.py if it is not running, and killing it otherwise, you can use psutil to do this reliably.

Something like:

import psutil
from subprocess import Popen

for process in psutil.process_iter():
    if process.cmdline() == ['python', 'StripCore.py']:
        print('Process found. Terminating it.')
        process.terminate()
        break
else:
    print('Process not found: starting it.')
    Popen(['python', 'StripCore.py'])

Sample run:

$python test_strip.py   #test_strip.py contains the code above
Process not found: starting it.
$python test_strip.py 
Process found. Terminating it.
$python test_strip.py 
Process not found: starting it.
$killall python
$python test_strip.py 
Process not found: starting it.
$python test_strip.py 
Process found. Terminating it.
$python test_strip.py 
Process not found: starting it.

Note: In previous psutil versions cmdline was an attribute instead of a method.

Can one do a for each loop in java in reverse order?

A work Around :

Collections.reverse(stringList).forEach(str -> ...);

Or with guava :

Lists.reverse(stringList).forEach(str -> ...);

How to convert minutes to hours/minutes and add various time values together using jQuery?

I took the liberty of modifying ConorLuddy's answer to address both 24 hour time and 12 hour time.

function minutesToHHMM (mins, twentyFour = false) {
  let h = Math.floor(mins / 60);
  let m = mins % 60;
  m = m < 10 ? '0' + m : m;

  if (twentyFour) {
    h = h < 10 ? '0' + h : h;
    return `${h}:${m}`;
  } else {
    let a = 'am';
    if (h >= 12) a = 'pm';
    if (h > 12) h = h - 12;
    return `${h}:${m} ${a}`;
  }
}

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

This error comes when there is error in your query syntax check field names table name, mean check your query syntax.

Android Studio rendering problems

  1. Open AndroidManifest.xml
  2. Change:

    android:theme="@style/AppTheme"

    to something like:

    android:theme="@style/Theme.AppCompat.Light"
  3. Hit "refresh" button in the "Previev" tab.

Javascript loading CSV file into an array

I highly recommend looking into this plugin:

http://github.com/evanplaice/jquery-csv/

I used this for a project handling large CSV files and it handles parsing a CSV into an array quite well. You can use this to call a local file that you specify in your code, also, so you are not dependent on a file upload.

Once you include the plugin above, you can essentially parse the CSV using the following:

$.ajax({
    url: "pathto/filename.csv",
    async: false,
    success: function (csvd) {
        data = $.csv.toArrays(csvd);
    },
    dataType: "text",
    complete: function () {
        // call a function on complete 
    }
});

Everything will then live in the array data for you to manipulate as you need. I can provide further examples for handling the array data if you need.

There are a lot of great examples available on the plugin page to do a variety of things, too.

Deleting rows with MySQL LEFT JOIN

Try this:

DELETE `deadline`
FROM `deadline`
INNER JOIN `job` ON `deadline`.`job_id` = `job`.`id`
WHERE `job`.`id` = 123

Test if a string contains a word in PHP?

<?php
//  Use this function and Pass Mixed string and what you want to search in mixed string.
//  For Example :
    $mixedStr = "hello world. This is john duvey";
    $searchStr= "john";

    if(strpos($mixedStr,$searchStr)) {
      echo "Your string here";
    }else {
      echo "String not here";
    }

How to concatenate strings in twig

Whenever you need to use a filter with a concatenated string (or a basic math operation) you should wrap it with ()'s. Eg.:

{{ ('http://' ~ app.request.host) | url_encode }}

How to declare strings in C

This link should satisfy your curiosity.

Basically (forgetting your third example which is bad), the different between 1 and 2 is that 1 allocates space for a pointer to the array.

But in the code, you can manipulate them as pointers all the same -- only thing, you cannot reallocate the second.

Python 3 - Encode/Decode vs Bytes/Str

To add to Lennart Regebro's answer There is even the third way that can be used:

encoded3 = str.encode(original, 'utf-8')
print(encoded3)

Anyway, it is actually exactly the same as the first approach. It may also look that the second way is a syntactic sugar for the third approach.


A programming language is a means to express abstract ideas formally, to be executed by the machine. A programming language is considered good if it contains constructs that one needs. Python is a hybrid language -- i.e. more natural and more versatile than pure OO or pure procedural languages. Sometimes functions are more appropriate than the object methods, sometimes the reverse is true. It depends on mental picture of the solved problem.

Anyway, the feature mentioned in the question is probably a by-product of the language implementation/design. In my opinion, this is a nice example that show the alternative thinking about technically the same thing.

In other words, calling an object method means thinking in terms "let the object gives me the wanted result". Calling a function as the alternative means "let the outer code processes the passed argument and extracts the wanted value".

The first approach emphasizes the ability of the object to do the task on its own, the second approach emphasizes the ability of an separate algoritm to extract the data. Sometimes, the separate code may be that much special that it is not wise to add it as a general method to the class of the object.

How to check for the type of a template parameter?

std::is_same() is only available since C++11. For pre-C++11 you can use typeid():

template <typename T>
void foo()
{
    if (typeid(T) == typeid(animal)) { /* ... */ }
}

Entity Framework The underlying provider failed on Open

Seems like a connection issue. You can use the Data link properties to find if the connection is fine. Do the following:

  1. Create a blank notepad and rename it to "X.UDL"
  2. Double click to open it
  3. Under connections tab choose the server name/enter the name use the correct credentials and DB
  4. Click OK to save it.

Now open the file in Notepad and compare the connection string properties.

Possible to restore a backup of SQL Server 2014 on SQL Server 2012?

You CANNOT do this - you cannot attach/detach or backup/restore a database from a newer version of SQL Server down to an older version - the internal file structures are just too different to support backwards compatibility. This is still true in SQL Server 2014 - you cannot restore a 2014 backup on anything other than another 2014 box (or something newer).

You can either get around this problem by

  • using the same version of SQL Server on all your machines - then you can easily backup/restore databases between instances

  • otherwise you can create the database scripts for both structure (tables, view, stored procedures etc.) and for contents (the actual data contained in the tables) either in SQL Server Management Studio (Tasks > Generate Scripts) or using a third-party tool

  • or you can use a third-party tool like Red-Gate's SQL Compare and SQL Data Compare to do "diffing" between your source and target, generate update scripts from those differences, and then execute those scripts on the target platform; this works across different SQL Server versions.

The compatibility mode setting just controls what T-SQL features are available to you - which can help to prevent accidentally using new features not available in other servers. But it does NOT change the internal file format for the .mdf files - this is NOT a solution for that particular problem - there is no solution for restoring a backup from a newer version of SQL Server on an older instance.

Multiple INNER JOIN SQL ACCESS

Access requires parentheses in the FROM clause for queries which include more than one join. Try it this way ...

FROM
    ((tbl_employee
    INNER JOIN tbl_netpay
    ON tbl_employee.emp_id = tbl_netpay.emp_id)
    INNER JOIN tbl_gross
    ON tbl_employee.emp_id = tbl_gross.emp_ID)
    INNER JOIN tbl_tax
    ON tbl_employee.emp_id = tbl_tax.emp_ID;

If possible, use the Access query designer to set up your joins. The designer will add parentheses as required to keep the db engine happy.

Angularjs: Error: [ng:areq] Argument 'HomeController' is not a function, got undefined

I was getting the error because i had added the controller script before the script where i had defined the corresponding module in the app. First add the script

<script src = "(path of module.js file)"></script>

Then only add

<script src = "(path of controller.js file)"></script>

In the main file.

java get file size efficiently

Actually, I think the "ls" may be faster. There are definitely some issues in Java dealing with getting File info. Unfortunately there is no equivalent safe method of recursive ls for Windows. (cmd.exe's DIR /S can get confused and generate errors in infinite loops)

On XP, accessing a server on the LAN, it takes me 5 seconds in Windows to get the count of the files in a folder (33,000), and the total size.

When I iterate recursively through this in Java, it takes me over 5 minutes. I started measuring the time it takes to do file.length(), file.lastModified(), and file.toURI() and what I found is that 99% of my time is taken by those 3 calls. The 3 calls I actually need to do...

The difference for 1000 files is 15ms local versus 1800ms on server. The server path scanning in Java is ridiculously slow. If the native OS can be fast at scanning that same folder, why can't Java?

As a more complete test, I used WineMerge on XP to compare the modified date, and size of the files on the server versus the files locally. This was iterating over the entire directory tree of 33,000 files in each folder. Total time, 7 seconds. java: over 5 minutes.

So the original statement and question from the OP is true, and valid. Its less noticeable when dealing with a local file system. Doing a local compare of the folder with 33,000 items takes 3 seconds in WinMerge, and takes 32 seconds locally in Java. So again, java versus native is a 10x slowdown in these rudimentary tests.

Java 1.6.0_22 (latest), Gigabit LAN, and network connections, ping is less than 1ms (both in the same switch)

Java is slow.

How do I bind to list of checkbox values with AngularJS?

Try my baby:

**

myApp.filter('inputSelected', function(){
  return function(formData){
    var keyArr = [];
    var word = [];
    Object.keys(formData).forEach(function(key){
    if (formData[key]){
        var keyCap = key.charAt(0).toUpperCase() + key.slice(1);
      for (var char = 0; char<keyCap.length; char++ ) {
        if (keyCap[char] == keyCap[char].toUpperCase()){
          var spacedLetter = ' '+ keyCap[char];
          word.push(spacedLetter);
        }
        else {
          word.push(keyCap[char]);
        }
      }
    }
    keyArr.push(word.join(''))
    word = [];
    })
    return keyArr.toString();
  }
})

**

Then for any ng-model with checkboxes, it will return a string of all the input you selected:

<label for="Heard about ITN">How did you hear about ITN?: *</label><br>
<label class="checkbox-inline"><input ng-model="formData.heardAboutItn.brotherOrSister" type="checkbox" >Brother or Sister</label>
<label class="checkbox-inline"><input ng-model="formData.heardAboutItn.friendOrAcquaintance" type="checkbox" >Friend or Acquaintance</label>


{{formData.heardAboutItn | inputSelected }}

//returns Brother or Sister, Friend or Acquaintance

Difference between break and continue statement

The break statement breaks out of the loop (the next statement to be executed is the first one after the closing brace), while continue starts the loop over at the next iteration.

<img>: Unsafe value used in a resource URL context

I'm using rc.4 and this method works for ES2015(ES6):

import {DomSanitizationService} from '@angular/platform-browser';

@Component({
  templateUrl: 'build/pages/veeu/veeu.html'
})
export class VeeUPage {
  static get parameters() {
    return [NavController, App, MenuController, DomSanitizationService];
  }

  constructor(nav, app, menu, sanitizer) {

    this.app = app;
    this.nav = nav;
    this.menu = menu;
    this.sanitizer = sanitizer;    
  }

  photoURL() {
    return this.sanitizer.bypassSecurityTrustUrl(this.mediaItems[1].url);
  }
}

In the HTML:

<iframe [src]='photoURL()' width="640" height="360" frameborder="0"
    webkitallowfullscreen mozallowfullscreen allowfullscreen>
</iframe>

Using a function will ensure that the value doesn't change after you sanitize it. Also be aware that the sanitization function you use depends on the context.

For images, bypassSecurityTrustUrl will work but for other uses you need to refer to the documentation:

https://angular.io/docs/ts/latest/api/platform-browser/index/DomSanitizer-class.html

I want to declare an empty array in java and then I want do update it but the code is not working

So the issue is in your array declaration you are declaring an empty array with the empty curly braces{} instead of an array that allows slots.

Roughly speaking, there can be three types of inputs :

 1. int array[] = null; #Does not point to any memory locations so is a null arrau
 2. int array[] = {) which is sort of equivalent to int array[] = new int[0];
 3. int array[] = new int[n] where n is some number indicating the number of 
memory locations in the array

Set up Python 3 build system with Sublime Text 3

And to add on to the already solved problem, I had installed Portable Scientific Python on my flash drive E: which on another computer changed to D:, I would get the error "The system cannot find the file specified". So I used parent directory to define the path, like this:

From this:

{
    "cmd": ["E:/WPy64-3720/python-3.7.2.amd64/python.exe", "$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python"
}

To this:

{
    "cmd": ["../../../../WPy64-3720/python-3.7.2.amd64/python.exe","$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python"
}

You can modify depending on where your python is installed your python.

check if directory exists and delete in one command unix

Try:

bash -c '[ -d my_mystery_dirname ] && run_this_command'

This will work if you can run bash on the remote machine....

In bash, [ -d something ] checks if there is directory called 'something', returning a success code if it exists and is a directory. Chaining commands with && runs the second command only if the first one succeeded. So [ -d somedir ] && command runs the command only if the directory exists.

Delegation: EventEmitter or Observable in Angular

Breaking news: I've added another answer that uses an Observable rather than an EventEmitter. I recommend that answer over this one. And actually, using an EventEmitter in a service is bad practice.


Original answer: (don't do this)

Put the EventEmitter into a service, which allows the ObservingComponent to directly subscribe (and unsubscribe) to the event:

import {EventEmitter} from 'angular2/core';

export class NavService {
  navchange: EventEmitter<number> = new EventEmitter();
  constructor() {}
  emit(number) {
    this.navchange.emit(number);
  }
  subscribe(component, callback) {
    // set 'this' to component when callback is called
    return this.navchange.subscribe(data => call.callback(component, data));
  }
}

@Component({
  selector: 'obs-comp',
  template: 'obs component, index: {{index}}'
})
export class ObservingComponent {
  item: number;
  subscription: any;
  constructor(private navService:NavService) {
   this.subscription = this.navService.subscribe(this, this.selectedNavItem);
  }
  selectedNavItem(item: number) {
    console.log('item index changed!', item);
    this.item = item;
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

@Component({
  selector: 'my-nav',
  template:`
    <div class="nav-item" (click)="selectedNavItem(1)">item 1 (click me)</div>
  `,
})
export class Navigation {
  constructor(private navService:NavService) {}
  selectedNavItem(item: number) {
    console.log('selected nav item ' + item);
    this.navService.emit(item);
  }
}

If you try the Plunker, there are a few things I don't like about this approach:

  • ObservingComponent needs to unsubscribe when it is destroyed
  • we have to pass the component to subscribe() so that the proper this is set when the callback is called

Update: An alternative that solves the 2nd bullet is to have the ObservingComponent directly subscribe to the navchange EventEmitter property:

constructor(private navService:NavService) {
   this.subscription = this.navService.navchange.subscribe(data =>
     this.selectedNavItem(data));
}

If we subscribe directly, then we wouldn't need the subscribe() method on the NavService.

To make the NavService slightly more encapsulated, you could add a getNavChangeEmitter() method and use that:

getNavChangeEmitter() { return this.navchange; }  // in NavService

constructor(private navService:NavService) {  // in ObservingComponent
   this.subscription = this.navService.getNavChangeEmitter().subscribe(data =>
     this.selectedNavItem(data));
}

Using VBA code, how to export Excel worksheets as image in Excel 2003?

do you want to try the below code I found on the internet somewhere many moons ago and used.

It uses the Export function of the Chart object along with the CopyPicture method of the Range object.

References:

How can I get the height and width of an uiimage?

let imageView: UIImageView = //this is your existing imageView

let imageViewHeight: CGFloat = imageView.frame.height

let imageViewWidth: CGFloat = imageView.frame.width

Apache - MySQL Service detected with wrong path. / Ports already in use

  • Ok it's very easy actually to solve this...most of you who are presented with this problem probably don't even realize you don't have the full software yet installed :) I tried looking online with little success except some1 mentioned you need to look for those services running already. Forexample problem with filezilla you look in task manager for filezilla and you stop the process then you click the X in the xampp control pannel to install filezilla and then click run and it should start the service normally showing you a green lite with a check mark.

  • Same goes for mysql issues.

  • As for the apache problem, it usualy is a problem with the port being overtaken by skype or some other program, but you can find info how to solve that on the net easily :)

How can I compile LaTeX in UTF8?

Convert your document to utf8. LaTeX just reads your text as it is. If you want to use the utf8 input encoding, your document has to be encoded in utf8. This can usually be set by the editor. There is also the program iconv that is useful for converting files from iso encodings to utf.

In the end, you'll have to use an editor that is capable of supporting utf. (I have no idea about the status of utf support on windows, but any reasonable editor on linux should be fine).

How to Uninstall RVM?

It’s easy; just do the following:

rvm implode

or

rm -rf ~/.rvm

And don’t forget to remove the script calls in the following files:

  • ~/.bashrc
  • ~/.bash_profile
  • ~/.profile

And maybe others depending on whatever shell you’re using.

Python class returning value

the worked proposition for me is __call__ on class who create list of little numbers:

import itertools
    
class SmallNumbers:
    def __init__(self, how_much):
        self.how_much = int(how_much)
        self.work_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
        self.generated_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
        start = 10
        end = 100
        for cmb in range(2, len(str(self.how_much)) + 1):
            self.ListOfCombinations(is_upper_then=start, is_under_then=end, combinations=cmb)
            start *= 10
            end *= 10

    def __call__(self, number, *args, **kwargs):
        return self.generated_list[number]

    def ListOfCombinations(self, is_upper_then, is_under_then, combinations):
        multi_work_list = eval(str('self.work_list,') * combinations)
        nbr = 0
        for subset in itertools.product(*multi_work_list):
            if is_upper_then <= nbr < is_under_then:
                self.generated_list.append(''.join(subset))
                if self.how_much == nbr:
                    break
            nbr += 1

and to run it:

if __name__ == '__main__':
        sm = SmallNumbers(56)
        print(sm.generated_list)
        print(sm.generated_list[34], sm.generated_list[27], sm.generated_list[10])
        print('The Best', sm(15), sm(55), sm(49), sm(0))

result

['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56']
34 27 10
The Best 15 55 49 0

TypeError: object of type 'int' has no len() error assistance needed

Abstract:

The reason why you are getting this error message is because you are trying to call a method on an int type of a variable. This would work if would have called len() function on a list type of a variable. Let's examin the two cases:

Fail:

num = 10

print(len(num))

The above will produce an error similar to yours due to calling len() function on an int type of a variable;

Success:

data = [0, 4, 8, 9, 12]

print(len(data))

The above will work since you are calling a function on a list type of a variable;

How do I use a pipe to redirect the output of one command to the input of another?

Not sure if you are coding these programs, but this is a simple example of how you'd do it.

program1.c

#include <stdio.h>
int main (int argc, char * argv[] ) {
    printf("%s", argv[1]); 
    return 0;
}

rgx.cpp

#include <cstdio>
#include <regex>
#include <iostream>
using namespace std;
int main (int argc, char * argv[] ) {
    char input[200];
    fgets(input,200,stdin);
    string s(input)
    smatch m;
    string reg_exp(argv[1]);
    regex e(reg_exp);
    while (regex_search (s,m,e)) {
      for (auto x:m) cout << x << " ";
      cout << endl;
      s = m.suffix().str();
    }
    return 0;
}

Compile both then run program1.exe "this subject has a submarine as a subsequence" | rgx.exe "\b(sub)([^ ]*)"

The | operator simply redirects the output of program1's printf operation from the stdout stream to the stdin stream whereby it's sitting there waiting for rgx.exe to pick up.

How to display an image stored as byte array in HTML/JavaScript?

Try putting this HTML snippet into your served document:

<img id="ItemPreview" src="">

Then, on JavaScript side, you can dynamically modify image's src attribute with so-called Data URL.

document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;

Alternatively, using jQuery:

$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);

This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..." part) in the URL accordingly.

Similar Questions:

Copy multiple files in Python

Here is another example of a recursive copy function that lets you copy the contents of the directory (including sub-directories) one file at a time, which I used to solve this problem.

import os
import shutil

def recursive_copy(src, dest):
    """
    Copy each file from src dir to dest dir, including sub-directories.
    """
    for item in os.listdir(src):
        file_path = os.path.join(src, item)

        # if item is a file, copy it
        if os.path.isfile(file_path):
            shutil.copy(file_path, dest)

        # else if item is a folder, recurse 
        elif os.path.isdir(file_path):
            new_dest = os.path.join(dest, item)
            os.mkdir(new_dest)
            recursive_copy(file_path, new_dest)

EDIT: If you can, definitely just use shutil.copytree(src, dest). This requires that that destination folder does not already exist though. If you need to copy files into an existing folder, the above method works well!

How do I open workbook programmatically as read-only?

Check out the language reference:

http://msdn.microsoft.com/en-us/library/aa195811(office.11).aspx

expression.Open(FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)

Count if two criteria match - EXCEL formula

Add the sheet name infront of the cell, e.g.:

=COUNTIFS(stock!A:A,"M",stock!C:C,"Yes")

Assumes the sheet name is "stock"

Can't install Scipy through pip

  1. Download SciPy from http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy
  2. Go into the directory the downloaded file is in and pip install the file.
  3. Go to python shell, run import scipy; it worked for me with no errors.

Determine device (iPhone, iPod Touch) with iOS

NSString *deviceType = [UIDevice currentDevice].model;

Check if xdebug is working

If you are using Eclipse then please note that while running on XDebug mode the magic constant __FILE__ will always be evaluated to:

xdebug://debug-eval

So the following check will return true if your session is under XDebug:

$is_xdebug = false !== strpos(__FILE__,'xdebug'); // true while on XDebug

How to change btn color in Bootstrap

The simplest way is to:

  1. intercept every button state

  2. add !important to override the states

    .btn-primary:hover,
    .btn-primary:active,
    .btn-primary:visited,
    .btn-primary:focus {
      background-color: black !important;
      border-color: black !important;
    }

OR the more practical UI way is to make the hover state of the button darker than the original state. Just use the CSS snippet below:

.btn-primary {
  background-color: Blue !important;
  border-color: Blue !important;
}
.btn-primary:hover,
.btn-primary:active,
.btn-primary:visited,
.btn-primary:focus {
  background-color: DarkBlue !important;
  border-color: DarkBlue !important;
}

to_string not declared in scope

This error, as correctly identified above, is due to the compiler not using c++11 or above standard. This answer is for Windows 10.

For c++11 and above standard support in codeblocks version 17:

  1. Click settings in the toolbar.

  2. A drop-down menu appears. Select compiler option.

  3. Choose Global Compiler Settings.

  4. In the toolbar in this new window in second section, choose compiler settings.

  5. Then choose compiler flags option in below toolbar.

  6. Unfold general tab. Check the C++ standard that you want your compiler to follow.

  7. Click OK.

For those who are trying to get C++11 support in Sublime text.

  1. Download mingw compiler version 7 or above. In versions below this, the default c++ standard used is c++98 whereas in versions higher than 7, the default standard used is c++11.

  2. Copy the folder in main C drive. It should not be inside any other folder in C drive.

  3. Rename the folder as MinGW. This name is case insensitive, so it should any variation of mingw and must not include any other characters in the name.

  4. Then go to environment variables and edit the path variable. Add this "C:\mingw\bin" and click OK.

  5. You can check the version of g++ in cmd by typing g++ -v.

  6. This should be sufficient to enable c++11 in sublime text.

If you want to take inputs and outputs as well from input files for competitive programming purposes, then follow this link.

Visual Studio setup problem - 'A problem has been encountered while loading the setup components. Canceling setup.'

Uninstall hotfixes installed in related to vs2008 and then try again. It worked for me and hopefully it will for you as well.

Thanks, Zelalem

How to remove specific value from array using jQuery

I had a similar task where I needed to delete multiple objects at once based on a property of the objects in the array.

So after a few iterations I end up with:

list = $.grep(list, function (o) { return !o.IsDeleted });

Android ListView Divider

Folks, here's why you should use 1px instead of 1dp or 1dip: if you specify 1dp or 1dip, Android will scale that down. On a 120dpi device, that becomes something like 0.75px translated, which rounds to 0. On some devices, that translates to 2-3 pixels, and it usually looks ugly or sloppy

For dividers, 1px is the correct height if you want a 1 pixel divider and is one of the exceptions for the "everything should be dip" rule. It'll be 1 pixel on all screens. Plus, 1px usually looks better on hdpi and above screens

"It's not 2012 anymore" edit: you may have to switch over to dp/dip starting at a certain screen density

How to ignore SSL certificate errors in Apache HttpClient 4.0

We are using HTTPClient 4.3.5 and we tried almost all solutions exist on the stackoverflow but nothing, After thinking and figuring out the problem, we come to the following code which works perfectly, just add it before creating HttpClient instance.

some method to call when making post requests....

SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    });

    SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(builder.build(),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslSF).build();
    HttpPost postRequest = new HttpPost(url);

continue your request in the normal form