Programs & Examples On #Phobos

Phobos is the official runtime and standard library of the D programming language.

How to set HttpResponse timeout for Android in Java

If you are using the HttpURLConnection, call setConnectTimeout() as described here:

URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(CONNECT_TIMEOUT);

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

On the anaconda prompt, do a

  • conda -V or conda --version to get the conda version.
  • python -V or python --version to get the python version.
  • conda list anaconda$ to get the Anaconda version.
  • conda list to get the Name, Version, Build & Channel details of all the packages installed (in the current environment).
  • conda info to get all the current environment details.
  • conda info --envs To see a list of all your environments

Detailed description here, download cheat sheet from here

Eclipse returns error message "Java was started but returned exit code = 1"

1 ) Open the SpringToolSuite4.ini File.
2 ) Search For the openFile.
3 ) Provide the jvm.dll file location in SpringToolSuite4.ini
4 ) Note : Provide the New Line between -vm and your jvm.dll file location path.as shown below.

openFile
-vm 
C:\Program Files\Java\jre8\bin\server\jvm.dll
-vmargs
-Dosgi.requiredJavaVersion=1.8
-Xms256m

enter image description here

How to subtract hours from a date in Oracle so it affects the day also

you should divide hours by 24 not 11
like this:
select to_char(sysdate - 2/24, 'dd-mon-yyyy HH24') from dual

Deserialize JSON array(or list) in C#

I was having the similar issue and solved by understanding the Classes in asp.net C#

I want to read following JSON string :

[
    {
        "resultList": [
            {
                "channelType": "",
                "duration": "2:29:30",
                "episodeno": 0,
                "genre": "Drama",
                "genreList": [
                    "Drama"
                ],
                "genres": [
                    {
                        "personName": "Drama"
                    }
                ],
                "id": 1204,
                "language": "Hindi",
                "name": "The Great Target",
                "productId": 1204,
                "productMasterId": 1203,
                "productMasterName": "The Great Target",
                "productName": "The Great Target",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "2005",
                "showGoodName": "Movies ",
                "views": 8333
            },
            {
                "channelType": "",
                "duration": "2:30:30",
                "episodeno": 0,
                "genre": "Romance",
                "genreList": [
                    "Romance"
                ],
                "genres": [
                    {
                        "personName": "Romance"
                    }
                ],
                "id": 1144,
                "language": "Hindi",
                "name": "Mere Sapnon Ki Rani",
                "productId": 1144,
                "productMasterId": 1143,
                "productMasterName": "Mere Sapnon Ki Rani",
                "productName": "Mere Sapnon Ki Rani",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "1997",
                "showGoodName": "Movies ",
                "views": 6482
            },
            {
                "channelType": "",
                "duration": "2:34:07",
                "episodeno": 0,
                "genre": "Drama",
                "genreList": [
                    "Drama"
                ],
                "genres": [
                    {
                        "personName": "Drama"
                    }
                ],
                "id": 1520,
                "language": "Telugu",
                "name": "Satyameva Jayathe",
                "productId": 1520,
                "productMasterId": 1519,
                "productMasterName": "Satyameva Jayathe",
                "productName": "Satyameva Jayathe",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "2004",
                "showGoodName": "Movies ",
                "views": 9910
            }
        ],
        "resultSize": 1171,
        "pageIndex": "1"
    }
]

My asp.net c# code looks like following

First, Class3.cs page created in APP_Code folder of Web application

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Text;
using System.IO;
using System.Web.Script.Serialization;
using System.Collections.Generic;

/// <summary>
/// Summary description for Class3
/// </summary>
public class Class3
{

    public List<ListWrapper_Main> ResultList_Main { get; set; }

    public class ListWrapper_Main
    {
        public List<ListWrapper> ResultList { get; set; }

        public string resultSize { get; set; }
        public string pageIndex { get; set; }
    }

    public class ListWrapper
    {
        public string channelType { get; set; }
        public string duration { get; set; }
        public int episodeno { get; set; }
        public string genre { get; set; }
        public string[] genreList { get; set; }
        public List<genres_cls> genres { get; set; }
        public int id { get; set; }
        public string imageUrl { get; set; }
        //public string imageurl { get; set; }
        public string language { get; set; }
        public string name { get; set; }
        public int productId { get; set; }
        public int productMasterId { get; set; }
        public string productMasterName { get; set; }
        public string productName { get; set; }
        public int productTypeId { get; set; }
        public string productTypeName { get; set; }
        public decimal rating { get; set; }
        public string releaseYear { get; set; }
        //public string releaseyear { get; set; }
        public string showGoodName { get; set; }
        public string views { get; set; }
    }
    public class genres_cls
    {
        public string personName { get; set; }
    }

}

Then, Browser page that reads the string/JSON string listed above and displays/Deserialize the JSON objects and displays the data

JavaScriptSerializer ser = new JavaScriptSerializer();


        string final_sb = sb.ToString();

        List<Class3.ListWrapper_Main> movieInfos = ser.Deserialize<List<Class3.ListWrapper_Main>>(final_sb.ToString());

        foreach (var itemdetail in movieInfos)
        {

            foreach (var itemdetail2 in itemdetail.ResultList)
            {
                Response.Write("channelType=" + itemdetail2.channelType + "<br/>");
                Response.Write("duration=" + itemdetail2.duration + "<br/>");
                Response.Write("episodeno=" + itemdetail2.episodeno + "<br/>");
                Response.Write("genre=" + itemdetail2.genre + "<br/>");

                string[] genreList_arr = itemdetail2.genreList;
                for (int i = 0; i < genreList_arr.Length; i++)
                    Response.Write("genreList1=" + genreList_arr[i].ToString() + "<br>");

                foreach (var genres1 in itemdetail2.genres)
                {
                    Response.Write("genres1=" + genres1.personName + "<br>");
                }

                Response.Write("id=" + itemdetail2.id + "<br/>");
                Response.Write("imageUrl=" + itemdetail2.imageUrl + "<br/>");
                //Response.Write("imageurl=" + itemdetail2.imageurl + "<br/>");
                Response.Write("language=" + itemdetail2.language + "<br/>");
                Response.Write("name=" + itemdetail2.name + "<br/>");
                Response.Write("productId=" + itemdetail2.productId + "<br/>");
                Response.Write("productMasterId=" + itemdetail2.productMasterId + "<br/>");
                Response.Write("productMasterName=" + itemdetail2.productMasterName + "<br/>");
                Response.Write("productName=" + itemdetail2.productName + "<br/>");
                Response.Write("productTypeId=" + itemdetail2.productTypeId + "<br/>");
                Response.Write("productTypeName=" + itemdetail2.productTypeName + "<br/>");
                Response.Write("rating=" + itemdetail2.rating + "<br/>");
                Response.Write("releaseYear=" + itemdetail2.releaseYear + "<br/>");
                //Response.Write("releaseyear=" + itemdetail2.releaseyear + "<br/>");
                Response.Write("showGoodName=" + itemdetail2.showGoodName + "<br/>");
                Response.Write("views=" + itemdetail2.views + "<br/><br>");
                //Response.Write("resultSize" + itemdetail2.resultSize + "<br/>");
                //  Response.Write("pageIndex" + itemdetail2.pageIndex + "<br/>");


            }



            Response.Write("resultSize=" + itemdetail.resultSize + "<br/><br>");
            Response.Write("pageIndex=" + itemdetail.pageIndex + "<br/><br>");

        }

'sb' is the actual string, i.e. JSON string of data mentioned very first on top of this reply

This is basically - web application asp.net c# code....

N joy...

Attach event to dynamic elements in javascript

I know that the topic is too old but I gave myself some minutes to create a very useful code that works fine and very easy using pure JAVASCRIPT. Here is the code with a simple example:

_x000D_
_x000D_
String.prototype.addEventListener=function(eventHandler, functionToDo){_x000D_
  let selector=this;_x000D_
  document.body.addEventListener(eventHandler, function(e){_x000D_
    e=(e||window.event);_x000D_
    e.preventDefault();_x000D_
    const path=e.path;_x000D_
    path.forEach(function(elem){_x000D_
      const selectorsArray=document.querySelectorAll(selector);_x000D_
      selectorsArray.forEach(function(slt){_x000D_
        if(slt==elem){_x000D_
          if(typeof functionToDo=="function") functionToDo(el=slt, e=e);_x000D_
        }_x000D_
      });_x000D_
    });_x000D_
  });_x000D_
}_x000D_
_x000D_
// And here is how we can use it actually !_x000D_
_x000D_
"input[type='number']".addEventListener("click", function(element, e){_x000D_
 console.log( e ); // Console log the value of the current number input_x000D_
});
_x000D_
<input type="number" value="25">_x000D_
<br>_x000D_
<input type="number" value="15">_x000D_
<br><br>_x000D_
<button onclick="addDynamicInput()">Add a Dynamic Input</button>_x000D_
<script type="text/javascript">_x000D_
  function addDynamicInput(){_x000D_
    const inpt=document.createElement("input");_x000D_
          inpt.type="number";_x000D_
          inpt.value=Math.floor(Math.random()*30+1);_x000D_
    document.body.prepend(inpt);_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_

How do I horizontally center an absolute positioned element inside a 100% width div?

You will have to assign both left and right property 0 value for margin: auto to center the logo.

So in this case:

#logo {
  background:red;
  height:50px;
  position:absolute;
  width:50px;
  left: 0;
  right: 0;
  margin: 0 auto;
}

You might also want to set position: relative for #header.

This works because, setting left and right to zero will horizontally stretch the absolutely positioned element. Now magic happens when margin is set to auto. margin takes up all the extra space(equally on each side) leaving the content to its specified width. This results in content becoming center aligned.

bundle install returns "Could not locate Gemfile"

You must be in the same directory of Gemfile

What "wmic bios get serialnumber" actually retrieves?

the wmic bios get serialnumber command call the Win32_BIOS wmi class and get the value of the SerialNumber property, which retrieves the serial number of the BIOS Chip of your system.

How to return history of validation loss in Keras

For plotting the loss directly the following works:

model_ = model.fit(X, Y, epochs= ..., verbose=1 )
plt.plot(list(model_.history.values())[0],'k-o')

How to listen for a WebView finishing loading a URL?

I have simplified NeTeInStEiN's code to be like this:

mWebView.setWebViewClient(new WebViewClient() {
        private int       webViewPreviousState;
        private final int PAGE_STARTED    = 0x1;
        private final int PAGE_REDIRECTED = 0x2;

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
            webViewPreviousState = PAGE_REDIRECTED;
            mWebView.loadUrl(urlNewString);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            webViewPreviousState = PAGE_STARTED;
            if (dialog == null || !dialog.isShowing())
                dialog = ProgressDialog.show(WebViewActivity.this, "", getString(R.string.loadingMessege), true, true,
                        new OnCancelListener() {

                            @Override
                            public void onCancel(DialogInterface dialog) {
                                // do something
                            }
                        });
        }

        @Override
        public void onPageFinished(WebView view, String url) {

            if (webViewPreviousState == PAGE_STARTED) {
                dialog.dismiss();
                dialog = null;
            }

        }
 });

It is easy to understand, OnPageFinished if the previous callback is on onPageStarted, so the page is completely loaded.

How can I use console logging in Internet Explorer?

For older version of IE (before IE8), it is not straight forward to see the console log in IE Developer Toolbar, after spending hours research and trying many different solutions, finally, the following toolbar is great tool for me:

The main advantage of this is providing a console for IE6 or IE7, so you can see what are the error (in the console log)

  • Note:
  • It is free
  • screen shot of the toolbar

enter image description here

What is <scope> under <dependency> in pom.xml for?

If we don't provide any scope then the default scope is compile, If you want to confirm, simply go to Effective pom tab in eclipse editor, it will show you as compile.

Java - No enclosing instance of type Foo is accessible

static class Thing will make your program work.

As it is, you've got Thing as an inner class, which (by definition) is associated with a particular instance of Hello (even if it never uses or refers to it), which means it's an error to say new Thing(); without having a particular Hello instance in scope.

If you declare it as a static class instead, then it's a "nested" class, which doesn't need a particular Hello instance.

ERROR Android emulator gets killed

For my case i need to close Virtualbox

Insert picture/table in R Markdown

When it comes to inserting a picture, r2evans's suggestion of ![Caption for the picture.](/path/to/image.png) can be problematic if PDF output is required.

The knitr function include_graphics knitr::include_graphics('/path/to/image.png') is a more portable alternative that will generate, on your behalf, the markdown that is most appropriate to the output format that you are generating.

Reading file using fscanf() in C

In your code:

while(fscanf(fp,"%s %c",item,&status) == 1)  

why 1 and not 2? The scanf functions return the number of objects read.

OR operator in switch-case?

dude do like this

    case R.id.someValue :
    case R.id.someOtherValue :
       //do stuff

This is same as using OR operator between two values Because of this case operator isn't there in switch case

How do I find the CPU and RAM usage using PowerShell?

I have combined all the above answers into a script that polls the counters and writes the measurements in the terminal:

