Programs & Examples On #Executiontimeout

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

The below code solved my problem :

request.ProtocolVersion = HttpVersion.Version10; // THIS DOES THE TRICK
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

how to increase MaxReceivedMessageSize when calling a WCF from C#

Change the customBinding in the web.config to use larger defaults. I picked 2MB as it is a reasonable size. Of course setting it to 2GB (as your code suggests) will work but it does leave you more vulnerable to attacks. Pick a size that is larger than your largest request but isn't overly large.

Check this : Using Large Message Requests in Silverlight with WCF

<system.serviceModel>
   <behaviors>
     <serviceBehaviors>
       <behavior name="TestLargeWCF.Web.MyServiceBehavior">
         <serviceMetadata httpGetEnabled="true"/>
         <serviceDebug includeExceptionDetailInFaults="false"/>
       </behavior>
     </serviceBehaviors>
   </behaviors>
   <bindings>
     <customBinding>
       <binding name="customBinding0">
         <binaryMessageEncoding />
         <!-- Start change -->
         <httpTransport maxReceivedMessageSize="2097152"
                        maxBufferSize="2097152"
                        maxBufferPoolSize="2097152"/>
         <!-- Stop change -->
       </binding>
     </customBinding>
   </bindings>
   <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
   <services>
     <service behaviorConfiguration="Web.MyServiceBehavior" name="TestLargeWCF.Web.MyService">
       <endpoint address=""
                binding="customBinding"
                bindingConfiguration="customBinding0"
                contract="TestLargeWCF.Web.MyService"/>
       <endpoint address="mex"
                binding="mexHttpBinding"
                contract="IMetadataExchange"/>
     </service>
   </services>
 </system.serviceModel> 

403 - Forbidden: Access is denied. You do not have permission to view this directory or page using the credentials that you supplied

Resolution for 404 Forbidden in recent .Net 4.7 MVC/webform pplication hosting in Azure VM We need to install the .Net 4.7 and extensibilty and development in server role other than the .Net 4.7/version feature as below: This might have been alreday activated .Net Activated feature

We need to also add the below under IIS webserver role-> Application Development -> select the .Net version as below Image to Activate the requited Role under IIS webserver Role Server Role Activation under application Development

How to increase executionTimeout for a long-running query?

When a query takes that long, I would advice to run it asynchronously and use a callback function for when it's complete.

I don't have much experience with ASP.NET, but maybe you can use AJAX for this asynchronous behavior.

Typically a web page should load in mere seconds, not minutes. Don't keep your users waiting for so long!

Setting Timeout Value For .NET Web Service

After creating your client specifying the binding and endpoint address, you can assign an OperationTimeout,

client.InnerChannel.OperationTimeout = new TimeSpan(0, 5, 0);

How do I set the request timeout for one controller action in an asp.net mvc application

<location path="ControllerName/ActionName">
    <system.web>
        <httpRuntime executionTimeout="1000"/>
    </system.web>
</location>

Probably it is better to set such values in web.config instead of controller. Hardcoding of configurable options is considered harmful.

Rotating and spacing axis labels in ggplot2

Change the last line to

q + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

By default, the axes are aligned at the center of the text, even when rotated. When you rotate +/- 90 degrees, you usually want it to be aligned at the edge instead:

alt text

The image above is from this blog post.

Android SDK location

When you first time install Android Studio Setup, you can also see the SDK folder. For me it is:

C:\Users\{USERNAME}\AppData\Local\Android\sdk

enter image description here

How to delete and update a record in Hive

UPDATE or DELETE a record isn't allowed in Hive, but INSERT INTO is acceptable.
A snippet from Hadoop: The Definitive Guide(3rd edition):

Updates, transactions, and indexes are mainstays of traditional databases. Yet, until recently, these features have not been considered a part of Hive's feature set. This is because Hive was built to operate over HDFS data using MapReduce, where full-table scans are the norm and a table update is achieved by transforming the data into a new table. For a data warehousing application that runs over large portions of the dataset, this works well.

Hive doesn't support updates (or deletes), but it does support INSERT INTO, so it is possible to add new rows to an existing table.

Sending a JSON HTTP POST request from Android

Posting parameters Using POST:-

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream  input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");   
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();  
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

The part which you missed is in the the following... i.e., as follows..

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();

The rest of the thing you can do it.

How to send POST request in JSON using HTTPClient in Android?

In this answer I am using an example posted by Justin Grammens.

About JSON

JSON stands for JavaScript Object Notation. In JavaScript properties can be referenced both like this object1.name and like this object['name'];. The example from the article uses this bit of JSON.

The Parts
A fan object with email as a key and [email protected] as a value

{
  fan:
    {
      email : '[email protected]'
    }
}

So the object equivalent would be fan.email; or fan['email'];. Both would have the same value of '[email protected]'.

About HttpClient Request

The following is what our author used to make a HttpClient Request. I do not claim to be an expert at all this so if anyone has a better way to word some of the terminology feel free.

public static HttpResponse makeRequest(String path, Map params) throws Exception 
{
    //instantiates httpclient to make request
    DefaultHttpClient httpclient = new DefaultHttpClient();

    //url with the post data
    HttpPost httpost = new HttpPost(path);

    //convert parameters into JSON object
    JSONObject holder = getJsonObjectFromMap(params);

    //passes the results to a string builder/entity
    StringEntity se = new StringEntity(holder.toString());

    //sets the post request as the resulting string
    httpost.setEntity(se);
    //sets a request header so the page receving the request
    //will know what to do with it
    httpost.setHeader("Accept", "application/json");
    httpost.setHeader("Content-type", "application/json");

    //Handles what is returned from the page 
    ResponseHandler responseHandler = new BasicResponseHandler();
    return httpclient.execute(httpost, responseHandler);
}

Map

If you are not familiar with the Map data structure please take a look at the Java Map reference. In short, a map is similar to a dictionary or a hash.

private static JSONObject getJsonObjectFromMap(Map params) throws JSONException {

    //all the passed parameters from the post request
    //iterator used to loop through all the parameters
    //passed in the post request
    Iterator iter = params.entrySet().iterator();

    //Stores JSON
    JSONObject holder = new JSONObject();

    //using the earlier example your first entry would get email
    //and the inner while would get the value which would be '[email protected]' 
    //{ fan: { email : '[email protected]' } }

    //While there is another entry
    while (iter.hasNext()) 
    {
        //gets an entry in the params
        Map.Entry pairs = (Map.Entry)iter.next();

        //creates a key for Map
        String key = (String)pairs.getKey();

        //Create a new map
        Map m = (Map)pairs.getValue();   

        //object for storing Json
        JSONObject data = new JSONObject();

        //gets the value
        Iterator iter2 = m.entrySet().iterator();
        while (iter2.hasNext()) 
        {
            Map.Entry pairs2 = (Map.Entry)iter2.next();
            data.put((String)pairs2.getKey(), (String)pairs2.getValue());
        }

        //puts email and '[email protected]'  together in map
        holder.put(key, data);
    }
    return holder;
}

Please feel free to comment on any questions that arise about this post or if I have not made something clear or if I have not touched on something that your still confused about... etc whatever pops in your head really.

(I will take down if Justin Grammens does not approve. But if not then thanks Justin for being cool about it.)

Update

I just happend to get a comment about how to use the code and realized that there was a mistake in the return type. The method signature was set to return a string but in this case it wasnt returning anything. I changed the signature to HttpResponse and will refer you to this link on Getting Response Body of HttpResponse the path variable is the url and I updated to fix a mistake in the code.

Shell command to sum integers, one per line?

The one-liner version in Python:

$ python -c "import sys; print(sum(int(l) for l in sys.stdin))"

How to perform a LEFT JOIN in SQL Server between two SELECT statements?

select *
from user
left join edge
on user.userid = edge.tailuser
and edge.headuser = 5043

The requested operation cannot be performed on a file with a user-mapped section open

Others have already established that this error is due to another application having a lock on the file. Just wanted to point out that git diff locks files as well until you quit out of it. That's what caused this in my case.

Simplest/cleanest way to implement a singleton in JavaScript

The following works in Node.js version 6:

class Foo {
  constructor(msg) {

    if (Foo.singleton) {
      return Foo.singleton;
    }

    this.msg = msg;
    Foo.singleton = this;
    return Foo.singleton;
  }
}

We test:

const f = new Foo('blah');
const d = new Foo('nope');
console.log(f); // => Foo { msg: 'blah' }
console.log(d); // => Foo { msg: 'blah' }

Check if one list contains element from the other

There is one method of Collection named retainAll but having some side effects for you reference

Retains only the elements in this list that are contained in the specified collection (optional operation). In other words, removes from this list all of its elements that are not contained in the specified collection.

true if this list changed as a result of the call

Its like

boolean b = list1.retainAll(list2);

What's the valid way to include an image with no src?

I found that simply setting the src to an empty string and adding a rule to your CSS to hide the broken image icon works just fine.

[src=''] {
    visibility: hidden;
}

Using regular expression in css?

Try my generic CSS regular expression

(([a-z]{5,6}.*?\))|([\d.+-]?)(?![a-z\s#.()%])(\d?\.?\d?)?[a-z\d%]+)|(url\([/"'][a-z:/.]*['")]\))|(rgb|hsl)a?\(\d+%?,?\s?\d+%?,?\s?\d+%?(,\s?\d+\.?\d?)?\)|(#(\w|[\d]){3,8})|([\w]{3,8}(?=.*-))

Demo https://regexr.com/4a22i

What is the difference between BIT and TINYINT in MySQL?

BIT should only allow 0 and 1 (and NULL, if the field is not defined as NOT NULL). TINYINT(1) allows any value that can be stored in a single byte, -128..127 or 0..255 depending on whether or not it's unsigned (the 1 shows that you intend to only use a single digit, but it does not prevent you from storing a larger value).

For versions older than 5.0.3, BIT is interpreted as TINYINT(1), so there's no difference there.

BIT has a "this is a boolean" semantic, and some apps will consider TINYINT(1) the same way (due to the way MySQL used to treat it), so apps may format the column as a check box if they check the type and decide upon a format based on that.

Verifying that a string contains only letters in C#

You can loop on the chars of string and check using the Char Method IsLetter but you can also do a trick using String method IndexOfAny to search other charaters that are not suppose to be in the string.

SOAP-UI - How to pass xml inside parameter

Either encode the needed XML entities or use CDATA.

<arg0>
    <!--Optional:-->
    <parameter1>&lt;test>like this&lt;/test></parameter1>
    <!--Optional:-->
    <parameter2><![CDATA[<test>or like this</test>]]></parameter2>
 </arg0>

Find column whose name contains a specific string

df.loc[:,df.columns.str.contains("spike")]

Adding text to a cell in Excel using VBA

You need to use Range and Value functions.
Range would be the cell where you want the text you want
Value would be the text that you want in that Cell

Range("A1").Value="whatever text"

How to compile a 64-bit application using Visual C++ 2010 Express?

And make sure you download the Windows7.1 SDK, not just the Windows 7 one. That caused me a lot of head pounding.

How to unzip a file using the command line?

Grab an executable from info-zip.

Info-ZIP supports hardware from microcomputers all the way up to Cray supercomputers, running on almost all versions of Unix, VMS, OS/2, Windows 9x/NT/etc. (a.k.a. Win32), Windows 3.x, Windows CE, MS-DOS, AmigaDOS, Atari TOS, Acorn RISC OS, BeOS, Mac OS, SMS/QDOS, MVS and OS/390 OE, VM/CMS, FlexOS, Tandem NSK and Human68K (Japanese). There is also some (old) support for LynxOS, TOPS-20, AOS/VS and Novell NLMs. Shared libraries (DLLs) are available for Unix, OS/2, Win32 and Win16, and graphical interfaces are available for Win32, Win16, WinCE and Mac OS.

Hibernate Criteria Restrictions AND / OR combination

think works

Criteria criteria = getSession().createCriteria(clazz); 
Criterion rest1= Restrictions.and(Restrictions.eq(A, "X"), 
           Restrictions.in("B", Arrays.asList("X",Y)));
Criterion rest2= Restrictions.and(Restrictions.eq(A, "Y"), 
           Restrictions.eq(B, "Z"));
criteria.add(Restrictions.or(rest1, rest2));

insert data into database using servlet and jsp in eclipse

Can you check value of i by putting logger or println(). and check with closing db conn at the end. Rest your code looks fine and it should work.

HTML5 LocalStorage: Checking if a key exists

The MDN documentation shows how the getItem method is implementated:

Object.defineProperty(oStorage, "getItem", {
      value: function (sKey) { return sKey ? this[sKey] : null; },
      writable: false,
      configurable: false,
      enumerable: false
    });

If the value isn't set, it returns null. You are testing to see if it is undefined. Check to see if it is null instead.

if(localStorage.getItem("username") === null){

How to get the current branch name in Git?

I know this is late but on a linux/mac ,from the terminal you can use the following.

git status | sed -n 1p

Explanation:

git status -> gets the working tree status
sed -n 1p -> gets the first line from the status body

Response to the above command will look as follows:

"On branch your_branch_name"

Javascript swap array elements

try this function...

_x000D_
_x000D_
$(document).ready(function () {_x000D_
        var pair = [];_x000D_
        var destinationarray = ['AAA','BBB','CCC'];_x000D_
_x000D_
        var cityItems = getCityList(destinationarray);_x000D_
        for (var i = 0; i < cityItems.length; i++) {_x000D_
            pair = [];_x000D_
            var ending_point = "";_x000D_
            for (var j = 0; j < cityItems[i].length; j++) {_x000D_
                pair.push(cityItems[i][j]);_x000D_
            }_x000D_
            alert(pair);_x000D_
            console.log(pair)_x000D_
        }_x000D_
_x000D_
    });_x000D_
    function getCityList(inputArray) {_x000D_
        var Util = function () {_x000D_
        };_x000D_
_x000D_
        Util.getPermuts = function (array, start, output) {_x000D_
            if (start >= array.length) {_x000D_
                var arr = array.slice(0);_x000D_
                output.push(arr);_x000D_
            } else {_x000D_
                var i;_x000D_
_x000D_
                for (i = start; i < array.length; ++i) {_x000D_
                    Util.swap(array, start, i);_x000D_
                    Util.getPermuts(array, start + 1, output);_x000D_
                    Util.swap(array, start, i);_x000D_
                }_x000D_
            }_x000D_
        }_x000D_
_x000D_
        Util.getAllPossiblePermuts = function (array, output) {_x000D_
            Util.getPermuts(array, 0, output);_x000D_
        }_x000D_
_x000D_
        Util.swap = function (array, from, to) {_x000D_
            var tmp = array[from];_x000D_
            array[from] = array[to];_x000D_
            array[to] = tmp;_x000D_
        }_x000D_
        var output = [];_x000D_
        Util.getAllPossiblePermuts(inputArray, output);_x000D_
        return output;_x000D_
    }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Shell script to get the process ID on Linux

Its pretty simple. Simply Run Any Program like this :- x= gedit & echo $! this will give you PID of this process. then do this kill -9 $x

Converting Python dict to kwargs?

Here is a complete example showing how to use the ** operator to pass values from a dictionary as keyword arguments.

>>> def f(x=2):
...     print(x)
... 
>>> new_x = {'x': 4}
>>> f()        #    default value x=2
2
>>> f(x=3)     #   explicit value x=3
3
>>> f(**new_x) # dictionary value x=4 
4

Should I use string.isEmpty() or "".equals(string)?

The main benefit of "".equals(s) is you don't need the null check (equals will check its argument and return false if it's null), which you seem to not care about. If you're not worried about s being null (or are otherwise checking for it), I would definitely use s.isEmpty(); it shows exactly what you're checking, you care whether or not s is empty, not whether it equals the empty string

How to set input type date's default value to today?

new Date().getFullYear()+"-"+ ((parseInt(new Date().getMonth())+1+100)+"").substring(1)

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

Actually the answer to the first part of the question is "Yes" in every programming language. For example, this is in the case of C/C++:

#define a   (b++)
int b = 1;
if (a ==1 && a== 2 && a==3) {
    std::cout << "Yes, it's possible!" << std::endl;
} else {
    std::cout << "it's impossible!" << std::endl;
}

mysql query result into php array

What about this:

while ($row = mysql_fetch_array($result)) 
{
    $new_array[$row['id']]['id'] = $row['id'];
    $new_array[$row['id']]['link'] = $row['link'];
}

To retrieve link and id:

foreach($new_array as $array)
{       
   echo $array['id'].'<br />';
   echo $array['link'].'<br />';
}

How to add some non-standard font to a website?

Or you could try sIFR. I know it uses Flash, but only if available. If Flash isn't available, it displays the original text in its original (CSS) font.

Hide separator line on one UITableViewCell

To follow up on Hiren's answer.

in ViewDidLoad and the following line :

self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

Or, if you are using XIB's or Storyboards change "separator" to "none" :

Interface builder

And in CellForRowAtIndexPath add this :

CGFloat separatorInset; // Separator x position 
CGFloat separatorHeight; 
CGFloat separatorWidth; 
CGFloat separatorY; 
UIImageView *separator;
UIColor *separatorBGColor;

separatorY      = cell.frame.size.height;
separatorHeight = (1.0 / [UIScreen mainScreen].scale);  // This assures you to have a 1px line height whatever the screen resolution
separatorWidth  = cell.frame.size.width;
separatorInset  = 15.0f;
separatorBGColor  = [UIColor colorWithRed: 204.0/255.0 green: 204.0/255.0 blue: 204.0/255.0 alpha:1.0];

separator = [[UIImageView alloc] initWithFrame:CGRectMake(separatorInset, separatorY, separatorWidth,separatorHeight)];
separator.backgroundColor = separatorBGColor;
[cell addSubView: separator];

Here is an example of the result where I display a tableview with dynamic Cells (but only have a single one with contents). The result being that only that one has a separator and not all the "dummy" ones tableview automatically adds to fill the screen.

enter image description here

Hope this helps.

EDIT: For those who don't always read the comments, there actually is a better way to do it with a few lines of code :

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.tableFooterView = UIView()
}

Maven: add a folder or jar file into current classpath

The classpath setting of the compiler plugin are two args. Changed it like this and it worked for me:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
  <compilerArgs>
     <arg>-cp</arg>
     <arg>${cp}:${basedir}/lib/bad.jar</arg>
  </compilerArgs>
</configuration>

I used the gmavenplus-plugin to read the path and create the property 'cp':

      <plugin>
    <!--
      Use Groovy to read classpath and store into
      file named value of property <cpfile>

      In second step use Groovy to read the contents of
      the file into a new property named <cp>

      In the compiler plugin this is used to create a
      valid classpath
    -->
    <groupId>org.codehaus.gmavenplus</groupId>
    <artifactId>gmavenplus-plugin</artifactId>
    <version>1.12.0</version>
    <dependencies>
      <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-all</artifactId>
        <!-- any version of Groovy \>= 1.5.0 should work here -->
        <version>3.0.6</version>
        <type>pom</type>
        <scope>runtime</scope>
      </dependency>
    </dependencies>
    <executions>
      <execution>
        <id>read-classpath</id>
        <phase>validate</phase>
        <goals>
          <goal>execute</goal>
        </goals>
      </execution>

    </executions>
    <configuration>
      <scripts>
        <script><![CDATA[
                def file = new File(project.properties.cpfile)
                /* create a new property named 'cp'*/
                project.properties.cp = file.getText()
                println '<<< Retrieving classpath into new property named <cp> >>>'
                println 'cp = ' + project.properties.cp
              ]]></script>
      </scripts>
    </configuration>
  </plugin>

How to print a float with 2 decimal places in Java?

Try this:-

private static String getDecimalFormat(double value) {

    String getValue = String.valueOf(value).split("[.]")[1];

      if (getValue.length() == 1) {
          return String.valueOf(value).split("[.]")[0] +
                "."+ getValue.substring(0, 1) + 
                String.format("%0"+1+"d", 0);
       } else {
          return String.valueOf(value).split("[.]")[0]
            +"." + getValue.substring(0, 2);
      }


 }

How do I check in python if an element of a list is empty?

I got around this with len() and a simple if/else statement.

List elements will come back as an integer when wrapped in len() (1 for present, 0 for absent)

l = []

print(len(l)) # Prints 0

if len(l) == 0:
    print("Element is empty")
else:
    print("Element is NOT empty")

Output:

Element is empty    

Request redirect to /Account/Login?ReturnUrl=%2f since MVC 3 install on server

Drezus - you solved it for me. Thanks so much.

In your AccountController, login should look like this:

    [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View();
    }

How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

from now, unix timestamp param,

function timeSince(ts){
    now = new Date();
    ts = new Date(ts*1000);
    var delta = now.getTime() - ts.getTime();

    delta = delta/1000; //us to s

    var ps, pm, ph, pd, min, hou, sec, days;

    if(delta<=59){
        ps = (delta>1) ? "s": "";
        return delta+" second"+ps
    }

    if(delta>=60 && delta<=3599){
        min = Math.floor(delta/60);
        sec = delta-(min*60);
        pm = (min>1) ? "s": "";
        ps = (sec>1) ? "s": "";
        return min+" minute"+pm+" "+sec+" second"+ps;
    }

    if(delta>=3600 && delta<=86399){
        hou = Math.floor(delta/3600);
        min = Math.floor((delta-(hou*3600))/60);
        ph = (hou>1) ? "s": "";
        pm = (min>1) ? "s": "";
        return hou+" hour"+ph+" "+min+" minute"+pm;
    } 

    if(delta>=86400){
        days = Math.floor(delta/86400);
        hou =  Math.floor((delta-(days*86400))/60/60);
        pd = (days>1) ? "s": "";
        ph = (hou>1) ? "s": "";
        return days+" day"+pd+" "+hou+" hour"+ph;
    }

}

Excel Macro - Select all cells with data and format as table

Try this one for current selection:

Sub A_SelectAllMakeTable2()
    Dim tbl As ListObject
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

or equivalent of your macro (for Ctrl+Shift+End range selection):

Sub A_SelectAllMakeTable()
    Dim tbl As ListObject
    Dim rng As Range

    Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

Get int from String, also containing letters, in Java

Unless you're talking about base 16 numbers (for which there's a method to parse as Hex), you need to explicitly separate out the part that you are interested in, and then convert it. After all, what would be the semantics of something like 23e44e11d in base 10?

