Programs & Examples On #Renderaction

RenderAction is an ASP.NET MVC helper method, available starting in the 2nd version, that calls from a view and outputs the results of the action in place within the view.

Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction

Difference is first one returns an MvcHtmlString but second (Render..) outputs straight to the response.

Browse files and subfolders in Python

In python 3 you can use os.scandir():

for i in os.scandir(path):
    if i.is_file():
        print('File: ' + i.path)
    elif i.is_dir():
        print('Folder: ' + i.path)

Why does jQuery or a DOM method such as getElementById not find the element?

My solution was to not use the id of an anchor element: <a id='star_wars'>Place to jump to</a>. Apparently blazor and other spa frameworks have issues jumping to anchors on the same page. To get around that I had to use document.getElementById('star_wars'). However this didn't work until I put the id in a paragraph element instead: <p id='star_wars'>Some paragraph<p>.

Example using bootstrap:

<button class="btn btn-link" onclick="document.getElementById('star_wars').scrollIntoView({behavior:'smooth'})">Star Wars</button>

... lots of other text

<p id="star_wars">Star Wars is an American epic...</p>

Datatable vs Dataset

A DataTable object represents tabular data as an in-memory, tabular cache of rows, columns, and constraints. The DataSet consists of a collection of DataTable objects that you can relate to each other with DataRelation objects.

How to stop text from taking up more than 1 line?

Sometimes using &nbsp; instead of spaces will work. Clearly it has drawbacks, though.

CSS background image alt attribute

In this Yahoo Developer Network (archived link) article it is suggested that if you absolutely must use a background-image instead of img element and alt attribute, use ARIA attributes as follows:

<div role="img" aria-label="adorable puppy playing on the grass">
  ...
</div>

The use case in the article describes how Flickr chose to use background images because performance was greatly improved on mobile devices.

Can "git pull --all" update all my local branches?

The following one-liner fast-forwards all branches that have an upstream branch if possible, and prints an error otherwise:

git branch \
  --format "%(if)%(upstream:short)%(then)git push . %(upstream:short):%(refname:short)%(end)" |
  sh

How does it work?

It uses a custom format with the git branch command. For each branch that has an upstream branch, it prints a line with the following pattern:

git push . <remote-ref>:<branch>

This can be piped directly into sh (assuming that the branch names are well-formed). Omit the | sh to see what it's doing.

Caveats

The one-liner will not contact your remotes. Issue a git fetch or git fetch --all before running it.

The currently checked-out branch will not be updated with a message like

! [remote rejected] origin/master -> master (branch is currently checked out)

For this, you can resort to regular git pull --ff-only .

Alias

Add the following to your .gitconfig so that git fft performs this command:

[alias]
        fft = !sh -c 'git branch --format \"%(if)%(upstream:short)%(then)git push . %(upstream:short):%(refname:short)%(end)\" | sh' -

See also my .gitconfig. The alias is a shorthand to "fast-forward tracking (branches)".

round up to 2 decimal places in java?

String roundOffTo2DecPlaces(float val)
{
    return String.format("%.2f", val);
}

html - table row like a link

//Style
  .trlink {
    color:blue;
  }
  .trlink:hover {
    color:red;
  }

<tr class="trlink" onclick="function to navigate to a page goes here">
<td>linktext</td>
</tr>

Something along these lines perhaps? Though it does use JS, but that's only way to make a row (tr) clickable.

Unless you have a single cell with an anchor tag that fills the entire cell.

And then, you shouldn't be using a table anyhow.

How to enter a formula into a cell using VBA?

You aren't building your formula right.

Worksheets("EmployeeCosts").Range("B" & var1a).Formula =  "=SUM(H5:H" & var1a & ")"

This does the same as the following lines do:

Dim myFormula As String
myFormula = "=SUM(H5:H"
myFormula = myFormula & var1a
myformula = myformula & ")"

which is what you are trying to do.

Also, you want to have the = at the beginning of the formala.

Difference between __getattr__ vs __getattribute__

  • getattribute: Is used to retrieve an attribute from an instance. It captures every attempt to access an instance attribute by using dot notation or getattr() built-in function.
  • getattr: Is executed as the last resource when attribute is not found in an object. You can choose to return a default value or to raise AttributeError.

Going back to the __getattribute__ function; if the default implementation was not overridden; the following checks are done when executing the method:

  • Check if there is a descriptor with the same name (attribute name) defined in any class in the MRO chain (method object resolution)
  • Then looks into the instance’s namespace
  • Then looks into the class namespace
  • Then into each base’s namespace and so on.
  • Finally, if not found, the default implementation calls the fallback getattr() method of the instance and it raises an AttributeError exception as default implementation.

This is the actual implementation of the object.__getattribute__ method:

.. c:function:: PyObject* PyObject_GenericGetAttr(PyObject *o, PyObject *name) Generic attribute getter function that is meant to be put into a type object's tp_getattro slot. It looks for a descriptor in the dictionary of classes in the object's MRO as well as an attribute in the object's :attr:~object.dict (if present). As outlined in :ref:descriptors, data descriptors take preference over instance attributes, while non-data descriptors don't. Otherwise, an :exc:AttributeError is raised.

Is an entity body allowed for an HTTP DELETE request?

It seems ElasticSearch uses this: https://www.elastic.co/guide/en/elasticsearch/reference/5.x/search-request-scroll.html#_clear_scroll_api

Which means Netty support this.

Like mentionned in comments it may not be the case anymore

Navigation bar show/hide

In Swift 4.2 and Xcode 10

self.navigationController?.isNavigationBarHidden = true  //Hide
self.navigationController?.isNavigationBarHidden = false  //Show

If you don't want to display Navigation bar only in 1st VC, but you want display in 2nd VC onword's

In your 1st VC write this code.

override func viewWillAppear(_ animated: Bool) {
    self.navigationController?.isNavigationBarHidden = true  //Hide
}

override func viewWillDisappear(_ animated: Bool) {
    self.navigationController?.isNavigationBarHidden = false  //Show
}

jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

This is a syntax issue, the jQuery library included with WordPress loads in "no conflict" mode. This is to prevent compatibility problems with other javascript libraries that WordPress can load. In "no-confict" mode, the $ shortcut is not available and the longer jQuery is used, i.e.

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

By including the $ in parenthesis after the function call you can then use this shortcut within the code block.

For full details see WordPress Codex

Django Multiple Choice Field / Checkbox Select Multiple

Brant's solution is absolutely correct, but I needed to modify it to make it work with multiple select checkboxes and commit=false. Here is my solution:

models.py

class Choices(models.Model):
    description = models.CharField(max_length=300)

class Profile(models.Model):
   user = models.ForeignKey(User, blank=True, unique=True, verbose_name_('user'))
   the_choices = models.ManyToManyField(Choices)

forms.py

class ProfileForm(forms.ModelForm):
    the_choices = forms.ModelMultipleChoiceField(queryset=Choices.objects.all(), required=False, widget=forms.CheckboxSelectMultiple)

    class Meta:
        model = Profile
        exclude = ['user']

views.py

if request.method=='POST':
    form = ProfileForm(request.POST)
    if form.is_valid():
        profile = form.save(commit=False)
        profile.user = request.user
        profile.save()
        form.save_m2m() # needed since using commit=False
    else:
        form = ProfileForm()

return render_to_response(template_name, {"profile_form": form}, context_instance=RequestContext(request))

How to open an existing project in Eclipse?

If you closed the project, you can open it again easily by going to the top bar (alt) > ?Project > Open Project Top menu > Project > Open Project You will get a menu where you can open closed projects that can be preventing you from opening these projects through the File menu. The window that lets you open any closed projects after you go through the menu listed previously

How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?

An alternative to the custom filter is to create an extension method to serialize any object to JSON.

public static class ObjectExtensions
{
    /// <summary>Serializes the object to a JSON string.</summary>
    /// <returns>A JSON string representation of the object.</returns>
    public static string ToJson(this object value)
    {
        var settings = new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver(),
            Converters = new List<JsonConverter> { new StringEnumConverter() }
        };

        return JsonConvert.SerializeObject(value, settings);
    }
}

Then call it when returning from the controller action.

return Content(person.ToJson(), "application/json");

Finding all cycles in a directed graph

To clarify:

  1. Strongly Connected Components will find all subgraphs that have at least one cycle in them, not all possible cycles in the graph. e.g. if you take all strongly connected components and collapse/group/merge each one of them into one node (i.e. a node per component), you'll get a tree with no cycles (a DAG actually). Each component (which is basically a subgraph with at least one cycle in it) can contain many more possible cycles internally, so SCC will NOT find all possible cycles, it will find all possible groups that have at least one cycle, and if you group them, then the graph will not have cycles.

  2. to find all simple cycles in a graph, as others mentioned, Johnson's algorithm is a candidate.

Saving numpy array to txt file row wise

just

' '.join(a)

and write this output to a file.

CRON job to run on the last day of the month

What about this?

edit user's .bashprofile adding:

export LAST_DAY_OF_MONTH=$(cal | awk '!/^$/{ print $NF }' | tail -1)

Then add this entry to crontab:

mm hh * * 1-7 [[ $(date +'%d') -eq $LAST_DAY_OF_MONTH ]] && /absolutepath/myscript.sh

How to create large PDF files (10MB, 50MB, 100MB, 200MB, 500MB, 1GB, etc.) for testing purposes?