$totalRam = (Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum).Sum
while($true) {
    $date = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $cpuTime = (Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue
    $availMem = (Get-Counter '\Memory\Available MBytes').CounterSamples.CookedValue
    $date + ' > CPU: ' + $cpuTime.ToString("#,0.000") + '%, Avail. Mem.: ' + $availMem.ToString("N0") + 'MB (' + (104857600 * $availMem / $totalRam).ToString("#,0.0") + '%)'
    Start-Sleep -s 2
}

This produces the following output:

2020-02-01 10:56:55 > CPU: 0.797%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:56:59 > CPU: 0.447%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:57:03 > CPU: 0.089%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:57:07 > CPU: 0.000%, Avail. Mem.: 2,118MB (51.7%)

You can hit Ctrl+C to abort the loop.

So, you can connect to any Windows machine with this command:

Enter-PSSession -ComputerName MyServerName -Credential MyUserName

...paste it in, and run it, to get a "live" measurement. If connecting to the machine doesn't work directly, take a look here.

Python not working in command prompt?

This working for me :

PS C:\Users\MyUsername> py -V

Python 3.9.0

How do I reference tables in Excel using VBA?

In addition, it's convenient to define variables referring to objects. For instance,

Sub CreateTable()
    Dim lo as ListObject
    Set lo = ActiveSheet.ListObjects.Add(xlSrcRange, Range("$B$1:$D$16"), , xlYes)
    lo.Name = "Table1"
    lo.TableStyle = "TableStyleLight2"
    ...
End Sub

You will probably find it advantageous at once.

Inheritance with base class constructor with parameters

I could be wrong, but I believe since you are inheriting from foo, you have to call a base constructor. Since you explicitly defined the foo constructor to require (int, int) now you need to pass that up the chain.

public bar(int a, int b) : base(a, b)
{
     c = a * b;
}

This will initialize foo's variables first and then you can use them in bar. Also, to avoid confusion I would recommend not naming parameters the exact same as the instance variables. Try p_a or something instead, so you won't accidentally be handling the wrong variable.

jQuery Ajax File Upload

<html>
    <head>
        <title>Ajax file upload</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script>
            $(document).ready(function (e) {
            $("#uploadimage").on('submit', (function(e) {
            e.preventDefault();
                    $.ajax({
                    url: "upload.php", // Url to which the request is send
                            type: "POST", // Type of request to be send, called as method
                            data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
                            contentType: false, // The content type used when sending data to the server.
                            cache: false, // To unable request pages to be cached
                            processData:false, // To send DOMDocument or non processed data file it is set to false
                            success: function(data)   // A function to be called if request succeeds
                            {
                            alert(data);
                            }
                    });
            }));
        </script>
    </head>
    <body>
        <div class="main">
            <h1>Ajax Image Upload</h1><br/>
            <hr>
            <form id="uploadimage" action="" method="post" enctype="multipart/form-data">
                <div id="image_preview"><img id="previewing" src="noimage.png" /></div>
                <hr id="line">
                <div id="selectImage">
                    <label>Select Your Image</label><br/>
                    <input type="file" name="file" id="file" required />
                    <input type="submit" value="Upload" class="submit" />
                </div>
            </form>
        </div>
    </body>
</html>

Emulator in Android Studio doesn't start

I faced the same problem. From some research that I did, I realized that my computer does not support virtualization. So I had to install BLUESTACKS. Believe me it worked...you can also try it.

  1. Just go to your directory C:\Android\sdk\platform-tools and double click adb
  2. Ensure that your bluestack is running.
  3. When you try to run the project, it automatically shows up to run with the bluestacks....just choose the bluestack and you are done.

If you want the setup of bluestack, just google it you can have a number of sites to download from for free.

How to copy selected lines to clipboard in vim

Install "xclip" if you haven't...

sudo apt-get install xclip

Xclip puts the data into the "selection/highlighted" clipboard that you middle-click to paste as opposed to "ctrl+v"

While in vim use ex commands:

7w !xclip

or

1,7w !xclip

or

%w !xclip

Then just middle-click to paste into any other application...

Python Request Post with param data

Set data to this:

data ={"eventType":"AAS_PORTAL_START","data":{"uid":"hfe3hf45huf33545","aid":"1","vid":"1"}}

Show Current Location and Update Location in MKMapView in Swift

For Swift 2, you should change it to the following:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations.last

    let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

    self.map.setRegion(region, animated: true)
}

Oracle query to fetch column names

The only way that I was able to get the column names was using the following query:

select COLUMN_NAME
FROM all_tab_columns atc
WHERE table_name like 'USERS'

ToggleButton in C# WinForms

You can always code your own button with custom graphics and a PictureBox, though it won't necessarily match the Windows theme of your users.

How to stick text to the bottom of the page?

From my research and starting on this post, i think this is the best option:

_x000D_
_x000D_
<p style=" position: absolute; bottom: 0; left: 0; width: 100%; text-align: center;">This will stick at the botton no matter what :).</p> 
_x000D_
_x000D_
_x000D_

This option allow resizes of the page and even if the page is blank it will stick at the bottom.

How can I disable HREF if onclick is executed?

In my case, I had a condition when the user click the "a" element. The condition was:

If other section had more than ten items, then the user should be not redirected to other page.

If other section had less than ten items, then the user should be redirected to other page.

The functionality of the "a" elements depends of the other component. The code within click event is the follow:

var elementsOtherSection = document.querySelectorAll("#vehicle-item").length;
if (elementsOtherSection> 10){
     return true;
}else{
     event.preventDefault();
     return false;
}

Best way to convert strings to symbols in hash

How about this:

my_hash = HashWithIndifferentAccess.new(YAML.load_file('yml'))

# my_hash['key'] => "val"
# my_hash[:key]  => "val"

"Server Tomcat v7.0 Server at localhost failed to start" without stack trace while it works in terminal

enter image description here

Consider cleaning your poject before running the servelet. This will delete all the corrupted files.

How to get a cookie from an AJAX response?

You're looking for a response header of Set-Cookie:

xhr.getResponseHeader('Set-Cookie');

It won't work with HTTPOnly cookies though.

Update

According to the XMLHttpRequest Level 1 and XMLHttpRequest Level 2, this particular response headers falls under the "forbidden" response headers that you can obtain using getResponseHeader(), so the only reason why this could work is basically a "naughty" browser.

Ruby - ignore "exit" in code

loop {   begin     Bar.new   rescue SystemExit     p $!  #: #<SystemExit: exit>   end } 

This will print #<SystemExit: exit> in an infinite loop, without ever exiting.

How to disable sort in DataGridView?

private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
      for (int i = 0; i < dataGridView1.Columns.Count; i++)
      {
           dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
      }
}

Two Divs next to each other, that then stack with responsive change

today this kind of thing can be done by using display:flex;

https://jsfiddle.net/suunyz3e/1435/

html:

  <div class="container flex-direction">
      <div class="div1">
        <span>Div One</span>
      </div>
      <div class="div2">
        <span>Div Two</span>
      </div>
  </div>

css:

.container{
  display:inline-flex;
  flex-wrap:wrap;
  border:1px solid black;
}
.flex-direction{
  flex-direction:row;
}
.div1{
  border-right:1px solid black;
  background-color:#727272;
  width:165px;
  height:132px;
}

.div2{
  background-color:#fff;
  width:314px;
  height:132px;
}

span{
  font-size:16px;
    font-weight:bold;
    display: block;
    line-height: 132px;
    text-align: center;
}

@media screen and (max-width: 500px) {
  .flex-direction{
  flex-direction:column;
  }
.div1{
  width:202px;
  height:131px;
  border-right:none;
  border-bottom:1px solid black;
  }
  .div2{
    width:202px;
    height:107px;
  }
  .div2 span{
    line-height:107px;
  }

}

Which way is best for creating an object in JavaScript? Is `var` necessary before an object property?

There are a many ways to create your objects in JavaScript. Using a constructer function to create an object or object literal notation is using alot in JavaScript. Also creating an instance of Object and then adding properties and methods to it, there are three common ways to do create objects in JavaScript.

Constructer functions

There are built-in constructer functions that we all may use them time to time, like Date(), Number(), Boolean() etc, all constructer functions start with Capital letter, in the meantime we can create custom constructor function in JavaScript like this:

function Box (Width, Height, fill) {  
  this.width = Width;  // The width of the box 
  this.height = Height;  // The height of the box 
  this.fill = true;  // Is it filled or not?
}  

and you can invoke it, simply using new(), to create a new instance of the constructor, create something like below and call the constructor function with filled parameters:

var newBox = new Box(8, 12, true);  

Object literals

Using object literals are very used case creating object in JavaScript, this an example of creating a simple object, you can assign anything to your object properties as long as they are defined:

var person = { 
    name: "Alireza",
    surname: "Dezfoolian"
    nose: 1,  
    feet: 2,  
    hands: 2,
    cash: null
};  

Prototyping

After creating an Object, you can prototype more members to that, for example adding colour to our Box, we can do this:

Box.prototype.colour = 'red';

sqldeveloper error message: Network adapter could not establish the connection error

I have had the same problem. I am using windows 7 and this should also work for windows 8. The services responsible for the TNS listener and database were stopped when I looked in the Task Manager.

1: Hit Ctrl-Alt-Del and select "Start Task Manager".

From there go to the "Services" tab.

There are 5 services that need to be running for the database to be accessed correctly.

In the list below "databasename" is the database name you assigned during creation without the quotes.

I am also using database 11g, if you are using another type those fields would be different below. the * after home is the home install, if you have more than 1 database there would be home1, and home2

These are the 5 services

  1. OracleVssWriter"databasename"
  2. OracleService"databasename"
  3. OracleOraDb11g_home*TNSListener
  4. OracleOraDb11g_home*ClrAgent
  5. OracleDBConsole"databasename"

If any of these services are stopped right click on them and start them. After they have all started go back into SQL developer and re-try the connection and it should work.

Using jQuery UI sortable with HTML tables

You can call sortable on a <tbody> instead of on the individual rows.

<table>
    <tbody>
        <tr> 
            <td>1</td>
            <td>2</td>
        </tr>
        <tr>
            <td>3</td>
            <td>4</td> 
        </tr>
        <tr>
            <td>5</td>
            <td>6</td>
        </tr>  
    </tbody>    
</table>?

<script>
    $('tbody').sortable();
</script> 

_x000D_
_x000D_
$(function() {_x000D_
  $( "tbody" ).sortable();_x000D_
});
_x000D_
 _x000D_
table {_x000D_
    border-spacing: collapse;_x000D_
    border-spacing: 0;_x000D_
}_x000D_
td {_x000D_
    width: 50px;_x000D_
    height: 25px;_x000D_
    border: 1px solid black;_x000D_
}
_x000D_
 _x000D_
_x000D_
<link href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet">_x000D_
<script src="//code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>_x000D_
_x000D_
<table>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <td>1</td>_x000D_
            <td>2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>3</td>_x000D_
            <td>4</td>_x000D_
        </tr>_x000D_
        <tr> _x000D_
            <td>5</td>_x000D_
            <td>6</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>7</td>_x000D_
            <td>8</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>9</td> _x000D_
            <td>10</td>_x000D_
        </tr>  _x000D_
    </tbody>    _x000D_
</table>
_x000D_
_x000D_
_x000D_

Android ListView Text Color

I needed to make a ListView with items of different colors. I modified Shardul's method a bit and result in this:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                this, android.R.layout.simple_list_item_1, colorString) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                TextView textView = (TextView) super.getView(position, convertView, parent);
                textView.setBackgroundColor(assignBackgroundColor(position));
                textView.setTextColor(assignTextColor(position));
                return textView;
            }
        };
        colorList.setAdapter(adapter);

assignBackgroundColor() and assignTextColor() are methods that assign color you want. They can be replaced with int[] arrays.

How should I edit an Entity Framework connection string?

Follow the next steps:

  1. Open the app.config and comment on the connection string (save file)
  2. Open the edmx (go to properties, the connection string should be blank), close the edmx file again
  3. Open the app.config and uncomment the connection string (save file)
  4. Open the edmx, go to properties, you should see the connection string uptated!!

What does EntityManager.flush do and why do I need to use it?

So when you call EntityManager.persist(), it only makes the entity get managed by the EntityManager and adds it (entity instance) to the Persistence Context. An Explicit flush() will make the entity now residing in the Persistence Context to be moved to the database (using a SQL).

Without flush(), this (moving of entity from Persistence Context to the database) will happen when the Transaction to which this Persistence Context is associated is committed.

Clearing UIWebview cache

I actually think it may retain cached information when you close out the UIWebView. I've tried removing a UIWebView from my UIViewController, releasing it, then creating a new one. The new one remembered exactly where I was at when I went back to an address without having to reload everything (it remembered my previous UIWebView was logged in).

So a couple of suggestions:

[[NSURLCache sharedURLCache] removeCachedResponseForRequest:NSURLRequest];

This would remove a cached response for a specific request. There is also a call that will remove all cached responses for all requests ran on the UIWebView:

[[NSURLCache sharedURLCache] removeAllCachedResponses];

After that, you can try deleting any associated cookies with the UIWebView:

for(NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {

    if([[cookie domain] isEqualToString:someNSStringUrlDomain]) {

        [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
    }
}

Swift 3:

// Remove all cache 
URLCache.shared.removeAllCachedResponses()

// Delete any associated cookies     
if let cookies = HTTPCookieStorage.shared.cookies {
    for cookie in cookies {
        HTTPCookieStorage.shared.deleteCookie(cookie)
    }
}

Convert a string to int using sql query

Try this one, it worked for me in Athena:

cast(MyVarcharCol as integer)

PostgreSQL Crosstab Query

Crosstab function is available under the tablefunc extension. You'll have to create this extension one time for the database.

CREATE EXTENSION tablefunc;

You can use the below code to create pivot table using cross tab:

create table test_Crosstab( section text,
<br/>status text,
<br/>count numeric)

<br/>insert into test_Crosstab values ( 'A','Active',1)
                <br/>,( 'A','Inactive',2)
                <br/>,( 'B','Active',4)
                <br/>,( 'B','Inactive',5)

select * from crosstab(
<br/>'select section
    <br/>,status
    <br/>,count
    <br/>from test_crosstab'
    <br/>)as ctab ("Section" text,"Active" numeric,"Inactive" numeric)

Can I call a constructor from another constructor (do constructor chaining) in C++?

In C++11, a constructor can call another constructor overload:

class Foo  {
     int d;         
public:
    Foo  (int i) : d(i) {}
    Foo  () : Foo(42) {} //New to C++11
};

Additionally, members can be initialized like this as well.

class Foo  {
     int d = 5;         
public:
    Foo  (int i) : d(i) {}
};

This should eliminate the need to create the initialization helper method. And it is still recommended not calling any virtual functions in the constructors or destructors to avoid using any members that might not be initialized.

Using JQuery to open a popup window and print

Got it! I found an idea here

http://www.mail-archive.com/[email protected]/msg18410.html

In this example, they loaded a blank popup window into an object, cloned the contents of the element to be displayed, and appended it to the body of the object. Since I already knew what the contents of view-details (or any page I load in the lightbox), I just had to clone that content instead and load it into an object. Then, I just needed to print that object. The final outcome looks like this:

$('.printBtn').bind('click',function() {
    var thePopup = window.open( '', "Customer Listing", "menubar=0,location=0,height=700,width=700" );
    $('#popup-content').clone().appendTo( thePopup.document.body );
    thePopup.print();
});

I had one small drawback in that the style sheet I was using in view-details.php was using a relative link. I had to change it to an absolute link. The reason being that the window didn't have a URL associated with it, so it had no relative position to draw on.

Works in Firefox. I need to test it in some other major browsers too.

I don't know how well this solution works when you're dealing with images, videos, or other process intensive solutions. Although, it works pretty well in my case, since I'm just loading tables and text values.

Thanks for the input! You gave me some ideas of how to get around this.

Javascript Get Values from Multiple Select Option Box

The for loop is getting one extra run. Change

for (x=0;x<=InvForm.SelBranch.length;x++)

to

for (x=0; x < InvForm.SelBranch.length; x++)

How to pass multiple arguments in processStartInfo?

Remember to include System.Diagnostics

ProcessStartInfo startInfo = new ProcessStartInfo("myfile.exe");        // exe file
startInfo.WorkingDirectory = @"C:\..\MyFile\bin\Debug\netcoreapp3.1\"; // exe folder

//here you add your arguments
startInfo.ArgumentList.Add("arg0");       // First argument          
startInfo.ArgumentList.Add("arg2");       // second argument
startInfo.ArgumentList.Add("arg3");       // third argument
Process.Start(startInfo);                 

How to perform Unwind segue programmatically?

Backwards compatible solution that will work for versions prior to ios6, for those interested:

- (void)unwindToViewControllerOfClass:(Class)vcClass animated:(BOOL)animated {

    for (int i=self.navigationController.viewControllers.count - 1; i >= 0; i--) {
        UIViewController *vc = [self.navigationController.viewControllers objectAtIndex:i];
        if ([vc isKindOfClass:vcClass]) {
            [self.navigationController popToViewController:vc animated:animated];
            return;
        }
    }
}

Convert char array to string use C

Assuming array is a character array that does not end in \0, you will want to use strncpy:

char * strncpy(char * destination, const char * source, size_t num);

like so:

strncpy(string, array, 20);
string[20] = '\0'

Then string will be a null terminated C string, as desired.

TypeError: method() takes 1 positional argument but 2 were given

In simple words.

In Python you should add self argument as the first argument to all defined methods in classes:

class MyClass:
  def method(self, arg):
    print(arg)

Then you can use your method according to your intuition:

>>> my_object = MyClass()
>>> my_object.method("foo")
foo

This should solve your problem :)

For a better understanding, you can also read the answers to this question: What is the purpose of self?

Is there a way to make npm install (the command) to work behind proxy?

when I give without http/http prefix in the proxy settings npm failed even when the proxy host and port were right values. It worked only after adding the protocol prefix.

ReportViewer Client Print Control "Unable to load client print control"?

I got this working with out removing any patches. The above patch was not working too. Finally what I did was on the IIS server install the following patch and reset / restart the IIS server. This is not for report manager application. This is for any ASP.NET Web application developed in .net3.5 using VS2008 http://www.microsoft.com/downloads/details.aspx?familyid=6AE0AA19-3E6C-474C-9D57-05B2347456B1&displaylang=en

How to perform a for loop on each character in a string in Bash?

Another approach, if you don't care about whitespace being ignored:

for char in $(sed -E s/'(.)'/'\1 '/g <<<"$your_string"); do
    # Handle $char here
done

What do the return values of Comparable.compareTo mean in Java?

System.out.println(A.compareTo(B)>0?"Yes":"No")

if the value of A>B it will return "Yes" or "No".

Get latitude and longitude based on location name with Google Autocomplete API

The below is the code that i used. It's working perfectly.

var geo = new google.maps.Geocoder;
geo.geocode({'address':address},function(results, status){
    if (status == google.maps.GeocoderStatus.OK) {              
        var myLatLng = results[0].geometry.location;

        // Add some code to work with myLatLng              

    } else {
        alert("Geocode was not successful for the following reason: " + status);
    }
});

Hope this will help.

When should I use File.separator and when File.pathSeparator?

You use separator when you are building a file path. So in unix the separator is /. So if you wanted to build the unix path /var/temp you would do it like this:

String path = File.separator + "var"+ File.separator + "temp"

You use the pathSeparator when you are dealing with a list of files like in a classpath. For example, if your app took a list of jars as argument the standard way to format that list on unix is: /path/to/jar1.jar:/path/to/jar2.jar:/path/to/jar3.jar

So given a list of files you would do something like this:

String listOfFiles = ...
String[] filePaths = listOfFiles.split(File.pathSeparator);

alert a variable value

var input_val=document.getElementById('my_variable');for (i=0; i<input_val.length; i++) {
xx = input_val[i];``
if (xx.name == "ans") {   
    new = xx.value;
    alert(new);    }}

Show all tables inside a MySQL database using PHP?

<?php
$dbname = 'mysql_dbname';
if (!mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
echo 'Could not connect to mysql';
exit;
}
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_row($result)) {
echo "Table: {$row[0]}\n";
}
mysql_free_result($result);
?>
//Try This code is running perfectly !!!!!!!!!!


Creating multiple log files of different content with log4j

I had this question, but with a twist - I was trying to log different content to different files. I had information for a LowLevel debug log, and a HighLevel user log. I wanted the LowLevel to go to only one file, and the HighLevel to go to both a file, and a syslogd.

My solution was to configure the 3 appenders, and then setup the logging like this:

log4j.threshold=ALL
log4j.rootLogger=,LowLogger

log4j.logger.HighLevel=ALL,Syslog,HighLogger
log4j.additivity.HighLevel=false

The part that was difficult for me to figure out was that the 'log4j.logger' could have multiple appenders listed. I was trying to do it one line at a time.

Hope this helps someone at some point!

Selenium using Python - Geckodriver executable needs to be in PATH

I'm using Windows 10 and this worked for me:

  1. Download geckodriver from here. Download the right version for the computer you are using.
  2. Unzip the file you just downloaded and cut/copy the ".exe" file it contains
  3. Navigate to C:{your python root folder}. Mine was C:\Python27. Paste the geckodriver.exe file in this folder.
  4. Restart your development environment.
  5. Try running the code again. It should work now.

Set Session variable using javascript in PHP

Not possible. Because JavaScript is client-side and session is server-side. To do anything related to a PHP session, you have to go to the server.

C++ compile time error: expected identifier before numeric constant

Initializations with (...) in the class body is not allowed. Use {..} or = .... Unfortunately since the respective constructor is explicit and vector has an initializer list constructor, you need a functional cast to call the wanted constructor

vector<string> name = decltype(name)(5);
vector<int> val = decltype(val)(5,0);

As an alternative you can use constructor initializer lists

 Attribute():name(5), val(5, 0) {}

How to connect android wifi to adhoc wifi?

You are correct that this is currently not natively supported in Android, although Google has been saying it will be coming ever since Android was officially launched.

While not natively supported, the hardware on every android device released to date do support it. It is just disabled in software, and you would need to enable it in order to use these features.

It is however, fairly easy to do this, but you need to be root, and the specifics may be slightly different between different devices. Your best source for more informationa about this, would be XDA developers: http://forum.xda-developers.com/forumdisplay.php?f=564. Most of the existing solutions are based on replacing wpa_supplicant, and is the method I would recommend if possible on your device. For more details, see http://szym.net/2010/12/adhoc-wifi-in-android/.

Update: Its been a few years now, and whenever I need an ad hoc network connection on my phone I use CyanogenMod. It gives you both programmatic and scripted access to these functions, and the ability to create ad hoc (ibss) networks in the WiFi settings menu.

wget ssl alert handshake failure

It works from here with same OpenSSL version, but a newer version of wget (1.15). Looking at the Changelog there is the following significant change regarding your problem:

1.14: Add support for TLS Server Name Indication.