Regular expressions could do the trick if you know for sure that you only have one number. Java has a built in regular expression parser.

If, on the other hands, your goal is to concatenate all the digits and dump the alphas, then that is fairly straightforward to do by iterating character by character to build a string with StringBuilder, and then parsing that one.

How to check if a date is greater than another in Java?

Parse the two dates firstDate and secondDate using SimpleDateFormat.

firstDate.after(secondDate);

firstDate.before(secondDate);

How to resolve Value cannot be null. Parameter name: source in linq?

When you call a Linq statement like this:

// x = new List<string>();
var count = x.Count(s => s.StartsWith("x"));

You are actually using an extension method in the System.Linq namespace, so what the compiler translates this into is:

var count = Enumerable.Count(x, s => s.StartsWith("x"));

So the error you are getting above is because the first parameter, source (which would be x in the sample above) is null.

Difference between exit() and sys.exit() in Python

exit is a helper for the interactive shell - sys.exit is intended for use in programs.

The site module (which is imported automatically during startup, except if the -S command-line option is given) adds several constants to the built-in namespace (e.g. exit). They are useful for the interactive interpreter shell and should not be used in programs.


Technically, they do mostly the same: raising SystemExit. sys.exit does so in sysmodule.c:

static PyObject *
sys_exit(PyObject *self, PyObject *args)
{
    PyObject *exit_code = 0;
    if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
        return NULL;
    /* Raise SystemExit so callers may catch it or clean up. */
    PyErr_SetObject(PyExc_SystemExit, exit_code);
   return NULL;
}

While exit is defined in site.py and _sitebuiltins.py, respectively.

class Quitter(object):
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return 'Use %s() or %s to exit' % (self.name, eof)
    def __call__(self, code=None):
        # Shells like IDLE catch the SystemExit, but listen when their
        # stdin wrapper is closed.
        try:
            sys.stdin.close()
        except:
            pass
        raise SystemExit(code)
__builtin__.quit = Quitter('quit')
__builtin__.exit = Quitter('exit')

Note that there is a third exit option, namely os._exit, which exits without calling cleanup handlers, flushing stdio buffers, etc. (and which should normally only be used in the child process after a fork()).

How can I select and upload multiple files with HTML and PHP, using HTTP POST?

i have created a php function which is used to upload multiple images, this function can upload multiple images in specific folder as well it can saves the records into the database in the following code $arrayimage is the array of images which is sent through form note that it will not allow upload to use multiple but you need to create different input field with same name as will you can set dynamic add field of file unput on button click.

$dir is the directory in which you want to save the image $fields is the name of the field which you want to store in the database

database field must be in array formate example if you have database imagestore and fields name like id,name,address then you need to post data like

$fields=array("id"=$_POST['idfieldname'], "name"=$_POST['namefield'],"address"=$_POST['addressfield']);

and then pass that field into function $fields

$table is the name of the table in which you want to store the data..

function multipleImageUpload($arrayimage,$dir,$fields,$table)
{
    //extracting extension of uploaded file
    $allowedExts = array("gif", "jpeg", "jpg", "png");
    $temp = explode(".", $arrayimage["name"]);
    $extension = end($temp);

    //validating image
    if ((($arrayimage["type"] == "image/gif")
    || ($arrayimage["type"] == "image/jpeg")
    || ($arrayimage["type"] == "image/jpg")
    || ($arrayimage["type"] == "image/pjpeg")
    || ($arrayimage["type"] == "image/x-png")
    || ($arrayimage["type"] == "image/png"))

    //check image size

    && ($arrayimage["size"] < 20000000)

    //check iamge extension in above created extension array
    && in_array($extension, $allowedExts)) 
    {
        if ($arrayimage["error"] > 0) 
        {
            echo "Error: " . $arrayimage["error"] . "<br>";
        } 
        else 
        {
            echo "Upload: " . $arrayimage["name"] . "<br>";
            echo "Type: " . $arrayimage["type"] . "<br>";
            echo "Size: " . ($arrayimage["size"] / 1024) . " kB<br>";
            echo "Stored in: ".$arrayimage['tmp_name']."<br>";

            //check if file is exist in folder of not
            if (file_exists($dir."/".$arrayimage["name"])) 
            {
                echo $arrayimage['name'] . " already exists. ";
            } 
            else 
            {
                //extracting database fields and value
                foreach($fields as $key=>$val)
                {
                    $f[]=$key;
                    $v[]=$val;
                    $fi=implode(",",$f);
                    $value=implode("','",$v);
                }
                //dynamic sql for inserting data into any table
                $sql="INSERT INTO " . $table ."(".$fi.") VALUES ('".$value."')";
                //echo $sql;
                $imginsquery=mysql_query($sql);
                move_uploaded_file($arrayimage["tmp_name"],$dir."/".$arrayimage['name']);
                echo "<br> Stored in: " .$dir ."/ Folder <br>";

            }
        }
    } 
    //if file not match with extension
    else 
    {
        echo "Invalid file";
    }
}
//function imageUpload ends here
}

//imageFunctions class ends here

you can try this code for inserting multiple images with its extension this function is created for checking image files you can replace the extension list for perticular files in the code

Can I assume (bool)true == (int)1 for any C++ compiler?

According to the standard, you should be safe with that assumption. The C++ bool type has two values - true and false with corresponding values 1 and 0.

The thing to watch about for is mixing bool expressions and variables with BOOL expression and variables. The latter is defined as FALSE = 0 and TRUE != FALSE, which quite often in practice means that any value different from 0 is considered TRUE.

A lot of modern compilers will actually issue a warning for any code that implicitly tries to cast from BOOL to bool if the BOOL value is different than 0 or 1.

Load local HTML file in a C# WebBrowser

quite late but it's the first hit i found from google

Instead of using the current directory or getting the assembly, just use the Application.ExecutablePath property:

//using System.IO;  
string applicationDirectory = Path.GetDirectoryName(Application.ExecutablePath);
string myFile = Path.Combine(applicationDirectory, "Sample.html");
webMain.Url = new Uri("file:///" + myFile);

How do I remove newlines from a text file?

Was having the same case today, super easy in vim or nvim, you can use gJ to join lines. For your use case, just do

99gJ

this will join all your 99 lines. You can adjust the number 99 as need according to how many lines to join. If just join 1 line, then only gJ is good enough.

How to detect page zoom level in all modern browsers?

I found this article enormously helpful. Huge thanks to yonran. I wanted to pass on some additional learning I found while implementing some of the techniques he provided. In FF6 and Chrome 9, support for media queries from JS was added, which can greatly simplify the media query approach necessary for determining zoom in FF. See the docs at MDN here. For my purposes, I only needed to detect whether the browser was zoomed in or out, I had no need for the actual zoom factor. I was able to get my answer with one line of JavaScript:

var isZoomed = window.matchMedia('(max--moz-device-pixel-ratio:0.99), (min--moz-device-pixel-ratio:1.01)').matches;

Combining this with the IE8+ and Webkit solutions, which were also single lines, I was able to detect zoom on the vast majority of browsers hitting our app with only a few lines of code.

Image.open() cannot identify image file - Python?

For whoever reaches here with the error colab PIL UnidentifiedImageError: cannot identify image file in Google Colab, with a new PIL versions, and none of the previous solutions works for him:

Simply restart the environment, your installed PIL version is probably outdated.

What is the difference between the float and integer data type when the size is the same?

  • float stores floating-point values, that is, values that have potential decimal places
  • int only stores integral values, that is, whole numbers

So while both are 32 bits wide, their use (and representation) is quite different. You cannot store 3.141 in an integer, but you can in a float.

Dissecting them both a little further:

In an integer, all bits are used to store the number value. This is (in Java and many computers too) done in the so-called two's complement. This basically means that you can represent the values of −231 to 231 − 1.

In a float, those 32 bits are divided between three distinct parts: The sign bit, the exponent and the mantissa. They are laid out as follows:

S EEEEEEEE MMMMMMMMMMMMMMMMMMMMMMM

There is a single bit that determines whether the number is negative or non-negative (zero is neither positive nor negative, but has the sign bit set to zero). Then there are eight bits of an exponent and 23 bits of mantissa. To get a useful number from that, (roughly) the following calculation is performed:

M × 2E

(There is more to it, but this should suffice for the purpose of this discussion)

The mantissa is in essence not much more than a 24-bit integer number. This gets multiplied by 2 to the power of the exponent part, which, roughly, is a number between −128 and 127.

Therefore you can accurately represent all numbers that would fit in a 24-bit integer but the numeric range is also much greater as larger exponents allow for larger values. For example, the maximum value for a float is around 3.4 × 1038 whereas int only allows values up to 2.1 × 109.

But that also means, since 32 bits only have 4.2 × 109 different states (which are all used to represent the values int can store), that at the larger end of float's numeric range the numbers are spaced wider apart (since there cannot be more unique float numbers than there are unique int numbers). You cannot represent some numbers exactly, then. For example, the number 2 × 1012 has a representation in float of 1,999,999,991,808. That might be close to 2,000,000,000,000 but it's not exact. Likewise, adding 1 to that number does not change it because 1 is too small to make a difference in the larger scales float is using there.

