Programs & Examples On #Happstack

Happstack is a fast and flexible Haskell web framework.

Saving image to file

You can save image , save the file in your current directory application and move the file to any directory .

 Bitmap btm = new Bitmap(image.width,image.height);
    Image img = btm;
                        img.Save(@"img_" + x + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                        FileInfo img__ = new FileInfo(@"img_" + x + ".jpg");
                        img__.MoveTo("myVideo\\img_" + x + ".jpg");

Hashmap does not work with int, char

Generics can be defined using Wrapper classes only. If you don't want to define using Wrapper types, you may use the Raw definition as below

@SuppressWarnings("rawtypes")
public HashMap buildMap(String letters)
{
    HashMap checkSum = new HashMap();

    for ( int i = 0; i < letters.length(); ++i )
    {
       checkSum.put(letters.charAt(i), primes[i]);
    }
    return checkSum;
}

Or define the HashMap using wrapper types, and store the primitive types. The primitive values will be promoted to their wrapper types.

public HashMap<Character, Integer> buildMap(String letters)
{
  HashMap<Character, Integer> checkSum = new HashMap<Character, Integer>();

  for ( int i = 0; i < letters.length(); ++i )
  {
    checkSum.put(letters.charAt(i), primes[i]);
  }
  return checkSum;
}

How to use System.Net.HttpClient to post a complex type?

You should use the SendAsync method instead, this is a generic method, that serializes the input to the service

Widget widget = new Widget()
widget.Name = "test"
widget.Price = 1;

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:44268/api/test");
client.SendAsync(new HttpRequestMessage<Widget>(widget))
    .ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode() );

If you don't want to create the concrete class, you can make it with the FormUrlEncodedContent class

var client = new HttpClient();

// This is the postdata
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("Name", "test"));
postData.Add(new KeyValuePair<string, string>("Price ", "100"));

HttpContent content = new FormUrlEncodedContent(postData); 

client.PostAsync("http://localhost:44268/api/test", content).ContinueWith(
    (postTask) =>
    {
        postTask.Result.EnsureSuccessStatusCode();
    });

Note: you need to make your id to a nullable int (int?)

If condition inside of map() React

There are two syntax errors in your ternary conditional:

  1. remove the keyword if. Check the correct syntax here.
  2. You are missing a parenthesis in your code. If you format it like this:

    {(this.props.schema.collectionName.length < 0 ? 
       (<Expandable></Expandable>) 
       : (<h1>hejsan</h1>) 
    )}
    

Hope this works!

How to run a JAR file

java -classpath Predit.jar your.package.name.MainClass

doGet and doPost in Servlets

Both GET and POST are used by the browser to request a single resource from the server. Each resource requires a separate GET or POST request.

  1. The GET method is most commonly (and is the default method) used by browsers to retrieve information from servers. When using the GET method the 3rd section of the request packet, which is the request body, remains empty.

The GET method is used in one of two ways: When no method is specified, that is when you or the browser is requesting a simple resource such as an HTML page, an image, etc. When a form is submitted, and you choose method=GET on the HTML tag. If the GET method is used with an HTML form, then the data collected through the form is sent to the server by appending a "?" to the end of the URL, and then adding all name=value pairs (name of the html form field and value entered in that field) separated by an "&" Example: GET /sultans/shop//form1.jsp?name=Sam%20Sultan&iceCream=vanilla HTTP/1.0 optional headeroptional header<< empty line >>>

The name=value form data will be stored in an environment variable called QUERY_STRING. This variable will be sent to a processing program (such as JSP, Java servlet, PHP etc.)

  1. The POST method is used when you create an HTML form, and request method=POST as part of the tag. The POST method allows the client to send form data to the server in the request body section of the request (as discussed earlier). The data is encoded and is formatted similar to the GET method, except that the data is sent to the program through the standard input.

Example: POST /sultans/shop//form1.jsp HTTP/1.0 optional headeroptional header<< empty line >>> name=Sam%20Sultan&iceCream=vanilla

When using the post method, the QUERY_STRING environment variable will be empty. Advantages/Disadvantages of GET vs. POST

Advantages of the GET method: Slightly faster Parameters can be entered via a form or by appending them after the URL Page can be bookmarked with its parameters

Disadvantages of the GET method: Can only send 4K worth of data. (You should not use it when using a textarea field) Parameters are visible at the end of the URL

Advantages of the POST method: Parameters are not visible at the end of the URL. (Use for sensitive data) Can send more that 4K worth of data to server

Disadvantages of the POST method: Can cannot be bookmarked with its data

How to get year/month/day from a date object?

Here is a cleaner way getting Year/Month/Day with template literals:

_x000D_
_x000D_
var date = new Date();_x000D_
var formattedDate = `${date.getFullYear()}/${(date.getMonth() + 1)}/${date.getDate()}`;_x000D_
console.log(formattedDate);
_x000D_
_x000D_
_x000D_

Struct inheritance in C++

Yes. The inheritance is public by default.

Syntax (example):

struct A { };
struct B : A { };
struct C : B { };

How do I clear all options in a dropdown box?

To remove the options of an HTML element of select, you can utilize the remove() method:

function removeOptions(selectElement) {
   var i, L = selectElement.options.length - 1;
   for(i = L; i >= 0; i--) {
      selectElement.remove(i);
   }
}

// using the function:
removeOptions(document.getElementById('DropList'));

It's important to remove the options backwards; as the remove() method rearranges the options collection. This way, it's guaranteed that the element to be removed still exists!

Importing xsd into wsdl

You have a couple of problems here.

First, the XSD has an issue where an element is both named or referenced; in your case should be referenced.

Change:

<xsd:element name="stock" ref="Stock" minOccurs="1" maxOccurs="unbounded"/> 

To:

<xsd:element name="stock" type="Stock" minOccurs="1" maxOccurs="unbounded"/> 

And:

  • Remove the declaration of the global element Stock
  • Create a complex type declaration for a type named Stock

So:

<xsd:element name="Stock">
    <xsd:complexType>

To:

<xsd:complexType name="Stock">

Make sure you fix the xml closing tags.

The second problem is that the correct way to reference an external XSD is to use XSD schema with import/include within a wsdl:types element. wsdl:import is reserved to referencing other WSDL files. More information is available by going through the WS-I specification, section WSDL and Schema Import. Based on WS-I, your case would be:

INCORRECT: (the way you showed it)

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <import namespace="http://stock.com/schemas/services/stock" location="Stock.xsd" />
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

CORRECT:

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <types>
        <schema xmlns="http://www.w3.org/2001/XMLSchema">
            <import namespace="http://stock.com/schemas/services/stock" schemaLocation="Stock.xsd" />             
        </schema>
    </types>
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

SOME processors may support both syntaxes. The XSD you put out shows issues, make sure you first validate the XSD.

It would be better if you go the WS-I way when it comes to WSDL authoring.

Other issues may be related to the use of relative vs. absolute URIs in locating external content.

How can I record a Video in my Android App.?

Here is a simple video recording example using the MediaRecorder:

public class VideoCapture extends Activity implements OnClickListener, SurfaceHolder.Callback {
    MediaRecorder recorder;
    SurfaceHolder holder;
    boolean recording = false;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        recorder = new MediaRecorder();
        initRecorder();
        setContentView(R.layout.main);

        SurfaceView cameraView = (SurfaceView) findViewById(R.id.CameraView);
        holder = cameraView.getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        cameraView.setClickable(true);
        cameraView.setOnClickListener(this);
    }

    private void initRecorder() {
        recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
        recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);

        CamcorderProfile cpHigh = CamcorderProfile
                .get(CamcorderProfile.QUALITY_HIGH);
        recorder.setProfile(cpHigh);
        recorder.setOutputFile("/sdcard/videocapture_example.mp4");
        recorder.setMaxDuration(50000); // 50 seconds
        recorder.setMaxFileSize(5000000); // Approximately 5 megabytes
    }

    private void prepareRecorder() {
        recorder.setPreviewDisplay(holder.getSurface());

        try {
            recorder.prepare();
        } catch (IllegalStateException e) {
            e.printStackTrace();
            finish();
        } catch (IOException e) {
            e.printStackTrace();
            finish();
        }
    }

    public void onClick(View v) {
        if (recording) {
            recorder.stop();
            recording = false;

            // Let's initRecorder so we can record again
            initRecorder();
            prepareRecorder();
        } else {
            recording = true;
            recorder.start();
        }
    }

    public void surfaceCreated(SurfaceHolder holder) {
        prepareRecorder();
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        if (recording) {
            recorder.stop();
            recording = false;
        }
        recorder.release();
        finish();
    }
}

It's from my book: Pro Android Media: Developing Graphics, Music, Video, and Rich Media Apps for Smartphones and Tablets

Also, do not forget to include these permissions in manifest:

<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Can we create an instance of an interface in Java?

Yes it is correct. you can do it with an inner class.

HTML 5 video or audio playlist

I optimized the javascript code from cameronjonesweb a little bit. Now you can just add the clips into the array. Everything else is done automatically.

<video autoplay controls id="Player" src="http://www.w3schools.com/html/movie.mp4" onclick="this.paused ? this.play() : this.pause();">Your browser does not support the video tag.</video>

<script>
var nextsrc = ["http://www.w3schools.com/html/movie.mp4","http://www.w3schools.com/html/mov_bbb.mp4"];
var elm = 0; var Player = document.getElementById('Player');
Player.onended = function(){
    if(++elm < nextsrc.length){         
         Player.src = nextsrc[elm]; Player.play();
    } 
}
</script>

How do I check whether a checkbox is checked in jQuery?

Toggle: 0/1 or else

<input type="checkbox" id="nolunch" />
<input id="checklunch />"

    $('#nolunch').change(function () {
    if ($(this).is(':checked')) {
        $('#checklunch').val('1');
    };
    if ($(this).is(':checked') == false) {
        $('#checklunch').val('0');
    };
});

How to replace all special character into a string using C#

Also, It can be done with LINQ

var str = "Hello@Hello&Hello(Hello)";
var characters = str.Select(c => char.IsLetter(c) ? c : ',')).ToArray();             
var output = new string(characters);
Console.WriteLine(output);

Convert int (number) to string with leading zeros? (4 digits)

Use the ToString() method - standard and custom numeric format strings. Have a look at the MSDN article How to: Pad a Number with Leading Zeros.

string text = no.ToString("0000");

How to check if an integer is within a range?

There is no builtin function, but you can easily achieve it by calling the functions min() and max() appropriately.

// Limit integer between 1 and 100000
$var = max(min($var, 100000), 1);

Select arrow style change

You can use this. Its Tested code

    select {
    background: url(http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png) no-repeat right !important;
    appearance: none !important;
    background-size: 25px 25px !important;
    background-position: 99% 50% !important;
}

Detecting Back Button/Hash Change in URL

Another great implementation is balupton's jQuery History which will use the native onhashchange event if it is supported by the browser, if not it will use an iframe or interval appropriately for the browser to ensure all the expected functionality is successfully emulated. It also provides a nice interface to bind to certain states.

Another project worth noting as well is jQuery Ajaxy which is pretty much an extension for jQuery History to add ajax to the mix. As when you start using ajax with hashes it get's quite complicated!

stop all instances of node.js server

Linux

To impress your friends

ps aux | grep -i node | awk '{print $2}' | xargs  kill -9

But this is the one you will remember

killall node

How do I apply a diff patch on Windows?

I am already using BeyondCompare (commercial) for diffs and merges, and this tool also has the capability to create, view and apply patches.

How do I execute a program using Maven?

With the global configuration that you have defined for the exec-maven-plugin:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.4.0</version>
  <configuration>
    <mainClass>org.dhappy.test.NeoTraverse</mainClass>
  </configuration>
</plugin>

invoking mvn exec:java on the command line will invoke the plugin which is configured to execute the class org.dhappy.test.NeoTraverse.

So, to trigger the plugin from the command line, just run:

mvn exec:java

Now, if you want to execute the exec:java goal as part of your standard build, you'll need to bind the goal to a particular phase of the default lifecycle. To do this, declare the phase to which you want to bind the goal in the execution element:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.4</version>
  <executions>
    <execution>
      <id>my-execution</id>
      <phase>package</phase>
      <goals>
        <goal>java</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <mainClass>org.dhappy.test.NeoTraverse</mainClass>
  </configuration>
</plugin>

With this example, your class would be executed during the package phase. This is just an example, adapt it to suit your needs. Works also with plugin version 1.1.

correct PHP headers for pdf file download

I had the same problem recently and this helped me:

    header('Content-Description: File Transfer'); 
    header('Content-Type: application/octet-stream'); 
    header('Content-Disposition: attachment; filename="FILENAME"'); 
    header('Content-Transfer-Encoding: binary'); 
    header('Expires: 0'); 
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
    header('Pragma: public'); 
    header('Content-Length: ' . filesize("PATH/TO/FILE")); 
    ob_clean(); 
    flush(); 
    readfile(PATH/TO/FILE);      
    exit();

I found this answer here

java.lang.NoClassDefFoundError: Could not initialize class XXX

Just several days ago, I met the same question just like yours. All code runs well on my local machine, but turns out error(noclassdeffound&initialize). So I post my solution, but I don't know why, I merely advance a possibility. I hope someone know will explain this.@John Vint Firstly, I'll show you my problem. My code has static variable and static block both. When I first met this problem, I tried John Vint's solution, and tried to catch the exception. However, I caught nothing. So I thought it is because the static variable(but now I know they are the same thing) and still found nothing. So, I try to find the difference between the linux machine and my computer. Then I found that this problem happens only when several threads run in one process(By the way, the linux machine has double cores and double processes). That means if there are two tasks(both uses the code which has static block or variables) run in the same process, it goes wrong, but if they run in different processes, both of them are ok. In the Linux machine, I use

mvn -U clean  test -Dtest=path 

to run a task, and because my static variable is to start a container(or maybe you initialize a new classloader), so it will stay until the jvm stop, and the jvm stops only when all the tasks in one process stop. Every task will start a new container(or classloader) and it makes the jvm confused. As a result, the error happens. So, how to solve it? My solution is to add a new command to the maven command, and make every task go to the same container.

-Dxxx.version=xxxxx #sorry can't post more

Maybe you have already solved this problem, but still hope it will help others who meet the same problem.

Display Images Inline via CSS

The code you have posted here and code on your site both are different. There is a break <br> after second image, so the third image into new line, remove this <br> and it will display correctly.

Int to Char in C#

Although not exactly answering the question as formulated, but if you need or can take the end result as string you can also use

string s = Char.ConvertFromUtf32(56);

which will give you surrogate UTF-16 pairs if needed, protecting you if you are out side of the BMP.

Shortest way to print current year in a website

TJ's answer is excellent but I ran into one scenario where my HTML was already rendered and the document.write script would overwrite all of the page contents with just the date year.

For this scenario, you can append a text node to the existing element using the following code:

<div>
    &copy;
    <span id="copyright">
        <script>document.getElementById('copyright').appendChild(document.createTextNode(new Date().getFullYear()))</script>
    </span>
    Company Name
</div>

Remove or uninstall library previously added : cocoapods

  1. Remove pod name(which to remove) from Podfile and then
  2. Open Terminal, set project folder path
  3. Run pod install --no-integrate

How link to any local file with markdown syntax?

If you have spaces in the filename, try these:

[file](./file%20with%20spaces.md)
[file](<./file with spaces.md>)