Note that this site does not require SNI. But www.coursera.org requires it. And if you would call wget with -v --debug (as I've explicitly recommended in my comment!) you will see:

$ wget https://class.coursera.org
...
HTTP request sent, awaiting response...
  HTTP/1.1 302 Found
...
Location: https://www.coursera.org/ [following]
...
Connecting to www.coursera.org (www.coursera.org)|54.230.46.78|:443... connected.
OpenSSL: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure
Unable to establish SSL connection.

So the error actually happens with www.coursera.org and the reason is missing support for SNI. You need to upgrade your version of wget.

How to POST request using RestSharp

My RestSharp POST method:

var client = new RestClient(ServiceUrl);

var request = new RestRequest("/resource/", Method.POST);

// Json to post.
string jsonToSend = JsonHelper.ToJson(json);

request.AddParameter("application/json; charset=utf-8", jsonToSend, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;

try
{
    client.ExecuteAsync(request, response =>
    {
        if (response.StatusCode == HttpStatusCode.OK)
        {
            // OK
        }
        else
        {
            // NOK
        }
    });
}
catch (Exception error)
{
    // Log
}

Getting parts of a URL (Regex)

Propose a much more readable solution (in Python, but applies to any regex):

def url_path_to_dict(path):
    pattern = (r'^'
               r'((?P<schema>.+?)://)?'
               r'((?P<user>.+?)(:(?P<password>.*?))?@)?'
               r'(?P<host>.*?)'
               r'(:(?P<port>\d+?))?'
               r'(?P<path>/.*?)?'
               r'(?P<query>[?].*?)?'
               r'$'
               )
    regex = re.compile(pattern)
    m = regex.match(path)
    d = m.groupdict() if m is not None else None

    return d

def main():
    print url_path_to_dict('http://example.example.com/example/example/example.html')

Prints:

{
'host': 'example.example.com', 
'user': None, 
'path': '/example/example/example.html', 
'query': None, 
'password': None, 
'port': None, 
'schema': 'http'
}

How do I create documentation with Pydoc?

Another thing that people may find useful...make sure to leave off ".py" from your module name. For example, if you are trying to generate documentation for 'original' in 'original.py':

yourcode_dir$ pydoc -w original.py
no Python documentation found for 'original.py'

yourcode_dir$ pydoc -w original
wrote original.html

Merge two objects with ES6

You can use Object.assign() to merge them into a new object:

_x000D_
_x000D_
const response = {_x000D_
  lat: -51.3303,_x000D_
  lng: 0.39440_x000D_
}_x000D_
_x000D_
const item = {_x000D_
  id: 'qwenhee-9763ae-lenfya',_x000D_
  address: '14-22 Elder St, London, E1 6BT, UK'_x000D_
}_x000D_
_x000D_
const newItem = Object.assign({}, item, { location: response });_x000D_
_x000D_
console.log(newItem );
_x000D_
_x000D_
_x000D_

You can also use object spread, which is a Stage 4 proposal for ECMAScript:

_x000D_
_x000D_
const response = {_x000D_
  lat: -51.3303,_x000D_
  lng: 0.39440_x000D_
}_x000D_
_x000D_
const item = {_x000D_
  id: 'qwenhee-9763ae-lenfya',_x000D_
  address: '14-22 Elder St, London, E1 6BT, UK'_x000D_
}_x000D_
_x000D_
const newItem = { ...item, location: response }; // or { ...response } if you want to clone response as well_x000D_
_x000D_
console.log(newItem );
_x000D_
_x000D_
_x000D_

Get public/external IP address?

You may use Telnet to programmatically query your router for the WAN IP.

The Telnet part

The Telnet part can be accomplished using, for example, this Minimalistic Telnet code as an API to send a Telnet command to your router and get the router's response. The remainder of this answer assumes you are set up in one way or another to send a Telnet command and get back the response in your code.

Limitations of approach

I will say up front that one drawback of querying the router compared to other approaches is that the code you write is likely to be fairly specific to your router model. That said, it can be a useful approach that doesn't rely on external servers, and you may anyway wish to access your router from your own software for other purposes, such as configuring and controlling it, making it more worthwhile writing specific code.

Example router command and response

The example below will not be right for all routers, but illustrates the approach in principle. You will need to change the particulars to suit your router commands and responses.

For example, the way to get your router to show the WAN IP may be the following Telnet command:

connection list

The output may consist of a list of lines of text, one per connection, with the IP address at offset 39. The line for the WAN connection may be identifiable from the word "Internet" somewhere in the line:

  RESP: 3947  17.110.226. 13:443       146.200.253. 16:60642     [R..A] Internet      6 tcp   128
<------------------  39  -------------><--  WAN IP -->

The output may pad each IP address segment out to three characters with spaces, which you will need to remove. (That is, in the xample above, you would need to turn "146.200.253. 16" into "146.200.253.16".)

By experimentation or consulting reference documentation for your router, you can establish the command to use for your specific router and how to interpret the router's response.

Code to get the WAN IP

(Assumes you have a method sendRouterCommand for the Telnet part—see above.)

Using the example router described above, the following code gets the WAN IP:

private bool getWanIp(ref string wanIP)
{
    string routerResponse = sendRouterCommand("connection list");

    return (getWanIpFromRouterResponse(routerResponse, out wanIP));
}

private bool getWanIpFromRouterResponse(string routerResponse, out string ipResult)
{
    ipResult = null;
    string[] responseLines = routerResponse.Split(new char[] { '\n' });

    //  RESP: 3947  17.110.226. 13:443       146.200.253. 16:60642     [R..A] Internet      6 tcp   128
    //<------------------  39  -------------><---  15   --->

    const int offset = 39, length = 15;

    foreach (string line in responseLines)
    {
        if (line.Length > (offset + length) && line.Contains("Internet"))
        {
            ipResult = line.Substring(39, 15).Replace(" ", "");
            return true;
        }
    }

    return false;
}

JUnit Eclipse Plugin?


Maybe you're in the wrong perspective?

Eclipse has a construct called a "perspective"; it's a task-oriented arrangement of windows, toolbar buttons, and menus. There's a Java perspective, a Debug perspective, there's probably a PHP perspective, etc. If you're not in the Java perspective, you won't see some of the buttons you expect (like New Class).

To switch perspectives, see the long-ish buttons on the right side of the toolbar, or use the Window menu.

How do I "break" out of an if statement?

You could use a label and a goto, but this is a bad hack. You should consider moving some of the stuff in your if statement to separate methods.

SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column

There is another issue you have to take care of it when you try mapping column which is string length, for example TK_NO nvarchar(50) you will have to map to the same length as the destination field.

Split long commands in multiple lines through Windows batch file

Though the carret will be preferable way to do this here's one more approach using macro that constructs a command by the passed arguments:

@echo off
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
set "{{=setlocal enableDelayedExpansion&for %%a in (" & set "}}="::end::" ) do if "%%~a" neq "::end::" (set command=!command! %%a) else (call !command! & endlocal)"
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

%{{%
    echo
    "command"
    written
    on a
    few lines
%}}%

command is easier to read without the carets but using special symbols e.g. brackets,redirection and so on will break it. So you can this for more simpler cases. Though you can still enclose parameters in double quotes

How to convert image to byte array

You can use File.ReadAllBytes() method to read any file into byte array. To write byte array into file, just use File.WriteAllBytes() method.

Hope this helps.

You can find more information and sample code here.

How do I get the domain originating the request in express.js?

Instead of:

var host = req.get('host');
var origin = req.get('origin');

you can also use:

var host = req.headers.host;
var origin = req.headers.origin;

Elasticsearch query to return all records

Simple! You can use size and from parameter!

http://localhost:9200/[your index name]/_search?size=1000&from=0

then you change the from gradually until you get all of the data.

Array of an unknown length in C#

A little background information:

As said, if you want to have a dynamic collection of things, use a List<T>. Internally, a List uses an array for storage too. That array has a fixed size just like any other array. Once an array is declared as having a size, it doesn't change. When you add an item to a List, it's added to the array. Initially, the List starts out with an array that I believe has a length of 16. When you try to add the 17th item to the List, what happens is that a new array is allocated, that's (I think) twice the size of the old one, so 32 items. Then the content of the old array is copied into the new array. So while a List may appear dynamic to the outside observer, internally it has to comply to the rules as well.

And as you might have guessed, the copying and allocation of the arrays isn't free so one should aim to have as few of those as possible and to do that you can specify (in the constructor of List) an initial size of the array, which in a perfect scenario is just big enough to hold everything you want. However, this is micro-optimization and it's unlikely it will ever matter to you, but it's always nice to know what you're actually doing.

What is the difference between Collection and List in Java?

First off: a List is a Collection. It is a specialized Collection, however.

A Collection is just that: a collection of items. You can add stuff, remove stuff, iterate over stuff and query how much stuff is in there.

A List adds the information about a defined sequence of stuff to it: You can get the element at position n, you can add an element at position n, you can remove the element at position n.

In a Collection you can't do that: "the 5th element in this collection" isn't defined, because there is no defined order.

There are other specialized Collections as well, for example a Set which adds the feature that it will never contain the same element twice.

Return char[]/string from a function

Including "string.h" makes things easier. An easier way to tackle your problem is:

#include <string.h>
    char* createStr(){
    static char str[20] = "my";
    return str;
}
int main(){
    char a[20];
    strcpy(a,createStr()); //this will copy the returned value of createStr() into a[]
    printf("%s",a);
    return 0;
}

Convert NVARCHAR to DATETIME in SQL Server 2008

DECLARE @chr nvarchar(50) = (SELECT CONVERT(nvarchar(50), GETDATE(), 103))

SELECT @chr chars, CONVERT(date, @chr, 103) date_again

Using multiple property files (via PropertyPlaceholderConfigurer) in multiple projects/modules

I know that this is an old question, but the ignore-unresolvable property was not working for me and I didn't know why.

The problem was that I needed an external resource (something like location="file:${CATALINA_HOME}/conf/db-override.properties") and the ignore-unresolvable="true" does not do the job in this case.

What one needs to do for ignoring a missing external resource is:

ignore-resource-not-found="true"

Just in case anyone else bumps into this.

Best way to do multi-row insert in Oracle?

If you have the values that you want to insert in another table already, then you can Insert from a select statement.

INSERT INTO a_table (column_a, column_b) SELECT column_a, column_b FROM b_table;

Otherwise, you can list a bunch of single row insert statements and submit several queries in bulk to save the time for something that works in both Oracle and MySQL.

@Espo's solution is also a good one that will work in both Oracle and MySQL if your data isn't already in a table.

Tri-state Check box in HTML?

Edit — Thanks to Janus Troelsen's comment, I found a better solution:

HTML5 defines a property for checkboxes called indeterminate

See w3c reference guide. To make checkbox appear visually indeterminate set it to true:

element.indeterminate = true;

Here is Janus Troelsen's fiddle. Note, however, that:

  • The indeterminate state cannot be set in the HTML markup, it can only be done via Javascript (see this JSfiddle test and this detailed article in CSS tricks)

  • This state doesn't change the value of the checkbox, it is only a visual cue that masks the input's real state.

  • Browser test: Worked for me in Chrome 22, Firefox 15, Opera 12 and back to IE7. Regarding mobile browsers, Android 2.0 browser and Safari mobile on iOS 3.1 don't have support for it.

Previous answer

Another alternative would be to play with the checkbox transparency for the "some selected" state (as Gmail does used to do in previous versions). It will require some javascript and a CSS class. Here I put a particular example that handles a list with checkable items and a checkbox that allows to select all/none of them. This checkbox shows a "some selected" state when some of the list items are selected.

Given a checkbox with an ID #select_all and several checkboxes with a class .select_one,

The CSS class that fades the "select all" checkbox would be the following:

.some_selected {
    opacity: 0.5;
    filter: alpha(opacity=50);
}

And the JS code that handles the tri-state of the select all checkbox is the following:

$('#select_all').change (function ()
{
    //Check/uncheck all the list's checkboxes
    $('.select_one').attr('checked', $(this).is(':checked'));
    //Remove the faded state
    $(this).removeClass('some_selected');
});

$('.select_one').change (function ()
{
  if ($('.select_one:checked').length == 0)
      $('#select_all').removeClass('some_selected').attr('checked', false);
  else if ($('.select_one:not(:checked)').length == 0)
      $('#select_all').removeClass('some_selected').attr('checked', true);
  else
      $('#select_all').addClass('some_selected').attr('checked', true);
});

You can try it here: http://jsfiddle.net/98BMK/

Hope that helps!

How can I copy the content of a branch to a new local branch?

git checkout old_branch
git branch new_branch

This will give you a new branch "new_branch" with the same state as "old_branch".

This command can be combined to the following:

git checkout -b new_branch old_branch

Global keyboard capture in C# application

My rep is too low to comment, but concerning the CallbackOnCollectedDelegate exception, I modified the public void SetupKeyboardHooks() in C4d's answer to look like this:

public void SetupKeyboardHooks(out object hookProc)
{
  _globalKeyboardHook = new GlobalKeyboardHook();
  _globalKeyboardHook.KeyboardPressed += OnKeyPressed;


  hookProc = _globalKeyboardHook.GcSafeHookProc;
}

where GcSafeHookProc is just a public getter for _hookProc in OPs

_hookProc = LowLevelKeyboardProc; // we must keep alive _hookProc, because GC is not aware about SetWindowsHookEx behaviour.

and stored the hookProc as a private field in the class calling the SetupKeyboardHooks(...), therefore keeping the reference alive, save from garbage collection, no more CallbackOnCollectedDelegate exception. Seems having this additional reference in the GlobalKeyboardHook class is not sufficient. Maybe make sure that this reference is also disposed when closing your app.

Vendor code 17002 to connect to SQLDeveloper

Listed are the steps that could rectify the error:

  1. Press Windows+R
  2. Type services.msc and strike Enter
  3. Find all services
  4. Starting with ora start these services and wait!!
  5. When your server specific service is initialized (in my case it was orcl)
  6. Now run mysql or whatever you are using and start coding.P

How to pass multiple parameters from ajax to mvc controller?

Try this:

var req={StrContactDetails:'data',IsPrimary:'True'}

$.ajax({
                   type: 'POST',
                   data: req,
                   url: '@url.Action("SaveEmergencyContact","Dhp")',
                   contentType: "application/json; charset=utf-8",
                   dataType: "json",
                   data: JSON.stringify(req),
                   success: function (data) {
                       alert("Success");
                   },
                   error: function (ob, errStr) {
                       alert("An error occured.Please try after sometime.");
                   }
               });

http://api.jquery.com/jquery.ajax/

Best Practice: Access form elements by HTML id or name attribute?

It’s not really answering your question, but just on this part:

[3] requires both an id and a name... having both is somewhat redundant

You’ll most likely need to have an id attribute on each form field anyway, so that you can associate its <label> element with it, like this:

<label for="foo">Foo:</label>
<input type="text" name="foo" id="foo" />

This is required for accessibility (i.e. if you don’t associate form labels and controls, why do you hate blind people so much?).

It is somewhat redundant, although less so when you have checkboxes/radio buttons, where several of them can share a name. Ultimately, id and name are for different purposes, even if both are often set to the same value.

Dump all tables in CSV format using 'mysqldump'

If you are using MySQL or MariaDB, the easiest and performant way dump CSV for single table is -

SELECT customer_id, firstname, surname INTO OUTFILE '/exportdata/customers.txt'
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  LINES TERMINATED BY '\n'
  FROM customers;

Now you can use other techniques to repeat this command for multiple tables. See more details here:

Call An Asynchronous Javascript Function Synchronously

You can force asynchronous JavaScript in NodeJS to be synchronous with sync-rpc.

It will definitely freeze your UI though, so I'm still a naysayer when it comes to whether what it's possible to take the shortcut you need to take. It's not possible to suspend the One And Only Thread in JavaScript, even if NodeJS lets you block it sometimes. No callbacks, events, anything asynchronous at all will be able to process until your promise resolves. So unless you the reader have an unavoidable situation like the OP (or, in my case, are writing a glorified shell script with no callbacks, events, etc.), DO NOT DO THIS!

But here's how you can do this:

./calling-file.js

var createClient = require('sync-rpc');
var mySynchronousCall = createClient(require.resolve('./my-asynchronous-call'), 'init data');

var param1 = 'test data'
var data = mySynchronousCall(param1);
console.log(data); // prints: received "test data" after "init data"

./my-asynchronous-call.js

function init(initData) {
  return function(param1) {
    // Return a promise here and the resulting rpc client will be synchronous
    return Promise.resolve('received "' + param1 + '" after "' + initData + '"');
  };
}
module.exports = init;

LIMITATIONS:

These are both a consequence of how sync-rpc is implemented, which is by abusing require('child_process').spawnSync:

  1. This will not work in the browser.
  2. The arguments to your function must be serializable. Your arguments will pass in and out of JSON.stringify, so functions and non-enumerable properties like prototype chains will be lost.

How to edit binary file on Unix systems

There's lightweight binary editor, check hexedit. http://www.linux.org/apps/AppId_6968.html. I tried using it for editing ELF binaries in Linux at least.

What is the regex for "Any positive integer, excluding 0"

This RegEx matches any Integer positive out of 0:

(?<!-)(?<!\d)[1-9][0-9]*

It works with two negative lookbehinds, which search for a minus before a number, which indicates it is a negative number. It also works for any negative number larger than -9 (e.g. -22).

Iterating through a string word by word

s = 'hi how are you'
l = list(map(lambda x: x,s.split()))
print(l)

Output: ['hi', 'how', 'are', 'you']

Bootstrap radio button "checked" flag

Assuming you want a default button checked.

<div class="row">
    <h1>Radio Group #2</h1>
    <label for="year" class="control-label input-group">Year</label>
    <div class="btn-group" data-toggle="buttons">
        <label class="btn btn-default">
            <input type="radio" name="year" value="2011">2011
        </label>
        <label class="btn btn-default">
            <input type="radio" name="year" value="2012">2012
        </label>
        <label class="btn btn-default active">
            <input type="radio" name="year" value="2013" checked="">2013
        </label>
    </div>
  </div>

Add the active class to the button (label tag) you want defaulted and checked="" to its input tag so it gets submitted in the form by default.

Get img src with PHP

Use a HTML parser like DOMDocument and then evaluate the value you're looking for with DOMXpath:

$html = '<img id="12" border="0" src="/images/image.jpg"
         alt="Image" width="100" height="100" />';

$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$src = $xpath->evaluate("string(//img/@src)"); # "/images/image.jpg"

Or for those who really need to save space:

$xpath = new DOMXPath(@DOMDocument::loadHTML($html));
$src = $xpath->evaluate("string(//img/@src)");

And for the one-liners out there:

$src = (string) reset(simplexml_import_dom(DOMDocument::loadHTML($html))->xpath("//img/@src"));

How do I clone a generic list in C#?

Using a cast may be helpful, in this case, for a shallow copy:

IList CloneList(IList list)
{
    IList result;
    result = (IList)Activator.CreateInstance(list.GetType());
    foreach (object item in list) result.Add(item);
    return result;
}

applied to generic list:

List<T> Clone<T>(List<T> argument) => (List<T>)CloneList(argument);

Best way to pretty print a hash

If you have JSON, I recommend JSON.pretty_generate(hash) because it is simpler than awesome_print, looks great in a pre tag, and allows for easy copying from a web page. (See also: How can I "pretty" format my JSON output in Ruby on Rails?)

postgresql - add boolean column to table set default

Just for future reference, if you already have a boolean column and you just want to add a default do:

ALTER TABLE users
  ALTER COLUMN priv_user SET DEFAULT false;

Full screen background image in an activity

The easiest way:

Step 1: Open AndroidManifest.xml file

You can see the file here!

Step 2: Locate android:theme="@style/AppTheme" >

Step 3: Change to android:theme="@style/Theme.AppCompat.NoActionBar" >

Step 4: Then Add ImageView & Image

Step 4: That's it!

Declaring a python function with an array parameters and passing an array argument to the function call?

I guess I'm unclear about what the OP was really asking for... Do you want to pass the whole array/list and operate on it inside the function? Or do you want the same thing done on every value/item in the array/list. If the latter is what you wish I have found a method which works well.

I'm more familiar with programming languages such as Fortran and C, in which you can define elemental functions which operate on each element inside an array. I finally tracked down the python equivalent to this and thought I would repost the solution here. The key is to 'vectorize' the function. Here is an example:

def myfunc(a,b):
    if (a>b): return a
    else: return b
vecfunc = np.vectorize(myfunc)
result=vecfunc([[1,2,3],[5,6,9]],[7,4,5])
print(result)

Output:

[[7 4 5]
 [7 6 9]]

'NoneType' object is not subscriptable?

The indexing e.g. [0] should occour inside of the print...

Generate war file from tomcat webapp folder

There is a way to create war file of your project from eclipse.

First a create an xml file with the following code,

Replace HistoryCheck with your project name.

<?xml version="1.0" encoding="UTF-8"?>
<project name="HistoryCheck" basedir="." default="default">
    <target name="default" depends="buildwar,deploy"></target>
    <target name="buildwar">
        <war basedir="war" destfile="HistoryCheck.war" webxml="war/WEB-INF/web.xml">
            <exclude name="WEB-INF/**" />
            <webinf dir="war/WEB-INF/">
                <include name="**/*.jar" />
            </webinf>
        </war>
    </target>
    <target name="deploy">
        <copy file="HistoryCheck.war" todir="." />
    </target>
</project>

Now, In project explorer right click on that xml file and Run as-> ant build

You can see the war file of your project in your project folder.

MySQL order by before group by

No. It makes no sense to order the records before grouping, since grouping is going to mutate the result set. The subquery way is the preferred way. If this is going too slow you would have to change your table design, for example by storing the id of of the last post for each author in a seperate table, or introduce a boolean column indicating for each author which of his post is the last one.

unique object identifier in javascript

Latest browsers provide a cleaner method for extending Object.prototype. This code will make the property hidden from property enumeration (for p in o)

For the browsers that implement defineProperty, you can implement uniqueId property like this:

(function() {
    var id_counter = 1;
    Object.defineProperty(Object.prototype, "__uniqueId", {
        writable: true
    });
    Object.defineProperty(Object.prototype, "uniqueId", {
        get: function() {
            if (this.__uniqueId == undefined)
                this.__uniqueId = id_counter++;
            return this.__uniqueId;
        }
    });
}());

For details, see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/defineProperty

What is the difference between Bower and npm?

Found this useful explanation from http://ng-learn.org/2013/11/Bower-vs-npm/

On one hand npm was created to install modules used in a node.js environment, or development tools built using node.js such Karma, lint, minifiers and so on. npm can install modules locally in a project ( by default in node_modules ) or globally to be used by multiple projects. In large projects the way to specify dependencies is by creating a file called package.json which contains a list of dependencies. That list is recognized by npm when you run npm install, which then downloads and installs them for you.

On the other hand bower was created to manage your frontend dependencies. Libraries like jQuery, AngularJS, underscore, etc. Similar to npm it has a file in which you can specify a list of dependencies called bower.json. In this case your frontend dependencies are installed by running bower install which by default installs them in a folder called bower_components.

As you can see, although they perform a similar task they are targeted to a very different set of libraries.

How do I make the text box bigger in HTML/CSS?

According to this answer, here is what it says:

In Javascript, you can manipulate DOM CSS properties, for example:

document.getElementById('textboxid').style.height="200px";
document.getElementById('textboxid').style.fontSize="14pt";

If you simply want to specify the height and font size, use CSS or style attributes, e.g.

//in your CSS file or <style> tag
#textboxid
{
    height:200px;
    font-size:14pt;
}

<!--in your HTML-->
<input id="textboxid" ...>

Or

<input style="height:200px;font-size:14pt;" .....>

jQuery - replace all instances of a character in a string

'some+multi+word+string'.replace(/\+/g, ' ');
                                   ^^^^^^

'g' = "global"

Cheers

Cannot declare instance members in a static class in C#

If the class is declared static, all of the members must be static too.

static NameValueCollection appSetting = ConfigurationManager.AppSettings;

Are you sure you want your employee class to be static? You almost certainly don't want that behaviour. You'd probably be better off removing the static constraint from the class and the members.

Evaluate a string with a switch in C++

You can map the strings to enum values, then switch on the enum:

enum Options {
    Option_Invalid,
    Option1,
    Option2,
    //others...
};

Options resolveOption(string input);

//  ...later...

switch( resolveOption(input) )
{
    case Option1: {
        //...
        break;
    }
    case Option2: {
        //...
        break;
    }
    // handles Option_Invalid and any other missing/unmapped cases
    default: {
        //...
        break;
    }
}

Resolving the enum can be implemented as a series of if checks:

 Options resolveOption(std::string input) {
    if( input == "option1" ) return Option1;
    if( input == "option2" ) return Option2;
    //...
    return Option_Invalid;
 }

Or a map lookup:

 Options resolveOption(std::string input) {
    static const std::map<std::string, Option> optionStrings {
        { "option1", Option1 },
        { "option2", Option2 },
        //...
    };

    auto itr = optionStrings.find(input);
    if( itr != optionStrings.end() ) {
        return *itr;
    }
    return Option_Invalid; 
}

How do I set the timeout for a JAX-WS webservice client?

ProxyWs proxy = (ProxyWs) factory.create();
Client client = ClientProxy.getClient(proxy);
HTTPConduit http = (HTTPConduit) client.getConduit();
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(0);
httpClientPolicy.setReceiveTimeout(0);
http.setClient(httpClientPolicy);

This worked for me.

How to securely save username/password (local)?

I wanted to encrypt and decrypt the string as a readable string.

Here is a very simple quick example in C# Visual Studio 2019 WinForms based on the answer from @Pradip.

Right click project > properties > settings > Create a username and password setting.

enter image description here

Now you can leverage those settings you just created. Here I save the username and password but only encrypt the password in it's respectable value field in the user.config file.

Example of the encrypted string in the user.config file.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <userSettings>
        <secure_password_store.Properties.Settings>
            <setting name="username" serializeAs="String">
                <value>admin</value>
            </setting>
            <setting name="password" serializeAs="String">
                <value>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAQpgaPYIUq064U3o6xXkQOQAAAAACAAAAAAAQZgAAAAEAACAAAABlQQ8OcONYBr9qUhH7NeKF8bZB6uCJa5uKhk97NdH93AAAAAAOgAAAAAIAACAAAAC7yQicDYV5DiNp0fHXVEDZ7IhOXOrsRUbcY0ziYYTlKSAAAACVDQ+ICHWooDDaUywJeUOV9sRg5c8q6/vizdq8WtPVbkAAAADciZskoSw3g6N9EpX/8FOv+FeExZFxsm03i8vYdDHUVmJvX33K03rqiYF2qzpYCaldQnRxFH9wH2ZEHeSRPeiG</value>
            </setting>
        </secure_password_store.Properties.Settings>
    </userSettings>
</configuration>

enter image description here

Full Code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace secure_password_store
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Exit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void Login_Click(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true)
            {
                Properties.Settings.Default.username = textBox1.Text;
                Properties.Settings.Default.password = EncryptString(ToSecureString(textBox2.Text));
                Properties.Settings.Default.Save();
            }
            else if (checkBox1.Checked == false)
            {
                Properties.Settings.Default.username = "";
                Properties.Settings.Default.password = "";
                Properties.Settings.Default.Save();
            }
            MessageBox.Show("{\"data\": \"some data\"}","Login Message Alert",MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        private void DecryptString_Click(object sender, EventArgs e)
        {
            SecureString password = DecryptString(Properties.Settings.Default.password);
            string readable = ToInsecureString(password);
            textBox4.AppendText(readable + Environment.NewLine);
        }
        private void Form_Load(object sender, EventArgs e)
        {
            //textBox1.Text = "UserName";
            //textBox2.Text = "Password";
            if (Properties.Settings.Default.username != string.Empty)
            {
                textBox1.Text = Properties.Settings.Default.username;
                checkBox1.Checked = true;
                SecureString password = DecryptString(Properties.Settings.Default.password);
                string readable = ToInsecureString(password);
                textBox2.Text = readable;
            }
            groupBox1.Select();
        }


        static byte[] entropy = Encoding.Unicode.GetBytes("SaLtY bOy 6970 ePiC");

        public static string EncryptString(SecureString input)
        {
            byte[] encryptedData = ProtectedData.Protect(Encoding.Unicode.GetBytes(ToInsecureString(input)),entropy,DataProtectionScope.CurrentUser);
            return Convert.ToBase64String(encryptedData);
        }

        public static SecureString DecryptString(string encryptedData)
        {
            try
            {
                byte[] decryptedData = ProtectedData.Unprotect(Convert.FromBase64String(encryptedData),entropy,DataProtectionScope.CurrentUser);
                return ToSecureString(Encoding.Unicode.GetString(decryptedData));
            }
            catch
            {
                return new SecureString();
            }
        }

        public static SecureString ToSecureString(string input)
        {
            SecureString secure = new SecureString();
            foreach (char c in input)
            {
                secure.AppendChar(c);
            }
            secure.MakeReadOnly();
            return secure;
        }

        public static string ToInsecureString(SecureString input)
        {
            string returnValue = string.Empty;
            IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(input);
            try
            {
                returnValue = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr);
            }
            finally
            {
                System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr);
            }
            return returnValue;
        }

        private void EncryptString_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.password = EncryptString(ToSecureString(textBox2.Text));
            textBox3.AppendText(Properties.Settings.Default.password.ToString() + Environment.NewLine);
        }
    }
}