Similarly, you can also represent very small numbers (between 0 and 1) in a float but regardless of whether the numbers are very large or very small, float only has a precision of around 6 or 7 decimal digits. If you have large numbers those digits are at the start of the number (e.g. 4.51534 × 1035, which is nothing more than 451534 follows by 30 zeroes – and float cannot tell anything useful about whether those 30 digits are actually zeroes or something else), for very small numbers (e.g. 3.14159 × 10−27) they are at the far end of the number, way beyond the starting digits of 0.0000...

ORACLE IIF Statement

In PL/SQL, there is a trick to use the undocumented OWA_UTIL.ITE function.

SET SERVEROUTPUT ON

DECLARE
    x   VARCHAR2(10);
BEGIN
    x := owa_util.ite('a' = 'b','T','F');
    dbms_output.put_line(x);
END;
/

F

PL/SQL procedure successfully completed.

Close Current Tab

Found a one-liner that works in Chrome 66 from: http://www.yournewdesigner.com/css-experiments/javascript-window-close-firefox.html

TLDR: tricks the browser into believing JavaScirpt opened the current tab/window

window.open('', '_parent', '').close();

So for completeness

<input type="button" name="close" value="close" onclick="window.close();">

Though let it also be noted that readers may want to place this into a function that fingerprints which browsers require such trickery, because Firefox 59 doesn't work with the above.

MySQL Calculate Percentage

try this

   SELECT group_name, employees, surveys, COUNT( surveys ) AS test1, 
        concat(round(( surveys/employees * 100 ),2),'%') AS percentage
    FROM a_test
    GROUP BY employees

DEMO HERE

Output Django queryset as JSON

To return the queryset you retrieved with queryset = Users.objects.all(), you first need to serialize them.

Serialization is the process of converting one data structure to another. Using Class-Based Views, you could return JSON like this.

from django.core.serializers import serialize
from django.http import JsonResponse
from django.views.generic import View

class JSONListView(View):
    def get(self, request, *args, **kwargs):
        qs = User.objects.all()
        data = serialize("json", qs)
        return JsonResponse(data)

This will output a list of JSON. For more detail on how this works, check out my blog article How to return a JSON Response with Django. It goes into more detail on how you would go about this.

Pythonic way to print list items

[print(a) for a in list] will give a bunch of None types at the end though it prints out all the items

How to create a JPA query with LEFT OUTER JOIN

Normally the ON clause comes from the mapping's join columns, but the JPA 2.1 draft allows for additional conditions in a new ON clause.

See,

http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/JPQL#ON

Looping over a list in Python

You may as well use for x in values rather than for x in values[:]; the latter makes an unnecessary copy. Also, of course that code checks for a length of 2 rather than of 3...

The code only prints one item per value of x - and x is iterating over the elements of values, which are the sublists. So it will only print each sublist once.

Advantages of using display:inline-block vs float:left in CSS

There is one characteristic about inline-block which may not be straight-forward though. That is that the default value for vertical-align in CSS is baseline. This may cause some unexpected alignment behavior. Look at this article.

http://www.brunildo.org/test/inline-block.html

Instead, when you do a float:left, the divs are independent of each other and you can align them using margin easily.

Set value of hidden input with jquery

To make it with jquery, make this way:

var test = $("input[name=testing]:hidden");
test.val('work!');

Or

var test = $("input[name=testing]:hidden").val('work!');

See working in this fiddle.

Is there a "not equal" operator in Python?

Not equal != (vs equal ==)

Are you asking about something like this?

answer = 'hi'

if answer == 'hi':     # equal
   print "hi"
elif answer != 'hi':   # not equal
   print "no hi"

This Python - Basic Operators chart might be helpful.

The Android emulator is not starting, showing "invalid command-line parameter"

emulator-arm.exe error, couldn't run. Problem was that my laptop has 2 graphic cards and was selected only one (the performance one) from Nvidia 555M. By selecting the other graphic card from Nvidia mediu,(selected base Intel card) the emulator started!

ThreeJS: Remove object from scene

I think seeing your usage for addEntity and removeEntity code would be helpful, but my first thought is are you actually setting the object.name? Try in your loader just before scene.add(object); something like this:

object.name = "test_name";
scene.add(object);

What might be happening is the default "name" for an Object3D is "", so when you then call your removeEntity function it fails due to the scene objects name being ""

Also, I notice you pass in object.name to your loader? Is this where your storing the URL to the resource? If so, I would recommend using the Object3D's built in .userData method to store that information and keep the name field for scene identification purposes.

Edit: Response to newly added Code

First thing to note is it's not a great idea to have "/" in your object name, it seems to work fine but you never know if some algorithm will decide to escape that string and break your project.

Second item is now that I've seen your code, its actually straight forward whats going on. Your delete function is trying to delete by name, you need an Object3D to delete. Try this:

function removeEntity(object) {
    var selectedObject = scene.getObjectByName(object.name);
    scene.remove( selectedObject );
    animate();
}

Here you see I lookup your Object3D in the Three.js Scene by passing in your object tag's name attribute. Hope that helps

How can I sort generic list DESC and ASC?

Without Linq:

Ascending:

li.Sort();

Descending:

li.Sort();
li.Reverse();

How to change resolution (DPI) of an image?

It's simply a matter of scaling the image width and height up by the correct ratio. Not all images formats support a DPI metatag, and when they do, all they're telling your graphics software to do is divide the image by the ratio supplied.

For example, if you export a 300dpi image from Photoshop to a JPEG, the image will appear to be very large when viewed in your picture viewing software. This is because the DPI information isn't supported in JPEG and is discarded when saved. This means your picture viewer doesn't know what ratio to divide the image by and instead displays the image at at 1:1 ratio.

To get the ratio you need to scale the image by, see the code below. Just remember, this will stretch the image, just like it would in Photoshop. You're essentially quadrupling the size of the image so it's going to stretch and may produce artifacts.

Pseudo code

ratio = 300.0 / 72.0   // 4.167
image.width * ratio
image.height * ratio

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

OS Mojave 10.14., Python 3.6

Using pip install graphviz had good feedback in terminal, but lead to this error when I tried to make a graph in a Jupyter notebook. I then ran brew install graphviz, which gave an error in terminal. Then I ran conda install graphviz and the graph worked.

From @Leighton's comment: pip only gets path problem same as yours and conda only gets import error.

To draw an Underline below the TextView in Android

In Kotlin you can create extension property:

inline var TextView.underline: Boolean
    set(visible) {
        paintFlags = if (visible) paintFlags or Paint.UNDERLINE_TEXT_FLAG
        else paintFlags and Paint.UNDERLINE_TEXT_FLAG.inv()
    }
    get() = paintFlags and Paint.UNDERLINE_TEXT_FLAG == Paint.UNDERLINE_TEXT_FLAG

And use:

textView.underline = true

Open Excel file for reading with VBA without display

Open the workbook as hidden and then set it as "saved" so that users are not prompted when they close out.

Dim w As Workbooks

Private Sub Workbook_Open()
    Application.ScreenUpdating = False
    Set w = Workbooks
    w.Open Filename:="\\server\PriceList.xlsx", UpdateLinks:=False, ReadOnly:=True 'this is the data file were going to be opening
    ActiveWindow.Visible = False
    ThisWorkbook.Activate
    Application.ScreenUpdating = True
End Sub

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    w.Item(2).Saved = True 'this will suppress the safe prompt for the data file only
End Sub

This is somewhat derivative of the answer posted by Ashok.

By doing it this way though you will not get prompted to save changes back to the Excel file your reading from. This is great if the Excel file your reading from is intended as a data source for validation. For example if the workbook contains product names and price data it can be hidden and you can show an Excel file that represents an invoice with drop downs for product that validates from that price list.

You can then store the price list on a shared location on a network somewhere and make it read-only.

Tainted canvases may not be exported

Check out CORS enabled image from MDN. Basically you must have a server hosting images with the appropriate Access-Control-Allow-Origin header.

_x000D_
_x000D_
<IfModule mod_setenvif.c>
    <IfModule mod_headers.c>
        <FilesMatch "\.(cur|gif|ico|jpe?g|png|svgz?|webp)$">
            SetEnvIf Origin ":" IS_CORS
            Header set Access-Control-Allow-Origin "*" env=IS_CORS
        </FilesMatch>
    </IfModule>
</IfModule>
_x000D_
_x000D_
_x000D_

You will be able to save those images to DOM Storage as if they were served from your domain otherwise you will run into security issue.

_x000D_
_x000D_
var img = new Image,
    canvas = document.createElement("canvas"),
    ctx = canvas.getContext("2d"),
    src = "http://example.com/image"; // insert image url here

img.crossOrigin = "Anonymous";

img.onload = function() {
    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage( img, 0, 0 );
    localStorage.setItem( "savedImageData", canvas.toDataURL("image/png") );
}
img.src = src;
// make sure the load event fires for cached images too
if ( img.complete || img.complete === undefined ) {
    img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
    img.src = src;
}
_x000D_
_x000D_
_x000D_

Getting NetworkCredential for current user (C#)

You can get the user name using System.Security.Principal.WindowsIdentity.GetCurrent() but there is not way to get current user password!

How can I convert byte size into a human-readable format in Java?

This is a modified version of aioobe's answer.

Changes:

  • Locale parameter, because some languages use . and others , as decimal point.
  • human-readable code

private static final String[] SI_UNITS = { "B", "kB", "MB", "GB", "TB", "PB", "EB" };
private static final String[] BINARY_UNITS = { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB" };

public static String humanReadableByteCount(final long bytes, final boolean useSIUnits, final Locale locale)
{
    final String[] units = useSIUnits ? SI_UNITS : BINARY_UNITS;
    final int base = useSIUnits ? 1000 : 1024;

    // When using the smallest unit no decimal point is needed, because it's the exact number.
    if (bytes < base) {
        return bytes + " " + units[0];
    }

    final int exponent = (int) (Math.log(bytes) / Math.log(base));
    final String unit = units[exponent];
    return String.format(locale, "%.1f %s", bytes / Math.pow(base, exponent), unit);
}

How can I use iptables on centos 7?

And to add, you should also be able to do the same for ip6tables after running the systemctl mask firewalld command:

    systemctl start ip6tables.service
    systemctl enable ip6tables.service

nginx: how to create an alias url route?

server {
  server_name example.com;
  root /path/to/root;
  location / {
    # bla bla
  }
  location /demo {
    alias /path/to/root/production/folder/here;
  }
}

If you need to use try_files inside /demo you'll need to replace alias with a root and do a rewrite because of the bug explained here

ERROR:'keytool' is not recognized as an internal or external command, operable program or batch file

The keytool command might not be in your path—it’s part of Java, which is installed as part of Android Studio. For the concrete path, run flutter doctor -v and locate the path printed after ‘Java binary at:’. Then use that fully qualified path replacing java (at the end) with keytool. If your path includes space-separated names, such as Program Files, use platform-appropriate notation for the names. For example, on Mac/Linux use Program\ Files, and on Windows use "Program Files".

What is <=> (the 'Spaceship' Operator) in PHP 7?

The <=> ("Spaceship") operator will offer combined comparison in that it will :

Return 0 if values on either side are equal
Return 1 if the value on the left is greater
Return -1 if the value on the right is greater

The rules used by the combined comparison operator are the same as the currently used comparison operators by PHP viz. <, <=, ==, >= and >. Those who are from Perl or Ruby programming background may already be familiar with this new operator proposed for PHP7.

   //Comparing Integers

    echo 1 <=> 1; //output  0
    echo 3 <=> 4; //output -1
    echo 4 <=> 3; //output  1

    //String Comparison

    echo "x" <=> "x"; //output  0
    echo "x" <=> "y"; //output -1
    echo "y" <=> "x"; //output  1

Is there a way to ignore a single FindBugs warning?

At the time of writing this (May 2018), FindBugs seems to have been replaced by SpotBugs. Using the SuppressFBWarnings annotation requires your code to be compiled with Java 8 or later and introduces a compile time dependency on spotbugs-annotations.jar.

Using a filter file to filter SpotBugs rules has no such issues. The documentation is here.

jQuery counting elements by class - what is the best way to implement this?

Getting a count of the number of elements that refer to the same class is as simple as this

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
        <script type="text/javascript">

            $(document).ready(function() {
                alert( $(".red").length );
            });

        </script>
    </head>
    <body>

        <p class="red">Test</p>
        <p class="red">Test</p>
        <p class="red anotherclass">Test</p>
        <p class="red">Test</p>
        <p class="red">Test</p>
        <p class="red anotherclass">Test</p>
    </body>
</html>

PHP Parse error: syntax error, unexpected end of file in a CodeIgniter View

Usually the problem is not closing brackets (}) or missing semicolon (;)

Stop UIWebView from "bouncing" vertically?

webView.scrollView.scrollEnabled=NO; webView.scrollView.bounces=NO;

Using Gulp to Concatenate and Uglify files

Solution using gulp-uglify, gulp-concat and gulp-sourcemaps. This is from a project I'm working on.

gulp.task('scripts', function () {
    return gulp.src(scripts, {base: '.'})
        .pipe(plumber(plumberOptions))
        .pipe(sourcemaps.init({
            loadMaps: false,
            debug: debug,
        }))
        .pipe(gulpif(debug, wrapper({
            header: fileHeader,
        })))
        .pipe(concat('all_the_things.js', {
            newLine:'\n;' // the newline is needed in case the file ends with a line comment, the semi-colon is needed if the last statement wasn't terminated
        }))
        .pipe(uglify({
            output: { // http://lisperator.net/uglifyjs/codegen
                beautify: debug,
                comments: debug ? true : /^!|\b(copyright|license)\b|@(preserve|license|cc_on)\b/i,
            },
            compress: { // http://lisperator.net/uglifyjs/compress, http://davidwalsh.name/compress-uglify
                sequences: !debug,
                booleans: !debug,
                conditionals: !debug,
                hoist_funs: false,
                hoist_vars: debug,
                warnings: debug,
            },
            mangle: !debug,
            outSourceMap: true,
            basePath: 'www',
            sourceRoot: '/'
        }))
        .pipe(sourcemaps.write('.', {
            includeContent: true,
            sourceRoot: '/',
        }))
        .pipe(plumber.stop())
        .pipe(gulp.dest('www/js'))
});

This combines and compresses all your scripts, puts them into a file called all_the_things.js. The file will end with a special line

//# sourceMappingURL=all_the_things.js.map

Which tells your browser to look for that map file, which it also writes out.

How to change the timeout on a .NET WebClient object

For anyone who needs a WebClient with a timeout that works for async/task methods, the suggested solutions won't work. Here's what does work:

public class WebClientWithTimeout : WebClient
{
    //10 secs default
    public int Timeout { get; set; } = 10000;

    //for sync requests
    protected override WebRequest GetWebRequest(Uri uri)
    {
        var w = base.GetWebRequest(uri);
        w.Timeout = Timeout; //10 seconds timeout
        return w;
    }

    //the above will not work for async requests :(
    //let's create a workaround by hiding the method
    //and creating our own version of DownloadStringTaskAsync
    public new async Task<string> DownloadStringTaskAsync(Uri address)
    {
        var t = base.DownloadStringTaskAsync(address);
        if(await Task.WhenAny(t, Task.Delay(Timeout)) != t) //time out!
        {
            CancelAsync();
        }
        return await t;
    }
}

I blogged about the full workaround here

How can I find the last element in a List<>?

Change

for (int cnt3 = 0 ; cnt3 <= integerList.FindLastIndex ; cnt3++)

to

for (int cnt3 = 0 ; cnt3 < integerList.Count; cnt3++)

Input size vs width

I just got through fighting with a table that I couldn't make any smaller no matter which element I tried to make smaller the width of the table stayed the same. I searched using firebug but couldn't find the element that was setting the width so high.

Finally I tried changing the size attribute of the input text elements and that fixed it. For some reason the size attribute over-rode the css widths. I was using jQuery to dynamically add rows to a table and it was these rows that contained the inputs. So perhaps when it comes to dynamically adding inputs using the appendTo() function maybe it is better to set the size attribute along with the width.

How to get the list of all printers in computer

Look at the static System.Drawing.Printing.PrinterSettings.InstalledPrinters property.

It is a list of the names of all installed printers on the system.

MySQL InnoDB not releasing disk space after deleting data rows from table

Just had the same problem myself.

What happens is, that even if you drop the database, innodb will still not release disk space. I had to export, stop mysql, remove the files manually, start mysql, create database and users, and then import. Thank god I only had 200MB worth of rows, but it spared 250GB of innodb file.

Fail by design.

Django optional url parameters

Django = 2.2

urlpatterns = [
    re_path(r'^project_config/(?:(?P<product>\w+)/(?:(?P<project_id>\w+)/)/)?$', tool.views.ProjectConfig, name='project_config')
]

How to insert an object in an ArrayList at a specific position

Note that when you insert into a List at a position, you are really inserting at a dynamic position within the List's current elements. See here:

http://tpcg.io/0KmArS

package com.tutorialspoint;

import java.util.ArrayList;

public class ArrayListDemo {
   public static void main(String[] args) {

      // create an empty array list with an initial capacity
      ArrayList<Integer> arrlist = new ArrayList<Integer>(5);

      // use add() method to add elements in the list
      arrlist.add(15, 15);
      arrlist.add(22, 22);
      arrlist.add(30, 30);
      arrlist.add(40, 40);

      // adding element 25 at third position
      arrlist.add(2, 25);

      // let us print all the elements available in list
      for (Integer number : arrlist) {
         System.out.println("Number = " + number);
      }  
   }
}

$javac com/tutorialspoint/ArrayListDemo.java

$java -Xmx128M -Xms16M com/tutorialspoint/ArrayListDemo

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 15, Size: 0
    at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:661)
    at java.util.ArrayList.add(ArrayList.java:473)
    at com.tutorialspoint.ArrayListDemo.main(ArrayListDemo.java:12)