First one seems more reliable

Search for one value in any column of any table inside a database

I found a fairly robust solution at https://gallery.technet.microsoft.com/scriptcenter/c0c57332-8624-48c0-b4c3-5b31fe641c58 , which I thought was worth pointing out. It searches columns of these types: varchar, char, nvarchar, nchar, text. It works great and supports specific table-searching as well as multiple search-terms.

Default value in Doctrine

You can do it using xml as well:

<field name="acmeOne" type="string" column="acmeOne" length="36">
    <options>
        <option name="comment">Your SQL field comment goes here.</option>
        <option name="default">Default Value</option>
    </options>
</field>

How do I debug jquery AJAX calls?

Using pretty much any modern browser you need to learn the Network tab. See this SO post about How to debug AJAX calls.

Where are include files stored - Ubuntu Linux, GCC

The \#include files of gcc are stored in /usr/include . The standard include files of g++ are stored in /usr/include/c++.

Override valueof() and toString() in Java enum

You can use a static Map in your enum that maps Strings to enum constants. Use it in a 'getEnum' static method. This skips the need to iterate through the enums each time you want to get one from its String value.

public enum RandomEnum {

    StartHere("Start Here"),
    StopHere("Stop Here");

    private final String strVal;
    private RandomEnum(String strVal) {
        this.strVal = strVal;
    }

    public static RandomEnum getEnum(String strVal) {
        if(!strValMap.containsKey(strVal)) {
            throw new IllegalArgumentException("Unknown String Value: " + strVal);
        }
        return strValMap.get(strVal);
    }

    private static final Map<String, RandomEnum> strValMap;
    static {
        final Map<String, RandomEnum> tmpMap = Maps.newHashMap();
        for(final RandomEnum en : RandomEnum.values()) {
            tmpMap.put(en.strVal, en);
        }
        strValMap = ImmutableMap.copyOf(tmpMap);
    }

    @Override
    public String toString() {
        return strVal;
    }
}

Just make sure the static initialization of the map occurs below the declaration of the enum constants.

BTW - that 'ImmutableMap' type is from the Google guava API, and I definitely recommend it in cases like this.


EDIT - Per the comments:

  1. This solution assumes that each assigned string value is unique and non-null. Given that the creator of the enum can control this, and that the string corresponds to the unique & non-null enum value, this seems like a safe restriction.
  2. I added the 'toSTring()' method as asked for in the question

SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

Just a small observation: you keep mentioning conn usr\pass, and this is a typo, right? Cos it should be conn usr/pass. Or is it different on a Unix based OS?

Furthermore, just to be sure: if you use tnsnames, your login string will look different from when you use the login method you started this topic out with.

tnsnames.ora should be in $ORACLE_HOME$\network\admin. That is the Oracle home on the machine from which you are trying to connect, so in your case your PC. If you have multiple oracle_homes and wish to use only one tnsnames.ora, you can set environment variable tns_admin (e.g. set TNS_ADMIN=c:\oracle\tns), and place tnsnames.ora in that directory.

Your original method of logging on (usr/[email protected]:port/servicename) should always work. So far I think you have all the info, except for the port number, which I am sure your DBA will be able to give you. If this method still doesn't work, either the server's IP address is not available from your client, or it is a firewall issue (blocking a certain port), or something else not (directly) related to Oracle or SQL*Plus.

hth! Regards, Remco

OkHttp Post Body as JSON

You can create your own JSONObject then toString().

Remember run it in the background thread like doInBackground in AsyncTask.

OkHttp version > 4:

// create your json here
JSONObject jsonObject = new JSONObject();
try {
    jsonObject.put("KEY1", "VALUE1");
    jsonObject.put("KEY2", "VALUE2");
} catch (JSONException e) {
    e.printStackTrace();
}

val client = OkHttpClient()
val mediaType = "application/json; charset=utf-8".toMediaType()
val body = jsonObject.toString().toRequestBody(mediaType)
val request: Request = Request.Builder()
            .url("https://YOUR_URL/")
            .post(body)
            .build()

var response: Response? = null
try {
    response = client.newCall(request).execute()
    val resStr = response.body!!.string()
} catch (e: IOException) {
    e.printStackTrace()
}
   

OkHttp version 3:

// create your json here
JSONObject jsonObject = new JSONObject();
try {
    jsonObject.put("KEY1", "VALUE1");
    jsonObject.put("KEY2", "VALUE2");
} catch (JSONException e) {
    e.printStackTrace();
}

  OkHttpClient client = new OkHttpClient();
  MediaType JSON = MediaType.parse("application/json; charset=utf-8");
  // put your json here
  RequestBody body = RequestBody.create(JSON, jsonObject.toString());
  Request request = new Request.Builder()
                    .url("https://YOUR_URL/")
                    .post(body)
                    .build();

  Response response = null;
  try {
      response = client.newCall(request).execute();
      String resStr = response.body().string();
  } catch (IOException e) {
      e.printStackTrace();
  }

Swift - Remove " character from string

Let's say you have a string:

var string = "potatoes + carrots"

And you want to replace the word "potatoes" in that string with "tomatoes"

string = string.replacingOccurrences(of: "potatoes", with: "tomatoes", options: NSString.CompareOptions.literal, range: nil)

If you print your string, it will now be: "tomatoes + carrots"

If you want to remove the word potatoes from the sting altogether, you can use:

string = string.replacingOccurrences(of: "potatoes", with: "", options: NSString.CompareOptions.literal, range: nil)

If you want to use some other characters in your sting, use:

  • Null Character (\0)
  • Backslash (\)
  • Horizontal Tab (\t)
  • Line Feed (\n)
  • Carriage Return (\r)
  • Double Quote (\")
  • Single Quote (\')

Example:

string = string.replacingOccurrences(of: "potatoes", with: "dog\'s toys", options: NSString.CompareOptions.literal, range: nil)

Output: "dog's toys + carrots"

Search an Oracle database for tables with specific column names?

Here is one that we have saved off to findcol.sql so we can run it easily from within SQLPlus

set verify off
clear break
accept colnam prompt 'Enter Column Name (or part of): '
set wrap off
select distinct table_name, 
                column_name, 
                data_type || ' (' || 
                decode(data_type,'LONG',null,'LONG RAW',null,
                       'BLOB',null,'CLOB',null,'NUMBER',
                       decode(data_precision,null,to_char(data_length),
                              data_precision||','||data_scale
                             ), data_length
                      ) || ')' data_type
  from all_tab_columns
 where column_name like ('%' || upper('&colnam') || '%');
set verify on

The HTTP request is unauthorized with client authentication scheme 'Ntlm'. The authentication header received from the server was 'Negotiate,NTLM'

You can eliminate the client from the problem by using wftech, this is an old tool but I have found it useful in diagnosing authentication issues. wfetch allows you to specify NTLM, Negotiate and kerberos, this may well help you better understand your problem. As you are trying to call a service and wfetch knows nothing about WCF, I would suggest applying your endpoint binding (PROVIDERSSoapBinding) to the serviceMetadata then you can do an HTTP GET of the WSDL for the service with the same security settings.

Another option, which may be available to you is to force the server to use NTLM, you can do this by either editing the metabase (IIS 6) and removing the Negotiate setting, more details at http://support.microsoft.com/kb/215383.

If you are using IIS 7.x then the approach is slightly different, details of how to configure the authentication providers are here http://www.iis.net/configreference/system.webserver/security/authentication/windowsauthentication.

I notice that you have blocked out the server address with xxx.xx.xx.xxx, so I'm guessing that this is an IP address rather than a server name, this may cause issues with authentication, so if possible try targeting the machine name.

Sorry that I haven't given you the answer but rather pointers for getting closer to the issue, but I hope it helps.

I'll finish by saying that I have experienced this same issue and my only recourse was to use Kerberos rather than NTLM, don't forget you'll need to register an SPN for the service if you do go down this route.

Upgrade python in a virtualenv

Did you see this? If I haven't misunderstand that answer, you may try to create a new virtualenv on top of the old one. You just need to know which python is going to use your virtualenv (you will need to see your virtualenv version).

If your virtualenv is installed with the same python version of the old one and upgrading your virtualenv package is not an option, you may want to read this in order to install a virtualenv with the python version you want.

EDIT

I've tested this approach (the one that create a new virtualenv on top of the old one) and it worked fine for me. I think you may have some problems if you change from python 2.6 to 2.7 or 2.7 to 3.x but if you just upgrade inside the same version (staying at 2.7 as you want) you shouldn't have any problem, as all the packages are held in the same folders for both python versions (2.7.x and 2.7.y packages are inside your_env/lib/python2.7/).

If you change your virtualenv python version, you will need to install all your packages again for that version (or just link the packages you need into the new version packages folder, i.e: your_env/lib/python_newversion/site-packages)

Trust Anchor not found for Android SSL Connection

The Trust anchor error can happen for a lot of reasons. For me it was simply that I was trying to access https://example.com/ instead of https://www.example.com/.

So you might want to double-check your URLs before starting to build your own Trust Manager (like I did).

Display a angular variable in my html page

In your template, you have access to all the variables that are members of the current $scope. So, tobedone should be $scope.tobedone, and then you can display it with {{tobedone}}, or [[tobedone]] in your case.

Android: Test Push Notification online (Google Cloud Messaging)

Found a very easy way to do this.

Open http://phpfiddle.org/

Paste following php script in box. In php script set API_ACCESS_KEY, set device ids separated by coma.

Press F9 or click Run.

Have fun ;)

<?php


// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'YOUR-API-ACCESS-KEY-GOES-HERE' );


$registrationIds = array("YOUR DEVICE IDS WILL GO HERE" );

// prep the bundle
$msg = array
(
    'message'       => 'here is a message. message',
    'title'         => 'This is a title. title',
    'subtitle'      => 'This is a subtitle. subtitle',
    'tickerText'    => 'Ticker text here...Ticker text here...Ticker text here',
    'vibrate'   => 1,
    'sound'     => 1
);

$fields = array
(
    'registration_ids'  => $registrationIds,
    'data'              => $msg
);

$headers = array
(
    'Authorization: key=' . API_ACCESS_KEY,
    'Content-Type: application/json'
);

$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );

echo $result;
?>

For FCM, google url would be: https://fcm.googleapis.com/fcm/send

For FCM v1 google url would be: https://fcm.googleapis.com/v1/projects/YOUR_GOOGLE_CONSOLE_PROJECT_ID/messages:send

Note: While creating API Access Key on google developer console, you have to use 0.0.0.0/0 as ip address. (For testing purpose).

In case of receiving invalid Registration response from GCM server, please cross check the validity of your device token. You may check the validity of your device token using following url:

https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=YOUR_DEVICE_TOKEN

Some response codes:

Following is the description of some response codes you may receive from server.

{ "message_id": "XXXX" } - success
{ "message_id": "XXXX", "registration_id": "XXXX" } - success, device registration id has been changed mainly due to app re-install
{ "error": "Unavailable" } - Server not available, resend the message
{ "error": "InvalidRegistration" } - Invalid device registration Id 
{ "error": "NotRegistered"} - Application was uninstalled from the device

iOS 7.0 No code signing identities found

For me, setting Project ? Targets/[Your project] ? General ? Team to "None" solved the issue.

T-SQL XOR Operator

The xor operator is ^

For example: SELECT A ^ B where A and B are integer category data types.

Linux command for extracting war file?

Or

jar xvf myproject.war

CSS: how to position element in lower right?

Lets say your HTML looks something like this:

<div class="box">
    <!-- stuff -->
    <p class="bet_time">Bet 5 days ago</p>
</div>

Then, with CSS, you can make that text appear in the bottom right like so:

.box {
    position:relative;
}
.bet_time {
    position:absolute;
    bottom:0;
    right:0;
}

The way this works is that absolutely positioned elements are always positioned with respect to the first relatively positioned parent element, or the window. Because we set the box's position to relative, .bet_time positions its right edge to the right edge of .box and its bottom edge to the bottom edge of .box

jQuery: How to get to a particular child of a parent?

This will find the first parent with class box then find the first child class with regex matching something and get the id.

$(".mylink").closest(".box").find('[class*="something"]').first().attr("id")

Entity framework self referencing loop detected

I had same problem and found that you can just apply the [JsonIgnore] attribute to the navigation property you don't want to be serialised. It will still serialise both the parent and child entities but just avoids the self referencing loop.

How to customize the configuration file of the official PostgreSQL Docker image?

With Docker Compose

When working with Docker Compose, you can use command: postgres -c option=value in your docker-compose.yml to configure Postgres.

For example, this makes Postgres log to a file:

command: postgres -c logging_collector=on -c log_destination=stderr -c log_directory=/logs

Adapting Vojtech Vitek's answer, you can use

command: postgres -c config_file=/etc/postgresql.conf

to change the config file Postgres will use. You'd mount your custom config file with a volume:

volumes:
   - ./customPostgresql.conf:/etc/postgresql.conf

Here's the docker-compose.yml of my application, showing how to configure Postgres:

# Start the app using docker-compose pull && docker-compose up to make sure you have the latest image
version: '2.1'
services:
  myApp:
    image: registry.gitlab.com/bullbytes/myApp:latest
    networks:
      - myApp-network
  db:
     image: postgres:9.6.1
     # Make Postgres log to a file.
     # More on logging with Postgres: https://www.postgresql.org/docs/current/static/runtime-config-logging.html
     command: postgres -c logging_collector=on -c log_destination=stderr -c log_directory=/logs
     environment:
       # Provide the password via an environment variable. If the variable is unset or empty, use a default password
       - POSTGRES_PASSWORD=${POSTGRES_PASSWORD:-4WXUms893U6j4GE&Hvk3S*hqcqebFgo!vZi}
     # If on a non-Linux OS, make sure you share the drive used here. Go to Docker's settings -> Shared Drives
     volumes:
       # Persist the data between container invocations
       - postgresVolume:/var/lib/postgresql/data
       - ./logs:/logs
     networks:
       myApp-network:
         # Our application can communicate with the database using this hostname
         aliases:
           - postgresForMyApp
networks:
  myApp-network:
    driver: bridge
# Creates a named volume to persist our data. When on a non-Linux OS, the volume's data will be in the Docker VM
# (e.g., MobyLinuxVM) in /var/lib/docker/volumes/
volumes:
  postgresVolume:

Permission to write to the log directory

Note that when on Linux, the log directory on the host must have the right permissions. Otherwise you'll get the slightly misleading error

FATAL: could not open log file "/logs/postgresql-2017-02-04_115222.log": Permission denied

I say misleading, since the error message suggests that the directory in the container has the wrong permission, when in reality the directory on the host doesn't permit writing.

To fix this, I set the correct permissions on the host using

chgroup ./logs docker && chmod 770 ./logs

Converting File to MultiPartFile

MockMultipartFile exists for this purpose. As in your snippet if the file path is known, the below code works for me.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.mock.web.MockMultipartFile;

Path path = Paths.get("/path/to/the/file.txt");
String name = "file.txt";
String originalFileName = "file.txt";
String contentType = "text/plain";
byte[] content = null;
try {
    content = Files.readAllBytes(path);
} catch (final IOException e) {
}
MultipartFile result = new MockMultipartFile(name,
                     originalFileName, contentType, content);

Android Respond To URL in Intent

You might need to allow different combinations of data in your intent filter to get it to work in different cases (http/ vs https/, www. vs no www., etc).

