Programs & Examples On #Getstate

No String-argument constructor/factory method to deserialize from String value ('')

mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

My code work well just as the answer above. The reason is that the json from jackson is different with the json sent from controller.

String test1= mapper.writeValueAsString(result1);

And the json is like(which can be deserialized normally):

{"code":200,"message":"god","data":[{"nics":null,"status":null,"desktopOperatorType":null,"marker":null,"user_name":null,"user_group":null,"user_email":null,"product_id":null,"image_id":null,"computer_name":"AAAA","desktop_id":null,"created":null,"ip_address":null,"security_groups":null,"root_volume":null,"data_volumes":null,"availability_zone":null,"ou_name":null,"login_status":null,"desktop_ip":null,"ad_id":null},{"nics":null,"status":null,"desktopOperatorType":null,"marker":null,"user_name":null,"user_group":null,"user_email":null,"product_id":null,"image_id":null,"computer_name":"BBBB","desktop_id":null,"created":null,"ip_address":null,"security_groups":null,"root_volume":null,"data_volumes":null,"availability_zone":null,"ou_name":null,"login_status":null,"desktop_ip":null,"ad_id":null}]}

but the json send from the another service just like:

{"code":200,"message":"????????","data":[{"nics":"","status":"","metadata":"","desktopOperatorType":"","marker":"","user_name":"csrgzbsjy","user_group":"ADMINISTRATORS","user_email":"","product_id":"","image_id":"","computer_name":"B-jiegou-all-15","desktop_id":"6360ee29-eb82-416b-aab8-18ded887e8ff","created":"2018-11-12T07:45:15.000Z","ip_address":"192.168.2.215","security_groups":"","root_volume":"","data_volumes":"","availability_zone":"","ou_name":"","login_status":"","desktop_ip":"","ad_id":""},{"nics":"","status":"","metadata":"","desktopOperatorType":"","marker":"","user_name":"glory_2147","user_group":"ADMINISTRATORS","user_email":"","product_id":"","image_id":"","computer_name":"H-pkpm-all-357","desktop_id":"709164e4-d3e6-495d-9c1e-a7b82e30bc83","created":"2018-11-09T09:54:09.000Z","ip_address":"192.168.2.235","security_groups":"","root_volume":"","data_volumes":"","availability_zone":"","ou_name":"","login_status":"","desktop_ip":"","ad_id":""}]}

You can notice the difference when dealing with the param without initiation. Be careful

Accessing Redux state in an action creator?

When your scenario is simple you can use

import store from '../store';

export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
  return {
    type: SOME_ACTION,
    items: store.getState().otherReducer.items,
  }
}

But sometimes your action creator need to trigger multi actions

for example async request so you need REQUEST_LOAD REQUEST_LOAD_SUCCESS REQUEST_LOAD_FAIL actions

export const [REQUEST_LOAD, REQUEST_LOAD_SUCCESS, REQUEST_LOAD_FAIL] = [`REQUEST_LOAD`
    `REQUEST_LOAD_SUCCESS`
    `REQUEST_LOAD_FAIL`
]
export function someAction() {
    return (dispatch, getState) => {
        const {
            items
        } = getState().otherReducer;
        dispatch({
            type: REQUEST_LOAD,
            loading: true
        });
        $.ajax('url', {
            success: (data) => {
                dispatch({
                    type: REQUEST_LOAD_SUCCESS,
                    loading: false,
                    data: data
                });
            },
            error: (error) => {
                dispatch({
                    type: REQUEST_LOAD_FAIL,
                    loading: false,
                    error: error
                });
            }
        })
    }
}

Note: you need redux-thunk to return function in action creator

Pretty Printing JSON with React

The 'react-json-view' provides solution rendering json string.

import ReactJson from 'react-json-view';
<ReactJson src={my_important_json} theme="monokai" />

Android: Internet connectivity change listener

This my implementation which you can providing in application scope:

class NetworkStateHelper @Inject constructor(
        private val context: Context
) {
    private val cache: BehaviorSubject<Boolean> = BehaviorSubject.create()

    private val receiver = object : BroadcastReceiver() {
        override fun onReceive(c: Context?, intent: Intent?) {
            cache.onNext(isOnlineOrConnecting())
        }
    }

    init {
        val intentFilter = IntentFilter()
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
        context.registerReceiver(receiver, intentFilter)
        cache.onNext(isOnlineOrConnecting())
    }

    fun subscribe(): Observable<Boolean> {
        return cache
    }

    fun isOnlineOrConnecting(): Boolean {
        val cm = context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val netInfo = cm.activeNetworkInfo
        return netInfo != null && netInfo.isConnectedOrConnecting
    }
}

I used this rxjava and dagger2 libraies

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

NullPointerExceptions are among the easier exceptions to diagnose, frequently. Whenever you get an exception in Java and you see the stack trace ( that's what your second quote-block is called, by the way ), you read from top to bottom. Often, you will see exceptions that start in Java library code or in native implementations methods, for diagnosis you can just skip past those until you see a code file that you wrote.

Then you like at the line indicated and look at each of the objects ( instantiated classes ) on that line -- one of them was not created and you tried to use it. You can start by looking up in your code to see if you called the constructor on that object. If you didn't, then that's your problem, you need to instantiate that object by calling new Classname( arguments ). Another frequent cause of NullPointerExceptions is accidentally declaring an object with local scope when there is an instance variable with the same name.

In your case, the exception occurred in your constructor for Workshop on line 75. <init> means the constructor for a class. If you look on that line in your code, you'll see the line

denimjeansButton.addItemListener(this);

There are fairly clearly two objects on this line: denimjeansButton and this. this is synonymous with the class instance you are currently in and you're in the constructor, so it can't be this. denimjeansButton is your culprit. You never instantiated that object. Either remove the reference to the instance variable denimjeansButton or instantiate it.

error C2220: warning treated as error - no 'object' file generated

The error says that a warning was treated as an error, therefore your problem is a warning message! The object file is then not created because there was an error. So you need to check your warnings and fix them.

In case you don't know how to find them: Open the Error List (View > Error List) and click on Warning.

How to programmatically log out from Facebook SDK 3.0 without using Facebook login/logout button?

private Session.StatusCallback statusCallback = new SessionStatusCallback();

logout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Session.openActiveSession(this, true, statusCallback);  
}
});

private class SessionStatusCallback implements Session.StatusCallback {
@Override
public void call(Session session, SessionState state,
Exception exception) {
session.closeAndClearTokenInformation();    
}
}

android activity has leaked window com.android.internal.policy.impl.phonewindow$decorview Issue

 @Override
    protected void onPostExecute(final Boolean success) {
        mProgressDialog.dismiss();
        mProgressDialog = null;

setting the value null works for me

nginx: send all requests to a single html page

Using just try_files didn't work for me - it caused a rewrite or internal redirection cycle error in my logs.

The Nginx docs had some additional details:

http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files

So I ended up using the following:

root /var/www/mysite;

location / {
    try_files $uri /base.html;
}

location = /base.html {
    expires 30s;
}

Android: How to Enable/Disable Wifi or Internet Connection Programmatically

This method is deprecated now from now starting with Android Q.

Try This will really help.

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {// if build version is less than Q try the old traditional method
                    if (!wifiManager.isWifiEnabled()) {
                        wifiManager.setWifiEnabled(true);
                        btnOnOff.setText("Wifi ONN");
                    } else {
                        wifiManager.setWifiEnabled(false);
                        btnOnOff.setText("Wifi OFF");
                    }
                } else {// if it is Android Q and above go for the newer way    NOTE: You can also use this code for less than android Q also
                    Intent panelIntent = new Intent(Settings.Panel.ACTION_WIFI);
                    startActivityForResult(panelIntent, 1);
                }

Razor view engine - How can I add Partial Views

If you don't want to duplicate code, and like me you just want to show stats, in your view model, you could just pass in the models you want to get data from like so:

public class GameViewModel
{
    public virtual Ship Ship { get; set; }
    public virtual GamePlayer GamePlayer { get; set; }     
}

Then, in your controller just run your queries on the respective models, pass them to the view model and return it, example:

GameViewModel PlayerStats = new GameViewModel();

GamePlayer currentPlayer = (from c in db.GamePlayer [more queries]).FirstOrDefault();

[code to check if results]

//pass current player into custom view model
PlayerStats.GamePlayer = currentPlayer;

Like I said, you should only really do this if you want to display stats from the relevant tables, and there's no other part of the CRUD process happening, for security reasons other people have mentioned above.

Http Basic Authentication in Java using HttpClient?

Here are a few points:

  • You could consider upgrading to HttpClient 4 (generally speaking, if you can, I don't think version 3 is still actively supported).

  • A 500 status code is a server error, so it might be useful to see what the server says (any clue in the response body you're printing?). Although it might be caused by your client, the server shouldn't fail this way (a 4xx error code would be more appropriate if the request is incorrect).

  • I think setDoAuthentication(true) is the default (not sure). What could be useful to try is pre-emptive authentication works better:

    client.getParams().setAuthenticationPreemptive(true);
    

Otherwise, the main difference between curl -d "" and what you're doing in Java is that, in addition to Content-Length: 0, curl also sends Content-Type: application/x-www-form-urlencoded. Note that in terms of design, you should probably send an entity with your POST request anyway.

How to populate a dropdownlist with json data in jquery?

var listItems= "";
var jsonData = jsonObj.d;
    for (var i = 0; i < jsonData.Table.length; i++){
      listItems+= "<option value='" + jsonData.Table[i].stateid + "'>" + jsonData.Table[i].statename + "</option>";
    }
    $("#<%=DLState.ClientID%>").html(listItems);

Example

   <html>
    <head></head>
    <body>
      <select id="DLState">
      </select>
    </body>
    </html>

    /*javascript*/
    var jsonList = {"Table" : [{"stateid" : "2","statename" : "Tamilnadu"},
                {"stateid" : "3","statename" : "Karnataka"},
                {"stateid" : "4","statename" : "Andaman and Nicobar"},
                 {"stateid" : "5","statename" : "Andhra Pradesh"},
                 {"stateid" : "6","statename" : "Arunachal Pradesh"}]}

    $(document).ready(function(){
      var listItems= "";
      for (var i = 0; i < jsonList.Table.length; i++){
        listItems+= "<option value='" + jsonList.Table[i].stateid + "'>" + jsonList.Table[i].statename + "</option>";
      }
      $("#DLState").html(listItems);
    });    

jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

I was looking through source 1.3.2, when using JSONP, the request is made by building a SCRIPT element dynamically, which gets past the browsers Same-domain policy. Naturally, you can't make a POST request using a SCRIPT element, the browser would fetch the result using GET.

As you are requesting a JSONP call, the SCRIPT element is not generated, because it only does this when the Type of AJAX call is set to GET.

http://dev.jquery.com/ticket/4690

ASP.NET / C#: DropDownList SelectedIndexChanged in server control not firing

You need to set AutoPostBack to true for the Country DropDownList.

protected override void OnLoad(EventArgs e)
{
    // base stuff

    ddlCountries.AutoPostBack = true;

    // other stuff
}

Edit

I missed that you had done this. In that case you need to check that ViewState is enabled.

Why are unnamed namespaces used and what are their benefits?

Unnamed namespace limits access of class,variable,function and objects to the file in which it is defined. Unnamed namespace functionality is similar to static keyword in C/C++.
static keyword limits access of global variable and function to the file in which they are defined.
There is difference between unnamed namespace and static keyword because of which unnamed namespace has advantage over static. static keyword can be used with variable, function and objects but not with user defined class.
For example:

static int x;  // Correct 

But,

static class xyz {/*Body of class*/} //Wrong
static structure {/*Body of structure*/} //Wrong

But same can be possible with unnamed namespace. For example,

 namespace {
           class xyz {/*Body of class*/}
           static structure {/*Body of structure*/}
  } //Correct

Communication between tabs or windows

For those searching for a solution not based on jQuery, this is a plain JavaScript version of the solution provided by Thomas M:

window.addEventListener("storage", message_receive);

function message_broadcast(message) {
    localStorage.setItem('message',JSON.stringify(message));
}

function message_receive(ev) {
    if (ev.key == 'message') {
        var message=JSON.parse(ev.newValue);
    }
}

Use css gradient over background image

Ok, I solved it by adding the url for the background image at the end of the line.

Here's my working code:

_x000D_
_x000D_
.css {_x000D_
  background: -moz-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, rgba(0, 0, 0, 0)), color-stop(59%, rgba(0, 0, 0, 0)), color-stop(100%, rgba(0, 0, 0, 0.65))), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  background: -webkit-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  background: -o-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  background: -ms-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  height: 200px;_x000D_
_x000D_
}
_x000D_
<div class="css"></div>
_x000D_
_x000D_
_x000D_

How to switch to the new browser window, which opens after click on the button?

Modify registry for IE:

ie_x64_tabprocgrowth.png

  1. HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main
  2. Right-click ? New ? String Value ? Value name: TabProcGrowth (create if not exist)
  3. TabProcGrowth (right-click) ? Modify... ? Value data: 0

Source: Selenium WebDriver windows switching issue in Internet Explorer 8-10

For my case, IE began detecting new window handles after the registry edit.

Taken from the MSDN Blog:

Tab Process Growth : Sets the rate at which IE creates New Tab processes.

The "Max-Number" algorithm: This specifies the maximum number of tab processes that may be executed for a single isolation session for a single frame process at a specific mandatory integrity level (MIC). Relative values are:

  • TabProcGrowth=0 : tabs and frames run within the same process; frames are not unified across MIC levels.
  • TabProcGrowth =1: all tabs for a given frame process run in a single tab process for a given MIC level.

Source: Opening a New Tab may launch a New Process with Internet Explorer 8.0


Internet Options:

  • Security ? Untick Enable Protected Mode for all zones (Internet, Local intranet, Trusted sites, Restricted sites)
  • Advanced ? Security ? Untick Enable Enhanced Protected Mode

Code:

Browser: IE11 x64 (Zoom: 100%)
OS: Windows 7 x64
Selenium: 3.5.1
WebDriver: IEDriverServer x64 3.5.1

public static String openWindow(WebDriver driver, By by) throws IOException {
String parentHandle = driver.getWindowHandle(); // Save parent window
WebElement clickableElement = driver.findElement(by);
clickableElement.click(); // Open child window
WebDriverWait wait = new WebDriverWait(driver, 10); // Timeout in 10s
boolean isChildWindowOpen = wait.until(ExpectedConditions.numberOfWindowsToBe(2));
if (isChildWindowOpen) {
    Set<String> handles = driver.getWindowHandles();
    // Switch to child window
    for (String handle : handles) {
        driver.switchTo().window(handle);
        if (!parentHandle.equals(handle)) {
            break;
        }
    }
    driver.manage().window().maximize();
}
return parentHandle; // Returns parent window if need to switch back
}



/* How to use method */
String parentHandle = Selenium.openWindow(driver, by);

// Do things in child window
driver.close();

// Return to parent window
driver.switchTo().window(parentHandle);

The above code includes an if-check to make sure you are not switching to the parent window as Set<T> has no guaranteed ordering in Java. WebDriverWait appears to increase the chance of success as supported by below statement.

Quoted from Luke Inman-Semerau: (Developer for Selenium)

The browser may take time to acknowledge the new window, and you may be falling into your switchTo() loop before the popup window appears.

You automatically assume that the last window returned by getWindowHandles() will be the last one opened. That's not necessarily true, as they are not guaranteed to be returned in any order.

Source: Unable to handle a popup in IE,control is not transferring to popup window


Related Posts:

How to pass a textbox value from view to a controller in MVC 4?

Try the following in your view to check the output from each. The first one updates when the view is called a second time. My controller uses the key ShowCreateButton and has the optional parameter _createAction with a default value - you can change this to your key/parameter

@Html.TextBox("_createAction", null, new { Value = (string)ViewBag.ShowCreateButton })
@Html.TextBox("_createAction", ViewBag.ShowCreateButton )
@ViewBag.ShowCreateButton

How to push a docker image to a private repository

You need to tag your image correctly first with your registryhost:

docker tag [OPTIONS] IMAGE[:TAG] [REGISTRYHOST/][USERNAME/]NAME[:TAG]

Then docker push using that same tag.

docker push NAME[:TAG]

Example:

docker tag 518a41981a6a myRegistry.com/myImage
docker push myRegistry.com/myImage

A beginner's guide to SQL database design

These are questions which, in my opionion, requires different knowledge from different domains.

  1. You just can't know in advance "which" tables to build, you have to know the problem you have to solve and design the schema accordingly;
  2. This is a mix of database design decision and your database vendor custom capabilities (ie. you should check the documentation of your (r)dbms and eventually learn some "tips & tricks" for scaling), also the configuration of your dbms is crucial for scaling (replication, data partitioning and so on);
  3. again, almost every rdbms comes with a particular "dialect" of the SQL language, so if you want efficient queries you have to learn that particular dialect --btw. much probably write elegant query which are also efficient is a big deal: elegance and efficiency are frequently conflicting goals--

That said, maybe you want to read some books, personally I've used this book in my datbase university course (and found a decent one, but I've not read other books in this field, so my advice is to check out for some good books in database design).