How to convert LINQ query result to List?

You need to somehow convert each tbcourse object to an instance of course. For instance course could have a constructor that takes a tbcourse. You could then write the query like this:

var qry = from c in obj.tbCourses
          select new course(c);

List<course> lst = qry.ToList();

Get Date in YYYYMMDD format in windows batch file

You can try this ! This should work on windows machines.

for /F "usebackq tokens=1,2,3 delims=-" %%I IN (`echo %date%`) do echo "%%I" "%%J" "%%K"

Re-run Spring Boot Configuration Annotation Processor to update generated metadata

For me, other answers didn't work. I had to go to open Files and do Invalidate caches and restart on Intellij. After that, everything worked fine again.

android View not attached to window manager

Another option is not to start the async task until the dialog is attached to the window by overriding onAttachedToWindow() on the dialog, that way it is always dismissible.

Can dplyr package be used for conditional mutating?

case_when is now a pretty clean implementation of the SQL-style case when:

structure(list(a = c(1, 3, 4, 6, 3, 2, 5, 1), b = c(1, 3, 4, 
2, 6, 7, 2, 6), c = c(6, 3, 6, 5, 3, 6, 5, 3), d = c(6, 2, 4, 
5, 3, 7, 2, 6), e = c(1, 2, 4, 5, 6, 7, 6, 3), f = c(2, 3, 4, 
2, 2, 7, 5, 2)), .Names = c("a", "b", "c", "d", "e", "f"), row.names = c(NA, 
8L), class = "data.frame") -> df


df %>% 
    mutate( g = case_when(
                a == 2 | a == 5 | a == 7 | (a == 1 & b == 4 )     ~   2,
                a == 0 | a == 1 | a == 4 |  a == 3 | c == 4       ~   3
))

Using dplyr 0.7.4

The manual: http://dplyr.tidyverse.org/reference/case_when.html

UITableView - scroll to the top

If you don't want scrolling, you can start and stop the scrolling animation as soon as you start it.

    $('document').ready(function() {
    $("html, body").animate({ scrollTop: 0 }, 500);
    return true;
    });

Also, to animate put values for 'x' and 'y', passing in 0,0 will scroll the page to the top left instantly.

window.scrollTo(x, y);

POST data in JSON format

Here is an example using jQuery...

 <head>
   <title>Test</title>
   <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
   <script type="text/javascript" src="http://www.json.org/json2.js"></script>
   <script type="text/javascript">
     $(function() {
       var frm = $(document.myform);
       var dat = JSON.stringify(frm.serializeArray());

       alert("I am about to POST this:\n\n" + dat);

       $.post(
         frm.attr("action"),
         dat,
         function(data) {
           alert("Response: " + data);
         }
       );
     });
   </script>
</head>

The jQuery serializeArray function creates a Javascript object with the form values. Then you can use JSON.stringify to convert that into a string, if needed. And you can remove your body onload, too.

write() versus writelines() and concatenated strings

Actually, I think the problem is that your variable "lines" is bad. You defined lines as a tuple, but I believe that write() requires a string. All you have to change is your commas into pluses (+).

nl = "\n"
lines = line1+nl+line2+nl+line3+nl
textdoc.writelines(lines)

should work.

Oracle timestamp data type

The number in parentheses specifies the precision of fractional seconds to be stored. So, (0) would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.

So an unspecified value would store a date like:

TIMESTAMP 24-JAN-2012 08.00.05.993847 AM

And specifying (0) stores only:

TIMESTAMP(0) 24-JAN-2012 08.00.05 AM

See Oracle documentation on data types.

pip install: Please check the permissions and owner of that directory

pip install --user <package name> (no sudo needed) worked for me for a very similar problem.

Service Reference Error: Failed to generate code for the service reference

Have to uncheck the Reuse types in all referenced assemblies from Configure service reference option

Check this for details

Connect to Active Directory via LDAP

DC is your domain. If you want to connect to the domain example.com than your dc's are: DC=example,DC=com

You actually don't need any hostname or ip address of your domain controller (There could be plenty of them).

Just imagine that you're connecting to the domain itself. So for connecting to the domain example.com you can simply write

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");

And you're done.

You can also specify a user and a password used to connect:

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com", "username", "password");

Also be sure to always write LDAP in upper case. I had some trouble and strange exceptions until I read somewhere that I should try to write it in upper case and that solved my problems.

The directoryEntry.Path Property allows you to dive deeper into your domain. So if you want to search a user in a specific OU (Organizational Unit) you can set it there.

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
directoryEntry.Path = "LDAP://OU=Specific Users,OU=All Users,OU=Users,DC=example,DC=com";

This would match the following AD hierarchy:

  • com
    • example
      • Users
        • All Users
          • Specific Users

Simply write the hierarchy from deepest to highest.

Now you can do plenty of things

For example search a user by account name and get the user's surname:

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
DirectorySearcher searcher = new DirectorySearcher(directoryEntry) {
    PageSize = int.MaxValue,
    Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=AnAccountName))"
};

searcher.PropertiesToLoad.Add("sn");

var result = searcher.FindOne();

if (result == null) {
    return; // Or whatever you need to do in this case
}

string surname;

if (result.Properties.Contains("sn")) {
    surname = result.Properties["sn"][0].ToString();
}

IIS: Where can I find the IIS logs?

I have found the IIS Log files at the following location.

C:\inetpub\logs\LogFiles\

which help to fix my issue.

What is sr-only in Bootstrap 3?

The .sr-only class hides an element to all devices except screen readers:

Skip to main content Combine .sr-only with .sr-only-focusable to show the element again when it is focused

.sr-only {
border: 0 !important;
clip: rect(1px, 1px, 1px, 1px) !important; /* 1 */
-webkit-clip-path: inset(50%) !important;
    clip-path: inset(50%) !important;  /* 2 */
height: 1px !important;
margin: -1px !important;
overflow: hidden !important;
padding: 0 !important;
position: absolute !important;
width: 1px !important;
white-space: nowrap !important;            /* 3 */

}

Get Excel sheet name and use as variable in macro

in a Visual Basic Macro you would use

pName = ActiveWorkbook.Path      ' the path of the currently active file
wbName = ActiveWorkbook.Name     ' the file name of the currently active file
shtName = ActiveSheet.Name       ' the name of the currently selected worksheet

The first sheet in a workbook can be referenced by

ActiveWorkbook.Worksheets(1)

so after deleting the [Report] tab you would use

ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name

to "work on that sheet later on" you can create a range object like

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]

and continue working on MySheet(rowNum, colNum) etc. ...

shortcut creation of a range object without defining shtName:

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]

c++ boost split string

The problem is somewhere else in your code, because this works:

string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));

cout << "* size of the vector: " << strs.size() << endl;    
for (size_t i = 0; i < strs.size(); i++)
    cout << strs[i] << endl;

and testing your approach, which uses a vector iterator also works:

string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));

cout << "* size of the vector: " << strs.size() << endl;
for (vector<string>::iterator it = strs.begin(); it != strs.end(); ++it)
{
    cout << *it << endl;
}

Again, your problem is somewhere else. Maybe what you think is a \t character on the string, isn't. I would fill the code with debugs, starting by monitoring the insertions on the vector to make sure everything is being inserted the way its supposed to be.

Output:

* size of the vector: 3
test
test2
test3

incompatible character encodings: ASCII-8BIT and UTF-8

I have a suspicion that you either copy/pasted a part of your Haml template into the file, or you're working with a non-Unicode/non-UTF-8 friendly editor.

See if you can recreate that file from the scratch in a UTF-8 friendly editor. There are plenty for any platform and see whether this fixes your problem. Start by erasing the line with #content and retyping it manually.

How to store a dataframe using Pandas

Although there are already some answers I found a nice comparison in which they tried several ways to serialize Pandas DataFrames: Efficiently Store Pandas DataFrames.

They compare:

  • pickle: original ASCII data format
  • cPickle, a C library
  • pickle-p2: uses the newer binary format
  • json: standardlib json library
  • json-no-index: like json, but without index
  • msgpack: binary JSON alternative
  • CSV
  • hdfstore: HDF5 storage format

In their experiment, they serialize a DataFrame of 1,000,000 rows with the two columns tested separately: one with text data, the other with numbers. Their disclaimer says:

You should not trust that what follows generalizes to your data. You should look at your own data and run benchmarks yourself

The source code for the test which they refer to is available online. Since this code did not work directly I made some minor changes, which you can get here: serialize.py I got the following results:

time comparison results

They also mention that with the conversion of text data to categorical data the serialization is much faster. In their test about 10 times as fast (also see the test code).

Edit: The higher times for pickle than CSV can be explained by the data format used. By default pickle uses a printable ASCII representation, which generates larger data sets. As can be seen from the graph however, pickle using the newer binary data format (version 2, pickle-p2) has much lower load times.

Some other references:

Android Percentage Layout Height

You could add another empty layout below that one and set them both to have the same layout weight. They should get 50% of the space each.

How to recover corrupted Eclipse workspace?

In my case, it was not the workspace that was broken but Eclipse itself. Even though it seemed like workspace is broken (the same error dialog, etc.), all I had to do was reinstall Eclipse and point it to the old workspace. You can't really repair a broken workspace if it is the workspace that is broken but you can do so just for good measure, maybe it'll work.

npm install error from the terminal

First download json package file from https://github.com/npm/read-package-json and then run npm install from terminal.

Inheritance and init method in Python

In the first situation, Num2 is extending the class Num and since you are not redefining the special method named __init__() in Num2, it gets inherited from Num.

When a class defines an __init__() method, class instantiation automatically invokes __init__() for the newly-created class instance.

In the second situation, since you are redefining __init__() in Num2 you need to explicitly call the one in the super class (Num) if you want to extend its behavior.

class Num2(Num):
    def __init__(self,num):
        Num.__init__(self,num)
        self.n2 = num*2

Python list directory, subdirectory, and files

A bit simpler one-liner:

import os
from itertools import product, chain

chain.from_iterable([[os.sep.join(w) for w in product([i[0]], i[2])] for i in os.walk(dir)])

Force LF eol in git repo and working copy

To force LF line endings for all text files, you can create .gitattributes file in top-level of your repository with the following lines (change as desired):

# Ensure all C and PHP files use LF.
*.c         eol=lf
*.php       eol=lf

which ensures that all files that Git considers to be text files have normalized (LF) line endings in the repository (normally core.eol configuration controls which one do you have by default).

Based on the new attribute settings, any text files containing CRLFs should be normalized by Git. If this won't happen automatically, you can refresh a repository manually after changing line endings, so you can re-scan and commit the working directory by the following steps (given clean working directory):

$ echo "* text=auto" >> .gitattributes
$ rm .git/index     # Remove the index to force Git to
$ git reset         # re-scan the working directory
$ git status        # Show files that will be normalized
$ git add -u
$ git add .gitattributes
$ git commit -m "Introduce end-of-line normalization"

or as per GitHub docs:

git add . -u
git commit -m "Saving files before refreshing line endings"
git rm --cached -r . # Remove every file from Git's index.
git reset --hard # Rewrite the Git index to pick up all the new line endings.
git add . # Add all your changed files back, and prepare them for a commit.
git commit -m "Normalize all the line endings" # Commit the changes to your repository.

See also: @Charles Bailey post.

In addition, if you would like to exclude any files to not being treated as a text, unset their text attribute, e.g.

manual.pdf      -text

Or mark it explicitly as binary:

# Denote all files that are truly binary and should not be modified.
*.png binary
*.jpg binary

To see some more advanced git normalization file, check .gitattributes at Drupal core:

# Drupal git normalization
# @see https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html
# @see https://www.drupal.org/node/1542048

# Normally these settings would be done with macro attributes for improved
# readability and easier maintenance. However macros can only be defined at the
# repository root directory. Drupal avoids making any assumptions about where it
# is installed.

# Define text file attributes.
# - Treat them as text.
# - Ensure no CRLF line-endings, neither on checkout nor on checkin.
# - Detect whitespace errors.
#   - Exposed by default in `git diff --color` on the CLI.
#   - Validate with `git diff --check`.
#   - Deny applying with `git apply --whitespace=error-all`.
#   - Fix automatically with `git apply --whitespace=fix`.

*.config  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.css     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.dist    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.engine  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.html    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=html
*.inc     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.install text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.js      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.json    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.lock    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.map     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.md      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.module  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.php     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.po      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.profile text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.script  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.sh      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.sql     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.svg     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.theme   text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.twig    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.txt     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.xml     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.yml     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2

# Define binary file attributes.
# - Do not treat them as text.
# - Include binary diff in patches instead of "binary files differ."
*.eot     -text diff
*.exe     -text diff
*.gif     -text diff
*.gz      -text diff
*.ico     -text diff
*.jpeg    -text diff
*.jpg     -text diff
*.otf     -text diff
*.phar    -text diff
*.png     -text diff
*.svgz    -text diff
*.ttf     -text diff
*.woff    -text diff
*.woff2   -text diff

See also:

How to check for null/empty/whitespace values with a single test?

you can use

SELECT [column_name] 
FROM [table_name]
WHERE [column_name] LIKE '% %' 
OR [column_name] IS NULL

Initial size for the ArrayList

This might help someone -

ArrayList<Integer> integerArrayList = new ArrayList<>(Arrays.asList(new Integer[10]));

How to SUM two fields within an SQL query

Try the following:

SELECT *, (FieldA + FieldB) AS Sum
FROM Table

Wipe data/Factory reset through ADB