For example, I had to do the following for an app which would open when the user opened a link to Google Drive forms (www.docs.google.com/forms)

Note that path prefix is optional.

        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data android:scheme="http" />
            <data android:scheme="https" />

            <data android:host="www.docs.google.com" />
            <data android:host="docs.google.com" />

            <data android:pathPrefix="/forms" />
        </intent-filter>

What is difference between Errors and Exceptions?

In general error is which nobody can control or guess when it occurs.Exception can be guessed and can be handled. In Java Exception and Error are sub class of Throwable.It is differentiated based on the program control.Error such as OutOfMemory Error which no programmer can guess and can handle it.It depends on dynamically based on architectire,OS and server configuration.Where as Exception programmer can handle it and can avoid application's misbehavior.For example if your code is looking for a file which is not available then IOException is thrown.Such instances programmer can guess and can handle it.

Convert command line argument to string

It's already an array of C-style strings:

#include <iostream>
#include <string>
#include <vector>


int main(int argc, char *argv[]) // Don't forget first integral argument 'argc'
{
  std::string current_exec_name = argv[0]; // Name of the current exec program
  std::vector<std::string> all_args;

  if (argc > 1) {
    all_args.assign(argv + 1, argv + argc);
  }
}

Argument argc is count of arguments plus the current exec file.

Pass variables to AngularJS controller, best practice?

You could use ng-init in an outer div:

<div ng-init="param='value';">
    <div ng-controller="BasketController" >
        <label>param: {{value}}</label>
    </div>
</div>  

The parameter will then be available in your controller's scope:

function BasketController($scope) {
        console.log($scope.param);
}

Is there an upside down caret character?

I'd use a couple of tiny images. Would look better too.

Alternatively, you can try the Character Map utility that comes with Windows or try looking here.

Another solution I've seen is to use the Wingdings font for symbols. That has a lot fo arrows.

What is PECS (Producer Extends Consumer Super)?

let’s try visualizing this concept.

<? super SomeType> is an “undefined(yet)” type, but that undefined type should be a superclass of the ‘SomeType’ class.

The same goes for <? extends SomeType>. It’s a type that should extend the ‘SomeType’ class (it should be a child class of the ‘SomeType’ class).

If we consider the concept of 'class inheritance' in a Venn diagram, an example would be like this:

enter image description here

Mammal class extends Animal class (Animal class is a superclass of Mammal class).

Cat/Dog class extends Mammal class (Mammal class is a superclass of Cat/Dog class).

Then, let’s think about the ‘circles’ in the above diagram as a ‘box’ that has a physical volume.

enter image description here

You CAN’T put a bigger box into a smaller one.

You can ONLY put a smaller box into a bigger one.

When you say <? super SomeType>, you wanna describe a ‘box’ that is the same size or bigger than the ‘SomeType’ box.

If you say <? extends SomeType>, then you wanna describe a ‘box’ that is the same size or smaller than the ‘SomeType’ box.

so what is PECS anyway?

An example of a ‘Producer’ is a List which we only read from.

An example of a ‘Consumer’ is a List which we only write into.

Just keep in mind this:

  • We ‘read’ from a ‘producer’, and take that stuff into our own box.

  • And we ‘write’ our own box into a ‘consumer’.

So, we need to read(take) something from a ‘producer’ and put that into our ‘box’. This means that any boxes taken from the producer should NOT be bigger than our ‘box’. That’s why “Producer Extends.”

“Extends” means a smaller box(smaller circle in the Venn diagram above). The boxes of a producer should be smaller than our own box, because we are gonna take those boxes from the producer and put them into our own box. We can’t put anything bigger than our box!

Also, we need to write(put) our own ‘box’ into a ‘consumer’. This means that the boxes of the consumer should NOT be smaller than our own box. That’s why “Consumer Super.”

“Super” means a bigger box(bigger circle in the Venn diagram above). If we want to put our own boxes into a consumer, the boxes of the consumer should be bigger than our box!

Now we can easily understand this example:

public class Collections { 
  public static <T> void copy(List<? super T> dest, List<? extends T> src) {
      for (int i = 0; i < src.size(); i++) 
        dest.set(i, src.get(i)); 
  } 
}

In the above example, we want to read(take) something from src and write(put) them into dest. So the src is a “Producer” and its “boxes” should be smaller(more specific) than some type T.

Vice versa, the dest is a “Consumer” and its “boxes” should be bigger(more general) than some type T.

If the “boxes” of the src were bigger than that of the dest, we couldn’t put those big boxes into the smaller boxes the dest has.

If anyone reads this, I hope it helps you better understand “Producer Extends, Consumer Super.”

Happy coding! :)

Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

if you got an error

Execution failed for task ‘:app:fabricGenerateResourcesDebug’. Crashlytics Developer Tools error.

remove also this line:

apply plugin: 'io.fabric'

Prevent screen rotation on Android

In your Manifest file, for each Activity that you want to lock the screen rotation add: if you want to lock it in horizontal mode:

<activity
        ...
        ...
        android:screenOrientation="landscape">

or if you want to lock it in vertical mode:

<activity
            ...
            ...
            android:screenOrientation="portrait">

Which tool to build a simple web front-end to my database

For Data access you can use OData. Here is a demo where Scott Hanselman creates an OData front end to StackOverflow database in 30 minutes, with XML and JSON access: Creating an OData API for StackOverflow including XML and JSON in 30 minutes.

For administrative access, like phpMyAdmin package, there is no well established one. You may give a try to IIS Database Manager.

Equal height rows in a flex container

You can accomplish that now with display: grid:

_x000D_
_x000D_
.list {_x000D_
  display: grid;_x000D_
  overflow: hidden;_x000D_
  grid-template-columns: repeat(3, 1fr);_x000D_
  grid-auto-rows: 1fr;_x000D_
  grid-column-gap: 5px;_x000D_
  grid-row-gap: 5px;_x000D_
  max-width: 500px;_x000D_
}_x000D_
.list-item {_x000D_
  background-color: #ccc;_x000D_
  display: flex;_x000D_
  padding: 0.5em;_x000D_
  margin-bottom: 20px;_x000D_
}_x000D_
.list-content {_x000D_
  width: 100%;_x000D_
}
_x000D_
<ul class="list">_x000D_
  <li class="list-item">_x000D_
    <div class="list-content">_x000D_
      <h2>box 1</h2>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>_x000D_
    </div>_x000D_
  </li>_x000D_
  <li class="list-item">_x000D_
    <div class="list-content">_x000D_
      <h3>box 2</h3>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>_x000D_
    </div>_x000D_
  </li>_x000D_
_x000D_
  <li class="list-item">_x000D_
    <div class="list-content">_x000D_
      <h3>box 2</h3>_x000D_
      <p>Lorem ipsum dolor</p>_x000D_
    </div>_x000D_
  </li>_x000D_
_x000D_
  <li class="list-item">_x000D_
    <div class="list-content">_x000D_
      <h3>box 2</h3>_x000D_
      <p>Lorem ipsum dolor</p>_x000D_
    </div>_x000D_
  </li>_x000D_
  <li class="list-item">_x000D_
    <div class="list-content">_x000D_
      <h1>h1</h1>_x000D_
    </div>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Although the grid itself is not flexbox, it behaves very similar to a flexbox container, and the items inside the grid can be flex.

The grid layout is also very handy in the case you want responsive grids. That is, if you want the grid to have a different number of columns per row you can then just change grid-template-columns:

grid-template-columns: repeat(1, 1fr); // 1 column
grid-template-columns: repeat(2, 1fr); // 2 columns
grid-template-columns: repeat(3, 1fr); // 3 columns

and so on...

You can mix it with media queries and change according to the size of the page.

Sadly there is still no support for container queries / element queries in the browsers (out of the box) to make it work well with changing the number of columns according to the container size, not to the page size (this would be great to use with reusable webcomponents).

More information about the grid layout:

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout

Support of the Grid Layout accross browsers:

https://caniuse.com/#feat=css-grid

How to print a percentage value in python?

You are dividing integers then converting to float. Divide by floats instead.

As a bonus, use the awesome string formatting methods described here: http://docs.python.org/library/string.html#format-specification-mini-language

To specify a percent conversion and precision.

>>> float(1) / float(3)
[Out] 0.33333333333333331

>>> 1.0/3.0
[Out] 0.33333333333333331

>>> '{0:.0%}'.format(1.0/3.0) # use string formatting to specify precision
[Out] '33%'

>>> '{percent:.2%}'.format(percent=1.0/3.0)
[Out] '33.33%'

A great gem!

How to merge a specific commit in Git

Let's try to take an example and understand:

I have a branch, say master, pointing to X <commit-id>, and I have a new branch pointing to Y <sha1>.

Where Y <commit-id> = <master> branch commits - few commits

Now say for Y branch I have to gap-close the commits between the master branch and the new branch. Below is the procedure we can follow:

Step 1:

git checkout -b local origin/new

where local is the branch name. Any name can be given.

Step 2:

  git merge origin/master --no-ff --stat -v --log=300

Merge the commits from master branch to new branch and also create a merge commit of log message with one-line descriptions from at most <n> actual commits that are being merged.

For more information and parameters about Git merge, please refer to:

git merge --help

Also if you need to merge a specific commit, then you can use:

git cherry-pick <commit-id>

How to convert a Collection to List?

What you request is quite a costy operation, make sure you don't need to do it often (e.g in a cycle).

If you need it to stay sorted and you update it frequently, you can create a custom collection. For example, I came up with one that has your TreeBidiMap and TreeMultiset under the hood. Implement only what you need and care about data integrity.

class MyCustomCollection implements Map<K, V> {
    TreeBidiMap<K, V> map;
    TreeMultiset<V> multiset;
    public V put(K key, V value) {
        removeValue(map.put(key, value));
        multiset.add(value);
    }
    public boolean remove(K key) {
        removeValue(map.remove(key));
    }
    /** removes value that was removed/replaced in map */
    private removeValue(V value) {
        if (value != null) {
            multiset.remove(value);
        }
    }
    public Set<K> keySet() {
        return Collections.unmodifiableSet(map.keySet());
    }
    public Collection<V> values() {
        return Collections.unmodifiableCollection(multiset);
    }
    // many more methods to be implemented, e.g. count, isEmpty etc.
    // but these are fairly simple
}

This way, you have a sorted Multiset returned from values(). However, if you need it to be a list (e.g. you need the array-like get(index) method), you'd need something more complex.

For brevity, I only return unmodifiable collections. What @Lino mentioned is correct, and modifying the keySet or values collection as it is would make it inconsistent. I don't know any consistent way to make the values mutable, but the keySet could support remove if it uses the remove method from the MyCustomCollection class above.

How do I get length of list of lists in Java?

import java.util.ArrayList;

public class TestClass {

public static void main(String[] args) {

    ArrayList<ArrayList<String>> listOLists = new ArrayList<ArrayList<String>>();
    ArrayList<String> List_1 = new ArrayList<String>();
    List_1.add("1");
    List_1.add("2");
    listOLists.add(List_1);

    ArrayList<String> List_2 = new ArrayList<String>();
    List_2.add("4");
    List_2.add("5");
    List_2.add("10");
    List_2.add("11");
    listOLists.add(List_2);
    for (int i = 0; i < listOLists.size(); i++) {
        System.out.print("list " + i + " :");
        for (int j = 0; j < listOLists.get(i).size(); j++) {
            System.out.print(listOLists.get(i).get(j) + " ;");
        }
        System.out.println();
    }

}

}

I hope this solution gives a better picture of list if lists

How to make full screen background in a web page

Use this CSS to make full screen backgound in a web page.