If you want to generate a file in the Windows, then, please follow the below steps:

  1. Go to a directory where you want to save the generated file
  2. Open the command prompt on that directory
  3. Run this fsutil file createnew [filename].[extension] [# of bytes] command. For example fsutil file createnew test.pdf 999999999
  4. 95.3 MB File will be generated

Update: The generated file will not be a valid pdf file. It just holds the given size.

Waiting on a list of Future

The CompletionService will take your Callables with the .submit() method and you can retrieve the computed futures with the .take() method.

One thing you must not forget is to terminate the ExecutorService by calling the .shutdown() method. Also you can only call this method when you have saved a reference to the executor service so make sure to keep one.

Example code - For a fixed number of work items to be worked on in parallel:

ExecutorService service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

CompletionService<YourCallableImplementor> completionService = 
new ExecutorCompletionService<YourCallableImplementor>(service);

ArrayList<Future<YourCallableImplementor>> futures = new ArrayList<Future<YourCallableImplementor>>();

for (String computeMe : elementsToCompute) {
    futures.add(completionService.submit(new YourCallableImplementor(computeMe)));
}
//now retrieve the futures after computation (auto wait for it)
int received = 0;

while(received < elementsToCompute.size()) {
 Future<YourCallableImplementor> resultFuture = completionService.take(); 
 YourCallableImplementor result = resultFuture.get();
 received ++;
}
//important: shutdown your ExecutorService
service.shutdown();

Example code - For a dynamic number of work items to be worked on in parallel:

public void runIt(){
    ExecutorService service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    CompletionService<CallableImplementor> completionService = new ExecutorCompletionService<CallableImplementor>(service);
    ArrayList<Future<CallableImplementor>> futures = new ArrayList<Future<CallableImplementor>>();

    //Initial workload is 8 threads
    for (int i = 0; i < 9; i++) {
        futures.add(completionService.submit(write.new CallableImplementor()));             
    }
    boolean finished = false;
    while (!finished) {
        try {
            Future<CallableImplementor> resultFuture;
            resultFuture = completionService.take();
            CallableImplementor result = resultFuture.get();
            finished = doSomethingWith(result.getResult());
            result.setResult(null);
            result = null;
            resultFuture = null;
            //After work package has been finished create new work package and add it to futures
            futures.add(completionService.submit(write.new CallableImplementor()));
        } catch (InterruptedException | ExecutionException e) {
            //handle interrupted and assert correct thread / work packet count              
        } 
    }

    //important: shutdown your ExecutorService
    service.shutdown();
}

public class CallableImplementor implements Callable{
    boolean result;

    @Override
    public CallableImplementor call() throws Exception {
        //business logic goes here
        return this;
    }

    public boolean getResult() {
        return result;
    }

    public void setResult(boolean result) {
        this.result = result;
    }
}

Set content of iframe

I needed to reuse the same iframe and replace the content each time. I've tried a few ways and this worked for me:

// Set the iframe's src to about:blank so that it conforms to the same-origin policy 
iframeElement.src = "about:blank";

// Set the iframe's new HTML
iframeElement.contentWindow.document.open();
iframeElement.contentWindow.document.write(newHTML);
iframeElementcontentWindow.document.close();

Here it is as a function:

function replaceIframeContent(iframeElement, newHTML)
{
    iframeElement.src = "about:blank";
    iframeElement.contentWindow.document.open();
    iframeElement.contentWindow.document.write(newHTML);
    iframeElement.contentWindow.document.close();
}

UPDATE with CASE and IN - Oracle

"The list are variables/paramaters that is pre-defined as comma separated lists". Do you mean that your query is actually

UPDATE tab1   SET budgpost_gr1=     
CASE  WHEN (budgpost in ('1001,1012,50055'))  THEN 'BP_GR_A'   
      WHEN (budgpost in ('5,10,98,0'))  THEN 'BP_GR_B'  
      WHEN (budgpost in ('11,876,7976,67465'))     
      ELSE 'Missing' END`

If so, you need a function to take a string and parse it into a list of numbers.

create type tab_num is table of number;

create or replace function f_str_to_nums (i_str in varchar2) return tab_num is
  v_tab_num tab_num := tab_num();
  v_start   number := 1;
  v_end     number;
  v_delim   VARCHAR2(1) := ',';
  v_cnt     number(1) := 1;
begin
  v_end := instr(i_str||v_delim,v_delim,1, v_start);
  WHILE v_end > 0 LOOP
    v_cnt := v_cnt + 1;
    v_tab_num.extend;
    v_tab_num(v_tab_num.count) := 
                  substr(i_str,v_start,v_end-v_start);
    v_start := v_end + 1;
    v_end := instr(i_str||v_delim,v_delim,v_start);
  END LOOP;
  RETURN v_tab_num;
end;
/

Then you can use the function like so:

select column_id, 
   case when column_id in 
     (select column_value from table(f_str_to_nums('1,2,3,4'))) then 'red' 
   else 'blue' end
from  user_tab_columns
where table_name = 'EMP'

AngularJS: Basic example to use authentication in Single Page Application

In angularjs you can create the UI part, service, Directives and all the part of angularjs which represent the UI. It is nice technology to work on.

As any one who new into this technology and want to authenticate the "User" then i suggest to do it with the power of c# web api. for that you can use the OAuth specification which will help you to built a strong security mechanism to authenticate the user. once you build the WebApi with OAuth you need to call that api for token:

_x000D_
_x000D_
var _login = function (loginData) {_x000D_
 _x000D_
        var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password;_x000D_
 _x000D_
        var deferred = $q.defer();_x000D_
 _x000D_
        $http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) {_x000D_
 _x000D_
            localStorageService.set('authorizationData', { token: response.access_token, userName: loginData.userName });_x000D_
 _x000D_
            _authentication.isAuth = true;_x000D_
            _authentication.userName = loginData.userName;_x000D_
 _x000D_
            deferred.resolve(response);_x000D_
 _x000D_
        }).error(function (err, status) {_x000D_
            _logOut();_x000D_
            deferred.reject(err);_x000D_
        });_x000D_
 _x000D_
        return deferred.promise;_x000D_
 _x000D_
    };_x000D_
 
_x000D_
_x000D_
_x000D_

and once you get the token then you request the resources from angularjs with the help of Token and access the resource which kept secure in web Api with OAuth specification.

Please have a look into the below article for more help:-

http://bitoftech.net/2014/06/09/angularjs-token-authentication-using-asp-net-web-api-2-owin-asp-net-identity/

How do I do multiple CASE WHEN conditions using SQL Server 2008?

This can be an efficient way of performing different tests on a single statement

select
case colour_txt 
  when 'red' then 5 
  when 'green' then 4 
  when 'orange' then 3
else 0 
end as Pass_Flag

this only works on equality comparisons!

Angular2 handling http response

Update alpha 47

As of alpha 47 the below answer (for alpha46 and below) is not longer required. Now the Http module handles automatically the errores returned. So now is as easy as follows

http
  .get('Some Url')
  .map(res => res.json())
  .subscribe(
    (data) => this.data = data,
    (err) => this.error = err); // Reach here if fails

Alpha 46 and below

You can handle the response in the map(...), before the subscribe.

http
  .get('Some Url')
  .map(res => {
    // If request fails, throw an Error that will be caught
    if(res.status < 200 || res.status >= 300) {
      throw new Error('This request has failed ' + res.status);
    } 
    // If everything went fine, return the response
    else {
      return res.json();
    }
  })
  .subscribe(
    (data) => this.data = data, // Reach here if res.status >= 200 && <= 299
    (err) => this.error = err); // Reach here if fails

Here's a plnkr with a simple example.

Note that in the next release this won't be necessary because all status codes below 200 and above 299 will throw an error automatically, so you won't have to check them by yourself. Check this commit for more info.

The activity must be exported or contain an intent-filter

I changed the Select Run/Debug Configuration from my MainActivity to App and it started working. Select App configuration snapshot:

enter image description here

How do I count columns of a table

SELECT count(*)
FROM information_schema.columns
WHERE table_name = 'tbl_ifo'

Java Multithreading concept and join() method

First of all, when you create ob1 then constructor is called and it starts execution. At that time t.start() also runs in separate thread. Remember when a new thread is created, it runs parallely to main thread. And thats why main start execution again with next statement.

And Join() statement is used to prevent the child thread from becoming orphan. Means if you did'nt call join() in your main class, then main thread will exit after its execution and child thread will be still there executing the statements. Join() will wait until all child thread complete its execution and then only main method will exit.

Go through this article, helps a lot.

INSTALL_FAILED_USER_RESTRICTED : android studio using redmi 4 device

For me only installing from Google drive worked.

How do I display a decimal value to 2 decimal places?

If you need to keep only 2 decimal places (i.e. cut off all the rest of decimal digits):

decimal val = 3.14789m;
decimal result = Math.Floor(val * 100) / 100; // result = 3.14

If you need to keep only 3 decimal places:

decimal val = 3.14789m;
decimal result = Math.Floor(val * 1000) / 1000; // result = 3.147

How to convert local time string to UTC?

I've had the most success with python-dateutil:

from dateutil import tz

def datetime_to_utc(date):
    """Returns date in UTC w/o tzinfo"""
    return date.astimezone(tz.gettz('UTC')).replace(tzinfo=None) if date.tzinfo else date

How do I check which version of NumPy I'm using?

From the command line, you can simply issue:

python -c "import numpy; print(numpy.version.version)"

Or:

python -c "import numpy; print(numpy.__version__)"

Best way to iterate through a Perl array

If you only care about the elements of @Array, use:

for my $el (@Array) {
# ...
}

or

If the indices matter, use:

for my $i (0 .. $#Array) {
# ...
}

Or, as of perl 5.12.1, you can use:

while (my ($i, $el) = each @Array) {
# ...
}

If you need both the element and its index in the body of the loop, I would expect using each to be the fastest, but then you'll be giving up compatibility with pre-5.12.1 perls.

Some other pattern than these might be appropriate under certain circumstances.

load Js file in HTML

If this is your detail.html I don't see where do you load detail.js? Maybe this

<script src="js/index.js"></script>

should be this

<script src="js/detail.js"></script>

?

Java check if boolean is null

boolean is a primitive type, and therefore can not be null.

Its boxed type, Boolean, can be null.

The function is probably returning a Boolean as opposed to a boolean, so assigning the result to a Boolean-type variable will allow you to test for nullity.

Disable scrolling when touch moving certain element

To my surprise, the "preventDefault()" method is working for me on latest Google Chrome (version 85) on iOS 13.7. It also works on Safari on the same device and also working on my Android 8.0 tablet. I am currently implemented it for 2D view on my site here: https://papercraft-maker.com

Android Drawing Separator/Divider Line in Layout?

Here is your answer..this is an example to draw line between controls...

<TextView
            android:id="@+id/textView1"
            style="@style/behindMenuItemLabel1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="1dp"
            android:text="FaceBook Feeds" />

         <View
             android:layout_width="fill_parent"
             android:layout_height="2dp"
             android:background="#d13033"/>

         <ListView
            android:id="@+id/list1"
            android:layout_width="350dp"
            android:layout_height="50dp" />

This code draw line between two controls...

How do I check if an object's type is a particular subclass in C++?

I was thinking along the lines of using typeid()...

Well, yes, it could be done by comparing: typeid().name(). If we take the already described situation, where:

class Base;
class A : public Base {...};
class B : public Base {...};

void foo(Base *p)
{
  if(/* p is A */) /* do X */
  else /* do Y */
}

A possible implementation of foo(Base *p) would be:

#include <typeinfo>

void foo(Base *p)
{
    if(typeid(*p) == typeid(A))
    {
        // the pointer is pointing to the derived class A
    }  
    else if (typeid(*p).name() == typeid(B).name()) 
    {
        // the pointer is pointing to the derived class B
    }
}

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

O(1) always execute in the same time regardless of dataset n. An example of O(1) would be an ArrayList accessing its element with index.

O(n) also known as Linear Order, the performance will grow linearly and in direct proportion to the size of the input data. An example of O(n) would be an ArrayList insertion and deletion at random position. As each subsequent insertion/deletion at random position will cause the elements in the ArrayList to shift left right of its internal array in order to maintain its linear structure, not to mention about the creation of a new arrays and the copying of elements from the old to new array which takes up expensive processing time hence, detriment the performance.

How to run a Powershell script from the command line and pass a directory as a parameter

Change your code to the following :

Function Foo($directory)
    {
        echo $directory
    }

    if ($args.Length -eq 0)
    {
        echo "Usage: Foo <directory>"
    }
    else
    {
        Foo([string[]]$args)
    }

And then invoke it as:

powershell -ExecutionPolicy RemoteSigned -File "c:\foo.ps1" "c:\Documents and Settings" "c:\test"

How to remove item from a python list in a loop?

x = [i for i in x if len(i)==2]

CSS3 Transition - Fade out effect

Here is another way to do the same.

fadeIn effect

.visible {
  visibility: visible;
  opacity: 1;
  transition: opacity 2s linear;
}

fadeOut effect

.hidden {
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s 2s, opacity 2s linear;
}

UPDATE 1: I found more up-to-date tutorial CSS3 Transition: fadeIn and fadeOut like effects to hide show elements and Tooltip Example: Show Hide Hint or Help Text using CSS3 Transition here with sample code.

UPDATE 2: (Added details requested by @big-money)

When showing the element (by switching to the visible class), we want the visibility:visible to kick in instantly, so it’s ok to transition only the opacity property. And when hiding the element (by switching to the hidden class), we want to delay the visibility:hidden declaration, so that we can see the fade-out transition first. We’re doing this by declaring a transition on the visibility property, with a 0s duration and a delay. You can see a detailed article here.

I know I am too late to answer but posting this answer to save others time. Hope it helps you!!

Browser detection in JavaScript?

I know I'm WAY late to this question, but figured I'd throw my snippets up here. A lot of the answers here are OK, and, as one points out, it's generally best to use feature detection rather than rely on the userAgent string. However, if you are going to go that route, I've written a complete snippet, as well as an alternate jQuery implementation to replace the depricated $.browser.


Vanilla JS

My first snippet simply adds four properties to the navigator object: browser, version, mobile, & webkit.

jsFiddle


/** navigator [extended]
 *  Simply extends Browsers navigator Object to include browser name, version number, and mobile type (if available).
 *
 *  @property {String} browser The name of the browser.
 *  @property {Double} version The current Browser version number.
 *  @property {String|Boolean} mobile Will be `false` if is not found to be mobile device. Else, will be best guess Name of Mobile Device (not to be confused with browser name)
 *  @property {Boolean} webkit If is webkit or not.
 */
;(function(){function c(){try{switch(!0){case /MSIE|Trident/i.test(navigator.userAgent):return"MSIE";case /Chrome/.test(navigator.userAgent):return"Chrome";case /Opera/.test(navigator.userAgent):return"Opera";case /Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(navigator.userAgent):return/Silk/i.test(navigator.userAgent)?"Silk":"Kindle";case /BlackBerry/.test(navigator.userAgent):return"BlackBerry";case /PlayBook/.test(navigator.userAgent):return"PlayBook";case /BB[0-9]{1,}; Touch/.test(navigator.userAgent):return"Blackberry";
case /Android/.test(navigator.userAgent):return"Android";case /Safari/.test(navigator.userAgent):return"Safari";case /Firefox/.test(navigator.userAgent):return"Mozilla";case /Nokia/.test(navigator.userAgent):return"Nokia"}}catch(a){console.debug("ERROR:setBrowser\t",a)}}function d(){try{switch(!0){case /Sony[^ ]*/i.test(navigator.userAgent):return"Sony";case /RIM Tablet/i.test(navigator.userAgent):return"RIM Tablet";case /BlackBerry/i.test(navigator.userAgent):return"BlackBerry";case /iPhone/i.test(navigator.userAgent):return"iPhone";
case /iPad/i.test(navigator.userAgent):return"iPad";case /iPod/i.test(navigator.userAgent):return"iPod";case /Opera Mini/i.test(navigator.userAgent):return"Opera Mini";case /IEMobile/i.test(navigator.userAgent):return"IEMobile";case /BB[0-9]{1,}; Touch/i.test(navigator.userAgent):return"BlackBerry";case /Nokia/i.test(navigator.userAgent):return"Nokia";case /Android/i.test(navigator.userAgent):return"Android"}}catch(a){console.debug("ERROR:setMobile\t",a)}return!1}function e(){try{switch(!0){case /MSIE|Trident/i.test(navigator.userAgent):return/Trident/i.test(navigator.userAgent)&&
/rv:([0-9]{1,}[\.0-9]{0,})/.test(navigator.userAgent)?parseFloat(navigator.userAgent.match(/rv:([0-9]{1,}[\.0-9]{0,})/)[1].replace(/[^0-9\.]/g,"")):/MSIE/i.test(navigator.userAgent)&&0<parseFloat(navigator.userAgent.split("MSIE")[1].replace(/[^0-9\.]/g,""))?parseFloat(navigator.userAgent.split("MSIE")[1].replace(/[^0-9\.]/g,"")):"Edge";case /Chrome/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("Chrome/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""));case /Opera/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("Version/")[1].replace(/[^0-9\.]/g,
""));case /Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(navigator.userAgent):if(/Silk/i.test(navigator.userAgent))return parseFloat(navigator.userAgent.split("Silk/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""));if(/Kindle/i.test(navigator.userAgent)&&/Version/i.test(navigator.userAgent))return parseFloat(navigator.userAgent.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""));case /BlackBerry/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("/")[1].replace(/[^0-9\.]/g,
""));case /PlayBook/.test(navigator.userAgent):case /BB[0-9]{1,}; Touch/.test(navigator.userAgent):case /Safari/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""));case /Firefox/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split(/Firefox\//i)[1].replace(/[^0-9\.]/g,""));case /Android/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,
""));case /Nokia/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("Browser")[1].replace(/[^0-9\.]/g,""))}}catch(a){console.debug("ERROR:setVersion\t",a)}}a:{try{if(navigator&&navigator.userAgent){navigator.browser=c();navigator.mobile=d();navigator.version=e();var b;b:{try{b=/WebKit/i.test(navigator.userAgent);break b}catch(a){console.debug("ERROR:setWebkit\t",a)}b=void 0}navigator.webkit=b;break a}}catch(a){}throw Error("Browser does not support `navigator` Object |OR| has undefined `userAgent` property.");
}})();
/*  simple c & p of above   */

Error "initializer element is not constant" when trying to initialize variable with const

In C language, objects with static storage duration have to be initialized with constant expressions, or with aggregate initializers containing constant expressions.

A "large" object is never a constant expression in C, even if the object is declared as const.

Moreover, in C language, the term "constant" refers to literal constants (like 1, 'a', 0xFF and so on), enum members, and results of such operators as sizeof. Const-qualified objects (of any type) are not constants in C language terminology. They cannot be used in initializers of objects with static storage duration, regardless of their type.

For example, this is NOT a constant

const int N = 5; /* `N` is not a constant in C */

The above N would be a constant in C++, but it is not a constant in C. So, if you try doing

static int j = N; /* ERROR */

you will get the same error: an attempt to initialize a static object with a non-constant.

This is the reason why, in C language, we predominantly use #define to declare named constants, and also resort to #define to create named aggregate initializers.

How do I remove blue "selected" outline on buttons?

You can remove this by adding !important to your outline.

button{
 outline: none !important;
}

How to change a table name using an SQL query?

rename table name :

RENAME TABLE old_tableName TO new_tableName;

for example:

RENAME TABLE company_name TO company_master;

What is the purpose of global.asax in asp.net

The Global.asax file, also known as the ASP.NET application file, is an optional file that contains code for responding to application-level and session-level events raised by ASP.NET or by HTTP modules.

http://msdn.microsoft.com/en-us/library/2027ewzw.aspx

How to POST request using RestSharp

I added this helper method to handle my POST requests that return an object I care about.

For REST purists, I know, POSTs should not return anything besides a status. However, I had a large collection of ids that was too big for a query string parameter.

Helper Method:

    public TResponse Post<TResponse>(string relativeUri, object postBody) where TResponse : new()
    {
        //Note: Ideally the RestClient isn't created for each request. 
        var restClient = new RestClient("http://localhost:999");

        var restRequest = new RestRequest(relativeUri, Method.POST)
        {
            RequestFormat = DataFormat.Json
        };

        restRequest.AddBody(postBody);

        var result = restClient.Post<TResponse>(restRequest);

        if (!result.IsSuccessful)
        {
            throw new HttpException($"Item not found: {result.ErrorMessage}");
        }

        return result.Data;
    }

Usage:

    public List<WhateverReturnType> GetFromApi()
    {
        var idsForLookup = new List<int> {1, 2, 3, 4, 5};

        var relativeUri = "/api/idLookup";

        var restResponse = Post<List<WhateverReturnType>>(relativeUri, idsForLookup);

        return restResponse;
    }

How to get screen width without (minus) scrollbar?

The safest place to get the correct width and height without the scrollbars is from the HTML element. Try this:

var width = document.documentElement.clientWidth
var height = document.documentElement.clientHeight

Browser support is pretty decent, with IE 9 and up supporting this. For OLD IE, use one of the many fallbacks mentioned here.

jQuery detect if textarea is empty

Here is my working code

function emptyTextAreaCheck(textarea, submitButtonClass) {
        if(!submitButtonClass)
            submitButtonClass = ".transSubmit";

            if($(textarea).val() == '') {
                $(submitButtonClass).addClass('disabled_button');
                $(submitButtonClass).removeClass('transSubmit');
            }

        $(textarea).live('focus keydown keyup', function(){
            if($(this).val().length == 0) {
                $(submitButtonClass).addClass('disabled_button');
                $(submitButtonClass).removeClass('transSubmit');
            } else {
                $('.disabled_button').addClass('transSubmit').css({
                    'cursor':'pointer'
                }).removeClass('disabled_button');
            }
        });
    }

how to change default python version?

Change the "default" Python by putting it ahead of the system Python on your path, for instance:

export PATH=/usr/local/bin:$PATH

How to update json file with python

def updateJsonFile():
    jsonFile = open("replayScript.json", "r") # Open the JSON file for reading
    data = json.load(jsonFile) # Read the JSON into the buffer
    jsonFile.close() # Close the JSON file

    ## Working with buffered content
    tmp = data["location"] 
    data["location"] = path
    data["mode"] = "replay"

    ## Save our changes to JSON file
    jsonFile = open("replayScript.json", "w+")
    jsonFile.write(json.dumps(data))
    jsonFile.close()

Testing for empty or nil-value string

The second clause does not need a !variable.nil? check—if evaluation reaches that point, variable.nil is guaranteed to be false (because of short-circuiting).

This should be sufficient:

variable = id if variable.nil? || variable.empty?

If you're working with Ruby on Rails, Object.blank? solves this exact problem:

An object is blank if it’s false, empty, or a whitespace string. For example, "", " ", nil, [], and {} are all blank.

NSAttributedString add text alignment

Xamarin.iOS

NSMutableParagraphStyle paragraphStyle = new NSMutableParagraphStyle();
paragraphStyle.HyphenationFactor = 1.0f;
var hyphenAttribute = new UIStringAttributes();
hyphenAttribute.ParagraphStyle = paragraphStyle;
var attributedString = new NSAttributedString(str: name, attributes: hyphenAttribute);

jQuery creating objects

May be you want this (oop in javascript)

function box(color)
{
    this.color=color;
}

var box1=new box('red');    
var box2=new box('white');    

DEMO.

For more information.

SQL Server 2008 - Case / If statements in SELECT Clause

Simple CASE expression:

CASE input_expression 
     WHEN when_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END

Searched CASE expression:

CASE
     WHEN Boolean_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END

Reference: http://msdn.microsoft.com/en-us/library/ms181765.aspx

The transaction log for database is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases

As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:

WHILE EXISTS (SELECT 1 
              FROM   YourTable 
              WHERE  <yourCondition>) 
  DELETE TOP(10000) FROM YourTable 
  WHERE  <yourCondition>

How to take MySQL database backup using MySQL Workbench?

  1. On ‘HOME’ page -- > select 'Manage Import / Export' under 'Server Administration'

  2. A box comes up... choose which server holds the data you want to back up.

  3. On the 'Export to Disk' tab, then select which databases you want to export.

  4. If you want all the tables, select option ‘Export to self-contained file’, otherwise choose the other option for a selective restore

  5. If you need advanced options, see other post, otherwise then click ‘Start Export’

How to regex in a MySQL query

In my case (Oracle), it's WHERE REGEXP_LIKE(column, 'regex.*'). See here:

SQL Function

Description


REGEXP_LIKE

This function searches a character column for a pattern. Use this function in the WHERE clause of a query to return rows matching the regular expression you specify.

...

REGEXP_REPLACE

This function searches for a pattern in a character column and replaces each occurrence of that pattern with the pattern you specify.

...

REGEXP_INSTR

This function searches a string for a given occurrence of a regular expression pattern. You specify which occurrence you want to find and the start position to search from. This function returns an integer indicating the position in the string where the match is found.

...

REGEXP_SUBSTR

This function returns the actual substring matching the regular expression pattern you specify.

(Of course, REGEXP_LIKE only matches queries containing the search string, so if you want a complete match, you'll have to use '^$' for a beginning (^) and end ($) match, e.g.: '^regex.*$'.)

javascript multiple OR conditions in IF statement

When it checks id!=2 it returns true and stops further checking

How to invoke bash, run commands inside the new shell, and then give control back to user?

This is a late answer, but I had the exact same problem and Google sent me to this page, so for completeness here is how I got around the problem.

As far as I can tell, bash does not have an option to do what the original poster wanted to do. The -c option will always return after the commands have been executed.

Broken solution: The simplest and obvious attempt around this is:

bash -c 'XXXX ; bash'

This partly works (albeit with an extra sub-shell layer). However, the problem is that while a sub-shell will inherit the exported environment variables, aliases and functions are not inherited. So this might work for some things but isn't a general solution.

Better: The way around this is to dynamically create a startup file and call bash with this new initialization file, making sure that your new init file calls your regular ~/.bashrc if necessary.

# Create a temporary file
TMPFILE=$(mktemp)

# Add stuff to the temporary file
echo "source ~/.bashrc" > $TMPFILE
echo "<other commands>" >> $TMPFILE
echo "rm -f $TMPFILE" >> $TMPFILE

# Start the new bash shell 
bash --rcfile $TMPFILE

The nice thing is that the temporary init file will delete itself as soon as it is used, reducing the risk that it is not cleaned up correctly.

Note: I'm not sure if /etc/bashrc is usually called as part of a normal non-login shell. If so you might want to source /etc/bashrc as well as your ~/.bashrc.

Dynamically add event listener

I will add a StackBlitz example and a comment to the answer from @tahiche.

The return value is a function to remove the event listener after you have added it. It is considered good practice to remove event listeners when you don't need them anymore. So you can store this return value and call it inside your ngOnDestroy method.

I admit that it might seem confusing at first, but it is actually a very useful feature. How else can you clean up after yourself?

export class MyComponent implements OnInit, OnDestroy {

  public removeEventListener: () => void;

  constructor(
    private renderer: Renderer2, 
    private elementRef: ElementRef
  ) {
  }

  public ngOnInit() {
    this.removeEventListener = this.renderer.listen(this.elementRef.nativeElement, 'click', (event) => {
      if (event.target instanceof HTMLAnchorElement) {
        // Prevent opening anchors the default way
        event.preventDefault();
        // Your custom anchor click event handler
        this.handleAnchorClick(event);
      }
    });
  }

  public ngOnDestroy() {
    this.removeEventListener();
  }
}

You can find a StackBlitz here to show how this could work for catching clicking on anchor elements.

I added a body with an image as follows:
<img src="x" onerror="alert(1)"></div>
to show that the sanitizer is doing its job.

Here in this fiddle you find the same body attached to an innerHTML without sanitizing it and it will demonstrate the issue.

How to generate gcc debug symbol outside the build target?

Compile with debug information:

gcc -g -o main main.c

Separate the debug information:

objcopy --only-keep-debug main main.debug

or

cp main main.debug
strip --only-keep-debug main.debug

Strip debug information from origin file:

objcopy --strip-debug main

or

strip --strip-debug --strip-unneeded main

debug by debuglink mode:

objcopy --add-gnu-debuglink main.debug main
gdb main

You can also use exec file and symbol file separatly:

gdb -s main.debug -e main

or

gdb
(gdb) exec-file main
(gdb) symbol-file main.debug

For details:

(gdb) help exec-file
(gdb) help symbol-file

Ref:
https://sourceware.org/gdb/onlinedocs/gdb/Files.html#Files https://sourceware.org/gdb/onlinedocs/gdb/Separate-Debug-Files.html

jquery ajax get responsetext from http url

Since jQuery AJAX requests fail if they are cross-domain, you can use cURL (in PHP) to set up a proxy server.

Suppose a PHP file responder.php has these contents:

$url = "https://www.google.com";
$ch      = curl_init( $url );
curl_set_opt($ch, CURLOPT_RETURNTRANSFER, "true")
$response= curl_exec( $ch );
curl_close( $ch );
return $response;

Your AJAX request should be to this responder.php file so that it executes the cross-domain request.

AES Encryption for an NSString on the iPhone

@owlstead, regarding your request for "a cryptographically secure variant of one of the given answers," please see RNCryptor. It was designed to do exactly what you're requesting (and was built in response to the problems with the code listed here).

RNCryptor uses PBKDF2 with salt, provides a random IV, and attaches HMAC (also generated from PBKDF2 with its own salt. It support synchronous and asynchronous operation.

Request format is unrecognized for URL unexpectedly ending in

For the record I was getting this error when I moved an old app from one server to another. I added the <add name="HttpGet"/> <add name="HttpPost"/> elements to the web.config, which changed the error to:

System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at BitMeter2.DataBuffer.incrementCurrent(Int64 val)
   at BitMeter2.DataBuffer.WindOn(Int64 count, Int64 amount)
   at BitMeter2.DataHistory.windOnBuffer(DataBuffer buffer, Int64 totalAmount, Int32 increments)
   at BitMeter2.DataHistory.NewData(Int64 downloadValue, Int64 uploadValue)
   at BitMeter2.frmMain.tickProcessing(Boolean fromTimerEvent)

In order to fix this error I had to add the ScriptHandlerFactory lines to web.config:

  <system.webServer>
    <handlers>
      <remove name="ScriptHandlerFactory" />
      <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    </handlers>
  </system.webServer>

Why it worked without these lines on one web server and not the other I don't know.

Access Google's Traffic Data through a Web Service

I don't think Google will provide this API. And traffic data not only contains the incident data.

Today many online maps show city traffic, but they have not provide the API for the developer. We even don't know where they get the traffic data. Maybe the government has the data.

So I think you could think about it from another direction. For example, there are many social network website out there. Everybody could post the traffic information on the website. We can collection these information to get the traffic status. Or maybe we can create a this type website.

But that type traffic data (talked about above) is not accurate. Even the information provided by human will be wrong.

Luckily I found that my city now provides an Mobile App called "Real-time Bus Information". It could tell the citizen where the bus is now, and when will arrive at the bus station. And I sniff the REST API in this App. The data from REST API give the important data, for example the lat and lon, and also the bus speed. And it's real-time data! So I think we could compute the traffic status from these data (by some programming). Here is some sample data : https://github.com/sp-chenyang/bus/blob/master/sample_data/bjgj_aibang_com_8899_bjgj_php_city_linename_stationno_datatype_type.json

Even the bus data will not enough to compute the accurate real-time traffic status. Incidents, traffic light and other things will affect the traffic status. But I think this is the beginning.

At the end, I think you could try to find whether your city provides these data.

PS: I am always thinking that life will be better for people in the future , but not now.

python-How to set global variables in Flask?

With:

global index_add_counter

You are not defining, just declaring so it's like saying there is a global index_add_counter variable elsewhere, and not create a global called index_add_counter. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global keyword and initialize your variable:

index_add_counter = 0

Now you can import it with:

from app import index_add_counter

The construction:

global index_add_counter

is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:

index_add_counter = 0
def test():
  global index_add_counter # means: in this scope, use the global name
  print(index_add_counter)

What is the best open-source java charting library? (other than jfreechart)

There is JChart which is all open source. I'm not sure exactly what you are graphing and how you are graphing it (servlets, swing, etc) so I would say just look at a couple different ones and see which works for you.

http://sourceforge.net/projects/jchart/

I've also used JGraph but I've only used their commercial version. They do offer an open source version however:

http://www.jgraph.com/jgraph.html

Hash string in c#

If performance is not a major concern, you can also use any of these methods:
(In case you wanted the hash string to be in upper case, replace "x2" with "X2".)

public static string SHA256ToString(string s) 
{
    using (var alg = SHA256.Create())
        return string.Join(null, alg.ComputeHash(Encoding.UTF8.GetBytes(s)).Select(x => x.ToString("x2")));
}

or:

public static string SHA256ToString(string s)
{            
    using (var alg = SHA256.Create())
        return alg.ComputeHash(Encoding.UTF8.GetBytes(s)).Aggregate(new StringBuilder(), (sb, x) => sb.Append(x.ToString("x2"))).ToString();
}

Bootstrap 3 - How to load content in modal body via AJAX?

A simple way to use modals is with eModal!

Ex from github:

  1. Link to eModal.js <script src="//rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>
  2. use eModal to display a modal for alert, ajax, prompt or confirm

    // Display an alert modal with default title (Attention)
    eModal.ajax('your/url.html');
    

_x000D_
_x000D_
$(document).ready(function () {/* activate scroll spy menu */_x000D_
_x000D_
    var iconPrefix = '.glyphicon-';_x000D_
_x000D_
_x000D_
    $(iconPrefix + 'cloud').click(ajaxDemo);_x000D_
    $(iconPrefix + 'comment').click(alertDemo);_x000D_
    $(iconPrefix + 'ok').click(confirmDemo);_x000D_
    $(iconPrefix + 'pencil').click(promptDemo);_x000D_
    $(iconPrefix + 'screenshot').click(iframeDemo);_x000D_
    ///////////////////* Implementation *///////////////////_x000D_
_x000D_
    // Demos_x000D_
    function ajaxDemo() {_x000D_
        var title = 'Ajax modal';_x000D_
        var params = {_x000D_
            buttons: [_x000D_
               { text: 'Close', close: true, style: 'danger' },_x000D_
               { text: 'New content', close: false, style: 'success', click: ajaxDemo }_x000D_
            ],_x000D_
            size: eModal.size.lg,_x000D_
            title: title,_x000D_
            url: 'http://maispc.com/app/proxy.php?url=http://loripsum.net/api/' + Math.floor((Math.random() * 7) + 1) + '/short/ul/bq/prude/code/decorete'_x000D_
        };_x000D_
_x000D_
        return eModal_x000D_
            .ajax(params)_x000D_
            .then(function () { alert('Ajax Request complete!!!!', title) });_x000D_
    }_x000D_
_x000D_
    function alertDemo() {_x000D_
        var title = 'Alert modal';_x000D_
        return eModal_x000D_
            .alert('You welcome! Want clean code ?', title)_x000D_
            .then(function () { alert('Alert modal is visible.', title); });_x000D_
    }_x000D_
_x000D_
    function confirmDemo() {_x000D_
        var title = 'Confirm modal callback feedback';_x000D_
        return eModal_x000D_
            .confirm('It is simple enough?', 'Confirm modal')_x000D_
            .then(function (/* DOM */) { alert('Thank you for your OK pressed!', title); })_x000D_
            .fail(function (/*null*/) { alert('Thank you for your Cancel pressed!', title) });_x000D_
    }_x000D_
_x000D_
    function iframeDemo() {_x000D_
        var title = 'Insiders';_x000D_
        return eModal_x000D_
            .iframe('https://www.youtube.com/embed/VTkvN51OPfI', title)_x000D_
            .then(function () { alert('iFrame loaded!!!!', title) });_x000D_
    }_x000D_
_x000D_
    function promptDemo() {_x000D_
        var title = 'Prompt modal callback feedback';_x000D_
        return eModal_x000D_
            .prompt({ size: eModal.size.sm, message: 'What\'s your name?', title: title })_x000D_
            .then(function (input) { alert({ message: 'Hi ' + input + '!', title: title, imgURI: 'https://avatars0.githubusercontent.com/u/4276775?v=3&s=89' }) })_x000D_
            .fail(function (/**/) { alert('Why don\'t you tell me your name?', title); });_x000D_
    }_x000D_
_x000D_
    //#endregion_x000D_
});
_x000D_
.fa{_x000D_
  cursor:pointer;_x000D_
 }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.5/united/bootstrap.min.css" rel="stylesheet" >_x000D_
<link href="http//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">_x000D_
_x000D_
<div class="row" itemprop="about">_x000D_
 <div class="col-sm-1 text-center"></div>_x000D_
 <div class="col-sm-2 text-center">_x000D_
  <div class="row">_x000D_
   <div class="col-sm-10 text-center">_x000D_
    <h3>Ajax</h3>_x000D_
    <p>You must get the message from a remote server? No problem!</p>_x000D_
    <i class="glyphicon glyphicon-cloud fa-5x pointer" title="Try me!"></i>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
 <div class="col-sm-2 text-center">_x000D_
  <div class="row">_x000D_
   <div class="col-sm-10 text-center">_x000D_
    <h3>Alert</h3>_x000D_
    <p>Traditional alert box. Using only text or a lot of magic!?</p>_x000D_
    <i class="glyphicon glyphicon-comment fa-5x pointer" title="Try me!"></i>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
_x000D_
 <div class="col-sm-2 text-center">_x000D_
  <div class="row">_x000D_
   <div class="col-sm-10 text-center">_x000D_
    <h3>Confirm</h3>_x000D_
    <p>Get an okay from user, has never been so simple and clean!</p>_x000D_
    <i class="glyphicon glyphicon-ok fa-5x pointer" title="Try me!"></i>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
 <div class="col-sm-2 text-center">_x000D_
  <div class="row">_x000D_
   <div class="col-sm-10  text-center">_x000D_
    <h3>Prompt</h3>_x000D_
    <p>Do you have a question for the user? We take care of it...</p>_x000D_
    <i class="glyphicon glyphicon-pencil fa-5x pointer" title="Try me!"></i>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
 <div class="col-sm-2 text-center">_x000D_
  <div class="row">_x000D_
   <div class="col-sm-10  text-center">_x000D_
    <h3>iFrame</h3>_x000D_
    <p>IFrames are hard to deal with it? We don't think so!</p>_x000D_
    <i class="glyphicon glyphicon-screenshot fa-5x pointer" title="Try me!"></i>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
 <div class="col-sm-1 text-center"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

CSS image resize percentage of itself?

This actually is possible, and I discovered how quite by accident while designing my first large-scale responsive design site.

<div class="wrapper">
  <div class="box">
    <img src="/logo.png" alt="">
  </div>
</div>

.wrapper { position:relative; overflow:hidden; }

.box { float:left; } //Note: 'float:right' would work too

.box > img { width:50%; }

The overflow:hidden gives the wrapper height and width, despite the floating contents, without using the clearfix hack. You can then position your content using margins. You can even make the wrapper div an inline-block.

What is the shortcut to Auto import all in Android Studio?

You can make short cut key for missing import in android studio which you like

  1. Click on file Menu
  2. Click on Settting
  3. click on key map
  4. Search for "auto-import"
  5. double click on auto import and select add keyboard short cut key
  6. that's all

enter image description here

enter image description here

enter image description here

Note: You can import single missing import using alt+enter which shown in pop up

enter image description here

Adding Buttons To Google Sheets and Set value to Cells on clicking

Consider building an Add-on that has an actual button and not using the outdated method of linking an image to a script function.

In the script editor, under the Help menu >> Welcome Screen >> link to Google Sheets Add-on - will give you sample code to use.

How can I display a JavaScript object?

You can also use ES6 template literal concept to display the content of a JavaScript object in a string format.

alert(`${JSON.stringify(obj)}`);

_x000D_
_x000D_
const obj  = {_x000D_
  "name" : "John Doe",_x000D_
  "habbits": "Nothing",_x000D_
};_x000D_
alert(`${JSON.stringify(obj)}`);
_x000D_
_x000D_
_x000D_

How to parse XML in Bash?

After some research for translation between Linux and Windows formats of the file paths in XML files I found interesting tutorials and solutions on:

Failed to install android-sdk: "java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema"

For Linux users (I'm using a Debian Distro, Kali) Here's how I resolved mine.

If you don't already have jdk-8, you want to get it at oracle's site

https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

I got the jdk-8u191-linux-x64.tar.gz

Step 1 - Installing Java Move and unpack it at a suitable location like so

$ mv jdk-8u191-linux-x64.tar.gz /suitablelocation/
$ tar -xzvf /suitablelocation/jdk-8u191-linux-x64.tar.gz

You should get an unzipped folder like jdk1.8.0_191 You can delete the tarball afterwards to conserve space

Step 2 - Setting up alternatives to the default java location

$ update-alternatives --install /usr/bin/java java /suitablelocation/jdk1.8.0_191/bin/java 1
$ update-alternatives --install /usr/bin/javac javac /suitablelocation/jdk1.8.0_191/bin/javac 1

Step 3 - Selecting your alternatives as default

$ update-alternatives --set java /suitablelocation/jdk1.8.0_191/bin/java
$ update-alternatives --set javac /suitablelocation/jdk1.8.0_191/bin/javac

Step 4 - Confirming default java version

$ java -version

Notes

  1. In the original article here: https://forums.kali.org/showthread.php?41-Installing-Java-on-Kali-Linux, the default plugin for mozilla was also set. I assume we don't really need the plugins as we're simply trying to develop for android.
  2. As in @spassvogel's answer, you should also place a @repositories.cfg file in your ~/.android directory as this is needed to update the tools repo lists
  3. Moving some things around may require root authority. Use sudo wisely.
  4. For sdkmanager usage, see official guide: https://developer.android.com/studio/command-line/sdkmanager

Git in Visual Studio - add existing project?

For me a Git repository (not GitHub) was already created, but empty. This was my solution for adding the existing project to the Git repository:

  1. I cloned and checked out a repository with Git Extensions.
  2. Then I copied my existing project files into this repository.
  3. Added a .gitignore file.
  4. Staged and committed all files.
  5. Pushed onto the remote repository.

It would be interesting to see this all done directly in Visual Studio 2015 without tools like Git Extensions, but the things I tried in Visual Studio didn't work (Add to source control is not available for my project, adding a remote didn't help, etc.).

Python None comparison: should I use "is" or ==?

Summary:

Use is when you want to check against an object's identity (e.g. checking to see if var is None). Use == when you want to check equality (e.g. Is var equal to 3?).

Explanation:

You can have custom classes where my_var == None will return True

e.g:

class Negator(object):
    def __eq__(self,other):
        return not other

thing = Negator()
print thing == None    #True
print thing is None    #False

is checks for object identity. There is only 1 object None, so when you do my_var is None, you're checking whether they actually are the same object (not just equivalent objects)

In other words, == is a check for equivalence (which is defined from object to object) whereas is checks for object identity:

lst = [1,2,3]
lst == lst[:]  # This is True since the lists are "equivalent"
lst is lst[:]  # This is False since they're actually different objects

How to add minutes to current time in swift

You can do date arithmetic by using NSDateComponents. For example:

import Foundation

let comps = NSDateComponents()

comps.minute = 5

let cal = NSCalendar.currentCalendar()

let r = cal.dateByAddingComponents(comps, toDate: NSDate(), options: nil)

It is what you see when you try it in playground

enter image description here

specifying goal in pom.xml

I've bumped into this question because I actually wanted to define a default goal in pom.xml. You can define a default goal under build:

<build>
    <defaultGoal>install</defaultGoal>
...
</build>

After that change, you can then simply run mvn which will do exactly the same as mvn install.

Note: I don't favor this as a default approach. My use case was to define a profile that downloaded a previous version of that project from Artifactory and wanted to tie that profile to a given phase. For convenience, I can run mvn -Pdownload-jar -Dversion=0.0.9 and don't need to specify a goal/phase there. I think it's reasonable to define a defaultGoal in a profile which has a very specific function for a particular phase.

Python safe method to get value of nested dictionary

Building up on Yoav's answer, an even safer approach:

def deep_get(dictionary, *keys):
    return reduce(lambda d, key: d.get(key, None) if isinstance(d, dict) else None, keys, dictionary)

Angular ForEach in Angular4/Typescript?

In Typescript use the For Each like below.

selectChildren(data, $event) {
let parentChecked = data.checked;
for(var obj in this.hierarchicalData)
    {
        for (var childObj in obj )
        {
            value.checked = parentChecked;
        }
    }
}

What are the rules about using an underscore in a C++ identifier?

As for the other part of the question, it's common to put the underscore at the end of the variable name to not clash with anything internal.

I do this even inside classes and namespaces because I then only have to remember one rule (compared to "at the end of the name in global scope, and the beginning of the name everywhere else").

What is the best way to ensure only one instance of a Bash script is running?

from with your script:

ps -ef | grep $0 | grep $(whoami)

how to mysqldump remote db from local machine

mysqldump from remote server use SSL

1- Security with SSL

192.168.0.101 - remote server

192.168.0.102 - local server

Remore server

CREATE USER 'backup_remote_2'@'192.168.0.102' IDENTIFIED WITH caching_sha2_password BY '3333333' REQUIRE SSL;

GRANT ALL PRIVILEGES ON *.* TO 'backup_remote_2'@'192.168.0.102';

FLUSH PRIVILEGES;

-

Local server

sudo /usr/local/mysql/bin/mysqldump \
 --databases test_1 \
 --host=192.168.0.101 \
 --user=backup_remote_2 \
 --password=3333333 \
 --master-data \
 --set-gtid-purged \
 --events \
 --triggers \
 --routines \
 --verbose \
 --ssl-mode=REQUIRED \
 --result-file=/home/db_1.sql

====================================

2 - Security with SSL (REQUIRE X509)

192.168.0.101 - remote server

192.168.0.102 - local server

Remore server

CREATE USER 'backup_remote'@'192.168.0.102' IDENTIFIED WITH caching_sha2_password BY '1111111' REQUIRE X509;

GRANT ALL PRIVILEGES ON *.* TO 'backup_remote'@'192.168.0.102';

FLUSH PRIVILEGES;

-

Local server

sudo /usr/local/mysql/bin/mysqldump \
 --databases test_1 \
 --host=192.168.0.101 \
 --user=backup_remote \
 --password=1111111 \
 --events \
 --triggers \
 --routines \
 --verbose \
 --ssl-mode=VERIFY_CA \
 --ssl-ca=/usr/local/mysql/data/ssl/ca.pem \
 --ssl-cert=/usr/local/mysql/data/ssl/client-cert.pem \
 --ssl-key=/usr/local/mysql/data/ssl/client-key.pem \
 --result-file=/home/db_name.sql

[Note]

On local server

/usr/local/mysql/data/ssl/

-rw------- 1 mysql mysql 1.7K Apr 16 22:28 ca-key.pem
-rw-r--r-- 1 mysql mysql 1.1K Apr 16 22:28 ca.pem
-rw-r--r-- 1 mysql mysql 1.1K Apr 16 22:28 client-cert.pem
-rw------- 1 mysql mysql 1.7K Apr 16 22:28 client-key.pem

Copy this files from remote server for (REQUIRE X509) or if SSL without (REQUIRE X509) do not copy


On remote server

/usr/local/mysql/data/

-rw------- 1 mysql mysql 1.7K Apr 16 22:28  ca-key.pem
-rw-r--r-- 1 mysql mysql 1.1K Apr 16 22:28  ca.pem
-rw-r--r-- 1 mysql mysql 1.1K Apr 16 22:28  client-cert.pem
-rw------- 1 mysql mysql 1.7K Apr 16 22:28  client-key.pem
-rw------- 1 mysql mysql 1.7K Apr 16 22:28  private_key.pem
-rw-r--r-- 1 mysql mysql  451 Apr 16 22:28  public_key.pem
-rw-r--r-- 1 mysql mysql 1.1K Apr 16 22:28  server-cert.pem
-rw------- 1 mysql mysql 1.7K Apr 16 22:28  server-key.pem

my.cnf

[mysqld]
# SSL
ssl_ca=/usr/local/mysql/data/ca.pem
ssl_cert=/usr/local/mysql/data/server-cert.pem
ssl_key=/usr/local/mysql/data/server-key.pem

Increase Password Security

https://dev.mysql.com/doc/refman/8.0/en/password-security-user.html

setState() inside of componentDidUpdate()

You can use setState inside componentDidUpdate

CSS media query to target iPad and iPad only?

this is for ipad

@media all and (device-width: 768px) {
  
}

this is for ipad pro

@media all and (device-width: 1024px){
  
}

Change font color and background in html on mouseover

It would be great if you use :hover pseudo class over the onmouseover event

td:hover
{
   background-color:white
}

and for the default styling just use

td
{
  background-color:black
}

As you want to use these styling not over all the td elements then you need to specify the class to those elements and add styling to that class like this

.customTD
{
   background-color:black
}
.customTD:hover
{
  background-color:white;
}

You can also use :nth-child selector to select the td elements

How do I match any character across multiple lines in a regular expression?

we can also use

(.*?\n)*?

to match everything including newline without greedy

This will make the new line optional

(.*?|\n)*?

How to strip all whitespace from string

Taking advantage of str.split's behavior with no sep parameter:

>>> s = " \t foo \n bar "
>>> "".join(s.split())
'foobar'

If you just want to remove spaces instead of all whitespace:

>>> s.replace(" ", "")
'\tfoo\nbar'

Premature optimization

Even though efficiency isn't the primary goal—writing clear code is—here are some initial timings:

$ python -m timeit '"".join(" \t foo \n bar ".split())'
1000000 loops, best of 3: 1.38 usec per loop
$ python -m timeit -s 'import re' 're.sub(r"\s+", "", " \t foo \n bar ")'
100000 loops, best of 3: 15.6 usec per loop

Note the regex is cached, so it's not as slow as you'd imagine. Compiling it beforehand helps some, but would only matter in practice if you call this many times:

$ python -m timeit -s 'import re; e = re.compile(r"\s+")' 'e.sub("", " \t foo \n bar ")'
100000 loops, best of 3: 7.76 usec per loop

Even though re.sub is 11.3x slower, remember your bottlenecks are assuredly elsewhere. Most programs would not notice the difference between any of these 3 choices.

Java HTTPS client certificate authentication

I've connected to bank with two-way SSL (client and server certificate) with Spring Boot. So describe here all my steps, hope it helps someone (simplest working solution, I've found):

  1. Generate sertificate request:

    • Generate private key:

      openssl genrsa -des3 -passout pass:MY_PASSWORD -out user.key 2048
      
    • Generate certificate request:

      openssl req -new -key user.key -out user.csr -passin pass:MY_PASSWORD
      

    Keep user.key (and password) and send certificate request user.csr to bank for my sertificate

  2. Receive 2 certificate: my client root certificate clientId.crt and bank root certificate: bank.crt

  3. Create Java keystore (enter key password and set keystore password):

    openssl pkcs12 -export -in clientId.crt -inkey user.key -out keystore.p12 -name clientId -CAfile ca.crt -caname root
    

    Don't pay attention on output: unable to write 'random state'. Java PKCS12 keystore.p12 created.

  4. Add into keystore bank.crt (for simplicity I've used one keystore):

    keytool -import -alias banktestca -file banktestca.crt -keystore keystore.p12 -storepass javaops
    

    Check keystore certificates by:

    keytool -list -keystore keystore.p12
    
  5. Ready for Java code:) I've used Spring Boot RestTemplate with add org.apache.httpcomponents.httpcore dependency:

    @Bean("sslRestTemplate")
    public RestTemplate sslRestTemplate() throws Exception {
      char[] storePassword = appProperties.getSslStorePassword().toCharArray();
      URL keyStore = new URL(appProperties.getSslStore());
    
      SSLContext sslContext = new SSLContextBuilder()
            .loadTrustMaterial(keyStore, storePassword)
      // use storePassword twice (with key password do not work)!!
            .loadKeyMaterial(keyStore, storePassword, storePassword) 
            .build();
    
      // Solve "Certificate doesn't match any of the subject alternative names"
      SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
    
      CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
      HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client);
      RestTemplate restTemplate = new RestTemplate(factory);
      // restTemplate.setMessageConverters(List.of(new Jaxb2RootElementHttpMessageConverter()));
      return restTemplate;
    }
    

Subversion stuck due to "previous operation has not finished"?

I resolved this error today when it occurred trying to Commit to SVN. The error was genuine, TortoiseSVN could not access a file which I tried to Commit. This file had been saved while running a program "As Administrator" in Windows. This means the file has Administrator access but not access from my account (TortoiseSVN running as interactive user). I took ownership of the nominated file under my windows account and after that Cleanup was able to proceed.

Facebook share link - can you customize the message body text?

Like @Ardee said you sharer.php uses data from the meta tags, the Dialog API accepts parameters. Facebook have removed the ability to use the message parameter but you can use the quote parameter which can be useful in a lot of cases e.g.

enter image description here

https://www.facebook.com/dialog/share?
app_id=[your-app-id]
&display=popup
&title=This+is+the+title+parameter
&description=This+is+the+description+parameter
&quote=This+is+the+quote+parameter
&caption=This+is+the+caption+parameter
&href=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2F
&redirect_uri=https%3A%2F%2Fwww.[url-in-your-accepted-list].com

Just have to create an app id:

https://developers.facebook.com/docs/apps/register

Then make sure the redirect url domain is listed in the accepted domains for that app.

How to use a keypress event in AngularJS?

This is an extension on the answer from EpokK.

I had the same problem of having to call a scope function when enter is pushed on an input field. However I also wanted to pass the value of the input field to the function specified. This is my solution:

app.directive('ltaEnter', function () {
return function (scope, element, attrs) {
    element.bind("keydown keypress", function (event) {
        if(event.which === 13) {
          // Create closure with proper command
          var fn = function(command) {
            var cmd = command;
            return function() {
              scope.$eval(cmd);
            };
          }(attrs.ltaEnter.replace('()', '("'+ event.target.value +'")' ));

          // Apply function
          scope.$apply(fn);

          event.preventDefault();
        }
    });
};

});

The use in HTML is as follows:

<input type="text" name="itemname" lta-enter="add()" placeholder="Add item"/>

Kudos to EpokK for his answer.

modal View controllers - how to display and dismiss

This line:

[self dismissViewControllerAnimated:YES completion:nil];

isn't sending a message to itself, it's actually sending a message to its presenting VC, asking it to do the dismissing. When you present a VC, you create a relationship between the presenting VC and the presented one. So you should not destroy the presenting VC while it is presenting (the presented VC can't send that dismiss message back…). As you're not really taking account of it you are leaving the app in a confused state. See my answer Dismissing a Presented View Controller in which I recommend this method is more clearly written:

[self.presentingViewController dismissViewControllerAnimated:YES completion:nil];

In your case, you need to ensure that all of the controlling is done in mainVC . You should use a delegate to send the correct message back to MainViewController from ViewController1, so that mainVC can dismiss VC1 and then present VC2.

In VC2 VC1 add a protocol in your .h file above the @interface:

@protocol ViewController1Protocol <NSObject>

    - (void)dismissAndPresentVC2;

@end

and lower down in the same file in the @interface section declare a property to hold the delegate pointer:

@property (nonatomic,weak) id <ViewController1Protocol> delegate;

In the VC1 .m file, the dismiss button method should call the delegate method

- (IBAction)buttonPressedFromVC1:(UIButton *)sender {
    [self.delegate dissmissAndPresentVC2]
}

Now in mainVC, set it as VC1's delegate when creating VC1:

- (IBAction)present1:(id)sender {
    ViewController1* vc = [[ViewController1 alloc] initWithNibName:@"ViewController1" bundle:nil];
    vc.delegate = self;
    [self present:vc];
}

and implement the delegate method:

- (void)dismissAndPresent2 {
    [self dismissViewControllerAnimated:NO completion:^{
        [self present2:nil];
    }];
}

present2: can be the same method as your VC2Pressed: button IBAction method. Note that it is called from the completion block to ensure that VC2 is not presented until VC1 is fully dismissed.

You are now moving from VC1->VCMain->VC2 so you will probably want only one of the transitions to be animated.

update

In your comments you express surprise at the complexity required to achieve a seemingly simple thing. I assure you, this delegation pattern is so central to much of Objective-C and Cocoa, and this example is about the most simple you can get, that you really should make the effort to get comfortable with it.

In Apple's View Controller Programming Guide they have this to say:

Dismissing a Presented View Controller

When it comes time to dismiss a presented view controller, the preferred approach is to let the presenting view controller dismiss it. In other words, whenever possible, the same view controller that presented the view controller should also take responsibility for dismissing it. Although there are several techniques for notifying the presenting view controller that its presented view controller should be dismissed, the preferred technique is delegation. For more information, see “Using Delegation to Communicate with Other Controllers.”

If you really think through what you want to achieve, and how you are going about it, you will realise that messaging your MainViewController to do all of the work is the only logical way out given that you don't want to use a NavigationController. If you do use a NavController, in effect you are 'delegating', even if not explicitly, to the navController to do all of the work. There needs to be some object that keeps a central track of what's going on with your VC navigation, and you need some method of communicating with it, whatever you do.

In practice Apple's advice is a little extreme... in normal cases, you don't need to make a dedicated delegate and method, you can rely on [self presentingViewController] dismissViewControllerAnimated: - it's when in cases like yours that you want your dismissing to have other effects on remote objects that you need to take care.

Here is something you could imagine to work without all the delegate hassle...

- (IBAction)dismiss:(id)sender {
    [[self presentingViewController] dismissViewControllerAnimated:YES 
                                                        completion:^{
        [self.presentingViewController performSelector:@selector(presentVC2:) 
                                            withObject:nil];
    }];

}

After asking the presenting controller to dismiss us, we have a completion block which calls a method in the presentingViewController to invoke VC2. No delegate needed. (A big selling point of blocks is that they reduce the need for delegates in these circumstances). However in this case there are a few things getting in the way...

  • in VC1 you don't know that mainVC implements the method present2 - you can end up with difficult-to-debug errors or crashes. Delegates help you to avoid this.
  • once VC1 is dismissed, it's not really around to execute the completion block... or is it? Does self.presentingViewController mean anything any more? You don't know (neither do I)... with a delegate, you don't have this uncertainty.
  • When I try to run this method, it just hangs with no warning or errors.

So please... take the time to learn delegation!

update2

In your comment you have managed to make it work by using this in VC2's dismiss button handler:

 [self.view.window.rootViewController dismissViewControllerAnimated:YES completion:nil]; 

This is certainly much simpler, but it leaves you with a number of issues.

Tight coupling
You are hard-wiring your viewController structure together. For example, if you were to insert a new viewController before mainVC, your required behaviour would break (you would navigate to the prior one). In VC1 you have also had to #import VC2. Therefore you have quite a lot of inter-dependencies, which breaks OOP/MVC objectives.

Using delegates, neither VC1 nor VC2 need to know anything about mainVC or it's antecedents so we keep everything loosely-coupled and modular.

Memory
VC1 has not gone away, you still hold two pointers to it:

  • mainVC's presentedViewController property
  • VC2's presentingViewController property

You can test this by logging, and also just by doing this from VC2

[self dismissViewControllerAnimated:YES completion:nil]; 

It still works, still gets you back to VC1.

That seems to me like a memory leak.

The clue to this is in the warning you are getting here:

[self presentViewController:vc2 animated:YES completion:nil];
[self dismissViewControllerAnimated:YES completion:nil];
 // Attempt to dismiss from view controller <VC1: 0x715e460>
 // while a presentation or dismiss is in progress!

The logic breaks down, as you are attempting to dismiss the presenting VC of which VC2 is the presented VC. The second message doesn't really get executed - well perhaps some stuff happens, but you are still left with two pointers to an object you thought you had got rid of. (edit - I've checked this and it's not so bad, both objects do go away when you get back to mainVC)

That's a rather long-winded way of saying - please, use delegates. If it helps, I made another brief description of the pattern here:
Is passing a controller in a construtor always a bad practice?

update 3
If you really want to avoid delegates, this could be the best way out:

In VC1:

[self presentViewController:VC2
                   animated:YES
                 completion:nil];

But don't dismiss anything... as we ascertained, it doesn't really happen anyway.

In VC2:

[self.presentingViewController.presentingViewController 
    dismissViewControllerAnimated:YES
                       completion:nil];

As we (know) we haven't dismissed VC1, we can reach back through VC1 to MainVC. MainVC dismisses VC1. Because VC1 has gone, it's presented VC2 goes with it, so you are back at MainVC in a clean state.

It's still highly coupled, as VC1 needs to know about VC2, and VC2 needs to know that it was arrived at via MainVC->VC1, but it's the best you're going to get without a bit of explicit delegation.

How does Zalgo text work?

The text uses combining characters, also known as combining marks. See section 2.11 of Combining Characters in the Unicode Standard (PDF).

In Unicode, character rendering does not use a simple character cell model where each glyph fits into a box with given height. Combining marks may be rendered above, below, or inside a base character

So you can easily construct a character sequence, consisting of a base character and “combining above” marks, of any length, to reach any desired visual height, assuming that the rendering software conforms to the Unicode rendering model. Such a sequence has no meaning of course, and even a monkey could produce it (e.g., given a keyboard with suitable driver).

And you can mix “combining above” and “combining below” marks.

The sample text in the question starts with:

Angular directives - when and how to use compile, controller, pre-link and post-link

In which order the directive functions are executed?

For a single directive

Based on the following plunk, consider the following HTML markup:

<body>
    <div log='some-div'></div>
</body>

With the following directive declaration:

myApp.directive('log', function() {
  
    return {
        controller: function( $scope, $element, $attrs, $transclude ) {
            console.log( $attrs.log + ' (controller)' );
        },
        compile: function compile( tElement, tAttributes ) {
            console.log( tAttributes.log + ' (compile)'  );
            return {
                pre: function preLink( scope, element, attributes ) {
                    console.log( attributes.log + ' (pre-link)'  );
                },
                post: function postLink( scope, element, attributes ) {
                    console.log( attributes.log + ' (post-link)'  );
                }
            };
         }
     };  
     
});

The console output will be:

some-div (compile)
some-div (controller)
some-div (pre-link)
some-div (post-link)

We can see that compile is executed first, then controller, then pre-link and last is post-link.

For nested directives

Note: The following does not apply to directives that render their children in their link function. Quite a few Angular directives do so (like ngIf, ngRepeat, or any directive with transclude). These directives will natively have their link function called before their child directives compile is called.

The original HTML markup is often made of nested elements, each with its own directive. Like in the following markup (see plunk):

<body>
    <div log='parent'>
        <div log='..first-child'></div>
        <div log='..second-child'></div>
    </div>
</body>

The console output will look like this:

// The compile phase
parent (compile)
..first-child (compile)
..second-child (compile)

// The link phase   
parent (controller)
parent (pre-link)
..first-child (controller)
..first-child (pre-link)
..first-child (post-link)
..second-child (controller)
..second-child (pre-link)
..second-child (post-link)
parent (post-link)

We can distinguish two phases here - the compile phase and the link phase.

The compile phase

When the DOM is loaded Angular starts the compile phase, where it traverses the markup top-down, and calls compile on all directives. Graphically, we could express it like so:

An image illustrating the compilation loop for children

It is perhaps important to mention that at this stage, the templates the compile function gets are the source templates (not instance template).

The link phase

DOM instances are often simply the result of a source template being rendered to the DOM, but they may be created by ng-repeat, or introduced on the fly.

Whenever a new instance of an element with a directive is rendered to the DOM, the link phase starts.

In this phase, Angular calls controller, pre-link, iterates children, and call post-link on all directives, like so:

An illustration demonstrating the link phase steps

How to insert the current timestamp into MySQL database using a PHP insert query

Your usage of now() is correct. However, you need to use one type of quotes around the entire query and another around the values.

You can modify your query to use double quotes at the beginning and end, and single quotes around $somename:

$update_query = "UPDATE db.tablename SET insert_time=now() WHERE username='$somename'";

What is the use of printStackTrace() method in Java?

It helps to trace the exception. For example you are writing some methods in your program and one of your methods causes bug. Then printstack will help you to identify which method causes the bug. Stack will help like this:

First your main method will be called and inserted to stack, then the second method will be called and inserted to the stack in LIFO order and if any error occurs somewhere inside any method then this stack will help to identify that method.

Check element CSS display with JavaScript

Basic JavaScript:

if (document.getElementById("elementId").style.display == 'block') { 
  alert('this Element is block'); 
}

How can I suppress column header output for a single SQL statement?

Invoke mysql with the -N (the alias for -N is --skip-column-names) option:

mysql -N ...
use testdb;
select * from names;

+------+-------+
|    1 | pete  |
|    2 | john  |
|    3 | mike  |
+------+-------+
3 rows in set (0.00 sec)

Credit to ErichBSchulz for pointing out the -N alias.

To remove the grid (the vertical and horizontal lines) around the results use -s (--silent). Columns are separated with a TAB character.

mysql -s ...
use testdb;
select * from names;

id  name
1   pete
2   john
3   mike

To output the data with no headers and no grid just use both -s and -N.

mysql -sN ...

How to install a python library manually

I'm going to assume compiling the QuickFix package does not produce a setup.py file, but rather only compiles the Python bindings and relies on make install to put them in the appropriate place.

In this case, a quick and dirty fix is to compile the QuickFix source, locate the Python extension modules (you indicated on your system these end with a .so extension), and add that directory to your PYTHONPATH environmental variable e.g., add

export PYTHONPATH=~/path/to/python/extensions:PYTHONPATH

or similar line in your shell configuration file.

A more robust solution would include making sure to compile with ./configure --prefix=$HOME/.local. Assuming QuickFix knows to put the Python files in the appropriate site-packages, when you do make install, it should install the files to ~/.local/lib/pythonX.Y/site-packages, which, for Python 2.6+, should already be on your Python path as the per-user site-packages directory.

If, on the other hand, it did provide a setup.py file, simply run

python setup.py install --user

for Python 2.6+.

Why is there no ForEach extension method on IEnumerable?

If you have F# (which will be in the next version of .NET), you can use

Seq.iter doSomething myIEnumerable

XSD - how to allow elements in any order any number of times?

If none of the above is working, you are probably working on EDI trasaction where you need to validate your result against an HIPPA schema or any other complex xsd for that matter. The requirement is that, say there 8 REF segments and any of them have to appear in any order and also not all are required, means to say you may have them in following order 1st REF, 3rd REF , 2nd REF, 9th REF. Under default situation EDI receive will fail, beacause default complex type is

<xs:sequence>
  <xs:element.../>
</xs:sequence>

The situation is even complex when you are calling your element by refrence and then that element in its original spot is quite complex itself. for example:

<xs:element>
<xs:complexType>
<xs:sequence>
<element name="REF1"  ref= "REF1_Mycustomelment" minOccurs="0" maxOccurs="1">
<element name="REF2"  ref= "REF2_Mycustomelment" minOccurs="0" maxOccurs="1">
<element name="REF3"  ref= "REF3_Mycustomelment" minOccurs="0" maxOccurs="1">
</xs:sequence>
</xs:complexType>
</xs:element>

Solution:

Here simply replacing "sequence" with "all" or using "choice" with min/max combinations won't work!

First thing replace "xs:sequence" with "<xs:all>" Now,You need to make some changes where you are Referring the element from, There go to:

<xs:annotation>
  <xs:appinfo>
    <b:recordinfo structure="delimited" field.........Biztalk/2003">

***Now in the above segment add trigger point in the end like this trigger_field="REF01_...complete name.." trigger_value = "38" Do the same for other REF segments where trigger value will be different like say "18", "XX" , "YY" etc..so that your record info now looks like:b:recordinfo structure="delimited" field.........Biztalk/2003" trigger_field="REF01_...complete name.." trigger_value="38">


This will make each element unique, reason being All REF segements (above example) have same structure like REF01, REF02, REF03. And during validation the structure validation is ok but it doesn't let the values repeat because it tries to look for remaining values in first REF itself. Adding triggers will make them all unique and they will pass in any order and situational cases (like use 5 out 9 and not all 9/9).

Hope it helps you, for I spent almost 20 hrs on this.

Good Luck

How can I use numpy.correlate to do autocorrelation?

To answer your first question, numpy.correlate(a, v, mode) is performing the convolution of a with the reverse of v and giving the results clipped by the specified mode. The definition of convolution, C(t)=? -8 < i < 8 aivt+i where -8 < t < 8, allows for results from -8 to 8, but you obviously can't store an infinitely long array. So it has to be clipped, and that is where the mode comes in. There are 3 different modes: full, same, & valid:

  • "full" mode returns results for every t where both a and v have some overlap.
  • "same" mode returns a result with the same length as the shortest vector (a or v).
  • "valid" mode returns results only when a and v completely overlap each other. The documentation for numpy.convolve gives more detail on the modes.

For your second question, I think numpy.correlate is giving you the autocorrelation, it is just giving you a little more as well. The autocorrelation is used to find how similar a signal, or function, is to itself at a certain time difference. At a time difference of 0, the auto-correlation should be the highest because the signal is identical to itself, so you expected that the first element in the autocorrelation result array would be the greatest. However, the correlation is not starting at a time difference of 0. It starts at a negative time difference, closes to 0, and then goes positive. That is, you were expecting:

autocorrelation(a) = ? -8 < i < 8 aivt+i where 0 <= t < 8

But what you got was:

autocorrelation(a) = ? -8 < i < 8 aivt+i where -8 < t < 8

What you need to do is take the last half of your correlation result, and that should be the autocorrelation you are looking for. A simple python function to do that would be:

def autocorr(x):
    result = numpy.correlate(x, x, mode='full')
    return result[result.size/2:]

You will, of course, need error checking to make sure that x is actually a 1-d array. Also, this explanation probably isn't the most mathematically rigorous. I've been throwing around infinities because the definition of convolution uses them, but that doesn't necessarily apply for autocorrelation. So, the theoretical portion of this explanation may be slightly wonky, but hopefully the practical results are helpful. These pages on autocorrelation are pretty helpful, and can give you a much better theoretical background if you don't mind wading through the notation and heavy concepts.

using facebook sdk in Android studio

I fixed the

"Could not find property 'ANDROID_BUILD_SDK_VERSION' on project ':facebook'."

error on the build.gradle file, by adding in gradle.properties the values:

ANDROID_BUILD_TARGET_SDK_VERSION=21<br>
ANDROID_BUILD_MIN_SDK_VERSION=15<br>
ANDROID_BUILD_TOOLS_VERSION=21.1.2<br>
ANDROID_BUILD_SDK_VERSION=21<br>

Source: https://stackoverflow.com/a/21490651/2161698

Possible reason for NGINX 499 error codes

This doesn't answer the OPs question, but since I ended up here after searching furiously for an answer, I wanted to share what we discovered.

In our case, it turns out these 499s are expected. When users use the type-ahead feature in some search boxes, for example, we see something like this in the logs.

GET /api/search?q=h [Status 499] 
GET /api/search?q=he [Status 499]
GET /api/search?q=hel [Status 499]
GET /api/search?q=hell [Status 499]
GET /api/search?q=hello [Status 200]

So in our case I think its safe to use proxy_ignore_client_abort on which was suggested in a previous answer. Thanks for that!

Permissions for /var/www/html

You just need 775 for /var/www/html as long as you are logging in as myuser. The 7 octal in the middle (which is for "group" acl) ensures that the group has permission to read/write/execute. As long as you belong to the group that owns the files, "myuser" should be able to write to them. You may need to give group permissions to all the files in the docuemnt root, though:

chmod -R g+w /var/www/html

How to stop PHP code execution?

or try

trigger_error('Die', E_ERROR);

How to include multiple js files using jQuery $.getScript() method

I have improved @adeneo script so it will load all scripts in the specified order. It doesn't do chain loading, so it's very fast, but if you want even faster, change the 50 ms wait time.

$.getMultiScripts = function(arr, path) {

    function executeInOrder(scr, code, resolve) {
        // if its the first script that should be executed
        if (scr == arr[0]) {
            arr.shift();
            eval(code);
            resolve();
            console.log('executed', scr);
        } else {
            // waiting
            setTimeout(function(){
                executeInOrder(scr, code, resolve);
            }, 50);
        }
    }

    var _arr = $.map(arr, function(scr) {

        return new Promise((resolve) => {
            jQuery.ajax({
                type: "GET",
                url: (path || '') + scr,
                dataType: "text",
                success: function(code) {
                    console.log('loaded  ', scr);
                    executeInOrder(scr, code, resolve);
                },
                cache: true
            });
        });

    });
        
    _arr.push($.Deferred(function( deferred ){
        $( deferred.resolve );
    }));
        
    return $.when.apply($, _arr);
}

Usage is the same:

var script_arr = [
    'myscript1.js', 
    'myscript2.js', 
    'myscript3.js'
];

$.getMultiScripts(script_arr, '/mypath/').done(function() {
    // all scripts loaded
});

Execute jQuery function after another function completes

Deferred promises are a nice way to chain together function execution neatly and easily. Whether AJAX or normal functions, they offer greater flexibility than callbacks, and I've found easier to grasp.

function Typer()
{
var dfd = $.Deferred();
    var srcText = 'EXAMPLE ';
    var i = 0;
    var result = srcText[i];

UPDATE :

////////////////////////////////

  var timer=    setInterval(function() {
                    if(i == srcText.length) {

    // clearInterval(this);


       clearInterval(timer);

////////////////////////////////


   dfd.resolve();
                        };
                        i++;
                        result += srcText[i].replace("\n", "<br />");
                        $("#message").html( result);
                },
                100);
              return dfd.promise();
            }

I've modified the play function so it returns a promise when the audio finishes playing, which might be useful to some. The third function fires when sound finishes playing.

   function playBGM()
    {
      var playsound = $.Deferred();
      $('#bgm')[0].play();
      $("#bgm").on("ended", function() {
         playsound.resolve();
      });
        return playsound.promise();
    }


    function thirdFunction() {
        alert('third function');
    }

Now call the whole thing with the following: (be sure to use Jquery 1.9.1 or above as I found that 1.7.2 executes all the functions at once, rather than waiting for each to resolve.)

Typer().then(playBGM).then(thirdFunction);  

Before today, I had no luck using deferred promises in this way, and finally have grasped it. Precisely timed, chained interface events occurring exactly when we want them to, including async events, has never been easy. For me at least, I now have it under control thanks largely to others asking questions here.

Best way to retrieve variable values from a text file?

How reliable is your format? If the seperator is always exactly ': ', the following works. If not, a comparatively simple regex should do the job.

As long as you're working with fairly simple variable types, Python's eval function makes persisting variables to files surprisingly easy.

(The below gives you a dictionary, btw, which you mentioned was one of your prefered solutions).

def read_config(filename):
    f = open(filename)
    config_dict = {}
    for lines in f:
        items = lines.split(': ', 1)
        config_dict[items[0]] = eval(items[1])
    return config_dict

How to parse Excel (XLS) file in Javascript/HTML5

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/jszip.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.js"></script>_x000D_
<script>_x000D_
    var ExcelToJSON = function() {_x000D_
_x000D_
      this.parseExcel = function(file) {_x000D_
        var reader = new FileReader();_x000D_
_x000D_
        reader.onload = function(e) {_x000D_
          var data = e.target.result;_x000D_
          var workbook = XLSX.read(data, {_x000D_
            type: 'binary'_x000D_
          });_x000D_
          workbook.SheetNames.forEach(function(sheetName) {_x000D_
            // Here is your object_x000D_
            var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);_x000D_
            var json_object = JSON.stringify(XL_row_object);_x000D_
            console.log(JSON.parse(json_object));_x000D_
            jQuery( '#xlx_json' ).val( json_object );_x000D_
          })_x000D_
        };_x000D_
_x000D_
        reader.onerror = function(ex) {_x000D_
          console.log(ex);_x000D_
        };_x000D_
_x000D_
        reader.readAsBinaryString(file);_x000D_
      };_x000D_
  };_x000D_
_x000D_
  function handleFileSelect(evt) {_x000D_
    _x000D_
    var files = evt.target.files; // FileList object_x000D_
    var xl2json = new ExcelToJSON();_x000D_
    xl2json.parseExcel(files[0]);_x000D_
  }_x000D_
_x000D_
_x000D_
 _x000D_
</script>_x000D_
_x000D_
<form enctype="multipart/form-data">_x000D_
    <input id="upload" type=file  name="files[]">_x000D_
</form>_x000D_
_x000D_
    <textarea class="form-control" rows=35 cols=120 id="xlx_json"></textarea>_x000D_
_x000D_
    <script>_x000D_
        document.getElementById('upload').addEventListener('change', handleFileSelect, false);_x000D_
_x000D_
    </script>
_x000D_
_x000D_
_x000D_

Gcc error: gcc: error trying to exec 'cc1': execvp: No such file or directory

I experienced this soon after compiling and installing a shiny new GCC — version 8.1 — on RHEL 7. In the end, it ended up being a permissions problem; my root umask was the culprit. I eventually found cc1 hiding in /usr/local/libexec:

[root@nacelle gdb-8.1]# ls -l /usr/local/libexec/gcc/x86_64-pc-linux-gnu/8.1.0/ | grep cc1
-rwxr-xr-x 1 root root 196481344 Jul  2 13:53 cc1

However, the permissions on the directories leading there didn't allow my standard user account:

[root@nacelle gdb-8.1]# ls -l /usr/local/libexec/
total 4
drwxr-x--- 3 root root 4096 Jul  2 13:53 gcc
[root@nacelle gdb-8.1]# ls -l /usr/local/libexec/gcc/
total 4
drwxr-x--- 3 root root 4096 Jul  2 13:53 x86_64-pc-linux-gnu
[root@nacelle gdb-8.1]# ls -l /usr/local/libexec/gcc/x86_64-pc-linux-gnu/
total 4
drwxr-x--- 4 root root 4096 Jul  2 13:53 8.1.0

A quick recursive chmod to add world read/execute permissions fixed it right up:

[root@nacelle 8.1.0]# cd /usr/local/libexec
[root@nacelle lib]# ls -l | grep gcc
drwxr-x---  3 root root     4096 Jul  2 13:53 gcc
[root@nacelle lib]# chmod -R o+rx gcc
[root@nacelle lib]# ls -l | grep gcc
drwxr-xr-x  3 root root     4096 Jul  2 13:53 gcc

And now gcc can find cc1 when I ask it to compile something!

What does "while True" mean in Python?

While most of these answers are correct to varying degrees, none of them are as succinct as I would like.

Put simply, using while True: is just a way of running a loop that will continue to run until you explicitly break out of it using break or return. Since True will always evaluate to True, you have to force the loop to end when you want it to.

while True:
    # do stuff

    if some_condition:
        break

    # do more stuff - code here WILL NOT execute when `if some_condition:` evaluates to True

While normally a loop would be set to run until the while condition is false, or it reaches a predefined end point:

do_next = True

while do_next:

    # do stuff

    if some_condition:
        do_next = False

    # do more stuff - code here WILL execute even when `if some_condition:` evaluates to True

Those two code chunks effectively do the same thing

If the condition your loop evaluates against is possibly a value not directly in your control, such as a user input value, then validating the data and explicitly breaking out of the loop is usually necessary, so you'd want to do it with either method.

The while True format is more pythonic since you know that break is breaking the loop at that exact point, whereas do_next = False could do more stuff before the next evaluation of do_next.

I want to exception handle 'list index out of range.'

Taking reference of ThiefMaster? sometimes we get an error with value given as '\n' or null and perform for that required to handle ValueError:

Handling the exception is the way to go

try:
    gotdata = dlist[1]
except (IndexError, ValueError):
    gotdata = 'null'

AngularJS - $http.post send data as json

Use JSON.stringify() to wrap your json

var parameter = JSON.stringify({type:"user", username:user_email, password:user_password});
    $http.post(url, parameter).
    success(function(data, status, headers, config) {
        // this callback will be called asynchronously
        // when the response is available
        console.log(data);
      }).
      error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
      });

html select scroll bar

Horizontal scrollbars in a HTML Select are not natively supported. However, here's a way to create the appearance of a horizontal scrollbar:

1. First create a css class

<style type="text/css">
 .scrollable{
   overflow: auto;
   width: 70px; /* adjust this width depending to amount of text to display */
   height: 80px; /* adjust height depending on number of options to display */
   border: 1px silver solid;
 }
 .scrollable select{
   border: none;
 }
</style>

2. Wrap the SELECT inside a DIV - also, explicitly set the size to the number of options.

<div class="scrollable">
<select size="6" multiple="multiple">
    <option value="1" selected>option 1 The Long Option</option>
    <option value="2">option 2</option>
    <option value="3">option 3</option>
    <option value="4">option 4</option>
    <option value="5">option 5 Another Longer than the Long Option ;)</option>
    <option value="6">option 6</option>
</select>
</div>

How to put php inside JavaScript?

you need quotes around the string in javascript

var htmlString="<?php echo $htmlString; ?>";

How do I deal with installing peer dependencies in Angular CLI?

Peer dependency warnings, more often than not, can be ignored. The only time you will want to take action is if the peer dependency is missing entirely, or if the version of a peer dependency is higher than the version you have installed.

Let's take this warning as an example:

npm WARN @angular/[email protected] requires a peer of @angular/[email protected] but none is installed. You must install peer dependencies yourself.

With Angular, you would like the versions you are using to be consistent across all packages. If there are any incompatible versions, change the versions in your package.json, and run npm install so they are all synced up. I tend to keep my versions for Angular at the latest version, but you will need to make sure your versions are consistent for whatever version of Angular you require (which may not be the most recent).

In a situation like this:

npm WARN [email protected] requires a peer of @angular/core@^2.4.0 || ^4.0.0 but none is installed. You must install peer dependencies yourself.

If you are working with a version of Angular that is higher than 4.0.0, then you will likely have no issues. Nothing to do about this one then. If you are using an Angular version under 2.4.0, then you need to bring your version up. Update the package.json, and run npm install, or run npm install for the specific version you need. Like this:

npm install @angular/[email protected] --save

You can leave out the --save if you are running npm 5.0.0 or higher, that version saves the package in the dependencies section of the package.json automatically.

In this situation:

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

You are running Windows, and fsevent requires OSX. This warning can be ignored.

Hope this helps, and have fun learning Angular!

scrollIntoView Scrolls just too far

Based on the answer of Arseniy-II: I had the Use-Case where the scrolling entity was not window itself but a inner Template (in this case a div). In this scenario we need to set an ID for the scrolling container and get it via getElementById to use its scrolling function:

<div class="scroll-container" id="app-content">
  ...
</div>
const yOffsetForScroll = -100
const y = document.getElementById(this.idToScroll).getBoundingClientRect().top;
const main = document.getElementById('app-content');
main.scrollTo({
    top: y + main.scrollTop + yOffsetForScroll,
    behavior: 'smooth'
  });

Leaving it here in case someone faces a similar situation!

Importing Excel into a DataTable Quickly

MS Office Interop is slow and even Microsoft does not recommend Interop usage on server side and cannot be use to import large Excel files. For more details see why not to use OLE Automation from Microsoft point of view.

Instead, you can use any Excel library, like EasyXLS for example. This is a code sample that shows how to read the Excel file:

ExcelDocument workbook = new ExcelDocument();
DataSet ds = workbook.easy_ReadXLSActiveSheet_AsDataSet("excel.xls");
DataTable dataTable = ds.Tables[0];

If your Excel file has multiple sheets or for importing only ranges of cells (for better performances) take a look to more code samples on how to import Excel to DataTable in C# using EasyXLS.

How to append multiple items in one line in Python

mylist = [1,2,3]

def multiple_appends(listname, *element):
    listname.extend(element)

multiple_appends(mylist, 4, 5, "string", False)
print(mylist)

OUTPUT:

[1, 2, 3, 4, 5, 'string', False]

How do I convert hex to decimal in Python?

>>> int("0xff", 16)
255

or

>>> int("FFFF", 16)
65535

Read the docs.

Print "hello world" every X seconds

I figure it out with a timer, hope it helps. I have used a timer from java.util.Timer and TimerTask from the same package. See below:

TimerTask task = new TimerTask() {

    @Override
    public void run() {
        System.out.println("Hello World");
    }
};

Timer timer = new Timer();
timer.schedule(task, new Date(), 3000);

Delete files older than 10 days using shell script in Unix

find is the common tool for this kind of task :

find ./my_dir -mtime +10 -type f -delete

EXPLANATIONS

  • ./my_dir your directory (replace with your own)
  • -mtime +10 older than 10 days
  • -type f only files
  • -delete no surprise. Remove it to test your find filter before executing the whole command

And take care that ./my_dir exists to avoid bad surprises !

Mapping a JDBC ResultSet to an object

No need of storing resultSet values into String and again setting into POJO class. Instead set at the time you are retrieving.

Or best way switch to ORM tools like hibernate instead of JDBC which maps your POJO object direct to database.

But as of now use this:

List<User> users=new ArrayList<User>();

while(rs.next()) {
   User user = new User();      
   user.setUserId(rs.getString("UserId"));
   user.setFName(rs.getString("FirstName"));
  ...
  ...
  ...


  users.add(user);
} 

how to set start page in webconfig file in asp.net c#

the following code worked fine for me. kindly check other setting in your web config

 <system.webServer>
     <defaultDocument>
            <files>
                <clear />               
                <add value="Login.aspx"/>
            </files>
        </defaultDocument>
    </system.webServer>

'No JUnit tests found' in Eclipse

Sometimes, it occurs when you add Junit Library in Module path. So, Delete it there and add in Class path.

How do I install PHP cURL on Linux Debian?

Type in console as root:

apt-get update && apt-get install php5-curl

or with sudo:

sudo apt-get update && sudo apt-get install php5-curl

Sorry I missread.

1st, check your DNS config and if you can ping any host at all,

ping google.com
ping zm.archive.ubuntu.com

If it does not work, check /etc/resolv.conf or /etc/network/resolv.conf, if not, change your apt-source to a different one.

/etc/apt/sources.list

Mirrors: http://www.debian.org/mirror/list

You should not use Ubuntu sources on Debian and vice versa.

Git with SSH on Windows

I've found my ssh.exe in "C:/Program Files/Git/usr/bin" directory

Adding a UISegmentedControl to UITableView

   self.tableView.tableHeaderView = segmentedControl; 

If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.

enter image description here enter image description here

Redirection of standard and error output appending to the same log file

Andy gave me some good pointers, but I wanted to do it in an even cleaner way. Not to mention that with the 2>&1 >> method PowerShell complained to me about the log file being accessed by another process, i.e. both stderr and stdout trying to lock the file for access, I guess. So here's how I worked it around.

First let's generate a nice filename, but that's really just for being pedantic:

$name = "sync_common"
$currdate = get-date -f yyyy-MM-dd
$logfile = "c:\scripts\$name\log\$name-$currdate.txt"

And here's where the trick begins:

start-transcript -append -path $logfile

write-output "starting sync"
robocopy /mir /copyall S:\common \\10.0.0.2\common 2>&1 | Write-Output
some_other.exe /exeparams 2>&1 | Write-Output
...
write-output "ending sync"

stop-transcript

With start-transcript and stop-transcript you can redirect ALL output of PowerShell commands to a single file, but it doesn't work correctly with external commands. So let's just redirect all the output of those to the stdout of PS and let transcript do the rest.

In fact, I have no idea why the MS engineers say they haven't fixed this yet "due to the high cost and technical complexities involved" when it can be worked around in such a simple way.

Either way, running every single command with start-process is a huge clutter IMHO, but with this method, all you gotta do is append the 2>&1 | Write-Output code to each line which runs external commands.

Are there any log file about Windows Services Status?

Under Windows 7, open the Event Viewer. You can do this the way Gishu suggested for XP, typing eventvwr from the command line, or by opening the Control Panel, selecting System and Security, then Administrative Tools and finally Event Viewer. It may require UAC approval or an admin password.

In the left pane, expand Windows Logs and then System. You can filter the logs with Filter Current Log... from the Actions pane on the right and selecting "Service Control Manager." Or, depending on why you want this information, you might just need to look through the Error entries.

enter image description here

The actual log entry pane (not shown) is pretty user-friendly and self-explanatory. You'll be looking for messages like the following:

"The Praxco Assistant service entered the stopped state."
"The Windows Image Acquisition (WIA) service entered the running state."
"The MySQL service terminated unexpectedly. It has done this 3 time(s)."

jQuery "on create" event for dynamically-created elements

instead of...

$(".class").click( function() {
    // do something
});

You can write...

$('body').on('click', '.class', function() {
    // do something
});

Valid characters of a hostname?

Checkout this wiki, specifically the section Restrictions on valid host names

Hostnames are composed of series of labels concatenated with dots, as are all domain names. For example, "en.wikipedia.org" is a hostname. Each label must be between 1 and 63 characters long, and the entire hostname (including the delimiting dots but not a trailing dot) has a maximum of 253 ASCII characters.

The Internet standards (Requests for Comments) for protocols mandate that component hostname labels may contain only the ASCII letters 'a' through 'z' (in a case-insensitive manner), the digits '0' through '9', and the hyphen ('-'). The original specification of hostnames in RFC 952, mandated that labels could not start with a digit or with a hyphen, and must not end with a hyphen. However, a subsequent specification (RFC 1123) permitted hostname labels to start with digits. No other symbols, punctuation characters, or white space are permitted.

How to load external webpage in WebView

try this;

webView.loadData("<iframe src='http://www.google.com' style='border: 0; width: 100%; height: 100%'></iframe>", "text/html; charset=utf-8", "UTF-8");

Which tool to build a simple web front-end to my database

The most rapid option is to hand out MS Access or SQL Sever Management Studio (there's a free express edition) along with a read only account.

PHP is simple and has a well earned reputation for getting stuff done. PHP is excellent for copying and pasting code, and you can iterate insanely fast in PHP. PHP can lead to hard-to-maintain applications, and it can be difficult to set up a visual debugger.

Given that you use SQL Server, ASP.NET is also a good option. This is somewhat harder to setup; you'll need an IIS server, with a configured application. Iterations are a bit slower. ASP.NET is easier to maintain and Visual Studio is the best visual debugger around.

How do I create and read a value from cookie?

function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname+"="+cvalue+"; "+expires;
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function checkCookie() {
    var user=getCookie("username");
    if (user != "") {
        alert("Welcome again " + user);
    } else {
       user = prompt("Please enter your name:","");
       if (user != "" && user != null) {
           setCookie("username", user, 30);
       }
    }
}

How do I filter date range in DataTables?

Here is my solution, cobbled together from the range filter example in the datatables docs, and letting moment.js do the dirty work of comparing the dates.

HTML

<input 
    type="text" 
    id="min-date"
    class="date-range-filter"
    placeholder="From: yyyy-mm-dd">

<input 
    type="text" 
    id="max-date" 
    class="date-range-filter"
    placeholder="To: yyyy-mm-dd">

<table id="my-table">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Created At</th>
        </tr>
    </thead>
</table>

JS

Install Moment: npm install moment

// Assign moment to global namespace
window.moment = require('moment');

// Set up your table
table = $('#my-table').DataTable({
    // ... do your thing here.
});

// Extend dataTables search
$.fn.dataTable.ext.search.push(
    function( settings, data, dataIndex ) {
        var min  = $('#min-date').val();
        var max  = $('#max-date').val();
        var createdAt = data[2] || 0; // Our date column in the table

        if  ( 
                ( min == "" || max == "" )
                || 
                ( moment(createdAt).isSameOrAfter(min) && moment(createdAt).isSameOrBefore(max) ) 
            )
        {
            return true;
        }
        return false;
    }
);

// Re-draw the table when the a date range filter changes
$('.date-range-filter').change( function() {
    table.draw();
} );

JSFiddle Here

Notes

  • Using moment decouples the date comparison logic, and makes it easy to work with different formats. In my table, I used yyyy-mm-dd, but you could use mm/dd/yyyy as well. Be sure to reference moment's docs when parsing other formats, as you may need to modify what method you use.

How to change the button color when it is active using bootstrap?

HTML--

<div class="col-sm-12" id="my_styles">
   <button type="submit" class="btn btn-warning" id="1">Button1</button>
   <button type="submit" class="btn btn-warning" id="2">Button2</button>
</div>

css--

.active{
         background:red;
    }
 button.btn:active{
     background:red;
 }

jQuery--

jQuery("#my_styles .btn").click(function(){
    jQuery("#my_styles .btn").removeClass('active');
    jQuery(this).toggleClass('active'); 

});

view the live demo on jsfiddle

Working with $scope.$emit and $scope.$on

According to the angularjs event docs the receiving end should be containing arguments with a structure like

@params

-- {Object} event being the event object containing info on the event

-- {Object} args that are passed by the callee (Note that this can only be one so better to send in a dictionary object always)

$scope.$on('fooEvent', function (event, args) { console.log(args) }); From your code

Also if you are trying to get a shared piece of information to be available accross different controllers there is an another way to achieve that and that is angular services.Since the services are singletons information can be stored and fetched across controllers.Simply create getter and setter functions in that service, expose these functions, make global variables in the service and use them to store the info

Any reason not to use '+' to concatenate two strings?

Plus operator is perfectly fine solution to concatenate two Python strings. But if you keep adding more than two strings (n > 25) , you might want to think something else.

''.join([a, b, c]) trick is a performance optimization.

Problems when trying to load a package in R due to rJava

Answer in link resolved my issue.

Before resolution, I tried by adding JAVA_HOME to windows environments. It resolved this error but created another issue. The solution in above link resolves this issue without creating additional issues.

Is there a no-duplicate List implementation out there?

So here's what I did eventually. I hope this helps someone else.

class NoDuplicatesList<E> extends LinkedList<E> {
    @Override
    public boolean add(E e) {
        if (this.contains(e)) {
            return false;
        }
        else {
            return super.add(e);
        }
    }

    @Override
    public boolean addAll(Collection<? extends E> collection) {
        Collection<E> copy = new LinkedList<E>(collection);
        copy.removeAll(this);
        return super.addAll(copy);
    }

    @Override
    public boolean addAll(int index, Collection<? extends E> collection) {
        Collection<E> copy = new LinkedList<E>(collection);
        copy.removeAll(this);
        return super.addAll(index, copy);
    }

    @Override
    public void add(int index, E element) {
        if (this.contains(element)) {
            return;
        }
        else {
            super.add(index, element);
        }
    }
}   

SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: YES) Symfony2

I dont know what is the exact reason but I solved the problem running:

   app/console cache:clear --env=prod

How to increase storage for Android Emulator? (INSTALL_FAILED_INSUFFICIENT_STORAGE)

avd manager has an option "ideal size of system partition", try setting that to 1024MB, or use the commandline launch option that does the same.

fyi, I only encountered this problem with the 4.0 emulator image.

How do I jump out of a foreach loop in C#?

Use break; and this will exit the foreach loop

laravel the requested url was not found on this server

In httpd.conf file you need to remove #

#LoadModule rewrite_module modules/mod_rewrite.so

after removing # line will look like this:

LoadModule rewrite_module modules/mod_rewrite.so

And Apache restart

What is the difference between .py and .pyc files?

Python compiles the .py and saves files as .pyc so it can reference them in subsequent invocations.

There's no harm in deleting them, but they will save compilation time if you're doing lots of processing.

Changing image sizes proportionally using CSS?

This help me to make the image 150% with ease.

.img-popup img {
  transform: scale(1.5);
}

How do I define a method in Razor?

You could also do it with a Func like this

@{
    var getStyle = new Func<int, int, string>((width, margin) => string.Format("width: {0}px; margin: {1}px;", width, margin));
}

<div style="@getStyle(50, 2)"></div>

Comment out HTML and PHP together

I agree that Pascal's solution is the way to go, but for those saying that it adds an extra task to remove the comments, you can use the following comment style trick to simplify your life:

<?php /* ?>
<tr>
      <td><?php echo $entry_keyword; ?></td>
      <td><input type="text" name="keyword" value="<?php echo $keyword; ?>" /></td>
    </tr>
    <tr>
      <td><?php echo $entry_sort_order; ?></td>
      <td><input name="sort_order" value="<?php echo $sort_order; ?>" size="1" /></td>
    </tr>
<?php // */ ?>

In order to stop the code block being commented out, simply change the opening comment to:

<?php //* ?>

JAX-WS client : what's the correct path to access the local WSDL?

One other approach that we have taken successfully is to generate the WS client proxy code using wsimport (from Ant, as an Ant task) and specify the wsdlLocation attribute.

<wsimport debug="true" keep="true" verbose="false" target="2.1" sourcedestdir="${generated.client}" wsdl="${src}${wsdl.file}" wsdlLocation="${wsdl.file}">
</wsimport>

Since we run this for a project w/ multiple WSDLs, the script resolves the $(wsdl.file} value dynamically which is set up to be /META-INF/wsdl/YourWebServiceName.wsdl relative to the JavaSource location (or /src, depending on how you have your project set up). During the build proess, the WSDL and XSDs files are copied to this location and packaged in the JAR file. (similar to the solution described by Bhasakar above)

MyApp.jar
|__META-INF
   |__wsdl
      |__YourWebServiceName.wsdl
      |__YourWebServiceName_schema1.xsd
      |__YourWebServiceName_schmea2.xsd

Note: make sure the WSDL files are using relative refrerences to any imported XSDs and not http URLs:

  <types>
    <xsd:schema>
      <xsd:import namespace="http://valueobject.common.services.xyz.com/" schemaLocation="YourWebService_schema1.xsd"/>
    </xsd:schema>
    <xsd:schema>
      <xsd:import namespace="http://exceptions.util.xyz.com/" schemaLocation="YourWebService_schema2.xsd"/>
    </xsd:schema>
  </types>

In the generated code, we find this:

/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.2-b05-
 * Generated source version: 2.1
 * 
 */
@WebServiceClient(name = "YourService", targetNamespace = "http://test.webservice.services.xyz.com/", wsdlLocation = "/META-INF/wsdl/YourService.wsdl")
public class YourService_Service
    extends Service
{

    private final static URL YOURWEBSERVICE_WSDL_LOCATION;
    private final static WebServiceException YOURWEBSERVICE_EXCEPTION;
    private final static QName YOURWEBSERVICE_QNAME = new QName("http://test.webservice.services.xyz.com/", "YourService");

    static {
        YOURWEBSERVICE_WSDL_LOCATION = com.xyz.services.webservice.test.YourService_Service.class.getResource("/META-INF/wsdl/YourService.wsdl");
        WebServiceException e = null;
        if (YOURWEBSERVICE_WSDL_LOCATION == null) {
            e = new WebServiceException("Cannot find '/META-INF/wsdl/YourService.wsdl' wsdl. Place the resource correctly in the classpath.");
        }
        YOURWEBSERVICE_EXCEPTION = e;
    }

    public YourService_Service() {
        super(__getWsdlLocation(), YOURWEBSERVICE_QNAME);
    }

    public YourService_Service(URL wsdlLocation, QName serviceName) {
        super(wsdlLocation, serviceName);
    }

    /**
     * 
     * @return
     *     returns YourService
     */
    @WebEndpoint(name = "YourServicePort")
    public YourService getYourServicePort() {
        return super.getPort(new QName("http://test.webservice.services.xyz.com/", "YourServicePort"), YourService.class);
    }

    /**
     * 
     * @param features
     *     A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy.  Supported features not in the <code>features</code> parameter will have their default values.
     * @return
     *     returns YourService
     */
    @WebEndpoint(name = "YourServicePort")
    public YourService getYourServicePort(WebServiceFeature... features) {
        return super.getPort(new QName("http://test.webservice.services.xyz.com/", "YourServicePort"), YourService.class, features);
    }

    private static URL __getWsdlLocation() {
        if (YOURWEBSERVICE_EXCEPTION!= null) {
            throw YOURWEBSERVICE_EXCEPTION;
        }
        return YOURWEBSERVICE_WSDL_LOCATION;
    }

}

Perhaps this might help too. It's just a different approach that does not use the "catalog" approach.

How to read a specific line using the specific line number from a file in Java?

Although as said in other answers, it is not possible to get to the exact line without knowing the offset ( pointer ) before. So, I've achieved this by creating an temporary index file which would store the offset values of every line. If the file is small enough, you could just store the indexes ( offset ) in memory without needing a separate file for it.

The offsets can be calculated by using the RandomAccessFile

    RandomAccessFile raf = new RandomAccessFile("myFile.txt","r"); 
    //above 'r' means open in read only mode
    ArrayList<Integer> arrayList = new ArrayList<Integer>();
    String cur_line = "";
    while((cur_line=raf.readLine())!=null)
    {
    arrayList.add(raf.getFilePointer());
    }
    //Print the 32 line
    //Seeks the file to the particular location from where our '32' line starts
    raf.seek(raf.seek(arrayList.get(31));
    System.out.println(raf.readLine());
    raf.close();

Also visit the java docs for more information: https://docs.oracle.com/javase/8/docs/api/java/io/RandomAccessFile.html#mode

Complexity : This is O(n) as it reads the entire file once. Please be aware for the memory requirements. If it's too big to be in memory, then make a temporary file that stores the offsets instead of ArrayList as shown above.

Note : If all you want in '32' line, you just have to call the readLine() also available through other classes '32' times. The above approach is useful if you want to get the a specific line (based on line number of course) multiple times.

Thanks !

How to detect READ_COMMITTED_SNAPSHOT is enabled?

Neither on SQL2005 nor 2012 does DBCC USEROPTIONS show is_read_committed_snapshot_on:

Set Option  Value
textsize    2147483647
language    us_english
dateformat  mdy
datefirst   7
lock_timeout    -1
quoted_identifier   SET
arithabort  SET
ansi_null_dflt_on   SET
ansi_warnings   SET
ansi_padding    SET
ansi_nulls  SET
concat_null_yields_null SET
isolation level read committed

byte[] to file in Java

Use Apache Commons IO

FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray)

Or, if you insist on making work for yourself...

try (FileOutputStream fos = new FileOutputStream("pathname")) {
   fos.write(myByteArray);
   //fos.close(); There is no more need for this line since you had created the instance of "fos" inside the try. And this will automatically close the OutputStream
}

How can I make one python file run another?

Get one python file to run another, using python 2.7.3 and Ubuntu 12.10:

  1. Put this in main.py:

    #!/usr/bin/python
    import yoursubfile
    
  2. Put this in yoursubfile.py

    #!/usr/bin/python
    print("hello")
    
  3. Run it:

    python main.py 
    
  4. It prints:

    hello
    

Thus main.py runs yoursubfile.py

There are 8 ways to answer this question, A more canonical answer is here: How to import other Python files?

How do I hide the bullets on my list for the sidebar?

You have a selector ul on line 252 which is setting list-style: square outside none (a square bullet). You'll have to change it to list-style: none or just remove the line.

If you only want to remove the bullets from that specific instance, you can use the specific selector for that list and its items as follows:

ul#groups-list.items-list { list-style: none }

Error - "UNION operator must have an equal number of expressions" when using CTE for recursive selection

The second result set have only one column but it should have 3 columns for it to be contented to the first result set

(columns must match when you use UNION)

Try to add ID as first column and PartOf_LOC_id to your result set, so you can do the UNION.

;
WITH    q AS ( SELECT   ID ,
                    Location ,
                    PartOf_LOC_id
           FROM     tblLocation t
           WHERE    t.ID = 1 -- 1 represents an example
           UNION ALL
           SELECT   t.ID ,
                    parent.Location + '>' + t.Location ,
                    t.PartOf_LOC_id
           FROM     tblLocation t
                    INNER JOIN q parent ON parent.ID = t.LOC_PartOf_ID
         )
SELECT  *
FROM    q

How to perform OR condition in django queryset?

Because QuerySets implement the Python __or__ operator (|), or union, it just works. As you'd expect, the | binary operator returns a QuerySet so order_by(), .distinct(), and other queryset filters can be tacked on to the end.

combined_queryset = User.objects.filter(income__gte=5000) | User.objects.filter(income__isnull=True)
ordered_queryset = combined_queryset.order_by('-income')

Update 2019-06-20: This is now fully documented in the Django 2.1 QuerySet API reference. More historic discussion can be found in DjangoProject ticket #21333.

How to escape comma and double quote at same time for CSV file?

If you're using CSVWriter. Check that you don't have the option

.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)

When I removed it the comma was showing as expected and not treating it as new column

call javascript function on hyperlink click

The simplest answer of all is...

_x000D_
_x000D_
<a href="javascript:alert('You clicked!')">My link</a>
_x000D_
_x000D_
_x000D_

Or to answer the question of calling a javascript function:

_x000D_
_x000D_
<script type="text/javascript">_x000D_
function myFunction(myMessage) {_x000D_
    alert(myMessage);_x000D_
}_x000D_
</script>_x000D_
_x000D_
<a href="javascript:myFunction('You clicked!')">My link</a>
_x000D_
_x000D_
_x000D_

Pandas: change data type of Series to String

You can use:

df.loc[:,'id'] = df.loc[:, 'id'].astype(str)

This is why they recommend this solution: Pandas doc

TD;LR

To reflect some of the answers:

df['id'] = df['id'].astype("string")

This will break on the given example because it will try to convert to StringArray which can not handle any number in the 'string'.

df['id']= df['id'].astype(str)

For me this solution throw some warning:

> SettingWithCopyWarning:  
> A value is trying to be set on a copy of a
> slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

HTML5 Audio Looping

This works and it is a lot easier to toggle that the methods above:

use inline: onended="if($(this).attr('data-loop')){ this.currentTime = 0; this.play(); }"

Turn the looping on by $(audio_element).attr('data-loop','1'); Turn the looping off by $(audio_element).removeAttr('data-loop');

jQuery: enabling/disabling datepicker

$("#nicIssuedDate").prop('disabled', true);

This is works 100% with bootstrap Datepicker

Nexus 5 USB driver

Is it your first android connected to your computer? Sometimes windows drivers need to be erased. Refer http://forum.xda-developers.com/showthread.php?t=2512549

HashMap with multiple values under the same key

No, not just as a HashMap. You'd basically need a HashMap from a key to a collection of values.

If you're happy to use external libraries, Guava has exactly this concept in Multimap with implementations such as ArrayListMultimap and HashMultimap.

Killing a process using Java

If you start the process from with in your Java application (ex. by calling Runtime.exec() or ProcessBuilder.start()) then you have a valid Process reference to it, and you can invoke the destroy() method in Process class to kill that particular process.

But be aware that if the process that you invoke creates new sub-processes, those may not be terminated (see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4770092).

On the other hand, if you want to kill external processes (which you did not spawn from your Java app), then one thing you can do is to call O/S utilities which allow you to do that. For example, you can try a Runtime.exec() on kill command under Unix / Linux and check for return values to ensure that the application was killed or not (0 means success, -1 means error). But that of course will make your application platform dependent.

How to handle AssertionError in Python and find out which line or statement it occurred on?

The traceback module and sys.exc_info are overkill for tracking down the source of an exception. That's all in the default traceback. So instead of calling exit(1) just re-raise:

try:
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
    print 'Houston, we have a problem.'
    raise

Which gives the following output that includes the offending statement and line number:

Houston, we have a problem.
Traceback (most recent call last):
  File "/tmp/poop.py", line 2, in <module>
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie

Similarly the logging module makes it easy to log a traceback for any exception (including those which are caught and never re-raised):

import logging

try:
    assert False == True 
except AssertionError:
    logging.error("Nothing is real but I can't quit...", exc_info=True)

Read int values from a text file in C

How about this?

fscanf(file,"%d %d %d %d %d %d %d",&line1_1,&line1_2, &line1_3, &line2_1, &line2_2, &line3_1, &line3_2); 

In this case spaces in fscanf match multiple occurrences of any whitespace until the next token in found.

Split code over multiple lines in an R script

For that particular case there is file.path :

File <- file.path("~", 
  "a", 
  "very", 
  "long",
  "path",
  "here",
  "that",
  "goes",
  "beyond",
  "80",
  "characters",
  "and",
  "then",
  "some",
  "more")
setwd(File)

How to make node.js require absolute? (instead of relative)

IMHO, the easiest way is to define your own function as part of GLOBAL object. Create projRequire.js in the root of you project with the following contents:

var projectDir = __dirname;

module.exports = GLOBAL.projRequire = function(module) {
  return require(projectDir + module);
}

In your main file before requireing any of project-specific modules:

// init projRequire
require('./projRequire');

After that following works for me:

// main file
projRequire('/lib/lol');

// index.js at projectDir/lib/lol/index.js
console.log('Ok');


@Totty, I've comed up with another solution, which could work for case you described in comments. Description gonna be tl;dr, so I better show a picture with structure of my test project.

How do I use arrays in C++?

5. Common pitfalls when using arrays.

5.1 Pitfall: Trusting type-unsafe linking.

OK, you’ve been told, or have found out yourself, that globals (namespace scope variables that can be accessed outside the translation unit) are Evil™. But did you know how truly Evil™ they are? Consider the program below, consisting of two files [main.cpp] and [numbers.cpp]:

// [main.cpp]
#include <iostream>

extern int* numbers;

int main()
{
    using namespace std;
    for( int i = 0;  i < 42;  ++i )
    {
        cout << (i > 0? ", " : "") << numbers[i];
    }
    cout << endl;
}

// [numbers.cpp]
int numbers[42] = {1, 2, 3, 4, 5, 6, 7, 8, 9};

In Windows 7 this compiles and links fine with both MinGW g++ 4.4.1 and Visual C++ 10.0.

Since the types don't match, the program crashes when you run it.

The Windows 7 crash dialog

In-the-formal explanation: the program has Undefined Behavior (UB), and instead of crashing it can therefore just hang, or perhaps do nothing, or it can send threating e-mails to the presidents of the USA, Russia, India, China and Switzerland, and make Nasal Daemons fly out of your nose.

In-practice explanation: in main.cpp the array is treated as a pointer, placed at the same address as the array. For 32-bit executable this means that the first int value in the array, is treated as a pointer. I.e., in main.cpp the numbers variable contains, or appears to contain, (int*)1. This causes the program to access memory down at very bottom of the address space, which is conventionally reserved and trap-causing. Result: you get a crash.

The compilers are fully within their rights to not diagnose this error, because C++11 §3.5/10 says, about the requirement of compatible types for the declarations,

[N3290 §3.5/10]
A violation of this rule on type identity does not require a diagnostic.

The same paragraph details the variation that is allowed:

… declarations for an array object can specify array types that differ by the presence or absence of a major array bound (8.3.4).

This allowed variation does not include declaring a name as an array in one translation unit, and as a pointer in another translation unit.

5.2 Pitfall: Doing premature optimization (memset & friends).

Not written yet

5.3 Pitfall: Using the C idiom to get number of elements.

With deep C experience it’s natural to write …

#define N_ITEMS( array )   (sizeof( array )/sizeof( array[0] ))

Since an array decays to pointer to first element where needed, the expression sizeof(a)/sizeof(a[0]) can also be written as sizeof(a)/sizeof(*a). It means the same, and no matter how it’s written it is the C idiom for finding the number elements of array.

Main pitfall: the C idiom is not typesafe. For example, the code …

#include <stdio.h>

#define N_ITEMS( array ) (sizeof( array )/sizeof( *array ))

void display( int const a[7] )
{
    int const   n = N_ITEMS( a );          // Oops.
    printf( "%d elements.\n", n );
}

int main()
{
    int const   moohaha[]   = {1, 2, 3, 4, 5, 6, 7};

    printf( "%d elements, calling display...\n", N_ITEMS( moohaha ) );
    display( moohaha );
}

passes a pointer to N_ITEMS, and therefore most likely produces a wrong result. Compiled as a 32-bit executable in Windows 7 it produces …

7 elements, calling display...
1 elements.

  1. The compiler rewrites int const a[7] to just int const a[].
  2. The compiler rewrites int const a[] to int const* a.
  3. N_ITEMS is therefore invoked with a pointer.
  4. For a 32-bit executable sizeof(array) (size of a pointer) is then 4.
  5. sizeof(*array) is equivalent to sizeof(int), which for a 32-bit executable is also 4.

In order to detect this error at run time you can do …

#include <assert.h>
#include <typeinfo>

#define N_ITEMS( array )       (                               \
    assert((                                                    \
        "N_ITEMS requires an actual array as argument",        \
        typeid( array ) != typeid( &*array )                    \
        )),                                                     \
    sizeof( array )/sizeof( *array )                            \
    )

7 elements, calling display...
Assertion failed: ( "N_ITEMS requires an actual array as argument", typeid( a ) != typeid( &*a ) ), file runtime_detect ion.cpp, line 16

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

The runtime error detection is better than no detection, but it wastes a little processor time, and perhaps much more programmer time. Better with detection at compile time! And if you're happy to not support arrays of local types with C++98, then you can do that:

#include <stddef.h>

typedef ptrdiff_t   Size;

template< class Type, Size n >
Size n_items( Type (&)[n] ) { return n; }

#define N_ITEMS( array )       n_items( array )

Compiling this definition substituted into the first complete program, with g++, I got …

M:\count> g++ compile_time_detection.cpp
compile_time_detection.cpp: In function 'void display(const int*)':
compile_time_detection.cpp:14: error: no matching function for call to 'n_items(const int*&)'

M:\count> _

How it works: the array is passed by reference to n_items, and so it does not decay to pointer to first element, and the function can just return the number of elements specified by the type.

With C++11 you can use this also for arrays of local type, and it's the type safe C++ idiom for finding the number of elements of an array.

5.4 C++11 & C++14 pitfall: Using a constexpr array size function.

With C++11 and later it's natural, but as you'll see dangerous!, to replace the C++03 function

typedef ptrdiff_t   Size;

template< class Type, Size n >
Size n_items( Type (&)[n] ) { return n; }

with

using Size = ptrdiff_t;

template< class Type, Size n >
constexpr auto n_items( Type (&)[n] ) -> Size { return n; }

where the significant change is the use of constexpr, which allows this function to produce a compile time constant.

For example, in contrast to the C++03 function, such a compile time constant can be used to declare an array of the same size as another:

// Example 1
void foo()
{
    int const x[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 4};
    constexpr Size n = n_items( x );
    int y[n] = {};
    // Using y here.
}

But consider this code using the constexpr version:

// Example 2
template< class Collection >
void foo( Collection const& c )
{
    constexpr int n = n_items( c );     // Not in C++14!
    // Use c here
}

auto main() -> int
{
    int x[42];
    foo( x );
}

The pitfall: as of July 2015 the above compiles with MinGW-64 5.1.0 with -pedantic-errors, and, testing with the online compilers at gcc.godbolt.org/, also with clang 3.0 and clang 3.2, but not with clang 3.3, 3.4.1, 3.5.0, 3.5.1, 3.6 (rc1) or 3.7 (experimental). And important for the Windows platform, it does not compile with Visual C++ 2015. The reason is a C++11/C++14 statement about use of references in constexpr expressions:

C++11 C++14 $5.19/2 nineth dash

A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine (1.9), would evaluate one of the following expressions:
        ?

  • an id-expression that refers to a variable or data member of reference type unless the reference has a preceding initialization and either
    • it is initialized with a constant expression or
    • it is a non-static data member of an object whose lifetime began within the evaluation of e;

One can always write the more verbose

// Example 3  --  limited

using Size = ptrdiff_t;

template< class Collection >
void foo( Collection const& c )
{
    constexpr Size n = std::extent< decltype( c ) >::value;
    // Use c here
}

… but this fails when Collection is not a raw array.

To deal with collections that can be non-arrays one needs the overloadability of an n_items function, but also, for compile time use one needs a compile time representation of the array size. And the classic C++03 solution, which works fine also in C++11 and C++14, is to let the function report its result not as a value but via its function result type. For example like this:

// Example 4 - OK (not ideal, but portable and safe)

#include <array>
#include <stddef.h>

using Size = ptrdiff_t;

template< Size n >
struct Size_carrier
{
    char sizer[n];
};

template< class Type, Size n >
auto static_n_items( Type (&)[n] )
    -> Size_carrier<n>;
// No implementation, is used only at compile time.

template< class Type, size_t n >        // size_t for g++
auto static_n_items( std::array<Type, n> const& )
    -> Size_carrier<n>;
// No implementation, is used only at compile time.

#define STATIC_N_ITEMS( c ) \
    static_cast<Size>( sizeof( static_n_items( c ).sizer ) )

template< class Collection >
void foo( Collection const& c )
{
    constexpr Size n = STATIC_N_ITEMS( c );
    // Use c here
    (void) c;
}

auto main() -> int
{
    int x[42];
    std::array<int, 43> y;
    foo( x );
    foo( y );
}

About the choice of return type for static_n_items: this code doesn't use std::integral_constant because with std::integral_constant the result is represented directly as a constexpr value, reintroducing the original problem. Instead of a Size_carrier class one can let the function directly return a reference to an array. However, not everybody is familiar with that syntax.

About the naming: part of this solution to the constexpr-invalid-due-to-reference problem is to make the choice of compile time constant explicit.

Hopefully the oops-there-was-a-reference-involved-in-your-constexpr issue will be fixed with C++17, but until then a macro like the STATIC_N_ITEMS above yields portability, e.g. to the clang and Visual C++ compilers, retaining type safety.

Related: macros do not respect scopes, so to avoid name collisions it can be a good idea to use a name prefix, e.g. MYLIB_STATIC_N_ITEMS.

Changing the background color of a drop down list transparent in html

Or maybe

 background: transparent !important;
 color: #ffffff;

How to use ADB in Android Studio to view an SQLite DB

Easiest Way: Connect to Sqlite3 via ADB Shell

I haven't found any way to do that in Android Studio, but I access the db with a remote shell instead of pulling the file each time.

Find all info here: http://developer.android.com/tools/help/sqlite3.html

1- Go to your platform-tools folder in a command prompt

2- Enter the command adb devices to get the list of your devices

C:\Android\adt-bundle-windows-x86_64\sdk\platform-tools>adb devices
List of devices attached
emulator-xxxx   device

3- Connect a shell to your device:

C:\Android\adt-bundle-windows-x86_64\sdk\platform-tools>adb -s emulator-xxxx shell

4a- You can bypass this step on rooted device

run-as <your-package-name> 

4b- Navigate to the folder containing your db file:

cd data/data/<your-package-name>/databases/

5- run sqlite3 to connect to your db:

sqlite3 <your-db-name>.db

6- run sqlite3 commands that you like eg:

Select * from table1 where ...;

Note: Find more commands to run below.

SQLite cheatsheet

There are a few steps to see the tables in an SQLite database:

  1. List the tables in your database:

    .tables
    
  2. List how the table looks:

    .schema tablename
    
  3. Print the entire table:

    SELECT * FROM tablename;
    
  4. List all of the available SQLite prompt commands:

    .help
    

Using GPU from a docker container?

Regan's answer is great, but it's a bit out of date, since the correct way to do this is avoid the lxc execution context as Docker has dropped LXC as the default execution context as of docker 0.9.

Instead it's better to tell docker about the nvidia devices via the --device flag, and just use the native execution context rather than lxc.

Environment

These instructions were tested on the following environment:

  • Ubuntu 14.04
  • CUDA 6.5
  • AWS GPU instance.

Install nvidia driver and cuda on your host

See CUDA 6.5 on AWS GPU Instance Running Ubuntu 14.04 to get your host machine setup.

Install Docker

$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 36A1D7869245C8950F966E92D8576A8BA88D21E9
$ sudo sh -c "echo deb https://get.docker.com/ubuntu docker main > /etc/apt/sources.list.d/docker.list"
$ sudo apt-get update && sudo apt-get install lxc-docker

Find your nvidia devices

ls -la /dev | grep nvidia

crw-rw-rw-  1 root root    195,   0 Oct 25 19:37 nvidia0 
crw-rw-rw-  1 root root    195, 255 Oct 25 19:37 nvidiactl
crw-rw-rw-  1 root root    251,   0 Oct 25 19:37 nvidia-uvm

Run Docker container with nvidia driver pre-installed

I've created a docker image that has the cuda drivers pre-installed. The dockerfile is available on dockerhub if you want to know how this image was built.

You'll want to customize this command to match your nvidia devices. Here's what worked for me:

 $ sudo docker run -ti --device /dev/nvidia0:/dev/nvidia0 --device /dev/nvidiactl:/dev/nvidiactl --device /dev/nvidia-uvm:/dev/nvidia-uvm tleyden5iwx/ubuntu-cuda /bin/bash

Verify CUDA is correctly installed

This should be run from inside the docker container you just launched.

Install CUDA samples:

$ cd /opt/nvidia_installers
$ ./cuda-samples-linux-6.5.14-18745345.run -noprompt -cudaprefix=/usr/local/cuda-6.5/

Build deviceQuery sample:

$ cd /usr/local/cuda/samples/1_Utilities/deviceQuery
$ make
$ ./deviceQuery   

If everything worked, you should see the following output:

deviceQuery, CUDA Driver = CUDART, CUDA Driver Version = 6.5, CUDA Runtime Version = 6.5, NumDevs =    1, Device0 = GRID K520
Result = PASS

Fastest method to replace all instances of a character in a string

You can use the following:

newStr = str.replace(/[^a-z0-9]/gi, '_');

or

newStr = str.replace(/[^a-zA-Z0-9]/g, '_');

This is going to replace all the character that are not letter or numbers to ('_'). Simple change the underscore value for whatever you want to replace it.

How to set JAVA_HOME path on Ubuntu?

I normally set paths in

~/.bashrc

However for Java, I followed instructions at https://askubuntu.com/questions/55848/how-do-i-install-oracle-java-jdk-7

and it was sufficient for me.

you can also define multiple java_home's and have only one of them active (rest commented).

suppose in your bashrc file, you have

export JAVA_HOME=......jdk1.7

#export JAVA_HOME=......jdk1.8

notice 1.8 is commented. Once you do

source ~/.bashrc

jdk1.7 will be in path.

you can switch them fairly easily this way. There are other more permanent solutions too. The link I posted has that info.

Boxplot in R showing the mean

abline(h=mean(x))

for a horizontal line (use v instead of h for vertical if you orient your boxplot horizontally), or

points(mean(x))

for a point. Use the parameter pch to change the symbol. You may want to colour them to improve visibility too.

Note that these are called after you have drawn the boxplot.

If you are using the formula interface, you would have to construct the vector of means. For example, taking the first example from ?boxplot:

boxplot(count ~ spray, data = InsectSprays, col = "lightgray")
means <- tapply(InsectSprays$count,InsectSprays$spray,mean)
points(means,col="red",pch=18)

If your data contains missing values, you might want to replace the last argument of the tapply function with function(x) mean(x,na.rm=T)

"Cannot update paths and switch to branch at the same time"

For me I needed to add the remote:

git remote -add myRemoteName('origin' in your case) remoteGitURL

then I could fetch

git fetch myRemoteName

Warning: Cannot modify header information - headers already sent by ERROR

Check the document encoding.

I had this same problem. I develop on Windows XP using Notepad++ and WampServer to run Apache locally and all was fine. After uploading to hosting provider that uses Apache on Unix I got this error. I had no extra PHP tags or white-space from extra lines after the closing tag.

For me this was caused by the encoding of the text documents. I used the "Convert to UTF-8 without BOM" option in Notepad++(under Encoding tab) and reloaded to the web server. Problem fixed, no code/editing changes required.

How do I insert a JPEG image into a python Tkinter window?

from tkinter import *
from PIL import ImageTk, Image

window = Tk()
window.geometry("1000x300")

path = "1.jpg"

image = PhotoImage(Image.open(path))

panel = Label(window, image = image)

panel.pack()

window.mainloop()

How to access URL segment(s) in blade in Laravel 5?

BASED ON LARAVEL 5.7 & ABOVE

To get all segments of current URL:

$current_uri = request()->segments();

To get segment posts from http://example.com/users/posts/latest/

NOTE: Segments are an array that starts at index 0. The first element of array starts after the TLD part of the url. So in the above url, segment(0) will be users and segment(1) will be posts.

//get segment 0
$segment_users = request()->segment(0); //returns 'users'
//get segment 1
$segment_posts = request()->segment(1); //returns 'posts'

You may have noted that the segment method only works with the current URL ( url()->current() ). So I designed a method to work with previous URL too by cloning the segment() method:

public function index()
{
    $prev_uri_segments = $this->prev_segments(url()->previous());
}

 /**
 * Get all of the segments for the previous uri.
 *
 * @return array
 */
public function prev_segments($uri)
{
    $segments = explode('/', str_replace(''.url('').'', '', $uri));

    return array_values(array_filter($segments, function ($value) {
        return $value !== '';
    }));
}

How do I convert a pandas Series or index to a Numpy array?

You can use df.index to access the index object and then get the values in a list using df.index.tolist(). Similarly, you can use df['col'].tolist() for Series.

How to show a GUI message box from a bash script in linux?

Zenity is really the exact tool that I think that you are looking for.

or

zenity --help

Passing javascript variable to html textbox

Pass the variable to the form element like this

your form element

<input type="text" id="mytext">

javascript

var test = "Hello";
document.getElementById("mytext").value = test;//Now you get the js variable inside your form element

How to get div height to auto-adjust to background size?

This Worked For Me:

background-image: url("/assets/image_complete_path");
background-position: center; /* Center the image */
background-repeat: no-repeat; /* Do not repeat the image */
background-size: cover;
height: 100%;

Event listener for when element becomes visible?

There is at least one way, but it's not a very good one. You could just poll the element for changes like this:

var previous_style,
    poll = window.setInterval(function()
{
    var current_style = document.getElementById('target').style.display;
    if (previous_style != current_style) {
        alert('style changed');
        window.clearInterval(poll);
    } else {
        previous_style = current_style;
    }
}, 100);

The DOM standard also specifies mutation events, but I've never had the chance to use them, and I'm not sure how well they're supported. You'd use them like this:

target.addEventListener('DOMAttrModified', function()
{
    if (e.attrName == 'style') {
        alert('style changed');
    }
}, false);

This code is off the top of my head, so I'm not sure if it'd work.

The best and easiest solution would be to have a callback in the function displaying your target.

Python group by

result = []
# Make a set of your "types":
input_set = set([tpl[1] for tpl in input])
>>> set(['ETH', 'KAT', 'NOT'])
# Iterate over the input_set
for type_ in input_set:
    # a dict to gather things:
    D = {}
    # filter all tuples from your input with the same type as type_
    tuples = filter(lambda tpl: tpl[1] == type_, input)
    # write them in the D:
    D["type"] = type_
    D["itmes"] = [tpl[0] for tpl in tuples]
    # append D to results:
    result.append(D)

result
>>> [{'itmes': ['9085267', '11788544'], 'type': 'NOT'}, {'itmes': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'itmes': ['11013331', '9843236'], 'type': 'KAT'}]

Delete keychain items when an app is uninstalled

You can take advantage of the fact that NSUserDefaults are cleared by uninstallation of an app. For example:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //Clear keychain on first run in case of reinstallation
    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"FirstRun"]) {
        // Delete values from keychain here
        [[NSUserDefaults standardUserDefaults] setValue:@"1strun" forKey:@"FirstRun"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }

    //...Other stuff that usually happens in didFinishLaunching
}

This checks for and sets a "FirstRun" key/value in NSUserDefaults on the first run of your app if it's not already set. There's a comment where you should put code to delete values from the keychain. Synchronize can be called to make sure the "FirstRun" key/value is immediately persisted in case the user kills the app manually before the system persists it.

How does the Java 'for each' loop work?

public static Boolean Add_Tag(int totalsize)
{ List<String> fullst = new ArrayList<String>();
            for(int k=0;k<totalsize;k++)
            {
              fullst.addAll();
            }
}

MySQL: #1075 - Incorrect table definition; autoincrement vs another key?

You can make the id the primary key, and set member_id to NOT NULL UNIQUE. (Which you've done.) Columns that are NOT NULL UNIQUE can be the target of foreign key references, just like a primary key can. (I'm pretty sure that's true of all SQL platforms.)

At the conceptual level, there's no difference between PRIMARY KEY and NOT NULL UNIQUE. At the physical level, this is a MySQL issue; other SQL platforms will let you use a sequence without making it the primary key.

But if performance is really important, you should think twice about widening your table by four bytes per row for that tiny visual convenience. In addition, if you switch to INNODB in order to enforce foreign key constraints, MySQL will use your primary key in a clustered index. Since you're not using your primary key, I imagine that could hurt performance.

Comparing two arrays of objects, and exclude the elements who match values into new array in JS

well, this using lodash or vanilla javascript it depends on the situation.

but for just return the array that contains the duplicates it can be achieved by the following, offcourse it was taken from @1983

var result = result1.filter(function (o1) {
    return result2.some(function (o2) {
        return o1.id === o2.id; // return the ones with equal id
   });
});
// if you want to be more clever...
let result = result1.filter(o1 => result2.some(o2 => o1.id === o2.id));