After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.

 * The arguments which may be supplied in the recovery.command file:
 *   --send_intent=anystring - write the text out to recovery.intent
 *   --update_package=path - verify install an OTA package file
 *   --wipe_data - erase user data (and cache), then reboot
 *   --wipe_cache - wipe cache (but not user data), then reboot
 *   --set_encrypted_filesystem=on|off - enables / diasables encrypted fs

Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:

adb shell
recovery --wipe_data

Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.

EDIT:

For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command

For more information please see here: https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c

What does "O(1) access time" mean?

According to my perspective,

O(1) means time to execute one operation or instruction at a time is one, in time complexity analysis of algorithm for best case.

Retrieve all values from HashMap keys in an ArrayList Java

Java 8 solution for produce string like "key1: value1,key2: value2"

private static String hashMapToString(HashMap<String, String> hashMap) {

    return hashMap.keySet().stream()
            .map((key) -> key + ": " + hashMap.get(key))
            .collect(Collectors.joining(","));

}

and produce a list simple collect as list

private static List<String> hashMapToList(HashMap<String, String> hashMap) {

    return hashMap.keySet().stream()
            .map((key) -> key + ": " + hashMap.get(key))
            .collect(Collectors.toList());

}

Getting distance between two points based on latitude/longitude

You can use Uber's H3,point_dist() function to compute the spherical distance between two (lat, lng) points. We can set return unit ('km', 'm', or 'rads'). The default unit is Km.

Example :

import H3

coords_1 = (52.2296756, 21.0122287)
coords_2 = (52.406374, 16.9251681)
distance = h3.point_dist(coords_1,coords_2) #278.4584889328128

Hope this will usefull!

Access camera from a browser

As of 2017, WebKit announces support for WebRTC on Safari

Now you can access them with video and standard javascript WebRTC

E.g.

var video = document.createElement('video');
video.setAttribute('playsinline', '');
video.setAttribute('autoplay', '');
video.setAttribute('muted', '');
video.style.width = '200px';
video.style.height = '200px';

/* Setting up the constraint */
var facingMode = "user"; // Can be 'user' or 'environment' to access back or front camera (NEAT!)
var constraints = {
  audio: false,
  video: {
   facingMode: facingMode
  }
};

/* Stream it to video element */
navigator.mediaDevices.getUserMedia(constraints).then(function success(stream) {
  video.srcObject = stream;
});

Have a play with it.

git ignore vim temporary files

Here is the actual VIM code that generates the swap file extensions:

/* 
 * Change the ".swp" extension to find another file that can be used. 
 * First decrement the last char: ".swo", ".swn", etc. 
 * If that still isn't enough decrement the last but one char: ".svz" 
 * Can happen when editing many "No Name" buffers. 
 */
if (fname[n - 1] == 'a')        /* ".s?a" */
{   
    if (fname[n - 2] == 'a')    /* ".saa": tried enough, give up */
    {   
        EMSG(_("E326: Too many swap files found"));
        vim_free(fname);
        fname = NULL;
        break;  
    }
    --fname[n - 2];             /* ".svz", ".suz", etc. */
    fname[n - 1] = 'z' + 1;
}
--fname[n - 1];                 /* ".swo", ".swn", etc. */

This will generate swap files of the format:

[._]*.s[a-v][a-z]
[._]*.sw[a-p]
[._]s[a-v][a-z]
[._]sw[a-p]

Which is pretty much what is included in github's own gitignore file for VIM.

As others have correctly noted, this .gitignore will also ignore .svg image files and .swf adobe flash files.

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

If you want to bypass that restriction when fetching the contents with fetch API or XMLHttpRequest in javascript, you can use a proxy server so that it sets the header Access-Control-Allow-Origin to *.

const express = require('express');
const request = require('request');

const app = express();

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});

app.get('/fetch', (req, res) => {
  request(
    { url: req.query.url },
    (error, response, body) => {
      if (error || response.statusCode !== 200) {
        return res.status(500).send('error');
      }
      res.send(body);
    }
  )
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`listening on ${PORT}`));

Above is a sample code( node Js required ) which can act as a proxy server. For eg: If I want to fetch https://www.google.com normally a CORS error is thrown, but now since the request is sent through the proxy server hosted locally at port 3000, the proxy server adds the Access-Control-Allow-Origin header in the response and there wont be any issue.

Send a GET request to http://localhost:3000/fetch?url=Your URL here , instead of directly sending the request to the URl you want to fetch.

Your URL here stands for the URL you wish to fetch eg: https://www.google.com

How can I determine if a .NET assembly was built for x86 or x64?

An alternative to already mentioned tools is Telerik JustDecompile (free tool) which will display the information next to the assembly name:

Any or x86 or x64 information in Telerik

How To Make Circle Custom Progress Bar in Android

I've encountered same problem and not found any appropriate solution for my case, so I decided to go another way. I've created custom drawable class. Within this class I've created 2 Paints for progress line and background line (with some bigger stroke). First of all set startAngle and sweepAngle in constructor:

    mSweepAngle = 0;
    mStartAngle = 270;

Here is onDraw method of this class:

@Override
public void draw(Canvas canvas) {
    // draw background line
    canvas.drawArc(mRectF, 0, 360, false, mPaintBackground);
    // draw progress line
    canvas.drawArc(mRectF, mStartAngle, mSweepAngle, false, mPaintProgress);
}

So now all you need to do is set this drawable as a backgorund of the view, in background thread change sweepAngle:

mSweepAngle += 360 / totalTimerTime // this is mStep

and directly call InvalidateSelf() with some interval (e.g every 1 second or more often if you want smooth progress changes) on the view that have this drawable as a background. Thats it!

P.S. I know, I know...of course you want some more code. So here it is all flow:

  1. Create XML view :

     <View
     android:id="@+id/timer"
     android:layout_width="match_parent"
     android:layout_height="match_parent"/>
    
  2. Create and configure Custom Drawable class (as I described above). Don't forget to setup Paints for lines. Here paint for progress line:

    mPaintProgress = new Paint();
    mPaintProgress.setAntiAlias(true);
    mPaintProgress.setStyle(Paint.Style.STROKE);
    mPaintProgress.setStrokeWidth(widthProgress);
    mPaintProgress.setStrokeCap(Paint.Cap.ROUND);
    mPaintProgress.setColor(colorThatYouWant);
    

Same for backgroung paint (set width little more if you want)

  1. In drawable class create method for updating (Step calculation described above)

    public void update() {
        mSweepAngle += mStep;
        invalidateSelf();
    }
    
  2. Set this drawable class to YourTimerView (I did it in runtime) - view with @+id/timer from xml above:

    OurSuperDrawableClass superDrawable = new OurSuperDrawableClass(); YourTimerView.setBackgroundDrawable(superDrawable);

  3. Create background thread with runnable and update view:

    YourTimerView.post(new Runnable() {
        @Override
        public void run() {
            // update progress view
            superDrawable.update();
        }
    });
    

Thats it ! Enjoy your cool progress bar. Here screenshot of result if you're too bored of this amount of text.enter image description here

Is there a label/goto in Python?

For a forward Goto, you could just add:

while True:
  if some condition:
    break
  #... extra code
  break # force code to exit. Needed at end of while loop
#... continues here

This only helps for simple scenarios though (i.e. nesting these would get you into a mess)

How to initialize a two-dimensional array in Python?

If you use numpy, you can easily create 2d arrays:

import numpy as np

row = 3
col = 5
num = 10
x = np.full((row, col), num)

x

array([[10, 10, 10, 10, 10],
       [10, 10, 10, 10, 10],
       [10, 10, 10, 10, 10]])

Adjust plot title (main) position

We can use title() function with negative line value to bring down the title.

See this example:

plot(1, 1)
title("Title", line = -2)

enter image description here

Expand a div to fill the remaining width

Have a look at the available CSS layout frameworks. I would recommend Simpl or, the slightly more complex, Blueprint framework.

If you are using Simpl (which involves importing just one simpl.css file), you can do this:

<div class="Colum­nOne­Half">Tree</div>
<div class="Colum­nOne­Half">View</div>

, for a 50-50 layout, or :

<div class="Colum­nOne­Quarter">Tree</div>
<div class="Colum­nThreeQuarters">View</div>

, for a 25-75 one.

It's that simple.

Arduino Nano - "avrdude: ser_open():system can't open device "\\.\COM1": the system cannot find the file specified"

Instead of changing the COM port in Device manager, if you're using the Arduino software, I had to set the port in Tools > Port menu.

enter image description here

How to get city name from latitude and longitude coordinates in Google Maps?

try below code hope use full for you:-

CityAsyncTask cst = new CityAsyncTask(HomeScreenUserLocation.this,
                latitude, longitude);
        cst.execute();

        String lo = null;
        try {
            lo = cst.get().toString();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

and AsyncTask

public class CityAsyncTask extends AsyncTask<String, String, String> {
    Activity act;
    double latitude;
    double longitude;

    public CityAsyncTask(Activity act, double latitude, double longitude) {
        // TODO Auto-generated constructor stub
        this.act = act;
        this.latitude = latitude;
        this.longitude = longitude;
    }

    @Override
    protected String doInBackground(String... params) {
        String result = "";
        Geocoder geocoder = new Geocoder(act, Locale.getDefault());
        try {
            List<Address> addresses = geocoder.getFromLocation(latitude,
                    longitude, 1);
            Log.e("Addresses", "-->" + addresses);
            result = addresses.get(0).toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

    }
}

How to get the azure account tenant Id?

In the Azure CLI (I use GNU/Linux):

$ azure login  # add "-e AzureChinaCloud" if you're using Azure China

This will ask you to login via https://aka.ms/devicelogin or https://aka.ms/deviceloginchina

$ azure account show
info:    Executing command account show
data:    Name                        : BizSpark Plus
data:    ID                          : aZZZZZZZ-YYYY-HHHH-GGGG-abcdef569123
data:    State                       : Enabled
data:    Tenant ID                   : 0XXXXXXX-YYYY-HHHH-GGGG-123456789123
data:    Is Default                  : true
data:    Environment                 : AzureCloud
data:    Has Certificate             : No
data:    Has Access Token            : Yes
data:    User name                   : [email protected]
data:    
info:    account show command OK

or simply:

azure account show --json | jq -r '.[0].tenantId'

or the new az:

az account show --subscription a... | jq -r '.tenantId'
az account list | jq -r '.[].tenantId'

I hope it helps

How can I loop through a List<T> and grab each item?

The low level iterator manipulate code:

List<Money> myMoney = new List<Money>
{
    new Money{amount = 10, type = "US"},
    new Money{amount = 20, type = "US"}
};
using (var enumerator = myMoney.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        var element = enumerator.Current;
        Console.WriteLine(element.amount);
    }
}

React - Component Full Screen (with height 100%)

While this may not be the ideal answer but try this:

style={{top:'0', bottom:'0', left:'0', right:'0', position: 'absolute'}}

It keeps the size attached to borders which is not what you want but gives you somewhat same effect.

Find the nth occurrence of substring in a string

This will give you an array of the starting indices for matches to yourstring:

import re
indices = [s.start() for s in re.finditer(':', yourstring)]

Then your nth entry would be:

n = 2
nth_entry = indices[n-1]

Of course you have to be careful with the index bounds. You can get the number of instances of yourstring like this:

num_instances = len(indices)

AttributeError: 'str' object has no attribute 'append'

Why myList[1] is considered a 'str' object?

Because it is a string. What else is 'from form', if not a string? (Actually, strings are sequences too, i.e. they can be indexed, sliced, iterated, etc. as well - but that's part of the str class and doesn't make it a list or something).

mList[1] returns the first item in the list 'from form'

If you mean that myList is 'from form', no it's not!!! The second (indexing starts at 0) element is 'from form'. That's a BIG difference. It's the difference between a house and a person.

Also, myList doesn't have to be a list from your short code sample - it could be anything that accepts 1 as index - a dict with 1 as index, a list, a tuple, most other sequences, etc. But that's irrelevant.

but I cannot append to item 1 in the list myList

Of course not, because it's a string and you can't append to string. String are immutable. You can concatenate (as in, "there's a new object that consists of these two") strings. But you cannot append (as in, "this specific object now has this at the end") to them.

How to run a script at the start up of Ubuntu?

First of all, the easiest way to run things at startup is to add them to the file /etc/rc.local.

Another simple way is to use @reboot in your crontab. Read the cron manpage for details.

However, if you want to do things properly, in addition to adding a script to /etc/init.d you need to tell ubuntu when the script should be run and with what parameters. This is done with the command update-rc.d which creates a symlink from some of the /etc/rc* directories to your script. So, you'd need to do something like:

update-rc.d yourscriptname start 2

However, real init scripts should be able to handle a variety of command line options and otherwise integrate to the startup process. The file /etc/init.d/README has some details and further pointers.

Add two textbox values and display the sum in a third textbox automatically

i didn't find who made elegant answer , that's why let me say :

Array.from(
   document.querySelectorAll('#txt1,#txt2')
).map(e => parseInt(e.value) || 0) // to avoid NaN
.reduce((a, b) => a+b, 0)

_x000D_
_x000D_
window.sum= () => _x000D_
 document.getElementById('result').innerHTML=    _x000D_
   Array.from(_x000D_
     document.querySelectorAll('#txt1,#txt2')_x000D_
   ).map(e=>parseInt(e.value)||0)_x000D_
   .reduce((a,b)=>a+b,0)
_x000D_
<input type="text" id="txt1" onkeyup="sum()"/>_x000D_
<input type="text" id="txt2" onkeyup="sum()"  style="margin-right:10px;"/><span id="result"></span>
_x000D_
_x000D_
_x000D_

Correct way to initialize HashMap and can HashMap hold different value types?

Eclipse is suggesting you to define generic type so that you can have type safety. You can write

Map m = new HashMap();

which does not ensure type safety but following will ensure type safety

Map<Object,Object> = new HashMap<Object,Object>();

The Object can be any type such as String, Integer etc.

Error in spring application context schema

This happen to me after upgrade eclipse version. What works for me was clean the eclipse cache. Go to Window > Preferences > Network Connection > Cache > Remove All.

I hope this works for anyone!

Maven version with a property

The version of the pom.xml should be valid

<groupId>com.amazonaws.lambda</groupId>
<artifactId>lambda</artifactId>
<version>2.2.4 SNAPSHOT</version>
<packaging>jar</packaging>

This version should not be like 2.2.4. etc

How to manage a redirect request after a jQuery Ajax call

in the servlet you should put response.setStatus(response.SC_MOVED_PERMANENTLY); to send the '301' xmlHttp status you need for a redirection...

and in the $.ajax function you should not use the .toString() function..., just

if (xmlHttp.status == 301) { top.location.href = 'xxxx.jsp'; }

the problem is it is not very flexible, you can't decide where you want to redirect..

redirecting through the servlets should be the best way. but i still can not find the right way to do it.

How do I format a number with commas in T-SQL?

SELECT REPLACE(CONVERT(varchar(20), (CAST(9876543 AS money)), 1), '.00', '')

output= 9,876,543

and you can replace 9876543 by your column name.

Best way to represent a fraction in Java?

Well, for one, I'd get rid of the setters and make Fractions immutable.

You'll probably also want methods to add, subtract, etc., and maybe some way to get the representation in various String formats.

EDIT: I'd probably mark the fields as 'final' to signal my intent but I guess it's not a big deal...

Find and replace in file and overwrite file doesn't work, it empties the file

Warning: this is a dangerous method! It abuses the i/o buffers in linux and with specific options of buffering it manages to work on small files. It is an interesting curiosity. But don't use it for a real situation!

Besides the -i option of sed you can use the tee utility.

From man:

tee - read from standard input and write to standard output and files

So, the solution would be:

sed s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g index.html | tee | tee index.html

-- here the tee is repeated to make sure that the pipeline is buffered. Then all commands in the pipeline are blocked until they get some input to work on. Each command in the pipeline starts when the upstream commands have written 1 buffer of bytes (the size is defined somewhere) to the input of the command. So the last command tee index.html, which opens the file for writing and therefore empties it, runs after the upstream pipeline has finished and the output is in the buffer within the pipeline.

Most likely the following won't work:

sed s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g index.html | tee index.html

-- it will run both commands of the pipeline at the same time without any blocking. (Without blocking the pipeline should pass the bytes line by line instead of buffer by buffer. Same as when you run cat | sed s/bar/GGG/. Without blocking it's more interactive and usually pipelines of just 2 commands run without buffering and blocking. Longer pipelines are buffered.) The tee index.html will open the file for writing and it will be emptied. However, if you turn the buffering always on, the second version will work too.

How do I make an attributed string using Swift?

enter image description here

This answer has been updated for Swift 4.2.

Quick Reference

The general form for making and setting an attributed string is like this. You can find other common options below.

// create attributed string
let myString = "Swift Attributed String"
let myAttribute = [ NSAttributedString.Key.foregroundColor: UIColor.blue ]
let myAttrString = NSAttributedString(string: myString, attributes: myAttribute) 

// set attributed text on a UILabel
myLabel.attributedText = myAttrString

Text Color

let myAttribute = [ NSAttributedString.Key.foregroundColor: UIColor.blue ]

Background Color

let myAttribute = [ NSAttributedString.Key.backgroundColor: UIColor.yellow ]

Font

let myAttribute = [ NSAttributedString.Key.font: UIFont(name: "Chalkduster", size: 18.0)! ]

enter image description here

let myAttribute = [ NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue ]

enter image description here

let myShadow = NSShadow()
myShadow.shadowBlurRadius = 3
myShadow.shadowOffset = CGSize(width: 3, height: 3)
myShadow.shadowColor = UIColor.gray

let myAttribute = [ NSAttributedString.Key.shadow: myShadow ]

The rest of this post gives more detail for those who are interested.


Attributes

String attributes are just a dictionary in the form of [NSAttributedString.Key: Any], where NSAttributedString.Key is the key name of the attribute and Any is the value of some Type. The value could be a font, a color, an integer, or something else. There are many standard attributes in Swift that have already been predefined. For example:

  • key name: NSAttributedString.Key.font, value: a UIFont
  • key name: NSAttributedString.Key.foregroundColor, value: a UIColor
  • key name: NSAttributedString.Key.link, value: an NSURL or NSString

There are many others. See this link for more. You can even make your own custom attributes like:

  • key name: NSAttributedString.Key.myName, value: some Type.
    if you make an extension:

    extension NSAttributedString.Key {
        static let myName = NSAttributedString.Key(rawValue: "myCustomAttributeKey")
    }
    

Creating attributes in Swift

You can declare attributes just like declaring any other dictionary.

// single attributes declared one at a time
let singleAttribute1 = [ NSAttributedString.Key.foregroundColor: UIColor.green ]
let singleAttribute2 = [ NSAttributedString.Key.backgroundColor: UIColor.yellow ]
let singleAttribute3 = [ NSAttributedString.Key.underlineStyle: NSUnderlineStyle.double.rawValue ]

// multiple attributes declared at once
let multipleAttributes: [NSAttributedString.Key : Any] = [
    NSAttributedString.Key.foregroundColor: UIColor.green,
    NSAttributedString.Key.backgroundColor: UIColor.yellow,
    NSAttributedString.Key.underlineStyle: NSUnderlineStyle.double.rawValue ]

// custom attribute
let customAttribute = [ NSAttributedString.Key.myName: "Some value" ]

Note the rawValue that was needed for the underline style value.

Because attributes are just Dictionaries, you can also create them by making an empty Dictionary and then adding key-value pairs to it. If the value will contain multiple types, then you have to use Any as the type. Here is the multipleAttributes example from above, recreated in this fashion:

var multipleAttributes = [NSAttributedString.Key : Any]()
multipleAttributes[NSAttributedString.Key.foregroundColor] = UIColor.green
multipleAttributes[NSAttributedString.Key.backgroundColor] = UIColor.yellow
multipleAttributes[NSAttributedString.Key.underlineStyle] = NSUnderlineStyle.double.rawValue

Attributed Strings

Now that you understand attributes, you can make attributed strings.

Initialization

There are a few ways to create attributed strings. If you just need a read-only string you can use NSAttributedString. Here are some ways to initialize it:

// Initialize with a string only
let attrString1 = NSAttributedString(string: "Hello.")

// Initialize with a string and inline attribute(s)
let attrString2 = NSAttributedString(string: "Hello.", attributes: [NSAttributedString.Key.myName: "A value"])

// Initialize with a string and separately declared attribute(s)
let myAttributes1 = [ NSAttributedString.Key.foregroundColor: UIColor.green ]
let attrString3 = NSAttributedString(string: "Hello.", attributes: myAttributes1)

If you will need to change the attributes or the string content later, you should use NSMutableAttributedString. The declarations are very similar:

// Create a blank attributed string
let mutableAttrString1 = NSMutableAttributedString()

// Initialize with a string only
let mutableAttrString2 = NSMutableAttributedString(string: "Hello.")

// Initialize with a string and inline attribute(s)
let mutableAttrString3 = NSMutableAttributedString(string: "Hello.", attributes: [NSAttributedString.Key.myName: "A value"])

// Initialize with a string and separately declared attribute(s)
let myAttributes2 = [ NSAttributedString.Key.foregroundColor: UIColor.green ]
let mutableAttrString4 = NSMutableAttributedString(string: "Hello.", attributes: myAttributes2)

Changing an Attributed String

As an example, let's create the attributed string at the top of this post.

First create an NSMutableAttributedString with a new font attribute.

let myAttribute = [ NSAttributedString.Key.font: UIFont(name: "Chalkduster", size: 18.0)! ]
let myString = NSMutableAttributedString(string: "Swift", attributes: myAttribute )

If you are working along, set the attributed string to a UITextView (or UILabel) like this:

textView.attributedText = myString

You don't use textView.text.

Here is the result:

enter image description here

Then append another attributed string that doesn't have any attributes set. (Notice that even though I used let to declare myString above, I can still modify it because it is an NSMutableAttributedString. This seems rather unSwiftlike to me and I wouldn't be surprised if this changes in the future. Leave me a comment when that happens.)

let attrString = NSAttributedString(string: " Attributed Strings")
myString.append(attrString)

enter image description here

Next we'll just select the "Strings" word, which starts at index 17 and has a length of 7. Notice that this is an NSRange and not a Swift Range. (See this answer for more about Ranges.) The addAttribute method lets us put the attribute key name in the first spot, the attribute value in the second spot, and the range in the third spot.

var myRange = NSRange(location: 17, length: 7) // range starting at location 17 with a lenth of 7: "Strings"
myString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: myRange)