body {
    margin:0;
    padding:0;
    background:url("https://static.vecteezy.com/system/resources/previews/000/106/719/original/vector-abstract-blue-wave-background.jpg") no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

How can I get browser to prompt to save password?

Using a cookie would probably be the best way to do this.

You could have a checkbox for 'Remember me?' and have the form create a cookie to store the //user's login// info. EDIT: User Session Information

To create a cookie, you'll need to process the login form with PHP.

Size of Matrix OpenCV

A complete C++ code example, may be helpful for the beginners

#include <iostream>
#include <string>
#include "opencv/highgui.h"

using namespace std;
using namespace cv;

int main()
{
    cv:Mat M(102,201,CV_8UC1);
    int rows = M.rows;
    int cols = M.cols;

    cout<<rows<<" "<<cols<<endl;

    cv::Size sz = M.size();
    rows = sz.height;
    cols = sz.width;

    cout<<rows<<" "<<cols<<endl;
    cout<<sz<<endl;
    return 0;
}

Pandas sum by groupby, but exclude certain columns

The agg function will do this for you. Pass the columns and function as a dict with column, output:

df.groupby(['Country', 'Item_Code']).agg({'Y1961': np.sum, 'Y1962': [np.sum, np.mean]})  # Added example for two output columns from a single input column

This will display only the group by columns, and the specified aggregate columns. In this example I included two agg functions applied to 'Y1962'.

To get exactly what you hoped to see, included the other columns in the group by, and apply sums to the Y variables in the frame:

df.groupby(['Code', 'Country', 'Item_Code', 'Item', 'Ele_Code', 'Unit']).agg({'Y1961': np.sum, 'Y1962': np.sum, 'Y1963': np.sum})

Understanding `scale` in R

I thought I would contribute by providing a concrete example of the practical use of the scale function. Say you have 3 test scores (Math, Science, and English) that you want to compare. Maybe you may even want to generate a composite score based on each of the 3 tests for each observation. Your data could look as as thus:

student_id <- seq(1,10)
math <- c(502,600,412,358,495,512,410,625,573,522)
science <- c(95,99,80,82,75,85,80,95,89,86)
english <- c(25,22,18,15,20,28,15,30,27,18)
df <- data.frame(student_id,math,science,english)

Obviously it would not make sense to compare the means of these 3 scores as the scale of the scores are vastly different. By scaling them however, you have more comparable scoring units:

z <- scale(df[,2:4],center=TRUE,scale=TRUE)

You could then use these scaled results to create a composite score. For instance, average the values and assign a grade based on the percentiles of this average. Hope this helped!

Note: I borrowed this example from the book "R In Action". It's a great book! Would definitely recommend.

How to pass form input value to php function

You can write your php file to the action attr of form element.
At the php side you can get the form value by $_POST['element_name'].

Is Java RegEx case-insensitive?

You also can lead your initial string, which you are going to check for pattern matching, to lower case. And use in your pattern lower case symbols respectively.

addID in jQuery?

do you mean a method?

$('div.foo').attr('id', 'foo123');

Just be careful that you don't set multiple elements to the same ID.

Raising a number to a power in Java

^ in java does not mean to raise to a power. It means XOR.

You can use java's Math.pow()


And you might want to consider using double instead of int—that is:

double height;
double weight;

Note that 199/100 evaluates to 1.

Extract csv file specific columns to list in Python

import csv
from sys import argv

d = open("mydata.csv", "r")

db = []

for line in csv.reader(d):
    db.append(line)

# the rest of your code with 'db' filled with your list of lists as rows and columbs of your csv file.

Limit file format when using <input type="file">?

You can use the change event to monitor what the user selects and notify them at that point that the file is not acceptable. It does not limit the actual list of files displayed, but it is the closest you can do client-side, besides the poorly supported accept attribute.

_x000D_
_x000D_
var file = document.getElementById('someId');_x000D_
_x000D_
file.onchange = function(e) {_x000D_
  var ext = this.value.match(/\.([^\.]+)$/)[1];_x000D_
  switch (ext) {_x000D_
    case 'jpg':_x000D_
    case 'bmp':_x000D_
    case 'png':_x000D_
    case 'tif':_x000D_
      alert('Allowed');_x000D_
      break;_x000D_
    default:_x000D_
      alert('Not allowed');_x000D_
      this.value = '';_x000D_
  }_x000D_
};
_x000D_
<input type="file" id="someId" />
_x000D_
_x000D_
_x000D_

JSFiddle

"You tried to execute a query that does not include the specified aggregate function"

The error is because fName is included in the SELECT list, but is not included in a GROUP BY clause and is not part of an aggregate function (Count(), Min(), Max(), Sum(), etc.)

You can fix that problem by including fName in a GROUP BY. But then you will face the same issue with surname. So put both in the GROUP BY:

SELECT
    fName,
    surname,
    Count(*) AS num_rows
FROM
    author
    INNER JOIN book
    ON author.aID = book.authorID;
GROUP BY
    fName,
    surname

Note I used Count(*) where you wanted SUM(orders.quantity). However, orders isn't included in the FROM section of your query, so you must include it before you can Sum() one of its fields.

If you have Access available, build the query in the query designer. It can help you understand what features are possible and apply the correct Access SQL syntax.

How can my iphone app detect its own version number?

func getAppVersion() -> String {
    let dictionary = Bundle.main.infoDictionary!
    let versionValue = dictionary["CFBundleShortVersionString"] ?? "0"
    let buildValue = dictionary["CFBundleVersion"] ?? "0"
    return "\(versionValue) (build \(buildValue))"
}

Based on @rajat chauhan answer without forced cast to String.

Difference between float and decimal data type

Floating-Point Types (Approximate Value) - FLOAT, DOUBLE

The FLOAT and DOUBLE types represent approximate numeric data values. MySQL uses four bytes for single-precision values and eight bytes for double-precision values.

For FLOAT, the SQL standard permits an optional specification of the precision (but not the range of the exponent) in bits following the keyword FLOAT in parentheses. MySQL also supports this optional precision specification, but the precision value is used only to determine storage size. A precision from 0 to 23 results in a 4-byte single-precision FLOAT column. A precision from 24 to 53 results in an 8-byte double-precision DOUBLE column.

MySQL permits a nonstandard syntax: FLOAT(M,D) or REAL(M,D) or DOUBLE PRECISION(M,D). Here, “(M,D)” means than values can be stored with up to M digits in total, of which D digits may be after the decimal point. For example, a column defined as FLOAT(7,4) will look like -999.9999 when displayed. MySQL performs rounding when storing values, so if you insert 999.00009 into a FLOAT(7,4) column, the approximate result is 999.0001.

Because floating-point values are approximate and not stored as exact values, attempts to treat them as exact in comparisons may lead to problems. They are also subject to platform or implementation dependencies.

For maximum portability, code requiring storage of approximate numeric data values should use FLOAT or DOUBLE PRECISION with no specification of precision or number of digits.

https://dev.mysql.com/doc/refman/5.5/en/floating-point-types.html

Problems with Floating-Point Values

Floating-point numbers sometimes cause confusion because they are approximate and not stored as exact values. A floating-point value as written in an SQL statement may not be the same as the value represented internally. Attempts to treat floating-point values as exact in comparisons may lead to problems. They are also subject to platform or implementation dependencies. The FLOAT and DOUBLE data types are subject to these issues. For DECIMAL columns, MySQL performs operations with a precision of 65 decimal digits, which should solve most common inaccuracy problems.

The following example uses DOUBLE to demonstrate how calculations that are done using floating-point operations are subject to floating-point error.

mysql> CREATE TABLE t1 (i INT, d1 DOUBLE, d2 DOUBLE);
mysql> INSERT INTO t1 VALUES (1, 101.40, 21.40), (1, -80.00, 0.00),
    -> (2, 0.00, 0.00), (2, -13.20, 0.00), (2, 59.60, 46.40),
    -> (2, 30.40, 30.40), (3, 37.00, 7.40), (3, -29.60, 0.00),
    -> (4, 60.00, 15.40), (4, -10.60, 0.00), (4, -34.00, 0.00),
    -> (5, 33.00, 0.00), (5, -25.80, 0.00), (5, 0.00, 7.20),
    -> (6, 0.00, 0.00), (6, -51.40, 0.00);

mysql> SELECT i, SUM(d1) AS a, SUM(d2) AS b
    -> FROM t1 GROUP BY i HAVING a <> b;

+------+-------+------+
| i    | a     | b    |
+------+-------+------+
|    1 |  21.4 | 21.4 |
|    2 |  76.8 | 76.8 |
|    3 |   7.4 |  7.4 |
|    4 |  15.4 | 15.4 |
|    5 |   7.2 |  7.2 |
|    6 | -51.4 |    0 |
+------+-------+------+

The result is correct. Although the first five records look like they should not satisfy the comparison (the values of a and b do not appear to be different), they may do so because the difference between the numbers shows up around the tenth decimal or so, depending on factors such as computer architecture or the compiler version or optimization level. For example, different CPUs may evaluate floating-point numbers differently.

If columns d1 and d2 had been defined as DECIMAL rather than DOUBLE, the result of the SELECT query would have contained only one row—the last one shown above.

The correct way to do floating-point number comparison is to first decide on an acceptable tolerance for differences between the numbers and then do the comparison against the tolerance value. For example, if we agree that floating-point numbers should be regarded the same if they are same within a precision of one in ten thousand (0.0001), the comparison should be written to find differences larger than the tolerance value:

mysql> SELECT i, SUM(d1) AS a, SUM(d2) AS b FROM t1
    -> GROUP BY i HAVING ABS(a - b) > 0.0001;
+------+-------+------+
| i    | a     | b    |
+------+-------+------+
|    6 | -51.4 |    0 |
+------+-------+------+
1 row in set (0.00 sec)

Conversely, to get rows where the numbers are the same, the test should find differences within the tolerance value:

mysql> SELECT i, SUM(d1) AS a, SUM(d2) AS b FROM t1
    -> GROUP BY i HAVING ABS(a - b) <= 0.0001;
+------+------+------+
| i    | a    | b    |
+------+------+------+
|    1 | 21.4 | 21.4 |
|    2 | 76.8 | 76.8 |
|    3 |  7.4 |  7.4 |
|    4 | 15.4 | 15.4 |
|    5 |  7.2 |  7.2 |
+------+------+------+
5 rows in set (0.03 sec)

Floating-point values are subject to platform or implementation dependencies. Suppose that you execute the following statements:

CREATE TABLE t1(c1 FLOAT(53,0), c2 FLOAT(53,0));
INSERT INTO t1 VALUES('1e+52','-1e+52');
SELECT * FROM t1;

On some platforms, the SELECT statement returns inf and -inf. On others, it returns 0 and -0.

An implication of the preceding issues is that if you attempt to create a replication slave by dumping table contents with mysqldump on the master and reloading the dump file into the slave, tables containing floating-point columns might differ between the two hosts.

https://dev.mysql.com/doc/refman/5.5/en/problems-with-float.html

How to make a Python script run like a service or daemon in Linux

You have two options here.

  1. Make a proper cron job that calls your script. Cron is a common name for a GNU/Linux daemon that periodically launches scripts according to a schedule you set. You add your script into a crontab or place a symlink to it into a special directory and the daemon handles the job of launching it in the background. You can read more at Wikipedia. There is a variety of different cron daemons, but your GNU/Linux system should have it already installed.

  2. Use some kind of python approach (a library, for example) for your script to be able to daemonize itself. Yes, it will require a simple event loop (where your events are timer triggering, possibly, provided by sleep function).

I wouldn't recommend you to choose 2., because you would be, in fact, repeating cron functionality. The Linux system paradigm is to let multiple simple tools interact and solve your problems. Unless there are additional reasons why you should make a daemon (in addition to trigger periodically), choose the other approach.

Also, if you use daemonize with a loop and a crash happens, no one will check the mail after that (as pointed out by Ivan Nevostruev in comments to this answer). While if the script is added as a cron job, it will just trigger again.

How to store images in mysql database using php

<!-- 
//THIS PROGRAM WILL UPLOAD IMAGE AND WILL RETRIVE FROM DATABASE. UNSING BLOB
(IF YOU HAVE ANY QUERY CONTACT:[email protected])


CREATE TABLE  `images` (
  `id` int(100) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `image` longblob NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB ;

-->
<!-- this form is user to store images-->
<form action="index.php" method="post"  enctype="multipart/form-data">
Enter the Image Name:<input type="text" name="image_name" id="" /><br />

<input name="image" id="image" accept="image/JPEG" type="file"><br /><br />
<input type="submit" value="submit" name="submit" />
</form>
<br /><br />
<!-- this form is user to display all the images-->
<form action="index.php" method="post"  enctype="multipart/form-data">
Retrive all the images:
<input type="submit" value="submit" name="retrive" />
</form>



<?php
//THIS IS INDEX.PHP PAGE
//connect to database.db name is images
        mysql_connect("", "", "") OR DIE (mysql_error());
        mysql_select_db ("") OR DIE ("Unable to select db".mysql_error());
//to retrive send the page to another page
if(isset($_POST['retrive']))
{
    header("location:search.php");

}

//to upload
if(isset($_POST['submit']))
{
if(isset($_FILES['image'])) {
        $name=$_POST['image_name'];
        $email=$_POST['mail'];
        $fp=addslashes(file_get_contents($_FILES['image']['tmp_name'])); //will store the image to fp
        }
                // our sql query
                $sql = "INSERT INTO images VALUES('null', '{$name}','{$fp}');";
                            mysql_query($sql) or die("Error in Query insert: " . mysql_error());
} 
?>



<?php
//SEARCH.PHP PAGE
    //connect to database.db name = images
         mysql_connect("localhost", "root", "") OR DIE (mysql_error());
        mysql_select_db ("image") OR DIE ("Unable to select db".mysql_error());
//display all the image present in the database

        $msg="";
        $sql="select * from images";
        if(mysql_query($sql))
        {
            $res=mysql_query($sql);
            while($row=mysql_fetch_array($res))
            {
                    $id=$row['id'];
                    $name=$row['name'];
                    $image=$row['image'];

                  $msg.= '<a href="search.php?id='.$id.'"><img src="data:image/jpeg;base64,'.base64_encode($row['image']). ' " />   </a>';

            }
        }
        else
            $msg.="Query failed";
?>
<div>
<?php
echo $msg;
?>

What’s the difference between “{}” and “[]” while declaring a JavaScript array?

When you declare

var a=[];

you are declaring a empty array.

But when you are declaring

var a={};

you are declaring a Object .

Although Array is also Object in Javascript but it is numeric key paired values. Which have all the functionality of object but Added some few method of Array like Push,Splice,Length and so on.

So if you want Some values where you need to use numeric keys use Array. else use object. you can Create object like:

var a={name:"abc",age:"14"}; 

And can access values like

console.log(a.name);

How to use IntelliJ IDEA to find all unused code?

Just use Analyze | Inspect Code with appropriate inspection enabled (Unused declaration under Declaration redundancy group).

Using IntelliJ 11 CE you can now "Analyze | Run Inspection by Name ... | Unused declaration"

FULL OUTER JOIN vs. FULL JOIN

Actually they are the same. LEFT OUTER JOIN is same as LEFT JOIN and RIGHT OUTER JOIN is same as RIGHT JOIN. It is more informative way to compare from INNER Join.

See this Wikipedia article for details.

Rename a table in MySQL

Table name change

RENAME TABLE old_table_name TO new_table_name;

Is it possible to simulate key press events programmatically?

It was single rowed once due to easy usage in a console context. But probably useful still.

_x000D_
_x000D_
var pressthiskey = "q"/* <-- q for example */;
var e = new Event("keydown");
e.key = pressthiskey;
e.keyCode = e.key.charCodeAt(0);
e.which = e.keyCode;
e.altKey = false;
e.ctrlKey = true;
e.shiftKey = false;
e.metaKey = false;
e.bubbles = true;
document.dispatchEvent(e);
_x000D_
_x000D_
_x000D_

How do I update/upsert a document in Mongoose?

app.put('url', function(req, res) {

        // use our bear model to find the bear we want
        Bear.findById(req.params.bear_id, function(err, bear) {

            if (err)
                res.send(err);

            bear.name = req.body.name;  // update the bears info

            // save the bear
            bear.save(function(err) {
                if (err)
                    res.send(err);

                res.json({ message: 'Bear updated!' });
            });

        });
    });

Here is a better approach to solving the update method in mongoose, you can check Scotch.io for more details. This definitely worked for me!!!

How often does python flush to a file?

You can also check the default buffer size by calling the read only DEFAULT_BUFFER_SIZE attribute from io module.

import io
print (io.DEFAULT_BUFFER_SIZE)

How to use WPF Background Worker

You may want to also look into using Task instead of background workers.

The easiest way to do this is in your example is Task.Run(InitializationThread);.

There are several benefits to using tasks instead of background workers. For example, the new async/await features in .net 4.5 use Task for threading. Here is some documentation about Task https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task

How to access the request body when POSTing using Node.js and Express?

In my case, I was missing to set the header:

"Content-Type: application/json"

SQLite Query in Android to count rows

Use an SQLiteStatement.

e.g.

 SQLiteStatement s = mDb.compileStatement( "select count(*) from users where uname='" + loginname + "' and pwd='" + loginpass + "'; " );

  long count = s.simpleQueryForLong();

Setting maxlength of textbox with JavaScript or jQuery

<head>
    <script type="text/javascript">
        function SetMaxLength () {
            var input = document.getElementById ("myInput");
            input.maxLength = 10;
        }
    </script>
</head>
<body>
    <input id="myInput" type="text" size="20" />
</body>

SSLHandshakeException: No subject alternative names present

Thanks,Bruno for giving me heads up on Common Name and Subject Alternative Name. As we figured out certificate was generated with CN with DNS name of network and asked for regeneration of new certificate with Subject Alternative Name entry i.e. san=ip:10.0.0.1. which is the actual solution.

But, we managed to find out a workaround with which we can able to run on development phase. Just add a static block in the class from which we are making ssl connection.

static {
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
        {
            public boolean verify(String hostname, SSLSession session)
            {
                // ip address of the service URL(like.23.28.244.244)
                if (hostname.equals("23.28.244.244"))
                    return true;
                return false;
            }
        });
}

If you happen to be using Java 8, there is a much slicker way of achieving the same result:

static {
    HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> hostname.equals("127.0.0.1"));
}

MySQL my.cnf file - Found option without preceding group

it is because of letters or digit infront of [mysqld] just check the leeters or digit anything is not required before [mysqld]

it may be something like

0[mysqld] then this error will occur

Parsing XML with namespace in Python via 'ElementTree'

To get the namespace in its namespace format, e.g. {myNameSpace}, you can do the following:

root = tree.getroot()
ns = re.match(r'{.*}', root.tag).group(0)

This way, you can use it later on in your code to find nodes, e.g using string interpolation (Python 3).

link = root.find(f"{ns}link")

Could not load file or assembly "System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

I had this, but, it was because I had added a NuGet package that had updated the binding redirects. Once I removed the package, the redirects were still there. I removed all of them, and then ran update-package -reinstall. This added the correct redirects.

How to delete/unset the properties of a javascript object?