How can I copy a file on Unix using C?

Another variant of the copy function using normal POSIX calls and without any loop. Code inspired from the buffer copy variant of the answer of caf. Warning: Using mmap can easily fail on 32 bit systems, on 64 bit system the danger is less likely.

#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <sys/mman.h>

int cp(const char *to, const char *from)
{
  int fd_from = open(from, O_RDONLY);
  if(fd_from < 0)
    return -1;
  struct stat Stat;
  if(fstat(fd_from, &Stat)<0)
    goto out_error;

  void *mem = mmap(NULL, Stat.st_size, PROT_READ, MAP_SHARED, fd_from, 0);
  if(mem == MAP_FAILED)
    goto out_error;

  int fd_to = creat(to, 0666);
  if(fd_to < 0)
    goto out_error;

  ssize_t nwritten = write(fd_to, mem, Stat.st_size);
  if(nwritten < Stat.st_size)
    goto out_error;

  if(close(fd_to) < 0) {
    fd_to = -1;
    goto out_error;
  }
  close(fd_from);

  /* Success! */
  return 0;
}
out_error:;
  int saved_errno = errno;

  close(fd_from);
  if(fd_to >= 0)
    close(fd_to);

  errno = saved_errno;
  return -1;
}

EDIT: Corrected the file creation bug. See comment in http://stackoverflow.com/questions/2180079/how-can-i-copy-a-file-on-unix-using-c/2180157#2180157 answer.

How to debug Lock wait timeout exceeded on MySQL?

As someone mentioned in one of the many SO threads concerning this problem: Sometimes the process that has locked the table shows up as sleeping in the processlist! I was tearing my hair out until I killed all the sleeping threads that were open in the database in question (none were active at the time). That finally unlocked the table and let the update query run.

The commenter said something akin to "Sometimes a MySQL thread locks a table, then sleeps while it waits for something non-MySQL-related to happen."

After re-re-reviewing the show engine innodb status log (once I'd tracked down the client responsible for the lock), I noticed the stuck thread in question was listed at the very bottom of the transaction list, beneath the active queries that were about to error out because of the frozen lock:

------------------
---TRANSACTION 2744943820, ACTIVE 1154 sec(!!)
2 lock struct(s), heap size 376, 2 row lock(s), undo log entries 1
MySQL thread id 276558, OS thread handle 0x7f93762e7710, query id 59264109 [ip] [database] cleaning up
Trx read view will not see trx with id >= 2744943821, sees < 2744943821

(unsure if the "Trx read view" message is related to the frozen lock, but unlike the other active transactions, this one does not show up with the query that was issued and instead claims the transaction is "cleaning up," yet has multiple row locks)

The moral of the story is that a transaction can be active even though the thread is sleeping.

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)

If for any chance you don't have to Xcode or had to delete it, e.g. in a situation when you needed to free up disc space in order to perform update simply install Xcode from the App Store. Once it'll be done and when you'll be launching this for the first time Xcode will ask you if you'd like to install components, click Install and it'll fix the issue as well.

Vuex - passing multiple parameters to mutation

Mutations expect two arguments: state and payload, where the current state of the store is passed by Vuex itself as the first argument and the second argument holds any parameters you need to pass.

The easiest way to pass a number of parameters is to destruct them:

mutations: {
    authenticate(state, { token, expiration }) {
        localStorage.setItem('token', token);
        localStorage.setItem('expiration', expiration);
    }
}

Then later on in your actions you can simply

store.commit('authenticate', {
    token,
    expiration,
});

Using Javamail to connect to Gmail smtp server ignores specified port and tries to use 25

In Java you would do something similar to:

Transport transport = session.getTransport("smtps");
transport.connect (smtp_host, smtp_port, smtp_username, smtp_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();    

Note 'smtpS' protocol. Also socketFactory properties is no longer necessary in modern JVMs but you might need to set 'mail.smtps.auth' and 'mail.smtps.starttls.enable' to 'true' for Gmail. 'mail.smtps.debug' could be helpful too.

Converting a factor to numeric without losing information R (as.numeric() doesn't seem to work)

First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.

For example,

> z <- factor(letters[c(3, 2, 3, 4)])

# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d

# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"

here, z has 4 elements.
The index is 2, 1, 2, 3 in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.

Then, as.numeric converts simply the index part of factor into numeric.
as.character handles the index and levels, and generates character vector expressed by its level.

?as.numeric says that Factors are handled by the default method.

CSS: background image on background color

For me this solution didn't work out:

background-color: #6DB3F2;
background-image: url('images/checked.png');

But instead it worked the other way:

<div class="block">
<span>
...
</span>
</div>

the css:

.block{
  background-image: url('img.jpg') no-repeat;
  position: relative;
}

.block::before{
  background-color: rgba(0, 0, 0, 0.37);
  content: '';
  display: block;
  height: 100%;
  position: absolute;
  width: 100%;
}

Imply bit with constant 1 or 0 in SQL Server

No, but you could cast the whole expression rather than the sub-components of that expression. Actually, that probably makes it less readable in this case.

Redirecting to a page after submitting form in HTML

For anyone else having the same problem, I figured it out myself.

_x000D_
_x000D_
    <html>_x000D_
      <body>_x000D_
        <form target="_blank" action="https://website.com/action.php" method="POST">_x000D_
          <input type="hidden" name="fullname" value="Sam" />_x000D_
          <input type="hidden" name="city" value="Dubai&#32;" />_x000D_
          <input onclick="window.location.href = 'https://website.com/my-account';" type="submit" value="Submit request" />_x000D_
        </form>_x000D_
      </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

All I had to do was add the target="_blank" attribute to inline on form to open the response in a new page and redirect the other page using onclick on the submit button.

How to change ReactJS styles dynamically?

Ok, finally found the solution.

Probably due to lack of experience with ReactJS and web development...

    var Task = React.createClass({
    render: function() {
      var percentage = this.props.children + '%';
      ....
        <div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
      ...

I created the percentage variable outside in the render function.

How can I get all element values from Request.Form without specifying exactly which one with .GetValues("ElementIdName")

Waqas Raja's answer with some LINQ lambda fun:

List<int> listValues = new List<int>();
Request.Form.AllKeys
    .Where(n => n.StartsWith("List"))
    .ToList()
    .ForEach(x => listValues.Add(int.Parse(Request.Form[x])));

The controller for path was not found or does not implement IController

I hope this helps someone else. I had this problem because, while I had the controller named properly, the class inside the file had a typo in it. I was looking for OrderSearch and the file was OrderSearchController.cs, but the class was OrdersSearchController.

Obviously, they should match, but they don't have to, and your route targets the class, not the filename.

CSS image resize percentage of itself?

This is a very old thread but I found it while searching for a simple solution to display retina (high res) screen capture on standard resolution display.

So there is an HTML only solution for modern browsers :

<img srcset="image.jpg 100w" sizes="50px" src="image.jpg"/>

This is telling the browser that the image is twice the dimension of it intended display size. The value are proportional and do not need to reflect the actual size of the image. One can use 2w 1px as well to achieve the same effect. The src attribute is only used by legacy browsers.

The nice effect of it is that it display the same size on retina or standard display, shrinking on the latter.

Avoid printStackTrace(); use a logger call instead

It means you should use logging framework like or and instead of printing exceptions directly:

e.printStackTrace();

you should log them using this frameworks' API:

log.error("Ops!", e);

Logging frameworks give you a lot of flexibility, e.g. you can choose whether you want to log to console or file - or maybe skip some messages if you find them no longer relevant in some environment.

css with background image without repeating the image

body {
    background: url(images/image_name.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

Here is a good solution to get your image to cover the full area of the web app perfectly

Save internal file in my own internal folder in Android

Save:

public boolean saveFile(Context context, String mytext){
    Log.i("TESTE", "SAVE");
    try {
        FileOutputStream fos = context.openFileOutput("file_name"+".txt",Context.MODE_PRIVATE);
        Writer out = new OutputStreamWriter(fos);
        out.write(mytext);
        out.close();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

Load:

public String load(Context context){
    Log.i("TESTE", "FILE");
    try {
        FileInputStream fis = context.openFileInput("file_name"+".txt");
        BufferedReader r = new BufferedReader(new InputStreamReader(fis));
        String line= r.readLine();
        r.close();
        return line;
    } catch (IOException e) {
        e.printStackTrace();
        Log.i("TESTE", "FILE - false");
        return null;
    }
}

How do I set a value in CKEditor with Javascript?

Sets the editor data. The data must be provided in the raw format (HTML). CKEDITOR.instances.editor1.setData( 'Put your Data.' ); refer this page

Spring RestTemplate timeout

  1. RestTemplate timeout with SimpleClientHttpRequestFactory To programmatically override the timeout properties, we can customize the SimpleClientHttpRequestFactory class as below.

Override timeout with SimpleClientHttpRequestFactory

//Create resttemplate
RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());

//Override timeouts in request factory
private SimpleClientHttpRequestFactory getClientHttpRequestFactory() 
{
    SimpleClientHttpRequestFactory clientHttpRequestFactory
                      = new SimpleClientHttpRequestFactory();
    //Connect timeout
    clientHttpRequestFactory.setConnectTimeout(10_000);

    //Read timeout
    clientHttpRequestFactory.setReadTimeout(10_000);
    return clientHttpRequestFactory;
}
  1. RestTemplate timeout with HttpComponentsClientHttpRequestFactory SimpleClientHttpRequestFactory helps in setting timeout but it is very limited in functionality and may not prove sufficient in realtime applications. In production code, we may want to use HttpComponentsClientHttpRequestFactory which support HTTP Client library along with resttemplate.

HTTPClient provides other useful features such as connection pool, idle connection management etc.

Read More : Spring RestTemplate + HttpClient configuration example

Override timeout with HttpComponentsClientHttpRequestFactory

//Create resttemplate
RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());

//Override timeouts in request factory
private SimpleClientHttpRequestFactory getClientHttpRequestFactory() 
{
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory
                      = new HttpComponentsClientHttpRequestFactory();
    //Connect timeout
    clientHttpRequestFactory.setConnectTimeout(10_000);

    //Read timeout
    clientHttpRequestFactory.setReadTimeout(10_000);
    return clientHttpRequestFactory;
}

reference: Spring RestTemplate timeout configuration example

How to fetch data from local JSON file on react native?

Take a look at this Github issue:

https://github.com/facebook/react-native/issues/231

They are trying to require non-JSON files, in particular JSON. There is no method of doing this right now, so you either have to use AsyncStorage as @CocoOS mentioned, or you could write a small native module to do what you need to do.

How to send a JSON object over Request with Android?

Nothing could be simple than this. Use OkHttpLibrary

Create your json

JSONObject requestObject = new JSONObject();
requestObject.put("Email", email);
requestObject.put("Password", password);

and send it like this.

OkHttpClient client = new OkHttpClient();

RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
            .addHeader("Content-Type","application/json")
            .url(url)
            .post(requestObject.toString())
            .build();

okhttp3.Response response = client.newCall(request).execute();

How to break out of the IF statement

This is a variation of something I learned several years back. Apparently, this is popular with C++ developers.

First off, I think I know why you want to break out of IF blocks. For me, I don't like a bunch of nested blocks because 1) it makes the code look messy and 2) it can be a pia to maintain if you have to move logic around.

Consider a do/while loop instead:

public void Method()
{
    bool something = true, something2 = false;

    do
    {
        if (!something) break;

        if (something2) break;

    } while (false);
}

The do/while loop is guaranteed to run only once just like an IF block thanks to the hardcoded false condition. When you want to exit early, just break.

How to stop an app on Heroku?

You can disable the app using enable maintenance mode from the admin panel.

  • Go to settings tabs.
  • In bottom just before deleting the app. enable maintenance mode. see in the screenshot below.

enter image description here

Present and dismiss modal view controller

The easiest way i tired in xcode 4.52 was to create an additional view and connect them by using segue modal(control drag the button from view one to the second view, chose Modal). Then drag in a button to second view or the modal view that you created. Control and drag this button to the header file and use action connection. This will create an IBaction in your controller.m file. Find your button action type in the code.

[self dismissViewControllerAnimated:YES completion:nil];

An exception of type 'System.NullReferenceException' occurred in myproject.DLL but was not handled in user code

It means somewhere in your chain of calls, you tried to access a Property or call a method on an object that was null.

Given your statement:

img1.ImageUrl = ConfigurationManager
                    .AppSettings
                    .Get("Url")
                    .Replace("###", randomString) 
                + Server.UrlEncode(
                      ((System.Web.UI.MobileControls.Form)Page
                      .FindControl("mobileForm"))
                      .Title);

I'm guessing either the call to AppSettings.Get("Url") is returning null because the value isn't found or the call to Page.FindControl("mobileForm") is returning null because the control isn't found.

You could easily break this out into multiple statements to solve the problem:

var configUrl = ConfigurationManager.AppSettings.Get("Url");
var mobileFormControl = Page.FindControl("mobileForm")
                            as System.Web.UI.MobileControls.Form;

if(configUrl != null && mobileFormControl != null)
{
    img1.ImageUrl = configUrl.Replace("###", randomString) + mobileControl.Title;
}

How to highlight a selected row in ngRepeat?

I needed something similar, the ability to click on a set of icons to indicate a choice, or a text-based choice and have that update the model (2-way-binding) with the represented value and to also a way to indicate which was selected visually. I created an AngularJS directive for it, since it needed to be flexible enough to handle any HTML element being clicked on to indicate a choice.

<ul ng-repeat="vote in votes" ...>
    <li data-choice="selected" data-value="vote.id">...</li>
</ul>

Solution: http://jsfiddle.net/brandonmilleraz/5fr9V/

What is the difference between 'typedef' and 'using' in C++11?

They are largely the same, except that:

The alias declaration is compatible with templates, whereas the C style typedef is not.

How can I connect to MySQL on a WAMP server?

Change localhost:8080 to localhost:3306.

How can I convert a zero-terminated byte array to string?

When you do not know the exact length of non-nil bytes in the array, you can trim it first:

string(bytes.Trim(arr, "\x00"))

How to scroll to top of a div using jQuery?

This is my solution to scroll to the top on a button click.

$(".btn").click(function () {
if ($(this).text() == "Show options") {
$(".tabs").animate(
  {
    scrollTop: $(window).scrollTop(0)
  },
  "slow"
 );
 }
});

Remove all classes that begin with a certain string

You don't need any jQuery specific code to handle this. Just use a RegExp to replace them:

$("#a").className = $("#a").className.replace(/\bbg.*?\b/g, '');

You can modify this to support any prefix but the faster method is above as the RegExp will be compiled only once:

function removeClassByPrefix(el, prefix) {
    var regx = new RegExp('\\b' + prefix + '.*?\\b', 'g');
    el.className = el.className.replace(regx, '');
    return el;
}

Java - How to convert type collection into ArrayList?

public <E> List<E> collectionToList(Collection<E> collection)
{
    return (collection instanceof List) ? (List<E>) collection : new ArrayList<E>(collection);
}

Use the above method for converting the collection to list

Add Class to Object on Page Load

I would recommend using jQuery with this function:

$(document).ready(function(){
 $('#about').addClass('expand');
});

This will add the expand class to an element with id of about when the dom is ready on page load.

Get a particular cell value from HTML table using JavaScript

You can get cell value with JS even when click on the cell:

.......................

      <head>

        <title>Search students by courses/professors</title>

        <script type="text/javascript">

        function ChangeColor(tableRow, highLight)
        {
           if (highLight){
               tableRow.style.backgroundColor = '00CCCC';
           }

        else{
             tableRow.style.backgroundColor = 'white';
            }   
      }

      function DoNav(theUrl)
      {
      document.location.href = theUrl;
      }
      </script>

    </head>
    <body>

         <table id = "c" width="180" border="1" cellpadding="0" cellspacing="0">

                <% for (Course cs : courses){ %>

                <tr onmouseover="ChangeColor(this, true);" 
                    onmouseout="ChangeColor(this, false);" 
                    onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');">

                     <td name = "title" align = "center"><%= cs.getTitle() %></td>

                </tr>
               <%}%>

    ........................
    </body>

I wrote the HTML table in JSP. Course is is a type. For example Course cs, cs= object of type Course which had 2 attributes: id, title. courses is an ArrayList of Course objects.

The HTML table displays all the courses titles in each cell. So the table has 1 column only: Course1 Course2 Course3 ...... Taking aside:

onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');"

This means that after user selects a table cell, for example "Course2", the title of the course- "Course2" will travel to the page where the URL is directing the user: http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp . "Course2" will arrive in FoundS.jsp page. The identifier of "Course2" is courseId. To declare the variable courseId, in which CourseX will be kept, you put a "?" after the URL and next to it the identifier.

I told you just in case you'll want to use it because I searched a lot for it and I found questions like mine. But now I found out from teacher so I post where people asked.

The example is working.I've seen.

Executing a shell script from a PHP script

It's a simple problem. When you are running from terminal, you are running the php file from terminal as a privileged user. When you go to the php from your web browser, the php script is being run as the web server user which does not have permissions to execute files in your home directory. In Ubuntu, the www-data user is the apache web server user. If you're on ubuntu you would have to do the following: chown yourusername:www-data /home/testuser/testscript chmod g+x /home/testuser/testscript

what the above does is transfers user ownership of the file to you, and gives the webserver group ownership of it. the next command gives the group executable permission to the file. Now the next time you go ahead and do it from the browser, it should work.

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

You just change the App_Start/WebApiConfig.cs like this:

public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();
        //Below formatter is used for returning the Json result.
        var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
        config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
        //Default route
        config.Routes.MapHttpRoute(
           name: "ApiControllerOnly",
           routeTemplate: "api/{controller}"
       );
    }

enable/disable zoom in Android WebView

The solution you posted seems to work in stopping the zoom controls from appearing when the user drags, however there are situations where a user will pinch zoom and the zoom controls will appear. I've noticed that there are 2 ways that the webview will accept pinch zooming, and only one of them causes the zoom controls to appear despite your code:

User Pinch Zooms and controls appear:

ACTION_DOWN
getSettings().setBuiltInZoomControls(false); getSettings().setSupportZoom(false);
ACTION_POINTER_2_DOWN
getSettings().setBuiltInZoomControls(true); getSettings().setSupportZoom(true);
ACTION_MOVE (Repeat several times, as the user moves their fingers)
ACTION_POINTER_2_UP
ACTION_UP

User Pinch Zoom and Controls don't appear:

ACTION_DOWN
getSettings().setBuiltInZoomControls(false); getSettings().setSupportZoom(false);
ACTION_POINTER_2_DOWN
getSettings().setBuiltInZoomControls(true); getSettings().setSupportZoom(true);
ACTION_MOVE (Repeat several times, as the user moves their fingers)
ACTION_POINTER_1_UP
ACTION_POINTER_UP
ACTION_UP

Can you shed more light on your solution?

Jquery- Get the value of first td in table

Install firebug and use console.log instead of alert. Then you will see the exact element your accessing.

Truncating Text in PHP?

$mystring = "this is the text I would like to truncate";

// Pass your variable to the function
$mystring = truncate($mystring);

// Truncated tring printed out;
echo $mystring;

//truncate text function
public function truncate($text) {

    //specify number fo characters to shorten by
    $chars = 25;

    $text = $text." ";
    $text = substr($text,0,$chars);
    $text = substr($text,0,strrpos($text,' '));
    $text = $text."...";
    return $text;
}

Centering the image in Bootstrap

Use This as the solution

This worked for me perfectly..

<div align="center">
   <img src="">
</div>

NSUserDefaults - How to tell if a key exists

Swift version to get Bool?

NSUserDefaults.standardUserDefaults().objectForKey(DefaultsIsGiver) as? Bool

Preventing SQL injection in Node.js

The node-mysql library automatically performs escaping when used as you are already doing. See https://github.com/felixge/node-mysql#escaping-query-values

C# string does not contain possible?

So you can utilize short-circuiting:

bool containsBoth = compareString.Contains(firstString) && 
                    compareString.Contains(secondString);

How do I calculate r-squared using Python and Numpy?

You can execute this code directly, this will find you the polynomial, and will find you the R-value you can put a comment down below if you need more explanation.

from scipy.stats import linregress
import numpy as np

x = np.array([1,2,3,4,5,6])
y = np.array([2,3,5,6,7,8])

p3 = np.polyfit(x,y,3) # 3rd degree polynomial, you can change it to any degree you want
xp = np.linspace(1,6,6)  # 6 means the length of the line
poly_arr = np.polyval(p3,xp)

poly_list = [round(num, 3) for num in list(poly_arr)]
slope, intercept, r_value, p_value, std_err = linregress(x, poly_list)
print(r_value**2)

Converting a JToken (or string) to a given Type

System.Convert.ChangeType(jtoken.ToString(), targetType);

or

JsonConvert.DeserializeObject(jtoken.ToString(), targetType);

--EDIT--

Uzair, Here is a complete example just to show you they work

string json = @"{
        ""id"" : 77239923,
        ""username"" : ""UzEE"",
        ""email"" : ""[email protected]"",
        ""name"" : ""Uzair Sajid"",
        ""twitter_screen_name"" : ""UzEE"",
        ""join_date"" : ""2012-08-13T05:30:23Z05+00"",
        ""timezone"" : 5.5,
        ""access_token"" : {
            ""token"" : ""nkjanIUI8983nkSj)*#)(kjb@K"",
            ""scope"" : [ ""read"", ""write"", ""bake pies"" ],
            ""expires"" : 57723
        },
        ""friends"" : [{
            ""id"" : 2347484,
            ""name"" : ""Bruce Wayne""
        },
        {
            ""id"" : 996236,
            ""name"" : ""Clark Kent""
        }]
    }";

var obj = (JObject)JsonConvert.DeserializeObject(json);
Type type = typeof(int);
var i1 = System.Convert.ChangeType(obj["id"].ToString(), type);
var i2 = JsonConvert.DeserializeObject(obj["id"].ToString(), type);

Copying Code from Inspect Element in Google Chrome

Click on the line or element you want to copy. Copy to clipboard. Paste.

The only tricky thing is if you click on a line, you get everything that line includes if it was folded. For example if you click on a div, and copy, you get everything that the div includes.

You can also get only what you want by Right Clicking, and select 'Edit as HTML'. This will make that section essentially text, with none of the folding activated. You can then select, copy and paste the relevant bits.

How to access global js variable in AngularJS directive

I created a working CodePen example demonstrating how to do this the correct way in AngularJS. The Angular $window service should be used to access any global objects since directly accessing window makes testing more difficult.

HTML:

<section ng-app="myapp" ng-controller="MainCtrl">
  Value of global variable read by AngularJS: {{variable1}}
</section>

JavaScript:

// global variable outside angular
var variable1 = true;

var app = angular.module('myapp', []);

app.controller('MainCtrl', ['$scope', '$window', function($scope, $window) {
  $scope.variable1 = $window.variable1;
}]);

change background image in body

You would need to use Javascript for this. You can set the style of the background-image for the body like so.

var body = document.getElementsByTagName('body')[0];
body.style.backgroundImage = 'url(http://localhost/background.png)';

Just make sure you replace the URL with the actual URL.

How can I append a string to an existing field in MySQL?

You need to use the CONCAT() function in MySQL for string concatenation:

UPDATE categories SET code = CONCAT(code, '_standard') WHERE id = 1;

Endless loop in C/C++

They are the same. But I suggest "while(ture)" which has best representation.

urllib2.HTTPError: HTTP Error 403: Forbidden

NSE website has changed and the older scripts are semi-optimum to current website. This snippet can gather daily details of security. Details include symbol, security type, previous close, open price, high price, low price, average price, traded quantity, turnover, number of trades, deliverable quantities and ratio of delivered vs traded in percentage. These conveniently presented as list of dictionary form.

Python 3.X version with requests and BeautifulSoup

from requests import get
from csv import DictReader
from bs4 import BeautifulSoup as Soup
from datetime import date
from io import StringIO 

SECURITY_NAME="3MINDIA" # Change this to get quote for another stock
START_DATE= date(2017, 1, 1) # Start date of stock quote data DD-MM-YYYY
END_DATE= date(2017, 9, 14)  # End date of stock quote data DD-MM-YYYY


BASE_URL = "https://www.nseindia.com/products/dynaContent/common/productsSymbolMapping.jsp?symbol={security}&segmentLink=3&symbolCount=1&series=ALL&dateRange=+&fromDate={start_date}&toDate={end_date}&dataType=PRICEVOLUMEDELIVERABLE"




def getquote(symbol, start, end):
    start = start.strftime("%-d-%-m-%Y")
    end = end.strftime("%-d-%-m-%Y")

    hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
         'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
         'Referer': 'https://cssspritegenerator.com',
         'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
         'Accept-Encoding': 'none',
         'Accept-Language': 'en-US,en;q=0.8',
         'Connection': 'keep-alive'}

    url = BASE_URL.format(security=symbol, start_date=start, end_date=end)
    d = get(url, headers=hdr)
    soup = Soup(d.content, 'html.parser')
    payload = soup.find('div', {'id': 'csvContentDiv'}).text.replace(':', '\n')
    csv = DictReader(StringIO(payload))
    for row in csv:
        print({k:v.strip() for k, v in row.items()})


 if __name__ == '__main__':
     getquote(SECURITY_NAME, START_DATE, END_DATE)

Besides this is relatively modular and ready to use snippet.

How to BULK INSERT a file into a *temporary* table where the filename is a variable?

It is possible to do everything you want. Aaron's answer was not quite complete.

His approach is correct, up to creating the temporary table in the inner query. Then, you need to insert the results into a table in the outer query.

The following code snippet grabs the first line of a file and inserts it into the table @Lines:

declare @fieldsep char(1) = ',';
declare @recordsep char(1) = char(10);

declare @Lines table (
    line varchar(8000)
);

declare @sql varchar(8000) = ' 
    create table #tmp (
        line varchar(8000)
    );

    bulk insert #tmp
        from '''+@filename+'''
        with (FirstRow = 1, FieldTerminator = '''+@fieldsep+''', RowTerminator = '''+@recordsep+''');

    select * from #tmp';

insert into @Lines
    exec(@sql);

select * from @lines

Cannot start GlassFish 4.1 from within Netbeans 8.0.1 Service area

I also had this problem, it is because there is an application LISTENING to 8080 port. To solve this problem I followed the below steps:

  1. Open cmd.exe then type

    netstat -aon | find ":8080" | find "LISTENING"

  2. You will see like this result

    TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 1464

  3. Copy PID "1464".

  4. Open Task Manager (Ctrl+Alt+del), go to the details tag, then find the program or service via PID that is listening to the port 8080 then STOP it or End process.

Get MAC address using shell script

Simply run:

ifconfig | grep ether | cut -d " " -f10

OR

ip a | grep ether | cut -d " " -f6

These two example commands will grep all lines with "ether" string and cut the mac address (that we need) following the number spaces (specified in the -f option) of the grepped portion.

Tested on different Linux flavors

C++ initial value of reference to non-const must be an lvalue

The &nKByte creates a temporary value, which cannot be bound to a reference to non-const.

You could change void test(float *&x) to void test(float * const &x) or you could just drop the pointer altogether and use void test(float &x); /*...*/ test(nKByte);.

Express.js req.body undefined

This is also one possibility: Make Sure that you should write this code before the route in your app.js(or index.js) file.

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

How to specify preference of library path?

As an alternative, you can use the environment variables LIBRARY_PATH and CPLUS_INCLUDE_PATH, which respectively indicate where to look for libraries and where to look for headers (CPATH will also do the job), without specifying the -L and -I options.

Edit: CPATH includes header with -I and CPLUS_INCLUDE_PATH with -isystem.

JDBC connection to MSSQL server in windows authentication mode

You need to add sqljdbc_auth.dll in your C:/windows/System32 folder. You can download it from http://www.microsoft.com/en-us/download/details.aspx?displaylang=en&id=11774 .

How to avoid .pyc files?

Starting with Python 3.8 you can use the environment variable PYTHONPYCACHEPREFIX to define a cache directory for Python.

From the Python docs:

If this is set, Python will write .pyc files in a mirror directory tree at this path, instead of in pycache directories within the source tree. This is equivalent to specifying the -X pycache_prefix=PATH option.

Example

If you add the following line to your ./profile in Linux:

export PYTHONPYCACHEPREFIX="$HOME/.cache/cpython/"

Python won't create the annoying __pycache__ directories in your project directory, instead it will put all of them under ~/.cache/cpython/

How to empty/destroy a session in rails?

to delete a user's session

session.delete(:user_id)

ClassNotFoundException com.mysql.jdbc.Driver

If you're facing this problem with Eclipse, I've been following many different solutions but the one that worked for me is this:

  1. Right click your project folder and open up Properties.

  2. From the right panel, select Java Build Path then go to Libraries tab.

  3. Select Add External JARs to import the mysql driver.

  4. From the right panel, select Deployment Assembly.

  5. Select Add..., then select Java Build Path Entries and click Next.

  6. You should see the sql driver on the list. Select it and click first.

And that's it! Try to run it again! Cheers!

Read remote file with node.js (http.get)

function(url,callback){
    request(url).on('data',(data) => {
        try{
            var json = JSON.parse(data);    
        }
        catch(error){
            callback("");
        }
        callback(json);
    })
}

You can also use this. This is to async flow. The error comes when the response is not a JSON. Also in 404 status code .

How to clean old dependencies from maven repositories?

Just clean every content under .m2-->repository folder.When you build project all dependencies load here.

In your case may be your project earlier was using old version of any dependency and now version is upgraded.So better clean .m2 folder and build your project with mvn clean install.

Now dependencies with latest version modules will be downloaded in this folder.

Read XLSX file in Java

Apache POI 3.5 have added support to all the OOXML (docx, xlsx, etc.)

See the XSSF sub project

How to write data to a JSON file using Javascript

Unfortunatelly, today (September 2018) you can not find cross-browser solution for client side file writing.

For example: in some browser like a Chrome we have today this possibility and we can write with FileSystemFileEntry.createWriter() with client side call, but according to the docu:

This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.


For IE (but not MS Edge) we could use ActiveX too, but this is only for this client.

If you want update your JSON file cross-browser you have to use server and client side together.

The client side script

On client side you can make a request to the server and then you have to read the response from server. Or you could read a file with FileReader too. For the cross-browser writing to the file you have to have some server (see below on server part).

var xhr = new XMLHttpRequest(),
    jsonArr,
    method = "GET",
    jsonRequestURL = "SOME_PATH/jsonFile/";

xhr.open(method, jsonRequestURL, true);
xhr.onreadystatechange = function()
{
    if(xhr.readyState == 4 && xhr.status == 200)
    {
        // we convert your JSON into JavaScript object
        jsonArr = JSON.parse(xhr.responseText);

        // we add new value:
        jsonArr.push({"nissan": "sentra", "color": "green"});

        // we send with new request the updated JSON file to the server:
        xhr.open("POST", jsonRequestURL, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        // if you want to handle the POST response write (in this case you do not need it):
        // xhr.onreadystatechange = function(){ /* handle POST response */ };
        xhr.send("jsonTxt="+JSON.stringify(jsonArr));
        // but on this place you have to have a server for write updated JSON to the file
    }
};
xhr.send(null);

Server side scripts

You can use a lot of different servers, but I would like to write about PHP and Node.js servers.

By using searching machine you could find "free PHP Web Hosting*" or "free Node.js Web Hosting". For PHP server I would recommend 000webhost.com and for Node.js I would recommend to see and to read this list.

PHP server side script solution

The PHP script for reading and writing from JSON file:

<?php

// This PHP script must be in "SOME_PATH/jsonFile/index.php"

$file = 'jsonFile.txt';

if($_SERVER['REQUEST_METHOD'] === 'POST')
// or if(!empty($_POST))
{
    file_put_contents($file, $_POST["jsonTxt"]);
    //may be some error handeling if you want
}
else if($_SERVER['REQUEST_METHOD'] === 'GET')
// or else if(!empty($_GET))
{
    echo file_get_contents($file);
    //may be some error handeling if you want
}
?>

Node.js server side script solution

I think that Node.js is a little bit complex for beginner. This is not normal JavaScript like in browser. Before you start with Node.js I would recommend to read one from two books:

The Node.js script for reading and writing from JSON file:

var http = require("http"),
    fs = require("fs"),
    port = 8080,
    pathToJSONFile = '/SOME_PATH/jsonFile.txt';

http.createServer(function(request, response)
{
    if(request.method == 'GET')
    {
        response.writeHead(200, {"Content-Type": "application/json"});
        response.write(fs.readFile(pathToJSONFile, 'utf8'));
        response.end();
    }
    else if(request.method == 'POST')
    {
        var body = [];

        request.on('data', function(chunk)
        {
            body.push(chunk);
        });

        request.on('end', function()
        {
            body = Buffer.concat(body).toString();
            var myJSONdata = body.split("=")[1];
            fs.writeFileSync(pathToJSONFile, myJSONdata); //default: 'utf8'
        });
    }
}).listen(port);

Related links for Node.js:

Error with multiple definitions of function

Here is a highly simplified but hopefully relevant view of what happens when you build your code in C++.

C++ splits the load of generating machine executable code in following different phases -

  1. Preprocessing - This is where any macros - #defines etc you might be using get expanded.

  2. Compiling - Each cpp file along with all the #included files in that file directly or indirectly (together called a compilation unit) is converted into machine readable object code.

    This is where C++ also checks that all functions defined (i.e. containing a body in { } e.g. void Foo( int x){ return Boo(x); }) are referring to other functions in a valid manner.

    The way it does that is by insisting that you provide at least a declaration of these other functions (e.g. void Boo(int); ) before you call it so it can check that you are calling it properly among other things. This can be done either directly in the cpp file where it is called or usually in an included header file.

    Note that only the machine code that corresponds to functions defined in this cpp and included files gets built as the object (binary) version of this compilation unit (e.g. Foo) and not the ones that are merely declared (e.g. Boo).

  3. Linking - This is the stage where C++ goes hunting for stuff declared and called in each compilation unit and links it to the places where it is getting called. Now if there was no definition found of this function the linker gives up and errors out. Similarly if it finds multiple definitions of the same function signature (essentially the name and parameter types it takes) it also errors out as it considers it ambiguous and doesn't want to pick one arbitrarily.

The latter is what is happening in your case. By doing a #include of the fun.cpp file, both fun.cpp and mainfile.cpp have a definition of funct() and the linker doesn't know which one to use in your program and is complaining about it.

The fix as Vaughn mentioned above is to not include the cpp file with the definition of funct() in mainfile.cpp and instead move the declaration of funct() in a separate header file and include that in mainline.cpp. This way the compiler will get the declaration of funct() to work with and the linker would get just one definition of funct() from fun.cpp and will use it with confidence.

How to exit an Android app programmatically?

If you use both finish and exit your app will close complitely

finish();

System.exit(0);

Initializing a list to a known number of elements in Python

Not quite sure why everyone is giving you a hard time for wanting to do this - there are several scenarios where you'd want a fixed size initialised list. And you've correctly deduced that arrays are sensible in these cases.

import array
verts=array.array('i',(0,)*1000)

For the non-pythonistas, the (0,)*1000 term is creating a tuple containing 1000 zeros. The comma forces python to recognise (0) as a tuple, otherwise it would be evaluated as 0.

I've used a tuple instead of a list because they are generally have lower overhead.

Convert Little Endian to Big Endian

OP's sample code is incorrect.

Endian conversion works at the bit and 8-bit byte level. Most endian issues deal with the byte level. OP code is doing a endian change at the 4-bit nibble level. Recommend instead:

// Swap endian (big to little) or (little to big)
uint32_t num = 9;
uint32_t b0,b1,b2,b3;
uint32_t res;

b0 = (num & 0x000000ff) << 24u;
b1 = (num & 0x0000ff00) << 8u;
b2 = (num & 0x00ff0000) >> 8u;
b3 = (num & 0xff000000) >> 24u;

res = b0 | b1 | b2 | b3;

printf("%" PRIX32 "\n", res);

If performance is truly important, the particular processor would need to be known. Otherwise, leave it to the compiler.

[Edit] OP added a comment that changes things.
"32bit numerical value represented by the hexadecimal representation (st uv wx yz) shall be recorded in a four-byte field as (st uv wx yz)."

It appears in this case, the endian of the 32-bit number is unknown and the result needs to be store in memory in little endian order.

uint32_t num = 9;
uint8_t b[4];
b[0] = (uint8_t) (num >>  0u);
b[1] = (uint8_t) (num >>  8u);
b[2] = (uint8_t) (num >> 16u);
b[3] = (uint8_t) (num >> 24u);

[2016 Edit] Simplification

... The type of the result is that of the promoted left operand.... Bitwise shift operators C11 §6.5.7 3

Using a u after the shift constants (right operands) results in the same as without it.

b3 = (num & 0xff000000) >> 24u;
b[3] = (uint8_t) (num >> 24u);
// same as 
b3 = (num & 0xff000000) >> 24;
b[3] = (uint8_t) (num >> 24);

How to dismiss notification after action has been clicked

You can always cancel() the Notification from whatever is being invoked by the action (e.g., in onCreate() of the activity tied to the PendingIntent you supply to addAction()).

what do these symbolic strings mean: %02d %01d?

The answer from Alexander refers to complete docs...

Your simple example from the question simply prints out these values with 2 digits - appending leading 0 if necessary.

How to use ConcurrentLinkedQueue?

This is largely a duplicate of another question.

Here's the section of that answer that is relevant to this question:

Do I need to do my own synchronization if I use java.util.ConcurrentLinkedQueue?

Atomic operations on the concurrent collections are synchronized for you. In other words, each individual call to the queue is guaranteed thread-safe without any action on your part. What is not guaranteed thread-safe are any operations you perform on the collection that are non-atomic.

For example, this is threadsafe without any action on your part:

queue.add(obj);

or

queue.poll(obj);

However; non-atomic calls to the queue are not automatically thread-safe. For example, the following operations are not automatically threadsafe:

if(!queue.isEmpty()) {
   queue.poll(obj);
}

That last one is not threadsafe, as it is very possible that between the time isEmpty is called and the time poll is called, other threads will have added or removed items from the queue. The threadsafe way to perform this is like this:

synchronized(queue) {
    if(!queue.isEmpty()) {
       queue.poll(obj);
    }
}

Again...atomic calls to the queue are automatically thread-safe. Non-atomic calls are not.

How do you write to a folder on an SD card in Android?

Add Permission to Android Manifest

Add this WRITE_EXTERNAL_STORAGE permission to your applications manifest.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your.company.package"
    android:versionCode="1"
    android:versionName="0.1">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <!-- ... -->
    </application>
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest> 

Check availability of external storage

You should always check for availability first. A snippet from the official android documentation on external storage.

boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
    // We can read and write the media
    mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    // We can only read the media
    mExternalStorageAvailable = true;
    mExternalStorageWriteable = false;
} else {
    // Something else is wrong. It may be one of many other states, but all we need
    //  to know is we can neither read nor write
    mExternalStorageAvailable = mExternalStorageWriteable = false;
}

Use a Filewriter

At last but not least forget about the FileOutputStream and use a FileWriter instead. More information on that class form the FileWriter javadoc. You'll might want to add some more error handling here to inform the user.

// get external storage file reference
FileWriter writer = new FileWriter(getExternalStorageDirectory()); 
// Writes the content to the file
writer.write("This\n is\n an\n example\n"); 
writer.flush();
writer.close();

Invoking a jQuery function after .each() has completed

It's probably to late but i think this code work...

$blocks.each(function(i, elm) {
 $(elm).fadeOut(200, function() {
  $(elm).remove();
 });
}).promise().done( function(){ alert("All was done"); } );

IllegalMonitorStateException on wait() call

Since you haven't posted code, we're kind of working in the dark. What are the details of the exception?

Are you calling Thread.wait() from within the thread, or outside it?

I ask this because according to the javadoc for IllegalMonitorStateException, it is:

Thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor.

To clarify this answer, this call to wait on a thread also throws IllegalMonitorStateException, despite being called from within a synchronized block:


     private static final class Lock { }
     private final Object lock = new Lock();

    @Test
    public void testRun() {
        ThreadWorker worker = new ThreadWorker();
        System.out.println ("Starting worker");
        worker.start();
        System.out.println ("Worker started - telling it to wait");
        try {
            synchronized (lock) {
                worker.wait();
            }
        } catch (InterruptedException e1) {
            String msg = "InterruptedException: [" + e1.getLocalizedMessage() + "]";
            System.out.println (msg);
            e1.printStackTrace();
            System.out.flush();
        }
        System.out.println ("Worker done waiting, we're now waiting for it by joining");
        try {
            worker.join();
        } catch (InterruptedException ex) { }

    }

Where can I find a NuGet package for upgrading to System.Web.Http v5.0.0.0?

I have several projects in a solution. For some of the projects, I previously added the references manually. When I used NuGet to update the WebAPI package, those references were not updated automatically.

I found out that I can either manually update those reference so they point to the v5 DLL inside the Packages folder of my solution or do the following.

  1. Go to the "Manage NuGet Packages"
  2. Select the Installed Package "Microsoft ASP.NET Web API 2.1"
  3. Click Manage and check the projects that I manually added before.

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'

The problem, as stated in your logs, is 2 dependencies trying to use different versions of 3rd dependency. Add one of the following to the app-gradle file:

androidTestCompile 'com.google.code.findbugs:jsr305:2.0.1'
androidTestCompile 'com.google.code.findbugs:jsr305:1.3.9'

How can I conditionally import an ES6 module?

If you'd like, you could use require. This is a way to have a conditional require statement.

let something = null;
let other = null;

if (condition) {
    something = require('something');
    other = require('something').other;
}
if (something && other) {
    something.doStuff();
    other.doOtherStuff();
}

How to combine GROUP BY, ORDER BY and HAVING

ORDER BY is always last...

However, you need to pick the fields you ACTUALLY WANT then select only those and group by them. SELECT * and GROUP BY Email will give you RANDOM VALUES for all the fields but Email. Most RDBMS will not even allow you to do this because of the issues it creates, but MySQL is the exception.

SELECT Email, COUNT(*)
FROM user_log
GROUP BY Email
HAVING COUNT(*) > 1
ORDER BY UpdateDate DESC

How do you decompile a swf file

I've used Sothink SWF decompiler a couple of times, the only problem is that as project gets more complex, the output of decompiler gets harder to compile back again. But it ensures that you can get your .as files most of the time, compilable fla is a question.

Sothink SWF Decompiler

trace a particular IP and port

tcptraceroute   xx.xx.xx.xx 9100

if you didn't find it you can install it

yum -y install tcptraceroute 

or

aptitude -y install tcptraceroute 

Error occurred during initialization of VM (java/lang/NoClassDefFoundError: java/lang/Object)

Check that downloaded eclipse/JDK/JRE is compatible with your processor/OS architecture that is are they 32bit or 64bit?

go get results in 'terminal prompts disabled' error for github private repo

1st -- go get will refuse to authenticate on the command line. So you need to cache the credentials in git. Because I use osx I can use osxkeychain credential helper.

2nd For me, I have 2FA enabled and thus could not use my password to auth. Instead I had to generate a personal access token to use in place of the password.

  1. setup osxkeychain credential helper https://help.github.com/articles/caching-your-github-password-in-git/
  2. If using TFA instead of using your password, generate a personal access token with repo scope https://github.com/settings/tokens
  3. git clone a private repo just to make it cache the password git clone https://github.com/user/private_repo and used your github.com username for username and the generated personal access token for password.
  4. Removed the just cloned repo and retest to ensure creds were cached -- git clone https://github.com/user/private_repo and this time wasnt asked for creds.

    1. go get will work with any repos that the personal access token can access. You may have to repeat the steps with other accounts / tokens as permissions vary.

Prevent users from submitting a form by hitting Enter

I needed to prevent only specific inputs from submitting, so I used a class selector, to let this be a "global" feature wherever I need it.

<input id="txtEmail" name="txtEmail" class="idNoEnter" .... />

And this jQuery code:

$('.idNoEnter').keydown(function (e) {
  if (e.keyCode == 13) {
    e.preventDefault();
  }
});

Alternatively, if keydown is insufficient:

$('.idNoEnter').on('keypress keydown keyup', function (e) {
   if (e.keyCode == 13) {
     e.preventDefault();
   }
});

Some notes:

Modifying various good answers here, the Enter key seems to work for keydown on all the browsers. For the alternative, I updated bind() to the on() method.

I'm a big fan of class selectors, weighing all the pros and cons and performance discussions. My naming convention is 'idSomething' to indicate jQuery is using it as an id, to separate it from CSS styling.

Overflow-x:hidden doesn't prevent content from overflowing in mobile browsers

I had tried many ways from replies in this topic, mostly works but got some side-effect like if I use overflow-x on body,html it might slow/freeze the page when users scroll down on mobile.

use position: fixed on wrapper/div inside the body is good too, but when I have a menu and use Javascript click animated scroll to some section, It's not working.

So, I decided to use touch-action: pan-y pinch-zoom on wrapper/div inside the body. Problem solved.

How do I convert from int to Long in Java?

How About

int myInt = 88;

// Will not compile

Long myLong = myInt;

// Compiles, and retains the non-NULL spirit of int. The best cast is no cast at all. Of course, your use case may require Long and possible NULL values. But if the int, or other longs are your only input, and your method can be modified, I would suggest this approach.

long myLong = myInt;

// Compiles, is the most efficient way, and makes it clear that the source value, is and will never be NULL.

Long myLong = (long) myInt;

Default value in an asp.net mvc view model

Create a base class for your ViewModels with the following constructor code which will apply the DefaultValueAttributeswhen any inheriting model is created.

public abstract class BaseViewModel
{
    protected BaseViewModel()
    {
        // apply any DefaultValueAttribute settings to their properties
        var propertyInfos = this.GetType().GetProperties();
        foreach (var propertyInfo in propertyInfos)
        {
            var attributes = propertyInfo.GetCustomAttributes(typeof(DefaultValueAttribute), true);
            if (attributes.Any())
            {
                var attribute = (DefaultValueAttribute) attributes[0];
                propertyInfo.SetValue(this, attribute.Value, null);
            }
        }
    }
}

And inherit from this in your ViewModels:

public class SearchModel : BaseViewModel
{
    [DefaultValue(true)]
    public bool IsMale { get; set; }
    [DefaultValue(true)]
    public bool IsFemale { get; set; }
}

Input type number "only numeric value" validation

The easiest way would be to use a library like this one and specifically you want noStrings to be true

    export class CustomValidator{   // Number only validation   
      static numeric(control: AbstractControl) {
        let val = control.value;

        const hasError = validate({val: val}, {val: {numericality: {noStrings: true}}});

        if (hasError) return null;

        return val;   
      } 
    }

How to reverse apply a stash?

git stash[save] takes your working directory state, and your index state, and stashes them away, setting index and working area to HEAD version.

git stash apply brings back those changes, so git reset --hard would remove them again.

git stash pop brings back those changes and removes top stashed change, so git stash [save] would return to previous (pre-pop) state in this case.

Iterate over model instance field names and values in template

I used https://stackoverflow.com/a/3431104/2022534 but replaced Django's model_to_dict() with this to be able to handle ForeignKey:

def model_to_dict(instance):
    data = {}
    for field in instance._meta.fields:
        data[field.name] = field.value_from_object(instance)
        if isinstance(field, ForeignKey):
            data[field.name] = field.rel.to.objects.get(pk=data[field.name])
    return data

Please note that I have simplified it quite a bit by removing the parts of the original I didn't need. You might want to put those back.

Difference between socket and websocket?

WebSocket is just another application level protocol over TCP protocol, just like HTTP.

Some snippets < Spring in Action 4> quoted below, hope it can help you understand WebSocket better.

In its simplest form, a WebSocket is just a communication channel between two applications (not necessarily a browser is involved)...WebSocket communication can be used between any kinds of applications, but the most common use of WebSocket is to facilitate communication between a server application and a browser-based application.

Fix height of a table row in HTML Table

my css

TR.gray-t {background:#949494;}
h3{
    padding-top:3px;
    font:bold 12px/2px Arial;
}

my html

<TR class='gray-t'>
<TD colspan='3'><h3>KAJANG</h3>

I decrease the 2nd size in font.

padding-top is used to fix the size in IE7.

How can I get date and time formats based on Culture Info?

Use a CultureInfo like this, from MSDN:

// Creates a CultureInfo for German in Germany.
CultureInfo ci = new CultureInfo("de-DE");

// Displays dt, formatted using the CultureInfo
Console.WriteLine(dt.ToString(ci));

More info on MSDN. Here is a link of all different cultures.

How to convert Json array to list of objects in c#

This is possible too:

using System.Web.Helpers;
var listOfObjectsResult = Json.Decode<List<DataType>>(JsonData);

Consider defining a bean of type 'service' in your configuration [Spring boot]

remove annotation configuration like service, repository, components

@Component
@Service

NameError: global name is not defined

Importing the namespace is somewhat cleaner. Imagine you have two different modules you import, both of them with the same method/class. Some bad stuff might happen. I'd dare say it is usually good practice to use:

import module

over

from module import function/class

Django - makemigrations - No changes detected

Another possibility is you squashed some migrations and applied the resulting one, but forgot to remove the replaces attribute from it.

Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive

For anyone having this who doesn't have IIS running on their dev PC, here's what happened to me: I had one website on, overwrote with files from a diff website that was 4 while the previous was 3.5. Got this error. Fixed it simply by changing the directory name of the website, which on a dev PC can be anything, so no problem. The above are probably more elegant to be sure, but sometimes simple works, IF you can get away with it, i.e., you're in dev rather than QA or Prod.

Excel VBA - Sum up a column

I have a label on my form receiving the sum of numbers from Column D in Sheet1. I am only interested in rows 2 to 50, you can use a row counter if your row count is dynamic. I have some blank entries as well in column D and they are ignored.

Me.lblRangeTotal = Application.WorksheetFunction.Sum(ThisWorkbook.Sheets("Sheet1").Range("D2:D50"))

How to scroll to top of page with JavaScript/jQuery?

In my case body didn't worked:

$('body').scrollTop(0);

But HTML worked:

$('html').scrollTop(0);

python object() takes no parameters error

I struggled for a while about this. Stupid rule for __init__. It is two "_" together to be "__"

How would I create a UIAlertView in Swift?

Click of View

@IBAction func testClick(sender: UIButton) {

  var uiAlert = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
  self.presentViewController(uiAlert, animated: true, completion: nil)

  uiAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in
   println("Click of default button")
  }))

  uiAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { action in
   println("Click of cancel button")
  }))

}