enter image description here

Finally, let's add a background color. For variety, let's use the addAttributes method (note the s). I could add multiple attributes at once with this method, but I will just add one again.

myRange = NSRange(location: 3, length: 17)
let anotherAttribute = [ NSAttributedString.Key.backgroundColor: UIColor.yellow ]
myString.addAttributes(anotherAttribute, range: myRange)

enter image description here

Notice that the attributes are overlapping in some places. Adding an attribute doesn't overwrite an attribute that is already there.

Related

Further Reading

Run Python script at startup in Ubuntu

In similar situations, I've done well by putting something like the following into /etc/rc.local:

cd /path/to/my/script
./my_script.py &
cd -
echo `date +%Y-%b-%d_%H:%M:%S` > /tmp/ran_rc_local  # check that rc.local ran

This has worked on multiple versions of Fedora and on Ubuntu 14.04 LTS, for both python and perl scripts.

Facebook how to check if user has liked page and show content?

There are some changes required to JavaScript code to handle rendering based on user liking or not liking the page mandated by Facebook moving to Auth2.0 authorization.

Change is fairly simple:-

sessions has to be replaced by authResponse and uid by userID

Moreover given the requirement of the code and some issues faced by people(including me) in general with FB.login, use of FB.getLoginStatus is a better alternative. It saves query to FB in case user is logged in and has authenticated your app.

Refer to Response and Sessions Object section for info on how this might save query to FB server. http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/

Issues with FB.login and its fixes using FB.getLoginStatus. http://forum.developers.facebook.net/viewtopic.php?id=70634

Here is the code posted above with changes which worked for me.

$(document).ready(function(){
    FB.getLoginStatus(function(response) {
        if (response.status == 'connected') {
            var user_id = response.authResponse.userID;
            var page_id = "40796308305"; //coca cola
            var fql_query = "SELECT uid FROM page_fan WHERE page_id =" + page_id + " and uid=" + user_id;
            var the_query = FB.Data.query(fql_query);

            the_query.wait(function(rows) {

                if (rows.length == 1 && rows[0].uid == user_id) {
                    $("#container_like").show();

                    //here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.

                } else {
                    $("#container_notlike").show();
                    //and here you could get the content for a non liker in ajax...
                }
            });
        } else {
            // user is not logged in
        }
    });

});

Getting time span between two times in C#?

Another way ( longer ) In VB.net [ Say 2300 Start and 0700 Finish next day ]

If tsStart > tsFinish Then

                            ' Take Hours difference and adjust accordingly
                            tsDifference = New TimeSpan((24 - tsStart.Hours) + tsFinish.Hours, 0, 0)

                            ' Add Minutes to Difference
                            tsDifference = tsDifference.Add(New TimeSpan(0, Math.Abs(tsStart.Minutes - tsFinish.Minutes), 0))


                            ' Add Seonds to Difference
                            tsDifference = tsDifference.Add(New TimeSpan(0, 0, Math.Abs(tsStart.Seconds - tsFinish.Seconds)))

Checking for duplicate strings in JavaScript array

The following code uses a unique-filter (checks if every occurrence of an item is the first occurence) to compare the number of unique items in an array with the total number of items: if both are equal, the array only contains unique elements, otherwise there are some duplicates.

var firstUnique = (value, index, array) => array.indexOf(value) === index;
var numUnique = strArray.filter(firstUnique).length;
var allUnique = strArray.length === numUnique; 

Center text output from Graphics.DrawString()

Through a combination of the suggestions I got, I came up with this:

    private void DrawLetter()
    {
        Graphics g = this.CreateGraphics();

        float width = ((float)this.ClientRectangle.Width);
        float height = ((float)this.ClientRectangle.Width);

        float emSize = height;

        Font font = new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular);

        font = FindBestFitFont(g, letter.ToString(), font, this.ClientRectangle.Size);

        SizeF size = g.MeasureString(letter.ToString(), font);
        g.DrawString(letter, font, new SolidBrush(Color.Black), (width-size.Width)/2, 0);

    }

    private Font FindBestFitFont(Graphics g, String text, Font font, Size proposedSize)
    {
        // Compute actual size, shrink if needed
        while (true)
        {
            SizeF size = g.MeasureString(text, font);

            // It fits, back out
            if (size.Height <= proposedSize.Height &&
                 size.Width <= proposedSize.Width) { return font; }

            // Try a smaller font (90% of old size)
            Font oldFont = font;
            font = new Font(font.Name, (float)(font.Size * .9), font.Style);
            oldFont.Dispose();
        }
    }

So far, this works flawlessly.

The only thing I would change is to move the FindBestFitFont() call to the OnResize() event so that I'm not calling it every time I draw a letter. It only needs to be called when the control size changes. I just included it in the function for completeness.

how to fix EXE4J_JAVA_HOME, No JVM could be found on your system error?

This has to be done during your exe4j configuration. In the fourth step of Exe4j wizard which is Executable Info select> Advanced options select 32-bit or 64-bit. This worked well for me. or else install both JDK tool-kits x64 and x32 in your machine.

How to delete migration files in Rails 3

Run below commands from app's home directory:

  1. rake db:migrate:down VERSION="20140311142212" (here version is the timestamp prepended by rails when migration was created. This action will revert DB changes due to this migration)

  2. Run "rails destroy migration migration_name" (migration_name is the one use chose while creating migration. Remove "timestamp_" from your migration file name to get it)

When do I use path params vs. query params in a RESTful API?

Best practice for RESTful API design is that path params are used to identify a specific resource or resources, while query parameters are used to sort/filter those resources.

Here's an example. Suppose you are implementing RESTful API endpoints for an entity called Car. You would structure your endpoints like this:

GET /cars
GET /cars/:id
POST /cars
PUT /cars/:id
DELETE /cars/:id

This way you are only using path parameters when you are specifying which resource to fetch, but this does not sort/filter the resources in any way.

Now suppose you wanted to add the capability to filter the cars by color in your GET requests. Because color is not a resource (it is a property of a resource), you could add a query parameter that does this. You would add that query parameter to your GET /cars request like this:

GET /cars?color=blue

This endpoint would be implemented so that only blue cars would be returned.

As far as syntax is concerned, your URL names should be all lowercase. If you have an entity name that is generally two words in English, you would use a hyphen to separate the words, not camel case.

Ex. /two-words

C: scanf to array

Use

scanf("%d", &array[0]);

and use == for comparision instead of =

'Incorrect SET Options' Error When Building Database Project

I had the same issue with the filtered index and my inserts and updates were failing. All I did was to change the stored procedure that had the insert and update statement to:

create procedure abc
()
AS
BEGIN
SET NOCOUNT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON 
SET ANSI_WARNINGS ON 
SET ANSI_PADDING ON 
end

How do I load a PHP file into a variable?

Alternatively, you can start output buffering, do an include/require, and then stop buffering. With ob_get_contents(), you can just get the stuff that was outputted by that other PHP file into a variable.

How to add rows dynamically into table layout

You might be better off using a ListView with a CursorAdapter (or SimpleCursorAdapter).

These are built to show rows from a sqlite database and allow refreshing with minimal programming on your part.

Edit - here is a tutorial involving SimpleCursorAdapter and ListView including sample code.

How do I bind the enter key to a function in tkinter?

Try running the following program. You just have to be sure your window has the focus when you hit Return--to ensure that it does, first click the button a couple of times until you see some output, then without clicking anywhere else hit Return.

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")
root.bind('<Return>', func)

def onclick():
    print("You clicked the button")

button = tk.Button(root, text="click me", command=onclick)
button.pack()

root.mainloop()

Then you just have tweak things a little when making both the button click and hitting Return call the same function--because the command function needs to be a function that takes no arguments, whereas the bind function needs to be a function that takes one argument(the event object):

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")

def onclick(event=None):
    print("You clicked the button")

root.bind('<Return>', onclick)

button = tk.Button(root, text="click me", command=onclick)
button.pack()

root.mainloop()

Or, you can just forgo using the button's command argument and instead use bind() to attach the onclick function to the button, which means the function needs to take one argument--just like with Return:

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")

def onclick(event):
    print("You clicked the button")

root.bind('<Return>', onclick)

button = tk.Button(root, text="click me")
button.bind('<Button-1>', onclick)
button.pack()

root.mainloop()

Here it is in a class setting:

import tkinter as tk

class Application(tk.Frame):
    def __init__(self):
        self.root = tk.Tk()
        self.root.geometry("300x200")

        tk.Frame.__init__(self, self.root)
        self.create_widgets()

    def create_widgets(self):
        self.root.bind('<Return>', self.parse)
        self.grid()

        self.submit = tk.Button(self, text="Submit")
        self.submit.bind('<Button-1>', self.parse)
        self.submit.grid()

    def parse(self, event):
        print("You clicked?")

    def start(self):
        self.root.mainloop()


Application().start()

multiple packages in context:component-scan, spring config

For Example you have the package "com.abc" and you have multiple packages inside it, You can use like

@ComponentScan("com.abc")