Best way to split string into lines

    private string[] GetLines(string text)
    {

        List<string> lines = new List<string>();
        using (MemoryStream ms = new MemoryStream())
        {
            StreamWriter sw = new StreamWriter(ms);
            sw.Write(text);
            sw.Flush();

            ms.Position = 0;

            string line;

            using (StreamReader sr = new StreamReader(ms))
            {
                while ((line = sr.ReadLine()) != null)
                {
                    lines.Add(line);
                }
            }
            sw.Close();
        }



        return lines.ToArray();
    }

angularjs directive call function specified in attribute and pass an argument to it

You can create a directive that executes a function call with params by using the attrName: "&" to reference the expression in the outer scope.

We want to replace the ng-click directive with ng-click-x:

<button ng-click-x="add(a,b)">Add</button>

If we had this scope:

$scope.a = 2;
$scope.b = 2;

$scope.add = function (a, b) {
  $scope.result = parseFloat(a) + parseFloat(b);
}

We could write our directive like so:

angular.module("ng-click-x", [])

.directive('ngClickX', [function () {

  return {

    scope: {

      // Reference the outer scope
      fn: "&ngClickX",

    },

    restrict: "A",

    link: function(scope, elem) {

      function callFn () {
        scope.$apply(scope.fn());
      }

      elem[0].addEventListener('click', callFn);
    }
  };
}]);

Here is a live demo: http://plnkr.co/edit/4QOGLD?p=info

Start thread with member function

Here is a complete example

#include <thread>
#include <iostream>

class Wrapper {
   public:
      void member1() {
          std::cout << "i am member1" << std::endl;
      }
      void member2(const char *arg1, unsigned arg2) {
          std::cout << "i am member2 and my first arg is (" << arg1 << ") and second arg is (" << arg2 << ")" << std::endl;
      }
      std::thread member1Thread() {
          return std::thread([=] { member1(); });
      }
      std::thread member2Thread(const char *arg1, unsigned arg2) {
          return std::thread([=] { member2(arg1, arg2); });
      }
};
int main(int argc, char **argv) {
   Wrapper *w = new Wrapper();
   std::thread tw1 = w->member1Thread();
   std::thread tw2 = w->member2Thread("hello", 100);
   tw1.join();
   tw2.join();
   return 0;
}

Compiling with g++ produces the following result

g++ -Wall -std=c++11 hello.cc -o hello -pthread

i am member1
i am member2 and my first arg is (hello) and second arg is (100)

Check if datetime instance falls in between other two datetime objects

You can, use:

if (date >= startDate && date<= EndDate) { return true; }

How to draw text using only OpenGL methods?

Drawing text in plain OpenGL isn't a straigth-forward task. You should probably have a look at libraries for doing this (either by using a library or as an example implementation).

Some good starting points could be GLFont, OpenGL Font Survey and NeHe Tutorial for Bitmap Fonts (Windows).

Note that bitmaps are not the only way of achieving text in OpenGL as mentioned in the font survey.

How can I measure the actual memory usage of an application or process?

Use the in-built System Monitor GUI tool available in Ubuntu.

Difference between "enqueue" and "dequeue"

Enqueue means to add an element, dequeue to remove an element.

var stackInput= []; // First stack
var stackOutput= []; // Second stack

// For enqueue, just push the item into the first stack
function enqueue(stackInput, item) {
  return stackInput.push(item);
}

function dequeue(stackInput, stackOutput) {
  // Reverse the stack such that the first element of the output stack is the
  // last element of the input stack. After that, pop the top of the output to
  // get the first element that was ever pushed into the input stack
  if (stackOutput.length <= 0) {
    while(stackInput.length > 0) {
      var elementToOutput = stackInput.pop();
      stackOutput.push(elementToOutput);
    }
  }

  return stackOutput.pop();
}

python pandas extract year from datetime: df['year'] = df['date'].year is not working

This works:

df['date'].dt.year

Now:

df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month

gives this data frame:

        date  Count  year  month
