Programs & Examples On #Actionview

HTML and Ruby templates used in [tag:ruby-on-rails]

Under what circumstances can I call findViewById with an Options Menu / Action Bar item?

I am trying to obtain a handle on one of the views in the Action Bar

I will assume that you mean something established via android:actionLayout in your <item> element of your <menu> resource.

I have tried calling findViewById(R.id.menu_item)

To retrieve the View associated with your android:actionLayout, call findItem() on the Menu to retrieve the MenuItem, then call getActionView() on the MenuItem. This can be done any time after you have inflated the menu resource.

How to filter a RecyclerView with a SearchView

I recommend modify the solution of @Xaver Kapeller with 2 things below to avoid a problem after you cleared the searched text (the filter didn't work anymore) due to the list back of adapter has smaller size than filter list and the IndexOutOfBoundsException happened. So the code need to modify as below

public void addItem(int position, ExampleModel model) {
    if(position >= mModel.size()) {
        mModel.add(model);
        notifyItemInserted(mModel.size()-1);
    } else {
        mModels.add(position, model);
        notifyItemInserted(position);
    }
}

And modify also in moveItem functionality

public void moveItem(int fromPosition, int toPosition) {
    final ExampleModel model = mModels.remove(fromPosition);
    if(toPosition >= mModels.size()) {
        mModels.add(model);
        notifyItemMoved(fromPosition, mModels.size()-1);
    } else {
        mModels.add(toPosition, model);
        notifyItemMoved(fromPosition, toPosition); 
    }
}

Hope that It could help you!

Creating a SearchView that looks like the material design guidelines

The following will create a SearchView identical to the one in Gmail and add it to the given Toolbar. You'll just have to implement your own "ViewUtil.convertDpToPixel" method.

private SearchView createMaterialSearchView(Toolbar toolbar, String hintText) {

    setSupportActionBar(toolbar);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setDisplayShowCustomEnabled(true);
    actionBar.setDisplayShowTitleEnabled(false);

    SearchView searchView = new SearchView(this);
    searchView.setIconifiedByDefault(false);
    searchView.setMaxWidth(Integer.MAX_VALUE);
    searchView.setMinimumHeight(Integer.MAX_VALUE);
    searchView.setQueryHint(hintText);

    int rightMarginFrame = 0;
    View frame = searchView.findViewById(getResources().getIdentifier("android:id/search_edit_frame", null, null));
    if (frame != null) {
        LinearLayout.LayoutParams frameParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        rightMarginFrame = ((LinearLayout.LayoutParams) frame.getLayoutParams()).rightMargin;
        frameParams.setMargins(0, 0, 0, 0);
        frame.setLayoutParams(frameParams);
    }

    View plate = searchView.findViewById(getResources().getIdentifier("android:id/search_plate", null, null));
    if (plate != null) {
        plate.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        plate.setPadding(0, 0, rightMarginFrame, 0);
        plate.setBackgroundColor(Color.TRANSPARENT);
    }

    int autoCompleteId = getResources().getIdentifier("android:id/search_src_text", null, null);
    if (searchView.findViewById(autoCompleteId) != null) {
        EditText autoComplete = (EditText) searchView.findViewById(autoCompleteId);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, (int) ViewUtil.convertDpToPixel(36));
        params.weight = 1;
        params.gravity = Gravity.CENTER_VERTICAL;
        params.leftMargin = rightMarginFrame;
        autoComplete.setLayoutParams(params);
        autoComplete.setTextSize(16f);
    }

    int searchMagId = getResources().getIdentifier("android:id/search_mag_icon", null, null);
    if (searchView.findViewById(searchMagId) != null) {
        ImageView v = (ImageView) searchView.findViewById(searchMagId);
        v.setImageDrawable(null);
        v.setPadding(0, 0, 0, 0);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 0, 0, 0);
        v.setLayoutParams(params);
    }

    toolbar.setTitle(null);
    toolbar.setContentInsetsAbsolute(0, 0);
    toolbar.addView(searchView);

    return searchView;
}

How to use SearchView in Toolbar Android

If you would like to setup the search facility inside your Fragment, just add these few lines:

Step 1 - Add the search field to you toolbar:

<item
    android:id="@+id/action_search"
    android:icon="@android:drawable/ic_menu_search"
    app:showAsAction="always|collapseActionView"
    app:actionViewClass="android.support.v7.widget.SearchView"
    android:title="Search"/>

Step 2 - Add the logic to your onCreateOptionsMenu()

import android.support.v7.widget.SearchView; // not the default !

@Override
public boolean onCreateOptionsMenu( Menu menu) {
    getMenuInflater().inflate( R.menu.main, menu);

    MenuItem myActionMenuItem = menu.findItem( R.id.action_search);
    searchView = (SearchView) myActionMenuItem.getActionView();
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            // Toast like print
            UserFeedback.show( "SearchOnQueryTextSubmit: " + query);
            if( ! searchView.isIconified()) {
                searchView.setIconified(true);
            }
            myActionMenuItem.collapseActionView();
            return false;
        }
        @Override
        public boolean onQueryTextChange(String s) {
            // UserFeedback.show( "SearchOnQueryTextChanged: " + s);
            return false;
        }
    });
    return true;
}

Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources

**

bundle install --no-deployment

**

$ jekyll help

jekyll 4.0.0 -- Jekyll is a blog-aware, static site generator in Ruby

Implementing SearchView in action bar


For Searchview use these code

  1. For XML

    <android.support.v7.widget.SearchView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/searchView">
    
    </android.support.v7.widget.SearchView>
    

  2. In your Fragment or Activity

    package com.example.user.salaryin;
    
    import android.app.ProgressDialog;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.view.MenuItemCompat;
    import android.support.v7.widget.GridLayoutManager;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.support.v7.widget.SearchView;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Toast;
    import com.example.user.salaryin.Adapter.BusinessModuleAdapter;
    import com.example.user.salaryin.Network.ApiClient;
    import com.example.user.salaryin.POJO.ProductDetailPojo;
    import com.example.user.salaryin.Service.ServiceAPI;
    import java.util.ArrayList;
    import java.util.List;
    import retrofit2.Call;
    import retrofit2.Callback;
    import retrofit2.Response;
    
    
    public class OneFragment extends Fragment implements SearchView.OnQueryTextListener {
    
    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;
    ArrayList<ProductDetailPojo> arrayList;
    BusinessModuleAdapter adapter;
    private ProgressDialog pDialog;
    GridLayoutManager gridLayoutManager;
    SearchView searchView;
    
    public OneFragment() {
        // Required empty public constructor
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    
        View rootView = inflater.inflate(R.layout.one_fragment,container,false);
    
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Please wait...");
    
    
        searchView=(SearchView)rootView.findViewById(R.id.searchView);
        searchView.setQueryHint("Search BY Brand");
        searchView.setOnQueryTextListener(this);
    
        recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
        layoutManager = new LinearLayoutManager(this.getActivity());
        recyclerView.setLayoutManager(layoutManager);
        gridLayoutManager = new GridLayoutManager(this.getActivity().getApplicationContext(), 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setHasFixedSize(true);
        getImageData();
    
    
        // Inflate the layout for this fragment
        //return inflater.inflate(R.layout.one_fragment, container, false);
        return rootView;
    }
    
    
    private void getImageData() {
        pDialog.show();
        ServiceAPI service = ApiClient.getRetrofit().create(ServiceAPI.class);
        Call<List<ProductDetailPojo>> call = service.getBusinessImage();
    
        call.enqueue(new Callback<List<ProductDetailPojo>>() {
            @Override
            public void onResponse(Call<List<ProductDetailPojo>> call, Response<List<ProductDetailPojo>> response) {
                if (response.isSuccessful()) {
                    arrayList = (ArrayList<ProductDetailPojo>) response.body();
                    adapter = new BusinessModuleAdapter(arrayList, getActivity());
                    recyclerView.setAdapter(adapter);
                    pDialog.dismiss();
                } else if (response.code() == 401) {
                    pDialog.dismiss();
                    Toast.makeText(getActivity(), "Data is not found", Toast.LENGTH_SHORT).show();
                }
    
            }
    
            @Override
            public void onFailure(Call<List<ProductDetailPojo>> call, Throwable t) {
                Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_SHORT).show();
                pDialog.dismiss();
    
            }
        });
    }
    
       /* @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        getActivity().getMenuInflater().inflate(R.menu.menu_search, menu);
        MenuItem menuItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
        searchView.setQueryHint("Search Product");
        searchView.setOnQueryTextListener(this);
    }*/
    
    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }
    
    @Override
    public boolean onQueryTextChange(String newText) {
        newText = newText.toLowerCase();
        ArrayList<ProductDetailPojo> newList = new ArrayList<>();
        for (ProductDetailPojo productDetailPojo : arrayList) {
            String name = productDetailPojo.getDetails().toLowerCase();
    
            if (name.contains(newText) )
                newList.add(productDetailPojo);
            }
        adapter.setFilter(newList);
        return true;
       }
    }
    
  3. In adapter class

     public void setFilter(List<ProductDetailPojo> newList){
        arrayList=new ArrayList<>();
        arrayList.addAll(newList);
        notifyDataSetChanged();
    }
    

rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

You will get better performance in production if you set config.assets.compile to false in production.rb and precompile your assets. You can precompile with this rake task:

bundle exec rake assets:precompile

If you are using Capistrano, version 2.8.0 has a recipe to handle this at deploy time. For more info, see the "In Production" section of the Asset Pipeline Guide: http://guides.rubyonrails.org/asset_pipeline.html

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

I encountered the error while migrating an app from Ruby 1.8.7 to 1.9.3 and it only occured in production. It turned out that I had some leftovers in my Memcache store. The now encoding sensitive Ruby 1.9.3 version of my app tried to mix old ASCII-8BIT values with new UTF-8.

It was as simple as flushing the cache to fix it for me.

Asp.Net MVC with Drop Down List, and SelectListItem Assistance

You have a view model to which your view is strongly typed => use strongly typed helpers:

<%= Html.DropDownListFor(
    x => x.SelectedAccountId, 
    new SelectList(Model.Accounts, "Value", "Text")
) %>

Also notice that I use a SelectList for the second argument.

And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:

public ActionResult AccountTransaction()
{
    var accounts = Services.AccountServices.GetAccounts(false);
    var viewModel = new AccountTransactionView
    {
        Accounts = accounts.Select(a => new SelectListItem
        {
            Text = a.Description,
            Value = a.AccountId.ToString()
        })
    };
    return View(viewModel);
}

link_to method and click event in Rails

just use

=link_to "link", "javascript:function()"

Using helpers in model: how do I include helper dependencies?

Just change the first line as follows :

include ActionView::Helpers

that will make it works.

UPDATE: For Rails 3 use:

ActionController::Base.helpers.sanitize(str)

Credit goes to lornc's answer

Java: Getting a substring from a string starting after a particular character

This can also get the filename

import java.nio.file.Paths;
import java.nio.file.Path;
Path path = Paths.get("/abc/def/ghfj.doc");
System.out.println(path.getFileName().toString());

Will print ghfj.doc

Accessing the web page's HTTP Headers in JavaScript

I think the question went in the wrong way, If you want to take the Request header from JQuery/JavaScript the answer is simply No. The other solutions is create a aspx page or jsp page then we can easily access the request header. Take all the request in aspx page and put into a session/cookies then you can access the cookies in JavaScript page..

How to set the font style to bold, italic and underlined in an Android TextView?

Programmatialy:

You can do programmatically using setTypeface() method:

Below is the code for default Typeface

textView.setTypeface(null, Typeface.NORMAL);      // for Normal Text
textView.setTypeface(null, Typeface.BOLD);        // for Bold only
textView.setTypeface(null, Typeface.ITALIC);      // for Italic
textView.setTypeface(null, Typeface.BOLD_ITALIC); // for Bold and Italic

and if you want to set custom Typeface:

textView.setTypeface(textView.getTypeface(), Typeface.NORMAL);      // for Normal Text
textView.setTypeface(textView.getTypeface(), Typeface.BOLD);        // for Bold only
textView.setTypeface(textView.getTypeface(), Typeface.ITALIC);      // for Italic
textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC); // for Bold and Italic

XML:

You can set Directly in XML file in like:

android:textStyle="normal"
android:textStyle="normal|bold"
android:textStyle="normal|italic"
android:textStyle="bold"
android:textStyle="bold|italic"

CSS submit button weird rendering on iPad/iPhone

oops! just found myself: just add this line on any element you need

   -webkit-appearance: none;

Base64 encoding in SQL Server 2005 T-SQL

Here's a modification to mercurial's answer that uses the subquery on the decode as well, allowing the use of variables in both instances.

DECLARE
    @EncodeIn VARCHAR(100) = 'Test String In',
    @EncodeOut VARCHAR(500),
    @DecodeOut VARCHAR(200)    

SELECT @EncodeOut = 
    CAST(N'' AS XML).value(
          'xs:base64Binary(xs:hexBinary(sql:column("bin")))'
        , 'VARCHAR(MAX)'
    )
FROM (
    SELECT CAST(@EncodeIn AS VARBINARY(MAX)) AS bin
) AS bin_sql_server_temp;

PRINT @EncodeOut

SELECT @DecodeOut = 
CAST(
    CAST(N'' AS XML).value(
        'xs:base64Binary(sql:column("bin"))'
      , 'VARBINARY(MAX)'
    ) 
    AS VARCHAR(MAX)
) 
FROM (
    SELECT CAST(@EncodeOut AS VARCHAR(MAX)) AS bin
) AS bin_sql_server_temp;

PRINT @DecodeOut

VSCode cannot find module '@angular/core' or any other modules

In the VSCode status bar, it must be showing typescript version - like this

enter image description here

Clicking on that version number will show you this, different versions available.

enter image description here

If you are using the VSCode version then switching to Workspace version solves the problem if it is VScode issue rather than your tsconfig.json (I am already using that one, so not highlighted)

enter image description here

How to make certain text not selectable with CSS

The CSS below stops users from being able to select text.

-webkit-user-select: none; /* Safari */        
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* IE10+/Edge */
user-select: none; /* Standard */

To target IE9 downwards the html attribute unselectable must be used instead:

<p unselectable="on">Test Text</p>

PHP returning JSON to JQUERY AJAX CALL

You can return json in PHP this way:

header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;

How to render a PDF file in Android

you can use a simple method by import

implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'

and the XML code is

<com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/pdfv"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </com.github.barteksc.pdfviewer.PDFView>

and just declare and add a file to an asset folder and just assign the name

   PDFView  pdfView=findViewById(R.id.pdfv);       
    pdfView.fromAsset("agl.pdf").load();

Get product id and product type in magento?

This worked for me-