C++ queue - simple example

std::queue<myclass*> my_queue; will do the job.

See here for more information on this container.

Check if any ancestor has a class using jQuery

if ($elem.parents('.left').length) {

}

How to get active user's UserDetails

Spring Security is intended to work with other non-Spring frameworks, hence it is not tightly integrated with Spring MVC. Spring Security returns the Authentication object from the HttpServletRequest.getUserPrincipal() method by default so that's what you get as the principal. You can obtain your UserDetails object directly from this by using

UserDetails ud = ((Authentication)principal).getPrincipal()

Note also that the object types may vary depending on the authentication mechanism used (you may not get a UsernamePasswordAuthenticationToken, for example) and the Authentication doesn't strictly have to contain a UserDetails. It can be a string or any other type.

If you don't want to call SecurityContextHolder directly, the most elegant approach (which I would follow) is to inject your own custom security context accessor interface which is customized to match your needs and user object types. Create an interface, with the relevant methods, for example:

interface MySecurityAccessor {

    MyUserDetails getCurrentUser();

    // Other methods
}

You can then implement this by accessing the SecurityContextHolder in your standard implementation, thus decoupling your code from Spring Security entirely. Then inject this into the controllers which need access to security information or information on the current user.

The other main benefit is that it is easy to make simple implementations with fixed data for testing, without having to worry about populating thread-locals and so on.

Mapping US zip code to time zone

Also note, that if you happen to be using Yahoo geocoding service you can have timezone information returned to you by setting the correct flag.

http://developer.yahoo.com/geo/placefinder/guide/requests.html#flags-parameter

Converting .NET DateTime to JSON

If you pass a DateTime from a .Net code to a javascript code, C#:

DateTime net_datetime = DateTime.Now;

javascript treats it as a string, like "/Date(1245398693390)/":

You can convert it as fllowing:

// convert the string to date correctly
var d = eval(net_datetime.slice(1, -1))

or:

// convert the string to date correctly
var d = eval("/Date(1245398693390)/".slice(1, -1))

How can I align two divs horizontally?

<html>
<head>
<style type="text/css">
#floatingDivs{float:left;}
</style>
</head>

<body>
<div id="floatingDivs">
    <span>source list</span>
    <select size="10">
        <option />
        <option />
        <option />
    </select>
</div>

<div id="floatingDivs">
    <span>destination list</span>
    <select size="10">
        <option />
        <option />
        <option />
    </select>
</div>

</body>
</html>

Naming conventions for Java methods that return boolean

The convention is to ask a question in the name.

Here are a few examples that can be found in the JDK:

isEmpty()

hasChildren()

That way, the names are read like they would have a question mark on the end.

Is the Collection empty?
Does this Node have children?

And, then, true means yes, and false means no.

Or, you could read it like an assertion:

The Collection is empty.
The node has children

Note:
Sometimes you may want to name a method something like createFreshSnapshot?. Without the question mark, the name implies that the method should be creating a snapshot, instead of checking to see if one is required.

In this case you should rethink what you are actually asking. Something like isSnapshotExpired is a much better name, and conveys what the method will tell you when it is called. Following a pattern like this can also help keep more of your functions pure and without side effects.

If you do a Google Search for isEmpty() in the Java API, you get lots of results.

Search for a string in Enum and return the Enum

var color =  Enum.Parse<Colors>("Green");

Change font-weight of FontAwesome icons?

.star-light::after {
    content: "\f005";
    font-family: "FontAwesome";
    font-size: 3.2rem;
    color: #fff;
    font-weight: 900;
    background-color: red;
}

Self-references in object literals / initializers

if your object is written as a function which returns an object, AND you use ES6 object-attribute 'methods', then it's possible:

const module = (state) => ({
  a: 1,
  oneThing() {
    state.b = state.b + this.a
  },
  anotherThing() {
    this.oneThing();
    state.c = state.b + this.a
  },
});

const store = {b: 10};
const root = module(store);

root.oneThing();
console.log(store);

root.anotherThing();
console.log(store);

console.log(root, Object.keys(root), root.prototype);

What does it mean when the size of a VARCHAR2 in Oracle is declared as 1 byte?

The VARCHAR datatype is synonymous with the VARCHAR2 datatype. To avoid possible changes in behavior, always use the VARCHAR2 datatype to store variable-length character strings.

If your database runs on a single-byte character set (e.g. US7ASCII, WE8MSWIN1252 or WE8ISO8859P1) it does not make any difference whether you use VARCHAR2(x BYTE) or VARCHAR2(x CHAR).

It makes only a difference when your DB runs on multi-byte character set (e.g. AL32UTF8 or AL16UTF16). You can simply see it in this example:

CREATE TABLE my_table (
    VARCHAR2_byte VARCHAR2(1 BYTE), 
    VARCHAR2_char VARCHAR2(1 CHAR)
);

INSERT INTO my_table (VARCHAR2_char) VALUES ('€');
1 row created.

INSERT INTO my_table (VARCHAR2_char) VALUES ('ü');
1 row created.

INSERT INTO my_table (VARCHAR2_byte) VALUES ('€');
INSERT INTO my_table (VARCHAR2_byte) VALUES ('€')
Error at line 10
ORA-12899: value too large for column "MY_TABLE"."VARCHAR2_BYTE" (actual: 3, maximum: 1)

INSERT INTO my_table (VARCHAR2_byte) VALUES ('ü')
Error at line 11
ORA-12899: value too large for column "MY_TABLE"."VARCHAR2_BYTE" (actual: 2, maximum: 1)

VARCHAR2(1 CHAR) means you can store up to 1 character, no matter how many byte it has. In case of Unicode one character may occupy up to 4 bytes.

VARCHAR2(1 BYTE) means you can store a character which occupies max. 1 byte.

If you don't specify either BYTE or CHAR then the default is taken from NLS_LENGTH_SEMANTICS session parameter.

Unless you have Oracle 12c where you can set MAX_STRING_SIZE=EXTENDED the limit is VARCHAR2(4000 CHAR)

However, VARCHAR2(4000 CHAR) does not mean you are guaranteed to store up to 4000 characters. The limit is still 4000 bytes, so in worst case you may store only up to 1000 characters in such field.

See this example ( in UTF-8 occupies 3 bytes):

CREATE TABLE my_table2(VARCHAR2_char VARCHAR2(4000 CHAR));

BEGIN
    INSERT INTO my_table2 VALUES ('€€€€€€€€€€');
    FOR i IN 1..7 LOOP
        UPDATE my_table2 SET VARCHAR2_char = VARCHAR2_char ||VARCHAR2_char;
    END LOOP;
END;
/

SELECT LENGTHB(VARCHAR2_char) , LENGTHC(VARCHAR2_char) FROM my_table2;

LENGTHB(VARCHAR2_CHAR) LENGTHC(VARCHAR2_CHAR)
---------------------- ----------------------
                  3840                   1280
1 row selected.


UPDATE my_table2 SET VARCHAR2_char = VARCHAR2_char ||VARCHAR2_char;

UPDATE my_table2 SET VARCHAR2_char = VARCHAR2_char ||VARCHAR2_char
Error at line 1
ORA-01489: result of string concatenation is too long

See also Examples and limits of BYTE and CHAR semantics usage (NLS_LENGTH_SEMANTICS) (Doc ID 144808.1)

SQL Server converting varbinary to string

I looked everywhere for an answer and finally this worked for me:

SELECT Lower(Substring(MASTER.dbo.Fn_varbintohexstr(0x21232F297A57A5A743894A0E4A801FC3), 3, 8000))

Outputs to (string):

21232f297a57a5a743894a0e4a801fc3

You can use it in your WHERE or JOIN conditions as well in case you want to compare/match varbinary records with strings

Remove the legend on a matplotlib figure

According to the information from @naitsirhc, I wanted to find the official API documentation. Here are my finding and some sample code.

  1. I created a matplotlib.Axes object by seaborn.scatterplot().
  2. The ax.get_legend() will return a matplotlib.legned.Legend instance.
  3. Finally, you call .remove() function to remove the legend from your plot.
ax = sns.scatterplot(......)
_lg = ax.get_legend()
_lg.remove()

If you check the matplotlib.legned.Legend API document, you won't see the .remove() function.

The reason is that the matplotlib.legned.Legend inherited the matplotlib.artist.Artist. Therefore, when you call ax.get_legend().remove() that basically call matplotlib.artist.Artist.remove().

In the end, you could even simplify the code into two lines.

ax = sns.scatterplot(......)
ax.get_legend().remove()

How can you program if you're blind?

I think that this would work well in extreme programming using the pair programming principle. If you're making software for blind people, who better to make it then someone who would literally be in touch with the business requirements, so I don't think it's very far fetched at all.

As for writing code, well unless there was some kind of feedback I think a person may struggle with syntax. Audio feedback may help to a point though.

How can I detect keydown or keypress event in angular.js?

JavaScript code using ng-controller:

$scope.checkkey = function (event) {
  alert(event.keyCode);  //this will show the ASCII value of the key pressed

}

In HTML:

<input type="text" ng-keypress="checkkey($event)" />

You can now place your checks and other conditions using the keyCode method.

Cordova : Requirements check failed for JDK 1.8 or greater

Sometimes changing the path and java-home does not work. You need to add

C:\Users\[your user]\AppData\Local\Android\Sdk\platform-tools
C:\Users\[your user]\AppData\Local\Android\Sdk\tools

to the environmental variable path as well.

Java int to String - Integer.toString(i) vs new Integer(i).toString()

Here Integer.toString calls the static method in the class Integer. It does not require the object to call.

If you call new Integer(i) you first create an instance of type Integer, which is a full Java object encapsulating the value of your int i. Then you call the toString method on it to ask it to return a string representation of itself.

Create PostgreSQL ROLE (user) if it doesn't exist

Here is a generic solution using plpgsql:

CREATE OR REPLACE FUNCTION create_role_if_not_exists(rolename NAME) RETURNS TEXT AS
$$
BEGIN
    IF NOT EXISTS (SELECT * FROM pg_roles WHERE rolname = rolename) THEN
        EXECUTE format('CREATE ROLE %I', rolename);
        RETURN 'CREATE ROLE';
    ELSE
        RETURN format('ROLE ''%I'' ALREADY EXISTS', rolename);
    END IF;
END;
$$
LANGUAGE plpgsql;

Usage:

posgres=# SELECT create_role_if_not_exists('ri');
 create_role_if_not_exists 
---------------------------
 CREATE ROLE
(1 row)
posgres=# SELECT create_role_if_not_exists('ri');
 create_role_if_not_exists 
---------------------------
 ROLE 'ri' ALREADY EXISTS
(1 row)

Adb install failure: INSTALL_CANCELED_BY_USER

In addition, any app lock password should be removed by SETTINGS>APP LOCK ,enter the set password and remove the lock. This worked for me on REDMI 4A

DIV :after - add content after DIV

Position your <div> absolutely at the bottom and don't forget to give div.A a position: relative - http://jsfiddle.net/TTaMx/

    .A {
        position: relative;
        margin: 40px 0;
        height: 40px;
        width: 200px;
        background: #eee;
    }

    .A:after {
        content: " ";
        display: block;
        background: #c00;
        height: 29px;
        width: 100%;

        position: absolute;
        bottom: -29px;
    }?

Get current language in CultureInfo

To get the 2 chars ISO 639-1 language identifier use:

System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

Encapsulation vs Abstraction?

Encapsulation protects to collapse the internal behaviour of object/instance from external entity. So, a control should be provided to confirm that the data which is being supplied is not going to harm the internal system of instance/object to survive its existance.

Good example, Divider is a class which has two instance variable dividend and divisor and a method getDividedValue.

Can you please think, if the divisor is set to 0 then internal system/behaviour (getDivided ) will break.

So, the object internal behaviour could be protected by throwing exception through a method.

How to host material icons offline?

Method 2. Self hosting Developer Guide

Download the latest release from github (assets: zip file), unzip, and copy the font folder, containing the material design icons files, into your local project -- https://github.com/google/material-design-icons/releases

You only need to use the font folder from the archive: it contains the icons fonts in the different formats (for multiple browser support) and boilerplate css.

  • Replace the source in the url attribute of @font-face, with the relative path to the iconfont folder in your local project, (where the font files are located) eg. url("iconfont/MaterialIcons-Regular.ttf")
@font-face {
   font-family: 'Material Icons';
   font-style: normal;
   font-weight: 400;
   src: url(iconfont/MaterialIcons-Regular.eot); /* For IE6-8 */
   src: local('Material Icons'),
        local('MaterialIcons-Regular'),
        url(iconfont/MaterialIcons-Regular.woff2) format('woff2'),
        url(iconfont/MaterialIcons-Regular.woff) format('woff'),
        url(iconfont/MaterialIcons-Regular.ttf) format('truetype');
}

.material-icons {
  font-family: 'Material Icons';
  font-weight: normal;
  font-style: normal;
  font-size: 24px;  /* Preferred icon size */
  display: inline-block;
  line-height: 1;
  text-transform: none;
  letter-spacing: normal;
  word-wrap: normal;
  white-space: nowrap;
  direction: ltr;

  /* Support for all WebKit browsers. */
  -webkit-font-smoothing: antialiased;
  /* Support for Safari and Chrome. */
  text-rendering: optimizeLegibility;

  /* Support for Firefox. */
  -moz-osx-font-smoothing: grayscale;

  /* Support for IE. */
  font-feature-settings: 'liga';
}

<i class="material-icons">face</i>

NPM / Bower Packages

Google officially has a Bower and NPM dependency option -- follow Material Icons Guide 1

Using bower : bower install material-design-icons --save

Using NPM : npm install material-design-icons --save

Material Icons : Alternatively look into Material design icon font and CSS framework for self hosting the icons, from @marella's https://marella.me/material-icons/


Note

It seems google has the project on low maintenance mode. The last release was, at time of writing, 3 years ago!

There are several issues on GitHub regarding this, but I'd like to refer to @cyberalien comment on the issue Is this project actively maintained? #951 where it refers several community projects that forked and continue maintaining material icons.


Read only the first line of a file?

This should do it:

f = open('myfile.txt')
first = f.readline()

How to jump to a particular line in a huge text file?

If you don't want to read the entire file in memory .. you may need to come up with some format other than plain text.

of course it all depends on what you're trying to do, and how often you will jump across the file.