simply use delete, but be aware that you should read fully what the effects are of using this:

 delete object.index; //true
 object.index; //undefined

but if I was to use like so:

var x = 1; //1
delete x; //false
x; //1

but if you do wish to delete variables in the global namespace, you can use it's global object such as window, or using this in the outermost scope i.e

var a = 'b';
delete a; //false
delete window.a; //true
delete this.a; //true

http://perfectionkills.com/understanding-delete/

another fact is that using delete on an array will not remove the index but only set the value to undefined, meaning in certain control structures such as for loops, you will still iterate over that entity, when it comes to array's you should use splice which is a prototype of the array object.

Example Array:

var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

if I was to do:

delete myCars[1];

the resulting array would be:

["Saab", undefined, "BMW"]

but using splice like so:

myCars.splice(1,1);

would result in:

["Saab", "BMW"]

Stored Procedure parameter default value - is this a constant or a variable

It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.

Look at the definition of sys.all_parameters:

default_value sql_variant If has_default_value is 1, the value of this column is the value of the default for the parameter; otherwise, NULL.

That is, whatever the default for a parameter is, it has to fit in that column.


As Alex K pointed out in the comments, you can just do:

CREATE PROCEDURE [dbo].[problemParam] 
    @StartDate INT = NULL,
    @EndDate INT = NULL
AS  
BEGIN
   SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))

provided that NULL isn't intended to be a valid value for @StartDate.


As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE() within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.

Why is this rsync connection unexpectedly closed on Windows?

i get the solution. i've using cygwin and this is the problem the rsync command for Windows work only in windows shell and works in the windows powershell.

A few times it has happened the same error between two linux boxes. and appears to be by incompatible versions of rsync

fatal: Unable to create temporary file '/home/username/git/myrepo.git/./objects/pack/tmp_pack_XXXXXX': Permission denied

I resolved it by giving permission to the user on each of the directories that you're using, like so:

sudo chown user /home/user/git

and so on.

GitHub: invalid username or password

  1. Control panel
  2. Credential manager
  3. Look for options webcredentials and windows credentials
  4. in either one you will find github credentials fix it with correct credentials
  5. open new instance of git bash you should be able to perform your git commands.

This worked for me, I was able to pull and push into my remote repo.

How to find the array index with a value?

In a multidimensional array.


Reference array:

var array = [
    { ID: '100', },
    { ID: '200', },
    { ID: '300', },
    { ID: '400', },
    { ID: '500', }
];

Using filter and indexOf:

var in_array = array.filter(function(item) { 
    return item.ID == '200' // look for the item where ID is equal to value
});
var index = array.indexOf(in_array[0]);

Looping through each item in the array using indexOf:

for (var i = 0; i < array.length; i++) {
    var item= array[i];
    if (item.ID == '200') { 
        var index = array.indexOf(item);
    }
}

hibernate could not get next sequence value

I got same error before, type this query in your database CREATE SEQUENCE hibernate_sequence START WITH 1 INCREMENT BY 1 NOCYCLE;

that's work for me, good luck ~

How to check if an excel cell is empty using Apache POI?

Try below code:

String empty = "-";
if (row.getCell(3) == null || row.getCell(3).getCellType() == Cell.CELL_TYPE_BLANK) {
    upld.setValue(empty);
} else {
    upld.setValue(row.getCell(3).getStringCellValue());
}

error LNK2005: xxx already defined in MSVCRT.lib(MSVCR100.dll) C:\something\LIBCMT.lib(setlocal.obj)

Getting this error, I changed the

c/C++ > Code Generation > Runtime Library to Multi-threaded library (DLL) /MD

for both code project and associated Google Test project. This solved the issue.

Note: all components of the project must have the same definition in c/C++ > Code Generation > Runtime Library. Either DLL or not DLL, but identical.

LoDash: Get an array of values from an array of object properties

In the new lodash release v4.0.0 _.pluck has removed in favor of _.map

Then you can use this:

_.map(users, 'id'); // [12, 14, 16, 18]

You can see in Github Changelog

Cloud Firestore collection count

This uses counting to create numeric unique ID. In my use, I will not be decrementing ever, even when the document that the ID is needed for is deleted.

Upon a collection creation that needs unique numeric value

  1. Designate a collection appData with one document, set with .doc id only
  2. Set uniqueNumericIDAmount to 0 in the firebase firestore console
  3. Use doc.data().uniqueNumericIDAmount + 1 as the unique numeric id
  4. Update appData collection uniqueNumericIDAmount with firebase.firestore.FieldValue.increment(1)
firebase
    .firestore()
    .collection("appData")
    .doc("only")
    .get()
    .then(doc => {
        var foo = doc.data();
        foo.id = doc.id;

        // your collection that needs a unique ID
        firebase
            .firestore()
            .collection("uniqueNumericIDs")
            .doc(user.uid)// user id in my case
            .set({// I use this in login, so this document doesn't
                  // exist yet, otherwise use update instead of set
                phone: this.state.phone,// whatever else you need
                uniqueNumericID: foo.uniqueNumericIDAmount + 1
            })
            .then(() => {

                // upon success of new ID, increment uniqueNumericIDAmount
                firebase
                    .firestore()
                    .collection("appData")
                    .doc("only")
                    .update({
                        uniqueNumericIDAmount: firebase.firestore.FieldValue.increment(
                            1
                        )
                    })
                    .catch(err => {
                        console.log(err);
                    });
            })
            .catch(err => {
                console.log(err);
            });
    });

SQL left join vs multiple tables on FROM line?

Basically, when your FROM clause lists tables like so:

SELECT * FROM
  tableA, tableB, tableC

the result is a cross product of all the rows in tables A, B, C. Then you apply the restriction WHERE tableA.id = tableB.a_id which will throw away a huge number of rows, then further ... AND tableB.id = tableC.b_id and you should then get only those rows you are really interested in.

DBMSs know how to optimise this SQL so that the performance difference to writing this using JOINs is negligible (if any). Using the JOIN notation makes the SQL statement more readable (IMHO, not using joins turns the statement into a mess). Using the cross product, you need to provide join criteria in the WHERE clause, and that's the problem with the notation. You are crowding your WHERE clause with stuff like

    tableA.id = tableB.a_id 
AND tableB.id = tableC.b_id 

which is only used to restrict the cross product. WHERE clause should only contain RESTRICTIONS to the resultset. If you mix table join criteria with resultset restrictions, you (and others) will find your query harder to read. You should definitely use JOINs and keep the FROM clause a FROM clause, and the WHERE clause a WHERE clause.

Check if a string contains a string in C++

#include <algorithm>        // std::search
#include <string>
using std::search; using std::count; using std::string;

int main() {
    string mystring = "The needle in the haystack";
    string str = "needle";
    string::const_iterator it;
    it = search(mystring.begin(), mystring.end(), 
                str.begin(), str.end()) != mystring.end();

    // if string is found... returns iterator to str's first element in mystring
    // if string is not found... returns iterator to mystring.end()

if (it != mystring.end())
    // string is found
else
    // not found

return 0;
}

How to split csv whose columns may contain ,

I had a problem with a CSV that contains fields with a quote character in them, so using the TextFieldParser, I came up with the following:

private static string[] parseCSVLine(string csvLine)
{
  using (TextFieldParser TFP = new TextFieldParser(new MemoryStream(Encoding.UTF8.GetBytes(csvLine))))
  {
    TFP.HasFieldsEnclosedInQuotes = true;
    TFP.SetDelimiters(",");

    try 
    {           
      return TFP.ReadFields();
    }
    catch (MalformedLineException)
    {
      StringBuilder m_sbLine = new StringBuilder();

      for (int i = 0; i < TFP.ErrorLine.Length; i++)
      {
        if (i > 0 && TFP.ErrorLine[i]== '"' &&(TFP.ErrorLine[i + 1] != ',' && TFP.ErrorLine[i - 1] != ','))
          m_sbLine.Append("\"\"");
        else
          m_sbLine.Append(TFP.ErrorLine[i]);
      }

      return parseCSVLine(m_sbLine.ToString());
    }
  }
}

A StreamReader is still used to read the CSV line by line, as follows:

using(StreamReader SR = new StreamReader(FileName))
{
  while (SR.Peek() >-1)
    myStringArray = parseCSVLine(SR.ReadLine());
}

jQuery class within class selector

For this html:

<div class="outer">
     <div class="inner"></div>
</div>

This selector should work:

$('.outer > .inner')

How do I align spans or divs horizontally?

You can use

.floatybox {
     display: inline-block;
     width: 123px;
}

If you only need to support browsers that have support for inline blocks. Inline blocks can have width, but are inline, like button elements.

Oh, and you might wnat to add vertical-align: top on the elements to make sure things line up

SQL Server - NOT IN

SELECT [T1].*
FROM [Table1] AS [T1]
WHERE  NOT EXISTS (SELECT 
    1 AS [C1]
    FROM [Table2] AS [T2]
    WHERE ([T2].[MAKE] = [T1].[MAKE]) AND
        ([T2].[MODEL] = [T1].[MODEL]) AND
        ([T2].[Serial Number] = [T1].[Serial Number])
);

Is it better to return null or empty collection?

It seems to me that you should return the value that is semantically correct in context, whatever that may be. A rule that says "always return an empty collection" seems a little simplistic to me.

Suppose in, say, a system for a hospital, we have a function that is supposed to return a list of all previous hospitalizations for the past 5 years. If the customer has not been in the hospital, it makes good sense to return an empty list. But what if the customer left that part of the admittance form blank? We need a different value to distinguish "empty list" from "no answer" or "don't know". We could throw an exception, but it's not necessarily an error condition, and it doesn't necessarily drive us out of the normal program flow.

I've often been frustrated by systems that cannot distinguish between zero and no answer. I've had a number of times where a system has asked me to enter some number, I enter zero, and I get an error message telling me that I must enter a value in this field. I just did: I entered zero! But it won't accept zero because it can't distinguish it from no answer.


Reply to Saunders:

Yes, I'm assuming that there's a difference between "Person didn't answer the question" and "The answer was zero." That was the point of the last paragraph of my answer. Many programs are unable to distinguish "don't know" from blank or zero, which seems to me a potentially serious flaw. For example, I was shopping for a house a year or so ago. I went to a real estate web site and there were many houses listed with an asking price of $0. Sounded pretty good to me: They're giving these houses away for free! But I'm sure the sad reality was that they just hadn't entered the price. In that case you may say, "Well, OBVIOUSLY zero means they didn't enter the price -- nobody's going to give a house away for free." But the site also listed the average asking and selling prices of houses in various towns. I can't help but wonder if the average didn't include the zeros, thus giving an incorrectly low average for some places. i.e. what is the average of $100,000; $120,000; and "don't know"? Technically the answer is "don't know". What we probably really want to see is $110,000. But what we'll probably get is $73,333, which would be completely wrong. Also, what if we had this problem on a site where users can order on-line? (Unlikely for real estate, but I'm sure you've seen it done for many other products.) Would we really want "price not specified yet" to be interpreted as "free"?

RE having two separate functions, an "is there any?" and an "if so, what is it?" Yes, you certainly could do that, but why would you want to? Now the calling program has to make two calls instead of one. What happens if a programmer fails to call the "any?" and goes straight to the "what is it?" ? Will the program return a mis-leading zero? Throw an exception? Return an undefined value? It creates more code, more work, and more potential errors.

The only benefit I see is that it enables you to comply with an arbitrary rule. Is there any advantage to this rule that makes it worth the trouble of obeying it? If not, why bother?


Reply to Jammycakes:

Consider what the actual code would look like. I know the question said C# but excuse me if I write Java. My C# isn't very sharp and the principle is the same.

With a null return:

HospList list=patient.getHospitalizationList(patientId);
if (list==null)
{
   // ... handle missing list ...
}
else
{
  for (HospEntry entry : list)
   //  ... do whatever ...
}

With a separate function:

if (patient.hasHospitalizationList(patientId))
{
   // ... handle missing list ...
}
else
{
  HospList=patient.getHospitalizationList(patientId))
  for (HospEntry entry : list)
   // ... do whatever ...
}

It's actually a line or two less code with the null return, so it's not more burden on the caller, it's less.

I don't see how it creates a DRY issue. It's not like we have to execute the call twice. If we always wanted to do the same thing when the list does not exist, maybe we could push handling down to the get-list function rather than having the caller do it, and so putting the code in the caller would be a DRY violation. But we almost surely don't want to always do the same thing. In functions where we must have the list to process, a missing list is an error that might well halt processing. But on an edit screen, we surely don't want to halt processing if they haven't entered data yet: we want to let them enter data. So handling "no list" must be done at the caller level one way or another. And whether we do that with a null return or a separate function makes no difference to the bigger principle.

Sure, if the caller doesn't check for null, the program could fail with a null-pointer exception. But if there's a separate "got any" function and the caller doesn't call that function but blindly calls the "get list" function, then what happens? If it throws an exception or otherwise fails, well, that's pretty much the same as what would happen if it returned null and didn't check for it. If it returns an empty list, that's just wrong. You're failing to distinguish between "I have a list with zero elements" and "I don't have a list". It's like returning zero for the price when the user didn't enter any price: it's just wrong.

I don't see how attaching an additional attribute to the collection helps. The caller still has to check it. How is that better than checking for null? Again, the absolute worst thing that could happen is for the programmer to forget to check it, and give incorrect results.

A function that returns null is not a surprise if the programmer is familiar with the concept of null meaning "don't have a value", which I think any competent programmer should have heard of, whether he thinks it's a good idea or not. I think having a separate function is more of a "surprise" problem. If a programmer is unfamiliar with the API, when he runs a test with no data he'll quickly discover that sometimes he gets back a null. But how would he discover the existence of another function unless it occurred to him that there might be such a function and he checks the documentation, and the documentation is complete and comprehensible? I would much rather have one function that always gives me a meaningful response, rather than two functions that I have to know and remember to call both.

VirtualBox Cannot register the hard disk already exists

After struggling for many days finally found a solution that works perfectly.

Mac OS open ~/Library folder (in your home directory) and delete the VirtulBox folder. This will remove all configurations and you can start the virtual box again!

Others look for .virtualbox folder in your home directory. Remove it and open VirtualBox should solve your issue.

Cheers!!

How do I list all remote branches in Git 1.7+?

I ended up doing a mess shell pipeline to get what I wanted. I just merged branches from the origin remote:

git branch -r --all --merged \
    | tail -n +2 \
    | grep -P '^  remotes/origin/(?!HEAD)' \
    | perl -p -e 's/^  remotes\/origin\///g;s/master\n//g'

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

Hibernate tries to insert data that violate underlying database integrity contraints.

There's probably misconfiguration in hibernate persistent classes and/or mapping configuration (*.hbm.xml or annotations in persitent classes).

Maybe a property of the bean you want to save is not type-compatible with its related field in database (could explain the constraint [numbering] part).

PHP: how can I get file creation date?

This is the example code taken from the PHP documentation here: https://www.php.net/manual/en/function.filemtime.php

// outputs e.g.  somefile.txt was last changed: December 29 2002 22:16:23.

$filename = 'somefile.txt';

if (file_exists($filename)) {

    echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}

The code specifies the filename, then checks if it exists and then displays the modification time using filemtime().

filemtime() takes 1 parameter which is the path to the file, this can be relative or absolute.

Eclipse IDE for Java - Full Dark Theme

Windows 10 users

If you want to get a custom window title color on Windows 10, in short going from this

