Programs & Examples On #Sharepoint discussion board

0

How to save the output of a console.log(object) to a file?

Right click on object and saving was not available for me.

The working solution for me is given below

Log as pretty string shown in this answer

console.log('jsonListBeauty', JSON.stringify(jsonList, null, 2));

in Chrome DevTools, Log shows as below

saveJsonlog

Just press Copy, It will be copied to clipboard with desired spacing level

Paste it on your favorite text editor and save it


image took on 15/02/2021, Google Chrome Version 88.0.4324.150

How to view the list of compile errors in IntelliJ?

I think this comes closest to what you wish:

(From IntelliJ IDEA Q&A for Eclipse Users):

enter image description here

The above can be combined with a recently introduced option in Compiler settings to get a view very similar to that of Eclipse.

Things to do:

  1. Switch to 'Problems' view in the Project pane:

    enter image description here

  2. Enable the setting to compile the project automatically :

    enter image description here

  3. Finally, look at the Problems view:

    enter image description here

Here is a comparison of what the same project (with a compilation error) looks like in Intellij IDEA 13.xx and Eclipse Kepler:

enter image description here

enter image description here

Relevant Links: The maven project shown above : https://github.com/ajorpheus/CompileTimeErrors
FAQ For 'Eclipse Mode' / 'Automatically Compile' a project : http://devnet.jetbrains.com/docs/DOC-1122

docker container ssl certificates

I am trying to do something similar to this. As commented above, I think you would want to build a new image with a custom Dockerfile (using the image you pulled as a base image), ADD your certificate, then RUN update-ca-certificates. This way you will have a consistent state each time you start a container from this new image.

# Dockerfile
FROM some-base-image:0.1
ADD you_certificate.crt:/container/cert/path
RUN update-ca-certificates

Let's say a docker build against that Dockerfile produced IMAGE_ID. On the next docker run -d [any other options] IMAGE_ID, the container started by that command will have your certificate info. Simple and reproducible.

How to check if a subclass is an instance of a class at runtime?

It's the other way around: B.class.isInstance(view)

How to get day of the month?

You could start by reading the documentation for Date. Then you realize that Date’s methods are all deprecated and turn to Calender instead.

Calendar now = Calendar.getInstance();
System.out.println(now.get(Calendar.DAY_OF_MONTH));

How to remove RVM (Ruby Version Manager) from my system

In addition to @tadman's answer I removed the wrappers in /usr/local/bin as well as the file /etc/profile.d/rvm.

The wrappers include:

erb
gem
irb
rake
rdoc
ri
ruby
testrb

How to return the current timestamp with Moment.js?

Try to use it this way:

let current_time = moment().format("HH:mm")

How can I display a modal dialog in Redux that performs asynchronous actions?

A lot of good solutions and valuable commentaries by known experts from JS community on the topic could be found here. It could be an indicator that it's not that trivial problem as it may seem. I think this is why it could be the source of doubts and uncertainty on the issue.

Fundamental problem here is that in React you're only allowed to mount component to its parent, which is not always the desired behavior. But how to address this issue?

I propose the solution, addressed to fix this issue. More detailed problem definition, src and examples can be found here: https://github.com/fckt/react-layer-stack#rationale

Rationale

react/react-dom comes comes with 2 basic assumptions/ideas:

  • every UI is hierarchical naturally. This why we have the idea of components which wrap each other
  • react-dom mounts (physically) child component to its parent DOM node by default

The problem is that sometimes the second property isn't what you want in your case. Sometimes you want to mount your component into different physical DOM node and hold logical connection between parent and child at the same time.

Canonical example is Tooltip-like component: at some point of development process you could find that you need to add some description for your UI element: it'll render in fixed layer and should know its coordinates (which are that UI element coord or mouse coords) and at the same time it needs information whether it needs to be shown right now or not, its content and some context from parent components. This example shows that sometimes logical hierarchy isn't match with the physical DOM hierarchy.

Take a look at https://github.com/fckt/react-layer-stack/blob/master/README.md#real-world-usage-example to see the concrete example which is answer to your question:

import { Layer, LayerContext } from 'react-layer-stack'
// ... for each `object` in array of `objects`
  const modalId = 'DeleteObjectConfirmation' + objects[rowIndex].id
  return (
    <Cell {...props}>
        // the layer definition. The content will show up in the LayerStackMountPoint when `show(modalId)` be fired in LayerContext
        <Layer use={[objects[rowIndex], rowIndex]} id={modalId}> {({
            hideMe, // alias for `hide(modalId)`
            index } // useful to know to set zIndex, for example
            , e) => // access to the arguments (click event data in this example)
          <Modal onClick={ hideMe } zIndex={(index + 1) * 1000}>
            <ConfirmationDialog
              title={ 'Delete' }
              message={ "You're about to delete to " + '"' + objects[rowIndex].name + '"' }
              confirmButton={ <Button type="primary">DELETE</Button> }
              onConfirm={ this.handleDeleteObject.bind(this, objects[rowIndex].name, hideMe) } // hide after confirmation
              close={ hideMe } />
          </Modal> }
        </Layer>

        // this is the toggle for Layer with `id === modalId` can be defined everywhere in the components tree
        <LayerContext id={ modalId }> {({showMe}) => // showMe is alias for `show(modalId)`
          <div style={styles.iconOverlay} onClick={ (e) => showMe(e) }> // additional arguments can be passed (like event)
            <Icon type="trash" />
          </div> }
        </LayerContext>
    </Cell>)
// ...

Excel VBA Copy a Range into a New Workbook

Modify to suit your specifics, or make more generic as needed:

Private Sub CopyItOver()
  Set NewBook = Workbooks.Add
  Workbooks("Whatever.xlsx").Worksheets("output").Range("A1:K10").Copy
  NewBook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteValues)
  NewBook.SaveAs FileName:=NewBook.Worksheets("Sheet1").Range("E3").Value
End Sub

How can I resolve the error: "The command [...] exited with code 1"?

This builds on the answer from JaredPar... and is for VS2017. The same "Build and Run" options are present in Visual Studio 2017.

I was getting, The command "chmod +x """ exited with code 1

In the build output window, I searched for "Error" and found a few errors in the same general area. I was able to click on a link in the build output, and found that the error involved this entry in the .targets file:

  <Target Name="ChmodChromeDriver" BeforeTargets="BeforeBuild" Condition="'$(WebDriverPlatform)' != 'win32'">
    <Exec Command="chmod +x &quot;$(ChromeDriverSrcPath)&quot;" />
  </Target>

In the build output, I also found a more detailed error message that essentially stated that it couldn't find Selenium.WebDriver.ChromeDriver v2.36 in the packages folder it was looking in. I checked the project's NuGet packages, and version 2.36 was indeed in the list of installed packages. I did find the package files for 2.36, and changed the attributes on the folder, subfolders and files from "Read Only" to "Read/Write". Built, but same failure. Sometimes "updating" to a different version of the package and then updating back to the original can fix this type of error. So I "updated" the reference in Manage NuGet packages to 2.37, built, failed, then "updated" back to 2.36, built, and the build succeeded without the "chmod +x" error message.

The project I was building was based on a Visual Studio Project template for Appium test tooling, template name "Develop_Automated_Test".

Same font except its weight seems different on different browsers

I collected and tested discussed solutions:

Windows10 Prof x64:

* FireFox v.56.0 x32 
* Opera v.49.0
* Google Chrome v.61.0.3163.100 x64-bit

macOs X Serra v.10.12.6 Mac mini (Mid 2010):

* Safari v.10.1.2(12603.3.8)
* FireFox v.57.0 Quantum
* Opera v49.0

Semi (still micro fat in Safari) solved fatty fonts:

text-transform: none; // mac ff fix
-webkit-font-smoothing: antialiased; // safari mac nicer
-moz-osx-font-smoothing: grayscale; // fix fatty ff on mac

Have no visual effect

line-height: 1;
text-rendering: optimizeLegibility; 
speak: none;
font-style: normal;
font-variant: normal;

Wrong visual effect:

-webkit-font-smoothing: subpixel-antialiased !important; //more fatty in safari
text-rendering: geometricPrecision !important; //more fatty in safari

do not forget to set !important when testing or be sure that your style is not overridden

Passing variables through handlebars partial

The accepted answer works great if you just want to use a different context in your partial. However, it doesn't let you reference any of the parent context. To pass in multiple arguments, you need to write your own helper. Here's a working helper for Handlebars 2.0.0 (the other answer works for versions <2.0.0):

Handlebars.registerHelper('renderPartial', function(partialName, options) {
    if (!partialName) {
        console.error('No partial name given.');
        return '';
    }
    var partial = Handlebars.partials[partialName];
    if (!partial) {
        console.error('Couldnt find the compiled partial: ' + partialName);
        return '';
    }
    return new Handlebars.SafeString( partial(options.hash) );
});

Then in your template, you can do something like:

{{renderPartial 'myPartialName' foo=this bar=../bar}}

And in your partial, you'll be able to access those values as context like:

<div id={{bar.id}}>{{foo}}</div>

What are the differences between Deferred, Promise and Future in JavaScript?

In light of apparent dislike for how I've attempted to answer the OP's question. The literal answer is, a promise is something shared w/ other objects, while a deferred should be kept private. Primarily, a deferred (which generally extends Promise) can resolve itself, while a promise might not be able to do so.

If you're interested in the minutiae, then examine Promises/A+.


So far as I'm aware, the overarching purpose is to improve clarity and loosen coupling through a standardized interface. See suggested reading from @jfriend00:

Rather than directly passing callbacks to functions, something which can lead to tightly coupled interfaces, using promises allows one to separate concerns for code that is synchronous or asynchronous.

Personally, I've found deferred especially useful when dealing with e.g. templates that are populated by asynchronous requests, loading scripts that have networks of dependencies, and providing user feedback to form data in a non-blocking manner.

Indeed, compare the pure callback form of doing something after loading CodeMirror in JS mode asynchronously (apologies, I've not used jQuery in a while):

/* assume getScript has signature like: function (path, callback, context) 
   and listens to onload && onreadystatechange */
$(function () {
   getScript('path/to/CodeMirror', getJSMode);

   // onreadystate is not reliable for callback args.
   function getJSMode() {
       getScript('path/to/CodeMirror/mode/javascript/javascript.js', 
           ourAwesomeScript);
   };

   function ourAwesomeScript() {
       console.log("CodeMirror is awesome, but I'm too impatient.");
   };
});

To the promises formulated version (again, apologies, I'm not up to date on jQuery):

/* Assume getScript returns a promise object */
$(function () {
   $.when(
       getScript('path/to/CodeMirror'),
       getScript('path/to/CodeMirror/mode/javascript/javascript.js')
   ).then(function () {
       console.log("CodeMirror is awesome, but I'm too impatient.");
   });
});

Apologies for the semi-pseudo code, but I hope it makes the core idea somewhat clear. Basically, by returning a standardized promise, you can pass the promise around, thus allowing for more clear grouping.

Oracle SQL: Use sequence in insert with Select Statement

I tested and the script run ok!

INSERT INTO HISTORICAL_CAR_STATS (HISTORICAL_CAR_STATS_ID, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT) 
WITH DATA AS
(
    SELECT '2010' YEAR,'12' MONTH ,'ALL' MAKE,'ALL' MODEL,REGION,sum(AVG_MSRP*COUNT)/sum(COUNT) AVG_MSRP,sum(Count) COUNT
    FROM HISTORICAL_CAR_STATS
    WHERE YEAR = '2010' AND MONTH = '12'
    AND MAKE != 'ALL' GROUP BY REGION
)
SELECT MY_SEQ.NEXTVAL, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT
FROM DATA;

you can read this article to understand more! http://www.orafaq.com/wiki/ORA-02287

Enable IIS7 gzip

Configuration

You can enable GZIP compression entirely in your Web.config file. This is particularly useful if you're on shared hosting and can't configure IIS directly, or you want your config to carry between all environments you target.

<system.webServer>
  <httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
    <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll"/>
    <dynamicTypes>
      <add mimeType="text/*" enabled="true"/>
      <add mimeType="message/*" enabled="true"/>
      <add mimeType="application/javascript" enabled="true"/>
      <add mimeType="*/*" enabled="false"/>
    </dynamicTypes>
    <staticTypes>
      <add mimeType="text/*" enabled="true"/>
      <add mimeType="message/*" enabled="true"/>
      <add mimeType="application/javascript" enabled="true"/>
      <add mimeType="*/*" enabled="false"/>
    </staticTypes>
  </httpCompression>
  <urlCompression doStaticCompression="true" doDynamicCompression="true"/>
</system.webServer>

Testing

To test whether compression is working or not, use the developer tools in Chrome or Firebug for Firefox and ensure the HTTP response header is set:

Content-Encoding: gzip

Note that this header won't be present if the response code is 304 (Not Modified). If that's the case, do a full refresh (hold shift or control while you press the refresh button) and check again.

How to send a message to a particular client with socket.io

SURE: Simply,

This is what you need :

io.to(socket.id).emit("event", data);

whenever a user joined to the server, socket details will be generated including ID. This is the ID really helps to send a message to particular people.

first we need to store all the socket.ids in array,

var people={};

people[name] =  socket.id;

here name is the receiver name. Example:

people["ccccc"]=2387423cjhgfwerwer23;

So, now we can get that socket.id with the receiver name whenever we are sending message:

for this we need to know the receivername. You need to emit receiver name to the server.

final thing is:

 socket.on('chat message', function(data){
io.to(people[data.receiver]).emit('chat message', data.msg);
});

Hope this works well for you.

Good Luck!!

C++ int to byte array

Another useful way of doing it that I use is unions:

union byteint
{
    byte b[sizeof int];
    int i;
};
byteint bi;
bi.i = 1337;
for(int i = 0; i<4;i++)
    destination[i] = bi.b[i];

This will make it so that the byte array and the integer will "overlap"( share the same memory ). this can be done with all kinds of types, as long as the byte array is the same size as the type( else one of the fields will not be influenced by the other ). And having them as one object is also just convenient when you have to switch between integer manipulation and byte manipulation/copying.

Using String Format to show decimal up to 2 places or simple integer

To make the code more clear that Kahia wrote in (it is clear but gets tricky when you want to add more text to it)...try this simple solution.

if (Math.Round((decimal)user.CurrentPoints) == user.CurrentPoints)
     ViewBag.MyCurrentPoints = String.Format("Your current Points: {0:0}",user.CurrentPoints);
else
     ViewBag.MyCurrentPoints = String.Format("Your current Points: {0:0.0}",user.CurrentPoints);

I had to add the extra cast (decimal) to have Math.Round compare the two decimal variables.

Java - get pixel array from image

This worked for me:

BufferedImage bufImgs = ImageIO.read(new File("c:\\adi.bmp"));    
double[][] data = new double[][];
bufImgs.getData().getPixels(0,0,bufImgs.getWidth(),bufImgs.getHeight(),data[i]);    

Create a list from two object lists with linq

You need something like a full outer join. System.Linq.Enumerable has no method that implements a full outer join, so we have to do it ourselves.

var dict1 = list1.ToDictionary(l1 => l1.Name);
var dict2 = list2.ToDictionary(l2 => l2.Name);
    //get the full list of names.
var names = dict1.Keys.Union(dict2.Keys).ToList();
    //produce results
var result = names
.Select( name =>
{
  Person p1 = dict1.ContainsKey(name) ? dict1[name] : null;
  Person p2 = dict2.ContainsKey(name) ? dict2[name] : null;
      //left only
  if (p2 == null)
  {
    p1.Change = 0;
    return p1;
  }
      //right only
  if (p1 == null)
  {
    p2.Change = 0;
    return p2;
  }
      //both
  p2.Change = p2.Value - p1.Value;
  return p2;
}).ToList();

Get current time in milliseconds in Python?

def TimestampMillisec64():
    return int((datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1)).total_seconds() * 1000) 

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

@RequestMapping is a class level

@GetMapping is a method-level

With sprint Spring 4.3. and up things have changed. Now you can use @GetMapping on the method that will handle the http request. The class-level @RequestMapping specification is refined with the (method-level)@GetMapping annotation

Here is an example:

@Slf4j
@Controller
@RequestMapping("/orders")/* The @Request-Mapping annotation, when applied
                            at the class level, specifies the kind of requests 
                            that this controller handles*/  

public class OrderController {

@GetMapping("/current")/*@GetMapping paired with the classlevel
                        @RequestMapping, specifies that when an 
                        HTTP GET request is received for /order, 
                        orderForm() will be called to handle the request..*/

public String orderForm(Model model) {

model.addAttribute("order", new Order());

return "orderForm";
}
}

Prior to Spring 4.3, it was @RequestMapping(method=RequestMethod.GET)

Extra reading from a book authored by Craig Walls Extra reading from a book authored by Craig Walls

Key Value Pair List

Using one of the subsets method in this question

var list = new List<KeyValuePair<string, int>>() { 
    new KeyValuePair<string, int>("A", 1),
    new KeyValuePair<string, int>("B", 0),
    new KeyValuePair<string, int>("C", 0),
    new KeyValuePair<string, int>("D", 2),
    new KeyValuePair<string, int>("E", 8),
};

int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);