For instance, if you're gonna be jumping to lines many times in the same file, and you know that the file does not change while working with it, you can do this:
First, pass through the whole file, and record the "seek-location" of some key-line-numbers (such as, ever 1000 lines),
Then if you want line 12005, jump to the position of 12000 (which you've recorded) then read 5 lines and you'll know you're in line 12005 and so on

How to delete session cookie in Postman?

new version of postman app has the ability to do that programmatically in pre-request or tests scripts since 2019/08

see more examples here: Delete cookies programmatically · Issue #3312 · postmanlabs/postman-app-support

clear all cookies

const jar = pm.cookies.jar();

jar.clear(pm.request.url, function (error) {
  // error - <Error>
});

get all cookies

const jar = pm.cookies.jar();

jar.getAll('http://example.com', function (error, cookies) {
  // error - <Error>
  // cookies - <PostmanCookieList>
  // PostmanCookieList: https://www.postmanlabs.com/postman-collection/CookieList.html
});

get specific cookie

const jar = pm.cookies.jar();

jar.get('http://example.com', 'token', function (error, value) {
  // error - <Error>
  // value - <String>
});

Remove "whitespace" between div element

use line-height: 0px;

WORKING DEMO

The CSS Code:

div{line-height:0;}

This will affect generically to all your Div's. If you want your existing parent div only to have no spacing, you can apply the same into it.

Quickest way to convert a base 10 number to any base in .NET?

Very late to the party on this one, but I wrote the following helper class recently for a project at work. It was designed to convert short strings into numbers and back again (a simplistic perfect hash function), however it will also perform number conversion between arbitrary bases. The Base10ToString method implementation answers the question that was originally posted.

The shouldSupportRoundTripping flag passed to the class constructor is needed to prevent the loss of leading digits from the number string during conversion to base-10 and back again (crucial, given my requirements!). Most of the time the loss of leading 0s from the number string probably won't be an issue.

Anyway, here's the code:

using System;
using System.Collections.Generic;
using System.Linq;

namespace StackOverflow
{
    /// <summary>
    /// Contains methods used to convert numbers between base-10 and another numbering system.
    /// </summary>
    /// <remarks>
    /// <para>
    /// This conversion class makes use of a set of characters that represent the digits used by the target
    /// numbering system. For example, binary would use the digits 0 and 1, whereas hex would use the digits
    /// 0 through 9 plus A through F. The digits do not have to be numerals.
    /// </para>
    /// <para>
    /// The first digit in the sequence has special significance. If the number passed to the
    /// <see cref="StringToBase10"/> method has leading digits that match the first digit, then those leading
    /// digits will effectively be 'lost' during conversion. Much of the time this won't matter. For example,
    /// "0F" hex will be converted to 15 decimal, but when converted back to hex it will become simply "F",
    /// losing the leading "0". However, if the set of digits was A through Z, and the number "ABC" was
    /// converted to base-10 and back again, then the leading "A" would be lost. The <see cref="System.Boolean"/>
    /// flag passed to the constructor allows 'round-tripping' behaviour to be supported, which will prevent
    /// leading digits from being lost during conversion.
    /// </para>
    /// <para>
    /// Note that numeric overflow is probable when using longer strings and larger digit sets.
    /// </para>
    /// </remarks>
    public class Base10Converter
    {
        const char NullDigit = '\0';

        public Base10Converter(string digits, bool shouldSupportRoundTripping = false)
            : this(digits.ToCharArray(), shouldSupportRoundTripping)
        {
        }

        public Base10Converter(IEnumerable<char> digits, bool shouldSupportRoundTripping = false)
        {
            if (digits == null)
            {
                throw new ArgumentNullException("digits");
            }

            if (digits.Count() == 0)
            {
                throw new ArgumentException(
                    message: "The sequence is empty.",
                    paramName: "digits"
                    );
            }

            if (!digits.Distinct().SequenceEqual(digits))
            {
                throw new ArgumentException(
                    message: "There are duplicate characters in the sequence.",
                    paramName: "digits"
                    );
            }

            if (shouldSupportRoundTripping)
            {
                digits = (new[] { NullDigit }).Concat(digits);
            }

            _digitToIndexMap =
                digits
                .Select((digit, index) => new { digit, index })
                .ToDictionary(keySelector: x => x.digit, elementSelector: x => x.index);

            _radix = _digitToIndexMap.Count;

            _indexToDigitMap =
                _digitToIndexMap
                .ToDictionary(keySelector: x => x.Value, elementSelector: x => x.Key);
        }

        readonly Dictionary<char, int> _digitToIndexMap;
        readonly Dictionary<int, char> _indexToDigitMap;
        readonly int _radix;

        public long StringToBase10(string number)
        {
            Func<char, int, long> selector =
                (c, i) =>
                {
                    int power = number.Length - i - 1;

                    int digitIndex;
                    if (!_digitToIndexMap.TryGetValue(c, out digitIndex))
                    {
                        throw new ArgumentException(
                            message: String.Format("Number contains an invalid digit '{0}' at position {1}.", c, i),
                            paramName: "number"
                            );
                    }

                    return Convert.ToInt64(digitIndex * Math.Pow(_radix, power));
                };

            return number.Select(selector).Sum();
        }

        public string Base10ToString(long number)
        {
            if (number < 0)
            {
                throw new ArgumentOutOfRangeException(
                    message: "Value cannot be negative.",
                    paramName: "number"
                    );
            }

            string text = string.Empty;

            long remainder;
            do
            {
                number = Math.DivRem(number, _radix, out remainder);

                char digit;
                if (!_indexToDigitMap.TryGetValue((int) remainder, out digit) || digit == NullDigit)
                {
                    throw new ArgumentException(
                        message: "Value cannot be converted given the set of digits used by this converter.",
                        paramName: "number"
                        );
                }

                text = digit + text;
            }
            while (number > 0);

            return text;
        }
    }
}

This can also be subclassed to derive custom number converters:

namespace StackOverflow
{
    public sealed class BinaryNumberConverter : Base10Converter
    {
        public BinaryNumberConverter()
            : base(digits: "01", shouldSupportRoundTripping: false)
        {
        }
    }

    public sealed class HexNumberConverter : Base10Converter
    {
        public HexNumberConverter()
            : base(digits: "0123456789ABCDEF", shouldSupportRoundTripping: false)
        {
        }
    }
}

And the code would be used like this:

using System.Diagnostics;

namespace StackOverflow
{
    class Program
    {
        static void Main(string[] args)
        {
            {
                var converter = new Base10Converter(
                    digits: "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz",
                    shouldSupportRoundTripping: true
                    );

                long number = converter.StringToBase10("Atoz");
                string text = converter.Base10ToString(number);
                Debug.Assert(text == "Atoz");
            }

            {
                var converter = new HexNumberConverter();

                string text = converter.Base10ToString(255);
                long number = converter.StringToBase10(text);
                Debug.Assert(number == 255);
            }
        }
    }
}

PHP display image BLOB from MySQL

Try Like this.

For Inserting into DB

$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$image = addslashes(file_get_contents($_FILES['images']['tmp_name']));
//you keep your column name setting for insertion. I keep image type Blob.
$query = "INSERT INTO products (id,image) VALUES('','$image')";  
$qry = mysqli_query($db, $query);

For Accessing image From Blob

$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$sql = "SELECT * FROM products WHERE id = $id";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image'] ).'"/>';

Hope It will help you.

Thanks.

Web Service vs WCF Service

This answer is based on an article that no longer exists:

Summary of article:

"Basically, WCF is a service layer that allows you to build applications that can communicate using a variety of communication mechanisms. With it, you can communicate using Peer to Peer, Named Pipes, Web Services and so on.

You can’t compare them because WCF is a framework for building interoperable applications. If you like, you can think of it as a SOA enabler. What does this mean?

Well, WCF conforms to something known as ABC, where A is the address of the service that you want to communicate with, B stands for the binding and C stands for the contract. This is important because it is possible to change the binding without necessarily changing the code. The contract is much more powerful because it forces the separation of the contract from the implementation. This means that the contract is defined in an interface, and there is a concrete implementation which is bound to by the consumer using the same idea of the contract. The datamodel is abstracted out."

... later ...

"should use WCF when we need to communicate with other communication technologies (e,.g. Peer to Peer, Named Pipes) rather than Web Service"

mongo - couldn't connect to server 127.0.0.1:27017

You can try with following command:

sudo service mongod start

Multiple input in JOptionPane.showInputDialog

Yes. You know that you can put any Object into the Object parameter of most JOptionPane.showXXX methods, and often that Object happens to be a JPanel.

In your situation, perhaps you could use a JPanel that has several JTextFields in it:

import javax.swing.*;

public class JOptionPaneMultiInput {
   public static void main(String[] args) {
      JTextField xField = new JTextField(5);
      JTextField yField = new JTextField(5);

      JPanel myPanel = new JPanel();
      myPanel.add(new JLabel("x:"));
      myPanel.add(xField);
      myPanel.add(Box.createHorizontalStrut(15)); // a spacer
      myPanel.add(new JLabel("y:"));
      myPanel.add(yField);

      int result = JOptionPane.showConfirmDialog(null, myPanel, 
               "Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION);
      if (result == JOptionPane.OK_OPTION) {
         System.out.println("x value: " + xField.getText());
         System.out.println("y value: " + yField.getText());
      }
   }
}

Carriage return in C?

Step-by-step:

[newline]ab

ab

[backspace]si

asi

[carriage-return]ha

hai

Carriage return, does not cause a newline. Under some circumstances a single CR or LF may be translated to a CR-LF pair. This is console and/or stream dependent.

addEventListener vs onclick

element.onclick = function() { /* do stuff */ }

element.addEventListener('click', function(){ /* do stuff */ },false);

They apparently do the same thing: listen for the click event and execute a callback function. Nevertheless, they’re not equivalent. If you ever need to choose between the two, this could help you to figure out which one is the best for you.

The main difference is that onclick is just a property, and like all object properties, if you write on more than once, it will be overwritten. With addEventListener() instead, we can simply bind an event handler to the element, and we can call it each time we need it without being worried of any overwritten properties. Example is shown here,

Try it: https://jsfiddle.net/fjets5z4/5/

In first place I was tempted to keep using onclick, because it’s shorter and looks simpler… and in fact it is. But I don’t recommend using it anymore. It’s just like using inline JavaScript. Using something like – that’s inline JavaScript – is highly discouraged nowadays (inline CSS is discouraged too, but that’s another topic).

However, the addEventListener() function, despite it’s the standard, just doesn’t work in old browsers (Internet Explorer below version 9), and this is another big difference. If you need to support these ancient browsers, you should follow the onclick way. But you could also use jQuery (or one of its alternatives): it basically simplifies your work and reduces the differences between browsers, therefore can save you a lot of time.

var clickEvent = document.getElementByID("onclick-eg");
var EventListener = document.getElementByID("addEventListener-eg");

clickEvent.onclick = function(){
    window.alert("1 is not called")
}
clickEvent.onclick = function(){
    window.alert("1 is not called, 2 is called")
}

EventListener.addEventListener("click",function(){
    window.alert("1 is called")
})
EventListener.addEventListener("click",function(){
    window.alert("2 is also called")
})

Find first element by predicate

In addition to Alexis C's answer, If you are working with an array list, in which you are not sure whether the element you are searching for exists, use this.

Integer a = list.stream()
                .peek(num -> System.out.println("will filter " + num))
                .filter(x -> x > 5)
                .findFirst()
                .orElse(null);

Then you could simply check whether a is null.

Is there a regular expression to detect a valid regular expression?

/
^                                             # start of string
(                                             # first group start
  (?:
    (?:[^?+*{}()[\]\\|]+                      # literals and ^, $
     | \\.                                    # escaped characters
     | \[ (?: \^?\\. | \^[^\\] | [^\\^] )     # character classes
          (?: [^\]\\]+ | \\. )* \]
     | \( (?:\?[:=!]|\?<[=!]|\?>)? (?1)?? \)  # parenthesis, with recursive content
     | \(\? (?:R|[+-]?\d+) \)                 # recursive matching
     )
    (?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )?   # quantifiers
  | \|                                        # alternative
  )*                                          # repeat content
)                                             # end first group
$                                             # end of string
/

This is a recursive regex, and is not supported by many regex engines. PCRE based ones should support it.

Without whitespace and comments:

/^((?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>)?(?1)??\)|\(\?(?:R|[+-]?\d+)\))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*)$/

.NET does not support recursion directly. (The (?1) and (?R) constructs.) The recursion would have to be converted to counting balanced groups:

^                                         # start of string
(?:
  (?: [^?+*{}()[\]\\|]+                   # literals and ^, $
   | \\.                                  # escaped characters
   | \[ (?: \^?\\. | \^[^\\] | [^\\^] )   # character classes
        (?: [^\]\\]+ | \\. )* \]
   | \( (?:\?[:=!]
         | \?<[=!]
         | \?>
         | \?<[^\W\d]\w*>
         | \?'[^\W\d]\w*'
         )?                               # opening of group
     (?<N>)                               #   increment counter
   | \)                                   # closing of group
     (?<-N>)                              #   decrement counter
   )
  (?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )? # quantifiers
| \|                                      # alternative
)*                                        # repeat content
$                                         # end of string
(?(N)(?!))                                # fail if counter is non-zero.

Compacted:

^(?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>|\?<[^\W\d]\w*>|\?'[^\W\d]\w*')?(?<N>)|\)(?<-N>))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*$(?(N)(?!))

From the comments:

Will this validate substitutions and translations?

It will validate just the regex part of substitutions and translations. s/<this part>/.../

It is not theoretically possible to match all valid regex grammars with a regex.

It is possible if the regex engine supports recursion, such as PCRE, but that can't really be called regular expressions any more.

Indeed, a "recursive regular expression" is not a regular expression. But this an often-accepted extension to regex engines... Ironically, this extended regex doesn't match extended regexes.

"In theory, theory and practice are the same. In practice, they're not." Almost everyone who knows regular expressions knows that regular expressions does not support recursion. But PCRE and most other implementations support much more than basic regular expressions.

using this with shell script in the grep command , it shows me some error.. grep: Invalid content of {} . I am making a script that could grep a code base to find all the files that contain regular expressions

This pattern exploits an extension called recursive regular expressions. This is not supported by the POSIX flavor of regex. You could try with the -P switch, to enable the PCRE regex flavor.

Regex itself "is not a regular language and hence cannot be parsed by regular expression..."

This is true for classical regular expressions. Some modern implementations allow recursion, which makes it into a Context Free language, although it is somewhat verbose for this task.

I see where you're matching []()/\. and other special regex characters. Where are you allowing non-special characters? It seems like this will match ^(?:[\.]+)$, but not ^abcdefg$. That's a valid regex.

[^?+*{}()[\]\\|] will match any single character, not part of any of the other constructs. This includes both literal (a - z), and certain special characters (^, $, .).

How to get current url in view in asp.net core 1.0

This was apparently always possible in .net core 1.0 with Microsoft.AspNetCore.Http.Extensions, which adds extension to HttpRequest to get full URL; GetEncodedUrl.

e.g. from razor view:

@using Microsoft.AspNetCore.Http.Extensions
...
<a href="@Context.Request.GetEncodedUrl()">Link to myself</a>

Since 2.0, also have relative path and query GetEncodedPathAndQuery.

Enable ASP.NET ASMX web service for HTTP POST / GET requests

Try to declare UseHttpGet over your method.

[ScriptMethod(UseHttpGet = true)]
public string HelloWorld()
{
    return "Hello World";
}

How to handle floats and decimal separators with html5 input type number

When you call $("#my_input").val(); it returns as string variable. So use parseFloat and parseIntfor converting. When you use parseFloat your desktop or phone ITSELF understands the meaning of variable.

And plus you can convert a float to string by using toFixed which has an argument the count of digits as below:

var i = 0.011;
var ss = i.toFixed(2); //It returns 0.01

Add MIME mapping in web.config for IIS Express

I'm not using IIS Express but developing against my Local Full IIS 7.

So if anyone else get's here trying to do that, I had to add the mime type for woff via IIS Manager

Mime Types >> Click Add link on right and then enter Extension: .woff MIME type: application/font-woff

Specifying row names when reading in a file

If you used read.table() (or one of it's ilk, e.g. read.csv()) then the easy fix is to change the call to:

read.table(file = "foo.txt", row.names = 1, ....)

where .... are the other arguments you needed/used. The row.names argument takes the column number of the data file from which to take the row names. It need not be the first column. See ?read.table for details/info.

If you already have the data in R and can't be bothered to re-read it, or it came from another route, just set the rownames attribute and remove the first variable from the object (assuming obj is your object)

rownames(obj) <- obj[, 1]  ## set rownames
obj <- obj[, -1]           ## remove the first variable

Why should I use core.autocrlf=true in Git?

For me.

Edit .gitattributes file.

add

*.dll binary

Then everything goes well.

How to do select from where x is equal to multiple values?

You can try using parentheses around the OR expressions to make sure your query is interpreted correctly, or more concisely, use IN:

SELECT ads.*, location.county 
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1 
AND ads.type = 13
AND ads.county_id IN (2,5,7,9)