eclipse - white window title

to this (or any other custom color for the window of your Eclipse IDE)

eclipse - full black

follow the next steps.

Go to C:\Windows\Resources\Themes\. Duplicate the folder aero and the file aero.theme. If you can't duplicate the folder and the file then right click on both, Properties, Security, Modify, add your user to Permissions, and set authorizations to modify, read and write.

Rename the folder C:\Windows\Resources\Themes\aero - copy and the file C:\Windows\Resources\Themes\aero - copy.theme to C:\Windows\Resources\Themes\custom and C:\Windows\Resources\Themes\custom.theme (you can pick the name you want).

themes folder

Rename C:\Windows\Resources\Themes\custom\aero.msstyles to C:\Windows\Resources\Themes\custom.msstyles.

custom theme folder

Rename C:\Windows\Resources\Themes\custom\%your_locale%\aero.msstyles.mui (%your_locale% is fr-FR in my case) to C:\Windows\Resources\Themes\custom\%your_locale%\custom.msstyles.mui.

custom theme - locale folder

Edit custom.theme with Notepad and change the PATH variable of VisualStyles to your custom.msstyles.

changing theme path

Set your custom theme (yet unchanged) by double-clicking on custom.theme. Then right-click on start menu button, go to Parameters -> Customize appearance -> Themes and select the second one. Go to the menu Colors, select dark mode for every applications. Choose custom color for accent color and put it full black.

start menu - parameters

choosing custom theme

changin custom theme

custom accent color

custom accent color set to black

Apply your favorite dark theme (here DevStyle - Darkest dark - Deep black) to Eclipse and voilà, you have a full dark theme for Eclipse on Windows 10!

eclipse - full black

How to get a time zone from a location using latitude and longitude coordinates?

  1. There are several sources online that have geojson data for timezones (here's one, here's another)

  2. Use a geometry library to create polygon objects from the geojson coordinates (shapely [python], GEOS [c++], JTS [java], NTS [.net]).

  3. Convert your lat/lng to a point object (however your library represents that) and check if it intersects the timezone polygon.

    from shapely.geometry import Polygon, Point
    
    def get_tz_from_lat_lng(lat, lng):
        for tz, geojson in timezones.iteritems():
            coordinates = geojson['features'][0]['geometry']['coordinates']
            polygon = Polygon(coordinates)
            point = Point(lng, lat)
            if polygon.contains(point):
                return tz
    

Where are environment variables stored in the Windows Registry?

There is a more efficient way of doing this in Windows 7. SETX is installed by default and supports connecting to other systems.

To modify a remote system's global environment variables, you would use

setx /m /s HOSTNAME-GOES-HERE VariableNameGoesHere VariableValueGoesHere

This does not require restarting Windows Explorer.

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

I know this is a bit old but the answer in short would be <load-on-startup> both occurrences have given the same id which is 1 twice. This may confuse loading sequence.

What's the best way to get the last element of an array without deleting it?

To do this and avoid the E_STRICT and not mess with the array's internal pointer you can use:

function lelement($array) {return end($array);}

$last_element = lelement($array);

lelement only works with a copy so it doesn't affect the array's pointer.

jquery-ui-dialog - How to hook into dialog close event

$( "#dialogueForm" ).dialog({
              autoOpen: false,
              height: "auto",
              width: "auto",
              modal: true,
                my: "center",
                at: "center",
                of: window,
              close : function(){
                  // functionality goes here
              }  
              });

"close" property of dialog gives the close event for the same.

Why is using the JavaScript eval function a bad idea?

I won't attempt to refute anything said heretofore, but i will offer this use of eval() that (as far as I know) can't be done any other way. There's probably other ways to code this, and probably ways to optimize it, but this is done longhand and without any bells and whistles for clarity sake to illustrate a use of eval that really doesn't have any other alternatives. That is: dynamical (or more accurately) programmically-created object names (as opposed to values).

//Place this in a common/global JS lib:
var NS = function(namespace){
    var namespaceParts = String(namespace).split(".");
    var namespaceToTest = "";
    for(var i = 0; i < namespaceParts.length; i++){
        if(i === 0){
            namespaceToTest = namespaceParts[i];
        }
        else{
            namespaceToTest = namespaceToTest + "." + namespaceParts[i];
        }

        if(eval('typeof ' + namespaceToTest) === "undefined"){
            eval(namespaceToTest + ' = {}');
        }
    }
    return eval(namespace);
}


//Then, use this in your class definition libs:
NS('Root.Namespace').Class = function(settings){
  //Class constructor code here
}
//some generic method:
Root.Namespace.Class.prototype.Method = function(args){
    //Code goes here
    //this.MyOtherMethod("foo"));  // => "foo"
    return true;
}


//Then, in your applications, use this to instantiate an instance of your class:
var anInstanceOfClass = new Root.Namespace.Class(settings);

EDIT: by the way, I wouldn't suggest (for all the security reasons pointed out heretofore) that you base you object names on user input. I can't imagine any good reason you'd want to do that though. Still, thought I'd point it out that it wouldn't be a good idea :)

Splitting a C++ std::string using tokens, e.g. ";"

There are several libraries available solving this problem, but the simplest is probably to use Boost Tokenizer:

#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>

typedef boost::tokenizer<boost::char_separator<char> > tokenizer;

std::string str("denmark;sweden;india;us");
boost::char_separator<char> sep(";");
tokenizer tokens(str, sep);

BOOST_FOREACH(std::string const& token, tokens)
{
    std::cout << "<" << *tok_iter << "> " << "\n";
}

Excel - Shading entire row based on change of value

I had to do something similar for my users, with a small variant that they want to have a running number grouping the similar items. Thought I'd share it here.

  • Make a new column A
  • Assuming the first row of data is in row 2 (row 1 being header), put 1 in A2
  • Assuming your File No is in column B, in the second row (in this case A3) make the formula =IF(B3=B2,A2,A2+1)
  • Fill/copy-paste cell A3 down the column to the last row (be careful not to copy A2 by accident; that will populate all cells with 1)
  • Select the data range
  • In the Home ribbon select Conditional Formatting -> New Rule
  • Choose Use a formula to determine which cells to format
  • In the formula cell, put =MOD($A1, 2)=1 as the formula
  • Click Format, select the Fill tab
  • Select the Background Color you want, then click OK
  • Click OK

enter image description here

Is it acceptable and safe to run pip install under sudo?

Your original problem is that pip cannot write the logs to the folder.

IOError: [Errno 13] Permission denied: '/Users/markwalker/Library/Logs/pip.log'

You need to cd into a folder in which the process invoked can write like /tmp so a cd /tmp and re invoking the command will probably work but is not what you want.

BUT actually for this particular case (you not wanting to use sudo for installing python packages) and no need for global package installs you can use the --user flag like this :

pip install --user <packagename>

and it will work just fine.

I assume you have a one user python python installation and do not want to bother with reading about virtualenv (which is not very userfriendly) or pipenv.

As some people in the comments section have pointed out the next approach is not a very good idea unless you do not know what to do and got stuck:

Another approach for global packages like in your case you want to do something like :

chown -R $USER /Library/Python/2.7/site-packages/

or more generally

chown -R $USER <path to your global pip packages>

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

Do you use the ob_start(ob_gzhandler) function? If so and If you output any content above the ob_start(ob_gzhandler) function, you'll get this error. You can don't use this function or don't output content above this function. The ob_gzhandler callback function will determine what type of content encoding the browser will accept and will return its output accordingly. So if you output content above this function, the content's encoding maybe different from the output content of ob_gzhandler and that cause this error.

How do I set the default page of my application in IIS7?

Just go to web.config file and add following

<system.webServer>
    <defaultDocument>
      <files>
        <clear />
        <add value="Path of your Page" />
      </files>
    </defaultDocument>
</system.webServer>

What is the Python 3 equivalent of "python -m SimpleHTTPServer"

The equivalent is:

python3 -m http.server

Pressed <button> selector

You can do this with php if the button opens a new page.

For example if the button link to a page named pagename.php as, url: www.website.com/pagename.php the button will stay red as long as you stay on that page.

I exploded the url by '/' an got something like:

url[0] = pagename.php

<? $url = explode('/', substr($_SERVER['REQUEST_URI'], strpos('/',$_SERVER['REQUEST_URI'] )+1,strlen($_SERVER['REQUEST_URI']))); ?>


<html>
<head>
  <style>
    .btn{
     background:white;
     }
    .btn:hover,
    .btn-on{
     background:red;
     }
  </style>
</head>
<body>
   <a href="/pagename.php" class="btn <? if (url[0]='pagename.php') {echo 'btn-on';} ?>">Click Me</a>
</body>
</html>

note: I didn't try this code. It might need adjustments.

Razor MVC Populating Javascript array with Model Array

To expand on the top-voted answer, for reference, if the you want to add more complex items to the array:

@:myArray.push(ClassMember1: "@d.ClassMember1", ClassMember2: "@d.ClassMember2");

etc.

Furthermore, if you want to pass the array as a parameter to your controller, you can stringify it first:

myArray = JSON.stringify({ 'myArray': myArray });

Checking if a double (or float) is NaN in C++

As comments above state a != a will not work in g++ and some other compilers, but this trick should. It may not be as efficient, but it's still a way:

bool IsNan(float a)
{
    char s[4];
    sprintf(s, "%.3f", a);
    if (s[0]=='n') return true;
    else return false;
}

Basically, in g++ (I am not sure about others though) printf prints 'nan' on %d or %.f formats if variable is not a valid integer/float. Therefore this code is checking for the first character of string to be 'n' (as in "nan")

Select element by exact match of its content

Try add a extend pseudo function:

$.expr[':'].textEquals = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return $(elem).text().match("^" + arg + "$");
    };
});

Then you can do:

$('p:textEquals("Hello World")');

Mixing a PHP variable with a string literal

You can use {} arround your variable, to separate it from what's after:

echo "{$test}y"

As reference, you can take a look to the Variable parsing - Complex (curly) syntax section of the PHP manual.

How to run travis-ci locally

UPDATE: I now have a complete turnkey, all-in-one answer, see https://stackoverflow.com/a/49019950/300224. Only took 3 years to figure out!

According to the Travis documentation: https://github.com/travis-ci/travis-ci there is a concoction of projects that collude to deliver the Travis CI web service we know and love. The following subset of projects appears to allow local make test functionality using the .travis.yml in your project:

travis-build

travis-build creates the build script for each job. It takes the configuration from the .travis.yml file and creates a bash script that is then run in the build environment by travis-worker.

travis-cookbooks

travis-cookbooks holds the Chef cookbooks that are used to provision the build environments.

travis-worker

travis-worker is responsible for running the build scripts in a clean environment. It streams the log output to travis-logs and pushes state updates (build starting/finishing) to travis-hub.

(The other subprojects are responsible for communicating with GitHub, their web interface, email, and their API.)

What is the iBeacon Bluetooth Profile

It’s very simple, it just advertises a string which contains a few characters conforming to Apple’s iBeacon standard. you can refer the Link http://glimwormbeacons.com/learn/what-makes-an-ibeacon-an-ibeacon/

onNewIntent() lifecycle and registered listeners

Note: Calling a lifecycle method from another one is not a good practice. In below example I tried to achieve that your onNewIntent will be always called irrespective of your Activity type.

OnNewIntent() always get called for singleTop/Task activities except for the first time when activity is created. At that time onCreate is called providing to solution for few queries asked on this thread.

You can invoke onNewIntent always by putting it into onCreate method like

@Override
public void onCreate(Bundle savedState){
    super.onCreate(savedState);
    onNewIntent(getIntent());
}

@Override
protected void onNewIntent(Intent intent) {
  super.onNewIntent(intent);
  //code
}

AndroidStudio: Failed to sync Install build tools

There may be some file access permission/restriction problems. First check to access the below directory manually, check whether your TARGET_VERSION exists, Then check the android sdk manager.

  • sdk/build-tools/{TARGET_VERSION}

svn over HTTP proxy

Okay, this topic is somewhat outdated, but as I found it on google and have a solution this might be interesting for someone:

Basically (of course) this is not possible on every http proxy but works on proxies allowing http connect on port 3690. This method is used by http proxies on port 443 to provide a way for secure https connections. If your administrator configures the proxy to open port 3690 for http connect you can setup your local machine to establish a tunnel through the proxy.

I just was in the need to check out some files from svn.openwrt.org within our companies network. An easy solution to create a tunnel is adding the following line to your /etc/hosts

127.0.0.1 svn.openwrt.org

Afterwards, you can use socat to create a tcp tunnel to a local port:

while true; do socat tcp-listen:3690 proxy:proxy.at.your.company:svn.openwrt.org:3690; done

You should execute the command as root. It opens the local port 3690 and on connection creates a tunnel to svn.openwrt.org on the same port.

Just replace the port and server addresses on your own needs.

vim line numbers - how to have them on by default?

Terminal > su > password > vim /etc/vimrc

Click here and edit as in line number (13):

set nu

click here and Edit as "Line number (13)"

Indent multiple lines quickly in vi

Use the > command. To indent five lines, 5>>. To mark a block of lines and indent it, Vjj> to indent three lines (Vim only). To indent a curly-braces block, put your cursor on one of the curly braces and use >% or from anywhere inside block use >iB.

If you’re copying blocks of text around and need to align the indent of a block in its new location, use ]p instead of just p. This aligns the pasted block with the surrounding text.

Also, the shiftwidth setting allows you to control how many spaces to indent.

Java 8 forEach with index

There are workarounds but no clean/short/sweet way to do it with streams and to be honest, you would probably be better off with:

int idx = 0;
for (Param p : params) query.bind(idx++, p);

Or the older style:

for (int idx = 0; idx < params.size(); idx++) query.bind(idx, params.get(idx));

Get integer value from string in swift

In Swift 3.0

Type 1: Convert NSString to String

    let stringNumb:NSString = "1357"
    let someNumb = Int(stringNumb as String) // 1357 as integer

Type 2: If the String has Integer only

    let stringNumb = "1357"
    let someNumb = Int(stringNumb) // 1357 as integer

Type 3: If the String has Float value

    let stringNumb = "13.57"
    if let stringToFloat = Float(stringNumb){
        let someNumb = Int(stringToFloat)// 13 as Integer
    }else{
       //do something if the stringNumb not have digit only. (i.e.,) let stringNumb = "13er4"
    }

find: missing argument to -exec

You have to put a space between {} and \;

So the command will be like:

find /home/me/download/ -type f -name "*.rm" -exec ffmpeg -i {} -sameq {}.mp3 && rm {} \;

How do you detect Credit card type based on number?

Anatoliy's answer in PHP:

 public static function detectCardType($num)
 {
    $re = array(
        "visa"       => "/^4[0-9]{12}(?:[0-9]{3})?$/",
        "mastercard" => "/^5[1-5][0-9]{14}$/",
        "amex"       => "/^3[47][0-9]{13}$/",
        "discover"   => "/^6(?:011|5[0-9]{2})[0-9]{12}$/",
    );

    if (preg_match($re['visa'],$num))
    {
        return 'visa';
    }
    else if (preg_match($re['mastercard'],$num))
    {
        return 'mastercard';
    }
    else if (preg_match($re['amex'],$num))
    {
        return 'amex';
    }
    else if (preg_match($re['discover'],$num))
    {
        return 'discover';
    }
    else
    {
        return false;
    }
 }

In Tensorflow, get the names of all the Tensors in a graph