if(Mage::registry('current_product')->getTypeId() == 'simple' ) {

Use getTypeId()

Stopping a JavaScript function when a certain condition is met

Use a try...catch statement in your main function and whenever you want to stop the function just use:

throw new Error("Stopping the function!");

Convert International String to \u Codes in java

You could probably hack if from this JavaScript code:

/* convert  to \uD83D\uDE4C */
function text_to_unicode(string) {
  'use strict';

  function is_whitespace(c) { return 9 === c || 10 === c || 13 === c || 32 === c;  }
  function left_pad(string) { return Array(4).concat(string).join('0').slice(-1 * Math.max(4, string.length)); }

  string = string.split('').map(function(c){ return "\\u" + left_pad(c.charCodeAt(0).toString(16).toUpperCase()); }).join('');

  return string;
}


/* convert \uD83D\uDE4C to  */
function unicode_to_text(string) {
  var  prefix = "\\\\u"
     , regex  = new RegExp(prefix + "([\da-f]{4})","ig")
     ; 

  string = string.replace(regex, function(match, backtrace1){
    return String.fromCharCode( parseInt(backtrace1, 16) )
  });

  return string;
}

source: iCompile - Yet Another JavaScript Unicode Encode/Decode

C# event with custom arguments

Example with no parameters:

delegate void NewEventHandler();
public event NewEventHandler OnEventHappens;

And from another class, you can subscribe to

otherClass.OnEventHappens += ExecuteThisFunctionWhenEventHappens;

And declare that function with no parameters.

Lightweight Javascript DB for use in Node.js

Maybe you should try LocallyDB it's easy-to-use and lightweight in addition to the with advanced selecting system similar to javascript conditional expression...

https://github.com/btwael/locallydb

How can prepared statements protect from SQL injection attacks?

In SQL Server, using a prepared statement is definitely injection-proof because the input parameters don't form the query. It means that the executed query is not a dynamic query. Example of an SQL injection vulnerable statement.

string sqlquery = "select * from table where username='" + inputusername +"' and password='" + pass + "'";

Now if the value in the inoutusername variable is something like a' or 1=1 --, this query now becomes:

select * from table where username='a' or 1=1 -- and password=asda

And the rest is commented after --, so it never gets executed and bypassed as using the prepared statement example as below.

Sqlcommand command = new sqlcommand("select * from table where username = @userinput and password=@pass");
command.Parameters.Add(new SqlParameter("@userinput", 100));
command.Parameters.Add(new SqlParameter("@pass", 100));
command.prepare();

So in effect you cannot send another parameter in, thus avoiding SQL injection...

Failed to start mongod.service: Unit mongod.service not found

For those that run into this and end up on this answer, as I did, where they got this error during uninstall orupgrade and Ubuntu keeps failing to uninstall the previous because the service doesn't exist this one line will get you past that and allow the uninstall or upgrade to continue.

sudo touch /lib/systemd/system/mongod.service

Is there a C# String.Format() equivalent in JavaScript?

I created it a long time ago, related question

String.Format = function (b) {
    var a = arguments;
    return b.replace(/(\{\{\d\}\}|\{\d\})/g, function (b) {
        if (b.substring(0, 2) == "{{") return b;
        var c = parseInt(b.match(/\d/)[0]);
        return a[c + 1]
    })
};

How to open a new file in vim in a new window

I use this subtle alias:

alias vim='gnome-terminal -- vim'

-x is deprecated now. We need to use -- instead

Where is my .vimrc file?

From cmd (Windows):

C\Users\You> `vim foo.txt`

Now in Vim, enter command mode by typing: ":" (i.e. Shift + ;)

:tabedit $HOME/.vimrc

In PowerShell, how do I define a function in a file and call it from the PowerShell commandline?

If your file has only one main function that you want to call/expose, then you can also just start the file with:

Param($Param1)

You can then call it e.g. as follows:

.\MyFunctions.ps1 -Param1 'value1'

This makes it much more convenient if you want to easily call just that function without having to import the function.

Not able to launch IE browser using Selenium2 (Webdriver) with Java

It needs to set same Security level in all zones. To do that follow the steps below:

  1. Open IE
  2. Go to Tools -> Internet Options -> Security
  3. Set all zones (Internet, Local intranet, Trusted sites, Restricted sites) to the same protected mode, enabled or disabled should not matter.

Finally, set Zoom level to 100% by right clicking on the gear located at the top right corner and enabling the status-bar. Default zoom level is now displayed at the lower right.

MySQL: update a field only if condition is met

Yes!

Here you have another example:

UPDATE prices
SET final_price= CASE
   WHEN currency=1 THEN 0.81*final_price
   ELSE final_price
END

This works because MySQL doesn't update the row, if there is no change, as mentioned in docs:

If you set a column to the value it currently has, MySQL notices this and does not update it.

Make a link use POST instead of GET

Check this it will help you

$().redirect('test.php', {'a': 'value1', 'b': 'value2'});

Force drop mysql bypassing foreign key constraint

You can use the following steps, its worked for me to drop table with constraint,solution already explained in the above comment, i just added screen shot for that -enter image description here

Simple way to repeat a string

using only JRE classes (System.arraycopy) and trying to minimize the number of temp objects you can write something like:

public static String repeat(String toRepeat, int times) {
    if (toRepeat == null) {
        toRepeat = "";
    }

    if (times < 0) {
        times = 0;
    }

    final int length = toRepeat.length();
    final int total = length * times;
    final char[] src = toRepeat.toCharArray();
    char[] dst = new char[total];

    for (int i = 0; i < total; i += length) {
        System.arraycopy(src, 0, dst, i, length);
    }

    return String.copyValueOf(dst);
}

EDIT

and without loops you can try with:

public static String repeat2(String toRepeat, int times) {
    if (toRepeat == null) {
        toRepeat = "";
    }

    if (times < 0) {
        times = 0;
    }

    String[] copies = new String[times];
    Arrays.fill(copies, toRepeat);
    return Arrays.toString(copies).
              replace("[", "").
              replace("]", "").
              replaceAll(", ", "");
}

EDIT 2

using Collections is even shorter:

public static String repeat3(String toRepeat, int times) {
    return Collections.nCopies(times, toRepeat).
           toString().
           replace("[", "").
           replace("]", "").
           replaceAll(", ", "");
}

however I still like the first version.

How do I get the value of a textbox using jQuery?

Use the .val() method.

Also I think you meant to use $("#txtEmail") as $("txtEmail") returns elements of type <txtEmail> which you probably don't have.

See here at the jQuery documentation.

Also jQuery val() method.

How to run eclipse in clean mode? what happens if we do so?

Two ways to run eclipse in clean mode.

1 ) In Eclipse.ini file

  • Open the eclipse.ini file located in the Eclipse installation directory.
  • Add -clean first line in the file.
  • Save the file.
  • Restart Eclipse.

enter image description here

2 ) From Command prompt (cmd/command)

  • Go to folder where Eclipse installed.
  • Take the path of Eclipse
  • C:..\eclipse\eclipse.exe -clean
  • press enter button

enter image description here

Adding values to Arraylist

Well by doing the above you open yourself to run time errors, unless you are happy to accept that your arraylists can contains both strings and integers and elephants.

Eclipse returns an error because it does not want you to be unaware of the fact that by specifying no type for the generic parameter you are opening yourself up for run time errors. At least with the other two examples you know that you can have objects in your Arraylist and since Inetegers and Strings are both objects Eclipse doesn't warn you.

Either code 2 or 3 are ok. But if you know you will have either only ints or only strings in your arraylist then I would do

ArrayList<Integer> arr = new ArrayList<Integer>();

or

ArrayList<String> arr = new ArrayList<String>();

respectively.

Changing image sizes proportionally using CSS?

If you don't want to stretch the image, fit it into div container without overflow and center it by adjusting it's margin if needed.

  1. The image will not get cropped
  2. The aspect ratio will also remain the same.

HTML:

<div id="app">
    <div id="container">
      <img src="#" alt="something">
    </div>
    <div id="container">
      <img src="#" alt="something">
    </div>
    <div id="container">
      <img src="#" alt="something">
    </div>
</div>

CSS:

div#container {
    height: 200px;
    width: 200px;
    border: 1px solid black;
    margin: 4px;
}
img {
    max-width: 100%;
    max-height: 100%;
    display: block;
    margin: 0 auto;
}

How to display default text "--Select Team --" in combo box on pageload in WPF?

No one said a pure xaml solution has to be complicated. Here's a simple one, with 1 data trigger on the text box. Margin and position as desired

<Grid>
    <ComboBox x:Name="mybox" ItemsSource="{Binding}"/>
    <TextBlock Text="Select Something" IsHitTestVisible="False">
           <TextBlock.Style>
                <Style TargetType="TextBlock">
                      <Setter Property="Visibility" Value="Hidden"/>
                      <Style.Triggers>
                            <DataTrigger Binding="{Binding ElementName=mybox,Path=SelectedItem}" Value="{x:Null}">
                                  <Setter Property="Visibility" Value="Visible"/>
                             </DataTrigger>
                      </Style.Triggers>
                </Style>
           </TextBlock.Style>
     </TextBlock>
</Grid>

How can I parse a JSON file with PHP?

$json_a = json_decode($string, TRUE);
$json_o = json_decode($string);



foreach($json_a as $person => $value)
{
    foreach($value as $key => $personal)
    {
        echo $person. " with ".$key . " is ".$personal;
        echo "<br>";
    }

}

JavaScript error (Uncaught SyntaxError: Unexpected end of input)

I got this since I had a comment in a file I was adding to my JS, really awkward reason to what was going on - though when clicking on the VM file that's pre-rendered and catches the error, you'll find out what exactly the error was, in my case it was simply uncommenting some code I was using.

Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window

Use this code to return and reload the current window:

function printpost() {
  if (window.print()) {
    return false;
  } else {
    location.reload();
  }
}

Java Swing revalidate() vs repaint()

revalidate() just request to layout the container, when you experienced simply call revalidate() works, it could be caused by the updating of child components bounds triggers the repaint() when their bounds are changed during the re-layout. In the case you mentioned, only component removed and no component bounds are changed, this case no repaint() is "accidentally" triggered.

How can I create basic timestamps or dates? (Python 3.4)

>>> import time
>>> print(time.strftime('%a %H:%M:%S'))
Mon 06:23:14

MySql Query Replace NULL with Empty String in Select

The original form is nearly perfect, you just have to omit prereq after CASE:

SELECT
  CASE
    WHEN prereq IS NULL THEN ' '
    ELSE prereq
  END AS prereq
FROM test;

How to URL encode a string in Ruby

str = "\x12\x34\x56\x78\x9a\xbc\xde\xf1\x23\x45\x67\x89\xab\xcd\xef\x12\x34\x56\x78\x9a"
require 'cgi'
CGI.escape(str)
# => "%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vx%9A"

Taken from @J-Rou's comment

:not(:empty) CSS selector is not working?

Being a void element, an <input> element is considered empty by the HTML definition of "empty", since the content model of all void elements is always empty. So they will always match the :empty pseudo-class, whether or not they have a value. This is also why their value is represented by an attribute in the start tag, rather than text content within start and end tags.

Also, from the Selectors spec:

The :empty pseudo-class represents an element that has no children at all. In terms of the document tree, only element nodes and content nodes (such as DOM text nodes, CDATA nodes, and entity references) whose data has a non-zero length must be considered as affecting emptiness;

Consequently, input:not(:empty) will never match anything in a proper HTML document. (It would still work in a hypothetical XML document that defines an <input> element that can accept text or child elements.)

I don't think you can style empty <input> fields dynamically using just CSS (i.e. rules that apply whenever a field is empty, and don't once text is entered). You can select initially empty fields if they have an empty value attribute (input[value=""]) or lack the attribute altogether (input:not([value])), but that's about it.

Merge two dataframes by index

This answer has been resolved for a while and all the available options are already out there. However in this answer I'll attempt to shed a bit more light on these options to help you understand when to use what.

This post will go through the following topics:

  • Merging with index under different conditions
    • options for index-based joins: merge, join, concat
    • merging on indexes
    • merging on index of one, column of other
  • effectively using named indexes to simplify merging syntax


Index-based joins

TL;DR

There are a few options, some simpler than others depending on the use case.

  1. DataFrame.merge with left_index and right_index (or left_on and right_on using named indexes)
  2. DataFrame.join (joins on index)
  3. pd.concat (joins on index)
PROS CONS
merge

• supports inner/left/right/full
• supports column-column, index-column, index-index joins

• can only join two frames at a time

join

• supports inner/left (default)/right/full
• can join multiple DataFrames at a time

• only supports index-index joins

concat

• specializes in joining multiple DataFrames at a time
• very fast (concatenation is linear time)

• only supports inner/full (default) joins
• only supports index-index joins


Index to index joins

Typically, an inner join on index would look like this:

left.merge(right, left_index=True, right_index=True)

Other types of joins (left, right, outer) follow similar syntax (and can be controlled using how=...).

Notable Alternatives

  1. DataFrame.join defaults to a left outer join on the index.

     left.join(right, how='inner',)
    

    If you happen to get ValueError: columns overlap but no suffix specified, you will need to specify lsuffix and rsuffix= arguments to resolve this. Since the column names are same, a differentiating suffix is required.

  2. pd.concat joins on the index and can join two or more DataFrames at once. It does a full outer join by default.

     pd.concat([left, right], axis=1, sort=False)
    

    For more information on concat, see this post.


Index to Column joins

To perform an inner join using index of left, column of right, you will use DataFrame.merge a combination of left_index=True and right_on=....

left.merge(right, left_index=True, right_on='key')

Other joins follow a similar structure. Note that only merge can perform index to column joins. You can join on multiple levels/columns, provided the number of index levels on the left equals the number of columns on the right.

join and concat are not capable of mixed merges. You will need to set the index as a pre-step using DataFrame.set_index.


This post is an abridged version of my work in Pandas Merging 101. Please follow this link for more examples and other topics on merging.

What is event bubbling and capturing?

Bubbling

  Event propagate to the upto root element is **BUBBLING**.

Capturing

  Event propagate from body(root) element to eventTriggered Element is **CAPTURING**.

Onclick event to remove default value in a text input field

<input name="Name" value="Enter Your Name" onfocus="freez(this)" onblur="freez(this)">


function freez(obj)
{
 if(obj.value=='')
 {
   obj.value='Enter Your Name';
 }else if(obj.value=='Enter Your Name')
 {
   obj.value='';
 }
} 

How to display loading message when an iFrame is loading?

$('iframe').load(function(){
      $(".loading").remove();
    alert("iframe is done loading")
}).show();


<iframe src="http://www.google.com" style="display:none;" width="600" height="300"/>
<div class="loading" style="width:600px;height:300px;">iframe loading</div>

Clang vs GCC - which produces faster binaries?

The only way to determine this is to try it. FWIW I have seen some really good improvements using Apple's LLVM gcc 4.2 compared to the regular gcc 4.2 (for x86-64 code with quite a lot of SSE), but YMMV for different code bases. Assuming you're working with x86/x86-64 and that you really do care about the last few percent then you ought to try Intel's ICC too, as this can often beat gcc - you can get a 30 day evaluation license from intel.com and try it.

Change border-bottom color using jquery?

If you have this in your CSS file:

.myApp
{
    border-bottom-color:#FF0000;
}

and a div for instance of:

<div id="myDiv">test text</div>

you can use:

$("#myDiv").addClass('myApp');// to add the style

$("#myDiv").removeClass('myApp');// to remove the style

or you can just use

$("#myDiv").css( 'border-bottom-color','#FF0000');

I prefer the first example, keeping all the CSS related items in the CSS files.

How to get cookie's expire time

To get cookies expire time, use this simple method.

<?php

//#############PART 1#############
//expiration time (a*b*c*d) <- change D corresponding to number of days for cookie expiration
$time = time()+(60*60*24*365);
$timeMemo = (string)$time;

//sets cookie with expiration time defined above
setcookie("testCookie", "" . $timeMemo . "", $time);

//#############PART 2#############
//this function will convert seconds to days.
function secToDays($sec){

    return ($sec / 60 / 60 / 24);

}
//checks if cookie is set and prints out expiration time in days
if(isset($_COOKIE['testCookie'])){

    echo "Cookie is set<br />";
    if(round(secToDays((intval($_COOKIE['testCookie']) - time())),1) < 1){
        echo "Cookie will expire today.";
    }else{
        echo "Cookie will expire in " . round(secToDays((intval($_COOKIE['testCookie']) - time())),1) . " day(s)";
    }

}else{
    echo "not set...";
}

?>

You need to keep Part 1 and Part 2 in different files, otherwise you will get the same expire date everytime.

What are the differences between "git commit" and "git push"?

Since git is a distributed version control system, the difference is that commit will commit changes to your local repository, whereas push will push changes up to a remote repo.

Parsing arguments to a Java command line program