0 2010-06-30    525  2010      6
1 2010-07-30    136  2010      7
2 2010-08-31    125  2010      8
3 2010-09-30     84  2010      9
4 2010-10-29   4469  2010     10

Getter and Setter?

After reading the other advices, I'm inclined to say that:

As a GENERIC rule, you will not always define setters for ALL properties, specially "internal" ones (semaphores, internal flags...). Read-only properties will not have setters, obviously, so some properties will only have getters; that's where __get() comes to shrink the code:

  • define a __get() (magical global getters) for all those properties which are alike,
  • group them in arrays so:
    • they'll share common characteristics: monetary values will/may come up properly formatted, dates in an specific layout (ISO, US, Intl.), etc.
    • the code itself can verify that only existing & allowed properties are being read using this magical method.
    • whenever you need to create a new similar property, just declare it and add its name to the proper array and it's done. That's way FASTER than defining a new getter, perhaps with some lines of code REPEATED again and again all over the class code.

Yes! we could write a private method to do that, also, but then again, we'll have MANY methods declared (++memory) that end up calling another, always the same, method. Why just not write a SINGLE method to rule them all...? [yep! pun absolutely intended! :)]

Magic setters can also respond ONLY to specific properties, so all date type properties can be screened against invalid values in one method alone. If date type properties were listed in an array, their setters can be defined easily. Just an example, of course. there are way too many situations.

About readability... Well... That's another debate: I don't like to be bound to the uses of an IDE (in fact, I don't use them, they tend to tell me (and force me) how to write... and I have my likes about coding "beauty"). I tend to be consistent about naming, so using ctags and a couple of other aids is sufficient to me... Anyway: once all this magic setters and getters are done, I write the other setters that are too specific or "special" to be generalized in a __set() method. And that covers all I need about getting and setting properties. Of course: there's not always a common ground, or there are such a few properties that is not worth the trouble of coding a magical method, and then there's still the old good traditional setter/getter pair.

Programming languages are just that: human artificial languages. So, each of them has its own intonation or accent, syntax and flavor, so I won't pretend to write a Ruby or Python code using the same "accent" than Java or C#, nor I would write a JavaScript or PHP to resemble Perl or SQL... Use them the way they're meant to be used.

Change background position with jQuery

Here you go:

$(document).ready(function(){
    $('#submenu li').hover(function(){
        $('#carousel').css('background-position', '10px 10px');
    }, function(){
        $('#carousel').css('background-position', '');
    });
});

JavaScript: IIF like statement

I typed this in my URL bar:

javascript:{ var col = 'screwdriver'; var x = '<option value="' + col + '"' + ((col == 'screwdriver') ? ' selected' : '') + '>Very roomy</option>'; alert(x); }

How to create empty folder in java?

Looks file you use the .mkdirs() method on a File object: http://www.roseindia.net/java/beginners/java-create-directory.shtml

// Create a directory; all non-existent ancestor directories are
// automatically created
success = (new File("../potentially/long/pathname/without/all/dirs")).mkdirs();
if (!success) {
    // Directory creation failed
}

Convert byte[] to char[]

System.Text.Encoding.ChooseYourEncoding.GetString(bytes).ToCharArray();

Substitute the right encoding above: e.g.

System.Text.Encoding.UTF8.GetString(bytes).ToCharArray();

Safe String to BigDecimal conversion

Please try this its working for me

BigDecimal bd ;
String value = "2000.00";

bd = new BigDecimal(value);
BigDecimal currency = bd;

Convert seconds value to hours minutes seconds?

You should have more luck with

hours = roundThreeCalc.divide(var3600, BigDecimal.ROUND_FLOOR);
myremainder = roundThreeCalc.remainder(var3600);
minutes = myremainder.divide(var60, BigDecimal.ROUND_FLOOR);
seconds = myremainder.remainder(var60);

This will drop the decimal values after each division.

Edit: If that didn't work, try this. (I just wrote and tested it)

public static int[] splitToComponentTimes(BigDecimal biggy)
{
    long longVal = biggy.longValue();
    int hours = (int) longVal / 3600;
    int remainder = (int) longVal - hours * 3600;
    int mins = remainder / 60;
    remainder = remainder - mins * 60;
    int secs = remainder;

    int[] ints = {hours , mins , secs};
    return ints;
}

Delete a row from a table by id

From this post, try this javascript:

function removeRow(id) {
  var tr = document.getElementById(id);
  if (tr) {
    if (tr.nodeName == 'TR') {
      var tbl = tr; // Look up the hierarchy for TABLE
      while (tbl != document && tbl.nodeName != 'TABLE') {
        tbl = tbl.parentNode;
      }

      if (tbl && tbl.nodeName == 'TABLE') {
        while (tr.hasChildNodes()) {
          tr.removeChild( tr.lastChild );
        }
      tr.parentNode.removeChild( tr );
      }
    } else {
      alert( 'Specified document element is not a TR. id=' + id );
    }
  } else {
    alert( 'Specified document element is not found. id=' + id );
  }
}

I tried this javascript in a test page and it worked for me in Firefox.

push object into array

can be done like this too.

       let data_array = [];
    
       let my_object = {}; 

       my_object.name = "stack";
       my_object.age = 20;
       my_object.hair_color = "red";
       my_object.eye_color = "green";
        
       data_array.push(my_object);

Rename computer and join to domain in one step with PowerShell

As nobody answer, I try something :

I think I understand why Attent one does not work. It's because joining a computer to a domain is somehow also renaming the computer (the domain name part, enter in the name of the machine).

So do you try to do it in full WMI way, you've got a method in Win32_ComputerSystem class called JoinDomainOrWorkgroup. Doing it on the same level perhaps gives you more chance to make it work.

npm install -g less does not work: EACCES: permission denied

In linux make sure getting all authority with:

sudo su

index.php not loading by default

This one works like a charm!

First

<IfModule dir_module>
    DirectoryIndex index.html
     DirectoryIndex index.php
</IfModule>

then after that from

<Files ".ht*">
    Require all denied
</Files>

to

 <Files ".ht*">
    Require all granted
</Files>

How to avoid Python/Pandas creating an index in a saved csv?

Another solution if you want to keep this column as index.

pd.read_csv('filename.csv', index_col='Unnamed: 0')

How to print an exception in Python?

Python 3: logging

Instead of using the basic print() function, the more flexible logging module can be used to log the exception. The logging module offers a lot extra functionality, e.g. logging messages into a given log file, logging messages with timestamps and additional information about where the logging happened. (For more information check out the official documentation.)

Logging an exception can be done with the module-level function logging.exception() like so:

import logging

try:
    1/0
except BaseException:
    logging.exception("An exception was thrown!")

Output:

ERROR:root:An exception was thrown!
Traceback (most recent call last):
  File ".../Desktop/test.py", line 4, in <module>
    1/0
ZeroDivisionError: division by zero 

Notes:

  • the function logging.exception() should only be called from an exception handler

  • the logging module should not be used inside a logging handler to avoid a RecursionError (thanks @PrakharPandey)


Alternative log-levels

It's also possible to log the exception with another log-level by using the keyword argument exc_info=True like so:

logging.debug("An exception was thrown!", exc_info=True)
logging.info("An exception was thrown!", exc_info=True)
logging.warning("An exception was thrown!", exc_info=True)

Paste multiple columns together

I benchmarked the answers of Anthony Damico, Brian Diggs and data_steve on a small sample tbl_df and got the following results.

> data <- data.frame('a' = 1:3, 
+                    'b' = c('a','b','c'), 
+                    'c' = c('d', 'e', 'f'), 
+                    'd' = c('g', 'h', 'i'))
> data <- tbl_df(data)
> cols <- c("b", "c", "d")
> microbenchmark(
+     do.call(paste, c(data[cols], sep="-")),
+     apply( data[ , cols ] , 1 , paste , collapse = "-" ),
+     tidyr::unite_(data, "x", cols, sep="-")$x,
+     times=1000
+ )
Unit: microseconds
                                         expr     min      lq      mean  median       uq       max neval
do.call(paste, c(data[cols], sep = "-"))       65.248  78.380  93.90888  86.177  99.3090   436.220  1000
apply(data[, cols], 1, paste, collapse = "-") 223.239 263.044 313.11977 289.514 338.5520   743.583  1000
tidyr::unite_(data, "x", cols, sep = "-")$x   376.716 448.120 556.65424 501.877 606.9315 11537.846  1000

However, when I evaluated on my own tbl_df with ~1 million rows and 10 columns the results were quite different.

> microbenchmark(
+     do.call(paste, c(data[c("a", "b")], sep="-")),
+     apply( data[ , c("a", "b") ] , 1 , paste , collapse = "-" ),
+     tidyr::unite_(data, "c", c("a", "b"), sep="-")$c,
+     times=25
+ )
Unit: milliseconds
                                                       expr        min         lq      mean     median        uq       max neval
do.call(paste, c(data[c("a", "b")], sep="-"))                 930.7208   951.3048  1129.334   997.2744  1066.084  2169.147    25
apply( data[ , c("a", "b") ] , 1 , paste , collapse = "-" )  9368.2800 10948.0124 11678.393 11136.3756 11878.308 17587.617    25
tidyr::unite_(data, "c", c("a", "b"), sep="-")$c              968.5861  1008.4716  1095.886  1035.8348  1082.726  1759.349    25

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

Add line break to ::after or ::before pseudo-element content

<p>Break sentence after the comma,<span class="mbr"> </span>in case of mobile version.</p>
<p>Break sentence after the comma,<span class="dbr"> </span>in case of desktop version.</p>

The .mbr and .dbr classes can simulate line-break behavior using CSS display:table. Useful if you want to replace real <br />.

Check out this demo Codepen: https://codepen.io/Marko36/pen/RBweYY,
and this post on responsive site use: Responsive line-breaks: simulate <br /> at given breakpoints.

Compare a date string to datetime in SQL Server?

SELECT  *
FROM    table1
WHERE   CONVERT(varchar(10),columnDatetime,121) = 
        CONVERT(varchar(10),CONVERT('14 AUG 2008' ,smalldatetime),121)

This will convert the datatime and the string into varchars of the format "YYYY-MM-DD".

This is very ugly, but should work

using BETWEEN in WHERE condition

$this->db->where('accommodation BETWEEN '' . $sdate . '' AND '' . $edate . ''');

this is my solution

How to quickly drop a user with existing privileges

In commandline, there is a command dropuser available to do drop user from postgres.

$ dropuser someuser

Jetty: HTTP ERROR: 503/ Service Unavailable

2012-04-20 11:14:32.617:WARN:oejx.XmlParser:FATAL@file:/C:/Users/***/workspace/Test/WEB-INF/web.xml line:1 col:7 : org.xml.sax.SAXParseException: The processing instruction target matching "[xX][mM][lL]" is not allowed.

You Log says, that you web.xml is malformed. Line 1, colum 7. It may be a UTF-8 Byte-Order-Marker

Try to verify, that your xml is wellformed and does not have a BOM. Java doesn't use BOMs.

Only mkdir if it does not exist

if [ ! -d directory ]; then
  mkdir directory
fi

or

mkdir -p directory

-p ensures creation if directory does not exist

CSS Always On Top

Assuming that your markup looks like:

<div id="header" style="position: fixed;"></div>
<div id="content" style="position: relative;"></div>

Now both elements are positioned; in which case, the element at the bottom (in source order) will cover element above it (in source order).

Add a z-index on header; 1 should be sufficient.

Setting background color for a JFrame

You can use this code block for JFrame background color.

    JFrame frame = new JFrame("Frame BG color");
    frame.setLayout(null);
    
    frame.setSize(1000, 650);
    frame.getContentPane().setBackground(new Color(5, 65, 90));
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.setVisible(true);

Sort objects in an array alphabetically on one property of the array

After try a little bit on this, and trying to make less loops as possible, I ended up with this solution:

Demo on codepen

const items = [
      {
        name: 'One'
      },
      {
        name: 'Maria is here'
      },
      {
        name: 'Another'
      },
      {
        name: 'Z with a z'
      },
      {
        name: '1 number'
      },
      {
        name: 'Two not a number'
      },
      {
        name: 'Third'
      },
      {
        name: 'Giant'
      }
    ];

    const sorted = items.sort((a, b) => {
      return a[name] > b[name];
    });

    let sortedAlphabetically = {};

    for(var item in sorted) {
      const firstLetter = sorted[item].name[0];
      if(sortedAlphabetically[firstLetter]) {
        sortedAlphabetically[firstLetter].push(sorted[item]);
      } else {
        sortedAlphabetically[firstLetter] = [sorted[item]]; 
      }
    }

    console.log('sorted', sortedAlphabetically);

How to catch an Exception from a thread

For those who needs to stop all Threads running and re-run all of them when any one of them is stopped on an Exception:

@Override
public void onApplicationEvent(ContextRefreshedEvent event) {

     // could be any function
     getStockHistory();

}


public void getStockHistory() {

     // fill a list of symbol to be scrapped
     List<String> symbolListNYSE = stockEntityRepository
     .findByExchangeShortNameOnlySymbol(ContextRefreshExecutor.NYSE);


    storeSymbolList(symbolListNYSE, ContextRefreshExecutor.NYSE);

}


private void storeSymbolList(List<String> symbolList, String exchange) {

    int total = symbolList.size();

    // I create a list of Thread 
    List<Thread> listThread = new ArrayList<Thread>();

    // For each 1000 element of my scrapping ticker list I create a new Thread
    for (int i = 0; i <= total; i += 1000) {
        int l = i;

        Thread t1 = new Thread() {

            public void run() {

                // just a service that store in DB my ticker list
                storingService.getAndStoreStockPrice(symbolList, l, 1000, 
                MULTIPLE_STOCK_FILL, exchange);

            }

        };

    Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(Thread thread, Throwable exception) {

                // stop thread if still running
                thread.interrupt();

                // go over every thread running and stop every one of them
                listThread.stream().forEach(tread -> tread.interrupt());

                // relaunch all the Thread via the main function
                getStockHistory();
            }
        };

        t1.start();
        t1.setUncaughtExceptionHandler(h);

        listThread.add(t1);

    }

}