EDIT

a full console application:

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<KeyValuePair<string, int>>() { 
                new KeyValuePair<string, int>("A", 1),
                new KeyValuePair<string, int>("B", 2),
                new KeyValuePair<string, int>("C", 3),
                new KeyValuePair<string, int>("D", 4),
                new KeyValuePair<string, int>("E", 5),
                new KeyValuePair<string, int>("F", 6),
            };

            int input = 12;
            var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);

            foreach (var res in alternatives)
            {
                Console.WriteLine(String.Join(",", res.Select(x => x.Key)));
            }
            Console.WriteLine("END");
            Console.ReadLine();
        }
    }

    public static class Extenions
    {
        public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
        {
            List<T> list = enumerable.ToList();
            ulong upper = (ulong)1 << list.Count;

            for (ulong i = 0; i < upper; i++)
            {
                List<T> l = new List<T>(list.Count);
                for (int j = 0; j < sizeof(ulong) * 8; j++)
                {
                    if (((ulong)1 << j) >= upper) break;

                    if (((i >> j) & 1) == 1)
                    {
                        l.Add(list[j]);
                    }
                }

                yield return l;
            }
        }
    }
}

Removing first x characters from string?

Example to show last 3 digits of account number.

x = '1234567890'   
x.replace(x[:7], '')

o/p: '890'

Test if number is odd or even

I am making an assumption that there is a counter already in place. in $i which is incremented at the end of a loop, This works for me using a shorthand query.

$row_pos = ($i & 1) ? 'odd' : 'even';

So what does this do, well it queries the statement we are making in essence $i is odd, depending whether its true or false will decide what gets returned. The returned value populates our variable $row_pos

My use of this is to place it inside the foreach loop, right before i need it, This makes it a very efficient one liner to give me the appropriate class names, this is because i already have a counter for the id's to make use of later in the program. This is a brief example of how i will use this part.

<div class='row-{$row_pos}'> random data <div>

This gives me odd and even classes on each row so i can use the correct class and stripe my printed results down the page.

The full example of what i use note the id has the counter applied to it and the class has my odd/even result applied to it.:

$i=0;
foreach ($a as $k => $v) {

    $row_pos = ($i & 1) ? 'odd' : 'even';
    echo "<div id='A{$i}' class='row-{$row_pos}'>{$v['f_name']} {$v['l_name']} - {$v['amount']} - {$v['date']}</div>\n";

$i++;
}

in summary, this gives me a very simple way to create a pretty table.

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

1 Close Android Studio (AS)

2 Delete the folder in C:\Users.gradle\wrapper\dists\gradle-2.1-all

3 Run AS as admin

4 Sync your project files

node.js - request - How to "emitter.setMaxListeners()"?

Although adding something to nodejs module is possible, it seems to be not the best way (if you try to run your code on other computer, the program will crash with the same error, obviously).

I would rather set max listeners number in your own code:

var options = {uri:headingUri, headers:headerData, maxRedirects:100};
request.setMaxListeners(0);
request.get(options, function (error, response, body) {
}

What does "Could not find or load main class" mean?

Seems like when I had this problem, it was unique.

Once I removed the package declaration at the top of the file, it worked perfectly.

Aside from doing that, there didn't seem to be any way to run a simple HelloWorld.java on my machine, regardless of the folder the compilation happened in, the CLASSPATH or PATH, parameters or folder called from.

Can you get the number of lines of code from a GitHub repository?

Open terminal and run the following:

curl https://api.codetabs.com/v1/loc?github=username/reponame

Delete forked repo from GitHub

No, it will not affect your original repository, just make sure that the repo address looks like "youGitName/TheRepository" and not like "OtherPersonGitName/TheRepo".

What is the "Illegal Instruction: 4" error and why does "-mmacosx-version-min=10.x" fix it?

I'm consciously writing this answer to an old question with this in mind, because the other answers didn't help me.

I got the Illegal Instruction: 4 while running the binary on the same system I had compiled it on, so -mmacosx-version-min didn't help.

I was using gcc in Code Blocks 16 on Mac OS X 10.11.

However, turning off all of Code Blocks' compiler flags for optimization worked. So look at all the flags Code Blocks set (right-click on the Project -> "Build Properties") and turn off all the flags you are sure you don't need, especially -s and the -Oflags for optimization. That did it for me.

How to turn off page breaks in Google Docs?

Other than that open the "View" menu at the top of the screen and un-check "Print Layout." Page breaks will now only be shown as a dashed line.

SQL Server loop - how do I loop through a set of records

I think this is the easy way example to iterate item.

declare @cateid int
select CateID into [#TempTable] from Category where GroupID = 'STOCKLIST'

while (select count(*) from #TempTable) > 0
begin
    select top 1 @cateid = CateID from #TempTable
    print(@cateid)

    --DO SOMETHING HERE

    delete #TempTable where CateID = @cateid
end

drop table #TempTable

How to set up fixed width for <td>?

If you're using <table class="table"> on your table, Bootstrap's table class adds a width of 100% to the table. You need to change the width to auto.

Also, if the first row of your table is a header row, you might need to add the width to th rather than td.

How to add multiple jar files in classpath in linux

For linux users, you should know the following:

  1. $CLASSPATH is specifically what Java uses to look through multiple directories to find all the different classes it needs for your script (unless you explicitly tell it otherwise with the -cp override). Using -cp (--classpath) requires that you keep track of all the directories manually and copy-paste that line every time you run the program (not preferable IMO).

  2. The colon (":") character separates the different directories. There is only one $CLASSPATH and it has all the directories in it. So, when you run "export CLASSPATH=...." you want to include the current value "$CLASSPATH" in order to append to it. For example:

    export CLASSPATH=.
    export CLASSPATH=$CLASSPATH:/usr/share/java/mysql-connector-java-5.1.12.jar
    

    In the first line above, you start CLASSPATH out with just a simple 'dot' which is the path to your current working directory. With that, whenever you run java it will look in the current working directory (the one you're in) for classes. In the second line above, $CLASSPATH grabs the value that you previously entered (.) and appends the path to a mysql dirver. Now, java will look for the driver AND for your classes.

  3. echo $CLASSPATH
    

    is super handy, and what it returns should read like a colon-separated list of all the directories you want java looking in for what it needs to run your script.

  4. Tomcat does not use CLASSPATH. Read what to do about that here: https://tomcat.apache.org/tomcat-8.0-doc/class-loader-howto.html

UPDATE with CASE and IN - Oracle

Got a solution that runs. Don't know if it is optimal though. What I do is to split the string according to http://blogs.oracle.com/aramamoo/2010/05/how_to_split_comma_separated_string_and_pass_to_in_clause_of_select_statement.html

Using:
select regexp_substr(' 1, 2 , 3 ','[^,]+', 1, level) from dual
connect by regexp_substr('1 , 2 , 3 ', '[^,]+', 1, level) is not null;

So my final code looks like this ($bp_gr1' are strings like 1,2,3):

UPDATE TAB1
SET    BUDGPOST_GR1 =
          CASE
             WHEN ( BUDGPOST IN (SELECT     REGEXP_SUBSTR ( '$BP_GR1',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                 FROM       DUAL
                                 CONNECT BY REGEXP_SUBSTR ( '$BP_GR1',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                               IS NOT NULL) )
             THEN
                'BP_GR1'
             WHEN ( BUDGPOST IN (SELECT     REGEXP_SUBSTR ( ' $BP_GR2',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                 FROM       DUAL
                                 CONNECT BY REGEXP_SUBSTR ( '$BP_GR2',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                               IS NOT NULL) )
             THEN
                'BP_GR2'
             WHEN ( BUDGPOST IN (SELECT     REGEXP_SUBSTR ( ' $BP_GR3',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                 FROM       DUAL
                                 CONNECT BY REGEXP_SUBSTR ( '$BP_GR3',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                               IS NOT NULL) )
             THEN
                'BP_GR3'
             WHEN ( BUDGPOST IN (SELECT     REGEXP_SUBSTR ( '$BP_GR4',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                 FROM       DUAL
                                 CONNECT BY REGEXP_SUBSTR ( '$BP_GR4',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                               IS NOT NULL) )
             THEN
                'BP_GR4'
             ELSE
                'SAKNAR BUDGETGRUPP'
          END;

Is there a way to make it run faster?

How do I create a pause/wait function using Qt?

we can use following method QT_Delay:

QTimer::singleShot(2000,this,SLOT(print_lcd()));

This will wait for 2 seconds before calling print_lcd().

Sum of two input value by jquery

Because at least one value is a string the + operator is being interpreted as a string concatenation operator. The simplest fix for this is to indicate that you intend for the values to be interpreted as numbers.

var total = +a + +b;

and

$('#total_price').val(+a + +b);

Or, better, just pull them out as numbers to begin with:

var a = +$('input[name=service_price]').val();
var b = +$('input[name=modem_price]').val();
var total = a+b;
$('#total_price').val(a+b);

See Mozilla's Unary + documentation.

Note that this is only a good idea if you know the value is going to be a number anyway. If this is user input you must be more careful and probably want to use parseInt and other validation as other answers suggest.

How is the default max Java heap size determined?

Finally!

As of Java 8u191 you now have the options:

-XX:InitialRAMPercentage
-XX:MaxRAMPercentage
-XX:MinRAMPercentage

that can be used to size the heap as a percentage of the usable physical RAM. (which is same as the RAM installed less what the kernel uses).

See Release Notes for Java8 u191 for more information. Note that the options are mentioned under a Docker heading but in fact they apply whether you are in Docker environment or in a traditional environment.

The default value for MaxRAMPercentage is 25%. This is extremely conservative.

My own rule: If your host is more or less dedicated to running the given java application, then you can without problems increase dramatically. If you are on Linux, only running standard daemons and have installed RAM from somewhere around 1 Gb and up then I wouldn't hesitate to use 75% for the JVM's heap. Again, remember that this is 75% of the RAM available, not the RAM installed. What is left is the other user land processes that may be running on the host and the other types of memory that the JVM needs (eg for stack). All together, this will typically fit nicely in the 25% that is left. Obviously, with even more installed RAM the 75% is a safer and safer bet. (I wish the JDK folks had implemented an option where you could specify a ladder)

Setting the MaxRAMPercentage option look like this:

java -XX:MaxRAMPercentage=75.0  ....

Note that these percentage values are of 'double' type and therefore you must specify them with a decimal dot. You get a somewhat odd error if you use "75" instead of "75.0".

Key Shortcut for Eclipse Imports

Some useful shortcuts. You're looking for the 1st one...

  1. Ctrl + Shift + O : Organize imports
  2. Ctrl + Shift + T : Open Type
  3. Ctrl + Shift + F4 : Close all Opened Editors
  4. Ctrl + O : Open declarations
  5. Ctrl + E : Open Editor
  6. Ctrl + / : Line Comment
  7. Alt + Shift + R : Rename
  8. Alt + Shift + L : extract to Local Variable
  9. Alt + Shift + M : extract to Method
  10. F3 : Open Declaration

Source Here

Date difference in years using C#

Use:

int Years(DateTime start, DateTime end)
{
    return (end.Year - start.Year - 1) +
        (((end.Month > start.Month) ||
        ((end.Month == start.Month) && (end.Day >= start.Day))) ? 1 : 0);
}

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

How does tuple comparison work in Python?

The Python documentation does explain it.

Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.

pandas resample documentation

There's more to it than this, but you're probably looking for this list:

B   business day frequency
C   custom business day frequency (experimental)
D   calendar day frequency
W   weekly frequency
M   month end frequency
BM  business month end frequency
MS  month start frequency
BMS business month start frequency
Q   quarter end frequency
BQ  business quarter endfrequency
QS  quarter start frequency
BQS business quarter start frequency
A   year end frequency
BA  business year end frequency
AS  year start frequency
BAS business year start frequency
H   hourly frequency
T   minutely frequency
S   secondly frequency
L   milliseconds
U   microseconds

Source: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases

round() doesn't seem to be rounding properly

You can use the string format operator %, similar to sprintf.

mystring = "%.2f" % 5.5999

Base64 decode snippet in C++

A little variation with a more compact lookup table and using C++17 features:

std::string base64_decode(const std::string_view in) {
  // table from '+' to 'z'
  const uint8_t lookup[] = {
      62,  255, 62,  255, 63,  52,  53, 54, 55, 56, 57, 58, 59, 60, 61, 255,
      255, 0,   255, 255, 255, 255, 0,  1,  2,  3,  4,  5,  6,  7,  8,  9,
      10,  11,  12,  13,  14,  15,  16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
      255, 255, 255, 255, 63,  255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
      36,  37,  38,  39,  40,  41,  42, 43, 44, 45, 46, 47, 48, 49, 50, 51};
  static_assert(sizeof(lookup) == 'z' - '+' + 1);

  std::string out;
  int val = 0, valb = -8;
  for (uint8_t c : in) {
    if (c < '+' || c > 'z')
      break;
    c -= '+';
    if (lookup[c] >= 64)
      break;
    val = (val << 6) + lookup[c];
    valb += 6;
    if (valb >= 0) {
      out.push_back(char((val >> valb) & 0xFF));
      valb -= 8;
    }
  }
  return out;
}

If you don't have std::string_view, try instead std::experimental::string_view.

vba pass a group of cells as range to function

As I'm beginner for vba, I'm willing to get a deep knowledge of vba of how all excel in-built functions work form there back.

So as on the above question I have putted my basic efforts.

Function multi_add(a As Range, ParamArray b() As Variant) As Double

    Dim ele As Variant

    Dim i As Long

    For Each ele In a
        multi_add = a + ele.Value **- a**
    Next ele

    For i = LBound(b) To UBound(b)
        For Each ele In b(i)
            multi_add = multi_add + ele.Value
        Next ele
    Next i

End Function

- a: This is subtracted for above code cause a count doubles itself so what values you adds it will add first value twice.

How to allow <input type="file"> to accept only image files?

Using type="file" and accept="image/*" (or the format you want), allow the user to chose a file with specific format. But you have to re check it again in client side, because the user can select other type of files. This works for me.

<input #imageInput accept="image/*" (change)="processFile(imageInput)" name="upload-photo" type="file" id="upload-photo" />

And then, in your javascript script

processFile(imageInput) {
    if (imageInput.files[0]) {
      const file: File = imageInput.files[0];
      var pattern = /image-*/;

      if (!file.type.match(pattern)) {
        alert('Invalid format');
        return;
      }

      // here you can do whatever you want with your image. Now you are sure that it is an image
    }
  }

Display animated GIF in iOS

You can use SwiftGif from this link

Usage:

imageView.loadGif(name: "jeremy")

Collapsing Sidebar with Bootstrap

Its not mentioned on doc, but Left sidebar on Bootstrap 3 is possible using "Collapse" method.

As mentioned by bootstrap.js :

Collapse.prototype.dimension = function () {
    var hasWidth = this.$element.hasClass('width')
    return hasWidth ? 'width' : 'height'
  }

This mean, adding class "width" into target, will expand by width instead of height :

http://jsfiddle.net/2316sfbz/2/

Using jQuery to see if a div has a child with a certain class

There is a hasClass function

if($('#popup p').hasClass('filled-text'))

Android ImageView Zoom-in and Zoom-Out

Just change ACTION_MOVE_EVENT in Chirag Raval Answer to set ZOOM_IN LIMIT

float[] values = new float[9]; matrix.getValues(values);
                //0.37047964 is limit for zoom in
                if(values[Matrix.MSCALE_X]>0.37047964) {
                    matrix.set(savedMatrix);
                    matrix.postScale(scale, scale, mid.x, mid.y);
                    view.setImageMatrix(matrix);
                }else if (scale>1){
                    matrix.set(savedMatrix);
                    matrix.postScale(scale, scale, mid.x, mid.y);
                    view.setImageMatrix(matrix);
                }

How to add results of two select commands in same query

If you want to make multiple operation use

select (sel1.s1+sel2+s2)

(select sum(hours) s1 from resource) sel1
join 
(select sum(hours) s2 from projects-time)sel2
on sel1.s1=sel2.s2

In Oracle, is it possible to INSERT or UPDATE a record through a view?

Oracle has two different ways of making views updatable:-

  1. The view is "key preserved" with respect to what you are trying to update. This means the primary key of the underlying table is in the view and the row appears only once in the view. This means Oracle can figure out exactly which underlying table row to update OR
  2. You write an instead of trigger.

I would stay away from instead-of triggers and get your code to update the underlying tables directly rather than through the view.

Error in Process.Start() -- The system cannot find the file specified

I had the same problem, but none of the solutions worked for me, because the message The system cannot find the file specified can be misleading in some special cases.

In my case, I use Notepad++ in combination with the registry redirect for notepad.exe. Unfortunately my path to Notepad++ in the registry was wrong.

So in fact the message The system cannot find the file specified was telling me, that it cannot find the application (Notepad++) associated with the file type(*.txt), not the file itself.

Maximum value of maxRequestLength?

As per MSDN the default value is 4096 KB (4 MB).

UPDATE

As for the Maximum, since it is an int data type, then theoretically you can go up to 2,147,483,647. Also I wanted to make sure that you are aware that IIS 7 uses maxAllowedContentLength for specifying file upload size. By default it is set to 30000000 around 30MB and being an uint, it should theoretically allow a max of 4,294,967,295

How to find list of possible words from a letter matrix [Boggle Solver]

I spent 3 months working on a solution to the 10 best point dense 5x5 Boggle boards problem.

The problem is now solved and laid out with full disclosure on 5 web pages. Please contact me with questions.

The board analysis algorithm uses an explicit stack to pseudo-recursively traverse the board squares through a Directed Acyclic Word Graph with direct child information, and a time stamp tracking mechanism. This may very well be the world's most advanced lexicon data structure.

The scheme evaluates some 10,000 very good boards per second on a quad core. (9500+ points)

Parent Web Page:

DeepSearch.c - http://www.pathcom.com/~vadco/deep.html

Component Web Pages:

Optimal Scoreboard - http://www.pathcom.com/~vadco/binary.html

Advanced Lexicon Structure - http://www.pathcom.com/~vadco/adtdawg.html

Board Analysis Algorithm - http://www.pathcom.com/~vadco/guns.html

Parallel Batch Processing - http://www.pathcom.com/~vadco/parallel.html

- This comprehensive body of work will only interest a person who demands the very best.

Plot multiple lines in one graph

You should bring your data into long (i.e. molten) format to use it with ggplot2:

library("reshape2")
mdf <- melt(mdf, id.vars="Company", value.name="value", variable.name="Year")

And then you have to use aes( ... , group = Company ) to group them:

ggplot(data=mdf, aes(x=Year, y=value, group = Company, colour = Company)) +
    geom_line() +
    geom_point( size=4, shape=21, fill="white")

enter image description here

How to generate unique IDs for form labels in React?

The id should be placed inside of componentWillMount (update for 2018) constructor, not render. Putting it in render will re-generate new ids unnecessarily.

If you're using underscore or lodash, there is a uniqueId function, so your resulting code should be something like:

constructor(props) {
    super(props);
    this.id = _.uniqueId("prefix-");
}

render() { 
  const id = this.id;
  return (
    <div>
        <input id={id} type="checkbox" />
        <label htmlFor={id}>label</label>
    </div>
  );
}

2019 Hooks update:

import React, { useState } from 'react';
import _uniqueId from 'lodash/uniqueId';

const MyComponent = (props) => {
  // id will be set once when the component initially renders, but never again
  // (unless you assigned and called the second argument of the tuple)
  const [id] = useState(_uniqueId('prefix-'));
  return (
    <div>
      <input id={id} type="checkbox" />
      <label htmlFor={id}>label</label>
    </div>
  );
}

What is the proof of of (N–1) + (N–2) + (N–3) + ... + 1= N*(N–1)/2

Sum of arithmetical progression

(A1+AN)/2*N = (1 + (N-1))/2*(N-1) = N*(N-1)/2

Avoid browser popup blockers

The general rule is that popup blockers will engage if window.open or similar is invoked from javascript that is not invoked by direct user action. That is, you can call window.open in response to a button click without getting hit by the popup blocker, but if you put the same code in a timer event it will be blocked. Depth of call chain is also a factor - some older browsers only look at the immediate caller, newer browsers can backtrack a little to see if the caller's caller was a mouse click etc. Keep it as shallow as you can to avoid the popup blockers.

C++: constructor initializer for arrays

Ideas from a twisted mind :

class mytwistedclass{
static std::vector<int> initVector;
mytwistedclass()
{
    //initialise with initVector[0] and then delete it :-)
}

};

now set this initVector to something u want to before u instantiate an object. Then your objects are initialized with your parameters.

Creating a new empty branch for a new project

i found this help:

git checkout --orphan empty.branch.name
git rm --cached -r .
echo "init empty branch" > README.md
git add README.md
git commit -m "init empty branch"

scp files from local to remote machine error: no such file or directory

As @Astariul said, path to the file might cause this bug.
In addition, any parent directory which contains non-ASCII character, for example Chinese, will cause this.
In that case, you should rename you parent directory

You have not accepted the license agreements of the following SDK components

You can install and accept the license of the SDK & tools via 2 ways:

1. Open the Android SDK Manager GUI via command line

Open the Android SDK manager via the command line using:

# Android SDK Tools 25.2.3 and lower - Open the Android SDK GUI via the command line
cd ~/Library/Android/sdk/tools && ./android

# 'Android SDK Tools' 25.2.3 and higher - `sdkmanager` is located in android_sdk/tools/bin/.
cd ~/Library/Android/sdk/tools/bin && ./sdkmanager

View more details on the new sdkmanager.

Select and install the required tools. (your location may be different)

2. Install and accept android license via command line:

Update the packages via command line, you'll be presented with the terms and conditions which you'll need to accept.

- Install or update to the latest version

This will install the latest platform-tools at the time you run it.

# Android SDK Tools 25.2.3 and lower. Install the latest `platform-tools` for android-25
android update sdk --no-ui --all --filter platform-tools,android-25,extra-android-m2repository

# Android SDK Tools 25.2.3 and higher
sdkmanager --update

- Install a specific version (25.0.1, 24.0.1, 23.0.1)

You can also install a specific version like so:

# Build Tools 23.0.1, 24.0.1, 25.0.1
android update sdk --no-ui --all --filter build-tools-25.0.1,android-25,extra-android-m2repository
android update sdk --no-ui --all --filter build-tools-24.0.1,android-24,extra-android-m2repository
android update sdk --no-ui --all --filter build-tools-23.0.1,android-23,extra-android-m2repository
# Alter the versions as required                      ?               ?

# -u --no-ui  : Updates from command-line (does not display the GUI)
# -a --all    : Includes all packages (such as obsolete and non-dependent ones.)
# -t --filter : A filter that limits the update to the specified types of
#               packages in the form of a comma-separated list of
#               [platform, system-image, tool, platform-tool, doc, sample,
#               source]. This also accepts the identifiers returned by
#               'list sdk --extended'.

# List version and description of other available SDKs and tools
android list sdk --extended
sdkmanager --list

Why Choose Struct Over Class?

I wouldn't say that structs offer less functionality.

Sure, self is immutable except in a mutating function, but that's about it.

Inheritance works fine as long as you stick to the good old idea that every class should be either abstract or final.

Implement abstract classes as protocols and final classes as structs.

The nice thing about structs is that you can make your fields mutable without creating shared mutable state because copy on write takes care of that :)

That's why the properties / fields in the following example are all mutable, which I would not do in Java or C# or swift classes.

Example inheritance structure with a bit of dirty and straightforward usage at the bottom in the function named "example":

protocol EventVisitor
{
    func visit(event: TimeEvent)
    func visit(event: StatusEvent)
}

protocol Event
{
    var ts: Int64 { get set }

    func accept(visitor: EventVisitor)
}

struct TimeEvent : Event
{
    var ts: Int64
    var time: Int64

    func accept(visitor: EventVisitor)
    {
        visitor.visit(self)
    }
}

protocol StatusEventVisitor
{
    func visit(event: StatusLostStatusEvent)
    func visit(event: StatusChangedStatusEvent)
}

protocol StatusEvent : Event
{
    var deviceId: Int64 { get set }

    func accept(visitor: StatusEventVisitor)
}

struct StatusLostStatusEvent : StatusEvent
{
    var ts: Int64
    var deviceId: Int64
    var reason: String

    func accept(visitor: EventVisitor)
    {
        visitor.visit(self)
    }

    func accept(visitor: StatusEventVisitor)
    {
        visitor.visit(self)
    }
}

struct StatusChangedStatusEvent : StatusEvent
{
    var ts: Int64
    var deviceId: Int64
    var newStatus: UInt32
    var oldStatus: UInt32

    func accept(visitor: EventVisitor)
    {
        visitor.visit(self)
    }

    func accept(visitor: StatusEventVisitor)
    {
        visitor.visit(self)
    }
}

func readEvent(fd: Int) -> Event
{
    return TimeEvent(ts: 123, time: 56789)
}

func example()
{
    class Visitor : EventVisitor
    {
        var status: UInt32 = 3;

        func visit(event: TimeEvent)
        {
            print("A time event: \(event)")
        }

        func visit(event: StatusEvent)
        {
            print("A status event: \(event)")

            if let change = event as? StatusChangedStatusEvent
            {
                status = change.newStatus
            }
        }
    }

    let visitor = Visitor()

    readEvent(1).accept(visitor)

    print("status: \(visitor.status)")
}

Replace all spaces in a string with '+'

You can also do it like:

str = str.replace(/\s/g, "+");

Have a look at this fiddle.

MYSQL: How to copy an entire row from one table to another in mysql with the second table having one extra column?

Alternatively, you can use Inner Queries to do so.

SQL> INSERT INTO <NEW_TABLE> SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM <OLD_TABLE>);

Hope this helps!

What's the most efficient way to test two integer ranges for overlap?

If someone is looking for a one-liner which calculates the actual overlap:

int overlap = ( x2 > y1 || y2 < x1 ) ? 0 : (y2 >= y1 && x2 <= y1 ? y1 : y2) - ( x2 <= x1 && y2 >= x1 ? x1 : x2) + 1; //max 11 operations

If you want a couple fewer operations, but a couple more variables:

bool b1 = x2 <= y1;
bool b2 = y2 >= x1;
int overlap = ( !b1 || !b2 ) ? 0 : (y2 >= y1 && b1 ? y1 : y2) - ( x2 <= x1 && b2 ? x1 : x2) + 1; // max 9 operations

Sass .scss: Nesting and multiple classes?

If that is the case, I think you need to use a better way of creating a class name or a class name convention. For example, like you said you want the .container class to have different color according to a specific usage or appearance. You can do this:

SCSS

.container {
  background: red;

  &--desc {
    background: blue;
  }

  // or you can do a more specific name
  &--blue {
    background: blue;
  }

  &--red {
    background: red;
  }
}

CSS

.container {
  background: red;
}

.container--desc {
  background: blue;
}

.container--blue {
  background: blue;
}

.container--red {
  background: red;
}

The code above is based on BEM Methodology in class naming conventions. You can check this link: BEM — Block Element Modifier Methodology

NSNotificationCenter addObserver in Swift

Pass Data using NSNotificationCenter

You can also pass data using NotificationCentre in swift 3.0 and NSNotificationCenter in swift 2.0.

Swift 2.0 Version

Pass info using userInfo which is a optional Dictionary of type [NSObject : AnyObject]?

let imageDataDict:[String: UIImage] = ["image": image]

// Post a notification
 NSNotificationCenter.defaultCenter().postNotificationName(notificationName, object: nil, userInfo: imageDataDict)

// Register to receive notification in your class
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: notificationName, object: nil)

// handle notification
func showSpinningWheel(notification: NSNotification) {
  if let image = notification.userInfo?["image"] as? UIImage {
  // do something with your image   
  }
}

Swift 3.0 Version

The userInfo now takes [AnyHashable:Any]? as an argument, which we provide as a dictionary literal in Swift

let imageDataDict:[String: UIImage] = ["image": image]

// post a notification
 NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict) 
// `default` is now a property, not a method call

// Register to receive notification in your class
NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

// handle notification
func showSpinningWheel(_ notification: NSNotification) {

  if let image = notification.userInfo?["image"] as? UIImage {
  // do something with your image   
  }
}

Source pass data using NotificationCentre(swift 3.0) and NSNotificationCenter(swift 2.0)

Adding link a href to an element using css

You don't need CSS for this.

     <img src="abc"/>

now with link:

     <a href="#myLink"><img src="abc"/></a>

Or with jquery, later on, you can use the wrap property, see these questions answer:

how to add a link to an image using jquery?

How do I install PHP cURL on Linux Debian?

I wrote an article on topis how to [manually install curl on debian linu][1]x.

[1]: http://www.jasom.net/how-to-install-curl-command-manually-on-debian-linux. This is its shortcut:

  1. cd /usr/local/src
  2. wget http://curl.haxx.se/download/curl-7.36.0.tar.gz
  3. tar -xvzf curl-7.36.0.tar.gz
  4. rm *.gz
  5. cd curl-7.6.0
  6. ./configure
  7. make
  8. make install

And restart Apache. If you will have an error during point 6, try to run apt-get install build-essential.

Perform curl request in javascript?

curl is a command in linux (and a library in php). Curl typically makes an HTTP request.

What you really want to do is make an HTTP (or XHR) request from javascript.

Using this vocab you'll find a bunch of examples, for starters: Sending authorization headers with jquery and ajax

Essentially you will want to call $.ajax with a few options for the header, etc.

$.ajax({
        url: 'https://api.wit.ai/message?v=20140826&q=',
        beforeSend: function(xhr) {
             xhr.setRequestHeader("Authorization", "Bearer 6QXNMEMFHNY4FJ5ELNFMP5KRW52WFXN5")
        }, success: function(data){
            alert(data);
            //process the JSON data etc
        }
})

How to calculate the bounding box for a given lat/lng location?

I wrote an article about finding the bounding coordinates:

http://JanMatuschek.de/LatitudeLongitudeBoundingCoordinates

The article explains the formulae and also provides a Java implementation. (It also shows why Federico's formula for the min/max longitude is inaccurate.)

$watch an object

you must changes in $watch ....

_x000D_
_x000D_
function MyController($scope) {_x000D_
    $scope.form = {_x000D_
        name: 'my name',_x000D_
    }_x000D_
_x000D_
    $scope.$watch('form.name', function(newVal, oldVal){_x000D_
        console.log('changed');_x000D_
     _x000D_
    });_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>_x000D_
<div ng-app>_x000D_
    <div ng-controller="MyController">_x000D_
        <label>Name:</label> <input type="text" ng-model="form.name"/>_x000D_
            _x000D_
        <pre>_x000D_
            {{ form }}_x000D_
        </pre>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using ADB to capture the screen

Using some of the knowledge from this and a couple of other posts, I found the method that worked the best for me was to:

adb shell 'stty raw; screencap -p'

I have posted a very simple Python script on GitHub that essentially mirrors the screen of a device connected over ADB:

https://github.com/baitisj/android_screen_mirror

How to handle onchange event on input type=file in jQuery?

Demo : http://jsfiddle.net/NbGBj/

$("document").ready(function(){

    $("#upload").change(function() {
        alert('changed!');
    });
});

Change value of input placeholder via model?

As Wagner Francisco said, (in JADE)

input(type="text", ng-model="someModel", placeholder="{{someScopeVariable}}")`

And in your controller :

$scope.someScopeVariable = 'somevalue'

jquery how to empty input field

To reset text, number, search, textarea inputs:

$('#shares').val('');

To reset select:

$('#select-box').prop('selectedIndex',0);

To reset radio input:

$('#radio-input').attr('checked',false);

To reset file input:

$("#file-input").val(null);

Git push rejected after feature branch rebase

The following works for me:

git push -f origin branch_name

and it does not remove any of my code.

But, if you want to avoid this then you can do the following:

git checkout master
git pull --rebase
git checkout -b new_branch_name

then you can cherry-pick all your commits to the new branch. git cherry-pick COMMIT ID and then push your new branch.

How to check all checkboxes using jQuery?

if(isAllChecked == 0)
{ 
    $("#select_all").prop("checked", true); 
}   

please change the above line to

if(isAllChecked == 0)
{ 
    $("#checkedAll").prop("checked", true); 
}   

in SSR's answer and its working perfect Thank you

How to use the read command in Bash?

Other bash alternatives that do not involve a subshell:

read str <<END             # here-doc
hello
END

read str <<< "hello"       # here-string

read str < <(echo hello)   # process substitution

Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?

You can use localStorage to save the data for later use, but you can not save to a file using JavaScript (in the browser).

To be comprehensive: You can not store something into a file using JavaScript in the Browser, but using HTML5, you can read files.

difference between iframe, embed and object elements

iframe have "sandbox" attribute that may block pop up etc

How to display all elements in an arraylist?

Tangential: String.format() rocks:

public String toString() {
    return String.format("%s %s", getMake(), getReg());
}

private static void printAll() {
    for (Car car: cars)
        System.out.println(car); // invokes Car.toString()
}

Where does npm install packages?

Global libraries

You can run npm list -g to see which global libraries are installed and where they're located. Use npm list -g | head -1 for truncated output showing just the path. If you want to display only main packages not its sub-packages which installs along with it - you can use - npm list --depth=0 which will show all packages and for getting only globally installed packages, just add -g i.e. npm list -g --depth=0.

On Unix systems they are normally placed in /usr/local/lib/node or /usr/local/lib/node_modules when installed globally. If you set the NODE_PATH environment variable to this path, the modules can be found by node.

Windows XP - %USERPROFILE%\AppData\npm\node_modules
Windows 7, 8 and 10 - %USERPROFILE%\AppData\Roaming\npm\node_modules

Non-global libraries

Non-global libraries are installed the node_modules sub folder in the folder you are currently in.

You can run npm list to see the installed non-global libraries for your current location.

When installing use -g option to install globally

npm install -g pm2 - pm2 will be installed globally. It will then typically be found in /usr/local/lib/node_modules (Use npm root -g to check where.)

npm install pm2 - pm2 will be installed locally. It will then typically be found in the local directory in /node_modules

Find position of a node using xpath

Unlike stated previously 'preceding-sibling' is really the axis to use, not 'preceding' which does something completely different, it selects everything in the document that is before the start tag of the current node. (see http://www.w3schools.com/xpath/xpath_axes.asp)

Looping through JSON with node.js

A little late but I believe some further clarification is given below.

You can iterate through a JSON array with a simple loop as well, like:

for(var i = 0; i < jsonArray.length; i++)
{
    console.log(jsonArray[i].attributename);
}

If you have a JSON object and you want to loop through all of its inner objects, then you first need to get all the keys in an array and loop through the keys to retrieve objects using the key names, like:

var keys = Object.keys(jsonObject);
for(var i = 0; i < keys.length; i++) 
{
    var key = keys[i];
    console.log(jsonObject.key.attributename);
}

Difference between drop table and truncate table?

TRUNCATE TABLE is functionally identical to DELETE statement with no WHERE clause: both remove all rows in the table. But TRUNCATE TABLE is faster and uses fewer system and transaction log resources than DELETE.

The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row. TRUNCATE TABLE removes the data by deallocating the data pages used to store the table's data, and only the page deallocations are recorded in the transaction log.

TRUNCATE TABLE removes all rows from a table, but the table structure and its columns, constraints, indexes and so on remain. The counter used by an identity for new rows is reset to the seed for the column. If you want to retain the identity counter, use DELETE instead. If you want to remove table definition and its data, use the DROP TABLE statement.

You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint; instead, use DELETE statement without a WHERE clause. Because TRUNCATE TABLE is not logged, it cannot activate a trigger.

TRUNCATE TABLE may not be used on tables participating in an indexed view.

From http://msdn.microsoft.com/en-us/library/aa260621(SQL.80).aspx

C - reading command line parameters

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

int main(int argc, char **argv) {
  int i, parameter = 0;
  if (argc >= 2) {
    /* there is 1 parameter (or more) in the command line used */
    /* argv[0] may point to the program name */
    /* argv[1] points to the 1st parameter */
    /* argv[argc] is NULL */
    parameter = atoi(argv[1]); /* better to use strtol */
    if (parameter > 0) {
      for (i = 0; i < parameter; i++) printf("%d ", i);
    } else {
      fprintf(stderr, "Please use a positive integer.\n");
    }
  }
  return 0;
}

Remove icon/logo from action bar on android

Calling

mActionBar.setDisplayHomeAsUpEnabled(true);

in addition to,

mActionBar.setDisplayShowHomeEnabled(false);

will hide the logo but display the Home As Up icon. :)

Python PIP Install throws TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'

Bizarrely if I remove the proxy from the environment and add it to the command line it works for me. For example to upgrade pip itself:

env http_proxy= https_proxy= pip install pip --upgrade --proxy 'http://proxy-url:80'

My issue was having the proxy in the environment. It seems that pip only honors the one in argument.

How to dynamically change header based on AngularJS partial view?

Thanks to tosh shimayama for his solution.
I thought it was not so clean to put a service straight into the $scope, so here's my slight variation on that: http://plnkr.co/edit/QJbuZZnZEDOBcYrJXWWs

The controller (that in original answer seemed to me a little bit too dumb) creates an ActionBar object, and this one is stuffed into $scope.
The object is responsible for actually querying the service. It also hides from the $scope the call to set the template URL, which instead is available to other controllers to set the URL.

Jenkins pipeline if else not working

your first try is using declarative pipelines, and the second working one is using scripted pipelines. you need to enclose steps in a steps declaration, and you can't use if as a top-level step in declarative, so you need to wrap it in a script step. here's a working declarative version:

pipeline {
    agent any

    stages {
        stage('test') {
            steps {
                sh 'echo hello'
            }
        }
        stage('test1') {
            steps {
                sh 'echo $TEST'
            }
        }
        stage('test3') {
            steps {
                script {
                    if (env.BRANCH_NAME == 'master') {
                        echo 'I only execute on the master branch'
                    } else {
                        echo 'I execute elsewhere'
                    }
                }
            }
        }
    }
}

you can simplify this and potentially avoid the if statement (as long as you don't need the else) by using "when". See "when directive" at https://jenkins.io/doc/book/pipeline/syntax/. you can also validate jenkinsfiles using the jenkins rest api. it's super sweet. have fun with declarative pipelines in jenkins!

Find column whose name contains a specific string

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

How can I format a String number to have commas and round?

I've created my own formatting utility. Which is extremely fast at processing the formatting along with giving you many features :)

It supports:

  • Comma Formatting E.g. 1234567 becomes 1,234,567.
  • Prefixing with "Thousand(K),Million(M),Billion(B),Trillion(T)".
  • Precision of 0 through 15.
  • Precision re-sizing (Means if you want 6 digit precision, but only have 3 available digits it forces it to 3).
  • Prefix lowering (Means if the prefix you choose is too large it lowers it to a more suitable prefix).

The code can be found here. You call it like this:

public static void main(String[])
{
   int settings = ValueFormat.COMMAS | ValueFormat.PRECISION(2) | ValueFormat.MILLIONS;
   String formatted = ValueFormat.format(1234567, settings);
}

I should also point out this doesn't handle decimal support, but is very useful for integer values. The above example would show "1.23M" as the output. I could probably add decimal support maybe, but didn't see too much use for it since then I might as well merge this into a BigInteger type of class that handles compressed char[] arrays for math computations.

How do I find out what is hammering my SQL Server?

For a GUI approach I would take a look at Activity Monitor under Management and sort by CPU.

Pass value to iframe from a window

What you have to do is to append the values as parameters in the iframe src (URL).

E.g. <iframe src="some_page.php?somedata=5&more=bacon"></iframe>

And then in some_page.php file you use php $_GET['somedata'] to retrieve it from the iframe URL. NB: Iframes run as a separate browser window in your file.

How to make graphics with transparent background in R using ggplot2?

Just to improve YCR's answer:

1) I added black lines on x and y axis. Otherwise they are made transparent too.

2) I added a transparent theme to the legend key. Otherwise, you will get a fill there, which won't be very esthetic.

Finally, note that all those work only with pdf and png formats. jpeg fails to produce transparent graphs.

MyTheme_transparent <- theme(
    panel.background = element_rect(fill = "transparent"), # bg of the panel
    plot.background = element_rect(fill = "transparent", color = NA), # bg of the plot
    panel.grid.major = element_blank(), # get rid of major grid
    panel.grid.minor = element_blank(), # get rid of minor grid
    legend.background = element_rect(fill = "transparent"), # get rid of legend bg
    legend.box.background = element_rect(fill = "transparent"), # get rid of legend panel bg
    legend.key = element_rect(fill = "transparent", colour = NA), # get rid of key legend fill, and of the surrounding
    axis.line = element_line(colour = "black") # adding a black line for x and y axis
)

display:inline vs display:block

Block

Takes up the full width available, with a new line before and after (display:block;)

Inline

Takes up only as much width as it needs, and does not force new lines (display:inline;)

positional argument follows keyword argument

The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:

argument_list        ::=  positional_arguments ["," starred_and_keywords]
                            ["," keywords_arguments]
                          | starred_and_keywords ["," keywords_arguments]
                          | keywords_arguments

Specifically, a keyword argument looks like this: tag='insider trading!' while a positional argument looks like this: ..., exchange, .... The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.

Also, when an argument has a default value, such as price=None, that means you don't have to provide it. If you don't provide it, it will use the default value instead.

To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity)

# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)

# Some positional, some keyword (all keywords at end):

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity, tag='insider trading!')

plot is not defined

Change that import to

from matplotlib.pyplot import *

Note that this style of imports (from X import *) is generally discouraged. I would recommend using the following instead:

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])

How do I style radio buttons with images - laughing smiley for good, sad smiley for bad?

With pure html (no JS), you can't really substitute a radio-button for an image (at least, I don't think you can). You could, though use the following to make the same connection to the user:

<form action="" method="post">
    <fieldset>
       <input type="radio" name="feeling" id="feelingSad" value="sad" /><label for="feelingSad"><img src="path/to/sad.png" /></label>
       <label for="feelingHappy"><input type="radio" name="feeling" id="feelingHappy" value="happy" /><img src="path/to/happy.png" /></label>
    </fieldset>
</form>

How to make matrices in Python?

you can also use append function

b = [ ]

for x in range(0, 5):
    b.append(["O"] * 5)

def print_b(b):
    for row in b:
        print " ".join(row)

Pip install Matplotlib error with virtualenv

To reduce the required packages to install you just need

apt-get install -y \
    libfreetype6-dev \
    libxft-dev && \
    pip install matplotlib

and you will get the following packages locally installed

Collecting matplotlib
  Downloading matplotlib-2.2.0-cp35-cp35m-manylinux1_x86_64.whl (12.5MB)
Collecting pytz (from matplotlib)
  Downloading pytz-2018.3-py2.py3-none-any.whl (509kB)
Collecting python-dateutil>=2.1 (from matplotlib)
  Downloading python_dateutil-2.6.1-py2.py3-none-any.whl (194kB)
Collecting pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 (from matplotlib)
  Downloading pyparsing-2.2.0-py2.py3-none-any.whl (56kB)
Requirement already satisfied: six>=1.10 in /opt/conda/envs/pytorch-py35/lib/python3.5/site-packages (from matplotlib)
Collecting cycler>=0.10 (from matplotlib)
  Downloading cycler-0.10.0-py2.py3-none-any.whl
Collecting kiwisolver>=1.0.1 (from matplotlib)
  Downloading kiwisolver-1.0.1-cp35-cp35m-manylinux1_x86_64.whl (949kB)
Requirement already satisfied: numpy>=1.7.1 in /opt/conda/envs/pytorch-py35/lib/python3.5/site-packages (from matplotlib)
Requirement already satisfied: setuptools in /opt/conda/envs/pytorch-py35/lib/python3.5/site-packages/setuptools-27.2.0-py3.5.egg (from kiwisolver>=1.0.1->matplotlib)
Installing collected packages: pytz, python-dateutil, pyparsing, cycler, kiwisolver, matplotlib
Successfully installed cycler-0.10.0 kiwisolver-1.0.1 matplotlib-2.2.0 pyparsing-2.2.0 python-dateutil-2.6.1 pytz-2018.3

How to convert SQL Query result to PANDAS Data Structure?

Here is mine. Just in case if you are using "pymysql":

import pymysql
from pandas import DataFrame

host   = 'localhost'
port   = 3306
user   = 'yourUserName'
passwd = 'yourPassword'
db     = 'yourDatabase'

cnx    = pymysql.connect(host=host, port=port, user=user, passwd=passwd, db=db)
cur    = cnx.cursor()

query  = """ SELECT * FROM yourTable LIMIT 10"""
cur.execute(query)

field_names = [i[0] for i in cur.description]
get_data = [xx for xx in cur]

cur.close()
cnx.close()

df = DataFrame(get_data)
df.columns = field_names

How to set dialog to show in full screen?

dialog = new Dialog(getActivity(),android.R.style.Theme_Translucent_NoTitleBar);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.loading_screen);
    Window window = dialog.getWindow();
    WindowManager.LayoutParams wlp = window.getAttributes();

    wlp.gravity = Gravity.CENTER;
    wlp.flags &= ~WindowManager.LayoutParams.FLAG_BLUR_BEHIND;
    window.setAttributes(wlp);
    dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    dialog.show();

try this.

Clear a terminal screen for real

I know the solution employing printing of new lines isn't much supported, but if all else fails, why not? Especially where one is operating in an environment where someone else is likely to be able to see the screen, yet not able to keylog. One potential solution then, is the following alias:

alias c="printf '\r\n%.0s' {1..50}"

Then, to "clear" away the current contents of the screen (or rather, hide them), just type c+Enter at the terminal.

Simple way to calculate median with MySQL

In some cases median gets calculated as follows :

The "median" is the "middle" value in the list of numbers when they are ordered by value. For even count sets, median is average of the two middle values. I've created a simple code for that :

$midValue = 0;
$rowCount = "SELECT count(*) as count {$from} {$where}";

$even = FALSE;
$offset = 1;
$medianRow = floor($rowCount / 2);
if ($rowCount % 2 == 0 && !empty($medianRow)) {
  $even = TRUE;
  $offset++;
  $medianRow--;
}

$medianValue = "SELECT column as median 
               {$fromClause} {$whereClause} 
               ORDER BY median 
               LIMIT {$medianRow},{$offset}";

$medianValDAO = db_query($medianValue);
while ($medianValDAO->fetch()) {
  if ($even) {
    $midValue = $midValue + $medianValDAO->median;
  }
  else {
    $median = $medianValDAO->median;
  }
}
if ($even) {
  $median = $midValue / 2;
}
return $median;

The $median returned would be the required result :-)

Call a function from another file?

Functions from .py file (can (of course) be in different directory) can be simply imported by writing directories first and then the file name without .py extension:

from directory_name.file_name import function_name

And later be used: function_name()

Twitter Bootstrap: div in container with 100% height

Update 2019

In Bootstrap 4, flexbox can be used to get a full height layout that fills the remaining space.

First of all, the container (parent) needs to be full height:

Option 1_ Add a class for min-height: 100%;. Remember that min-height will only work if the parent has a defined height:

html, body {
  height: 100%;
}

.min-100 {
    min-height: 100%;
}

https://codeply.com/go/dTaVyMah1U

Option 2_ Use vh units:

.vh-100 {
    min-height: 100vh;
}

https://codeply.com/go/kMahVdZyGj

Also of Bootstrap 4.1, the vh-100 and min-vh-100 classes are included in Bootstrap so there is no need to for the extra CSS

Then, use flexbox direction column d-flex flex-column on the container, and flex-grow-1 on any child divs (ie: row) that you want to fill the remaining height.

Also see:
Bootstrap 4 Navbar and content fill height flexbox
Bootstrap - Fill fluid container between header and footer
How to make the row stretch remaining height

Convert output of MySQL query to utf8

Addition:

When using the MySQL client library, then you should prevent a conversion back to your connection's default charset. (see mysql_set_character_set()[1])

In this case, use an additional cast to binary:

SELECT column1, CAST(CONVERT(column2 USING utf8) AS binary)
FROM my_table
WHERE my_condition;

Otherwise, the SELECT statement converts to utf-8, but your client library converts it back to a (potentially different) default connection charset.

How to iterate through range of Dates in Java?

Well, you could do something like this using Java 8's time-API, for this problem specifically java.time.LocalDate (or the equivalent Joda Time classes for Java 7 and older)

for (LocalDate date = startDate; date.isBefore(endDate); date = date.plusDays(1))
{
    ...
}

I would thoroughly recommend using java.time (or Joda Time) over the built-in Date/Calendar classes.

Arithmetic overflow error converting numeric to data type numeric

My guess is that you're trying to squeeze a number greater than 99999.99 into your decimal fields. Changing it to (8,3) isn't going to do anything if it's greater than 99999.999 - you need to increase the number of digits before the decimal. You can do this by increasing the precision (which is the total number of digits before and after the decimal). You can leave the scale the same unless you need to alter how many decimal places to store. Try decimal(9,2) or decimal(10,2) or whatever.

You can test this by commenting out the insert #temp and see what numbers the select statement is giving you and see if they are bigger than your column can handle.

gpg: no valid OpenPGP data found

By executing the following command, it will save a jenkins-ci.org.key file in the current working directory:

curl -O http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key

Then use the following command to add the key file:

apt-key add jenkins-ci.org.key

If the system returns OK, then the key file has been successfully added.

Get first day of week in SQL Server

For the basic (the current week's Sunday)

select cast(dateadd(day,-(datepart(dw,getdate())-1),getdate()) as date)

If previous week:

select cast(dateadd(day,-(datepart(dw,getdate())-1),getdate()) -7 as date)

Internally, we built a function that does it but if you need quick and dirty, this will do it.

Command to escape a string in bash

It may not be quite what you want, since it's not a standard command on anyone's systems, but since my program should work fine on POSIX systems (if compiled), I'll mention it anyway. If you have the ability to compile or add programs on the machine in question, it should work.

I've used it without issue for about a year now, but it could be that it won't handle some edge cases. Most specifically, I have no idea what it would do with newlines in strings; a case for \\n might need to be added. This list of characters is not authoritative, but I believe it covers everything else.

I wrote this specifically as a 'helper' program so I could make a wrapper for things like scp commands.

It can likely be implemented as a shell function as well

I therefore present escapify.c. I use it like so:

scp user@host:"$(escapify "/this/path/needs to be escaped/file.c")" destination_file.c

PLEASE NOTE: I made this program for my own personal use. It also will (probably wrongly) assume that if it is given more than one argument that it should just print an unescaped space and continue on. This means that it can be used to pass multiple escaped arguments correctly, but could be seen as unwanted behavior by some.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
  char c='\0';
  int i=0;
  int j=1;
  /* do not care if no args passed; escaped nothing is still nothing. */
  if(argc < 2)
  {
    return 0;
  }
  while(j<argc)
  {
    while(i<strlen(argv[j]))
    {
      c=argv[j][i];
      /* this switch has no breaks on purpose. */
      switch(c)
      {
      case ';':
      case '\'':
      case ' ':
      case '!':
      case '"':
      case '#':
      case '$':
      case '&':
      case '(':
      case ')':
      case '|':
      case '*':
      case ',':
      case '<':
      case '>':
      case '[':
      case ']':
      case '\\':
      case '^':
      case '`':
      case '{':
      case '}':
        putchar('\\');
      default:
        putchar(c);
      }
      i++;
    }
    j++;
    if(j<argc) {
      putchar(' ');
    }
    i=0;
  }
  /* newline at end */
  putchar ('\n');
  return 0;
}

True and False for && logic and || Logic table

Truth values can be described using a Boolean algebra. The article also contains tables for and and or. This should help you to get started or to get even more confused.

PHP how to get the base domain/url?

Use SERVER_NAME.

echo $_SERVER['SERVER_NAME']; //Outputs www.example.com

How to get the current URL within a Django template?

The below code helps me:

 {{ request.build_absolute_uri }}

make iframe height dynamic based on content inside- JQUERY/Javascript

I found that the accepted answer didn't suffice, since X-FRAME-OPTIONS: Allow-From isn't supported in safari or chrome. Went with a different approach instead, found in a presentation given by Ben Vinegar from Disqus. The idea is to add an event listener to the parent window, and then inside the iframe, use window.postMessage to send an event to the parent telling it to do something (resize the iframe).

So in the parent document, add an event listener:

window.addEventListener('message', function(e) {
  var $iframe = jQuery("#myIframe");
  var eventName = e.data[0];
  var data = e.data[1];
  switch(eventName) {
    case 'setHeight':
      $iframe.height(data);
      break;
  }
}, false);

And inside the iframe, write a function to post the message:

function resize() {
  var height = document.getElementsByTagName("html")[0].scrollHeight;
  window.parent.postMessage(["setHeight", height], "*"); 
}

Finally, inside the iframe, add an onLoad to the body tag to fire the resize function:

<body onLoad="resize();">

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

I've the same message, I have a webpage with do on visual studio 2010, I read a file.xls on that page,in my project visual has not any problem, when I put it on my IIS local throw me a 'Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine' ,I fixed that problem next following this steps,

1.-Open IIS
2.-Change the appPool on Advanced Settings
3.-true to enable to 32-bit application.

and that's all

ps.I changed Configuration Manager to X86 on Active Solution Platform

Get data from JSON file with PHP

Use json_decode to transform your JSON into a PHP array. Example:

$json = '{"a":"b"}';
$array = json_decode($json, true);
echo $array['a']; // b

How do I make a placeholder for a 'select' box?

I'm not content with HTML/CSS-only solutions, so I've decided to create a custom select using JavaScript.

This is something I've written in the past 30 mins, thus it can be further improved.

All you have to do is create a simple list with few data attributes. The code automatically turns the list into a selectable dropdown. It also adds a hidden input to hold the selected value, so it can be used in a form.

Input:

<ul class="select" data-placeholder="Role" data-name="role">
  <li data-value="admin">Administrator</li>
  <li data-value="mod">Moderator</li>
  <li data-value="user">User</li>
</ul>

Output:

<div class="ul-select-container">
    <input type="hidden" name="role" class="hidden">
    <div class="selected placeholder">
        <span class="text">Role</span>
        <span class="icon">?</span>
    </div>
    <ul class="select" data-placeholder="Role" data-name="role">
        <li class="placeholder">Role</li>
        <li data-value="admin">Administrator</li>
        <li data-value="mod">Moderator</li>
        <li data-value="user">User</li>
    </ul>
</div>

The text of the item that's supposed to be a placeholder is grayed out. The placeholder is selectable, in case the user wants to revert his/her choice. Also using CSS, all the drawbacks of select can be overcome (e.g., inability of the styling of the options).

_x000D_
_x000D_
// Helper function to create elements faster/easier_x000D_
// https://github.com/akinuri/js-lib/blob/master/element.js_x000D_
var elem = function(tagName, attributes, children, isHTML) {_x000D_
  let parent;_x000D_
  if (typeof tagName == "string") {_x000D_
    parent = document.createElement(tagName);_x000D_
  } else if (tagName instanceof HTMLElement) {_x000D_
    parent = tagName;_x000D_
  }_x000D_
  if (attributes) {_x000D_
    for (let attribute in attributes) {_x000D_
      parent.setAttribute(attribute, attributes[attribute]);_x000D_
    }_x000D_
  }_x000D_
  var isHTML = isHTML || null;_x000D_
  if (children || children == 0) {_x000D_
    elem.append(parent, children, isHTML);_x000D_
  }_x000D_
  return parent;_x000D_
};_x000D_
elem.append = function(parent, children, isHTML) {_x000D_
  if (parent instanceof HTMLTextAreaElement || parent instanceof HTMLInputElement) {_x000D_
    if (children instanceof Text || typeof children == "string" || typeof children == "number") {_x000D_
      parent.value = children;_x000D_
    } else if (children instanceof Array) {_x000D_
      children.forEach(function(child) {_x000D_
        elem.append(parent, child);_x000D_
      });_x000D_
    } else if (typeof children == "function") {_x000D_
      elem.append(parent, children());_x000D_
    }_x000D_
  } else {_x000D_
    if (children instanceof HTMLElement || children instanceof Text) {_x000D_
      parent.appendChild(children);_x000D_
    } else if (typeof children == "string" || typeof children == "number") {_x000D_
      if (isHTML) {_x000D_
        parent.innerHTML += children;_x000D_
      } else {_x000D_
        parent.appendChild(document.createTextNode(children));_x000D_
      }_x000D_
    } else if (children instanceof Array) {_x000D_
      children.forEach(function(child) {_x000D_
        elem.append(parent, child);_x000D_
      });_x000D_
    } else if (typeof children == "function") {_x000D_
      elem.append(parent, children());_x000D_
    }_x000D_
  }_x000D_
};_x000D_
_x000D_
_x000D_
// Initialize all selects on the page_x000D_
$("ul.select").each(function() {_x000D_
  var parent    = this.parentElement;_x000D_
  var refElem   = this.nextElementSibling;_x000D_
  var container = elem("div", {"class": "ul-select-container"});_x000D_
  var hidden    = elem("input", {"type": "hidden", "name": this.dataset.name, "class": "hidden"});_x000D_
  var selected  = elem("div", {"class": "selected placeholder"}, [_x000D_
    elem("span", {"class": "text"}, this.dataset.placeholder),_x000D_
    elem("span", {"class": "icon"}, "&#9660;", true),_x000D_
  ]);_x000D_
  var placeholder = elem("li", {"class": "placeholder"}, this.dataset.placeholder);_x000D_
  this.insertBefore(placeholder, this.children[0]);_x000D_
  container.appendChild(hidden);_x000D_
  container.appendChild(selected);_x000D_
  container.appendChild(this);_x000D_
  parent.insertBefore(container, refElem);_x000D_
});_x000D_
_x000D_
// Update necessary elements with the selected option_x000D_
$(".ul-select-container ul li").on("click", function() {_x000D_
  var text     = this.innerText;_x000D_
  var value    = this.dataset.value || "";_x000D_
  var selected = this.parentElement.previousElementSibling;_x000D_
  var hidden   = selected.previousElementSibling;_x000D_
  hidden.value = selected.dataset.value = value;_x000D_
  selected.children[0].innerText = text;_x000D_
  if (this.classList.contains("placeholder")) {_x000D_
    selected.classList.add("placeholder");_x000D_
  } else {_x000D_
    selected.classList.remove("placeholder");_x000D_
  }_x000D_
  selected.parentElement.classList.remove("visible");_x000D_
});_x000D_
_x000D_
// Open select dropdown_x000D_
$(".ul-select-container .selected").on("click", function() {_x000D_
  if (this.parentElement.classList.contains("visible")) {_x000D_
    this.parentElement.classList.remove("visible");_x000D_
  } else {_x000D_
    this.parentElement.classList.add("visible");_x000D_
  }_x000D_
});_x000D_
_x000D_
// Close select when focus is lost_x000D_
$(document).on("click", function(e) {_x000D_
  var container = $(e.target).closest(".ul-select-container");_x000D_
  if (container.length == 0) {_x000D_
    $(".ul-select-container.visible").removeClass("visible");_x000D_
  }_x000D_
});
_x000D_
.ul-select-container {_x000D_
  width: 200px;_x000D_
  display: table;_x000D_
  position: relative;_x000D_
  margin: 1em 0;_x000D_
}_x000D_
.ul-select-container.visible ul {_x000D_
  display: block;_x000D_
  padding: 0;_x000D_
  list-style: none;_x000D_
  margin: 0;_x000D_
}_x000D_
.ul-select-container ul {_x000D_
  background-color: white;_x000D_
  border: 1px solid hsla(0, 0%, 60%);_x000D_
  border-top: none;_x000D_
  -webkit-user-select: none;_x000D_
  display: none;_x000D_
  position: absolute;_x000D_
  width: 100%;_x000D_
  z-index: 999;_x000D_
}_x000D_
.ul-select-container ul li {_x000D_
  padding: 2px 5px;_x000D_
}_x000D_
.ul-select-container ul li.placeholder {_x000D_
  opacity: 0.5;_x000D_
}_x000D_
.ul-select-container ul li:hover {_x000D_
  background-color: dodgerblue;_x000D_
  color: white;_x000D_
}_x000D_
.ul-select-container ul li.placeholder:hover {_x000D_
  background-color: rgba(0, 0, 0, .1);_x000D_
  color: initial;_x000D_
}_x000D_
.ul-select-container .selected {_x000D_
  background-color: white;_x000D_
  padding: 3px 10px 4px;_x000D_
  padding: 2px 5px;_x000D_
  border: 1px solid hsla(0, 0%, 60%);_x000D_
  -webkit-user-select: none;_x000D_
}_x000D_
.ul-select-container .selected {_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.ul-select-container .selected.placeholder .text {_x000D_
  color: rgba(0, 0, 0, .5);_x000D_
}_x000D_
.ul-select-container .selected .icon {_x000D_
  font-size: .7em;_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
  opacity: 0.8;_x000D_
}_x000D_
.ul-select-container:hover .selected {_x000D_
  border: 1px solid hsla(0, 0%, 30%);_x000D_
}_x000D_
.ul-select-container:hover .selected .icon {_x000D_
  opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<ul class="select" data-placeholder="Role" data-name="role">_x000D_
  <li data-value="admin">Administrator</li>_x000D_
  <li data-value="mod">Moderator</li>_x000D_
  <li data-value="user">User</li>_x000D_
</ul>_x000D_
_x000D_
<ul class="select" data-placeholder="Sex" data-name="sex">_x000D_
  <li data-value="male">Male</li>_x000D_
  <li data-value="female">Female</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_


Update: I've improved this (selection using up/down/enter keys), tidied up the output a little bit, and turned this into a object. Current output:

<div class="li-select-container">
    <input type="text" readonly="" placeholder="Role" title="Role">
    <span class="arrow">?</span>
    <ul class="select">
        <li class="placeholder">Role</li>
        <li data-value="admin">Administrator</li>
        <li data-value="mod">Moderator</li>
        <li data-value="user">User</li>
    </ul>
</div>

Initialization:

new Liselect(document.getElementsByTagName("ul")[0]);

For further examination: JSFiddle, GitHub (renamed).


Update: I am have rewritten this again. Instead of using a list, we can just use a select. This way it'll work even without JavaScript (in case it's disabled).

Input:

<select name="role" data-placeholder="Role" required title="Role">
    <option value="admin">Administrator</option>
    <option value="mod">Moderator</option>
    <option>User</option>
</select>

new Advancelect(document.getElementsByTagName("select")[0]);

Output:

<div class="advanced-select">
    <input type="text" readonly="" placeholder="Role" title="Role" required="" name="role">
    <span class="arrow">?</span>
    <ul>
        <li class="placeholder">Role</li>
        <li data-value="admin">Administrator</li>
        <li data-value="mod">Moderator</li>
        <li>User</li>
    </ul>
</div>

JSFiddle, GitHub.

batch/bat to copy folder and content at once

I've been interested in the original question here and related ones.

For an answer, this week I did some experiments with XCOPY.

To help answer the original question, here I post the results of my experiments.

I did the experiments on Windows 7 64 bit Professional SP1 with the copy of XCOPY that came with the operating system.

For the experiments, I wrote some code in the scripting language Open Object Rexx and the editor macro language Kexx with the text editor KEdit.

XCOPY was called from the Rexx code. The Kexx code edited the screen output of XCOPY to focus on the crucial results.

The experiments all had to do with using XCOPY to copy one directory with several files and subdirectories.

The experiments consisted of 10 cases. Each case adjusted the arguments to XCOPY and called XCOPY once. All 10 cases were attempting to do the same copying operation.

Here are the main results:

(1) Of the 10 cases, only three did copying. The other 7 cases right away, just from processing the arguments to XCOPY, gave error messages, e.g.,

Invalid path

Access denied

with no files copied.

Of the three cases that did copying, they all did the same copying, that is, gave the same results.

(2) If want to copy a directory X and all the files and directories in directory X, in the hierarchical file system tree rooted at directory X, then apparently XCOPY -- and this appears to be much of the original question -- just will NOT do that.

One consequence is that if using XCOPY to copy directory X and its contents, then CAN copy the contents but CANNOT copy the directory X itself; thus, lose the time-date stamp on directory X, its archive bit, data on ownership, attributes, etc.

Of course if directory X is a subdirectory of directory Y, an XCOPY of Y will copy all of the contents of directory Y WITH directory X. So in this way can get a copy of directory X. However, the copy of directory X will have its time-date stamp of the time of the run of XCOPY and NOT the time-date stamp of the original directory X.

This change in time-date stamps can be awkward for a copy of a directory with a lot of downloaded Web pages: The HTML file of the Web page will have its original time-date stamp, but the corresponding subdirectory for files used by the HTML file will have the time-date stamp of the run of XCOPY. So, when sorting the copy on time date stamps, all the subdirectories, the HTML files and the corresponding subdirectories, e.g.,

x.htm

x_files

can appear far apart in the sort on time-date.

Hierarchical file systems go way back, IIRC to Multics at MIT in 1969, and since then lots of people have recognized the two cases, given a directory X, (i) copy directory X and all its contents and (ii) copy all the contents of X but not directory X itself. Well, if only from the experiments, XCOPY does only (ii).

So, the results of the 10 cases are below. For each case, in the results the first three lines have the first three arguments to XCOPY. So, the first line has the tree name of the directory to be copied, the 'source'; the second line has the tree name of the directory to get the copies, the 'destination', and the third line has the options for XCOPY. The remaining 1-2 lines have the results of the run of XCOPY.

One big point about the options is that options /X and /O result in result

Access denied

To see this, compare case 8 with the other cases that were the same, did not have /X and /O, but did copy.

These experiments have me better understand XCOPY and contribute an answer to the original question.

======= case 1 ==================
"k:\software\dir_time-date\"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_1\"
options = /E /F /G /H /K /O /R /V /X /Y
Result:  Invalid path
Result:  0 File(s) copied
======= case 2 ==================
"k:\software\dir_time-date\*"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_2\"
options = /E /F /G /H /K /O /R /V /X /Y
Result:  Access denied
Result:  0 File(s) copied
======= case 3 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_3\"
options = /E /F /G /H /K /O /R /V /X /Y
Result:  Access denied
Result:  0 File(s) copied
======= case 4 ==================
"k:\software\dir_time-date\"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_4\"
options = /E /F /G /H /K /R /V /Y
Result:  Invalid path
Result:  0 File(s) copied
======= case 5 ==================
"k:\software\dir_time-date\"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_5\"
options = /E /F /G /H /K /O /R /S /X /Y
Result:  Invalid path
Result:  0 File(s) copied
======= case 6 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_6\"
options = /E /F /G /H /I /K /O /R /S /X /Y
Result:  Access denied
Result:  0 File(s) copied
======= case 7 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_7"
options = /E /F /G /H /I /K /R /S /Y
Result:  20 File(s) copied
======= case 8 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_8"
options = /E /F /G /H /I /K /O /R /S /X /Y
Result:  Access denied
Result:  0 File(s) copied
======= case 9 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_9"
options = /I /S
Result:  20 File(s) copied
======= case 10 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_10"
options = /E /I /S
Result:  20 File(s) copied

How to set session attribute in java?

By default session object is available on jsp page(implicit object). It will not available in normal POJO java class. You can get the reference of HttpSession object on Servelt by using HttpServletRequest

HttpSession s=request.getSession()
s.setAttribute("name","value");

You can get session on an ActionSupport based Action POJO class as follows

 ActionContext ctx= ActionContext.getContext();
   Map m=ctx.getSession();
   m.put("name", value);

look at: http://ohmjavaclasses.blogspot.com/2011/12/access-session-in-action-class-struts2.html

Easiest way to make lua script wait/pause/sleep/block for a few seconds?

require 'alien'

if alien.platform == "windows" then
  kernel32 = alien.load("kernel32.dll")
  sleep = kernel32.Sleep
  sleep:types{ret="void",abi="stdcall","uint"}
else
  -- untested !!!
  libc = alien.default
  local usleep = libc.usleep
  usleep:types('int', 'uint')
  sleep = function(ms)
    while ms > 1000 do
      usleep(1000)
      ms = ms - 1000
    end
    usleep(1000 * ms)
  end
end 

print('hello')
sleep(500)  -- sleep 500 ms
print('world')

increase font size of hyperlink text html

you can add class in anchor tag also like below

.a_class {font-size: 100px} 

Download image with JavaScript

As @Ian explained, the problem is that jQuery's click() is not the same as the native one.

Therefore, consider using vanilla-js instead of jQuery:

var a = document.createElement('a');
a.href = "img.png";
a.download = "output.png";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);

Demo

Linq select object from list depending on objects attribute

I assume you are getting an exception because of Single. Your list may have more than one answer marked as correct, that is why Single will throw an exception use First, or FirstOrDefault();

Answer answer = Answers.FirstOrDefault(a => a.Correct);

Also if you want to get list of all items marked as correct you may try:

List<Answer> correctedAnswers =  Answers.Where(a => a.Correct).ToList();

If your desired result is Single, then the mistake you are doing in your query is comparing an item with the bool value. Your comparison

a == a.Correct

is wrong in the statement. Your single query should be:

Answer answer = Answers.Single(a => a.Correct == true);

Or shortly as:

Answer answer = Answers.Single(a => a.Correct);

How to remove all white space from the beginning or end of a string?

String.Trim() returns a string which equals the input string with all white-spaces trimmed from start and end:

"   A String   ".Trim() -> "A String"

String.TrimStart() returns a string with white-spaces trimmed from the start:

"   A String   ".TrimStart() -> "A String   "

String.TrimEnd() returns a string with white-spaces trimmed from the end:

"   A String   ".TrimEnd() -> "   A String"

None of the methods modify the original string object.

(In some implementations at least, if there are no white-spaces to be trimmed, you get back the same string object you started with:

csharp> string a = "a"; csharp> string trimmed = a.Trim(); csharp> (object) a == (object) trimmed; returns true

I don't know whether this is guaranteed by the language.)

Calculating Covariance with Python and Numpy

Thanks to unutbu for the explanation. By default numpy.cov calculates the sample covariance. To obtain the population covariance you can specify normalisation by the total N samples like this:

Covariance = numpy.cov(a, b, bias=True)[0][1]
print(Covariance)

or like this:

Covariance = numpy.cov(a, b, ddof=0)[0][1]
print(Covariance)

Access iframe elements in JavaScript

Make sure your iframe is already loaded. Old but reliable way without jQuery:

<iframe src="samedomain.com/page.htm" id="iframe" onload="access()"></iframe>

<script>
function access() {
   var iframe = document.getElementById("iframe");
   var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
   console.log(innerDoc.body);
}
</script>

Python: Is there an equivalent of mid, right, and left from BASIC?

There are built-in functions in Python for "right" and "left", if you are looking for a boolean result.

str = "this_is_a_test"
left = str.startswith("this")
print(left)
> True

right = str.endswith("test")
print(right)
> True

Convert command line argument to string

I'm not sure if this is 100% portable but the way the OS SHOULD parse the args is to scan through the console command string and insert a nil-term char at the end of each token, and int main(int,char**) doesn't use const char** so we can just iterate through the args starting from the third argument (@note the first arg is the working directory) and scan backward to the nil-term char and turn it into a space rather than start from beginning of the second argument and scanning forward to the nil-term char. Here is the function with test script, and if you do need to un-nil-ify more than one nil-term char then please comment so I can fix it; thanks.

#include <cstdio>
#include <iostream>

using namespace std;

namespace _ {
/* Converts int main(int,char**) arguments back into a string.
@return false if there are no args to convert.
@param arg_count The number of arguments.
@param args      The arguments. */
bool ArgsToString(int args_count, char** args) {
  if (args_count <= 1) return false;
  if (args_count == 2) return true;
  for (int i = 2; i < args_count; ++i) {
    char* cursor = args[i];
    while (*cursor) --cursor;
    *cursor = ' ';
  }
  return true;
}
}  // namespace _

int main(int args_count, char** args) {
  cout << "\n\nTesting ArgsToString...\n";

  if (args_count <= 1) return 1;
  cout << "\nArguments:\n";
  for (int i = 0; i < args_count; ++i) {
    char* arg = args[i];
    printf("\ni:%i\"%s\" 0x%p", i, arg, arg);
  }
  cout << "\n\nContiguous Args:\n";
  char* end = args[args_count - 1];
  while (*end) ++end;
  cout << "\n\nContiguous Args:\n";
  char* cursor = args[0];
  while (cursor != end) {
    char c = *cursor++;
    if (c == 0)
      cout << '`';
    else if (c < ' ')
      cout << '~';
    else
      cout << c;
  }
  cout << "\n\nPrinting argument string...\n";
  _::ArgsToString(args_count, args);
  cout << "\n" << args[1];
  return 0;
}

Functional programming vs Object Oriented programming

When do you choose functional programming over object oriented?

When you anticipate a different kind of software evolution:

  • Object-oriented languages are good when you have a fixed set of operations on things, and as your code evolves, you primarily add new things. This can be accomplished by adding new classes which implement existing methods, and the existing classes are left alone.

  • Functional languages are good when you have a fixed set of things, and as your code evolves, you primarily add new operations on existing things. This can be accomplished by adding new functions which compute with existing data types, and the existing functions are left alone.

When evolution goes the wrong way, you have problems:

  • Adding a new operation to an object-oriented program may require editing many class definitions to add a new method.

  • Adding a new kind of thing to a functional program may require editing many function definitions to add a new case.

This problem has been well known for many years; in 1998, Phil Wadler dubbed it the "expression problem". Although some researchers think that the expression problem can be addressed with such language features as mixins, a widely accepted solution has yet to hit the mainstream.

What are the typical problem definitions where functional programming is a better choice?

Functional languages excel at manipulating symbolic data in tree form. A favorite example is compilers, where source and intermediate languages change seldom (mostly the same things), but compiler writers are always adding new translations and code improvements or optimizations (new operations on things). Compilation and translation more generally are "killer apps" for functional languages.

How to programmatically close a JFrame

If by Alt-F4 or X you mean "Exit the Application Immediately Without Regard for What Other Windows or Threads are Running", then System.exit(...) will do exactly what you want in a very abrupt, brute-force, and possibly problematic fashion.

If by Alt-F4 or X you mean hide the window, then frame.setVisible(false) is how you "close" the window. The window will continue to consume resources/memory but can be made visible again very quickly.

If by Alt-F4 or X you mean hide the window and dispose of any resources it is consuming, then frame.dispose() is how you "close" the window. If the frame was the last visible window and there are no other non-daemon threads running, the program will exit. If you show the window again, it will have to reinitialize all of the native resources again (graphics buffer, window handles, etc).

dispose() might be closest to the behavior that you really want. If your app has multiple windows open, do you want Alt-F4 or X to quit the app or just close the active window?

The Java Swing Tutorial on Window Listeners may help clarify things for you.

Laravel 5.5 ajax call 419 (unknown status)

This error also happens if u forgot to include this, in your ajax submission request ( POST ), contentType: false, processData: false,

How to query DATETIME field using only date in Microsoft SQL Server?

select * from invoice where TRANS_DATE_D>= to_date  ('20170831115959','YYYYMMDDHH24MISS')
and TRANS_DATE_D<= to_date  ('20171031115959','YYYYMMDDHH24MISS');

What is a good pattern for using a Global Mutex in C#?

I want to make sure this is out there, because it's so hard to get right:

using System.Runtime.InteropServices;   //GuidAttribute
using System.Reflection;                //Assembly
using System.Threading;                 //Mutex
using System.Security.AccessControl;    //MutexAccessRule
using System.Security.Principal;        //SecurityIdentifier

static void Main(string[] args)
{
    // get application GUID as defined in AssemblyInfo.cs
    string appGuid =
        ((GuidAttribute)Assembly.GetExecutingAssembly().
            GetCustomAttributes(typeof(GuidAttribute), false).
                GetValue(0)).Value.ToString();

    // unique id for global mutex - Global prefix means it is global to the machine
    string mutexId = string.Format( "Global\\{{{0}}}", appGuid );

    // Need a place to store a return value in Mutex() constructor call
    bool createdNew;

    // edited by Jeremy Wiebe to add example of setting up security for multi-user usage
    // edited by 'Marc' to work also on localized systems (don't use just "Everyone") 
    var allowEveryoneRule =
        new MutexAccessRule( new SecurityIdentifier( WellKnownSidType.WorldSid
                                                   , null)
                           , MutexRights.FullControl
                           , AccessControlType.Allow
                           );
    var securitySettings = new MutexSecurity();
    securitySettings.AddAccessRule(allowEveryoneRule);

   // edited by MasonGZhwiti to prevent race condition on security settings via VanNguyen
    using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings))
    {
        // edited by acidzombie24
        var hasHandle = false;
        try
        {
            try
            {
                // note, you may want to time out here instead of waiting forever
                // edited by acidzombie24
                // mutex.WaitOne(Timeout.Infinite, false);
                hasHandle = mutex.WaitOne(5000, false);
                if (hasHandle == false)
                    throw new TimeoutException("Timeout waiting for exclusive access");
            }
            catch (AbandonedMutexException)
            {
                // Log the fact that the mutex was abandoned in another process,
                // it will still get acquired
                hasHandle = true;
            }

            // Perform your work here.
        }
        finally
        {
            // edited by acidzombie24, added if statement
            if(hasHandle)
                mutex.ReleaseMutex();
        }
    }
}

Google Map API v3 ~ Simply Close an infowindow?

We can use infowindow.close(map); to close all info windows if you already initialize the info window using infowindow = new google.maps.InfoWindow();

.do extension in web pages?

".do" is the "standard" extension mapped to for Struts Java platform. See http://struts.apache.org/ .

CSS table column autowidth

You could specify the width of all but the last table cells and add a table-layout:fixed and a width to the table.

You could set

table tr ul.actions {margin: 0; white-space:nowrap;}

(or set this for the last TD as Sander suggested instead).

This forces the inline-LIs not to break. Unfortunately this does not lead to a new width calculation in the containing UL (and this parent TD), and therefore does not autosize the last TD.

This means: if an inline element has no given width, a TD's width is always computed automatically first (if not specified). Then its inline content with this calculated width gets rendered and the white-space-property is applied, stretching its content beyond the calculated boundaries.

So I guess it's not possible without having an element within the last TD with a specific width.

List of <p:ajax> events

Here's what I found during debug.

enter image description here

How to find the duration of difference between two dates in java?

Here is how the problem can solved in Java 8 just like the answer by shamimz.

Source : http://docs.oracle.com/javase/tutorial/datetime/iso/period.html

LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1960, Month.JANUARY, 1);

Period p = Period.between(birthday, today);
long p2 = ChronoUnit.DAYS.between(birthday, today);

System.out.println("You are " + p.getYears() + " years, " + p.getMonths() + " months, and " + p.getDays() + " days old. (" + p2 + " days total)");

The code produces output similar to the following:

You are 53 years, 4 months, and 29 days old. (19508 days total)

We have to use LocalDateTime http://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html to get hour,minute,second differences.

Adding an identity to an existing column

Basically there are four logical steps.

  1. Create a new Identity column. Turn on Insert Identity for this new column.

  2. Insert the data from the source column (the column you wished to convert to Identity) to this new column.

  3. Turn off the Insert Identity for the new column.

  4. Drop your source column & rename the new column to the name of the source column.

There may be some more complexities like working across multiple servers etc.

Please refer the following article for the steps (using ssms & T-sql). These steps are intended for beginners with less grip on T-SQL.

http://social.technet.microsoft.com/wiki/contents/articles/23816.how-to-convert-int-column-to-identity-in-the-ms-sql-server.aspx

CodeIgniter: Unable to connect to your database server using the provided settings Error Message

Change $db['default']['dbdriver'] = 'mysql' to $db['default']['dbdriver'] = 'mysqli'

How to [recursively] Zip a directory in PHP?

Yet another recursive directory tree archiving, implemented as an extension to ZipArchive. As a bonus, a single-statement tree compression helper function is included. Optional localname is supported, as in other ZipArchive functions. Error handling code to be added...

class ExtendedZip extends ZipArchive {

    // Member function to add a whole file system subtree to the archive
    public function addTree($dirname, $localname = '') {
        if ($localname)
            $this->addEmptyDir($localname);
        $this->_addTree($dirname, $localname);
    }

    // Internal function, to recurse
    protected function _addTree($dirname, $localname) {
        $dir = opendir($dirname);
        while ($filename = readdir($dir)) {
            // Discard . and ..
            if ($filename == '.' || $filename == '..')
                continue;

            // Proceed according to type
            $path = $dirname . '/' . $filename;
            $localpath = $localname ? ($localname . '/' . $filename) : $filename;
            if (is_dir($path)) {
                // Directory: add & recurse
                $this->addEmptyDir($localpath);
                $this->_addTree($path, $localpath);
            }
            else if (is_file($path)) {
                // File: just add
                $this->addFile($path, $localpath);
            }
        }
        closedir($dir);
    }

    // Helper function
    public static function zipTree($dirname, $zipFilename, $flags = 0, $localname = '') {
        $zip = new self();
        $zip->open($zipFilename, $flags);
        $zip->addTree($dirname, $localname);
        $zip->close();
    }
}

// Example
ExtendedZip::zipTree('/foo/bar', '/tmp/archive.zip', ZipArchive::CREATE);

How can I use if/else in a dictionary comprehension?

You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

The final if clause acts as a filter, which is different from having the conditional expression.


Worth mentioning that you don't need to have an if-else condition for both the key and the value. For example, {(a if condition else b): value for key, value in dict.items()} will work.

VBA Check if variable is empty

How you test depends on the Property's DataType:

| Type                                 | Test                            | Test2
| Numeric (Long, Integer, Double etc.) | If obj.Property = 0 Then        | 
| Boolen (True/False)                  | If Not obj.Property Then        | If obj.Property = False Then
| Object                               | If obj.Property Is Nothing Then |
| String                               | If obj.Property = "" Then       | If LenB(obj.Property) = 0 Then
| Variant                              | If obj.Property = Empty Then    |

You can tell the DataType by pressing F2 to launch the Object Browser and looking up the Object. Another way would be to just use the TypeName function:MsgBox TypeName(obj.Property)

Am I trying to connect to a TLS-enabled daemon without TLS?

Make sure the Docker daemon is running:

service docker start

That fixed it for me!

error TS2339: Property 'x' does not exist on type 'Y'

Starting with TypeScript 2.2 using dot notation to access indexed properties is allowed. You won't get error TS2339 on your example.

See Dotted property for types with string index signatures in TypeScript 2.2 release note.

How to stop tracking and ignore changes to a file in Git?

If you do git update-index --assume-unchanged file.csproj, git won't check file.csproj for changes automatically: that will stop them coming up in git status whenever you change them. So you can mark all your .csproj files this way- although you'll have to manually mark any new ones that the upstream repo sends you. (If you have them in your .gitignore or .git/info/exclude, then ones you create will be ignored)

I'm not entirely sure what .csproj files are... if they're something along the lines of IDE configurations (similar to Eclipse's .eclipse and .classpath files) then I'd suggest they should simply never be source-controlled at all. On the other hand, if they're part of the build system (like Makefiles) then clearly they should--- and a way to pick up optional local changes (e.g. from a local.csproj a la config.mk) would be useful: divide the build up into global parts and local overrides.

postgresql - sql - count of `true` values

Simply convert boolean field to integer and do a sum. This will work on postgresql :

select sum(myCol::int) from <table name>

Hope that helps!

JavaScript - get the first day of the week from current date

Good evening,

I prefer to just have a simple extension method:

Date.prototype.startOfWeek = function (pStartOfWeek) {
    var mDifference = this.getDay() - pStartOfWeek;

    if (mDifference < 0) {
        mDifference += 7;
    }

    return new Date(this.addDays(mDifference * -1));
}

You'll notice this actually utilizes another extension method that I use:

Date.prototype.addDays = function (pDays) {
    var mDate = new Date(this.valueOf());
    mDate.setDate(mDate.getDate() + pDays);
    return mDate;
};

Now, if your weeks start on Sunday, pass in a "0" for the pStartOfWeek parameter, like so:

var mThisSunday = new Date().startOfWeek(0);

Similarly, if your weeks start on Monday, pass in a "1" for the pStartOfWeek parameter:

var mThisMonday = new Date().startOfWeek(1);

Regards,

Giving UIView rounded corners

You can also use an image:

UIImage *maskingImage = [UIImage imageNamed:@"bannerBarBottomMask.png"];
CALayer *maskingLayer = [CALayer layer];
maskingLayer.frame = CGRectMake(-(self.yourView.frame.size.width - self.yourView.frame.size.width) / 2
                                , 0
                                , maskingImage.size.width
                                , maskingImage.size.height);
[maskingLayer setContents:(id)[maskingImage CGImage]];
[self.yourView.layer setMask:maskingLayer];

Appending the same string to a list of strings in Python

Updating with more options

list1 = ['foo', 'fob', 'faz', 'funk']
addstring = 'bar'
for index, value in enumerate(list1):
    list1[index] = addstring + value #this will prepend the string
    #list1[index] = value + addstring this will append the string

Avoid using keywords as variables like 'list', renamed 'list' as 'list1' instead

How to run cron once, daily at 10pm

Here are some more examples

  • Run every 6 hours at 46 mins past the hour:

    46 */6 * * *

  • Run at 2:10 am:

    10 2 * * *

  • Run at 3:15 am:

    15 3 * * *

  • Run at 4:20 am:

    20 4 * * *

  • Run at 5:31 am:

    31 5 * * *

  • Run at 5:31 pm:

    31 17 * * *

Using the Jersey client to do a POST operation

If you need to do a file upload, you'll need to use MediaType.MULTIPART_FORM_DATA_TYPE. Looks like MultivaluedMap cannot be used with that so here's a solution with FormDataMultiPart.

InputStream stream = getClass().getClassLoader().getResourceAsStream(fileNameToUpload);

FormDataMultiPart part = new FormDataMultiPart();
part.field("String_key", "String_value");
part.field("fileToUpload", stream, MediaType.TEXT_PLAIN_TYPE);
String response = WebResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(String.class, part);

convert a list of objects from one type to another using lambda expression

If you need to use a function to cast:

var list1 = new List<Type1>();
var list2 = new List<Type2>();

list2 = list1.ConvertAll(x => myConvertFuntion(x));

Where my custom function is:

private Type2 myConvertFunction(Type1 obj){
   //do something to cast Type1 into Type2
   return new Type2();
}

Using Colormaps to set color of line in matplotlib

U may do as I have written from my deleted account (ban for new posts :( there was). Its rather simple and nice looking.

Im using 3-rd one of these 3 ones usually, also I wasny checking 1 and 2 version.

from matplotlib.pyplot import cm
import numpy as np

#variable n should be number of curves to plot (I skipped this earlier thinking that it is obvious when looking at picture - sorry my bad mistake xD): n=len(array_of_curves_to_plot)
#version 1:

color=cm.rainbow(np.linspace(0,1,n))
for i,c in zip(range(n),color):
   ax1.plot(x, y,c=c)

#or version 2: - faster and better:

color=iter(cm.rainbow(np.linspace(0,1,n)))
c=next(color)
plt.plot(x,y,c=c)

#or version 3:

color=iter(cm.rainbow(np.linspace(0,1,n)))
for i in range(n):
   c=next(color)
   ax1.plot(x, y,c=c)

example of 3:

Ship RAO of Roll vs Ikeda damping in function of Roll amplitude A44

Is it possible to return empty in react render function?

Slightly off-topic but if you ever needed a class-based component that never renders anything and you are happy to use some yet-to-be-standardised ES syntax, you might want to go:

render = () => null

This is basically an arrow method that currently requires the transform-class-properties Babel plugin. React will not let you define a component without the render function and this is the most concise form satisfying this requirement that I can think of.

I'm currently using this trick in a variant of ScrollToTop borrowed from the react-router documentation. In my case, there's only a single instance of the component and it doesn't render anything, so a short form of "render null" fits nice in there.

Take nth column in a text file

iirc :

cat filename.txt | awk '{ print $2 $4 }'

or, as mentioned in the comments :

awk '{ print $2 $4 }' filename.txt

Convert PEM to PPK file format

I used a trial version of ZOC Terminal Emulator and it worked. It readily accepts the Amazon's *.pem files.

The trick is though, that you need to specify "ec2-user" instead of "root" for the username - despite the example shown in the EC2 console, which is wrong! ;-)

How to input matrix (2D list) in Python?

no_of_rows = 3  # For n by n, and even works for n by m but just give no of rows
matrix = [[int(j) for j in input().split()] for i in range(n)]
print(matrix)

Difference between InvariantCulture and Ordinal string comparison

InvariantCulture

Uses a "standard" set of character orderings (a,b,c, ... etc.). This is in contrast to some specific locales, which may sort characters in different orders ('a-with-acute' may be before or after 'a', depending on the locale, and so on).

Ordinal

On the other hand, looks purely at the values of the raw byte(s) that represent the character.


There's a great sample at http://msdn.microsoft.com/en-us/library/e6883c06.aspx that shows the results of the various StringComparison values. All the way at the end, it shows (excerpted):

StringComparison.InvariantCulture:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)

StringComparison.Ordinal:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is greater than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)

You can see that where InvariantCulture yields (U+0069, U+0049, U+00131), Ordinal yields (U+0049, U+0069, U+00131).

Add column to SQL Server

Add new column to Table

ALTER TABLE [table]
ADD Column1 Datatype

E.g

ALTER TABLE [test]
ADD ID Int

If User wants to make it auto incremented then

ALTER TABLE [test]
ADD ID Int IDENTITY(1,1) NOT NULL

how to merge 200 csv files in Python

fout=open("out.csv","a")
for num in range(1,201):
    for line in open("sh"+str(num)+".csv"):
         fout.write(line)    
fout.close()

Powershell script to see currently logged in users (domain and machine) + status (active, idle, away)

There's no "simple command" to do that. You can write a function, or take your choice of several that are available online in various code repositories. I use this:

function get-loggedonuser ($computername){

#mjolinor 3/17/10

$regexa = '.+Domain="(.+)",Name="(.+)"$'
$regexd = '.+LogonId="(\d+)"$'

$logontype = @{
"0"="Local System"
"2"="Interactive" #(Local logon)
"3"="Network" # (Remote logon)
"4"="Batch" # (Scheduled task)
"5"="Service" # (Service account logon)
"7"="Unlock" #(Screen saver)
"8"="NetworkCleartext" # (Cleartext network logon)
"9"="NewCredentials" #(RunAs using alternate credentials)
"10"="RemoteInteractive" #(RDP\TS\RemoteAssistance)
"11"="CachedInteractive" #(Local w\cached credentials)
}

$logon_sessions = @(gwmi win32_logonsession -ComputerName $computername)
$logon_users = @(gwmi win32_loggedonuser -ComputerName $computername)

$session_user = @{}

$logon_users |% {
$_.antecedent -match $regexa > $nul
$username = $matches[1] + "\" + $matches[2]
$_.dependent -match $regexd > $nul
$session = $matches[1]
$session_user[$session] += $username
}


$logon_sessions |%{
$starttime = [management.managementdatetimeconverter]::todatetime($_.starttime)

$loggedonuser = New-Object -TypeName psobject
$loggedonuser | Add-Member -MemberType NoteProperty -Name "Session" -Value $_.logonid
$loggedonuser | Add-Member -MemberType NoteProperty -Name "User" -Value $session_user[$_.logonid]
$loggedonuser | Add-Member -MemberType NoteProperty -Name "Type" -Value $logontype[$_.logontype.tostring()]
$loggedonuser | Add-Member -MemberType NoteProperty -Name "Auth" -Value $_.authenticationpackage
$loggedonuser | Add-Member -MemberType NoteProperty -Name "StartTime" -Value $starttime

$loggedonuser
}

}

How to create and use resources in .NET

Well, after searching around and cobbling together various points from around StackOverflow (gee, I love this place already), most of the problems were already past this stage. I did manage to work out an answer to my problem though.

How to create a resource:

In my case, I want to create an icon. It's a similar process, no matter what type of data you want to add as a resource though.

  • Right click the project you want to add a resource to. Do this in the Solution Explorer. Select the "Properties" option from the list.
  • Click the "Resources" tab.
  • The first button along the top of the bar will let you select the type of resource you want to add. It should start on string. We want to add an icon, so click on it and select "Icons" from the list of options.
  • Next, move to the second button, "Add Resource". You can either add a new resource, or if you already have an icon already made, you can add that too. Follow the prompts for whichever option you choose.
  • At this point, you can double click the newly added resource to edit it. Note, resources also show up in the Solution Explorer, and double clicking there is just as effective.

How to use a resource:

Great, so we have our new resource and we're itching to have those lovely changing icons... How do we do that? Well, lucky us, C# makes this exceedingly easy.

There is a static class called Properties.Resources that gives you access to all your resources, so my code ended up being as simple as:

paused = !paused;
if (paused)
    notifyIcon.Icon = Properties.Resources.RedIcon;
else
    notifyIcon.Icon = Properties.Resources.GreenIcon;

Done! Finished! Everything is simple when you know how, isn't it?

Javascript geocoding from address to latitude and longitude numbers not working

The script tag to the api has changed recently. Use something like this to query the Geocoding API and get the JSON object back

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/geocode/json?address=THE_ADDRESS_YOU_WANT_TO_GEOCODE&key=YOUR_API_KEY"></script>

The address could be something like

1600+Amphitheatre+Parkway,+Mountain+View,+CA (URI Encoded; you should Google it. Very useful)

or simply

1600 Amphitheatre Parkway, Mountain View, CA

By entering this address https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY inside the browser, along with my API Key, I get back a JSON object which contains the Latitude & Longitude for the city of Moutain view, CA.

{"results" : [
  {
     "address_components" : [
        {
           "long_name" : "1600",
           "short_name" : "1600",
           "types" : [ "street_number" ]
        },
        {
           "long_name" : "Amphitheatre Parkway",
           "short_name" : "Amphitheatre Pkwy",
           "types" : [ "route" ]
        },
        {
           "long_name" : "Mountain View",
           "short_name" : "Mountain View",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "Santa Clara County",
           "short_name" : "Santa Clara County",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "California",
           "short_name" : "CA",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "United States",
           "short_name" : "US",
           "types" : [ "country", "political" ]
        },
        {
           "long_name" : "94043",
           "short_name" : "94043",
           "types" : [ "postal_code" ]
        }
     ],
     "formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
     "geometry" : {
        "location" : {
           "lat" : 37.4222556,
           "lng" : -122.0838589
        },
        "location_type" : "ROOFTOP",
        "viewport" : {
           "northeast" : {
              "lat" : 37.4236045802915,
              "lng" : -122.0825099197085
           },
           "southwest" : {
              "lat" : 37.4209066197085,
              "lng" : -122.0852078802915
           }
        }
     },
     "place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
     "types" : [ "street_address" ]
  }],"status" : "OK"}

Web Frameworks such like AngularJS allow us to perform these queries with ease.

How to upload files to server using JSP/Servlet?

HTML PAGE

<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="UploadServlet" method="post"
                        enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html> 

SERVLET FILE

// Import required java libraries
import java.io.*;
import java.util.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.*;

public class UploadServlet extends HttpServlet {

   private boolean isMultipart;
   private String filePath;
   private int maxFileSize = 50 * 1024;
   private int maxMemSize = 4 * 1024;
   private File file ;

   public void init( ){
      // Get the file location where it would be stored.
      filePath = 
             getServletContext().getInitParameter("file-upload"); 
   }
   public void doPost(HttpServletRequest request, 
               HttpServletResponse response)
              throws ServletException, java.io.IOException {
      // Check that we have a file upload request
      isMultipart = ServletFileUpload.isMultipartContent(request);
      response.setContentType("text/html");
      java.io.PrintWriter out = response.getWriter( );
      if( !isMultipart ){
         out.println("<html>");
         out.println("<head>");
         out.println("<title>Servlet upload</title>");  
         out.println("</head>");
         out.println("<body>");
         out.println("<p>No file uploaded</p>"); 
         out.println("</body>");
         out.println("</html>");
         return;
      }
      DiskFileItemFactory factory = new DiskFileItemFactory();
      // maximum size that will be stored in memory
      factory.setSizeThreshold(maxMemSize);
      // Location to save data that is larger than maxMemSize.
      factory.setRepository(new File("c:\\temp"));

      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);
      // maximum file size to be uploaded.
      upload.setSizeMax( maxFileSize );

      try{ 
      // Parse the request to get file items.
      List fileItems = upload.parseRequest(request);

      // Process the uploaded file items
      Iterator i = fileItems.iterator();

      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet upload</title>");  
      out.println("</head>");
      out.println("<body>");
      while ( i.hasNext () ) 
      {
         FileItem fi = (FileItem)i.next();
         if ( !fi.isFormField () )  
         {
            // Get the uploaded file parameters
            String fieldName = fi.getFieldName();
            String fileName = fi.getName();
            String contentType = fi.getContentType();
            boolean isInMemory = fi.isInMemory();
            long sizeInBytes = fi.getSize();
            // Write the file
            if( fileName.lastIndexOf("\\") >= 0 ){
               file = new File( filePath + 
               fileName.substring( fileName.lastIndexOf("\\"))) ;
            }else{
               file = new File( filePath + 
               fileName.substring(fileName.lastIndexOf("\\")+1)) ;
            }
            fi.write( file ) ;
            out.println("Uploaded Filename: " + fileName + "<br>");
         }
      }
      out.println("</body>");
      out.println("</html>");
   }catch(Exception ex) {
       System.out.println(ex);
   }
   }
   public void doGet(HttpServletRequest request, 
                       HttpServletResponse response)
        throws ServletException, java.io.IOException {

        throw new ServletException("GET method used with " +
                getClass( ).getName( )+": POST method required.");
   } 
}

web.xml

Compile above servlet UploadServlet and create required entry in web.xml file as follows.

<servlet>
   <servlet-name>UploadServlet</servlet-name>
   <servlet-class>UploadServlet</servlet-class>
</servlet>

<servlet-mapping>
   <servlet-name>UploadServlet</servlet-name>
   <url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>

How to insert date values into table

Since dob is DATE data type, you need to convert the literal to DATE using TO_DATE and the proper format model. The syntax is:

TO_DATE('<date_literal>', '<format_model>')

For example,

SQL> CREATE TABLE t(dob DATE);

Table created.

SQL> INSERT INTO t(dob) VALUES(TO_DATE('17/12/2015', 'DD/MM/YYYY'));

1 row created.

SQL> COMMIT;

Commit complete.

SQL> SELECT * FROM t;

DOB
----------
17/12/2015

A DATE data type contains both date and time elements. If you are not concerned about the time portion, then you could also use the ANSI Date literal which uses a fixed format 'YYYY-MM-DD' and is NLS independent.

For example,

SQL> INSERT INTO t(dob) VALUES(DATE '2015-12-17');

1 row created.

string encoding and decoding?

Guessing at all the things omitted from the original question, but, assuming Python 2.x the key is to read the error messages carefully: in particular where you call 'encode' but the message says 'decode' and vice versa, but also the types of the values included in the messages.

In the first example string is of type unicode and you attempted to decode it which is an operation converting a byte string to unicode. Python helpfully attempted to convert the unicode value to str using the default 'ascii' encoding but since your string contained a non-ascii character you got the error which says that Python was unable to encode a unicode value. Here's an example which shows the type of the input string:

>>> u"\xa0".decode("ascii", "ignore")

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    u"\xa0".decode("ascii", "ignore")
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128)

In the second case you do the reverse attempting to encode a byte string. Encoding is an operation that converts unicode to a byte string so Python helpfully attempts to convert your byte string to unicode first and, since you didn't give it an ascii string the default ascii decoder fails:

>>> "\xc2".encode("ascii", "ignore")

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    "\xc2".encode("ascii", "ignore")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128)

Folder is locked and I can't unlock it

Clean up, check all check box => This work for me

1067 error on attempt to start MySQL

I have mysql data folder replaced by a windows directory junction. I suspect ib_logfile0/1 and/or ibdata1 is corrupted.

Just try to delete those files and computername.err. Then restart mysql service. That's what I did, with success.

Copying ibdata1 files, after a full reinstallation of mysql, to the junction dir and replacing dir by the junction, restarting mysql, was not enough.

You have to let mysql rebuild those files.

How to clear the Entry widget after a button is pressed in Tkinter?

if you add the print code to check the type of real, you will see that real is a string, not an Entry so there is no delete attribute.

def res(real, secret):
    print(type(real))
    if secret==eval(real):
        showinfo(message='that is right!')
    real.delete(0, END)

>> output: <class 'str'>

Solution:

secret = randrange(1,100)
print(secret)

def res(real, secret):
    if secret==eval(real):
        showinfo(message='that is right!')
    ent.delete(0, END)    # we call the entry an delete its content

def guess():

    ge = Tk()
    ge.title('guessing game')

    Label(ge, text="what is your guess:").pack(side=TOP)

    global ent    # Globalize ent to use it in other function
    ent = Entry(ge)
    ent.pack(side=TOP)

    btn=Button(ge, text="Enter", command=lambda: res(ent.get(),secret))
    btn.pack(side=LEFT)

    ge.mainloop()

It should work.

fatal error C1083: Cannot open include file: 'xyz.h': No such file or directory?

Add the "code" folder to the project properties within Visual Studio

Project->Properties->Configuration Properties->C/C++->Additional Include Directories

Accessing Google Account Id /username via Android

Used these lines:

AccountManager manager = AccountManager.get(this);
Account[] accounts = manager.getAccountsByType("com.google");

the length of array accounts is always 0.

MySQL add days to a date

SET date = DATE_ADD( fieldname, INTERVAL 2 DAY )

Selenium and xPath - locating a link by containing text

Use this

//*[@id='popover-search']/div/div/ul/li[1]/a/span[contains(text(),'Some text')]

OR

//*[@id='popover-search']/div/div/ul/li[1]/a/span[contains(.,'Some text')]

how to set image from url for imageView

Using Glide library:

Glide.with(context)
  .load(new File(url)
  .diskCacheStrategy(DiskCacheStrategy.ALL)
  .into(imageView);

How do I automatically set the $DISPLAY variable for my current session?

Your vncserver have a configuration file somewher that set the display number. To do it automaticaly, one solution is to parse this file, extract the number and set it correctly. A simpler (better) is to have this display number set in a config script and use it in both your VNC server config and in your init scripts.

INSERT SELECT statement in Oracle 11G

Get rid of the values keyword and the parens. You can see an example here.

This is basic INSERT syntax:

INSERT INTO "table_name" ("column1", "column2", ...)
VALUES ("value1", "value2", ...);

This is the INSERT SELECT syntax:

INSERT INTO "table1" ("column1", "column2", ...)
SELECT "column3", "column4", ...
FROM "table2";

Iterating over arrays in Python 3

The for loop iterates over the elements of the array, not its indexes. Suppose you have a list ar = [2, 4, 6]:

When you iterate over it with for i in ar: the values of i will be 2, 4 and 6. So, when you try to access ar[i] for the first value, it might work (as the last position of the list is 2, a[2] equals 6), but not for the latter values, as a[4] does not exist.

If you intend to use indexes anyhow, try using for index, value in enumerate(ar):, then theSum = theSum + ar[index] should work just fine.

Excel VBA - select multiple columns not in sequential order

Working on a project I was stuck for some time on this concept - I ended up with a similar answer to Method 1 by @GSerg that worked great. Essentially I defined two formula ranges (using a few variables) and then used the Union concept. My example is from a larger project that I'm working on but hopefully the portion of code below can help some other people who might not know how to use the Union concept in conjunction with defined ranges and variables. I didn't include the entire code because at this point it's fairly long - if anyone wants more insight feel free to let me know.

First I declared all my variables as Public

Then I defined/set each variable

Lastly I set a new variable "SelectRanges" as the Union between the two other FormulaRanges

Public r As Long
Public c As Long
Public d As Long
Public FormulaRange3 As Range
Public FormulaRange4 As Range
Public SelectRanges As Range

With Sheet8




  c = pvt.DataBodyRange.Columns.Count + 1

  d = 3

  r = .Cells(.Rows.Count, 1).End(xlUp).Row

Set FormulaRange3 = .Range(.Cells(d, c + 2), .Cells(r - 1, c + 2))
    FormulaRange3.NumberFormat = "0"
    Set FormulaRange4 = .Range(.Cells(d, c + c + 2), .Cells(r - 1, c + c + 2))
    FormulaRange4.NumberFormat = "0"
    Set SelectRanges = Union(FormulaRange3, FormulaRange4)

How to quickly check if folder is empty (.NET)?

My code is amazing it just took 00:00:00.0007143 less than milisecond with 34 file in folder

   System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
    sw.Start();

     bool IsEmptyDirectory = (Directory.GetFiles("d:\\pdf").Length == 0);

     sw.Stop();
     Console.WriteLine(sw.Elapsed);

HTTP GET in VBS

You haven't at time of writing described what you are going to do with the response or what its content type is. An answer already contains a very basic usage of MSXML2.XMLHTTP (I recommend the more explicit MSXML2.XMLHTTP.3.0 progID) however you may need to do different things with the response, it may not be text.

The XMLHTTP also has a responseBody property which is a byte array version of the reponse and there is a responseStream which is an IStream wrapper for the response.

Note that in a server-side requirement (e.g., VBScript hosted in ASP) you would use MSXML.ServerXMLHTTP.3.0 or WinHttp.WinHttpRequest.5.1 (which has a near identical interface).

Here is an example of using XmlHttp to fetch a PDF file and store it:-

Dim oXMLHTTP
Dim oStream

Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.3.0")

oXMLHTTP.Open "GET", "http://someserver/folder/file.pdf", False
oXMLHTTP.Send

If oXMLHTTP.Status = 200 Then
    Set oStream = CreateObject("ADODB.Stream")
    oStream.Open
    oStream.Type = 1
    oStream.Write oXMLHTTP.responseBody
    oStream.SaveToFile "c:\somefolder\file.pdf"
    oStream.Close
End If

How to concatenate strings in twig

Also a little known feature in Twig is string interpolation:

{{ "http://#{app.request.host}" }}

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

Yes. Bootstrap uses CSS transitions so it can be done easily without any Javascript. Just use CSS3. Please take a look at

carousel.carousel-fade

in the CSS of the following examples:

PHP isset() with multiple parameters

The parameter(s) to isset() must be a variable reference and not an expression (in your case a concatenation); but you can group multiple conditions together like this:

if (isset($_POST['search_term'], $_POST['postcode'])) {
}

This will return true only if all arguments to isset() are set and do not contain null.

Note that isset($var) and isset($var) == true have the same effect, so the latter is somewhat redundant.

Update

The second part of your expression uses empty() like this:

empty ($_POST['search_term'] . $_POST['postcode']) == false

This is wrong for the same reasons as above. In fact, you don't need empty() here, because by that time you would have already checked whether the variables are set, so you can shortcut the complete expression like so:

isset($_POST['search_term'], $_POST['postcode']) && 
    $_POST['search_term'] && 
    $_POST['postcode']

Or using an equivalent expression:

!empty($_POST['search_term']) && !empty($_POST['postcode'])

Final thoughts

You should consider using filter functions to manage the inputs:

$data = filter_input_array(INPUT_POST, array(
    'search_term' => array(
        'filter' => FILTER_UNSAFE_RAW,
        'flags' => FILTER_NULL_ON_FAILURE,
    ),
    'postcode' => array(
        'filter' => FILTER_UNSAFE_RAW,
        'flags' => FILTER_NULL_ON_FAILURE,
    ),
));

if ($data === null || in_array(null, $data, true)) {
    // some fields are missing or their values didn't pass the filter
    die("You did something naughty");
}

// $data['search_term'] and $data['postcode'] contains the fields you want

Btw, you can customize your filters to check for various parts of the submitted values.

modal View controllers - how to display and dismiss

Radu Simionescu - awesome work! and below Your solution for Swift lovers:

@IBAction func showSecondControlerAndCloseCurrentOne(sender: UIButton) {
    let secondViewController = storyboard?.instantiateViewControllerWithIdentifier("ConrollerStoryboardID") as UIViewControllerClass // change it as You need it
    var presentingVC = self.presentingViewController
    self.dismissViewControllerAnimated(false, completion: { () -> Void   in
        presentingVC!.presentViewController(secondViewController, animated: true, completion: nil)
    })
}

Creating new database from a backup of another Database on the same server?

I think that is easier than this.

  • First, create a blank target database.
  • Then, in "SQL Server Management Studio" restore wizard, look for the option to overwrite target database. It is in the 'Options' tab and is called 'Overwrite the existing database (WITH REPLACE)'. Check it.
  • Remember to select target files in 'Files' page.

You can change 'tabs' at left side of the wizard (General, Files, Options)

NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface>

You don't need to use JsonConverterAttribute, keep your model clean, also use CustomCreationConverter, the code is simpler:

public class SampleConverter : CustomCreationConverter<ISample>
{
    public override ISample Create(Type objectType)
    {
        return new Sample();
    }
}

Then:

var sz = JsonConvert.SerializeObject( sampleGroupInstance );
JsonConvert.DeserializeObject<SampleGroup>( sz, new SampleConverter());

Documentation: Deserialize with CustomCreationConverter

How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?

Try this

SELECT CONVERT(varchar(11),getdate(),101) -- Converts to 'mm/dd/yyyy'

SELECT CONVERT(varchar(11),getdate(),103) -- Converts to 'dd/mm/yyyy'

More info here: https://msdn.microsoft.com/en-us/library/ms187928.aspx