Done with two buttons OK & Cancel

Class Diagrams in VS 2017

Noticed this in the beta and thought I had a bad install. The UI elements to add new Class Diagrams were missing and I was unable to open existing *.cd Class Diagram files in my solutions. Just upgraded to 2017 and found the problem remains. After some investigation it seems the Class Designer component is no longer installed by default.

Re-running the VS Installer and adding the Class Designer component restores both my ability to open and edit Class Diagrams as well as the UI elements needed to create new ones

VS Installer > Individual Components > Class Designer

How to set up file permissions for Laravel?

For Laravel developers, directory issues can be a little bit pain. In my application, I was creating directories on the fly and moving files to this directory in my local environment successfully. Then on server, I was getting errors while moving files to newly created directory.

Here are the things that I have done and got a successful result at the end.

  1. sudo find /path/to/your/laravel/root/directory -type f -exec chmod 664 {} \;
    sudo find /path/to/your/laravel/root/directory -type d -exec chmod 775 {} \;
  2. chcon -Rt httpd_sys_content_rw_t /path/to/my/file/upload/directory/in/laravel/project/
  3. While creating the new directory on the fly, I used the command mkdir($save_path, 0755, true);

After making those changes on production server, I successfully created new directories and move files to them.

Finally, if you use File facade in Laravel you can do something like this: File::makeDirectory($save_path, 0755, true);