To sum up :

You have a main function that create multiple thread, each of them has UncaughtExceptionHandler which is trigger by any Exception inside of a thread. You add every Thread to a List. If a UncaughtExceptionHandler is trigger it will loop through the List, stop every Thread and relaunch the main function recreation all the Thread.

curl error 18 - transfer closed with outstanding read data remaining

I got this error when my server process got an exception midway during generating the response and simply closed the connection without saying goodbye. curl still expected data from the connection and complained (rightfully).

IndentationError expected an indented block

This error also occurs if you have a block with no statements in it

For example:

def my_function():
    for i in range(1,10):


def say_hello():
    return "hello"

Notice that the for block is empty. You can use the pass statement if you want to test the remaining code in the module.

Margin between items in recycler view Android

Use CardView in Recyclerview Item Layout like this :

 <android.support.v7.widget.CardView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:card_view="http://schemas.android.com/tools"
        card_view:cardCornerRadius="10dp"
        app:cardBackgroundColor="#ACACAC"
        card_view:cardElevation="5dp"
        app:contentPadding="10dp"
        card_view:cardUseCompatPadding="true">

How to select a single column with Entity Framework?

Using LINQ your query should look something like this:

public User GetUser(int userID){

return
(
 from p in "MyTable" //(Your Entity Model)
 where p.UserID == userID
 select p.Name
).SingleOrDefault();

}

Of course to do this you need to have an ADO.Net Entity Model in your solution.

Ansible date variable

The lookup module of ansible works fine for me. The yml is:

- hosts: test
  vars:
    time: "{{ lookup('pipe', 'date -d \"1 day ago\" +\"%Y%m%d\"') }}"

You can replace any command with date to get result of the command.

Application.WorksheetFunction.Match method

You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.

I used CountIf below, but there is lots of different ways to check existence of a value in a range.

Public Sub test()

Dim rng As Range
Dim aNumber As Long

aNumber = 666

Set rng = Sheet5.Range("B16:B615")

    If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then

        rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)

    Else
        MsgBox aNumber & " does not exist in range " & rng.Address
    End If

End Sub

ALTERNATIVE WAY

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Long

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    If Not IsError(Application.Match(aNumber, rng, 0)) Then
        rowNum = Application.Match(aNumber, rng, 0)
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

OR

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Variant

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    rowNum = Application.Match(aNumber, rng, 0)

    If Not IsError(rowNum) Then
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

Formatting a field using ToText in a Crystal Reports formula field

if(isnull({uspRptMonthlyGasRevenueByGas;1.YearTotal})) = true then
   "nd"
else
    totext({uspRptMonthlyGasRevenueByGas;1.YearTotal},'###.00')

The above logic should be what you are looking for.

Removing elements from an array in C

Try this simple code:

#include <stdio.h>
#include <conio.h>
void main(void)
{ 
    clrscr();
    int a[4], i, b;
    printf("enter nos ");
    for (i = 1; i <= 5; i++) {
        scanf("%d", &a[i]);
    }
    for(i = 1; i <= 5; i++) {
        printf("\n%d", a[i]);
    }
    printf("\nenter element you want to delete ");
    scanf("%d", &b);
    for (i = 1; i <= 5; i++) {
        if(i == b) {
            a[i] = i++;
        }
        printf("\n%d", a[i]);
    }
    getch();
}

How do you count the number of occurrences of a certain substring in a SQL varchar?

I finally write this function that should cover all the possible situations, adding a char prefix and suffix to the input. this char is evaluated to be different to any of the char conteined in the search parameter, so it can't affect the result.

CREATE FUNCTION [dbo].[CountOccurrency]
(
@Input nvarchar(max),
@Search nvarchar(max)
)
RETURNS int AS
BEGIN
    declare @SearhLength as int = len('-' + @Search + '-') -2;
    declare @conteinerIndex as int = 255;
    declare @conteiner as char(1) = char(@conteinerIndex);
    WHILE ((CHARINDEX(@conteiner, @Search)>0) and (@conteinerIndex>0))
    BEGIN
        set @conteinerIndex = @conteinerIndex-1;
        set @conteiner = char(@conteinerIndex);
    END;
    set @Input = @conteiner + @Input + @conteiner
    RETURN (len(@Input) - len(replace(@Input, @Search, ''))) / @SearhLength
END 

usage

select dbo.CountOccurrency('a,b,c,d ,', ',')

CSS Image size, how to fill, but not stretch?

I think it's quite late for this answer. Anyway hope this will help somebody in the future. I faced the problem positioning the cards in angular. There are cards displayed for array of events. If image width of the event is big for card, the image should be shown by cropping from two sides and height of 100 %. If image height is long, images' bottom part is cropped and width is 100 %. Here is my pure css solution for this:

enter image description here

HTML:

 <span class="block clear img-card b-b b-light text-center" [ngStyle]="{'background-image' : 'url('+event.image+')'}"></span>

CSS

.img-card {
background-repeat: no-repeat;
background-size: cover;
background-position: 50% 50%;
width: 100%;
overflow: hidden;
}

How to truncate float values?

When using a pandas df this worked for me

import math
def truncate(number, digits) -> float:
    stepper = 10.0 ** digits
    return math.trunc(stepper * number) / stepper

df['trunc'] = df['float_val'].apply(lambda x: truncate(x,1))
df['trunc']=df['trunc'].map('{:.1f}'.format)

How to draw lines in Java

To answer your original question, it's (x1, y1) to (x2, y2).

For example,

This is to draw a horizontal line:

g.drawLine( 10, 30, 90, 30 );

vs

This is to draw a vertical line:

g.drawLine( 10, 30, 10, 90 );

I hope it helps.

What is AndroidX?

Android provides a couple of different library sets. One is called the Android support Library, and the other is called AndroidX. Selecting "Use android.* artifacts" indicates that we want to use AndroidX.

String's Maximum length in Java - calling length() method

apparently it's bound to an int, which is 0x7FFFFFFF (2147483647).

C# Dictionary get item by index

You can take keys or values per index:

int value = _dict.Values.ElementAt(5);//ElementAt value should be <= _dict.Count - 1
string key = _dict.Keys.ElementAt(5);//ElementAt value should be  < =_dict.Count - 1

How to undo a SQL Server UPDATE query?

Considering that you already have a full backup I’d just restore that backup into separate database and migrate the data from there.

If your data has changed after the latest backup then what you recover all data that way but you can try to recover that by reading transaction log.

If your database was in full recovery mode than transaction log has enough details to recover updates to your data after the latest backup.

You might want to try with DBCC LOG, fn_log functions or with third party log reader such as ApexSQL Log

Unfortunately there is no easy way to read transaction log because MS doesn’t provide documentation for this and stores the data in its proprietary format.

SQL: ... WHERE X IN (SELECT Y FROM ...)

Maybe try this

Select cust.*

From dbo.Customers cust
Left Join dbo.Subscribers subs on cust.Customer_ID = subs.Customer_ID
Where subs.Customer_Id Is Null

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

Your syntax is pretty screwy.

Change this:

input:not(disabled)not:[type="submit"]:focus{

to:

input:not(:disabled):not([type="submit"]):focus{

Seems that many people don't realize :enabled and :disabled are valid CSS selectors...

Compare two files report difference in python

You can add an conditional statement. If your array goes beyond index, then break and print the rest of the file.

Corrupted Access .accdb file: "Unrecognized Database Format"

Open access, go to the database tools tab, select compact and repair database. You can choose the database from there.

Can we write our own iterator in Java?

This is the complete code to write an iterator such that it iterates over elements that begin with 'a':

import java.util.Iterator;

public class AppDemo {

    public static void main(String args[]) {

        Bag<String> bag1 = new Bag<>();

        bag1.add("alice");
        bag1.add("bob"); 
        bag1.add("abigail");
        bag1.add("charlie"); 

        for (Iterator<String> it1 = bag1.iterator(); it1.hasNext();) {

            String s = it1.next();
            if (s != null)
                System.out.println(s); 
        }
    }
}

Custom Iterator class

import java.util.ArrayList;
import java.util.Iterator;

public class Bag<T> {

    private ArrayList<T> data;

    public Bag() {

        data = new ArrayList<>();
    }

    public void add(T e) {

        data.add(e); 
    }

    public Iterator<T> iterator() {

        return new BagIterator();
    }

    public class BagIterator<T> implements Iterator<T> {

        private int index; 
        private String str;

        public BagIterator() {

            index = 0;
        }

        @Override
        public boolean hasNext() {

             return index < data.size();  
        }

        @Override
        public T next() {

            str = (String) data.get(index); 
            if (str.startsWith("a"))
                return (T) data.get(index++); 
            index++; 
            return null; 
        }
    } 
}

Create a Maven project in Eclipse complains "Could not resolve archetype"

Add your MAVEN_HOME environment variable, edit your Path to include %MAVEN_HOME%/bin then try creating the project manually with Maven:

mvn archetype:generate -DgroupId=com.program -DartifactId=Program -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

Then import the existing Maven project to Eclipse.

How to open a Bootstrap modal window using jQuery?

In addition you can use via data attribute

<button type="button" data-toggle="modal" data-target="#myModal">Launch modal</button>

In this particular case you don't need to write javascript.

You can see more here: http://getbootstrap.com/2.3.2/javascript.html#modals

how to get request path with express req object

To supplement, here is an example expanded from the documentation, which nicely wraps all you need to know about accessing the paths/URLs in all cases with express:

app.use('/admin', function (req, res, next) { // GET 'http://www.example.com/admin/new?a=b'
  console.dir(req.originalUrl) // '/admin/new?a=b' (WARNING: beware query string)
  console.dir(req.baseUrl) // '/admin'
  console.dir(req.path) // '/new'
  console.dir(req.baseUrl + req.path) // '/admin/new' (full path without query string)
  next()
})

Based on: https://expressjs.com/en/api.html#req.originalUrl

Conclusion: As c1moore's answer states, use:

var fullPath = req.baseUrl + req.path;

What is the difference between a database and a data warehouse?

A data warehouse is a TYPE of database.

In addition to what folks have already said, data warehouses tend to be OLAP, with indexes, etc. tuned for reading, not writing, and the data is de-normalized / transformed into forms that are easier to read & analyze.

Some folks have said "databases" are the same as OLTP -- this isn't true. OLTP, again, is a TYPE of database.

Other types of "databases": Text files, XML, Excel, CSV..., Flat Files :-)

How to create id with AUTO_INCREMENT on Oracle?

Assuming you mean a column like the SQL Server identity column?

In Oracle, you use a SEQUENCE to achieve the same functionality. I'll see if I can find a good link and post it here.

Update: looks like you found it yourself. Here is the link anyway: http://www.techonthenet.com/oracle/sequences.php

How to bind Close command to a button

One option that I've found to work is to set this function up as a Behavior.

The Behavior:

    public class WindowCloseBehavior : Behavior<Window>
{
    public bool Close
    {
        get { return (bool) GetValue(CloseTriggerProperty); }
        set { SetValue(CloseTriggerProperty, value); }
    }

    public static readonly DependencyProperty CloseTriggerProperty =
        DependencyProperty.Register("Close", typeof(bool), typeof(WindowCloseBehavior),
            new PropertyMetadata(false, OnCloseTriggerChanged));

    private static void OnCloseTriggerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var behavior = d as WindowCloseBehavior;

        if (behavior != null)
        {
            behavior.OnCloseTriggerChanged();
        }
    }

    private void OnCloseTriggerChanged()
    {
        // when closetrigger is true, close the window
        if (this.Close)
        {
            this.AssociatedObject.Close();
        }
    }
}

On the XAML Window, you set up a reference to it and bind the Behavior's Close property to a Boolean "Close" property on your ViewModel:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
<i:Interaction.Behaviors>
    <behavior:WindowCloseBehavior Close="{Binding Close}" />
</i:Interaction.Behaviors>

So, from the View assign an ICommand to change the Close property on the ViewModel which is bound to the Behavior's Close property. When the PropertyChanged event is fired the Behavior fires the OnCloseTriggerChanged event and closes the AssociatedObject... which is the Window.

Python unittest passing arguments

Have a same problem. My solution is after you handle with parsing arguments using argparse or other way, remove arguments from sys.argv

sys.argv = sys.argv[:1]  

If you need you can filter unittest arguments from main.parseArgs()

Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

Never ever should you use money. It is not precise, and it is pure garbage; always use decimal/numeric.

Run this to see what I mean:

DECLARE
    @mon1 MONEY,
    @mon2 MONEY,
    @mon3 MONEY,
    @mon4 MONEY,
    @num1 DECIMAL(19,4),
    @num2 DECIMAL(19,4),
    @num3 DECIMAL(19,4),
    @num4 DECIMAL(19,4)

    SELECT
    @mon1 = 100, @mon2 = 339, @mon3 = 10000,
    @num1 = 100, @num2 = 339, @num3 = 10000

    SET @mon4 = @mon1/@mon2*@mon3
    SET @num4 = @num1/@num2*@num3

    SELECT @mon4 AS moneyresult,
    @num4 AS numericresult

Output: 2949.0000 2949.8525

To some of the people who said that you don't divide money by money:

Here is one of my queries to calculate correlations, and changing that to money gives wrong results.

select t1.index_id,t2.index_id,(avg(t1.monret*t2.monret)
    -(avg(t1.monret) * avg(t2.monret)))
            /((sqrt(avg(square(t1.monret)) - square(avg(t1.monret))))
            *(sqrt(avg(square(t2.monret)) - square(avg(t2.monret))))),
current_timestamp,@MaxDate
            from Table1 t1  join Table1 t2  on t1.Date = traDate
            group by t1.index_id,t2.index_id

What is the advantage of using heredoc in PHP?

First of all, all the reasons are subjective. It's more like a matter of taste rather than a reason.

Personally, I find heredoc quite useless and use it occasionally, most of the time when I need to get some HTML into a variable and don't want to bother with output buffering, to form an HTML email message for example.