You can do

[n.name for n in tf.get_default_graph().as_graph_def().node]

Also, if you are prototyping in an IPython notebook, you can show the graph directly in notebook, see show_graph function in Alexander's Deep Dream notebook

How do I delete NuGet packages that are not referenced by any project in my solution?

First open the Package Manager Console. Then select your project from the dropdown list. And run the following commands for uninstalling nuget packages.

Get-Package

for getting all the package you have installed.

and then

Uninstall-Package PagedList.Mvc

--- to uninstall a package named PagedList.MVC

Message

PM> Uninstall-Package PagedList.Mvc
Successfully removed 'PagedList.Mvc 4.5.0.0' from MCEMRBPP.PIR.

Can you 'exit' a loop in PHP?

break; leaves your loop.

continue; skips any code for the remainder of that loop and goes on to the next loop, so long as the condition is still true.

How to read/write a boolean when implementing the Parcelable interface?

you declare like this

 private boolean isSelectionRight;

write

 out.writeInt(isSelectionRight ? 1 : 0);

read

isSelectionRight  = in.readInt() != 0;

boolean type needs to be converted to something that Parcel supports and so we can convert it to int.

Setting WPF image source in code

Put the frame in a VisualBrush:

VisualBrush brush = new VisualBrush { TileMode = TileMode.None };

brush.Visual = frame;

brush.AlignmentX = AlignmentX.Center;
brush.AlignmentY = AlignmentY.Center;
brush.Stretch = Stretch.Uniform;

Put the VisualBrush in GeometryDrawing

GeometryDrawing drawing = new GeometryDrawing();

drawing.Brush = brush;

// Brush this in 1, 1 ratio
RectangleGeometry rect = new RectangleGeometry { Rect = new Rect(0, 0, 1, 1) };
drawing.Geometry = rect;

Now put the GeometryDrawing in a DrawingImage:

new DrawingImage(drawing);

Place this on your source of the image, and voilà!

You could do it a lot easier though:

<Image>
    <Image.Source>
        <BitmapImage UriSource="/yourassembly;component/YourImage.PNG"></BitmapImage>
    </Image.Source>
</Image>

And in code:

BitmapImage image = new BitmapImage { UriSource="/yourassembly;component/YourImage.PNG" };

What version of javac built my jar?

A jar is merely a container. It is a file archive a la tar. While a jar may have interesting information contained within it's META-INF hierarchy, it has no obligation to specify the vintage of the classes within it's contents. For that, one must examine the class files therein.

As as Peter Lawrey mentioned in comment to the original question, you can't necessarily know which JDK release built a given class file, but you can find out the byte code class version of the class file contained in a jar.

Yes, this kinda sucks, but the first step is to extract one or more classes from the jar. For example:

$ jar xf log4j-1.2.15.jar

On Linux, Mac OS X or Windows with Cygwin installed, the file(1) command knows the class version.

$ file ./org/apache/log4j/Appender.class
./org/apache/log4j/Appender.class: compiled Java class data, version 45.3

Or alternatively, using javap from the JDK as @jikes.thunderbolt aptly points out:

$ javap -v ./org/apache/log4j/Appender.class | grep major
 major version: 45

For Windows environments without either file or grep

> javap -v ./org/apache/log4j/Appender.class | findstr major
 major version: 45

FWIW, I will concur that javap will tell a whole lot more about a given class file than the original question asked.

Anyway, a different class version, for example:

$ file ~/bin/classes/P.class
/home/dave/bin/classes/P.class: compiled Java class data, version 50.0

The class version major number corresponds to the following Java JDK versions:

  • 45.3 = Java 1.1
  • 46 = Java 1.2
  • 47 = Java 1.3
  • 48 = Java 1.4
  • 49 = Java 5
  • 50 = Java 6
  • 51 = Java 7
  • 52 = Java 8
  • 53 = Java 9
  • 54 = Java 10
  • 55 = Java 11
  • 56 = Java 12
  • 57 = Java 13
  • 58 = Java 14

What is cardinality in Databases?

Cardinality of a set is the namber of the elements in set for we have a set a > a,b,c < so ths set contain 3 elements 3 is the cardinality of that set

Error while inserting date - Incorrect date value:

I had a different cause for this error. I tried to insert a date without using quotes and received a strange error telling me I had tried to insert a date from 2003.

My error message:

Although I was already using the YYYY-MM-DD format, I forgot to add quotes around the date. Even though it is a date and not a string, quotes are still required.

Resizing an Image without losing any quality

Here is a forum thread that provides a C# image resizing code sample. You could use one of the GD library binders to do resampling in C#.

How do I get a file's last modified time in Perl?

You need the stat call, and the file name:

my $last_mod_time = (stat ($file))[9];

Perl also has a different version:

my $last_mod_time = -M $file;

but that value is relative to when the program started. This is useful for things like sorting, but you probably want the first version.

AngularJS multiple filter with custom filter function

Try this:

<tr ng-repeat="player in players | filter:{id: player_id, name:player_name} | filter:ageFilter">

$scope.ageFilter = function (player) {
    return (player.age > $scope.min_age && player.age < $scope.max_age);
}

Show popup after page load

    <script type="text/javascript">
        $(window).on('load',function(){
            setTimeout(function(){ alert(" //show popup"); }, 5000); 
        });
    </script>

SQL Server AS statement aliased column within WHERE statement

Both accepted answer and Logical Processing Order explain why you could not do what you proposed.

Possible solution:

  • use derived table (cte/subquery)
  • use expression in WHERE
  • create view/computed column

From SQL Server 2008 you could use APPLY operator combined with Table valued Constructor:

SELECT *, s.distance
FROM poi_table 
CROSS APPLY (VALUES(6371*1000*acos(cos(radians(42.3936868308))*cos(radians(lat))*cos(radians(lon)-radians(-72.5277256966))+sin(radians(42.3936868308))*sin(radians(lat))))) AS s(distance)
WHERE distance < 500;

LiveDemo

How can I join multiple SQL tables using the IDs?

Simple INNER JOIN VIEW code....

CREATE VIEW room_view
AS SELECT a.*,b.*
FROM j4_booking a INNER JOIN j4_scheduling b
on a.room_id = b.room_id;

Rails: select unique values from a column

This works too.

Model.pluck("DISTINCT rating")

SignalR Console app example

The Self-Host now uses Owin. Checkout http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-signalr-20-self-host to setup the server. It's compatible with the client code above.

Convert integer into byte array (Java)

Simple solution which properly handles ByteOrder:

ByteBuffer.allocate(4).order(ByteOrder.nativeOrder()).putInt(yourInt).array();

How to read Data from Excel sheet in selenium webdriver

Your problem is that log4j has not been initialized. It does not affect the outcome of you application in any way, so it's safe to ignore or just initialize Log4J, see: How to initialize log4j properly?

regex string replace

This should work :

str = str.replace(/[^a-z0-9-]/g, '');

Everything between the indicates what your are looking for

  1. / is here to delimit your pattern so you have one to start and one to end
  2. [] indicates the pattern your are looking for on one specific character
  3. ^ indicates that you want every character NOT corresponding to what follows
  4. a-z matches any character between 'a' and 'z' included
  5. 0-9 matches any digit between '0' and '9' included (meaning any digit)
  6. - the '-' character
  7. g at the end is a special parameter saying that you do not want you regex to stop on the first character matching your pattern but to continue on the whole string

Then your expression is delimited by / before and after. So here you say "every character not being a letter, a digit or a '-' will be removed from the string".

How to get all child inputs of a div element (jQuery)

The 'find' method can be used to get all child inputs of a container that has already been cached to save looking it up again (whereas the 'children' method will only get the immediate children). e.g.

var panel= $("#panel");
var inputs = panel.find("input");

How to push changes to github after jenkins build completes?

The git checkout master of the answer by Woland isn't needed. Instead use the "Checkout to specific local branch" in the "Additional Behaviors" section to set the "Branch name" to master.

The git commit -am "blah" is still needed.

Now you can use the "Git Publisher" under "Post-build Actions" to push the changes. Be sure to specify the "Branches" to push ("Branch to push" = master, "Target remote name" = origin).

"Merge Results" isn't needed.

AngularJS For Loop with Numbers & Ranges

I tweaked this answer a bit and came up with this fiddle.

Filter defined as:

var myApp = angular.module('myApp', []);
myApp.filter('range', function() {
  return function(input, total) {
    total = parseInt(total);

    for (var i=0; i<total; i++) {
      input.push(i);
    }

    return input;
  };
});

With the repeat used like this:

<div ng-repeat="n in [] | range:100">
  do something
</div>

Flutter: RenderBox was not laid out

Reason for the error:

Column tries to expands in vertical axis, and so does the ListView, hence you need to constrain the height of ListView.


Solutions

  1. Use either Expanded or Flexible if you want to allow ListView to take up entire left space in Column.

    Column(
      children: <Widget>[
        Expanded(
          child: ListView(...),
        )
      ],
    )
    

  1. Use SizedBox if you want to restrict the size of ListView to a certain height.

    Column(
      children: <Widget>[
        SizedBox(
          height: 200, // constrain height
          child: ListView(),
        )
      ],
    )
    

  1. Use shrinkWrap, if your ListView isn't too big.

    Column(
      children: <Widget>[
        ListView(
          shrinkWrap: true, // use it
        )
      ],
    )
    

How to change the author and committer name and e-mail of multiple commits in Git?

It happens when you do not have a $HOME/.gitconfig initialized. You may fix this as:

git config --global user.name "you name"
git config --global user.email [email protected]
git commit --amend --reset-author

tested with git version 1.7.5.4

How can I return the difference between two lists?

I was looking similar but I wanted the difference in either list (uncommon elements between the 2 lists).

Let say I have:

List<String> oldKeys = Arrays.asList("key0","key1","key2","key5");
List<String> newKeys = Arrays.asList("key0","key2","key5", "key6");

And I wanted to know which key has been added and which key is removed i.e I wanted to get (key1, key6)

Using org.apache.commons.collections.CollectionUtils

List<String> list = new ArrayList<>(CollectionUtils.disjunction(newKeys, oldKeys));

Result

["key1", "key6"]

How can I create tests in Android Studio?