Simple insecure two-way data "obfuscation"?

I've been using the accepted answer by Mark Brittingham and its has helped me a lot. Recently I had to send encrypted text to a different organization and that's where some issues came up. The OP does not require these options but since this is a popular question I'm posting my modification (Encrypt and Decrypt functions borrowed from here):

  1. Different IV for every message - Concatenates IV bytes to the cipher bytes before obtaining the hex. Of course this is a convention that needs to be conveyed to the parties receiving the cipher text.
  2. Allows two constructors - one for default RijndaelManaged values, and one where property values can be specified (based on mutual agreement between encrypting and decrypting parties)

Here is the class (test sample at the end):

/// <summary>
/// Based on https://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged(v=vs.110).aspx
/// Uses UTF8 Encoding
///  http://security.stackexchange.com/a/90850
/// </summary>
public class AnotherAES : IDisposable
{
    private RijndaelManaged rijn;

    /// <summary>
    /// Initialize algo with key, block size, key size, padding mode and cipher mode to be known.
    /// </summary>
    /// <param name="key">ASCII key to be used for encryption or decryption</param>
    /// <param name="blockSize">block size to use for AES algorithm. 128, 192 or 256 bits</param>
    /// <param name="keySize">key length to use for AES algorithm. 128, 192, or 256 bits</param>
    /// <param name="paddingMode"></param>
    /// <param name="cipherMode"></param>
    public AnotherAES(string key, int blockSize, int keySize, PaddingMode paddingMode, CipherMode cipherMode)
    {
        rijn = new RijndaelManaged();
        rijn.Key = Encoding.UTF8.GetBytes(key);
        rijn.BlockSize = blockSize;
        rijn.KeySize = keySize;
        rijn.Padding = paddingMode;
        rijn.Mode = cipherMode;
    }

    /// <summary>
    /// Initialize algo just with key
    /// Defaults for RijndaelManaged class: 
    /// Block Size: 256 bits (32 bytes)
    /// Key Size: 128 bits (16 bytes)
    /// Padding Mode: PKCS7
    /// Cipher Mode: CBC
    /// </summary>
    /// <param name="key"></param>
    public AnotherAES(string key)
    {
        rijn = new RijndaelManaged();
        byte[] keyArray = Encoding.UTF8.GetBytes(key);
        rijn.Key = keyArray;
    }

    /// <summary>
    /// Based on https://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged(v=vs.110).aspx
    /// Encrypt a string using RijndaelManaged encryptor.
    /// </summary>
    /// <param name="plainText">string to be encrypted</param>
    /// <param name="IV">initialization vector to be used by crypto algorithm</param>
    /// <returns></returns>
    public byte[] Encrypt(string plainText, byte[] IV)
    {
        if (rijn == null)
            throw new ArgumentNullException("Provider not initialized");

        // Check arguments.
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText cannot be null or empty");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV cannot be null or empty");
        byte[] encrypted;

        // Create a decrytor to perform the stream transform.
        using (ICryptoTransform encryptor = rijn.CreateEncryptor(rijn.Key, IV))
        {
            // Create the streams used for encryption.
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
        }
        // Return the encrypted bytes from the memory stream.
        return encrypted;
    }//end EncryptStringToBytes

    /// <summary>
    /// Based on https://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged(v=vs.110).aspx
    /// </summary>
    /// <param name="cipherText">bytes to be decrypted back to plaintext</param>
    /// <param name="IV">initialization vector used to encrypt the bytes</param>
    /// <returns></returns>
    public string Decrypt(byte[] cipherText, byte[] IV)
    {
        if (rijn == null)
            throw new ArgumentNullException("Provider not initialized");

        // Check arguments.
        if (cipherText == null || cipherText.Length <= 0)
            throw new ArgumentNullException("cipherText cannot be null or empty");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV cannot be null or empty");

        // Declare the string used to hold the decrypted text.
        string plaintext = null;

        // Create a decrytor to perform the stream transform.
        using (ICryptoTransform decryptor = rijn.CreateDecryptor(rijn.Key, IV))
        {
            // Create the streams used for decryption.
            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {
                        // Read the decrypted bytes from the decrypting stream and place them in a string.
                        plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }
        }

        return plaintext;
    }//end DecryptStringFromBytes

    /// <summary>
    /// Generates a unique encryption vector using RijndaelManaged.GenerateIV() method
    /// </summary>
    /// <returns></returns>
    public byte[] GenerateEncryptionVector()
    {
        if (rijn == null)
            throw new ArgumentNullException("Provider not initialized");

        //Generate a Vector
        rijn.GenerateIV();
        return rijn.IV;
    }//end GenerateEncryptionVector


    /// <summary>
    /// Based on https://stackoverflow.com/a/1344255
    /// Generate a unique string given number of bytes required.
    /// This string can be used as IV. IV byte size should be equal to cipher-block byte size. 
    /// Allows seeing IV in plaintext so it can be passed along a url or some message.
    /// </summary>
    /// <param name="numBytes"></param>
    /// <returns></returns>
    public static string GetUniqueString(int numBytes)
    {
        char[] chars = new char[62];
        chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
        byte[] data = new byte[1];
        using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider())
        {
            data = new byte[numBytes];
            crypto.GetBytes(data);
        }
        StringBuilder result = new StringBuilder(numBytes);
        foreach (byte b in data)
        {
            result.Append(chars[b % (chars.Length)]);
        }
        return result.ToString();
    }//end GetUniqueKey()

    /// <summary>
    /// Converts a string to byte array. Useful when converting back hex string which was originally formed from bytes.
    /// </summary>
    /// <param name="hex"></param>
    /// <returns></returns>
    public static byte[] StringToByteArray(String hex)
    {
        int NumberChars = hex.Length;
        byte[] bytes = new byte[NumberChars / 2];
        for (int i = 0; i < NumberChars; i += 2)
            bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
        return bytes;
    }//end StringToByteArray

    /// <summary>
    /// Dispose RijndaelManaged object initialized in the constructor
    /// </summary>
    public void Dispose()
    {
        if (rijn != null)
            rijn.Dispose();
    }//end Dispose()
}//end class

and..

Here is the test sample:

class Program
{
    string key;
    static void Main(string[] args)
    {
        Program p = new Program();

        //get 16 byte key (just demo - typically you will have a predetermined key)
        p.key = AnotherAES.GetUniqueString(16);

        string plainText = "Hello World!";

        //encrypt
        string hex = p.Encrypt(plainText);

        //decrypt
        string roundTrip = p.Decrypt(hex);

        Console.WriteLine("Round Trip: {0}", roundTrip);
    }

    string Encrypt(string plainText)
    {
        Console.WriteLine("\nSending (encrypt side)...");
        Console.WriteLine("Plain Text: {0}", plainText);
        Console.WriteLine("Key: {0}", key);
        string hex = string.Empty;
        string ivString = AnotherAES.GetUniqueString(16);
        Console.WriteLine("IV: {0}", ivString);
        using (AnotherAES aes = new AnotherAES(key))
        {
            //encrypting side
            byte[] IV = Encoding.UTF8.GetBytes(ivString);

            //get encrypted bytes (IV bytes prepended to cipher bytes)
            byte[] encryptedBytes = aes.Encrypt(plainText, IV);
            byte[] encryptedBytesWithIV = IV.Concat(encryptedBytes).ToArray();

            //get hex string to send with url
            //this hex has both IV and ciphertext
            hex = BitConverter.ToString(encryptedBytesWithIV).Replace("-", "");
            Console.WriteLine("sending hex: {0}", hex);
        }

        return hex;
    }

    string Decrypt(string hex)
    {
        Console.WriteLine("\nReceiving (decrypt side)...");
        Console.WriteLine("received hex: {0}", hex);
        string roundTrip = string.Empty;
        Console.WriteLine("Key " + key);
        using (AnotherAES aes = new AnotherAES(key))
        {
            //get bytes from url
            byte[] encryptedBytesWithIV = AnotherAES.StringToByteArray(hex);

            byte[] IV = encryptedBytesWithIV.Take(16).ToArray();

            Console.WriteLine("IV: {0}", System.Text.Encoding.Default.GetString(IV));

            byte[] cipher = encryptedBytesWithIV.Skip(16).ToArray();

            roundTrip = aes.Decrypt(cipher, IV);
        }
        return roundTrip;
    }
}

enter image description here

Open JQuery Datepicker by clicking on an image w/ no input field

The jQuery documentation says that the datePicker needs to be attached to a SPAN or a DIV when it is not associated with an input box. You could do something like this:

<img src='someimage.gif' id="datepickerImage" />
<div id="datepicker"></div>

<script type="text/javascript">
 $(document).ready(function() {
    $("#datepicker").datepicker({
            changeMonth: true,
            changeYear: true,
    })
    .hide()
    .click(function() {
      $(this).hide();
    });

    $("#datepickerImage").click(function() {
       $("#datepicker").show(); 
    });
 });