Use the Apache Commons CLI library commandline.getArgs() to get arg1, arg2, arg3, and arg4. Here is some code:



    import org.apache.commons.cli.CommandLine;
    import org.apache.commons.cli.Option;
    import org.apache.commons.cli.Options;
    import org.apache.commons.cli.Option.Builder;
    import org.apache.commons.cli.CommandLineParser;
    import org.apache.commons.cli.DefaultParser;
    import org.apache.commons.cli.ParseException;

    public static void main(String[] parameters)
    {
        CommandLine commandLine;
        Option option_A = Option.builder("A")
            .required(true)
            .desc("The A option")
            .longOpt("opt3")
            .build();
        Option option_r = Option.builder("r")
            .required(true)
            .desc("The r option")
            .longOpt("opt1")
            .build();
        Option option_S = Option.builder("S")
            .required(true)
            .desc("The S option")
            .longOpt("opt2")
            .build();
        Option option_test = Option.builder()
            .required(true)
            .desc("The test option")
            .longOpt("test")
            .build();
        Options options = new Options();
        CommandLineParser parser = new DefaultParser();

        String[] testArgs =
        { "-r", "opt1", "-S", "opt2", "arg1", "arg2",
          "arg3", "arg4", "--test", "-A", "opt3", };

        options.addOption(option_A);
        options.addOption(option_r);
        options.addOption(option_S);
        options.addOption(option_test);

        try
        {
            commandLine = parser.parse(options, testArgs);

            if (commandLine.hasOption("A"))
            {
                System.out.print("Option A is present.  The value is: ");
                System.out.println(commandLine.getOptionValue("A"));
            }

            if (commandLine.hasOption("r"))
            {
                System.out.print("Option r is present.  The value is: ");
                System.out.println(commandLine.getOptionValue("r"));
            }

            if (commandLine.hasOption("S"))
            {
                System.out.print("Option S is present.  The value is: ");
                System.out.println(commandLine.getOptionValue("S"));
            }

            if (commandLine.hasOption("test"))
            {
                System.out.println("Option test is present.  This is a flag option.");
            }

            {
                String[] remainder = commandLine.getArgs();
                System.out.print("Remaining arguments: ");
                for (String argument : remainder)
                {
                    System.out.print(argument);
                    System.out.print(" ");
                }

                System.out.println();
            }

        }
        catch (ParseException exception)
        {
            System.out.print("Parse error: ");
            System.out.println(exception.getMessage());
        }
    }

Fatal error: "No Target Architecture" in Visual Studio

If you are building 32bit then make sure you don't have _WIN64 defined for your project.

MySQL - How to increase varchar size of an existing column in a database without breaking existing data?

I'd like explain the different alter table syntaxes - See the MySQL documentation

For adding/removing defaults on a column:

ALTER TABLE table_name
ALTER COLUMN col_name {SET DEFAULT literal | DROP DEFAULT}

For renaming a column, changing it's data type and optionally changing the column order:

ALTER TABLE table_name
CHANGE [COLUMN] old_col_name new_col_name column_definition
[FIRST|AFTER col_name]

For changing a column's data type and optionally changing the column order:

ALTER TABLE table_name
MODIFY [COLUMN] col_name column_definition
[FIRST | AFTER col_name]

How do I find the version of Apache running without access to the command line?

Warning, some Apache servers do not always send their version number when using HEAD, like in this case:

HTTP/1.1 200 OK
Date: Fri, 03 Oct 2008 13:09:45 GMT
Server: Apache
X-Powered-By: PHP/5.2.6RC4-pl0-gentoo
Set-Cookie: PHPSESSID=a97a60f86539b5502ad1109f6759585c; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Connection: close
Content-Type: text/html



Connection to host lost.

If PHP is installed then indeed, just use the php info command:

<?php phpinfo(); ?>

How to create a dotted <hr/> tag?

You can do:

<hr style="border-bottom: dotted 1px #000" />

Getting the exception value in Python

If you don't know the type/origin of the error, you can try:

import sys
try:
    doSomethingWrongHere()
except:
    print('Error: {}'.format(sys.exc_info()[0]))

But be aware, you'll get pep8 warning:

[W] PEP 8 (E722): do not use bare except

Selenium webdriver click google search

Based on quick inspection of google web, this would be CSS path to links in page list

ol[id="rso"] h3[class="r"] a

So you should do something like

String path = "ol[id='rso'] h3[class='r'] a";
driver.findElements(By.cssSelector(path)).get(2).click();

However you could also use xpath which is not really recommended as a best practice and also JQuery locators but I am not sure if you can use them aynywhere else except inArquillian Graphene

curl_exec() always returns false

Error checking and handling is the programmer's friend. Check the return values of the initializing and executing cURL functions. curl_error() and curl_errno() will contain further information in case of failure:

try {
    $ch = curl_init();

    // Check if initialization had gone wrong*    
    if ($ch === false) {
        throw new Exception('failed to initialize');
    }

    curl_setopt($ch, CURLOPT_URL, 'http://example.com/');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt(/* ... */);

    $content = curl_exec($ch);

    // Check the return value of curl_exec(), too
    if ($content === false) {
        throw new Exception(curl_error($ch), curl_errno($ch));
    }

    /* Process $content here */

    // Close curl handle
    curl_close($ch);
} catch(Exception $e) {

    trigger_error(sprintf(
        'Curl failed with error #%d: %s',
        $e->getCode(), $e->getMessage()),
        E_USER_ERROR);

}

* The curl_init() manual states:

Returns a cURL handle on success, FALSE on errors.

I've observed the function to return FALSE when you're using its $url parameter and the domain could not be resolved. If the parameter is unused, the function might never return FALSE. Always check it anyways, though, since the manual doesn't clearly state what "errors" actually are.

How to call getResources() from a class which has no context?

The normal solution to this is to pass an instance of the context to the class as you create it, or after it is first created but before you need to use the context.

Another solution is to create an Application object with a static method to access the application context although that couples the Droid object fairly tightly into the code.

Edit, examples added

Either modify the Droid class to be something like this

 public Droid(Context context,int x, int y) {
    this.bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.birdpic);
    this.x = x;
    this.y = y;
    }   

Or create an Application something like this:

public class App extends android.app.Application
{
    private static App mApp = null;
    /* (non-Javadoc)
     * @see android.app.Application#onCreate()
     */
    @Override
    public void onCreate()
    {
        super.onCreate();
        mApp = this;
    }
    public static Context context()
    {
        return mApp.getApplicationContext();
    }
}

And call App.context() wherever you need a context - note however that not all functions are available on an application context, some are only available on an activity context but it will certainly do with your need for getResources().

Please note that you'll need to add android:name to your application definition in your manifest, something like this:

<application
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:name=".App" >

using setTimeout on promise chain

To keep the promise chain going, you can't use setTimeout() the way you did because you aren't returning a promise from the .then() handler - you're returning it from the setTimeout() callback which does you no good.

Instead, you can make a simple little delay function like this:

function delay(t, v) {
   return new Promise(function(resolve) { 
       setTimeout(resolve.bind(null, v), t)
   });
}

And, then use it like this:

getLinks('links.txt').then(function(links){
    let all_links = (JSON.parse(links));
    globalObj=all_links;

    return getLinks(globalObj["one"]+".txt");

}).then(function(topic){
    writeToBody(topic);
    // return a promise here that will be chained to prior promise
    return delay(1000).then(function() {
        return getLinks(globalObj["two"]+".txt");
    });
});

Here you're returning a promise from the .then() handler and thus it is chained appropriately.


You can also add a delay method to the Promise object and then directly use a .delay(x) method on your promises like this:

_x000D_
_x000D_
function delay(t, v) {_x000D_
   return new Promise(function(resolve) { _x000D_
       setTimeout(resolve.bind(null, v), t)_x000D_
   });_x000D_
}_x000D_
_x000D_
Promise.prototype.delay = function(t) {_x000D_
    return this.then(function(v) {_x000D_
        return delay(t, v);_x000D_
    });_x000D_
}_x000D_
_x000D_
_x000D_
Promise.resolve("hello").delay(500).then(function(v) {_x000D_
    console.log(v);_x000D_
});
_x000D_
_x000D_
_x000D_

Or, use the Bluebird promise library which already has the .delay() method built-in.

Angular ng-repeat add bootstrap row every 3 or 4 cols

The best way to apply a class is to use ng-class.It can be used to apply classes based on some condition.

<div ng-repeat="product in products">
   <div ng-class="getRowClass($index)">
       <div class="col-sm-4" >
           <!-- your code -->
       </div>
   </div>

and then in your controller

$scope.getRowClass = function(index){
    if(index%3 == 0){
     return "row";
    }
}

What is the difference between method overloading and overriding?

Method overriding is when a child class redefines the same method as a parent class, with the same parameters. For example, the standard Java class java.util.LinkedHashSet extends java.util.HashSet. The method add() is overridden in LinkedHashSet. If you have a variable that is of type HashSet, and you call its add() method, it will call the appropriate implementation of add(), based on whether it is a HashSet or a LinkedHashSet. This is called polymorphism.

Method overloading is defining several methods in the same class, that accept different numbers and types of parameters. In this case, the actual method called is decided at compile-time, based on the number and types of arguments. For instance, the method System.out.println() is overloaded, so that you can pass ints as well as Strings, and it will call a different version of the method.

How to run a Runnable thread in Android at defined intervals?

Kotlin

private lateinit var runnable: Runnable
override fun onCreate(savedInstanceState: Bundle?) {
    val handler = Handler()
    runnable = Runnable {
        // do your work
        handler.postDelayed(runnable, 2000)
    }
    handler.postDelayed(runnable, 2000)
}

Java

Runnable runnable;
Handler handler;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    handler = new Handler();
    runnable = new Runnable() {
        @Override
        public void run() {
            // do your work
            handler.postDelayed(this, 1000);
        }
    };
    handler.postDelayed(runnable, 1000);
}

SELECT max(x) is returning null; how can I make it return 0?

or:

SELECT coalesce(MAX(X), 0) AS MaxX
FROM tbl
WHERE XID = 1

Getting the last argument passed to a shell script

After reading the answers above I wrote a Q&D shell script (should work on sh and bash) to run g++ on PGM.cpp to produce executable image PGM. It assumes that the last argument on the command line is the file name (.cpp is optional) and all other arguments are options.