The easiest way I found is the streamlined in my following blog post:

  1. Create a folder in which you'll write all your unit tests (preferably com.example.app.tests)
  2. Create a new test class (preferably NameOfClassTestedTests, i.e BankAccountLoginActivityTests)
  3. Extend InstrumentationTestCase
  4. Write a failing unit test to make sure we succeeded configuring unit tests
  5. Note that a unit test method name must start with the word “test” (preferably testTestedMethodNameExpectedResult() i.e testBankAccountValidationFailedShouldLogout())
  6. Configure your project for unit tests:
  7. Open the 'Run...' menu and click 'edit configurations'
  8. Click the + button
  9. Select the Android Tests template
  10. Input a name for your run configuration (preferably 'AppName Tests')
  11. Select your app in the module combobox
  12. Select the “All In Package” radio button (generally you'd want to select this option because it runs all unit tests in all your test classes)
  13. Fill in the test package name from step 1 (i.e com.example.app.tests)
  14. Select the device you wish to run your tests on
  15. Apply and save the configuration
  16. Run unit tests (and expect failure):
  17. Select your newly created Tests configuration from the Run menu
  18. Click Run and read the results in the output console

Good luck making your code more readable, maintainable and well-tested!

How to change Format of a Cell to Text using VBA

Well this should change your format to text.

Worksheets("Sheetname").Activate
Worksheets("SheetName").Columns(1).Select 'or Worksheets("SheetName").Range("A:A").Select
Selection.NumberFormat = "@"

Excel VBA Open workbook, perform actions, save as, close

After discussion posting updated answer:

Option Explicit
Sub test()

    Dim wk As String, yr As String
    Dim fname As String, fpath As String
    Dim owb As Workbook

    With Application
        .DisplayAlerts = False
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    wk = ComboBox1.Value
    yr = ComboBox2.Value
    fname = yr & "W" & wk
    fpath = "C:\Documents and Settings\jammil\Desktop\AutoFinance\ProjectControl\Data"

    On Error GoTo ErrorHandler
    Set owb = Application.Workbooks.Open(fpath & "\" & fname)

    'Do Some Stuff

    With owb
        .SaveAs fpath & Format(Date, "yyyymm") & "DB" & ".xlsx", 51
        .Close
    End With

    With Application
        .DisplayAlerts = True
        .ScreenUpdating = True
        .EnableEvents = True
    End With

Exit Sub
ErrorHandler: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then

Else: Call Clear

End Sub

Error Handling:

You could try something like this to catch a specific error:

    On Error Resume Next
    Set owb = Application.Workbooks.Open(fpath & "\" & fname)
    If Err.Number = 1004 Then
    GoTo FileNotFound
    Else
    End If

    ...
    Exit Sub
    FileNotFound: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then

    Else: Call Clear

How to remove backslash on json_encode() function?

I just figured out that json_encode does only escape \n if it's used within single quotes.

echo json_encode("Hello World\n");
// results in "Hello World\n"

And

echo json_encode('Hello World\n');
// results in "Hello World\\\n"

Java File - Open A File And Write To It

Please Search Google given to the world by Larry Page and Sergey Brin.

BufferedWriter out = null;

try {
    FileWriter fstream = new FileWriter("out.txt", true); //true tells to append data.
    out = new BufferedWriter(fstream);
    out.write("\nsue");
}

catch (IOException e) {
    System.err.println("Error: " + e.getMessage());
}

finally {
    if(out != null) {
        out.close();
    }
}

How do I create a WPF Rounded Corner container?

You don't need a custom control, just put your container in a border element:

<Border BorderBrush="#FF000000" BorderThickness="1" CornerRadius="8">
   <Grid/>
</Border>

You can replace the <Grid/> with any of the layout containers...

ValueError: unconverted data remains: 02:05

Well it was very simple. I was missing the format of the date in the json file, so I should write :

st = datetime.strptime(st, '%A %d %B %H %M')

because in the json file the date was like :

"start": "Friday 06 December 02:05",

Calculating text width

text width can be different for different parents, for example if u add a text into h1 tag it will be wider than div or label, so my solution like this:

<h1 id="header1">

</h1>

alert(calcTextWidth("bir iki", $("#header1")));

function calcTextWidth(text, parentElem){
    var Elem = $("<label></label>").css("display", "none").text(text);
    parentElem.append(Elem);
  var width = Elem.width();
  Elem.remove();
    return width;
}

How to initialize an array's length in JavaScript?

  • Array(5) gives you an array with length 5 but no values, hence you can't iterate over it.

  • Array.apply(null, Array(5)).map(function () {}) gives you an array with length 5 and undefined as values, now it can be iterated over.

  • Array.apply(null, Array(5)).map(function (x, i) { return i; }) gives you an array with length 5 and values 0,1,2,3,4.

  • Array(5).forEach(alert) does nothing, Array.apply(null, Array(5)).forEach(alert) gives you 5 alerts

  • ES6 gives us Array.from so now you can also use Array.from(Array(5)).forEach(alert)

  • If you want to initialize with a certain value, these are good to knows...
    Array.from('abcde'), Array.from('x'.repeat(5))
    or Array.from({length: 5}, (v, i) => i) // gives [0, 1, 2, 3, 4]

How do I left align these Bootstrap form items?

Just add style="text-align: left" to your label.

How to select a node of treeview programmatically in c#?

Call the TreeView.OnAfterSelect() protected method after you programatically select the node.

String Concatenation using '+' operator

It doesn't - the C# compiler does :)

So this code:

string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;

actually gets compiled as:

string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);

(Gah - intervening edit removed other bits accidentally.)

The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y which then needs to be copied again as part of the concatenation of (x + y) and z. Instead, we get it all done in one go.

EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:

string x = "";
foreach (string y in strings)
{
    x += y;
}

just ends up as equivalent to:

string x = "";
foreach (string y in strings)
{
    x = string.Concat(x, y);
}

... so this does generate a lot of garbage, and it's why you should use a StringBuilder for such cases. I have an article going into more details about the two which will hopefully answer further questions.

How to make a class property?

I think you may be able to do this with the metaclass. Since the metaclass can be like a class for the class (if that makes sense). I know you can assign a __call__() method to the metaclass to override calling the class, MyClass(). I wonder if using the property decorator on the metaclass operates similarly. (I haven't tried this before, but now I'm curious...)

[update:]

Wow, it does work:

class MetaClass(type):    
    def getfoo(self):
        return self._foo
    foo = property(getfoo)

    @property
    def bar(self):
        return self._bar

class MyClass(object):
    __metaclass__ = MetaClass
    _foo = 'abc'
    _bar = 'def'

print MyClass.foo
print MyClass.bar

Note: This is in Python 2.7. Python 3+ uses a different technique to declare a metaclass. Use: class MyClass(metaclass=MetaClass):, remove __metaclass__, and the rest is the same.

How to delete a line from a text file in C#?

I'd very simply:

  • Open the file for read/write
  • Read/seek through it until the start of the line you want to delete
  • Set the write pointer to the current read pointer
  • Read through to the end of the line we're deleting and skip the newline delimiters (counting the number of characters as we go, we'll call it nline)
  • Read byte-by-byte and write each byte to the file
  • When finished truncate the file to (orig_length - nline).

Creating a config file in PHP

I use a slight evolution of @hugo_leonardo 's solution:

<?php

return (object) array(
    'host' => 'localhost',
    'username' => 'root',
    'pass' => 'password',
    'database' => 'db'
);

?>

This allows you to use the object syntax when you include the php : $configs->host instead of $configs['host'].

Also, if your app has configs you need on the client side (like for an Angular app), you can have this config.php file contain all your configs (centralized in one file instead of one for JavaScript and one for PHP). The trick would then be to have another PHP file that would echo only the client side info (to avoid showing info you don't want to show like database connection string). Call it say get_app_info.php :

<?php

    $configs = include('config.php');
    echo json_encode($configs->app_info);

?>

The above assuming your config.php contains an app_info parameter:

<?php

return (object) array(
    'host' => 'localhost',
    'username' => 'root',
    'pass' => 'password',
    'database' => 'db',
    'app_info' => array(
        'appName'=>"App Name",
        'appURL'=> "http://yourURL/#/"
    )
);

?>

So your database's info stays on the server side, but your app info is accessible from your JavaScript, with for example a $http.get('get_app_info.php').then(...); type of call.

In VBA get rid of the case sensitivity when comparing words?

If the list to compare against is large, (ie the manilaListRange range in the example above), it is a smart move to use the match function. It avoids the use of a loop which could slow down the procedure. If you can ensure that the manilaListRange is all upper or lower case then this seems to be the best option to me. It is quick to apply 'UCase' or 'LCase' as you do your match.

If you did not have control over the ManilaListRange then you might have to resort to looping through this range in which case there are many ways to compare 'search', 'Instr', 'replace' etc.

How to use onBlur event on Angular2?

HTML

<input name="email" placeholder="Email"  (blur)="$event.target.value=removeSpaces($event.target.value)" value="">

TS

removeSpaces(string) {
 let splitStr = string.split(' ').join('');
  return splitStr;
}

How can I add an item to a ListBox in C# and WinForms?

If you just want to add a string to it, the simple answer is:

ListBox.Items.Add("some text");

What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

Versioning of assemblies in .NET can be a confusing prospect given that there are currently at least three ways to specify a version for your assembly.

Here are the three main version-related assembly attributes:

// Assembly mscorlib, Version 2.0.0.0
[assembly: AssemblyFileVersion("2.0.50727.3521")]
[assembly: AssemblyInformationalVersion("2.0.50727.3521")]
[assembly: AssemblyVersion("2.0.0.0")]

By convention, the four parts of the version are referred to as the Major Version, Minor Version, Build, and Revision.

The AssemblyFileVersion is intended to uniquely identify a build of the individual assembly

Typically you’ll manually set the Major and Minor AssemblyFileVersion to reflect the version of the assembly, then increment the Build and/or Revision every time your build system compiles the assembly. The AssemblyFileVersion should allow you to uniquely identify a build of the assembly, so that you can use it as a starting point for debugging any problems.

On my current project we have the build server encode the changelist number from our source control repository into the Build and Revision parts of the AssemblyFileVersion. This allows us to map directly from an assembly to its source code, for any assembly generated by the build server (without having to use labels or branches in source control, or manually keeping any records of released versions).

This version number is stored in the Win32 version resource and can be seen when viewing the Windows Explorer property pages for the assembly.

The CLR does not care about nor examine the AssemblyFileVersion.

The AssemblyInformationalVersion is intended to represent the version of your entire product

The AssemblyInformationalVersion is intended to allow coherent versioning of the entire product, which may consist of many assemblies that are independently versioned, perhaps with differing versioning policies, and potentially developed by disparate teams.

“For example, version 2.0 of a product might contain several assemblies; one of these assemblies is marked as version 1.0 since it’s a new assembly that didn’t ship in version 1.0 of the same product. Typically, you set the major and minor parts of this version number to represent the public version of your product. Then you increment the build and revision parts each time you package a complete product with all its assemblies.” — Jeffrey Richter, [CLR via C# (Second Edition)] p. 57

The CLR does not care about nor examine the AssemblyInformationalVersion.

The AssemblyVersion is the only version the CLR cares about (but it cares about the entire AssemblyVersion)

The AssemblyVersion is used by the CLR to bind to strongly named assemblies. It is stored in the AssemblyDef manifest metadata table of the built assembly, and in the AssemblyRef table of any assembly that references it.

This is very important, because it means that when you reference a strongly named assembly, you are tightly bound to a specific AssemblyVersion of that assembly. The entire AssemblyVersion must be an exact match for the binding to succeed. For example, if you reference version 1.0.0.0 of a strongly named assembly at build-time, but only version 1.0.0.1 of that assembly is available at runtime, binding will fail! (You will then have to work around this using Assembly Binding Redirection.)

Confusion over whether the entire AssemblyVersion has to match. (Yes, it does.)

There is a little confusion around whether the entire AssemblyVersion has to be an exact match in order for an assembly to be loaded. Some people are under the false belief that only the Major and Minor parts of the AssemblyVersion have to match in order for binding to succeed. This is a sensible assumption, however it is ultimately incorrect (as of .NET 3.5), and it’s trivial to verify this for your version of the CLR. Just execute this sample code.

On my machine the second assembly load fails, and the last two lines of the fusion log make it perfectly clear why:

.NET Framework Version: 2.0.50727.3521
---
Attempting to load assembly: Rhino.Mocks, Version=3.5.0.1337, Culture=neutral, PublicKeyToken=0b3305902db7183f
Successfully loaded assembly: Rhino.Mocks, Version=3.5.0.1337, Culture=neutral, PublicKeyToken=0b3305902db7183f
---
Attempting to load assembly: Rhino.Mocks, Version=3.5.0.1336, Culture=neutral, PublicKeyToken=0b3305902db7183f
Assembly binding for  failed:
System.IO.FileLoadException: Could not load file or assembly 'Rhino.Mocks, Version=3.5.0.1336, Culture=neutral, 
PublicKeyToken=0b3305902db7183f' or one of its dependencies. The located assembly's manifest definition 
does not match the assembly reference. (Exception from HRESULT: 0x80131040)
File name: 'Rhino.Mocks, Version=3.5.0.1336, Culture=neutral, PublicKeyToken=0b3305902db7183f'

=== Pre-bind state information ===
LOG: User = Phoenix\Dani
LOG: DisplayName = Rhino.Mocks, Version=3.5.0.1336, Culture=neutral, PublicKeyToken=0b3305902db7183f
 (Fully-specified)
LOG: Appbase = [...]
LOG: Initial PrivatePath = NULL
Calling assembly : AssemblyBinding, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.
===
LOG: This bind starts in default load context.
LOG: No application configuration file found.
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v2.0.50727\config\machine.config.
LOG: Post-policy reference: Rhino.Mocks, Version=3.5.0.1336, Culture=neutral, PublicKeyToken=0b3305902db7183f
LOG: Attempting download of new URL [...].
WRN: Comparing the assembly name resulted in the mismatch: Revision Number
ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.

I think the source of this confusion is probably because Microsoft originally intended to be a little more lenient on this strict matching of the full AssemblyVersion, by matching only on the Major and Minor version parts:

“When loading an assembly, the CLR will automatically find the latest installed servicing version that matches the major/minor version of the assembly being requested.” — Jeffrey Richter, [CLR via C# (Second Edition)] p. 56

This was the behaviour in Beta 1 of the 1.0 CLR, however this feature was removed before the 1.0 release, and hasn’t managed to re-surface in .NET 2.0:

“Note: I have just described how you should think of version numbers. Unfortunately, the CLR doesn’t treat version numbers this way. [In .NET 2.0], the CLR treats a version number as an opaque value, and if an assembly depends on version 1.2.3.4 of another assembly, the CLR tries to load version 1.2.3.4 only (unless a binding redirection is in place). However, Microsoft has plans to change the CLR’s loader in a future version so that it loads the latest build/revision for a given major/minor version of an assembly. For example, on a future version of the CLR, if the loader is trying to find version 1.2.3.4 of an assembly and version 1.2.5.0 exists, the loader with automatically pick up the latest servicing version. This will be a very welcome change to the CLR’s loader — I for one can’t wait.” — Jeffrey Richter, [CLR via C# (Second Edition)] p. 164 (Emphasis mine)

As this change still hasn’t been implemented, I think it’s safe to assume that Microsoft had back-tracked on this intent, and it is perhaps too late to change this now. I tried to search around the web to find out what happened with these plans, but I couldn’t find any answers. I still wanted to get to the bottom of it.

So I emailed Jeff Richter and asked him directly — I figured if anyone knew what happened, it would be him.

He replied within 12 hours, on a Saturday morning no less, and clarified that the .NET 1.0 Beta 1 loader did implement this ‘automatic roll-forward’ mechanism of picking up the latest available Build and Revision of an assembly, but this behaviour was reverted before .NET 1.0 shipped. It was later intended to revive this but it didn’t make it in before the CLR 2.0 shipped. Then came Silverlight, which took priority for the CLR team, so this functionality got delayed further. In the meantime, most of the people who were around in the days of CLR 1.0 Beta 1 have since moved on, so it’s unlikely that this will see the light of day, despite all the hard work that had already been put into it.

The current behaviour, it seems, is here to stay.

It is also worth noting from my discussion with Jeff that AssemblyFileVersion was only added after the removal of the ‘automatic roll-forward’ mechanism — because after 1.0 Beta 1, any change to the AssemblyVersion was a breaking change for your customers, there was then nowhere to safely store your build number. AssemblyFileVersion is that safe haven, since it’s never automatically examined by the CLR. Maybe it’s clearer that way, having two separate version numbers, with separate meanings, rather than trying to make that separation between the Major/Minor (breaking) and the Build/Revision (non-breaking) parts of the AssemblyVersion.

The bottom line: Think carefully about when you change your AssemblyVersion

The moral is that if you’re shipping assemblies that other developers are going to be referencing, you need to be extremely careful about when you do (and don’t) change the AssemblyVersion of those assemblies. Any changes to the AssemblyVersion will mean that application developers will either have to re-compile against the new version (to update those AssemblyRef entries) or use assembly binding redirects to manually override the binding.

  • Do not change the AssemblyVersion for a servicing release which is intended to be backwards compatible.
  • Do change the AssemblyVersion for a release that you know has breaking changes.

Just take another look at the version attributes on mscorlib:

// Assembly mscorlib, Version 2.0.0.0
[assembly: AssemblyFileVersion("2.0.50727.3521")]
[assembly: AssemblyInformationalVersion("2.0.50727.3521")]
[assembly: AssemblyVersion("2.0.0.0")]

Note that it’s the AssemblyFileVersion that contains all the interesting servicing information (it’s the Revision part of this version that tells you what Service Pack you’re on), meanwhile the AssemblyVersion is fixed at a boring old 2.0.0.0. Any change to the AssemblyVersion would force every .NET application referencing mscorlib.dll to re-compile against the new version!

Is there a difference between "throw" and "throw ex"?

To give you a different perspective on this, using throw is particularly useful if you're providing an API to a client and you want to provide verbose stack trace information for your internal library. By using throw here, I'd get the stack trace in this case of the System.IO.File library for File.Delete. If I use throw ex, then that information will not be passed to my handler.

static void Main(string[] args) {            
   Method1();            
}

static void Method1() {
    try {
        Method2();
    } catch (Exception ex) {
        Console.WriteLine("Exception in Method1");             
    }
}

static void Method2() {
    try {
        Method3();
    } catch (Exception ex) {
        Console.WriteLine("Exception in Method2");
        Console.WriteLine(ex.TargetSite);
        Console.WriteLine(ex.StackTrace);
        Console.WriteLine(ex.GetType().ToString());
    }
}

static void Method3() {
    Method4();
}

static void Method4() {
    try {
        System.IO.File.Delete("");
    } catch (Exception ex) {
        // Displays entire stack trace into the .NET 
        // or custom library to Method2() where exception handled
        // If you want to be able to get the most verbose stack trace
        // into the internals of the library you're calling
        throw;                
        // throw ex;
        // Display the stack trace from Method4() to Method2() where exception handled
    }
}

Convert Bitmap to File

Converting Bitmap to File needs to be done in background (NOT IN THE MAIN THREAD) it hangs the UI specially if the bitmap was large

File file;

public class fileFromBitmap extends AsyncTask<Void, Integer, String> {

    Context context;
    Bitmap bitmap;
    String path_external = Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg";

    public fileFromBitmap(Bitmap bitmap, Context context) {
        this.bitmap = bitmap;
        this.context= context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // before executing doInBackground
        // update your UI
        // exp; make progressbar visible
    }

    @Override
    protected String doInBackground(Void... params) {

        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        file = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
        try {
            FileOutputStream fo = new FileOutputStream(file);
            fo.write(bytes.toByteArray());
            fo.flush();
            fo.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        // back to main thread after finishing doInBackground
        // update your UI or take action after
        // exp; make progressbar gone

         sendFile(file);

    }
}

Calling it

new fileFromBitmap(my_bitmap, getApplicationContext()).execute();

you MUST use the file in onPostExecute .

To change directory of file to be stored in cache replace line :

 file = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");

with :

file  = new File(context.getCacheDir(), "temporary_file.jpg");

How to create an instance of System.IO.Stream stream

You have to create an instance of one of the subclasses. Stream is an abstract class that can't be instantiated directly.

There are a bunch of choices if you look at the bottom of the reference here:

Stream Class | Microsoft Developer Network

The most common probably being FileStream or MemoryStream. Basically, you need to decide where you wish the data backing your stream to come from, then create an instance of the appropriate subclass.