</script>

Pass a variable to a PHP script running from the command line

Save this code in file myfile.php and run as php myfile.php type=daily

<?php
$a = $argv;
$b = array();
if (count($a) === 1) exit;
foreach ($a as $key => $arg) {
    if ($key > 0) {
        list($x,$y) = explode('=', $arg);
        $b["$x"] = $y;  
    }
}
?>

If you add var_dump($b); before the ?> tag, you will see that the array $b contains type => daily.

Kubernetes how to make Deployment to update image

Another option which is more suitable for debugging but worth mentioning is to check in revision history of your rollout:

$ kubectl rollout history deployment my-dep
deployment.apps/my-dep
 
REVISION  CHANGE-CAUSE
1         <none>
2         <none>
3         <none>

To see the details of each revision, run:

 kubectl rollout history deployment my-dep --revision=2

And then returning to the previous revision by running:

 $kubectl rollout undo deployment my-dep --to-revision=2

And then returning back to the new one.
Like running ctrl+z -> ctrl+y (:

(*) The CHANGE-CAUSE is <none> because you should run the updates with the --record flag - like mentioned here:

kubectl set image deployment/nginx-deployment nginx=nginx:1.16.1 --record

(**) There is a discussion regarding deprecating this flag.

Pass array to MySQL stored routine

You can pass a string with your list and use a prepared statements to run a query, e.g. -

DELIMITER $$

CREATE PROCEDURE GetFruits(IN fruitArray VARCHAR(255))
BEGIN

  SET @sql = CONCAT('SELECT * FROM Fruits WHERE Name IN (', fruitArray, ')');
  PREPARE stmt FROM @sql;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;

END
$$

DELIMITER ;

How to use:

SET @fruitArray = '\'apple\',\'banana\'';
CALL GetFruits(@fruitArray);

How to add image in a TextView text?

This might Help You

  SpannableStringBuilder ssBuilder;

        ssBuilder = new SpannableStringBuilder(" ");
        // working code ImageSpan image = new ImageSpan(textView.getContext(), R.drawable.image);
        Drawable image = ContextCompat.getDrawable(textView.getContext(), R.drawable.image);
        float scale = textView.getContext().getResources().getDisplayMetrics().density;
        int width = (int) (12 * scale + 0.5f);
        int height = (int) (18 * scale + 0.5f);
        image.setBounds(0, 0, width, height);
        ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BASELINE);
        ssBuilder.setSpan(
                imageSpan, // Span to add
                0, // Start of the span (inclusive)
                1, // End of the span (exclusive)
                Spanned.SPAN_INCLUSIVE_EXCLUSIVE);// Do not extend the span when text add later

        ssBuilder.append(" " + text);
        ssBuilder = new SpannableStringBuilder(text);
        textView.setText(ssBuilder);

Why doesn't margin:auto center an image?

<div style="text-align:center;">
    <img src="queuedError.jpg" style="margin:auto; width:200px;" />
</div>

How to change the plot line color from blue to black?

The usual way to set the line color in matplotlib is to specify it in the plot command. This can either be done by a string after the data, e.g. "r-" for a red line, or by explicitely stating the color argument.

import matplotlib.pyplot as plt

plt.plot([1,2,3], [2,3,1], "r-") # red line
plt.plot([1,2,3], [5,5,3], color="blue") # blue line

plt.show()

See also the plot command's documentation.

In case you already have a line with a certain color, you can change that with the lines2D.set_color() method.

line, = plt.plot([1,2,3], [4,5,3], color="blue")
line.set_color("black")


Setting the color of a line in a pandas plot is also best done at the point of creating the plot:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({ "x" : [1,2,3,5], "y" : [3,5,2,6]})
df.plot("x", "y", color="r") #plot red line

plt.show()

If you want to change this color later on, you can do so by

plt.gca().get_lines()[0].set_color("black")

This will get you the first (possibly the only) line of the current active axes.
In case you have more axes in the plot, you could loop through them

for ax in plt.gcf().axes:
    ax.get_lines()[0].set_color("black")

and if you have more lines you can loop over them as well.

"Invalid signature file" when attempting to run a .jar

Please use the following command

zip -d yourjar.jar 'META-INF/*.SF' 'META-INF/*.RSA' 'META-INF/*SF'

How to parse a JSON and turn its values into an Array?

for your example:

{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}

you will have to do something of this effect:

JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");

this returns the array object.

Then iterating will be as follows:

    int size = the_json_array.length();
    ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
    for (int i = 0; i < size; i++) {
        JSONObject another_json_object = the_json_array.getJSONObject(i);
            //Blah blah blah...
            arrays.add(another_json_object);
    }

//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);

//The end...

You will have to determine if the data is an array (simply checking that charAt(0) starts with [ character).

Hope this helps.

How to write Unicode characters to the console?

Besides Console.OutputEncoding = System.Text.Encoding.UTF8;

for some characters you need to install extra fonts (ie. Chinese).

In Windows 10 first go to Region & language settings and install support for required language: enter image description here

After that you can go to Command Prompt Proporties (or Defaults if you like) and choose some font that supports your language (like KaiTi in Chinese case): enter image description here

Now you are set to go: enter image description here

Auto margins don't center image in page

You can center auto width div using display:table;

div{
margin: 0px auto;
float: none;
display: table;
}

use std::fill to populate vector with increasing numbers

I've seen the answers with std::generate but you can also "improve" that by using static variables inside the lambda, instead of declaring a counter outside of the function or creating a generator class :

std::vector<int> vec;
std::generate(vec.begin(), vec.end(), [] {
    static int i = 0;
    return i++;
});

I find it a little more concise

What is size_t in C?

Since nobody has yet mentioned it, the primary linguistic significance of size_t is that the sizeof operator returns a value of that type. Likewise, the primary significance of ptrdiff_t is that subtracting one pointer from another will yield a value of that type. Library functions that accept it do so because it will allow such functions to work with objects whose size exceeds UINT_MAX on systems where such objects could exist, without forcing callers to waste code passing a value larger than "unsigned int" on systems where the larger type would suffice for all possible objects.

Minimum 6 characters regex expression

Something along the lines of this?

<asp:TextBox id="txtUsername" runat="server" />

<asp:RegularExpressionValidator
    id="RegularExpressionValidator1"
    runat="server"
    ErrorMessage="Field not valid!"
    ControlToValidate="txtUsername"
    ValidationExpression="[0-9a-zA-Z]{6,}" />

How to use Monitor (DDMS) tool to debug application

As far as I know, currently (Android Studio 2.3) there is no way to do this.

As per Android Studio documentation:

"Note: Only one debugger can be connected to your device at a time."

When you attempt to connect Android Device Monitor it disconnects Android Studio's debug session and vice versa, when you attempt to connect Android Studio's debugger, it disconnects Android Device Monitor.

Fortunately the new version of Android Studio (3.0) will feature a Device File Explorer that will allow you to pull files from within Android Studio without the need to open the Android Device Monitor which should resolve the problem.

What is JavaScript's highest integer value that a number can go to without losing precision?

>= ES6:

Number.MIN_SAFE_INTEGER;
Number.MAX_SAFE_INTEGER;

<= ES5

From the reference:

Number.MAX_VALUE;
Number.MIN_VALUE;

_x000D_
_x000D_
console.log('MIN_VALUE', Number.MIN_VALUE);
console.log('MAX_VALUE', Number.MAX_VALUE);

console.log('MIN_SAFE_INTEGER', Number.MIN_SAFE_INTEGER); //ES6
console.log('MAX_SAFE_INTEGER', Number.MAX_SAFE_INTEGER); //ES6
_x000D_
_x000D_
_x000D_

Returning multiple values from a C++ function

In C++11 you can:

#include <tuple>

std::tuple<int, int> divide(int dividend, int divisor) {
    return  std::make_tuple(dividend / divisor, dividend % divisor);
}

#include <iostream>

int main() {
    using namespace std;

    int quotient, remainder;

    tie(quotient, remainder) = divide(14, 3);

    cout << quotient << ',' << remainder << endl;
}

In C++17:

#include <tuple>

std::tuple<int, int> divide(int dividend, int divisor) {
    return  {dividend / divisor, dividend % divisor};
}

#include <iostream>

int main() {
    using namespace std;

    auto [quotient, remainder] = divide(14, 3);

    cout << quotient << ',' << remainder << endl;
}

or with structs:

auto divide(int dividend, int divisor) {
    struct result {int quotient; int remainder;};
    return result {dividend / divisor, dividend % divisor};
}

#include <iostream>

int main() {
    using namespace std;

    auto result = divide(14, 3);

    cout << result.quotient << ',' << result.remainder << endl;

    // or

    auto [quotient, remainder] = divide(14, 3);

    cout << quotient << ',' << remainder << endl;
}

What does this error mean: "error: expected specifier-qualifier-list before 'type_name'"?

I was able to sort this out using Gorgando's fix, but instead of moving imports away, I commented each out individually, built the app, then edited accordingly until I got rid of them.

setAttribute('display','none') not working

It works for me

setAttribute('style', 'display:none');

What is the difference between Cygwin and MinGW?

Wikipedia does a comparison here.

From Cygwin's website:

  • Cygwin is a Linux-like environment for Windows. It consists of two parts: A DLL (cygwin1.dll) which acts as a Linux API emulation layer providing substantial Linux API functionality.
  • A collection of tools which provide Linux look and feel.

From Mingw's website:

MinGW ("Minimalistic GNU for Windows") is a collection of freely available and freely distributable Windows specific header files and import libraries combined with GNU toolsets that allow one to produce native Windows programs that do not rely on any 3rd-party C runtime DLLs

Is there a way to detach matplotlib plots so that the computation can continue?

I also wanted my plots to display run the rest of the code (and then keep on displaying) even if there is an error (I sometimes use plots for debugging). I coded up this little hack so that any plots inside this with statement behave as such.

This is probably a bit too non-standard and not advisable for production code. There is probably a lot of hidden "gotchas" in this code.

from contextlib import contextmanager

@contextmanager
def keep_plots_open(keep_show_open_on_exit=True, even_when_error=True):
    '''
    To continue excecuting code when plt.show() is called
    and keep the plot on displaying before this contex manager exits
    (even if an error caused the exit).
    '''
    import matplotlib.pyplot
    show_original = matplotlib.pyplot.show
    def show_replacement(*args, **kwargs):
        kwargs['block'] = False
        show_original(*args, **kwargs)
    matplotlib.pyplot.show = show_replacement

    pylab_exists = True
    try:
        import pylab
    except ImportError: 
        pylab_exists = False
    if pylab_exists:
        pylab.show = show_replacement

    try:
        yield
    except Exception, err:
        if keep_show_open_on_exit and even_when_error:
            print "*********************************************"
            print "Error early edition while waiting for show():" 
            print "*********************************************"
            import traceback
            print traceback.format_exc()
            show_original()
            print "*********************************************"
            raise
    finally:
        matplotlib.pyplot.show = show_original
        if pylab_exists:
            pylab.show = show_original
    if keep_show_open_on_exit:
        show_original()

# ***********************
# Running example
# ***********************
import pylab as pl
import time
if __name__ == '__main__':
    with keep_plots_open():
        pl.figure('a')
        pl.plot([1,2,3], [4,5,6])     
        pl.plot([3,2,1], [4,5,6])
        pl.show()

        pl.figure('b')
        pl.plot([1,2,3], [4,5,6])
        pl.show()

        time.sleep(1)
        print '...'
        time.sleep(1)
        print '...'
        time.sleep(1)
        print '...'
        this_will_surely_cause_an_error

If/when I implement a proper "keep the plots open (even if an error occurs) and allow new plots to be shown", I would want the script to properly exit if no user interference tells it otherwise (for batch execution purposes).

I may use something like a time-out-question "End of script! \nPress p if you want the plotting output to be paused (you have 5 seconds): " from https://stackoverflow.com/questions/26704840/corner-cases-for-my-wait-for-user-input-interruption-implementation.

Using a PHP variable in a text input value = statement

I have been doing PHP for my project, and I can say that the following code works for me. You should try it.

echo '<input type = "text" value = '.$idtest.'>'; 

How to fluently build JSON in Java?

See the Java EE 7 Json specification. This is the right way:

String json = Json.createObjectBuilder()
            .add("key1", "value1")
            .add("key2", "value2")
            .build()
            .toString();

Navigation Drawer (Google+ vs. YouTube)

Edit #3:

The Navigation Drawer pattern is officially described in the Android documentation!

enter image description here Check out the following links:

  • Design docs can be found here.
  • Developer docs can be found here.

Edit #2:

Roman Nurik (an Android design engineer at Google) has confirmed that the recommended behavior is to not move the Action Bar when opening the drawer (like the YouTube app). See this Google+ post.


Edit #1:

I answered this question a while ago, but I'm back to re-emphasize that Prixing has the best fly-out menu out there... by far. It's absolutely beautiful, perfectly smooth, and it puts Facebook, Google+, and YouTube to shame. EverNote is pretty good too... but still not as perfect as Prixing. Check out this series of posts on how the flyout menu was implemented (from none other than the head developer at Prixing himself!).


Original Answer:

Adam Powell and Richard Fulcher talk about this at 49:47 - 52:50 in the Google I/O talk titled "Navigation in Android".

To summarize their answer, as of the date of this posting the slide out navigation menu is not officially part of the Android application design standard. As you have probably discovered, there's currently no native support for this feature, but there was talk about making this an addition to an upcoming revision of the support package.

With regards to the YouTube and G+ apps, it does seem odd that they behave differently. My best guess is that the reason the YouTube app fixes the position of the action bar is,

  1. One of the most important navigational options for users using the YouTube app is search, which is performed in the SearchView in the action bar. It would make sense to make the action bar static in this regard, since it would allow the user to always have the option to search for new videos.

  2. The G+ app uses a ViewPager to display its content, so making the pull out menu specific to the layout content (i.e. everything under the action bar) wouldn't make much sense. Swiping is supposed to provide a means of navigating between pages, not a means of global navigation. This might be why they decided to do it differently in the G+ app than they did in the YouTube app.

    On another note, check out the Google Play app for another version of the "pull out menu" (when you are at the left most page, swipe left and a pull out, "half-page" menu will appear).

You're right in that this isn't very consistent behavior, but it doesn't seem like there is a 100% consensus within the Android team on how this behavior should be implemented yet. I wouldn't be surprised if in the future the apps are updated so that the navigation in both apps are identical (they seemed very keen on making navigation consistent across all Google-made apps in the talk).

Global and local variables in R

Variables declared inside a function are local to that function. For instance:

foo <- function() {
    bar <- 1
}
foo()
bar

gives the following error: Error: object 'bar' not found.

If you want to make bar a global variable, you should do:

foo <- function() {
    bar <<- 1
}
foo()
bar

In this case bar is accessible from outside the function.

However, unlike C, C++ or many other languages, brackets do not determine the scope of variables. For instance, in the following code snippet:

if (x > 10) {
    y <- 0
}
else {
    y <- 1
}

y remains accessible after the if-else statement.

As you well say, you can also create nested environments. You can have a look at these two links for understanding how to use them:

  1. http://stat.ethz.ch/R-manual/R-devel/library/base/html/environment.html
  2. http://stat.ethz.ch/R-manual/R-devel/library/base/html/get.html

Here you have a small example:

test.env <- new.env()

assign('var', 100, envir=test.env)
# or simply
test.env$var <- 100

get('var') # var cannot be found since it is not defined in this environment
get('var', envir=test.env) # now it can be found

Explaining the 'find -mtime' command

To find all files modified in the last 24 hours use the one below. The -1 here means changed 1 day or less ago.

find . -mtime -1 -ls

Get value of Span Text

You need to change your code as below:

<html>
<body>

<span id="span_Id">Click the button to display the content.</span>

<button onclick="displayDate()">Click Me</button>

<script>
function displayDate() {
   var span_Text = document.getElementById("span_Id").innerText;
   alert (span_Text);
}
</script>
</body>
</html>

Handle spring security authentication exceptions with @ExceptionHandler

Update: If you like and prefer to see the code directly, then I have two examples for you, one using standard Spring Security which is what you are looking for, the other one is using the equivalent of Reactive Web and Reactive Security:
- Normal Web + Jwt Security
- Reactive Jwt

The one that I always use for my JSON based endpoints looks like the following:

@Component
public class JwtAuthEntryPoint implements AuthenticationEntryPoint {

    @Autowired
    ObjectMapper mapper;

    private static final Logger logger = LoggerFactory.getLogger(JwtAuthEntryPoint.class);

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException e)
            throws IOException, ServletException {
        // Called when the user tries to access an endpoint which requires to be authenticated
        // we just return unauthorizaed
        logger.error("Unauthorized error. Message - {}", e.getMessage());

        ServletServerHttpResponse res = new ServletServerHttpResponse(response);
        res.setStatusCode(HttpStatus.UNAUTHORIZED);
        res.getServletResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        res.getBody().write(mapper.writeValueAsString(new ErrorResponse("You must authenticated")).getBytes());
    }
}