Formatting doesn't fit general indentation rules, but I don't think it's a big deal.

       //some code at it's proper level
       $this->body = <<<HERE
heredoc text sticks to the left border
but it seems OK to me.
HERE;
       $this->title = "Feedback";
       //and so on

As for the examples in the accepted answer, it is merely cheating.
String examples, in fact, being more concise if one won't cheat on them

$sql = "SELECT * FROM $tablename
        WHERE id in [$order_ids_list]
        AND product_name = 'widgets'";

$x = 'The point of the "argument" was to illustrate the use of here documents';

Pass multiple values with onClick in HTML link

function ReAssign(valautionId, userName) {
   var valautionId 
   var userName 
 alert(valautionId);
 alert(userName);
  }

<a href=# onclick="return ReAssign('valuationId','user')">Re-Assign</a>

How can I calculate an md5 checksum of a directory?

For the sake of completeness, there's md5deep(1); it's not directly applicable due to *.py filter requirement but should do fine together with find(1).

Using DataContractSerializer to serialize, but can't deserialize back

Other solution is:

public static T Deserialize<T>(string rawXml)
{
    using (XmlReader reader = XmlReader.Create(new StringReader(rawXml)))
    {
        DataContractSerializer formatter0 = 
            new DataContractSerializer(typeof(T));
        return (T)formatter0.ReadObject(reader);
    }
}

One remark: sometimes it happens that raw xml contains e.g.:

<?xml version="1.0" encoding="utf-16"?>

then of course you can't use UTF8 encoding used in other examples..

Different CURRENT_TIMESTAMP and SYSDATE in oracle

Note: SYSDATE - returns only date, i.e., "yyyy-mm-dd" is not correct. SYSDATE returns the system date of the database server including hours, minutes, and seconds. For example:

SELECT SYSDATE FROM DUAL; will return output similar to the following: 12/15/2017 12:42:39 PM

Pandas group-by and sum

Both the other answers accomplish what you want.

You can use the pivot functionality to arrange the data in a nice table

df.groupby(['Fruit','Name'],as_index = False).sum().pivot('Fruit','Name').fillna(0)



Name    Bob     Mike    Steve   Tom    Tony
Fruit                   
Apples  16.0    9.0     10.0    0.0     0.0
Grapes  35.0    0.0     0.0     87.0    15.0
Oranges 67.0    57.0    0.0     15.0    1.0

Android - Package Name convention

The package name is used for unique identification for your application.
Android uses the package name to determine if the application has been installed or not.
The general naming is:

com.companyname.applicationname

eg:

com.android.Camera

ImportError: No module named xlsxwriter

Here are some easy way to get you up and running with the XlsxWriter module.The first step is to install the XlsxWriter module.The pip installer is the preferred method for installing Python modules from PyPI, the Python Package Index:

sudo pip install xlsxwriter

Note

Windows users can omit sudo at the start of the command.

How to get the first element of an array?

You can use the combination of reverse then pop. The idea is to reverse the array then pop which will get you the last item in that array.

Be careful as this will modify the original array.

_x000D_
_x000D_
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];_x000D_
var first = fruits.reverse().pop();_x000D_
  _x000D_
console.log('First element -->', first);_x000D_
console.log('Original array -->', fruits);
_x000D_
_x000D_
_x000D_

How to list files using dos commands?

Try dir /b, for bare format.

dir /? will show you documentation of what you can do with the dir command. Here is the output from my Windows 7 machine:

C:\>dir /?
Displays a list of files and subdirectories in a directory.

DIR [drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D] [/L] [/N]
  [/O[[:]sortorder]] [/P] [/Q] [/R] [/S] [/T[[:]timefield]] [/W] [/X] [/4]

  [drive:][path][filename]
              Specifies drive, directory, and/or files to list.

  /A          Displays files with specified attributes.
  attributes   D  Directories                R  Read-only files
               H  Hidden files               A  Files ready for archiving
               S  System files               I  Not content indexed files
               L  Reparse Points             -  Prefix meaning not
  /B          Uses bare format (no heading information or summary).
  /C          Display the thousand separator in file sizes.  This is the
              default.  Use /-C to disable display of separator.
  /D          Same as wide but files are list sorted by column.
  /L          Uses lowercase.
  /N          New long list format where filenames are on the far right.
  /O          List by files in sorted order.
  sortorder    N  By name (alphabetic)       S  By size (smallest first)
               E  By extension (alphabetic)  D  By date/time (oldest first)
               G  Group directories first    -  Prefix to reverse order
  /P          Pauses after each screenful of information.
  /Q          Display the owner of the file.
  /R          Display alternate data streams of the file.
  /S          Displays files in specified directory and all subdirectories.
  /T          Controls which time field displayed or used for sorting
  timefield   C  Creation
              A  Last Access
              W  Last Written
  /W          Uses wide list format.
  /X          This displays the short names generated for non-8dot3 file
              names.  The format is that of /N with the short name inserted
              before the long name. If no short name is present, blanks are
              displayed in its place.
  /4          Displays four-digit years

Switches may be preset in the DIRCMD environment variable.  Override
preset switches by prefixing any switch with - (hyphen)--for example, /-W.

Jackson with JSON: Unrecognized field, not marked as ignorable

Adding setters and getters solved the problem, what I felt is the actual issue was how to solve it but not how to suppress/ignore the error. I got the error "Unrecognized field.. not marked as ignorable.."

Though I use the below annotation on top of the class it was not able to parse the json object and give me the input

@JsonIgnoreProperties(ignoreUnknown = true)

Then I realized that I did not add setters and getters, after adding setters and getters to the "Wrapper" and to the "Student" it worked like a charm.

Why do I get access denied to data folder when using adb?

Starting from API level 8 (Android 2.2), for the debuggable application (the one built by Android Studio all the times unless the release build was requested), you can use the shell run-as command to run a command or executable as a specific user/application or just switch to the UID of your application so you can access its data directory.

List directory content of yourapp:

run-as com.yourapp ls -l /data/data/com.yourapp

Switch to UID of com.yourapp and run all further commands using that uid (until you call exit):

run-as com.yourapp
cd /data/data/com.yourapp
ls -l
exit

 
Note 1: there is a known issue with some HTC Desire phones. Because of a non-standard owner/permissions of the /data/data directory, run-as command fails to run on those phones.

Note 2: As pointed in the comments by @Avio: run-as has issues also with Samsung Galaxy S phones running Cyanogenmod at any version (from 7 to 10.1) because on this platform /data/data is a symlink to /datadata. One way to solve the issue is to replace the symlink with the actual directory (unfortunately this usually requires root access).

Fragment Inside Fragment

There is no support for MapFragment, Android team says is working on it since Android 3.0. Here more information about the issue But what you can do it by creating a Fragment that returns a MapActivity. Here is a code example. Thanks to inazaruk:

How it works :

  • MainFragmentActivity is the activity that extends FragmentActivity and hosts two MapFragments.
  • MyMapActivity extends MapActivity and has MapView.
  • LocalActivityManagerFragment hosts LocalActivityManager.
  • MyMapFragment extends LocalActivityManagerFragment and with help of TabHost creates internal instance of MyMapActivity.

If you have any doubt please let me know

How to print multiple variable lines in Java

You can create Class Person with fields firstName and lastName and define method toString(). Here I created a util method which returns String presentation of a Person object.

This is a sample

Main

public class Main {

    public static void main(String[] args) {
        Person person = generatePerson();
        String personStr = personToString(person);
        System.out.println(personStr);
    }

    private static Person generatePerson() {
        String firstName = "firstName";//generateFirstName();
        String lastName = "lastName";//generateLastName;
        return new Person(firstName, lastName);
    }

    /*
     You can even put this method into a separate util class.
    */
    private static String personToString(Person person) {
        return person.getFirstName() + "\n" + person.getLastName();
    }
}

Person

public class Person {

    private String firstName;
    private String lastName;

    //getters, setters, constructors.
}

I prefer a separate util method to toString(), because toString() is used for debug. https://stackoverflow.com/a/3615741/4587961

I had experience writing programs with many outputs: HTML UI, excel or txt file, console. They may need different object presentation, so I created a util class which builds a String depending on the output.

How to list only top level directories in Python?

os.walk

Use os.walk with next item function:

next(os.walk('.'))[1]

For Python <=2.5 use:

os.walk('.').next()[1]

How this works

os.walk is a generator and calling next will get the first result in the form of a 3-tuple (dirpath, dirnames, filenames). Thus the [1] index returns only the dirnames from that tuple.

How can I read a large text file line by line using Java?

I usually do the reading routine straightforward:

void readResource(InputStream source) throws IOException {
    BufferedReader stream = null;
    try {
        stream = new BufferedReader(new InputStreamReader(source));
        while (true) {
            String line = stream.readLine();
            if(line == null) {
                break;
            }
            //process line
            System.out.println(line)
        }
    } finally {
        closeQuiet(stream);
    }
}

static void closeQuiet(Closeable closeable) {
    if (closeable != null) {
        try {
            closeable.close();
        } catch (IOException ignore) {
        }
    }
}

GetFiles with multiple extensions

Why not create an extension method? That's more readable.

public static IEnumerable<FileInfo> GetFilesByExtensions(this DirectoryInfo dir, params string[] extensions)
{
    if (extensions == null) 
         throw new ArgumentNullException("extensions");
    IEnumerable<FileInfo> files = Enumerable.Empty<FileInfo>();
    foreach(string ext in extensions)
    {
       files = files.Concat(dir.GetFiles(ext));
    }
    return files;
}

EDIT: a more efficient version:

public static IEnumerable<FileInfo> GetFilesByExtensions(this DirectoryInfo dir, params string[] extensions)
{
    if (extensions == null) 
         throw new ArgumentNullException("extensions");
    IEnumerable<FileInfo> files = dir.EnumerateFiles();
    return files.Where(f => extensions.Contains(f.Extension));
}

Usage:

DirectoryInfo dInfo = new DirectoryInfo(@"c:\MyDir");
dInfo.GetFilesByExtensions(".jpg",".exe",".gif");

What is the simplest way to SSH using Python?

I haven't tried it, but this pysftp module might help, which in turn uses paramiko. I believe everything is client-side.

The interesting command is probably .execute() which executes an arbitrary command on the remote machine. (The module also features .get() and .put methods which allude more to its FTP character).

UPDATE:

I've re-written the answer after the blog post I originally linked to is not available anymore. Some of the comments that refer to the old version of this answer will now look weird.

SQL query with avg and group by

If I understand what you need, try this:

SELECT id, pass, AVG(val) AS val_1 
FROM data_r1 
GROUP BY id, pass;

Or, if you want just one row for every id, this:

SELECT d1.id,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 1) as val_1,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 2) as val_2,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 3) as val_3,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 4) as val_4,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 5) as val_5,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 6) as val_6,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 7) as val_7
from data_r1 d1
GROUP BY d1.id

WhatsApp API (java/python)

From my blog

courtesy

There is a secret pilot program which WhatsApp is working on with selected businesses

News coverage:

For some of my technical experiments, I was trying to figure out how beneficial and feasible it is to implement bots for different chat platforms in terms of market share and so possibilities of adaptation. Especially when you have bankruptly failed twice, it's important to validate ideas and fail more faster.

Popular chat platforms like Messenger, Slack, Skype etc. have happily (in the sense officially) provided APIs for bots to interact with, but WhatsApp has not yet provided any API.

However, since many years, a lot of activities has happened around this - struggle towards automated interaction with WhatsApp platform:

  1. Bots App Bots App is interesting because it shows that something is really tried and tested.

  2. Yowsup A project still actively developed to interact with WhatsApp platform.

  3. Yallagenie Yallagenie claim that there is a demo bot which can be interacted with at +971 56 112 6652

  4. Hubtype Hubtype is working towards having a bot platform for WhatsApp for business.

  5. Fred Fred's task was to automate WhatsApp conversations, however since it was not officially supported by WhatsApp - it was shut down.

  6. Oye Gennie A bot blocked by WhatsApp.

  7. App/Website to WhatsApp We can use custom URL schemes and Android intent system to interact with WhatsApp but still NOT WhatsApp API.

  8. Chat API daemon Probably created by inspecting the API calls in WhatsApp web version. NOT affiliated with WhatsApp.

  9. WhatsBot Deactivated WhatsApp bot. Created during a hackathon.

  10. No API claim WhatsApp co-founder clearly stated this in a conference that they did not had any plans for APIs for WhatsApp.

  11. Bot Ware They probably are expecting WhatsApp to release their APIs for chat bot platforms.

  12. Vixi They seems to be talking about how some platform which probably would work for WhatsApp. There is no clarity as such.

  13. Unofficial API This API can shut off any time.

    And the number goes on...

How do I escape double and single quotes in sed?

Regarding the single quote, see the code below used to replace the string let's with let us:

command:

echo "hello, let's go"|sed 's/let'"'"'s/let us/g'

result:

hello, let us go

Redirecting exec output to a buffer or file

After forking, use dup2(2) to duplicate the file's FD into stdout's FD, then exec.

jQuery won't parse my JSON from AJAX query

This problem is usually because your request received the wrong mime type. When developing on your own computer, sometimes you are not receiving the proper mime type from the "server", which is your own computer. I ran into this problem once when developing by opening the locally stored file in the browser (e.g. the url was "c:/project/test.html").

Try using the beforeSend property to add a callback function that overrides the mime type. This will trick the code into dealing with json despite the wrong mime type being sent by the server and received by your calling code. Some example code is below.

The proper mime type is application/json according to this question, but I do know that application/j-son worked when I tried it (now several years ago). You should probably try application/json first.

var jsonMimeType = "application/json;charset=UTF-8";
$.ajax({
 type: "GET",
 url: myURL,
 beforeSend: function(x) {
  if(x && x.overrideMimeType) {
   x.overrideMimeType(jsonMimeType);
  }
 },
 dataType: "json",
 success: function(data){
  // do stuff...
 }
});