#!/bin/sh
if [ $# -lt 1 ]
then
    echo "Usage: `basename $0` [opt] pgm runs g++ to compile pgm[.cpp] into pgm"
    exit 2
fi
OPT=
PGM=
# PGM is the last argument, all others are considered options
for F; do OPT="$OPT $PGM"; PGM=$F; done
DIR=`dirname $PGM`
PGM=`basename $PGM .cpp`
# put -o first so it can be overridden by -o specified in OPT
set -x
g++ -o $DIR/$PGM $OPT $DIR/$PGM.cpp

Stretch Image to Fit 100% of Div Height and Width

will the height attribute stretch the image beyond its native resolution? If I have a image with a height of say 420 pixels, I can't get css to stretch the image beyond the native resolution to fill the height of the viewport.

I am getting pretty close results with:

 .rightdiv img {
        max-width: 25vw;
        min-height: 100vh;
    }

the 100vh is getting pretty close, with just a few pixels left over at the bottom for some reason.

Convert named list to vector with values only

This can be done by using unlist before as.vector. The result is the same as using the parameter use.names=FALSE.

as.vector(unlist(myList))

What is a lambda expression in C++11?

What is a lambda function?

The C++ concept of a lambda function originates in the lambda calculus and functional programming. A lambda is an unnamed function that is useful (in actual programming, not theory) for short snippets of code that are impossible to reuse and are not worth naming.

In C++ a lambda function is defined like this

[]() { } // barebone lambda

or in all its glory

[]() mutable -> T { } // T is the return type, still lacking throw()

[] is the capture list, () the argument list and {} the function body.

The capture list

The capture list defines what from the outside of the lambda should be available inside the function body and how. It can be either:

  1. a value: [x]
  2. a reference [&x]
  3. any variable currently in scope by reference [&]
  4. same as 3, but by value [=]

You can mix any of the above in a comma separated list [x, &y].

The argument list

The argument list is the same as in any other C++ function.

The function body

The code that will be executed when the lambda is actually called.

Return type deduction

If a lambda has only one return statement, the return type can be omitted and has the implicit type of decltype(return_statement).

Mutable

If a lambda is marked mutable (e.g. []() mutable { }) it is allowed to mutate the values that have been captured by value.

Use cases

The library defined by the ISO standard benefits heavily from lambdas and raises the usability several bars as now users don't have to clutter their code with small functors in some accessible scope.

C++14

In C++14 lambdas have been extended by various proposals.

Initialized Lambda Captures

An element of the capture list can now be initialized with =. This allows renaming of variables and to capture by moving. An example taken from the standard:

int x = 4;
auto y = [&r = x, x = x+1]()->int {
            r += 2;
            return x+2;
         }();  // Updates ::x to 6, and initializes y to 7.

and one taken from Wikipedia showing how to capture with std::move:

auto ptr = std::make_unique<int>(10); // See below for std::make_unique
auto lambda = [ptr = std::move(ptr)] {return *ptr;};

Generic Lambdas

Lambdas can now be generic (auto would be equivalent to T here if T were a type template argument somewhere in the surrounding scope):

auto lambda = [](auto x, auto y) {return x + y;};

Improved Return Type Deduction

C++14 allows deduced return types for every function and does not restrict it to functions of the form return expression;. This is also extended to lambdas.

C# ASP.NET MVC Return to Previous Page

I know this is very late, but maybe this will help someone else.

I use a Cancel button to return to the referring url. In the View, try adding this:

@{
  ViewBag.Title = "Page title";
  Layout = "~/Views/Shared/_Layout.cshtml";

  if (Request.UrlReferrer != null)
  {
    string returnURL = Request.UrlReferrer.ToString();
    ViewBag.ReturnURL = returnURL;
  }
}

Then you can set your buttons href like this:

<a href="@ViewBag.ReturnURL" class="btn btn-danger">Cancel</a>

Other than that, the update by Jason Enochs works great!

Resize UIImage and change the size of UIImageView

Use the category below and then apply border from Quartz into your image:

[yourimage.layer setBorderColor:[[UIColor whiteColor] CGColor]];
[yourimage.layer setBorderWidth:2];

The category: UIImage+AutoScaleResize.h

#import <Foundation/Foundation.h>

@interface UIImage (AutoScaleResize)

- (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize;

@end

UIImage+AutoScaleResize.m

#import "UIImage+AutoScaleResize.h"

@implementation UIImage (AutoScaleResize)

- (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize
{
    UIImage *sourceImage = self;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;

        if (widthFactor > heightFactor)
        {
            scaleFactor = widthFactor; // scale to fit height
        }
        else
        {
            scaleFactor = heightFactor; // scale to fit width
        }

        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;

        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
        {
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
        }
    }

    UIGraphicsBeginImageContext(targetSize); // this will crop

    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;

    [sourceImage drawInRect:thumbnailRect];

    newImage = UIGraphicsGetImageFromCurrentImageContext();

    if(newImage == nil)
    {
        NSLog(@"could not scale image");
    }

    //pop the context to get back to the default
    UIGraphicsEndImageContext();

    return newImage;
}

@end

How to install toolbox for MATLAB

There are many toolboxes. Since you mentioned one that is commercially available from MathWorks, I assume you mean how do you get a trial/license

http://www.mathworks.com/products/image/

There is a link for trials, purchase, demos. This will get you in touch with your sales representative. If you know your sales representative, you could just call to get attention faster.


If you mean just a general toolbox that is from a source other than MathWorks, I would check with the producer, as it will vary widely from "Put it on your path." to whatever their purchase and licensing procedure is.

Unable to merge dex

I had same problem. I just enabled Instant Run(It was disabled) then my project worked. You can find it in-

File->Settings-> Build,Execution,Deployment->Instant Run

In Android studio 3.5 Instant Run have been removed. Please see here for reference

httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

Your hosts file does not include a valid FQDN, nor is localhost an FQDN. An FQDN must include a hostname part, as well as a domain name part. For example, the following is a valid FQDN:

host.server4-245.com

Choose an FQDN and include it both in your /etc/hosts file on both the IPv4 and IPv6 addresses you are using (in your case, localhost or 127.0.0.1), and change your ServerName in your httpd configuration to match.

/etc/hosts:

127.0.0.1    localhost.localdomain localhost host.server4-245.com
::1          localhost.localdomain localhost host.server4-245.com

httpd.conf:

ServerName host.server4-245.com

How to prevent page from reloading after form submit - JQuery

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">

And then in your JS:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

How to make inline plots in Jupyter Notebook larger?

using something like:

import matplotlib.pyplot as plt
%matplotlib inline
plt.subplots(figsize=(18,8 ))
plt.subplot(1,3,1)
plt.subplot(1,3,2)
plt.subplot(1,3,3)

The output of the command

the output of the command

java SSL and cert keystore

SSL properties are set at the JVM level via system properties. Meaning you can either set them when you run the program (java -D....) Or you can set them in code by doing System.setProperty.

The specific keys you have to set are below:

javax.net.ssl.keyStore- Location of the Java keystore file containing an application process's own certificate and private key. On Windows, the specified pathname must use forward slashes, /, in place of backslashes.

javax.net.ssl.keyStorePassword - Password to access the private key from the keystore file specified by javax.net.ssl.keyStore. This password is used twice: To unlock the keystore file (store password), and To decrypt the private key stored in the keystore (key password).

javax.net.ssl.trustStore - Location of the Java keystore file containing the collection of CA certificates trusted by this application process (trust store). On Windows, the specified pathname must use forward slashes, /, in place of backslashes, \.

If a trust store location is not specified using this property, the SunJSSE implementation searches for and uses a keystore file in the following locations (in order):

  1. $JAVA_HOME/lib/security/jssecacerts
  2. $JAVA_HOME/lib/security/cacerts

javax.net.ssl.trustStorePassword - Password to unlock the keystore file (store password) specified by javax.net.ssl.trustStore.

javax.net.ssl.trustStoreType - (Optional) For Java keystore file format, this property has the value jks (or JKS). You do not normally specify this property, because its default value is already jks.

javax.net.debug - To switch on logging for the SSL/TLS layer, set this property to ssl.

Base64 String throwing invalid character error

Whether null char is allowed or not really depends on base64 codec in question. Given vagueness of Base64 standard (there is no authoritative exact specification), many implementations would just ignore it as white space. And then others can flag it as a problem. And buggiest ones wouldn't notice and would happily try decoding it... :-/

But it sounds c# implementation does not like it (which is one valid approach) so if removing it helps, that should be done.

One minor additional comment: UTF-8 is not a requirement, ISO-8859-x aka Latin-x, and 7-bit Ascii would work as well. This because Base64 was specifically designed to only use 7-bit subset which works with all 7-bit ascii compatible encodings.

Iterate a certain number of times without storing the iteration number anywhere

The idiom (shared by quite a few other languages) for an unused variable is a single underscore _. Code analysers typically won't complain about _ being unused, and programmers will instantly know it's a shortcut for i_dont_care_wtf_you_put_here. There is no way to iterate without having an item variable - as the Zen of Python puts it, "special cases aren't special enough to break the rules".

Check if not nil and not empty in Rails shortcut?

You can use .present? which comes included with ActiveSupport.

@city = @user.city.present?
# etc ...

You could even write it like this

def show
  %w(city state bio contact twitter mail).each do |attr|
    instance_variable_set "@#{attr}", @user[attr].present?
  end
end

It's worth noting that if you want to test if something is blank, you can use .blank? (this is the opposite of .present?)

Also, don't use foo == nil. Use foo.nil? instead.

How to redirect output of systemd service to a file

If for a some reason can't use rsyslog, this will do: ExecStart=/bin/bash -ce "exec /usr/local/bin/binary1 agent -config-dir /etc/sample.d/server >> /var/log/agent.log 2>&1"

docker build with --build-arg with multiple arguments

If you want to use environment variable during build. Lets say setting username and password.

username= Ubuntu
password= swed24sw

Dockerfile

FROM ubuntu:16.04
ARG SMB_PASS
ARG SMB_USER
# Creates a new User
RUN useradd -ms /bin/bash $SMB_USER
# Enters the password twice.
RUN echo "$SMB_PASS\n$SMB_PASS" | smbpasswd -a $SMB_USER

Terminal Command

docker build --build-arg SMB_PASS=swed24sw --build-arg SMB_USER=Ubuntu . -t IMAGE_TAG

Alert after page load

Why can't you use it in MVC?

Rather than using the body load method use jQuery and wait for the the document onready function to complete.

Java ArrayList - Check if list is empty

Source: CodeSpeedy Click to know more Check if an ArrayList is empty or not

import java.util.ArrayList;
public class arraycheck {
public static void main(String args[]){
ArrayList<Integer> list=new ArrayList<Integer>();

    if(list.size()==0){
        System.out.println("Its Empty");

    }
    else
        System.out.println("Not Empty");

   }

}

Output:

run:
Its Empty
BUILD SUCCESSFUL (total time: 0 seconds)

Register comdlg32.dll gets Regsvr32: DllRegisterServer entry point was not found

Information about missing entry point error installing legacy VB6 compiled applications on Windows 10 which I hope could be useful to someone.

Missing OCX files can be found in the "OS\System folder" of the Visual Basic 6.0 installer package. Today I copied the relevant OCX file (from our network) to the local computer

And then I typed the commands below, as administrator, which normally work to register it.

cd \windows\syswow64
regsvr32.exe /u mscomctl.ocx
regsvr32.exe /i mscomctl.ocx

(add the path to the locally copied file for the /i command)

However today I got errors from both these regsvr32.exe commands.

The second error was giving the DllImport missing entry point error which is similar to the error mentioned by the original poster.

To resolve, one of the things I tried was leaving out the switch -

regsvr32.exe mscomctl.ocx

To my surprise it then said it was successful. To confirm, the application started up properly afterwards.

iOS8 Beta Ad-Hoc App Download (itms-services)

Specify a 'display-image' and 'full-size-image' as described here: http://www.informit.com/articles/article.aspx?p=1829415&seqNum=16

iOS8 requires these images

Arrays in unix shell?

An array can be loaded in twoways.

set -A TEST_ARRAY alpha beta gamma

or

X=0 # Initialize counter to zero.

-- Load the array with the strings alpha, beta, and gamma

for ELEMENT in alpha gamma beta
do
    TEST_ARRAY[$X]=$ELEMENT
    ((X = X + 1))
done

Also, I think below information may help:

The shell supports one-dimensional arrays. The maximum number of array elements is 1,024. When an array is defined, it is automatically dimensioned to 1,024 elements. A one-dimensional array contains a sequence of array elements, which are like the boxcars connected together on a train track.

In case you want to access the array:

echo ${MY_ARRAY[2] # Show the third array element
 gamma 


echo ${MY_ARRAY[*] # Show all array elements
-   alpha beta gamma


echo ${MY_ARRAY[@] # Show all array elements
 -  alpha beta gamma


echo ${#MY_ARRAY[*]} # Show the total number of array elements
-   3


echo ${#MY_ARRAY[@]} # Show the total number of array elements
-   3

echo ${MY_ARRAY} # Show array element 0 (the first element)
-  alpha

Prevent row names to be written to file when using write.csv

For completeness, write_csv() from the readr package is faster and never writes row names

# install.packages('readr', dependencies = TRUE)
library(readr)
write_csv(t, "t.csv")

If you need to write big data out, use fwrite() from the data.table package. It's much faster than both write.csv and write_csv

# install.packages('data.table')
library(data.table)
fwrite(t, "t.csv")

Below is a benchmark that Edouard published on his site

microbenchmark(write.csv(data, "baseR_file.csv", row.names = F),
               write_csv(data, "readr_file.csv"),
               fwrite(data, "datatable_file.csv"),
               times = 10, unit = "s")

## Unit: seconds
##                                              expr        min         lq       mean     median         uq        max neval
##  write.csv(data, "baseR_file.csv", row.names = F) 13.8066424 13.8248250 13.9118324 13.8776993 13.9269675 14.3241311    10
##                 write_csv(data, "readr_file.csv")  3.6742610  3.7999409  3.8572456  3.8690681  3.8991995  4.0637453    10
##                fwrite(data, "datatable_file.csv")  0.3976728  0.4014872  0.4097876  0.4061506  0.4159007  0.4355469    10

How to match a substring in a string, ignoring case

import re
if re.search('(?i)Mandy Pande:', line):
    ...

How to create a Restful web service with input parameters?

You can. Try something like this:

@Path("/todo/{varX}/{varY}")
@Produces({"application/xml", "application/json"})
public Todo whatEverNameYouLike(@PathParam("varX") String varX,
    @PathParam("varY") String varY) {
        Todo todo = new Todo();
        todo.setSummary(varX);
        todo.setDescription(varY);
        return todo;
}

Then call your service with this URL;
http://localhost:8088/JerseyJAXB/rest/todo/summary/description

SSL InsecurePlatform error when using Requests package

Use the somewhat hidden security feature:

pip install requests[security] or pip install pyOpenSSL ndg-httpsclient pyasn1

Both commands install following extra packages:

  • pyOpenSSL
  • cryptography
  • idna

Please note that this is not required for python-2.7.9+.

If pip install fails with errors, check whether you have required development packages for libffi, libssl and python installed in your system using distribution's package manager:

  • Debian/Ubuntu - python-dev libffi-dev libssl-dev packages.

  • Fedora - openssl-devel python-devel libffi-devel packages.

Distro list above is incomplete.

Workaround (see the original answer by @TomDotTom):

In case you cannot install some of the required development packages, there's also an option to disable that warning:

import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()

If your pip itself is affected by InsecurePlatformWarning and cannot install anything from PyPI, it can be fixed with this step-by-step guide to deploy extra python packages manually.

How to detect window.print() finish

Implementing window.onbeforeprint and window.onafterprint

The window.close() call after the window.print() is not working in Chrome v 78.0.3904.70

To approach this I'm using Adam's answer with a simple modification:

     function print() {
    (function () {
       let afterPrintCounter = !!window.chrome ? 0 : 1;
       let beforePrintCounter = !!window.chrome ? 0 : 1;
       var beforePrint = function () {
          beforePrintCounter++;
          if (beforePrintCounter === 2) {
             console.log('Functionality to run before printing.');
          }
       };
       var afterPrint = function () {
          afterPrintCounter++;
          if (afterPrintCounter === 2) {
             console.log('Functionality to run after printing.');
             //window.close();
          }
       };
       if (window.matchMedia) {
          var mediaQueryList = window.matchMedia('print');
          mediaQueryList.addListener(function (mql) {
             if (mql.matches) {
                beforePrint();
             } else {
                afterPrint();
             }
          });
       }
       window.onbeforeprint = beforePrint;
       window.onafterprint = afterPrint;
    }());
    //window.print(); //To print the page when it is loaded
 }

I'm calling it in here:

<body onload="print();">

This works for me. Note that I use a counter for both functions, so that I can handle this event in different browsers (fires twice in Chrome, and one time in Mozilla). For detecting the browser you can refer to this answer

Invoke-customs are only supported starting with android 0 --min-api 26

If you have Java 7 so include the below following snippet within your app-level build.gradle :

compileOptions {

    sourceCompatibility JavaVersion.VERSION_1_7
    targetCompatibility JavaVersion.VERSION_1_7

}

R memory management / cannot allocate vector of size n Mb

I encountered a similar problem, and I used 2 flash drives as 'ReadyBoost'. The two drives gave additional 8GB boost of memory (for cache) and it solved the problem and also increased the speed of the system as a whole. To use Readyboost, right click on the drive, go to properties and select 'ReadyBoost' and select 'use this device' radio button and click apply or ok to configure.

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

For Android Developers,

Make sure you have enabled Facebook Login inside the Products list inside Dashboard of your Facebook project app and have added all the required details as you go through the whole flow.

The login should work without giving the same error.

How to convert an object to a byte array in C#

Take a look at Serialization, a technique to "convert" an entire object to a byte stream. You may send it to the network or write it into a file and then restore it back to an object later.

Calling a Fragment method from a parent Activity

FragmentManager fm = getFragmentManager(); 
MainFragment frag = (MainFragment)fm.findFragmentById(R.id.main_fragment); 
frag.<specific_function_name>(); 

spacing between form fields

I would wrap your rows in labels

<form action="doit" id="doit" method="post">
    <label>
        Name
        <input id="name" name="name" type="text" />
    </label>
    <label>
        Phone number
        <input id="phone" name="phone" type="text" />
    </label>
    <label>
        Year
        <input id="year" name="year" type="text" />
    </label>
</form>

And use

label, input {
    display: block;
}

label {
    margin-bottom: 20px;
}

Don't use brs for spacing!

Demo: http://jsfiddle.net/D8W2Q/

Python: Number of rows affected by cursor.execute("SELECT ...)

To get the number of selected rows I usually use the following:

cursor.execute(sql)
count = (len(cursor.fetchall))

Uninstalling Android ADT

If running on windows vista or later,
remember to run eclipse under a user with proper file permissions.
try to use the 'Run as Administrator' option.

How to generate a random String in Java

Many possibilities...

You know how to generate randomly an integer right? You can thus generate a char from it... (ex 65 -> A)

It depends what you need, the level of randomness, the security involved... but for a school project i guess getting UUID substring would fit :)

Convert JSON string to dict using Python

If you trust the data source, you can use eval to convert your string into a dictionary:

eval(your_json_format_string)

Example:

>>> x = "{'a' : 1, 'b' : True, 'c' : 'C'}"
>>> y = eval(x)

>>> print x
{'a' : 1, 'b' : True, 'c' : 'C'}
>>> print y
{'a': 1, 'c': 'C', 'b': True}

>>> print type(x), type(y)
<type 'str'> <type 'dict'>

>>> print y['a'], type(y['a'])
1 <type 'int'>

>>> print y['a'], type(y['b'])
1 <type 'bool'>

>>> print y['a'], type(y['c'])
1 <type 'str'>

Object of class stdClass could not be converted to string

I use codeignator and I got the error:

Object of class stdClass could not be converted to string.

for this post I get my result

I use in my model section

$query = $this->db->get('user', 10);
        return $query->result();

and from this post I use

$query = $this->db->get('user', 10);
        return $query->row();

and I solved my problem

RunAs A different user when debugging in Visual Studio

cmd.exe is located in different locations in different versions of Windows. To avoid needing the location of cmd.exe, you can use the command moogs wrote without calling "cmd.exe /C".

Here's an example that worked for me:

  1. Open Command Prompt
  2. Change directory to where your application's .exe file is located.
  3. Execute the following command: runas /user:domain\username Application.exe

So the final step will look something like this in Command Prompt:

C:\Projects\MyProject\bin\Debug>runas /user:domain\username Application.exe

Note: the domain name was required in my situation.

Convert String to Carbon

You were almost there.

Remove protected $dates = ['license_expire']

and then change your LicenseExpire accessor to:

public function getLicenseExpireAttribute($date)
{
    return Carbon::parse($date);
}

This way it will return a Carbon instance no matter what. So for your form you would just have $employee->license_expire->format('Y-m-d') (or whatever format is required) and diffForHumans() should work on your home page as well.

Hope this helps!

How to check list A contains any value from list B?

I've profiled Justins two solutions. a.Any(a => b.Contains(a)) is fastest.

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

namespace AnswersOnSO
{
    public class Class1
    {
        public static void Main(string []args)
        {
//            How to check if list A contains any value from list B?
//            e.g. something like A.contains(a=>a.id = B.id)?
            var a = new List<int> {1,2,3,4};
            var b = new List<int> {2,5};
            var times = 10000000;

            DateTime dtAny = DateTime.Now;
            for (var i = 0; i < times; i++)
            {
                var aContainsBElements = a.Any(b.Contains);
            }
            var timeAny = (DateTime.Now - dtAny).TotalSeconds;

            DateTime dtIntersect = DateTime.Now;
            for (var i = 0; i < times; i++)
            {
                var aContainsBElements = a.Intersect(b).Any();
            }
            var timeIntersect = (DateTime.Now - dtIntersect).TotalSeconds;

            // timeAny: 1.1470656 secs
            // timeIn.: 3.1431798 secs
        }
    }
}

Raise an event whenever a property's value changed?

Raising an event when a property changes is precisely what INotifyPropertyChanged does. There's one required member to implement INotifyPropertyChanged and that is the PropertyChanged event. Anything you implemented yourself would probably be identical to that implementation, so there's no advantage to not using it.

Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

In your mysql config file, which is present in /etc/my.cnf make the below changes and then restart mysqld dameon process

[client]
socket=/var/lib/mysql/mysql.sock

As well check this related thread

Can't connect to local MySQL server through socket '/tmp/mysql.sock

How to create Java gradle project

Unfortunately you cannot do it in one command. There is an open issue for the very feature.

Currently you'll have to do it by hand. If you need to do it often, you can create a custom gradle plugin, or just prepare your own project skeleton and copy it when needed.

EDIT

The JIRA issue mentioned above has been resolved, as of May 1, 2013, and fixed in 1.7-rc-1. The documentation on the Build Init Plugin is available, although it indicates that this feature is still in the "incubating" lifecycle.

Calculate a Running Total in SQL Server

The following will produce the required results.

SELECT a.SomeDate,
       a.SomeValue,
       SUM(b.SomeValue) AS RunningTotal
FROM TestTable a
CROSS JOIN TestTable b
WHERE (b.SomeDate <= a.SomeDate) 
GROUP BY a.SomeDate,a.SomeValue
ORDER BY a.SomeDate,a.SomeValue

Having a clustered index on SomeDate will greatly improve the performance.

Remove category & tag base from WordPress url - without a plugin

The dot trick will likely ruin your rss feeds and/or pagination. These work, though:

add_filter('category_rewrite_rules', 'no_category_base_rewrite_rules');
function no_category_base_rewrite_rules($category_rewrite) {
    $category_rewrite=array();
    $categories=get_categories(array('hide_empty'=>false));
    foreach($categories as $category) {
        $category_nicename = $category->slug;
        if ( $category->parent == $category->cat_ID )
            $category->parent = 0;
        elseif ($category->parent != 0 )
            $category_nicename = get_category_parents( $category->parent, false, '/', true ) . $category_nicename;
        $category_rewrite['('.$category_nicename.')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
        $category_rewrite['('.$category_nicename.')/page/?([0-9]{1,})/?$'] = 'index.php?category_name=$matches[1]&paged=$matches[2]';
        $category_rewrite['('.$category_nicename.')/?$'] = 'index.php?category_name=$matches[1]';
    }
    global $wp_rewrite;
    $old_base = $wp_rewrite->get_category_permastruct();
    $old_base = str_replace( '%category%', '(.+)', $old_base );
    $old_base = trim($old_base, '/');
    $category_rewrite[$old_base.'$'] = 'index.php?category_redirect=$matches[1]';
    return $category_rewrite;
}

// remove tag base
add_filter('tag_rewrite_rules', 'no_tag_base_rewrite_rules');
function no_tag_base_rewrite_rules($tag_rewrite) {
    $tag_rewrite=array();
    $tags=get_tags(array('hide_empty'=>false));
    foreach($tags as $tag) {
        $tag_nicename = $tag->slug;
        if ( $tag->parent == $tag->tag_ID )
            $tag->parent = 0;
        elseif ($tag->parent != 0 )
            $tag_nicename = get_tag_parents( $tag->parent, false, '/', true ) . $tag_nicename;
        $tag_rewrite['('.$tag_nicename.')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?tag=$matches[1]&feed=$matches[2]';
        $tag_rewrite['('.$tag_nicename.')/page/?([0-9]{1,})/?$'] = 'index.php?tag=$matches[1]&paged=$matches[2]';
        $tag_rewrite['('.$tag_nicename.')/?$'] = 'index.php?tag=$matches[1]';
    }
    global $wp_rewrite;
    $old_base = $wp_rewrite->get_tag_permastruct();
    $old_base = str_replace( '%tag%', '(.+)', $old_base );
    $old_base = trim($old_base, '/');
    $tag_rewrite[$old_base.'$'] = 'index.php?tag_redirect=$matches[1]';
    return $tag_rewrite;
}

// remove author base
add_filter('author_rewrite_rules', 'no_author_base_rewrite_rules');
function no_author_base_rewrite_rules($author_rewrite) { 
    global $wpdb;    
    $author_rewrite = array();    
    $authors = $wpdb->get_results("SELECT user_nicename AS nicename from $wpdb->users");    
    foreach($authors as $author) {
        $author_rewrite["({$author->nicename})/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$"] = 'index.php?author_name=$matches[1]&feed=$matches[2]';
        $author_rewrite["({$author->nicename})/page/?([0-9]+)/?$"] = 'index.php?author_name=$matches[1]&paged=$matches[2]';
        $author_rewrite["({$author->nicename})/?$"] = 'index.php?author_name=$matches[1]';
    }      
    return $author_rewrite;}
add_filter('author_link', 'no_author_base', 1000, 2);
function no_author_base($link, $author_id) {
    $link_base = trailingslashit(get_option('home'));
    $link = preg_replace("|^{$link_base}author/|", '', $link);
    return $link_base . $link;
}

What is the significance of load factor in HashMap?

If the buckets get too full, then we have to look through

a very long linked list.

And that's kind of defeating the point.

So here's an example where I have four buckets.

I have elephant and badger in my HashSet so far.

This is a pretty good situation, right?

Each element has zero or one elements.

Now we put two more elements into our HashSet.

     buckets      elements
      -------      -------
        0          elephant
        1          otter
         2          badger
         3           cat

This isn't too bad either.

Every bucket only has one element . So if I wanna know, does this contain panda?

I can very quickly look at bucket number 1 and it's not

there and

I known it's not in our collection.

If I wanna know if it contains cat, I look at bucket

number 3,

I find cat, I very quickly know if it's in our

collection.

What if I add koala, well that's not so bad.

             buckets      elements
      -------      -------
        0          elephant
        1          otter -> koala 
         2          badger
         3           cat

Maybe now instead of in bucket number 1 only looking at

one element,

I need to look at two.

But at least I don't have to look at elephant, badger and

cat.

If I'm again looking for panda, it can only be in bucket

number 1 and

I don't have to look at anything other then otter and

koala.

But now I put alligator in bucket number 1 and you can

see maybe where this is going.

That if bucket number 1 keeps getting bigger and bigger and

bigger, then I'm basically having to look through all of

those elements to find

something that should be in bucket number 1.

            buckets      elements
      -------      -------
        0          elephant
        1          otter -> koala ->alligator
         2          badger
         3           cat

If I start adding strings to other buckets,

right, the problem just gets bigger and bigger in every

single bucket.

How do we stop our buckets from getting too full?

The solution here is that

          "the HashSet can automatically

        resize the number of buckets."

There's the HashSet realizes that the buckets are getting

too full.

It's losing this advantage of this all of one lookup for

elements.

And it'll just create more buckets(generally twice as before) and

then place the elements into the correct bucket.

So here's our basic HashSet implementation with separate

chaining. Now I'm going to create a "self-resizing HashSet".

This HashSet is going to realize that the buckets are

getting too full and

it needs more buckets.

loadFactor is another field in our HashSet class.

loadFactor represents the average number of elements per

bucket,

above which we want to resize.

loadFactor is a balance between space and time.

If the buckets get too full then we'll resize.

That takes time, of course, but

it may save us time down the road if the buckets are a

little more empty.

Let's see an example.

Here's a HashSet, we've added four elements so far.

Elephant, dog, cat and fish.

          buckets      elements
      -------      -------
        0          
        1          elephant
         2          cat ->dog
         3           fish
          4         
           5

At this point, I've decided that the loadFactor, the

threshold,

the average number of elements per bucket that I'm okay

with, is 0.75.

The number of buckets is buckets.length, which is 6, and

at this point our HashSet has four elements, so the

current size is 4.

We'll resize our HashSet, that is we'll add more buckets,

when the average number of elements per bucket exceeds

the loadFactor.

That is when current size divided by buckets.length is

greater than loadFactor.

At this point, the average number of elements per bucket

is 4 divided by 6.

4 elements, 6 buckets, that's 0.67.

That's less than the threshold I set of 0.75 so we're

okay.

We don't need to resize.

But now let's say we add woodchuck.

                  buckets      elements
      -------      -------
        0          
        1          elephant
         2        woodchuck-> cat ->dog
         3           fish
          4         
           5

Woodchuck would end up in bucket number 3.

At this point, the currentSize is 5.

And now the average number of elements per bucket

is the currentSize divided by buckets.length.

That's 5 elements divided by 6 buckets is 0.83.

And this exceeds the loadFactor which was 0.75.

In order to address this problem, in order to make the

buckets perhaps a little

more empty so that operations like determining whether a

bucket contains

an element will be a little less complex, I wanna resize

my HashSet.

Resizing the HashSet takes two steps.

First I'll double the number of buckets, I had 6 buckets,

now I'm going to have 12 buckets.

Note here that the loadFactor which I set to 0.75 stays the same.

But the number of buckets changed is 12,

the number of elements stayed the same, is 5.

5 divided by 12 is around 0.42, that's well under our

loadFactor,

so we're okay now.

But we're not done because some of these elements are in

the wrong bucket now.

For instance, elephant.

Elephant was in bucket number 2 because the number of

characters in elephant

was 8.

We have 6 buckets, 8 minus 6 is 2.

That's why it ended up in number 2.

But now that we have 12 buckets, 8 mod 12 is 8, so

elephant does not belong in bucket number 2 anymore.

Elephant belongs in bucket number 8.

What about woodchuck?

Woodchuck was the one that started this whole problem.

Woodchuck ended up in bucket number 3.

Because 9 mod 6 is 3.

But now we do 9 mod 12.

9 mod 12 is 9, woodchuck goes to bucket number 9.

And you see the advantage of all this.

Now bucket number 3 only has two elements whereas before it had 3.

So here's our code,

where we had our HashSet with separate chaining that

didn't do any resizing.

Now, here's a new implementation where we use resizing.

Most of this code is the same,

we're still going to determine whether it contains the

value already.

If it doesn't, then we'll figure it out which bucket it

should go into and

then add it to that bucket, add it to that LinkedList.

But now we increment the currentSize field.

currentSize was the field that kept track of the number

of elements in our HashSet.

We're going to increment it and then we're going to look

at the average load,

the average number of elements per bucket.

We'll do that division down here.

We have to do a little bit of casting here to make sure

that we get a double.

And then, we'll compare that average load to the field

that I've set as

0.75 when I created this HashSet, for instance, which was

the loadFactor.

If the average load is greater than the loadFactor,

that means there's too many elements per bucket on

average, and I need to reinsert.

So here's our implementation of the method to reinsert

all the elements.

First, I'll create a local variable called oldBuckets.

Which is referring to the buckets as they currently stand

before I start resizing everything.

Note I'm not creating a new array of linked lists just yet.

I'm just renaming buckets as oldBuckets.

Now remember buckets was a field in our class, I'm going

to now create a new array

of linked lists but this will have twice as many elements

as it did the first time.

Now I need to actually do the reinserting,

I'm going to iterate through all of the old buckets.

Each element in oldBuckets is a LinkedList of strings

that is a bucket.

I'll go through that bucket and get each element in that

bucket.

And now I'm gonna reinsert it into the newBuckets.

I will get its hashCode.

I will figure out which index it is.

And now I get the new bucket, the new LinkedList of

strings and

I'll add it to that new bucket.

So to recap, HashSets as we've seen are arrays of Linked

Lists, or buckets.

A self resizing HashSet can realize using some ratio or

how to fix stream_socket_enable_crypto(): SSL operation failed with code 1

edit your .env and add this line after mail config lines

MAIL_ENCRYPTION=""

Save and try to send email

How to do an Integer.parseInt() for a decimal number?

Using BigDecimal to get rounding:

String s1="0.01";
int i1 = new BigDecimal(s1).setScale(0, RoundingMode.HALF_UP).intValueExact();

String s2="0.5";
int i2 = new BigDecimal(s2).setScale(0, RoundingMode.HALF_UP).intValueExact();

What is the difference between AF_INET and PF_INET in socket programming?

In fact, AF_ and PF_ are the same thing. There are some words on Wikipedia will clear your confusion

The original design concept of the socket interface distinguished between protocol types (families) and the specific address types that each may use. It was envisioned that a protocol family may have several address types. Address types were defined by additional symbolic constants, using the prefix AF_ instead of PF_. The AF_-identifiers are intended for all data structures that specifically deal with the address type and not the protocol family. However, this concept of separation of protocol and address type has not found implementation support and the AF_-constants were simply defined by the corresponding protocol identifier, rendering the distinction between AF_ versus PF_ constants a technical argument of no significant practical consequence. Indeed, much confusion exists in the proper usage of both forms.

How to verify if a file exists in a batch file?

Here is a good example on how to do a command if a file does or does not exist:

if exist C:\myprogram\sync\data.handler echo Now Exiting && Exit
if not exist C:\myprogram\html\data.sql Exit

We will take those three files and put it in a temporary place. After deleting the folder, it will restore those three files.

xcopy "test" "C:\temp"
xcopy "test2" "C:\temp"
del C:\myprogram\sync\
xcopy "C:\temp" "test"
xcopy "C:\temp" "test2"
del "c:\temp"

Use the XCOPY command:

xcopy "C:\myprogram\html\data.sql"  /c /d /h /e /i /y  "C:\myprogram\sync\"

I will explain what the /c /d /h /e /i /y means:

  /C           Continues copying even if errors occur.
  /D:m-d-y     Copies files changed on or after the specified date.
               If no date is given, copies only those files whose
               source time is newer than the destination time.
  /H           Copies hidden and system files also.
  /E           Copies directories and subdirectories, including empty ones.
               Same as /S /E. May be used to modify /T.
  /T           Creates directory structure, but does not copy files. Does not
               include empty directories or subdirectories. /T /E includes
  /I           If destination does not exist and copying more than one file,
               assumes that destination must be a directory.
  /Y           Suppresses prompting to confirm you want to overwrite an
               existing destination file.

`To see all the commands type`xcopy /? in cmd

Call other batch file with option sync.bat myprogram.ini.

I am not sure what you mean by this, but if you just want to open both of these files you just put the path of the file like

Path/sync.bat
Path/myprogram.ini

If it was in the Bash environment it was easy for me, but I do not know how to test if a file or folder exists and if it is a file or folder.

You are using a batch file. You mentioned earlier you have to create a .bat file to use this:

I have to create a .BAT file that does this:

Apache 2.4.3 (with XAMPP 1.8.1) not starting in windows 8

change 80 to 81 and 443 to 444 by clicking config button and editing httpd.conf and httpd-ssl.congf. Now you can Access XAMPP from 127.0.0.1:81

What is the optimal way to compare dates in Microsoft SQL server?

Converting to a DATE or using an open-ended date range in any case will yield the best performance. FYI, convert to date using an index are the best performers. More testing a different techniques in article: What is the most efficient way to trim time from datetime? Posted by Aaron Bertrand

From that article:

DECLARE @dateVar datetime = '19700204';

-- Quickest when there is an index on t.[DateColumn], 
-- because CONVERT can still use the index.
SELECT t.[DateColumn]
FROM MyTable t
WHERE = CONVERT(DATE, t.[DateColumn]) = CONVERT(DATE, @dateVar);

-- Quicker when there is no index on t.[DateColumn]
DECLARE @dateEnd datetime = DATEADD(DAY, 1, @dateVar);
SELECT t.[DateColumn] 
FROM MyTable t
WHERE t.[DateColumn] >= @dateVar AND 
      t.[DateColumn] < @dateEnd;

Also from that article: using BETWEEN, DATEDIFF or CONVERT(CHAR(8)... are all slower.

How do I test if a recordSet is empty? isNull?

I would check the "End of File" flag:

If temp_rst1.EOF Or temp_rst2.EOF Then MsgBox "null"

String concatenation in Jinja

My bad, in trying to simplify it, I went too far, actually stuffs is a record of all kinds of info, I just want the id in it.

stuffs = [[123, first, last], [456, first, last]]

I want my_sting to be

my_sting = '123, 456'

My original code should have looked like this:

{% set my_string = '' %}
{% for stuff in stuffs %}
{% set my_string = my_string + stuff.id + ', '%}
{% endfor%}

Thinking about it, stuffs is probably a dictionary, but you get the gist.

Yes I found the join filter, and was going to approach it like this:

 {% set my_string = [] %}
 {% for stuff in stuffs %}
 {% do my_string.append(stuff.id) %}
 {% endfor%}
 {%  my_string|join(', ') %}

But the append doesn't work without importing the extensions to do it, and reading that documentation gave me a headache. It doesn't explicitly say where to import it from or even where you would put the import statement, so I figured finding a way to concat would be the lesser of the two evils.

What is an application binary interface (ABI)?

ABI - Application Binary Interface is about a machine code communication in runtime between two binary parts like - application, library, OS... ABI describes how objects are saved in memory, how functions are called(calling convention), mangling...

A good example of API and ABI is iOS ecosystem with Swift language.

  • Application layer - When you create an application using different languages. For example you can create application using Swift and Objective-C[Mixing Swift and Objective-C]

  • Application - OS layer - runtime - Swift runtime and standard libraries are parts of OS and they should not be included into each bundle(e.g. app, framework). It is the same as like Objective-C uses

  • Library layer - Module Stability case - compile time - you will be able to import a framework which was built with another version of Swift's compiler. It means that it is safety to create a closed-source(pre-build) binary which will be consumed by a different version of compiler( .swiftinterface is used with .swiftmodule) and you will not get

    Module compiled with _ cannot be imported by the _ compiler
    
  • Library layer - Library Evolution case

    1. Compile time - if a dependency was changed, a client has not to be recompiled.
    2. Runtime - a system library or a dynamic framework can be hot-swapped by a new one.

[API vs ABI]
[Swift Module and Library stability]

jQuery.post( ) .done( ) and success:

The reason to prefer Promises over callback functions is to have multiple callbacks and to avoid the problems like Callback Hell.

Callback hell (for more details, refer http://callbackhell.com/): Asynchronous javascript, or javascript that uses callbacks, is hard to get right intuitively. A lot of code ends up looking like this:

asyncCall(function(err, data1){
    if(err) return callback(err);       
    anotherAsyncCall(function(err2, data2){
        if(err2) return calllback(err2);
        oneMoreAsyncCall(function(err3, data3){
            if(err3) return callback(err3);
            // are we done yet?
        });
    });
});

With Promises above code can be rewritten as below:

asyncCall()
.then(function(data1){
    // do something...
    return anotherAsyncCall();
})
.then(function(data2){
    // do something...  
    return oneMoreAsyncCall();    
})
.then(function(data3){
    // the third and final async response
})
.fail(function(err) {
    // handle any error resulting from any of the above calls    
})
.done();

Displaying a 3D model in JavaScript/HTML5

a couple years down the road, I'd vote for three.js because

ie 11 supports webgl (to what extent I can't assure you since i'm usually in chrome)

and, as far as importing external models into three.js, here's a link to mrdoob's updated loaders (so many!)

UPDATE nov 2019: the THREE.js loaders are now far more and it makes little sense to post them all: just go to this link

http://threejs.org/examples and review the loaders - at least 20 of them

Change action bar color in android

Maybe this can help you also. It's from the website:

http://nathanael.hevenet.com/android-dev-changing-the-title-bar-background/

First things first you need to have a custom theme declared for your application (or activity, depending on your needs). Something like…

<!-- Somewhere in AndroidManifest.xml -->
<application ... android:theme="@style/ThemeSelector">

Then, declare your custom theme for two cases, API versions with and without the Holo Themes. For the old themes we’ll customize the windowTitleBackgroundStyle attribute, and for the newer ones the ActionBarStyle.

<!-- res/values/styles.xml -->
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="ThemeSelector" parent="android:Theme.Light">
        <item name="android:windowTitleBackgroundStyle">@style/WindowTitleBackground</item>
    </style>

    <style name="WindowTitleBackground">     
        <item name="android:background">@color/title_background</item>
    </style>

</resources>

<!-- res/values-v11/styles.xml -->
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="ThemeSelector" parent="android:Theme.Holo.Light">
        <item name="android:actionBarStyle">@style/ActionBar</item>
    </style>

    <style name="ActionBar" parent="android:style/Widget.Holo.ActionBar">     
        <item name="android:background">@color/title_background</item>
    </style>

</resources>

That’s it!

How to normalize a vector in MATLAB efficiently? Any related built-in function?

I don't know any MATLAB and I've never used it, but it seems to me you are dividing. Why? Something like this will be much faster:

d = 1/norm(V)
V1 = V * d

Can I set up HTML/Email Templates with ASP.NET?

If flexibility is one of your prerequisites, XSLT might be a good choice, which is completely supported by .NET framework and you would be able to even let the user edit those files. This article (http://www.aspfree.com/c/a/XML/XSL-Transformations-using-ASP-NET/) might be useful for a start (msdn has more info about it). As said by ScarletGarden NVelocity is another good choice but I do prefer XSLT for its " built-in" .NET framework support and platform agnostic.

Twitter bootstrap modal-backdrop doesn't disappear

I suffered a similar issue: in my modal window, I have two buttons, "Cancel" and "OK". Originally, both buttons would close the modal window by invoking $('#myModal').modal('hide') (with "OK" previously executing some code) and the scenario would be the following:

  1. Open the modal window
  2. Do some operations, then click on "OK" do validate them and close the modal
  3. Open the modal again and dismiss by clicking on "Cancel"
  4. Re-open the modal, click again on "Cancel" ==> the backdrop is no longer accessible!

well, my fellow next desk saved my day: instead of invoking $('#myModal').modal('hide'), give your buttons the attribute data-dismiss="modal" and add a "click" event to your "Submit" button. In my problem, the HTML (well, TWIG) code for the button is:

<button id="modal-btn-ok" class="btn" data-dismiss="modal">OK</button>
<button id="modal-btn-cancel" class="btn" data-dismiss="modal">Cancel</button>

and in my JavaScript code, I have:

$("#modal-btn-ok").one("click", null, null, function(){
    // My stuff to be done
});

while no "click" event is attributed to the "Cancel" button. The modal now closes properly and lets me play again with the "normal" page. It actually seems that the data-dismiss="modal" should be the only way to indicate that a button (or whatever DOM element) should close a Bootstrap modal. The .modal('hide') method seems to behave in a not quite controllable way.

Hope this helps!

mysql datatype for telephone number and address

INT(10) does not mean a 10-digit number, it means an integer with a display width of 10 digits. The maximum value for an INT in MySQL is 2147483647 (or 4294967295 if unsigned).

You can use a BIGINT instead of INT to store it as a numeric. Using BIGINT will save you 3 bytes per row over VARCHAR(10).

To Store "Country + area + number separately". You can try using a VARCHAR(20), this allows you the ability to store international phone numbers properly, should that need arise.

JSON string to JS object

the string in your question is not a valid json string. From json.org website:

JSON is built on two structures:

* A collection of name/value pairs. In various languages, this is 
  realized as an object, record, struct, dictionary, hash table, keyed list, or
  associative array.
* An ordered list of values. In most languages, this is realized as an
  array, vector, list, or sequence.

Basically a json string will always start with either { or [.

Then as @Andy E and @Cryo said you can parse the string with json2.js or some other libraries.

IMHO you should avoid eval because it will any javascript program, so you might incur in security issues.

jQuery, simple polling example

Here's a helpful article on long polling (long-held HTTP request) using jQuery. A code snippet derived from this article:

(function poll() {
    setTimeout(function() {
        $.ajax({
            url: "/server/api/function",
            type: "GET",
            success: function(data) {
                console.log("polling");
            },
            dataType: "json",
            complete: poll,
            timeout: 2000
        })
    }, 5000);
})();

This will make the next request only after the ajax request has completed.

A variation on the above that will execute immediately the first time it is called before honouring the wait/timeout interval.

(function poll() {
    $.ajax({
        url: "/server/api/function",
        type: "GET",
        success: function(data) {
            console.log("polling");
        },
        dataType: "json",
        complete: setTimeout(function() {poll()}, 5000),
        timeout: 2000
    })
})();

How to change DatePicker dialog color for Android 5.0

try this, work for me

Put the two options, colorAccent and android:colorAccent

<style name="AppTheme" parent="@style/Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
   ....
    <item name="android:dialogTheme">@style/AppTheme.DialogTheme</item>
    <item name="android:datePickerDialogTheme">@style/Dialog.Theme</item>
</style>

<style name="AppTheme.DialogTheme" parent="Theme.AppCompat.Light.Dialog">

<!-- Put the two options, colorAccent and android:colorAccent. -->
    <item name="colorAccent">@color/colorPrimary</item>
    <item name="android:colorPrimary">@color/colorPrimary</item>
    <item name="android:colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="android:colorAccent">@color/colorPrimary</item>
 </style>

IF EXIST C:\directory\ goto a else goto b problems windows XP batch files

Use parentheses to group the individual branches:

IF EXIST D:\RPS_BACKUP\backups_to_zip\ (goto zipexist) else goto zipexistcontinue

In your case the parser won't ever see the else belonging to the if because goto will happily accept everything up to the end of the command. You can see a similar issue when using echo instead of goto.

Also using parentheses will allow you to use the statements directly without having to jump around (although I wasn't able to rewrite your code to actually use structured programming techniques; maybe it's too early or it doesn't lend itself well to block structures as the code is right now).

trace a particular IP and port

you can use tcpdump on the server to check if the client even reaches the server.

  tcpdump -i any tcp port 9100

also make sure your firewall is not blocking incoming connections.

EDIT: you can also write the dump into a file and view it with wireshark on your client if you don't want to read it on the console.

2nd Edit: you can check if you can reach the port via

 nc ip 9100 -z -v

from your local PC.

Why does JavaScript only work after opening developer tools in IE once?

Here's another possible reason besides the console.log issue (at least in IE11):

When the console is not open, IE does pretty aggressive caching, so make sure that any $.ajax calls or XMLHttpRequest calls have caching set to false.

For example:

$.ajax({cache: false, ...})

When the developer console is open, caching is less aggressive. Seems to be a bug (or maybe a feature?)

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 74 supplied

You need to pass in a sequence, but you forgot the comma to make your parameters a tuple:

cursor.execute('INSERT INTO images VALUES(?)', (img,))

Without the comma, (img) is just a grouped expression, not a tuple, and thus the img string is treated as the input sequence. If that string is 74 characters long, then Python sees that as 74 separate bind values, each one character long.

>>> len(img)
74
>>> len((img,))
1

If you find it easier to read, you can also use a list literal:

cursor.execute('INSERT INTO images VALUES(?)', [img])

Search All Fields In All Tables For A Specific Value (Oracle)

Yes you can and your DBA will hate you and will find you to nail your shoes to the floor because that will cause lots of I/O and bring the database performance really down as the cache purges.

select column_name from all_tab_columns c, user_all_tables u where c.table_name = u.table_name;

for a start.

I would start with the running queries, using the v$session and the v$sqlarea. This changes based on oracle version. This will narrow down the space and not hit everything.

On Windows, running "import tensorflow" generates No module named "_pywrap_tensorflow" error

cuDNN causes my problem. PATH variable doesn't work for me. I have to copy the files in my cuDNN folders into respectful CUDA 8.0 folder structure.

Change onClick attribute with javascript

Another solution is to set the 'onclick' attribute to a function that returns your writeLED function.

document.getElementById('buttonLED'+id).onclick = function(){ return writeLED(1,1)};

This can also be useful for other cases when you create an element in JavaScript while it has not yet been drawn in the browser.

Inserting an item in a Tuple

You can code simply like this as well:

T += (new_element,)

Java Security: Illegal key size or default parameters?

Starting from Java 9 or 8u151, you can use comment a line in the file:

<JAVA_HOME>/jre/lib/security/java.security

And change:

#crypto.policy=unlimited

to

crypto.policy=unlimited

PHP output showing little black diamonds with a question mark

This will help you. Put this inside <head> tag

<meta charset="iso-8859-1">

How to remove all line breaks from a string

On mac, just use \n in regexp to match linebreaks. So the code will be string.replace(/\n/g, ''), ps: the g followed means match all instead of just the first.

On windows, it will be \r\n.

Objective-C and Swift URL encoding

int strLength = 0;
NSString *urlStr = @"http://www";
NSLog(@" urlStr : %@", urlStr );
NSMutableString *mutableUrlStr = [urlStr mutableCopy];
NSLog(@" mutableUrlStr : %@", mutableUrlStr );
strLength = [mutableUrlStr length];
[mutableUrlStr replaceOccurrencesOfString:@":" withString:@"%3A" options:NSCaseInsensitiveSearch range:NSMakeRange(0, strLength)];
NSLog(@" mutableUrlStr : %@", mutableUrlStr );
strLength = [mutableUrlStr length];
[mutableUrlStr replaceOccurrencesOfString:@"/" withString:@"%2F" options:NSCaseInsensitiveSearch range:NSMakeRange(0, strLength)];
NSLog(@" mutableUrlStr : %@", mutableUrlStr );

What is [Serializable] and when should I use it?

Some practical uses for the [Serializable] attribute:

  • Saving object state using binary serialisation; you can very easily 'save' entire object instances in your application to a file or network stream and then recreate them by deserialising - check out the BinaryFormatter class in System.Runtime.Serialization.Formatters.Binary
  • Writing classes whose object instances can be stored on the clipboard using Clipboard.SetData() - nonserialisable classes cannot be placed on the clipboard.
  • Writing classes which are compatible with .NET Remoting; generally, any class instance you pass between application domains (except those which extend from MarshalByRefObject) must be serialisable.

These are the most common usage cases that I have come across.

Cross-browser custom styling for file upload button

Any easy way to cover ALL file inputs is to just style your input[type=button] and drop this in globally to turn file inputs into buttons:

$(document).ready(function() {
    $("input[type=file]").each(function () {
        var thisInput$ = $(this);
        var newElement = $("<input type='button' value='Choose File' />");
        newElement.click(function() {
            thisInput$.click();
        });
        thisInput$.after(newElement);
        thisInput$.hide();
    });
});

Here's some sample button CSS that I got from http://cssdeck.com/labs/beautiful-flat-buttons:

input[type=button] {
  position: relative;
  vertical-align: top;
  width: 100%;
  height: 60px;
  padding: 0;
  font-size: 22px;
  color:white;
  text-align: center;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.25);
  background: #454545;
  border: 0;
  border-bottom: 2px solid #2f2e2e;
  cursor: pointer;
  -webkit-box-shadow: inset 0 -2px #2f2e2e;
  box-shadow: inset 0 -2px #2f2e2e;
}
input[type=button]:active {
  top: 1px;
  outline: none;
  -webkit-box-shadow: none;
  box-shadow: none;
}

Choosing the default value of an Enum type without having to change values

The default is the first one in the definition. For example:

public enum MyEnum{His,Hers,Mine,Theirs}

Enum.GetValues(typeOf(MyEnum)).GetValue(0);

This will return His

What does this thread join code mean?

A picture is worth a thousand words.

    Main thread-->----->--->-->--block##########continue--->---->
                 \                 |               |
sub thread start()\                | join()        |
                   \               |               |
                    ---sub thread----->--->--->--finish    

Hope to useful, for more detail click here

Grant Select on a view not base table when base table is in a different database

You can grant permissions on a view and not the base table. This is one of the reasons people like using views.

Have a look here: GRANT Object Permissions (Transact-SQL)

Print in one line dynamically

In Python 3 you can do it this way:

for item in range(1,10):
    print(item, end =" ")

Outputs:

1 2 3 4 5 6 7 8 9 

Tuple: You can do the same thing with a tuple:

tup = (1,2,3,4,5)

for n in tup:
    print(n, end = " - ")

Outputs:

1 - 2 - 3 - 4 - 5 - 

Another example:

list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]
for item in list_of_tuples:
    print(item)

Outputs:

(1, 2)
('A', 'B')
(3, 4)
('Cat', 'Dog')

You can even unpack your tuple like this:

list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]

# Tuple unpacking so that you can deal with elements inside of the tuple individually
for (item1, item2) in list_of_tuples:
    print(item1, item2)   

Outputs:

1 2
A B
3 4
Cat Dog

another variation:

list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]
for (item1, item2) in list_of_tuples:
    print(item1)
    print(item2)
    print('\n')

Outputs:

1
2


A
B


3
4


Cat
Dog

What is the difference between readonly="true" & readonly="readonly"?

I'm not sure how they're functionally different. My current batch of OS X browsers don't show any difference.

I would assume they are all functionally the same due to legacy HTML attribute handling. Back in the day, any flag (Boolean) attribute need only be present, sans value, eg

<input readonly>
<option selected>

When XHTML came along, this syntax wasn't valid and values were required. Whilst the W3 specified using the attribute name as the value, I'm guessing most browser vendors decided to simply check for attribute existence.

Where does the iPhone Simulator store its data?

For react-native users who don't use Xcode often, you can just use find. Open a terminal and search by with the database name.

$ find ~/Library/Developer -name 'myname.db'

If you don't know the exact name you can use wildcards:

$ find ~/Library/Developer -name 'myname.*'

Draw Circle using css alone

  • Create a div with a set height and width (so, for a circle, use the same height and width), forming a square
  • add a border-radius of 50% which will make it circular in shape. (note: no prefix has been required for a long time)
  • You can then play around with background-color / gradients / (even pseudo elements) to create something like this:

_x000D_
_x000D_
.red {_x000D_
  background-color: red;_x000D_
}_x000D_
.green {_x000D_
  background-color: green;_x000D_
}_x000D_
.blue {_x000D_
  background-color: blue;_x000D_
}_x000D_
.yellow {_x000D_
  background-color: yellow;_x000D_
}_x000D_
.sphere {_x000D_
  height: 200px;_x000D_
  width: 200px;_x000D_
  border-radius: 50%;_x000D_
  text-align: center;_x000D_
  vertical-align: middle;_x000D_
  font-size: 500%;_x000D_
  position: relative;_x000D_
  box-shadow: inset -10px -10px 100px #000, 10px 10px 20px black, inset 0px 0px 10px black;_x000D_
  display: inline-block;_x000D_
  margin: 5%;_x000D_
}_x000D_
.sphere::after {_x000D_
  background-color: rgba(255, 255, 255, 0.3);_x000D_
  content: '';_x000D_
  height: 45%;_x000D_
  width: 12%;_x000D_
  position: absolute;_x000D_
  top: 4%;_x000D_
  left: 15%;_x000D_
  border-radius: 50%;_x000D_
  transform: rotate(40deg);_x000D_
}
_x000D_
<div class="sphere red"></div>_x000D_
<div class="sphere green"></div>_x000D_
<div class="sphere blue"></div>_x000D_
<div class="sphere yellow"></div>_x000D_
<div class="sphere"></div>
_x000D_
_x000D_
_x000D_

add item to dropdown list in html using javascript

Try to use appendChild method:

select.appendChild(option);

How to multiply all integers inside list

Try a list comprehension:

l = [x * 2 for x in l]

This goes through l, multiplying each element by two.

Of course, there's more than one way to do it. If you're into lambda functions and map, you can even do

l = map(lambda x: x * 2, l)

to apply the function lambda x: x * 2 to each element in l. This is equivalent to:

def timesTwo(x):
    return x * 2

l = map(timesTwo, l)

Note that map() returns a map object, not a list, so if you really need a list afterwards you can use the list() function afterwards, for instance:

l = list(map(timesTwo, l))

Thanks to Minyc510 in the comments for this clarification.

How to communicate between Docker containers via "hostname"

As far as I know, by using only Docker this is not possible. You need some DNS to map container ip:s to hostnames.

If you want out of the box solution. One solution is to use for example Kontena. It comes with network overlay technology from Weave and this technology is used to create virtual private LAN networks for each service and every service can be reached by service_name.kontena.local-address.

Here is simple example of Wordpress application's YAML file where Wordpress service connects to MySQL server with wordpress-mysql.kontena.local address:

wordpress:                                                                         
  image: wordpress:4.1                                                             
  stateful: true                                                                   
  ports:                                                                           
    - 80:80                                                                      
  links:                                                                           
    - mysql:wordpress-mysql                                                        
  environment:                                                                     
    - WORDPRESS_DB_HOST=wordpress-mysql.kontena.local                              
    - WORDPRESS_DB_PASSWORD=secret                                                 
mysql:                                                                             
  image: mariadb:5.5                                                               
  stateful: true                                                                   
  environment:                                                                     
    - MYSQL_ROOT_PASSWORD=secret

Regular expression for floating point numbers

In c notation, float number can occur in following shapes:

  1. 123
  2. 123.
  3. 123.24
  4. .24
  5. 2e-2 = 2 * 10 pow -2 = 2 * 0.1
  6. 4E+4 = 4 * 10 pow 4 = 4 * 10 000

For creating float regular expresion, I will first create "int regular expresion variable":

(([1-9][0-9]*)|0) will be int

Now, I will write small chunks of float regular expresion - solution is to concat those chunks with or simbol "|".

Chunks:

- (([+-]?{int}) satysfies case 1
- (([+-]?{int})"."[0-9]*)  satysfies cases 2 and 3
- ("."[0-9]*) satysfies case 4
- ([+-]?{int}[eE][+-]?{int}) satysfies cases 5 and 6

Final solution (concanating small chunks):

(([+-]?{int})|(([+-]?{int})"."[0-9]*)|("."[0-9]*)|([+-]?{int}[eE][+-]?{int})

How to sort in-place using the merge sort algorithm?

This is my C version:

void mergesort(int *a, int len) {
  int temp, listsize, xsize;

  for (listsize = 1; listsize <= len; listsize*=2) {
    for (int i = 0, j = listsize; (j+listsize) <= len; i += (listsize*2), j += (listsize*2)) {
      merge(& a[i], listsize, listsize);
    }
  }

  listsize /= 2;

  xsize = len % listsize;
  if (xsize > 1)
    mergesort(& a[len-xsize], xsize);

  merge(a, listsize, xsize);
}

void merge(int *a, int sizei, int sizej) {
  int temp;
  int ii = 0;
  int ji = sizei;
  int flength = sizei+sizej;

  for (int f = 0; f < (flength-1); f++) {
    if (sizei == 0 || sizej == 0)
      break;

    if (a[ii] < a[ji]) {
      ii++;
      sizei--;
    }
    else {
      temp = a[ji];

      for (int z = (ji-1); z >= ii; z--)
        a[z+1] = a[z];  
      ii++;

      a[f] = temp;

      ji++;
      sizej--;
    }
  }
}

How to delete rows in tables that contain foreign keys to other tables

If you have multiply rows to delete and you don't want to alter the structure of your tables you can use cursor. 1-You first need to select rows to delete(in a cursor) 2-Then for each row in the cursor you delete the referencing rows and after that delete the row him self.

Ex:

--id is primary key of MainTable
    declare @id int
    set @id = 1
    declare theMain cursor for select FK from MainTable where MainID = @id
    declare @fk_Id int
    open theMain
    fetch next from theMain into @fk_Id
    while @@fetch_status=0
    begin
        --fkid is the foreign key 
        --Must delete from Main Table first then child.
        delete from MainTable where fkid = @fk_Id
        delete from ReferencingTable where fkid = @fk_Id
        fetch next from theMain into @fk_Id
    end
    close theMain
    deallocate theMain

hope is useful

Generate a dummy-variable

another way you can do it is use

ifelse(year < 1965 , 1, 0)

Copy files on Windows Command Line with Progress

The Esentutl /y option allows copyng (single) file files with progress bar like this :

enter image description here

the command should look like :

esentutl /y "FILE.EXT" /d "DEST.EXT" /o

The command is available on every windows machine but the y option is presented in windows vista. As it works only with single files does not look very useful for a small ones. Other limitation is that the command cannot overwrite files. Here's a wrapper script that checks the destination and if needed could delete it (help can be seen by passing /h).

DB2 Timestamp select statement

You might want to use TRUNC function on your column when comparing with string format, so it compares only till seconds, not milliseconds.

SELECT * FROM <table_name> WHERE id = 1 
AND TRUNC(usagetime, 'SS') = '2012-09-03 08:03:06';

If you wanted to truncate upto minutes, hours, etc. that is also possible, just use appropriate notation instead of 'SS':

hour ('HH'), minute('MI'), year('YEAR' or 'YYYY'), month('MONTH' or 'MM'), Day ('DD')

How to count lines of Java code using IntelliJ IDEA?

Just like Neil said:

Ctrl-Shift-F -> Text to find = '\n' -> Find.

With only one improvement, if you enter "\n+", you can search for non-empty lines

If lines with only whitespace can be considered empty too, then you can use the regex "(\s*\n\s*)+" to not count them.

Maximum concurrent Socket.IO connections

I tried to use socket.io on AWS, I can at most keep around 600 connections stable.

And I found out it is because socket.io used long polling first and upgraded to websocket later.

after I set the config to use websocket only, I can keep around 9000 connections.

Set this config at client side:

const socket = require('socket.io-client')
const conn = socket(host, { upgrade: false, transports: ['websocket'] })

libxml install error using pip

I solved this issue by increasing my server ram.

I was running only 512 MB and when I upgraded to 1 GB I had no problem.

I also installed every package manually prior to this in an attempt to fix the problem, but I'm not sure whether this is a necessary step.

How to join entries in a set into one string?

You have the join statement backwards try:

print ', '.join(set_3)

How to get the indexpath.row when an element is activated?

Use an extension to UITableView to fetch the cell that contains any view:


@Paulw11's answer of setting up a custom cell type with a delegate property that sends messages to the table view is a good way to go, but it requires a certain amount of work to set up.

I think walking the table view cell's view hierarchy looking for the cell is a bad idea. It is fragile - if you later enclose your button in a view for layout purposes, that code is likely to break.

Using view tags is also fragile. You have to remember to set up the tags when you create the cell, and if you use that approach in a view controller that uses view tags for another purpose you can have duplicate tag numbers and your code can fail to work as expected.

I have created an extension to UITableView that lets you get the indexPath for any view that is contained in a table view cell. It returns an Optional that will be nil if the view passed in actually does not fall within a table view cell. Below is the extension source file in it's entirety. You can simply put this file in your project and then use the included indexPathForView(_:) method to find the indexPath that contains any view.

//
//  UITableView+indexPathForView.swift
//  TableViewExtension
//
//  Created by Duncan Champney on 12/23/16.
//  Copyright © 2016-2017 Duncan Champney.
//  May be used freely in for any purpose as long as this 
//  copyright notice is included.

import UIKit

public extension UITableView {
  
  /**
  This method returns the indexPath of the cell that contains the specified view
   
   - Parameter view: The view to find.
   
   - Returns: The indexPath of the cell containing the view, or nil if it can't be found
   
  */
  
    func indexPathForView(_ view: UIView) -> IndexPath? {
        let center = view.center
        let viewCenter = self.convert(center, from: view.superview)
        let indexPath = self.indexPathForRow(at: viewCenter)
        return indexPath
    }
}

To use it, you can simply call the method in the IBAction for a button that's contained in a cell:

func buttonTapped(_ button: UIButton) {
  if let indexPath = self.tableView.indexPathForView(button) {
    print("Button tapped at indexPath \(indexPath)")
  }
  else {
    print("Button indexPath not found")
  }
}

(Note that the indexPathForView(_:) function will only work if the view object it's passed is contained by a cell that's currently on-screen. That's reasonable, since a view that is not on-screen doesn't actually belong to a specific indexPath; it's likely to be assigned to a different indexPath when it's containing cell is recycled.)

EDIT:

You can download a working demo project that uses the above extension from Github: TableViewExtension.git

Add image in pdf using jspdf

First you need to load the image, convert data, and then pass to jspdf (in typescript):

loadImage(imagePath): ng.IPromise<any> {
    var defer = this.q.defer<any>();
    var img = new Image();
    img.src = imagePath;
    img.addEventListener('load',()=>{
            var canvas = document.createElement('canvas');
            canvas.width = img.width;
            canvas.height = img.height;

            var context = canvas.getContext('2d');
            context.drawImage(img, 0, 0);

            var dataURL = canvas.toDataURL('image/jpeg');

            defer.resolve(dataURL);
    });

    return defer.promise;
}

generatePdf() {
    this.loadImage('img/businessLogo.jpg').then((data) => {
        var pdf = new jsPDF();
        pdf.addImage(data,'JPEG', 15, 40, 180, 160);
        pdf.text(30, 20, 'Hello world!');
        var pdf_container =  angular.element(document.getElementById('pdf_preview'));
        pdf_container.attr('src', pdf.output('datauristring'));
    });
}

Business logic in MVC

Model = code for CRUD database operations.

Controller = responds to user actions, and passes the user requests for data retrieval or delete/update to the model, subject to the business rules specific to an organization. These business rules could be implemented in helper classes, or if they are not too complex, just directly in the controller actions. The controller finally asks the view to update itself so as to give feedback to the user in the form of a new display, or a message like 'updated, thanks', etc.,

View = UI that is generated based on a query on the model.

There are no hard and fast rules regarding where business rules should go. In some designs they go into model, whereas in others they are included with the controller. But I think it is better to keep them with the controller. Let the model worry only about database connectivity.

Defining constant string in Java?

It would look like this:

public static final String WELCOME_MESSAGE = "Hello, welcome to the server";

If the constants are for use just in a single class, you'd want to make them private instead of public.

What is the best way to paginate results in SQL Server

   CREATE view vw_sppb_part_listsource as 
    select row_number() over (partition by sppb_part.init_id order by sppb_part.sppb_part_id asc ) as idx, * from (
      select 
          part.SPPB_PART_ID
          , 0 as is_rev
          , part.part_number 
          , part.init_id 
      from t_sppb_init_part part 
      left join t_sppb_init_partrev prev on ( part.SPPB_PART_ID = prev.SPPB_PART_ID )
      where prev.SPPB_PART_ID is null 
      union 
      select 
          part.SPPB_PART_ID
          , 1 as is_rev
          , prev.part_number 
          , part.init_id 
      from t_sppb_init_part part 
      inner join t_sppb_init_partrev prev on ( part.SPPB_PART_ID = prev.SPPB_PART_ID )
    ) sppb_part

will restart idx when it comes to different init_id

Trigger an action after selection select2

For above v4

$('#yourselect').on("select2:select", function(e) { 
     // after selection of select2 
});

Mapping many-to-many association table with extra column(s)

As said before, with JPA, in order to have the chance to have extra columns, you need to use two OneToMany associations, instead of a single ManyToMany relationship. You can also add a column with autogenerated values; this way, it can work as the primary key of the table, if useful.

For instance, the implementation code of the extra class should look like that:

@Entity
@Table(name = "USER_SERVICES")
public class UserService{

    // example of auto-generated ID
    @Id
    @Column(name = "USER_SERVICES_ID", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long userServiceID;



    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "USER_ID")
    private User user;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "SERVICE_ID")
    private Service service;



    // example of extra column
    @Column(name="VISIBILITY")    
    private boolean visibility;



    public long getUserServiceID() {
        return userServiceID;
    }


    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Service getService() {
        return service;
    }

    public void setService(Service service) {
        this.service = service;
    }

    public boolean getVisibility() {
        return visibility;
    }

    public void setVisibility(boolean visibility) {
        this.visibility = visibility;
    }

}

DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled

Try setting the definer for the function!

So instead of

CREATE FUNCTION get_pet_owner

you will write something akin to

CREATE DEFINER=procadmin@% FUNCTION get_pet_owner

which ought to work if the user prodacmin has rights to create functions/procedures.

In my case the function worked when generated through MySQL Workbench but did not work when run directly as an SQL script. Making the changes above fixed the problem.

Using Java to pull data from a webpage?

Here's my solution using URL and try with resources phrase to catch the exceptions.

/**
 * Created by mona on 5/27/16.
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class ReadFromWeb {
    public static void readFromWeb(String webURL) throws IOException {
        URL url = new URL(webURL);
        InputStream is =  url.openStream();
        try( BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        }
        catch (MalformedURLException e) {
            e.printStackTrace();
            throw new MalformedURLException("URL is malformed!!");
        }
        catch (IOException e) {
            e.printStackTrace();
            throw new IOException();
        }

    }
    public static void main(String[] args) throws IOException {
        String url = "https://madison.craigslist.org/search/sub";
        readFromWeb(url);
    }

}

You could additionally save it to file based on your needs or parse it using XML or HTML libraries.

what's the easiest way to put space between 2 side-by-side buttons in asp.net

If you want the style to apply globally you could use the adjacent sibling combinator from css.

.my-button-style + .my-button-style {
  margin-left: 40px;
}

/* general button style */
.my-button-style {
  height: 100px;
  width: 150px;
}

Here is a fiddle: https://jsfiddle.net/caeLosby/10/

It is similar to some of the existing answers but it does not set the margin on the first button. For example in the case

<button id="btn1" class="my-button-style"/>
<button id="btn2" class="my-button-style"/>

only btn2 will get the margin.

For further information see https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_combinator

Trying to get PyCharm to work, keep getting "No Python interpreter selected"

I got the same issue when i newly installed pycharm in my windows 10 machine.

  • download python setup

  • install this solved my problem.

for more help visit goodluck

During the install of python make sure you have "Install for all users" selected. Uninstall python and do a custom install and check "Install for all users"

YouTube API to fetch all videos on a channel

Since everyone answering this question has problems due to the 500 video limit here's an alternate solution using youtube_dl in Python 3. Also, no API key is needed.

  1. Install youtube_dl: sudo pip3 install youtube-dl
  2. Find out your target channel's channel id. The ID is going to start with UC. Replace the C for Channel with U for Upload (i.e. UU...), this is the upload playlist.
  3. Use the playlist downloader feature from youtube-dl. Ideally you do NOT want to download every video in the playlist which is the default, but only the metadata.

Example (warning -- takes tens of minutes):

import youtube_dl, pickle

             # UCVTyTA7-g9nopHeHbeuvpRA is the channel id (1517+ videos)
PLAYLIST_ID = 'UUVTyTA7-g9nopHeHbeuvpRA'  # Late Night with Seth Meyers

with youtube_dl.YoutubeDL({'ignoreerrors': True}) as ydl:

    playd = ydl.extract_info(PLAYLIST_ID, download=False)

    with open('playlist.pickle', 'wb') as f:
        pickle.dump(playd, f, pickle.HIGHEST_PROTOCOL)

    vids = [vid for vid in playd['entries'] if 'A Closer Look' in vid['title']]
    print(sum('Trump' in vid['title'] for vid in vids), '/', len(vids))

Is there a way to run Python on Android?

You can run your Python code using sl4a. sl4a supports Python, Perl, JRuby, Lua, BeanShell, JavaScript, Tcl, and shell script.

You can learn sl4a Python Examples.

Switch statement with returns -- code correctness

Keep the breaks - you're less likely to run into trouble if/when you edit the code later if the breaks are already in place.

Having said that, it's considered by many (including me) to be bad practice to return from the middle of a function. Ideally a function should have one entry point and one exit point.

How to return string value from the stored procedure

change your

return @str1+'present in the string' ;

to

set @r = @str1+'present in the string' 

including parameters in OPENQUERY

SELECT field1 FROM OPENQUERY 
                   ([NameOfLinkedSERVER], 
                   'SELECT field1 FROM TABLENAME') 
                           WHERE field1=@someParameter T1 
                                 INNER JOIN MYSQLSERVER.DATABASE.DBO.TABLENAME           
                                 T2 ON T1.PK = T2.PK

unary operator expected in shell script when comparing null value with string

Why all people want to use '==' instead of simple '=' ? It is bad habit! It used only in [[ ]] expression. And in (( )) too. But you may use just = too! It work well in any case. If you use numbers, not strings use not parcing to strings and then compare like strings but compare numbers. like that

let -i i=5 # garantee that i is nubmber
test $i -eq 5 && echo "$i is equal 5" || echo "$i not equal 5"

It's match better and quicker. I'm expert in C/C++, Java, JavaScript. But if I use bash i never use '==' instead '='. Why you do so?

Android Lint contentDescription warning

Disabling Lint warnings will easily get you into trouble later on. You're better off just specifying contentDescription for all of your ImageViews. If you don't need a description, then just use:

android:contentDescription="@null"

How can I check if a program exists from a Bash script?

I have a function defined in my .bashrc that makes this easier.

command_exists () {
    type "$1" &> /dev/null ;
}

Here's an example of how it's used (from my .bash_profile.)

if command_exists mvim ; then
    export VISUAL="mvim --nofork"
fi

pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available

I ran into this problem! I accidentally installed the 32-bit version of Miniconda3. Make sure you choose the 64 bit version!

How to use MapView in android using google map V2?

yes you can use MapView in v2... for further details you can get help from this

https://gist.github.com/joshdholtz/4522551


SomeFragment.java

public class SomeFragment extends Fragment implements OnMapReadyCallback{
 
    MapView mapView;
    GoogleMap map;
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.some_layout, container, false);
 
        // Gets the MapView from the XML layout and creates it
        mapView = (MapView) v.findViewById(R.id.mapview);
        mapView.onCreate(savedInstanceState);
 
    
        mapView.getMapAsync(this);
        
 
        return v;
    }
 
   @Override
   public void onMapReady(GoogleMap googleMap) {
       map = googleMap;
       map.getUiSettings().setMyLocationButtonEnabled(false);
       map.setMyLocationEnabled(true);
       /*
       //in old Api Needs to call MapsInitializer before doing any CameraUpdateFactory call
        try {
            MapsInitializer.initialize(this.getActivity());
        } catch (GooglePlayServicesNotAvailableException e) {
            e.printStackTrace();
        } 
       */
        
        // Updates the location and zoom of the MapView
        /*CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
        map.animateCamera(cameraUpdate);*/
        map.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(43.1, -87.9)));

    }

    @Override
    public void onResume() {
        mapView.onResume();
        super.onResume();
    }


    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }
 
    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }
 
    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }
 
}

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example"
    android:versionCode="1"
    android:versionName="1.0" >
    
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>
    
    <permission
        android:name="com.example.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>
    <uses-permission android:name="com.example.permission.MAPS_RECEIVE"/>
    
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="your_key"/>
        
        <activity
            android:name=".HomeActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    
    </application>
 
</manifest>

some_layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    
    <com.google.android.gms.maps.MapView android:id="@+id/mapview"
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" />
 
</LinearLayout>

javascript getting my textbox to display a variable

_x000D_
_x000D_
function myfunction() {_x000D_
  var first = document.getElementById("textbox1").value;_x000D_
  var second = document.getElementById("textbox2").value;_x000D_
  var answer = parseFloat(first) + parseFloat(second);_x000D_
_x000D_
  var textbox3 = document.getElementById('textbox3');_x000D_
  textbox3.value = answer;_x000D_
}
_x000D_
<input type="text" name="textbox1" id="textbox1" /> + <input type="text" name="textbox2" id="textbox2" />_x000D_
<input type="submit" name="button" id="button1" onclick="myfunction()" value="=" />_x000D_
<br/> Your answer is:--_x000D_
<input type="text" name="textbox3" id="textbox3" readonly="true" />
_x000D_
_x000D_
_x000D_

Linux: Which process is causing "device busy" when doing umount?

If you still can not unmount or remount your device after stopping all services and processes with open files, then there may be a swap file or swap partition keeping your device busy. This will not show up with fuser or lsof. Turn off swapping with:

sudo swapoff -a

You could check beforehand and show a summary of any swap partitions or swap files with:

swapon -s

or:

cat /proc/swaps

As an alternative to using the command sudo swapoff -a, you might also be able to disable the swap by stopping a service or systemd unit. For example:

sudo systemctl stop dphys-swapfile

or:

sudo systemctl stop var-swap.swap

In my case, turning off swap was necessary, in addition to stopping any services and processes with files open for writing, so that I could remount my root partition as read only in order to run fsck on my root partition without rebooting. This was necessary on a Raspberry Pi running Raspbian Jessie.

How to hide a div with jQuery?

$("myDiv").hide(); and $("myDiv").show(); does not work in Internet Explorer that well.

The way I got around this was to get the html content of myDiv using .html().

I then wrote it to a newly created DIV. I then appended the DIV to the body and appended the content of the variable Content to the HiddenField then read that contents from the newly created div when I wanted to show the DIV.

After I used the .remove() method to get rid of the DIV that was temporarily holding my DIVs html.

var Content = $('myDiv').html(); 
        $('myDiv').empty();
        var hiddenField = $("<input type='hidden' id='myDiv2'>");
        $('body').append(hiddenField);
        HiddenField.val(Content);

and then when I wanted to SHOW the content again.

        var Content = $('myDiv');
        Content.html($('#myDiv2').val());
        $('#myDiv2').remove();

This was more reliable that the .hide() & .show() methods.

Get current value selected in dropdown using jQuery

To get the value of a drop-down (select) element, just use val().

$('._someDropDown').live('change', function(e) {
  alert($(this).val());
});

If you want to the text of the selected option, using this:

$('._someDropDown').live('change', function(e) {
  alert($('[value=' + $(this).val() + ']', this).text());
});

.mp4 file not playing in chrome

Encountering the same problem, I solved this by reconverting the file with default mp4 settings in iMovie.

GROUP BY with MAX(DATE)

You cannot include non-aggregated columns in your result set which are not grouped. If a train has only one destination, then just add the destination column to your group by clause, otherwise you need to rethink your query.

Try:

SELECT t.Train, t.Dest, r.MaxTime
FROM (
      SELECT Train, MAX(Time) as MaxTime
      FROM TrainTable
      GROUP BY Train
) r
INNER JOIN TrainTable t
ON t.Train = r.Train AND t.Time = r.MaxTime

Angular 2 Show and Hide an element

When you don't care about removing the Html Dom-Element, use *ngIf.

Otherwise, use this:

<div [style.visibility]="(numberOfUnreadAlerts == 0) ? 'hidden' : 'visible' ">
   COUNTER: {{numberOfUnreadAlerts}} 
</div>

Use Excel pivot table as data source for another Pivot Table

You have to convert the pivot to values first before you can do that:

  • Remove the subtotals
  • Repeat the row items
  • Copy / Paste values
  • Insert a new pivot table

Aren't promises just callbacks?

Promises are not callbacks, both are programming idioms that facilitate async programming. Using an async/await-style of programming using coroutines or generators that return promises could be considered a 3rd such idiom. A comparison of these idioms across different programming languages (including Javascript) is here: https://github.com/KjellSchubert/promise-future-task

How can I protect my .NET assemblies from decompilation?

No obsfuscator can protect your application, not even any one described here. See this link, it's an deobsfuscator which can deobsfuscate almost every obsfuscator out there.

https://github.com/0xd4d/de4dot

The best way which can help you (but remember that they are also not full prof) is to use mixed codes, code your important codes in unmanaged language and make a DLL like in C or C++ and then protect them either with Armageddon or Themida. Themida is not for every cracker, it's one of the best protector in the market, it can also protect your .NET software.

Detect if string contains any spaces

What you have will find a space anywhere in the string, not just between words.

If you want to find any kind of whitespace, you can use this, which uses a regular expression:

if (/\s/.test(str)) {
    // It has any kind of whitespace
}

\s means "any whitespace character" (spaces, tabs, vertical tabs, formfeeds, line breaks, etc.), and will find that character anywhere in the string.

According to MDN, \s is equivalent to: [ \f\n\r\t\v?\u00a0\u1680?\u180e\u2000?\u2001\u2002?\u2003\u2004?\u2005\u2006?\u2007\u2008?\u2009\u200a?\u2028\u2029??\u202f\u205f?\u3000].


For some reason, I originally read your question as "How do I see if a string contains only spaces?" and so I answered with the below. But as @CrazyTrain points out, that's not what the question says. I'll leave it, though, just in case...

If you mean literally spaces, a regex can do it:

if (/^ *$/.test(str)) {
    // It has only spaces, or is empty
}

That says: Match the beginning of the string (^) followed by zero or more space characters followed by the end of the string ($). Change the * to a + if you don't want to match an empty string.

If you mean whitespace as a general concept:

if (/^\s*$/.test(str)) {
    // It has only whitespace
}

That uses \s (whitespace) rather than the space, but is otherwise the same. (And again, change * to + if you don't want to match an empty string.)

Doing HTTP requests FROM Laravel to an external API

Basic Solution for Laravel 8 is

use Illuminate\Support\Facades\Http;

$response = Http::get('http://example.com');

I had conflict between "GuzzleHTTP sending requests" and "Illuminate\Http\Request;" don't ask me why... [it's here to be searchable]

So looking for 1sec i found in Laravel 8 Doc...

**Guzzle is inside the Laravel 8 Http Request !**

https://laravel.com/docs/8.x/http-client#making-requests

as you can see

https://laravel.com/docs/8.x/http-client#introduction

Laravel provides an expressive, minimal API around the Guzzle HTTP client, allowing you to quickly make outgoing HTTP requests to communicate with other web applications. Laravel's wrapper around Guzzle is focused on its most common use cases and a wonderful developer experience.

It worked for me very well, have fun and if helpful point up!

Click events on Pie Charts in Chart.js

To successfully track click events and on what graph element the user clicked, I did the following in my .js file I set up the following variables:

vm.chartOptions = {
    onClick: function(event, array) {
        let element = this.getElementAtEvent(event);
        if (element.length > 0) {
            var series= element[0]._model.datasetLabel;
            var label = element[0]._model.label;
            var value = this.data.datasets[element[0]._datasetIndex].data[element[0]._index];
        }
    }
};
vm.graphSeries = ["Series 1", "Serries 2"];
vm.chartLabels = ["07:00", "08:00", "09:00", "10:00"];
vm.chartData = [ [ 20, 30, 25, 15 ], [ 5, 10, 100, 20 ] ];

Then in my .html file I setup the graph as follows:

<canvas id="releaseByHourBar" 
    class="chart chart-bar"
    chart-data="vm.graphData"
    chart-labels="vm.graphLabels" 
    chart-series="vm.graphSeries"
    chart-options="vm.chartOptions">
</canvas>

How do I create a new class in IntelliJ without using the mouse?

If you use Mac, you are in luck. One can change the keymap for Intellij as Mac OS X, then you can use option+C.

Sorting Values of Set

Strings are sorted lexicographically. The behavior you're seeing is correct.

Define your own comparator to sort the strings however you prefer.

It would also work the way you're expecting (5 as the first element) if you changed your collections to Integer instead of using String.