The object mapper becomes a bean once you add the spring web starter, but I prefer to customize it, so here is my implementation for ObjectMapper:

  @Bean
    public Jackson2ObjectMapperBuilder objectMapperBuilder() {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.modules(new JavaTimeModule());

        // for example: Use created_at instead of createdAt
        builder.propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);

        // skip null fields
        builder.serializationInclusion(JsonInclude.Include.NON_NULL);
        builder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        return builder;
    }

The default AuthenticationEntryPoint you set in your WebSecurityConfigurerAdapter class:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// ............
   @Autowired
    private JwtAuthEntryPoint unauthorizedHandler;
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .authorizeRequests()
                // .antMatchers("/api/auth**", "/api/login**", "**").permitAll()
                .anyRequest().permitAll()
                .and()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);


        http.headers().frameOptions().disable(); // otherwise H2 console is not available
        // There are many ways to ways of placing our Filter in a position in the chain
        // You can troubleshoot any error enabling debug(see below), it will print the chain of Filters
        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    }
// ..........
}

How to convert answer into two decimal point

If you have a Decimal or similar numeric type, you can use:

Math.Round(myNumber, 2)

EDIT: So, in your case, it would be:

Public Class Form1
  Private Sub btncalc_Click(ByVal sender As System.Object,
                            ByVal e As System.EventArgs) Handles btncalc.Click
    txtA.Text = Math.Round((Val(txtD.Text) / Val(txtC.Text) * Val(txtF.Text) / Val(txtE.Text)), 2)
    txtB.Text = Math.Round((Val(txtA.Text) * 1000 / Val(txtG.Text)), 2)
  End Sub
End Class

bash: shortest way to get n-th column of output

You can use cut to access the second field:

cut -f2

Edit: Sorry, didn't realise that SVN doesn't use tabs in its output, so that's a bit useless. You can tailor cut to the output but it's a bit fragile - something like cut -c 10- would work, but the exact value will depend on your setup.

Another option is something like: sed 's/.\s\+//'

How to check whether a int is not null or empty?

public class Demo {
    private static int i;
    private static Integer j;
    private static int k = -1;

    public static void main(String[] args) {
        System.out.println(i+" "+j+" "+k);
    }
}

OutPut: 0 null -1

Writing handler for UIAlertAction

this is how i do it with xcode 7.3.1

// create function
func sayhi(){
  print("hello")
}

// create the button

let sayinghi = UIAlertAction(title: "More", style: UIAlertActionStyle.Default, handler:  { action in
            self.sayhi()})

// adding the button to the alert control

myAlert.addAction(sayhi);

// the whole code, this code will add 2 buttons

  @IBAction func sayhi(sender: AnyObject) {
        let myAlert = UIAlertController(title: "Alert", message:"sup", preferredStyle: UIAlertControllerStyle.Alert);
        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:nil)

        let sayhi = UIAlertAction(title: "say hi", style: UIAlertActionStyle.Default, handler:  { action in
            self.sayhi()})

        // this action can add to more button
        myAlert.addAction(okAction);
        myAlert.addAction(sayhi);

        self.presentViewController(myAlert, animated: true, completion: nil)
    }

    func sayhi(){
        // move to tabbarcontroller
     print("hello")
    }

Selecting last element in JavaScript array

use es6 deconstruction array with the spread operator

var last = [...yourArray].pop();

note that yourArray doesn't change.

Select an Option from the Right-Click Menu in Selenium Webdriver - Java

We will take the help of WebDriver action class and perform Right Click. the below is the syntax :

Actions action = new Actions(driver).contextClick(element);
action.build().perform();

Below are the Steps we have followed in the example:

  1. Identify the element
  2. Wait for the presence of Element
  3. Now perform Context click
  4. After that we need to select the required link.

package com.pack.rightclick;

    import org.openqa.selenium.Alert;
    import org.openqa.selenium.By;
    import org.openqa.selenium.NoSuchElementException;
    import org.openqa.selenium.StaleElementReferenceException;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.interactions.Actions;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;
    import org.testng.Assert;
    import org.testng.annotations.AfterClass;
    import org.testng.annotations.BeforeClass;
    import org.testng.annotations.Test;

public class RightClickExample {

    WebDriver driver;

    String URL = "http://medialize.github.io/jQuery-contextMenu/demo.html";

    @BeforeClass
    public void Setup() {
        driver = new FirefoxDriver();
        driver.manage().window().maximize();
    }

    @Test
    public void rightClickTest() {
        driver.navigate().to(URL);
        By locator = By.cssSelector(".context-menu-one.box");
        WebDriverWait wait = new WebDriverWait(driver, 5);
        wait.until(ExpectedConditions.presenceOfElementLocated(locator)); 
        WebElement element=driver.findElement(locator);
        rightClick(element);
        WebElement elementEdit =driver.findElement(By.cssSelector(".context-menu-item.icon.icon-edit>span"));
        elementEdit.click();
        Alert alert=driver.switchTo().alert();
        String textEdit = alert.getText();
        Assert.assertEquals(textEdit, "clicked: edit", "Failed to click on Edit link");
    }

    public void rightClick(WebElement element) {
        try {
            Actions action = new Actions(driver).contextClick(element);
            action.build().perform();

            System.out.println("Sucessfully Right clicked on the element");
        } catch (StaleElementReferenceException e) {
            System.out.println("Element is not attached to the page document "
                    + e.getStackTrace());
        } catch (NoSuchElementException e) {
            System.out.println("Element " + element + " was not found in DOM "
                    + e.getStackTrace());
        } catch (Exception e) {
            System.out.println("Element " + element + " was not clickable "
                    + e.getStackTrace());
        }
    }

    @AfterClass
    public void tearDown() {
        driver.quit();
    }


}

How to draw a checkmark / tick using CSS?

Here is another CSS solution. its take less line of code.

ul li:before
{content:'\2713';
  display:inline-block;
  color:red;
  padding:0 6px 0 0;
  }
ul li{list-style-type:none;font-size:1em;}

<ul>
    <li>test1</li>
    <li>test</li>
</ul>

Here is the Demo link http://jsbin.com/keliguqi/1/

can't access mysql from command line mac

I think this is the more simpler approach:

  1. Install mySQL-Shell package from mySQL site
  2. Run mysqlsh (should be added to your path by default after install)
  3. Connect to your database server like so: MySQL JS > \connect --mysql [username]@[endpoint/server]:3306
  4. Switch to SQL Mode by typing "\sql" in your prompt
  5. The console should print out the following to let you know you are good to go:

Switching to SQL mode... Commands end with ;

Go forth and do great things! :)

Set Background cell color in PHPExcel

function cellColor($cells,$color){
    global $objPHPExcel;

    $objPHPExcel->getActiveSheet()->getStyle($cells)->getFill()->applyFromArray(array(
        'type' => PHPExcel_Style_Fill::FILL_SOLID,
        'startcolor' => array(
             'rgb' => $color
        )
    ));
}

cellColor('B5', 'F28A8C');
cellColor('G5', 'F28A8C');
cellColor('A7:I7', 'F28A8C');
cellColor('A17:I17', 'F28A8C');
cellColor('A30:Z30', 'F28A8C');

enter image description here

SSH to Vagrant box in Windows?

There is an OpenSSH package for Windows which is basically a stripped down Cygwin. It has an msi-Installer and (after setting your path accordingly) works with "vsagrant ssh":

http://sourceforge.net/projects/opensshwindows/?source=directory

tar: add all files and directories in current directory INCLUDING .svn and so on

Don't create the tar file in the directory you are packing up:

tar -czf /tmp/workspace.tar.gz .

does the trick, except it will extract the files all over the current directory when you unpack. Better to do:

cd ..
tar -czf workspace.tar.gz workspace

or, if you don't know the name of the directory you were in:

base=$(basename $PWD)
cd ..
tar -czf $base.tar.gz $base

(This assumes that you didn't follow symlinks to get to where you are and that the shell doesn't try to second guess you by jumping backwards through a symlink - bash is not trustworthy in this respect. If you have to worry about that, use cd -P .. to do a physical change directory. Stupid that it is not the default behaviour in my view - confusing, at least, for those for whom cd .. never had any alternative meaning.)


One comment in the discussion says:

I [...] need to exclude the top directory and I [...] need to place the tar in the base directory.

The first part of the comment does not make much sense - if the tar file contains the current directory, it won't be created when you extract file from that archive because, by definition, the current directory already exists (except in very weird circumstances).

The second part of the comment can be dealt with in one of two ways:

  1. Either: create the file somewhere else - /tmp is one possible location - and then move it back to the original location after it is complete.
  2. Or: if you are using GNU Tar, use the --exclude=workspace.tar.gz option. The string after the = is a pattern - the example is the simplest pattern - an exact match. You might need to specify --exclude=./workspace.tar.gz if you are working in the current directory contrary to recommendations; you might need to specify --exclude=workspace/workspace.tar.gz if you are working up one level as suggested. If you have multiple tar files to exclude, use '*', as in --exclude=./*.gz.

How to get the indices list of all NaN value in numpy array?

You can use np.where to match the boolean conditions corresponding to Nan values of the array and map each outcome to generate a list of tuples.

>>>list(map(tuple, np.where(np.isnan(x))))
[(1, 2), (2, 0)]

Why use armeabi-v7a code over armeabi code?

Depends on what your native code does, but v7a has support for hardware floating point operations, which makes a huge difference. armeabi will work fine on all devices, but will be a lot slower, and won't take advantage of newer devices' CPU capabilities. Do take some benchmarks for your particular application, but removing the armeabi-v7a binaries is generally not a good idea. If you need to reduce size, you might want to have two separate apks for older (armeabi) and newer (armeabi-v7a) devices.

Pandas DataFrame to List of Dictionaries

As an extension to John Galt's answer -

For the following DataFrame,

   customer  item1   item2   item3
0         1  apple    milk  tomato
1         2  water  orange  potato
2         3  juice   mango   chips

If you want to get a list of dictionaries including the index values, you can do something like,

df.to_dict('index')

Which outputs a dictionary of dictionaries where keys of the parent dictionary are index values. In this particular case,

{0: {'customer': 1, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},
 1: {'customer': 2, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},
 2: {'customer': 3, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}}

how to make a jquery "$.post" request synchronous

From the Jquery docs: you specify the async option to be false to get a synchronous Ajax request. Then your callback can set some data before your mother function proceeds.

Here's what your code would look like if changed as suggested:

beforecreate: function(node,targetNode,type,to) {
    jQuery.ajax({
         url:    url,
         success: function(result) {
                      if(result.isOk == false)
                          alert(result.message);
                  },
         async:   false
    });          
}

this is because $.ajax is the only request type that you can set the asynchronousity for

PHP add elements to multidimensional array with array_push

if you want to add the data in the increment order inside your associative array you can do this:

$newdata =  array (
      'wpseo_title' => 'test',
      'wpseo_desc' => 'test',
      'wpseo_metakey' => 'test'
    );

// for recipe

$md_array["recipe_type"][] = $newdata;

//for cuisine

 $md_array["cuisine"][] = $newdata;

this will get added to the recipe or cuisine depending on what was the last index.

Array push is usually used in the array when you have sequential index: $arr[0] , $ar[1].. you cannot use it in associative array directly. But since your sub array is had this kind of index you can still use it like this

array_push($md_array["cuisine"],$newdata);

Given URL is not allowed by the Application configuration Facebook application error

So... facebook distinguishes pretty harshly between http and https in your app. This is just another small thing to check if you run into trouble.

How can I get the UUID of my Android phone in an application?

Instead of getting IMEI from TelephonyManager use ANDROID_ID.

Settings.Secure.ANDROID_ID

This works for each android device irrespective of having telephony.

Detecting input change in jQuery?

UPDATED for clarification and example

examples: http://jsfiddle.net/pxfunc/5kpeJ/

Method 1. input event

In modern browsers use the input event. This event will fire when the user is typing into a text field, pasting, undoing, basically anytime the value changed from one value to another.

In jQuery do that like this

$('#someInput').bind('input', function() { 
    $(this).val() // get the current value of the input field.
});

starting with jQuery 1.7, replace bind with on:

$('#someInput').on('input', function() { 
    $(this).val() // get the current value of the input field.
});

Method 2. keyup event

For older browsers use the keyup event (this will fire once a key on the keyboard has been released, this event can give a sort of false positive because when "w" is released the input value is changed and the keyup event fires, but also when the "shift" key is released the keyup event fires but no change has been made to the input.). Also this method doesn't fire if the user right-clicks and pastes from the context menu:

$('#someInput').keyup(function() {
    $(this).val() // get the current value of the input field.
});

Method 3. Timer (setInterval or setTimeout)

To get around the limitations of keyup you can set a timer to periodically check the value of the input to determine a change in value. You can use setInterval or setTimeout to do this timer check. See the marked answer on this SO question: jQuery textbox change event or see the fiddle for a working example using focus and blur events to start and stop the timer for a specific input field

How to remove leading zeros from alphanumeric text?

Using regex as some of the answers suggest is a good way to do that. If you don't want to use regex then you can use this code:

String s = "00a0a121";

while(s.length()>0 && s.charAt(0)=='0')
{
   s = s.substring(1); 
}

Align DIV's to bottom or baseline

You would probably would have to set the child div to have position: absolute.

Update your child style to

#parentDiv .childDiv
{
  height:100px;
  width:30px;
  background-color:#999;
  position:absolute;
  top:207px;
}

How to prettyprint a JSON file?

You could use the built-in module pprint (https://docs.python.org/3.9/library/pprint.html).

How you can read the file with json data and print it out.

import json
import pprint

json_data = None
with open('file_name.txt', 'r') as f:
    data = f.read()
    json_data = json.loads(data)

pprint.pprint(json_data)

RecyclerView - How to smooth scroll to top of item on a certain position?

Probably @droidev approach is the correct one, but I just want to publish something a little bit different, which does basically the same job and doesn't require extension of the LayoutManager.

A NOTE here - this is gonna work well if your item (the one that you want to scroll on the top of the list) is visible on the screen and you just want to scroll it to the top automatically. It is useful when the last item in your list has some action, which adds new items in the same list and you want to focus the user on the new added items:

int recyclerViewTop = recyclerView.getTop();
int positionTop = recyclerView.findViewHolderForAdapterPosition(positionToScroll) != null ? recyclerView.findViewHolderForAdapterPosition(positionToScroll).itemView.getTop() : 200;
final int calcOffset = positionTop - recyclerViewTop; 
//then the actual scroll is gonna happen with (x offset = 0) and (y offset = calcOffset)
recyclerView.scrollBy(0, offset);

The idea is simple: 1. We need to get the top coordinate of the recyclerview element; 2. We need to get the top coordinate of the view item that we want to scroll to the top; 3. At the end with the calculated offset we need to do

recyclerView.scrollBy(0, offset);

200 is just example hard coded integer value that you can use if the viewholder item doesn't exist, because that is possible as well.

Force decimal point instead of comma in HTML5 number input (client-side)

HTML step Attribute

<input type="number" name="points" step="3">

Example: if step="3", legal numbers could be -3, 0, 3, 6, etc.

 

Tip: The step attribute can be used together with the max and min attributes to create a range of legal values.

Note: The step attribute works with the following input types: number, range, date, datetime, datetime-local, month, time and week.

Can I use DIV class and ID together in CSS?

#y.x should work. And it's convenient too. You can make a page with different kinds of output. You can give a certain element an id, but give it different classes depending on the look you want.

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

Passing command line arguments from Maven as properties in pom.xml

mvn clean package -DpropEnv=PROD

Then using like this in POM.xml

<properties>
    <myproperty>${propEnv}</myproperty>
</properties>

How do I check particular attributes exist or not in XML?

You can use LINQ to XML,

XDocument doc = XDocument.Load(file);

var result = (from ele in doc.Descendants("section")
              select ele).ToList();

foreach (var t in result)
{
    if (t.Attributes("split").Count() != 0)
    {
        // Exist
    }

    // Suggestion from @UrbanEsc
    if(t.Attributes("split").Any())
    {

    }
}

OR

 XDocument doc = XDocument.Load(file);

 var result = (from ele in doc.Descendants("section").Attributes("split")
               select ele).ToList();

 foreach (var t in result)
 {
     // Response.Write("<br/>" +  t.Value);
 }

Changing the default title of confirm() in JavaScript?

You can always use a hidden div and use javascript to "popup" the div and have buttons that are like yes and or no. Pretty easy stuff to do.

Struct like objects in Java

You can make a simple class with public fields and no methods in Java, but it is still a class and is still handled syntactically and in terms of memory allocation just like a class. There is no way to genuinely reproduce structs in Java.

Should I use window.navigate or document.location in JavaScript?

window.location also affects to the frame,

the best form i found is:

parent.window.location.href

And the worse is:

parent.document.URL 

I did a massive browser test, and some rare IE with several plugins get undefined with the second form.

Using sed and grep/egrep to search and replace

try something using a for loop

 for i in `egrep -lR "YOURSEARCH" .` ; do echo  $i; sed 's/f/k/' <$i >/tmp/`basename $i`; mv /tmp/`basename $i` $i; done

not pretty, but should do.

Using find to locate files that match one of multiple patterns

What about

ls {*.py,*.html}

It lists out all the files ending with .py or .html in their filenames

android edittext onchange listener

It was bothering me that implementing a listener for all of my EditText fields required me to have ugly, verbose code so I wrote the below class. May be useful to anyone stumbling upon this.

public abstract class TextChangedListener<T> implements TextWatcher {
    private T target;

    public TextChangedListener(T target) {
        this.target = target;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {}

    @Override
    public void afterTextChanged(Editable s) {
        this.onTextChanged(target, s);
    }

    public abstract void onTextChanged(T target, Editable s);
}

Now implementing a listener is a little bit cleaner.

editText.addTextChangedListener(new TextChangedListener<EditText>(editText) {
            @Override
            public void onTextChanged(EditText target, Editable s) {
                //Do stuff
            }
        });

As for how often it fires, one could maybe implement a check to run their desired code in //Do stuff after a given a

How to hide a div element depending on Model value? MVC

Try:

<div style="@(Model.booleanVariable ? "display:block" : "display:none")">Some links</div>

Use the "Display" style attribute with your bool model attribute to define the div's visibility.

how to make div click-able?

I suggest to use jQuery:

$('#mydiv')
  .css('cursor', 'pointer')
  .click(
    function(){
     alert('Click event is fired');
    }
  )
  .hover(
    function(){
      $(this).css('background', '#ff00ff');
    },
    function(){
      $(this).css('background', '');
    }
  );

TypeError: $.ajax(...) is not a function?

If you are using bootstrap html template remember to remove the link to jquery slim at the bottom of the template. I post this detail here as I cannot comment answers yet..

How to set seekbar min and max value

There is no option to set a min or max value in seekbar , so you can use a formula here to scale your value.

Desired_value = ( progress * ( Max_value - Min_value) / 100 ) + Min_value

I have tested this formula in many examples. In your example, if the progressBar is the middle(i.e. progress = 50 ) and your Min_val and Max_val are 60 and 180 respectively, then this formula will give you the Desired_value '120'.

How to predict input image using trained model in Keras?

keras predict_classes (docs) outputs A numpy array of class predictions. Which in your model case, the index of neuron of highest activation from your last(softmax) layer. [[0]] means that your model predicted that your test data is class 0. (usually you will be passing multiple image, and the result will look like [[0], [1], [1], [0]] )

You must convert your actual label (e.g. 'cancer', 'not cancer') into binary encoding (0 for 'cancer', 1 for 'not cancer') for binary classification. Then you will interpret your sequence output of [[0]] as having class label 'cancer'

How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter?

For me, to develop for web, works fine the following:

Image(
  image: AssetImage('lib/images/portadaSchamann5.png'),
  alignment: Alignment.center,
  height: double.infinity,
  width: double.infinity,
  fit: BoxFit.fill,
),

Service will not start: error 1067: the process terminated unexpectedly

Goto:

Registry-> HKEY_LOCAL??_MACHINE-> System-> Cur??rentControlSet-> Servi??ces.

Find the concerned service & delete it. Close regedit. Reboot the PC & Re-install the concerned service. Now the error should be gone.

django order_by query set, ascending and descending

Reserved.objects.filter(client=client_id).order_by('-check_in')

A hyphen "-" in front of "check_in" indicates descending order. Ascending order is implied.

We don't have to add an all() before filter(). That would still work, but you only need to add all() when you want all objects from the root QuerySet.

More on this here: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters

ASP.Net MVC: How to display a byte array image from model

If the image isn't that big, and if there's a good chance you'll be re-using the image often, and if you don't have too many of them, and if the images are not secret (meaning it's no big deal if one user could potentially see another person's image)...

Lots of "if"s here, so there's a good chance this is a bad idea:

You can store the image bytes in Cache for a short time, and make an image tag pointed toward an action method, which in turn reads from the cache and spits out your image. This will allow the browser to cache the image appropriately.

// In your original controller action
HttpContext.Cache.Add("image-" + model.Id, model.ImageBytes, null,
    Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(1),
    CacheItemPriority.Normal, null);

// In your view:
<img src="@Url.Action("GetImage", "MyControllerName", new{fooId = Model.Id})">

// In your controller:
[OutputCache(VaryByParam = "fooId", Duration = 60)]
public ActionResult GetImage(int fooId) {
    // Make sure you check for null as appropriate, re-pull from DB, etc.
    return File((byte[])HttpContext.Cache["image-" + fooId], "image/gif");
}

This has the added benefit (or is it a crutch?) of working in older browsers, where the inline images don't work in IE7 (or IE8 if larger than 32kB).

Best way to check for "empty or null value"

In ran into a kind of similar case, were I had to do this . My Table definition look like :

id(bigint)|name (character varying)|results(character varying)
1 | "Peters"| [{"jk1":"jv1"},{"jk1":"jv2"}]
2 | "Russel"| null

To filter out the results column with null or empty in it , what worked was :

SELECT * FROM tablename where results NOT IN  ('null','{}'); 

This returned all rows which are not null on results.

I'm not sure how to fix this query to return the same all rows which are not null on results.

SELECT * FROM tablename where results is not null; 

--- hmm what am I missing,casting ? any inputs?

How to post a file from a form with Axios

Add the file to a formData object, and set the Content-Type header to multipart/form-data.

var formData = new FormData();
var imagefile = document.querySelector('#file');
formData.append("image", imagefile.files[0]);
axios.post('upload_file', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
})

When is null or undefined used in JavaScript?

Regarding this topic the specification (ecma-262) is quite clear

I found it really useful and straightforward, so that I share it: - Here you will find Equality algorithm - Here you will find Strict equality algorithm

I bumped into it reading "Abstract equality, strict equality, and same value" from mozilla developer site, section sameness.

I hope you find it useful.

How to throw RuntimeException ("cannot find symbol")

throw new RuntimeException(msg); // notice the "new" keyword

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

That happened for me, because I was invoking commit() from subfragment which was leaking activity. It kept activity as a property and on a rotation activity variable was not updated by onAttach(); So I was trying to commit transaction on zombie Activity by retained (setRetainInstance(true);) fragment.

Using for loop inside of a JSP

Do this

    <% for(int i = 0; i < allFestivals.size(); i+=1) { %>
        <tr>      
            <td><%=allFestivals.get(i).getFestivalName()%></td>
        </tr>
    <% } %>

Better way is to use c:foreach see link jstl for each

How can I change the user on Git Bash?

For any OS

This helped me so I'll put it here, just in case. Once you are done with adding the rsa keys for both the accounts, add a config file in your .ssh directory for both the accounts (.ssh/config)

# First account
Host github.com-<FIRST_ACCOUNT_USERNAME_HERE>
   HostName github.com
   User git
   IdentityFile ~/.ssh/id_rsa_user1
   
# Second account
Host github.com-<SECOND_ACCOUNT_USERNAME_HERE>   
   HostName github.com
   User git
   IdentityFile ~/.ssh/id_rsa_user2

Make sure you use the correct usernames and RSA files. Next, you can open the terminal/git bash on the repository root and check which account you would be pushing from

git config user.email

Suppose this returns the first user email and you want to push from the second user. Change the local user.name and user.email :

git config user.name "SECOND_USER"
git config user.email "[email protected]"

(This won't change the global config and you can have the first user set up as the global user). Once done, you can confirm with git config user.email and it should return the email of the second user. You're all set to push to GitHub with the second user. The rest is all the same old git add , git commit and git push. To push from the first user, change the local user.name again and follow the same steps. Hope it helps :)


If the above steps are still not working for you, check to see if you have uploaded the RSA keys within GitHub portal. Refer to GitHub documentation:

Then, clear your ssh cached keys Reference

ssh-add -D

Then add you 2 ssh keys

ssh-add ~/.ssh/id_rsa_user1
ssh-add ~/.ssh/id_rsa_user2

Then type in your terminal:

ssh -T [email protected]<SECOND_ACCOUNT_USERNAME_HERE>

You should see the following output:

Hi <SECOND_USERNAME>! You've successfully authenticated, but GitHub does not provide shell access.

Then, assign the correct remote to your local repository. Make sure you put the same username as the one you gave in your .ssh/config file next to Host. In the following case [email protected]<SECOND_ACCOUNT_USERNAME_HERE>.

git remote rm origin
git remote add origin [email protected]<SECOND_ACCOUNT_USERNAME_HERE>:/your_username/your_repository.git

Convert Rtf to HTML

Mike Stall posted the code for one he wrote in c# here :

http://blogs.msdn.com/jmstall/archive/2006/10/20/rtf_5F00_html.aspx

How to check if a string is null in python

Try this:

if cookie and not cookie.isspace():
    # the string is non-empty
else:
    # the string is empty

The above takes in consideration the cases where the string is None or a sequence of white spaces.

Finding the max value of an attribute in an array of objects

To find the maximum y value of the objects in array:

Math.max.apply(Math, array.map(function(o) { return o.y; }))

Session 'app': Error Launching activity

For me the problem was that the app I was trying to launch was already installed under a different user account on my phone. I saw this when I went to Settings->apps looking to uninstall it. I switched to the other user, uninstalled it, came back to the original user, and was able to install and launch the app from Android Studio with no more problems.

Simple way to query connected USB devices info in Python?

When I run your code, I get the following output for example.

<usb.Device object at 0xef38c0>
Device: 001
  idVendor: 7531 (0x1d6b)
  idProduct: 1 (0x0001)
Manufacturer: 3
Serial: 1
Product: 2

Noteworthy are that a) I have usb.Device objects whereas you have usb.legacy.Device objects, and b) I have device filenames.

Each usb.Bus has a dirname field and each usb.Device has the filename. As you can see, the filename is something like 001, and so is the dirname. You can combine these to get the bus file. For dirname=001 and filname=001, it should be something like /dev/bus/usb/001/001.

You should first, though figure out what this "usb.legacy" situation is. I'm running the latest version and I don't even have a legacy sub-module.

Finally, you should use the idVendor and idProduct fields to uniquely identify the device when it's plugged in.

Error : java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V

I had the same error when initializing Spring on startup, using some different library versions, but everything worked when I got my versions in this order in the classpath (the other libraries in the cp were not important):

  1. asm-3.1.jar
  2. cglib-nodep-2.1_3.jar
  3. asm-attrs-1.5.3.jar

Tomcat view catalina.out log file

I found logs of Apache Tomcat/9.0.33 version in below path:

In tail -f /opt/tomcat/logs/catalina.out

Thanks.

cannot make a static reference to the non-static field

main is a static method. It cannot refer to balance, which is an attribute (non-static variable). balance has meaning only when it is referred through an object reference (such as myAccount.balance or yourAccount.balance). But it doesn't have any meaning when it is referred through class (such as Account.balance (whose balance is that?))

I made some changes to your code so that it compiles.

public static void main(String[] args) {
    Account account = new Account(1122, 20000, 4.5);
    account.withdraw(2500);
    account.deposit(3000);

and:

public void withdraw(double withdrawAmount) {
    balance -= withdrawAmount;
}

public void deposit(double depositAmount) {
    balance += depositAmount;
}   

What is the difference between a URI, a URL and a URN?

Identity = Name with Location

Every URL(Uniform Resource Locator) is a URI(Uniform Resource Identifier), abstractly speaking, but every URI is not a URL. There is another subcategory of URI is URN (Uniform Resource Name), which is a named resource but do not specify how to locate them, like mailto, news, ISBN is URIs. Source

enter image description here

URN:

  • URN Format : urn:[namespace identifier]:[namespace specific string]
  • urn: and : stand for themselves.
  • Examples:
    • urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66
    • urn:ISSN:0167-6423
    • urn:isbn:096139210x
    • Amazon Resource Names (ARNs) is a uniquely identify AWS resources.
      • ARN Format : arn:partition:service:region:account-id:resource

URL:

  • URL Format : [scheme]://[Domain][Port]/[path]?[queryString]#[fragmentId]
  • :,//,? and # stand for themselves.
  • schemes are https,ftp,gopher,mailto,news,telnet,file,man,info,whatis,ldap...
  • Examples:

Analogy:
To reach a person: Driving(protocol others SMS, email, phone), Address(hostname other phone-number, emailid) and person name(object name with a relative path).

Getting list of parameter names inside python function

locals() returns a dictionary with local names:

def func(a,b,c):
    print(locals().keys())

prints the list of parameters. If you use other local variables those will be included in this list. But you could make a copy at the beginning of your function.

cURL not working (Error #77) for SSL connections on CentOS for non-root users

I had faced same issue whenever I tried executing curl on my https server.

About to connect() to localhost port 443 (#0)
Trying ::1...
Connected to localhost (::1) port 443 (#0)
Initializing NSS with certpath: sql:/etc/pki/nssdb

Observed this issue when I configured keystore path incorrectly. After correcting keystore path it worked.