text:
Q: Switching to other versions of PyCharm unsets the Project Interpreter in the previous one I have installed both PyCharm Edu 2018.3 and PyCharm Professional 2018.1.5 in my computer. Every time I switch from Edu to Professional and vice versa, I have to set the Project Interpreter, because it's lost.

The detailed description (TL;DR):
I open some project in one of these versions of PyCharm, and all is OK.
Then I open the same project in the other one - to find that the Project Interpreter is not set - in spite that I set it before (to the path C:\Users\User\Anaconda3\python.exe). So I set it to the same path again, and all things work.
But this time only in this version of PyCharm.
Because when I switch back to the previous version of Pycharm, the situation is similar - I find that the Project Interpreter is not set - in spite that all things worked before, and the Project Interpreter was set (to the same path C:\Users\User\Anaconda3\python.exe).
So I set it to the same path again, and all things work now - but only in this version of Pycharm, because after switching back to the other version, the Project Interpreter is not set.
It doesn't matter when I switch between active versions of PyCharm, or when I exit one version, and then I launch the other one.
One version of PyCharm unset Project Interpreter in the other one, and vice versa.
What happens, and how to fix it?

A: Configuration parameters are saved in 2 different places:

You have installed 2 version of PyCharm - Edu and Professional - so you have 3 configuration places:

Every version of PyCharm has its own list of available interpreters, for example:

Note that the Project Interpreter is (so far) not set, and that every interpreter has its name.
Now we open our project in Pycharm Edu, and select a Project Interpreter for it:

Note that in the Project Configuration, the selected interpreter is saved as its name, and NOT as the interpreter itself (a path to it).
Now we open the same project in PyCharm Professional (or switch to it, if it was already opened):

We may see, that the name of its Project Interpreter (Name1) is NOT found in the PyCharm Professional list of its interpreters. And as the result of  it, you have NOT set the Project Interpreter for PyCharm professional!
So you are forced to select one - and you select the same interpreter, but now with the name NameA. All is OK, while you don't switch to PyCharm Edu, after that you will meet the same problems.
The solution is to assign the same names for the same interpreters in both version of Pycharm (Edu and Professional):

That's all. Now you can freely switch between 2 versions of PyCharm, and nothing bad happens.

How that problem may arise?

*

*Because the original names of interpreters were long and very, very similar. Compare the following names:
Python 3.6 (C:\Users\User\Anaconda3\python.exe)
Python 3.6.1 (C:\Users\User\Anaconda3\python.exe)

*Because as part of that names was the full path to the corresponding interpreter, so the user was misguided - they supposed that they selected an interpreter, while they selected a name.
Who assigned those long names, and why to the same path were chosen different names in different versions of PyCharm (Edu and Professional)?
The PyCharm itself. In the time of its installation (or just after it) it searches local disk(s) for Python Interpreters, adds each one into its list, and assigns it a name composed of

*

*the interpreter's name,

*the interpreter's version number, and

*the full path to it (in parentheses).

If between installations of two PyCharm versions the user updates a particular interpreter, its new version number becomes the part of its new name, so it will differ from the name used in the Python Interpreter list of the first PyCharm version.
And the problems listed in the question will arise...

How to change the name of an interpreter?
From the Project Interpreter.
It's a little counter-intuitive, because the list of interpreters (with their names) has nothing with the project configuration - it's a part of a particular PyCharm edition configuration.
File | Settings... | Project: (your_project_name) | Project Interpreter

Then click on Project Interpreter combo-box (1), and select "Show all..." (2).
Pops-up a window with a misleading, deceptive name "Project Interpreters" in its title. It's not true, as it lists NOT project interpreters, but Pycharm (this particular version) interpreters!
Select the interpreter with the unsatisfactory name, click on icon with a pencil on it (3) to edit it, and in another popup window rewrite the name of that interpreter (4):


text:
Q: HAProxy Multi-Process TLS Proxying doesn't pass TLS Info on We get enough TLS traffic on HAProxy now that a single process isn't able to cope with the number of new TLS connections.
After seeing how StackOverflow uses a TLS proxy on processes 2-N that sends traffic back to process 1, I started experimenting with that, as the default behavior (each process acting independently) is less than ideal.
I've now effectively got a configuration like this:
global
  nbproc 3
  cpu-map 1 0
  cpu-map 2 1
  cpu-map 3 2

  stats bind-process all

  stats socket /haproxy/proc1.sock mode 666 level admin process 1
  stats socket /haproxy/proc2.sock mode 666 level admin process 2
  stats socket /haproxy/proc2.sock mode 666 level admin process 3

defaults
  log global
  mode http
  option dontlognull

listen tlsproxy
  bind-process 2 3
  bind 0.0.0.0:443 ssl crt /haproxy/example.com.pem
  mode tcp
  option tcplog

  server fe_www abns@fe_www.sock send-proxy

frontend fe_www
  bind-process 1
  bind 0.0.0.0:80
  bind abns@fe_www.sock accept-proxy

  default_backend be_www

backend be_www
  bind-process 1

  server www01 10.1.1.1:80

This works.
However, information about the TLS connection is not available to fe_www
This causes two problems:
ACLs that use TLS connection information (eg to redirect HTTP traffic to HTTPS) are now broken, as everything is now a non-secure connection.
HTTP Logging of information like the TLS Version, TLS Ciphers, etc is broken - that information is not carried across.
I've tried swapping the use of abstract named sockets for loopback IP bindings, but this doesn't help.
Is there a way to bring the TLS information across in the proxied connection?

A: You can use send-proxy-v2-ssl to send SSL related information but as discussed in this ML thread HAProxy does not implement yet the parsing of those information in the receiving part (accept-proxy).
The only solution here is as suggested by "gf_", you need to use mode http in the tlsproxy part and do all the ssl related actions (ACLs, redirects, logging) there.

A: For those willing/able to wait for HAProxy 1.8 to come out, multithreading support using nbthread instead of nbproc looks like it will solve all of these issues.
Based on the linked blog post, it looks like this would be the correct version of the config to use for HAProxy 1.8 and later:
global
  nbthread 3

  stats bind-process all

  stats socket /haproxy/proc.sock mode 666 level admin

defaults
  log global
  mode http
  option dontlognull

frontend fe_www
  bind 0.0.0.0:80

  default_backend be_www

backend be_www

  server www01 10.1.1.1:80

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is the runtime of the append procedure O(n)? For example, in OCaml when you are appending an item to a list of length n.
x@[mylist]

A: Yes, the runtime of @ in OCaml is O(n) (where n is the length of the left operand).
Generally appending to the end of an immutable singly linked list (or an immutable doubly linked list for that matter) will always be O(n).

A: Your code snippet doesn't match your question, which suggests you're confused about what the operator does or which operator to use.
The @ or List.append operator concatenates 2 lists, and list1 @ list2 takes O(length(list1)) time and is not tail-recursive. rev_append is tail-recursive but still O(n) in time. The usual way to add an item to a list however is with the :: constructor, and item :: mylist takes O(1) time.

A: Yes, as mentioned, there are two reasons why it must be O(n):

*

*You must iterate to the end of the singly-linked list, which takes O(n)

*Since pairs are immutable, you must copy all the pairs in the first list in order to append, which also takes O(n)
A related interesting topic is tail-recursive vs non-tail recursive ways to append

A: In summary, yes.
To illustrate, a simple (not tail-recursive) append function could be written as follows:
let rec (@) xs ys =
    match xs with
    | [] -> ys
    | x::xs' -> x::(xs' @ ys)

So internally append (@) breaks down the first list (xs) and uses cons (::) operator to build the resulting list. It's easy to see that there are n steps of prepending (::), where n is the length of the first list.


text:
Q: Colour of text inside spinner I have a spinner inside a layout.
<Spinner android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:spinnerMode="dropdown"
    android:id="@+id/spn_college_names"></Spinner>

I am setting it's value using Matrix Cursor and Simple Cursor Adapter as below
spn_CollegeNames = (Spinner) findViewById(R.id.spn_college_names);
    String[] ColoumnNames = {"_id","CollegeName"};
    _CollegeNames = getResources().getStringArray(R.array.settings_college_names);
    MatrixCursor cursor = new MatrixCursor(ColoumnNames);

    for (int CollegeIndex = 0; CollegeIndex < _CollegeNames.length; CollegeIndex++ )
    {
        cursor.addRow(new Object[] {CollegeIndex+1 , _CollegeNames[CollegeIndex]});
    }

    SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, cursor, new String[] {"CollegeName"}, new int[] {android.R.id.text1},0 );
    /*TextView tv = (TextView) spn_CollegeNames.getSelectedView();
    tv.setTextColor(Color.BLACK);*/
    spn_CollegeNames.setAdapter(cursorAdapter);

My problem now is that the text in the spinner is appearing in gray color. I want to change the text to black. I know I can use android:enteries attribute in the layout but I will be replacing the matrix cursor with database cursor in future which means I will not have fixed string array values.

A: You can achieve it by overriding getDropdownView and/or getView. getDropdownView returns view for expanded spinner and getView returns view for collapsed spinner.
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, cursor, new String[] {"CollegeName"}, new int[] {android.R.id.text1},0 ){

@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
    View view = super.getDropDownView(position,convertView,parent);
    TextView text = (TextView)view.findViewById(android.R.id.text1);
    text.setTextColor(Color.BLACK);
    return view;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = super.getView(position,convertView,parent);
    TextView text = (TextView)view.findViewById(android.R.id.text1);
    text.setTextColor(Color.BLACK);
    return view;
}

};

A: Try this :
private OnItemSelectedListener OnCatSpinnerCL = new AdapterView.OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View view, int pos,
            long id) {
        ((TextView) parent.getChildAt(0)).setTextColor(Color.BLACK);
    }

    public void onNothingSelected(AdapterView<?> parent) {
    }
};

A: Instead of android.R.layout.simple_spinner_dropdown_item you have to provide your custom textView item .
Spinnerlayout.xml
  <TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#00eeff"
android:text="TextView" />

Your adapter
    SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.spinnerlayout, cursor, new String[] {"CollegeName"}, new int[] {android.R.id.text1},0 );


text:
Q: SolrCoreInitalizationException: SolrCore 'solrprodshard2' is not available due to init failure: Error opening new searcher We store our Index in shared NAS drive. To perform DR exercise, we switched NAS to different cluster and reverted back. During this time we removed write.lock files on Index. When we reconfigured the NAS to original cluster, we are not able to bring it back to original state.
We are seeing above error for all the cores. Is there a way to preserve index and connect them back to original nodes?
in solr cloud mode, we are not able to see Disk usage data in dashboard.

Thanks in advance.


text:
Q: Is there any difference between the idiom "that's about the size of it" and "that's about the extent of it"? Could you tell me if there is any difference between the idiom that's about the size of it and that's about the extent of it? For example:

Person A: What Kate's birthday party?
Person B: She dropped her birthday cake. That's about the size of it./That's about extent of it.

A: They both probably mean the same thing: "that's it, not much (or nothing) more".
But "that's about the size of it" is so uncommon in modern American English, it's almost a stretch for the reader to make the connection.


text:
Q: Twilio Conference - Record the Conference in the middle of the Call I am developing a conference application using Twilio. I need to record the conference but not from the start. Whenever I need to record I should be able to record the conference. It is mostly in the middle of the call. For example like I am having a call with 3-4 other participants and maybe after 10 or 15 minutes, I will need to start recording the call. I checked Twilio conference-updater and participant-updater but I didn't find any way to record the call. So if I use the Twilio call-updater and pass Twiml with Record (I saw Record is a one-way recording) will it work and record the whole conference or will it only record one person (owner of that call sid) voice? Or else is there another cleaner approach to do this? Thanks in advance.

A: Conference Recording Controls
Conference recordings can be paused and resumed in the same way as regular calls. The only difference is instead of making your HTTP POST requests to the active call's subresources, your requests would go to the active conference's subresources.


text:
Q: Static source file(.html) update does not working to application I am just a newbee to jhipster. finally I generated jhipster and runned an application. I tried to change static file(.html) for test.

*

*What I did as follows.

*

*I changed src/main/webapp/app/layouts/footer/footer.component.html file content.
('This is your footer'  --> 'This is your footer !!!!!')

*Executed command yarn start. Application running without problem.

*I found running application footer still' This is your footer'. But footer.component.html file content still 'This is your footer !!!!!'.

*I tried many times but application's footer still unchanged.

*I tried compile executing command yo jhipster.

*Terminal Ask overwriting footer.component.html file? so I typed 'y'

*After compile I checked footer.component.html file content. but it rolled back to the original file ('This is your footer'. not 'This is your footer !!!!!')
Please Teach me what I had missed. How can I change contents of static files.
This problem makes me crazy for last 2days.
Thanks in advance.

A: Please let us know if you installed any language while creating the project.
If yes then jhipster uses this following library for translations, so the actual String comes from a json file.
https://angular-translate.github.io/
You can do the following.
Instead of

This is your footer

Try the following.

This is your footer!!!

Or a better option would be to change the json file.
src/main/webapp/i18n/en/global.json
 "footer": "This is your footer"

to
 "footer": "This is your footer!!!"


text:
Q: Large parameters and errorlevels in old-style MS-DOS assembly programs? Several years ago I used to write x86 assembly programs for MS-DOS operating system; most of them still run unmodified in Windows CMD.EXE command processor. My question is about two specific points in these programs:

*

*The program parameters are located at offset 81H in the Program Segment Prefix and have a maximum lenght of 127 characters.

*The ERRORLEVEL value that the program return is loaded in AL register prior to the Terminate Program function (4CH) of the INT 21H, so it is limited to values in the range 0-255.
I realized that in Windows XP the commands executed in a DOS window can process parameters of up to 8 KB size and may return a 32-bits signed value as ERRORLEVEL. So my question is: Is there a SIMPLE way that an old-style MS-DOS assembly program may have access to 8KB parameters and return 32-bits ERRORLEVEL values?
Yes, I know that a Windows-compliant assembly program have access to these features, but I wonder if a program could do that in a very simple way...

A: Your 16-bit programs are running on 32-bit Windows due to NTVDM. More and more machines are getting 64-bit OS'es by default, and 64-bit Windows doesn't even have the NTVDM, so it won't work anymore.
I advise you to port your programs to 32 or 64-bit Windows.
After porting, access to the command line is easy. WinMain and main both have the command line as an argument.


text:
Q: WooCommerce: Remove PayPal Express Button in cart I want to remove the "Proceed to checkout" buttons in the cart if the cart amount is below 20$.
I found a way to remove the default checkout button with this code:
function disable_checkout_button() {

    // Set this variable to specify a minimum order value
    $minimum = 20;
    $total = WC()->cart->cart_contents_total;
    if( $total < $minimum ){
        remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );
    }
}

But the PayPal Express Checkout button is still there.
Is there a way to remove that button in the same way?
I didn't found an hook to do it.
EDIT: I read here, that the PayPal buttons are added to the cart page using the woocommerce_proceed_to_checkout hook.
But adding the following line doesn't do anything for me:
remove_action( 'woocommerce_proceed_to_checkout', 'display_paypal_button', 20 );

A: add_filter( 'woocommerce_available_payment_gateways', 'disable_paypal' );

function disable_paypal( $available_gateways ) {
$minimum = 20;
if ( WC()->cart->total > $minimum ) {
unset( $available_gateways['ppec_paypal'] );
}
return $available_gateways;
}

Check for available payment gateway set the minimum amount and then disable Paypal.


text:
Q: Exposing GraphQL based APIs I have data stored in the file system (normalized across multiple small files) and I have written python functions to read/write data from the file system. Read API returns object of type Job. Write API expects an object of type Job to be passed as an argument.
def get_jobs(starttime, endtime):
  ''' Reads and returns jobs that ran between starttime and endtime interval '''

def put_job(job):
  ''' Persists Job object to a file system '''

class Job:
    def __init__(self, name, key, starttime, endtime):
        self.name = name
        self.key = key
        self.starttime = starttime
        self.endtime = endtime

Now I want to expose these functions via a web server. I would prefer exposing GraphQL APIs with Django.
Questions:

*

*Is Django/Django REST framework a right choice for this? I am new to
Django and GraphQL.

*Django models seem to be tightly coupled with Databases. Will I have to create another Job model class, and create it using Job returned by read_jobs function? If yes, how can I create a simple web application from here?

Note:

*

*Job object is a three-level nested object and has many attributes/properties. For the demonstration purpose, I kept only four attributes/properties in the question here.

*I would prefer Django because my application at this stage might look a bit small but over time it will grow and I have lots of features that I need to add. I am specifically looking for solutions with django-graphene based application without using SQLite DB or without assuming that the data is getting fetched from some database. I want to leverage my persistence API methods for querying data from the file system.

A: Django could be a (good but heavier) solution, but here is simpler solution using Flask:
from flask import Flask, jsonify

app = Flask(__name__)

class Job:
    def __init__(self, name, key, starttime, endtime):
        self.name = name
        self.key = key
        self.starttime = starttime
        self.endtime = endtime

@app.route("/get", methods=['GET'])
def get_jobs(starttime, endtime):
    ''' Reads and returns jobs that ran between starttime and endtime interval '''
    jobs = read_data(starttime, endtime) # your read_data() method
    return jsonify({'jobs': jobs})

@app.route("/put", methods=['POST'])   # or methods=['PUT']
def put_job(request):

    # access your data trough the request object:
    job_name = request.args.get('name', '')
    job_key = request.args.get('key', '')

    # or get it in json
    job_data = request.json

    write_data(Job.from_json(job_data))

I used Json here because I'm more confortable with it, but if GraphQL is important for you, I recommend to you the Graphene-Python library.

There is also a project of integration of Graphene with Flask


text:
Q: Location of all Citidal fetch quests in ME3 I am looking for a fetch quest list similar to "Assuming everyone survived in Mass Effect 2, where and how do they make an appearance?"

What I have in mind is something like this:
Apien Crest: Banner of the First Regiment

*

*For: Turian officer in Purgatory

*Where: Castellus sector -> Apien Crest cluster -> Digeris

A: Can't really spend the time right now to write up all of them.
The wiki lists all the missions.
Just scroll to the ME3 Galaxy at War missions for the citadel.


text:
Q: Unable to detect delete button of soft keyboard in emulator I am trying to detect back or delete button of soft keyboard using below method. Its working perfectly in physical devices but its not working emulator. Emulator is able to detect all the key events(like enter button, number buttons) expect delete button. On pressing the delete button in emulator neither onKeyDown() nor dispatchKeyEvent() is called.  What can be the problem ?
Purpose of doing this:
I am trying to navigate to previous EditText fields if the user presses delete on the current empty EditText field. That is why I was relying on the dispatchKeyEvent() method.
I am using Nexus 5X API 25 emulator
public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_DEL) {
            Log.e(TAG,keyCode)
        }
        return super.onKeyDown(keyCode, event);
    }

Here is my layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:focusable="true"
        android:hint="Name" />

</RelativeLayout>

Image of the delete button:

A: After understanding your requirement I found that onKeyDown and onKeyUp are not working on Nexus 5 API 25 emulator but TextWatcher can serve your purpose if you really want to use Nexus 5 API 25 emulator.
On Nexus 5X API 26, onKeyDown and onKeyUp are working fine. Of course TextWatcher is working as well.
Use TextWatcher to detect change in text inside EditText and there you can check which key is pressed. Below is working code:
    TextWatcher textWatcher = new TextWatcher() {

        public void  beforeTextChanged(CharSequence s, int start, int count, int after){
            if (after < count) {
                Log.d("DELETE_KEY_PRESSED", "beforeTextChanged: ");
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.length()>0 && s.subSequence(s.length()-1, s.length()).toString().equalsIgnoreCase("\n")) {
                Log.d("ENTER_KEY_PRESSED", "onTextChanged: ");
            } else if (s.length() == 0) {
                Log.d("DELETE_KEY_PRESSED", "onTextChanged: ");
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

    EditText editText = (EditText) findViewById(R.id.edit);
    editText.addTextChangedListener(textWatcher);

You can use TextWatcher to detect all the other key pressed as well.
By the way, for me onKeyDown() and onKeyUp() are also working fine on emulator. I am using below code:
//To detect DELETE KEY PRESS event there is no text in EditText
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_DEL) {
        Log.d("KEY_PRESSED - onKeyDown", "KEYCODE_DEL");
    }
    return super.onKeyDown(keyCode, event);
}

//To detect DELETE KEY PRESS event there is no text in EditText
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_DEL) {
        Log.d("KEY_PRESSED - onKeyUp", "KEYCODE_DEL");
    }
    return super.onKeyUp(keyCode, event);
}

NOTE: I am using Nexus 5X API 26 emulator


text:
Q: Passing Domain Name as Parameter With ASP.Net MVC Routing In one of our web application, i need to send domain name (ex: domainname.com) as parameter with asp.net mvc routing. So i created a route definition like below:
    routes.MapRoute(
        name: "AccountDetail",
        url: "{controller}/{action}/{htip}/{dname}",
        defaults: new {
            controller = "Account",
            action = "Index"
        },
    );

Also i have a method defined in AccountController like below:
public ActionResult Details(string htip, string dname) { }

According to the this route config and method declared in controller, MVC generates urls like http://localhost:63740/Account/Details/N/domainname.com and this is what i expect.
But if i follow this url, IIS's 404 error page welcomes me instead of any MVC related page. Because MVC doesn't handle the url, because of TLD at the end (.com).
How can i achieve to make MVC handle these urls?


text:
Q: Creating unique pages based on Mailchimp Merge Tags : )
So, I'd like to send out an email (campaign) with the preview of an article, then I like to provide a link where users can read the full article on my website. On a sidebar, I'd like to show the user which newsletter lists they're subscribed to (and not subscribed to) so they might easily adjust their settings should they like to.
Once I have the user on the page, and my website knows their email address or the md5 hash of it. I can use the hash to interact with the MailChimp API (v3) to subscribe and unsubscribe them from various lists, but how do I get their information over to my website in the first place?
If I use the |EMAIL| merge tag in the "read full article" link, I put their plain text email in the query string of the URL. The |UNIQID| perhaps? I don't see what it does in the 3.0 API.
Side note: I'm aware that users who share this page, if the query strings contains a way to identify that user, they expose to their friends the ability to change their settings. I don't know how to avoid this either. Perhaps a redirect is best?
Sorry I don't have code yet.


text:
Q: JUnit exception test case i am trying to write junit test case expecting the NullPointer Exception.
like this
@Test(expected = NullPointerException.class)
        public void testException() throws CustomiseException {
            CustomBean expected= new CustomBean();

//below line will throw null pointer exception , that i want to test with junit
        when(repo.isValid().thenReturn(expected);

        }

but when running Junit it is getting failed with below error:
it is throwing exception at the same line which i want to test, can anyone help me with this ?


text:
Q: Django admin css loads perfectly (status: 200) but the output shows pure html with no styles loaded I am very new to Django and I have been following steps from a site I found.
I have already tried doing the solutions I found on other questions but none of them worked on my situation.
Django Admin - Webpage
cmd output
Django Admin - Output no CSS

My static settings looks like this:
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
#STATIC_ROOT = os.path.join(BASE_DIR, 'static')

and my installed apps settings looks like this:
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'boards',
]

Thanks in advance!
EDIT:
here is the html I was loading:
{% load static %}<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Boards</title>
        <link rel="stylesheet" text="text/css" href="{% static 'myproject/css/bootstrap.css' %}">

Boards

                        Board
                        Posts
                        Topics
                        Last Post

                    {% for board in boards %}

                                {{board.name}}

                                {{ board.description }}

                            0
                            0

                        {% endfor %}

A: In your template, please load the static files like this
{% load static %}


text:
Q: Check how many element between ID I have a div,
<div id=refer_friends>
    <input type='text' name='refer1'>
    <input type='text' name='refer2'>
    <input type='text' name='refer3'>
</div>

How to check, how many input elements between DIV refer_friend?
I am using jQuery.

A: $('#refer_friends :input').length;

When you say 'input elements', this will get all input elements. Use the input[type=text] or :text to get only text elements.

A: $("#refer_friends").find("input[type='text']").length;

A: alert($("#edit_changes *:text").size());

problem fixed


text:
Q: Is it okay to open a file in the parameter of a function? I am checking if I did something correctly here in C++. Since recently coming out of Python, the way how things work in the language is a bit weird to me but I am getting used to it.
The task was to:

Step 1: Define a struct that can hold information about bank accounts. First:
  ■ Each instance will hold the name for the account and an account number. We have created an input file that has at least three accounts, called "accounts.txt":

"moe 6
larry 28
curly 42"

Read a file of account information, filling a vector of account objects. Define local variables corresponding to each data item. Loop through the file, reading into these variables. Clear the vector, reopen the file (call the open method), andrepeat the above, except using curly braced intializers to intialize the instance. Close the file and display all objects.

Step 2: Define a class to hold accounts. Redo the above steps from task 1 that you did with the struct version. Use the same stream variable! Write getters to access the fields in the accounts when printing. Add an output operator for your class. First, Repeat the print loop using this output operator.Now make the output operator a friend, by adding a friendprototype to your account class definition. Add a line in the output operator that prints the fields "directly", i.e. without using the getters. The vector push_back method will be passed as temporary object defined as the argument to push_back. Repeat the filling of the vector using emplace_back and again display the contents.
Step 3: Add transactions to your world.
  A transaction will be implemented as a class and have a field to indicate whether this is a deposit or a withdrawal and a field to say how much is being deposited or withdrawn. The account class will keep track of transactions applied to it. It will need a vector to store this history of transactions. It will also need a "balance" field to indicate how much is in the account. The account will have methods "deposit" and "withdrawal" which will be passed the amount and will add an appropriate transaction object to the history and modify the balance as needed. The output operator for the account will need to change so that it can display (you format it) the history, i.e. the transactions. When you finish, test this by reading in another file "transactions.txt" that has
  commands such as:

"Account moe 6
Deposit 6 10
Withdraw 6 100
Account larry 28
Withdraw 6 100
Deposit 6 10
Deposit 6 10
Withdraw 6 5
Account curly 42"

I am not sure if I opened the file accounts.txt correctly the way they wanted. I defined it inside the parameter of the function readandDisplayUsingStruct. Is it okay to do it this way? Would it seem like bad style of coding? Anyway, they were very specific in how I should perform this assignment with the steps they provided. It was more restrictive since they did not allow that I would conjure up my own way to do this.
I provided a snippet of the code I've written below.

class AccountClass
{
private:
    string name;
    int accno;
    vector<Transaction> vHistory;
public:
    AccountClass(string nm, int acno) :name(nm), accno(acno)
    {

    }
    string getName()
    {
        return name;
    }

    int getaccno()
    {
        return accno;
    }

    void addTransaction(Transaction t)
    {
        vHistory.push_back(t);
    }
};

void readandDisplayUsingStruct(string fileName= "accounts.txt")
{
    ifstream fin;

    fin.open(fileName);

    if (!fin.is_open())
        return;

    string line;

    vector<Account> vAccounts;

    //Read each line from the file
    while (getline(fin, line))
    {
        stringstream ss(line);
        string name;
        int no;
        //Split the line into name and id using string stream
        ss >> name;
        ss >> no;
        Account acc{ name,no };
        vAccounts.push_back(acc);
    }

    cout << "The Read Values are" << endl;

    for (Account acc : vAccounts)
    {
        cout << "Name : " << acc.name << "\n";
        cout << "No : " << acc.accno << "\n";
    }

    //Clear the vector
    vAccounts.clear();

    fin.close();

    //Again do the same operation using local variables without Braces Initialisation.
    fin.open(fileName);

    if (!fin.is_open())
        return;

    string line1;

    vector<Account> vAccounts2;

    //Read each line from the file
    while (getline(fin, line1))
    {
        stringstream ss(line1);
        string name;
        int no;
        //Split the line into name and id using string stream
        ss >> name;
        ss >> no;
        Account acc;
        //Explicit initialisation
        acc.name = name;
        acc.accno = no;
        vAccounts2.push_back(acc);
    }

    std::cout << "The Read Values are" << endl;

    for (Account acc : vAccounts)
    {
        std::cout << "Name : " << acc.name << "\n";
        std::cout << "No : " << acc.accno << "\n";
    }

    fin.close();

}


text:
Q: Add Slider Input in Collapsable Sidebar Shiny I would like to add a slider in a collapsible sidebar. I am having some issues  displaying the content that is associated with the tabName in the body. Ie. When I click the tab, the content in the body does not show.
This is the code and how it looks like when we comment out the slider input.

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = "Dynamic Menu"),
  dashboardSidebar(
    sidebarMenu(
      menuItem("hello", tabName = "helloWorld", icon = icon("calendar")#,
              #sliderInput("slide", "chose Slide", min = 5, max = 10, value = 10)
              )
    )
  ),
  dashboardBody(
    tabItems(
      tabItem(tabName = "helloWorld",
              tags$h1("hey")
      )
    )
  )
)

server <- function(input, output, session){

}

shinyApp(ui, server)

If we use the slider input, the body disappears. I have tried using some java script but I can not seem to get the result I am looking for. Keep in my the sidebar should be collapsible if I decide to add in another menuItem.

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = "Dynamic Menu"),
  dashboardSidebar(
    sidebarMenu(
      menuItem("hello", tabName = "helloWorld", icon = icon("calendar"),
              sliderInput("slide", "chose Slide", min = 5, max = 10, value = 10)
              )
    )
  ),
  dashboardBody(
    tabItems(
      tabItem(tabName = "helloWorld",
              tags$h1("hey")
      )
    )
  )
)

server <- function(input, output, session){

}

shinyApp(ui, server)

A: What if you remove tabItems and tabItem entirely of your Body?
Try with this:
dashboardBody(
    tags$h1("hey")
  )

Or do you want to have multiple bodies depending on which menuItem is selected?


text:
Q: AngularJS: show loader image until data is loaded screen image1
screen image2
displaying results using angular js + php, how to show loader image until data is loaded, here my code is written below,
How do I have AngularJS show a loading image until the data has finished loading?
app.js file
var app = angular.module('myApp3', ['ui.bootstrap']);

app.filter('startFrom', function() {

    return function(input, start) {
        if(input) {
            start = +start; //parse to int
            return input.slice(start);
        }
        return [];
    }
});
app.controller('customersCrtl', function ($scope, $http, $timeout) {
    $http.get('http://www.testurl.com/index.php/site/getprofileLocations').success(function(data){

        $scope.list = data;
        $scope.currentPage = 1; //current page
        $scope.entryLimit = 20; //max no of items to display in a page
        $scope.filteredItems = $scope.list.length; //Initially for no filter
        $scope.totalItems = $scope.list.length;
    });
    $scope.setPage = function(pageNo) {
        $scope.currentPage = pageNo;
    };
    $scope.filter = function() {
        $timeout(function() {
            $scope.filteredItems = $scope.filtered.length;
        }, 10);
    };
    $scope.sort_by = function(predicate) {
        $scope.predicate = predicate;
        $scope.reverse = !$scope.reverse;
    };
});

and php code is here

PageSize:
            <select ng-model="entryLimit" class="form-control">
                <option>5</option>
                <option>10</option>
                <option>20</option>
                <option>50</option>
                <option>100</option>
            </select>

Filter:
            <input type="text" ng-model="search" ng-change="filter()" placeholder="Filter" class="form-control" />

Filtered {{ filtered.length }} Of {{ totalItems}} Total Locations

 0">

            Id
            Place Name
            Category ID

                   {{data.id}}
                    {{data.name}}
                    {{data.category_name}}

No Locations found

 0">

A: display loader onload and hide it once data loaded.
$scope.showLoader = true;
$http.get('http://www.testurl.com/index.php/site/getprofileLocations').success(function(data){
    $scope.showLoader = false;
    // rest of your code
});

EDIT: html code from Saeed's answer

A: Addition to @Venugopal`s answer.
To display that loading image in the html

A: You need to show the loader image before the ajax call and remove it after it completes in both success and error handler.
you will find plenty of loader images online, which you can use it for your application.
JS CODE
 //show the loader image in center of screen & prevent any user interactions
 $scope.imLoading = true;
 $http.get('http://www.testurl.com/index.php/site/getprofileLocations').then(
   function(data){
       //hide the loader image & process successful data.
       $scope.imLoading = false;
   }, function (errorData) {
       //hide the loader image & show error message to user
       $scope.imLoading = false;
 });

CSS:
.im_loading{
 display:none;
 position:fixed;
 top:50%;
 left:50%;
 margin:-35px 0px 0px -35px;
 background:#fff url(../images/loader.gif) no-repeat center center;
 width:70px;
 height:70px;
 z-index:9999;
 -moz-border-radius:10px;
 -webkit-border-radius:10px;
 border-radius:10px;
 -moz-box-shadow:1px 1px 3px #000;
 -webkit-box-shadow:1px 1px 3px #000;
 box-shadow:1px 1px 3px #000;
 opacity:0.7;
 filter:progid:DXImageTransform.Microsoft.Alpha(opacity=70);
}

HTML CODE:

Note: Your code is proccessing only successful ajax call & not erroneous call which is not good as your code becomes unresponsive when error is returned, so you need to handle error case as well.

A: You can do one thing:

*

*Keep hidden your html content by default

*Show it when you get the response

like:

   .....

So using this only loader will show till you get your data from server.

A: Whenever we use an HTTP call in AngularJS, we want to show the loading image by default. So here, we are going to achieve this by using a custom directive.
JS CODE
var app = angular.module('appMyCustomModule',[]);
app.directive('dirCustomLoader', ['$http', function ($http) {
    return {
        restrict: 'E',
        template: '

',
        link: function (scope, element, attrs) {
            scope.isLoading = function () {
                return $http.pendingRequests.length > 0;
            };
            scope.$watch(scope.isLoading, function (value) {
                if (value)
                    element.removeClass('ng-hide');
                else
                    element.addClass('ng-hide');
            });
        }
    };
}]);

CSS:
.loading-icon {
    background: url(static image url) no-repeat scroll center #fff;
    display: inline-block;
    font-size: 0;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 9999999999999999999 !important;
    opacity: .5;
}

HTML CODE:
<dir-custom-loader class="ng-hide"></dir-custom-loader>

A: There is a better way that prevents showing two icons for example:
(BAD WAY)
When angular is manipulating the DOM, it can show the search icon before hiding the loading icon. Thats why its bad to have two elements.

(GOOD WAY)
This way prevents showing the loading and the search icon when angular is hiding and showing elements.

And the script would be something like this.
$scope.clickEventThatDoSomething = function () {
    $scope.loadingData = true;
    http.get('http://YourAPIUrl').then(function (data) {
        $scope.loadingData = false;
        $scope.data = data.data;
    }).catch(function (err) {
        $scope.loadingData = false;
    })
}


text:
Q: Sync between two controller Using 2 MM9z_639 controller for SPI master and SPI slave.
In datasheet it mentioned as when it configured as Master,clock should be bus clock/2, when it configured as Slave, clock should be bus clock/4
So I decided to keep bus clock /4, to ensure both controllers are running on same time.  I am using bus clock as 28Mhz.
Initially mater will send character 'R'.Slave will reply with 'R'. Then both will start executing their code.
To verify sync, I enabled 500ms timer. Every 500ms tone counter will increment both sides.
For every one sec master will ask counter value of slave and also stores its count value.  If both counter are same then both are in sync.
But problem is:
in master = 2,4,6,8,...
from slave = 0,0,2,4
Initially two bytes getting 0.
Then I decided to send some dummy data from slave to master whenever interrupt hits. In this condition I am getting proper value.
Also I checked both are running on same speed.
Please find the code for SPI.
I am using controller MM9Z1_639 NXP
Here am doing sync between two controller so that both controller should start reading adc channel at same time. For that one first i send char 'a' from master to slave and slave will replay back with 'r'.Then on wards both code will start reading adc channel.
Parallel am starting 500ms timer to increase count. And reading both Master and slave count every  1 sec.
void Init(void)
{

    /* SPICR1 register configuration */
    SPICR1_SPE = 1U;
    SPICR1_LSBFE = 0U;
    SPICR1_CPHA = 1U;
    SPICR1_CPOL = 0U;

#ifdef MICRO1
    SPICR1_MSTR = 1U;

    SPICR1_SSOE = 0U;
    SPICR1_SPIE = 0U;
    SPICR1_SPTIE = 0U;
#endif

#ifdef MICRO2
    SPICR1_MSTR = 0U;
    SPICR1_SSOE = 0U;
    SPICR1_SPIE = 1U;
    SPICR1_SPTIE = 1U;
#endif

    /*SPICR2 register configuration */

    SPICR2_XFRW = 0U; /* 8 bit data transfer */
    SPICR2_SPC0 = 0U;
    SPICR2_BIDIROE = 0U;

#ifdef MICRO1
    SPICR2_MODFEN = 0U;

    SPICR2_SPISWAI = 1U;
#endif

#ifdef MICRO1
    SPICR2_MODFEN = 0U;
#endif

    /*SPIBR configuration */
    SPIBR = 0x01;

T_UBYTE Spi_ASample_Tx_Buf_Index = 0;
T_FLAG Spi_ASample_Sync_data;
T_UBYTE Rx_Count = 0;
static T_UBYTE counter =0x03;
static T_UBYTE call =0x00;
static T_UBYTE status_timer =0;

void ISR_FCT Spi_ASample_ISR(void)
{

#ifdef MICRO2
    if (SPISR_SPTEF)
    {
        (void)bspi_GetRxData();
        if(status_timer==1)
        {
        SPIDRL='r';
        status_timer=3;

        }
        else if(status_timer==0)
        {
            SPIDRL='A';
        }
        else
        {
            SPIDRL=ADC_sync_time();

        }
        if (Rx_Count < 7)
            Rx_Count++;
        else
            Rx_Count = 0;
    }
#endif

}

void start_ADC_Sync_time()
{
    if(status_timer>0)
    {
    call=(call+1);
    }
}

T_UBYTE ADC_sync_time(void)
{

return call;
}

void set_flag(void)
{
    status_timer=1;
}


text:
Q: How can I choose algorithms in a function the scenario likes this:
There is an algorithm called alg1, and another algorithm called alg2.
And there is an entry function called solve, how can I pass alg1 to solve then I can use alg1 to compute, and pass alg2 to compute with alg2?
solve(a, b, alg1) #return the results computed with alg1
solve(a, b, alg2) #return the results computed with alg2

Do I need to write the algorithms as functions?

A: A typical elegant API could be based on the multiple dispatch mechanism and could look like this:
abstract type AbstractAlgo end
struct Algo1 <: AbstractAlgo end
struct Algo2 <: AbstractAlgo
    param::Int
end

function solve(a,b,alg::T) where T<:AbstractAlgo
    throw("Algorithm $T is not yet implemented")
end
function solve(a,b,alg::Algo1)
   println("solving...")
end

Some tests:
julia> solve(1,2,Algo1())
solving...

julia> solve(1,2,Algo2(777))
ERROR: "Algorithm Algo2 is not yet implemented"

A: In julia you can pass funcions as parameters, so:
function alg1(a,b)
...
end

solve(a,b,alg) = alg(a,b)

# calling solve
answer = solve(a,b,alg1)

Of course there are other ways, as transforming algs is structures and employing multiple dispatch, but the solution above should answer the question..


text:
Q: WPF ProgressBar not updating its progress status I am using a wpf UserControl to replace text in files in selected drawing files of AutoCAD. The wpf control is to display a status (ProgressBar) indicating the number of files processed at any given time. So I put up the following code, but the ProgressBar simply does not show any progress. Here is the part of relevant code.
XAML:
<ProgressBar HorizontalAlignment="Stretch" Name="pgrSearch" Minimum="0" Maximum="{Binding Path=ProgressBarMaximum}"
                 Value="{Binding Path=ProgressBarCurrent}" Height="20" Margin="10"  />

CodeBehind:
public partial class ReplaceUserControl : UserControl, INotifyPropertyChanged {
    public ReplaceUserControl() {
        InitializeComponent();
        this.DataContext = this;
    }
    ....

    private int _progressBarMaximum;
    public int ProgressBarMaximum {
        get { return _progressBarMaximum; }
        set { _progressBarMaximum = value; RaisePropertyChanged("ProgressBarMaximum"); }
    }

    private int _progressBarCurrent;
    private int ProgressBarCurrent {
        get { return _progressBarCurrent; }
        set { _progressBarCurrent = value; RaisePropertyChanged("ProgressBarCurrent"); }
    }

    private void ReplaceTextInFiles() { //Called from Button_Click Handler
        ....

        ProgressBarMaximum = filesList.Count - 1;

        SearchReplaceWorker replaceWorker = new SearchReplaceWorker(); //The Work Horse
        replaceWorker.FileProcessed += new FileProcessedEventHandler(worker_FileProcessed); //Raised by Work Horse when each file is processed

        BackgroundWorker workerThread = new BackgroundWorker(); //The Background Worker Thread
        workerThread.DoWork += (o, e) => {
            replaceWorker.ReplaceTextInFiles(SearchText, ReplaceText, filesList, ReportFolderPath, MatchCase, MatchSubstring);
        };
        workerThread.RunWorkerAsync(); //Start the Background Thread Async
    }

    void worker_FileProcessed(object sender, EventArgs e) {
        ProgressBarCurrent = ProgressBarCurrent + 1; //Update the ProgressBar status
    }

Why doesn't the ProgressBar update itself when the ProgressBarCurrent is incremented as  indicated above in code.
Edit:
In Order to process the ProgressBar update code on UI thread, I changed my code to use BackgroundWorker.ReportProgress() as given under.
CodeBehind for UserControl:
private void ReplaceTextInFiles() { //Called from Button_Click()
    if (!Directory.Exists(SearchFolderPath)) {
        MessageBox.Show("Invalid Directory Selected for Search");
        return;
    }

    if (!Directory.Exists(ReportFolderPath)) {
        MessageBox.Show("Invalid Directory Selected for Report File");
        return;
    }

    List<string> filesList = null;
    try {
        if (LookInSubFolders) {
            filesList = Directory.GetFiles(@SearchFolderPath, "*.dwg", SearchOption.AllDirectories).ToList();
        }
        else {
            filesList = Directory.GetFiles(@SearchFolderPath, "*.dwg", SearchOption.TopDirectoryOnly).ToList();
        }
    }
    catch (Exception ex) {
        MessageBox.Show("Error Occurred getting the files list. Contact Admin");
    }

    pgrSearch.Visibility = Visibility.Visible;
    ProgressBarMaximum = filesList.Count - 1;

    SearchReplaceWorker replaceWorker = new SearchReplaceWorker();

    BackgroundWorker workerThread = new BackgroundWorker();
    workerThread.WorkerReportsProgress = true;
    workerThread.ProgressChanged += (o, e) => { //This event handler gets called correctly.
        ProgressBarCurrent++;
    };
    workerThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(workerThread_RunWorkerCompleted);
    workerThread.DoWork += (o, e) => {
        replaceWorker.ReplaceTextInFiles(workerThread, SearchText, ReplaceText, filesList, ReportFolderPath, MatchCase, MatchSubstring);
    };
    workerThread.RunWorkerAsync();
}

The BackgroundWorker:
public void ReplaceTextInFiles(BackgroundWorker workerThread, string searchText, string replaceText, List<string> filesList, string reportPath,
                                      bool MatchCase, bool MatchSubstring) {
    ...
    workerThread.ReportProgress(50);
}

Still the ProgressBar doesn't update itself.

A: I created a test project with your initial code. After a while I found that you have declared the ProgressBarCurrent property as private. After changing to public it worked for me. So it doesn't seem necessary to update the property on the UI thread. It looks like a Dispatcher.Invoke call is made internally when reading back the updated property value.


text:
Q: Can a function be differentiable at the end points of its (closed interval) domain? Assume $f$ has a domain of $[a,b]$. Is it possible that $f$ is differentiable on the closed interval $[a,b]$, or must the maximal domain for $f'$ be $(a,b)$?

A: It depends on the definition of differentiability you have. Some textbooks only define it for interior points. But there is also a more general definition (see this answer for references):

A function $f: A \rightarrow \mathbb R$ is differentiable for an accumulation point $a \in A$ of $A$ with derivative $f^\prime(a)$, iff for each $x_n \rightarrow a$ with $x_n\in A\setminus\{a\}$ you have $f^\prime(a) = \lim_{n\rightarrow\infty} \frac{f(x_n)-f(a)}{x_n-a}$.

So the answer is yes: You can define the derivative in a way, such that $f'$ is also defined for the end points of a closed interval. Note that for some theorem like the mean value theorem you only need continuity at the end points of the interval.


text:
Q: Error module Qt I'm new to QT. I have a problem with a widget named QWebView as when I want to compile it says : unknown module in QT: webkit
I wrote in my qmake.pro file the line :
    QT       += core gui network webkit
Am I wrong ? I read in doc I just need to add this package.
I'm on QT 5.8 on macbook.
If anyone could help, I'll be thankful !

A: Qt 5.8 doesn't include the webkit module. Use the webengine or webview module instead.
Since you're on a mac, if you're OK with Qt 5.7 included in macports, you'll get webkit module there as well:
sudo port install qt5-qtwebkit


text:
Q: Radius of hypersphere for higher dimensions So while trying to improve my intuition about higher dimensions I found this video on youtube: Specific Part
Visualized for 2D(from the Video):

I would formulate the problem as follows:

*

*d-cube $[-1,1]^d$ divided into $2^d$ d-cubes each containing a the largest centered ball

*draw the d-ball centered thaat touches all unit d-balls
As said in the video the Volume V for the centered ball is $V \rightarrow \infty$ for $d \rightarrow \infty$
So I understand that the Volume of the d-balls in the unit d-cubes decreases and why and I can also proof that by calculating $\frac{Vball(d,r)}{Vcube(d,2r)} | d \rightarrow \infty$
Edit: And I also informally understand why the Volume of the centered d-ball increases
Could you hint me towards how a proof(sketch) could look like on how the radius of the centered ball behaves for: $d \rightarrow \infty$ ?

A: Ok the solution is too have a look at the main diagonal of the unit cubes. In 2D it is relatively easy to see that one edge of each square lies exactly in the center of the inscribed centered ball. Since the diameter of the unit ball is 1 we know that the radius of the central square is  $\frac{{\sqrt d} -1 }{2} $ (Note that the maindiagonal of the d-cube of side length l is: ${\sqrt d}\ l$) since when we substract the diameter from the main diagonal, half of the rest is the radius.
Since this obviously goes to infinity the radius for $d \rightarrow \infty$ is $\infty$


text:
Q: How to use kCIInputBoostShadowAmountKey? I would like to boost the shadows in an UIImage, akin to the one in Mac OS:

Is kCIInputBoostShadowAmountKey the correct key to use?
If yes, how to use it?
I'm able to use CIFilter with CIColorControls to edit the saturation and brightness:
CIContext *context3 = [CIContext contextWithOptions:nil];
CIFilter *filter = [CIFilter filterWithName:@"CIColorControls"];
[filter setValue:outputImage forKey:kCIInputImageKey];
[filter setValue:@0.3f forKey:kCIInputSaturationKey];
//[filter setValue:@1.0f forKey:kCIInputBoostShadowAmountKey]; this is not working.. since it's not in CIColorControls...
CIImage *outputImage3 = [filter valueForKey:kCIOutputImageKey];
_outputImage.image = [UIImage imageWithCGImage:[context3 createCGImage:outputImage3 fromRect:outputImage3.extent]];

Update:
Got it it's CIHighlightShadowAdjust. But which parameter to set?
CIImage *inputImage;
NSNumber *inputRadius;
NSNumber *inputShadowAmount; // this one?
NSNumber *inputHighlightAmount;
NSNumber *_inputRadius;

A: I was searching for the key too. Somehow there isn't, but you can use the string "inputHighlightAmount" directly.
let parameters = [
        kCIInputImageKey: self,
        "inputHighlightAmount": highlight,
        "inputShadowAmount": shadow,
        ] as [String : Any]
let filter = CIFilter(name: "CIHighlightShadowAdjust", parameters: parameters)


text:
Q: Chart.js v2 Show Data Points Above Bar Chart Is there a way to customize the snippets available here to make the bar chart have data points above? I know angular-chart.js uses Chart.js V2 and the questions I found were already old. Like this one but it's not being wrapped in Angular.
JavaScript from the Demo:
angular.module("app", ["chart.js"]).controller("BarCtrl", function ($scope) {
  $scope.labels = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
  $scope.series = ['Series A', 'Series B'];

  $scope.data = [
    [65, 59, 80, 81, 56, 55, 40],
    [28, 48, 40, 19, 86, 27, 90]
  ];
});

HTML
<canvas id="bar" class="chart chart-bar"
  chart-data="data" chart-labels="labels" chart-series="series">
</canvas>


text:
Q: Javascript - Creating an event listener for an exported class I'm trying to create a class that supplies an event listener and handler for a html canvas object to respond to when left and right arrow keys are pressed. my project has 2 files a game's classes file and the game's main file
these are the functions that would normally go into the games main file. but I'm trying to make them into a class that can be exported.
// unmodified code
function keyDownHandler(e) {
  if (e.keyCode == 39) {
    rightPressed = true;
  }
  else if (e.keyCode == 37) {
    leftPressed = true;
   }
}

 function keyUpHandler(e) {
   if (e.keyCode == 39) {
    rightPressed = false;
  }
   else if (e.keyCode == 37) {
     leftPressed = false;
   }
}
 document.addEventListener("keydown", keyDownHandler, false);
 document.addEventListener("keyup", keyUpHandler, false);

// actual answer is below
export class Paddle {
  constructor (world) {
    this.canvas = world.canvas,
    this.ctx = world.ctx,
    this.paddleHeight = 10;
    this.paddleWidth = 75;
    this.paddleX = (this.canvas.width - this.paddleWidth) / 2;
    this.rightPressed = false;
    this.leftPressed = false;
    // do i have to make a attribute for the event handlers?
    // or do i just add the listeners here?
  }

 draw()  {
    this.ctx.beginPath();
    this.ctx.rect(this.paddleX, this.canvas.height - this.paddleHeight, this.paddleWidth, this.paddleHeight);
    this.ctx.fillStyle = "#0095DD";
    this.ctx.fill();
    this.ctx.closePath();
}

keyDownHandler(e) {
    if (e.keyCode == 39) {
        rightPressed = true;
    }
    else if (e.keyCode == 37) {
        leftPressed = true;
    }
}

keyUpHandler(e) {
    if (e.keyCode == 39) {
        rightPressed = false;
    }
    else if (e.keyCode == 37) {
        leftPressed = false;
    }
}
listener() {
    document.addEventListener("keydown", this.keyDownHandler, false);
    document.addEventListener("keyup", this.keyUpHandler, false);
}
}

A: Create object that contains properties keyDownHandler and keyUpHandler as a functions and keyDown and KeyUp as a constants in the module
// Module my-module.js
var foo={
rightPressed:false;
leftPressed:false;
keyDownHandler:function(e) {
    if (e.keyCode == 39) {
        this.rightPressed = true;
    }
   else if (e.keyCode == 37) {
        this.leftPressed = true;
    }
}
keyUpHandler:function(e){
     if (e.keyCode == 39) {
         this.rightPressed = false;
     }
    else if (e.keyCode == 37) {
         this.leftPressed = false;
     }
  const keyDown=  document.addEventListener("keydown", this.keyDownHandler, false);
 const keyUp= document.addEventListener("keyup", this.keyUpHandler, false);
}
export {foo};

Import the Module
import{foo} from 'my-module';

Use the constants
foo.keyUp;
foo.keyDown;

A: You're really quite close - but in your keyHandler functions, you have this:
if (e.keyCode == 39) {
    rightPressed = true;
}

There is no global variable rightPressed - it exists only in the class Paddle. Change your key handlers to this:
keyDownHandler(e) {
    if (e.keyCode == 39) {
        this.rightPressed = true; //Changed here
    }
    else if (e.keyCode == 37) {
        this.leftPressed = true; //Changed here
    }
}

keyUpHandler(e) {
    if (e.keyCode == 39) {
        this.rightPressed = false; //Changed here
    }
    else if (e.keyCode == 37) {
        this.leftPressed = false; //Changed here
    }
}

Now all you need to do is change the listener() function in Paddle like this:
listener() {
    document.body.addEventListener("keydown", this.keyDownHandler(e), false);
    document.body.addEventListener("keyup", this.keyUpHandler(e), false);

And create the instance of your class like this:
var player = new Paddle(world);

And you need to put all the functions into the constructor for it to work.


text:
Q: Change default content type for previewing site with "nanoc view" I generate HTML files without any filetype extension with the following route in nanoc's Rules file:
route '/blog/*/' do
  item.identifier.chop
end

So the file /content/blog/hello-world.html gets generated as /output/blog/hello-world, leading to the URL path /blog/hello-world.
When using nanoc's built-in preview server (nanoc view, which uses adsf and WEBrick, as far as I understand), these extension-less HTML files get interpreted as plain text.
For previewing with nanoc view, how can I set the default content type (i.e. text/html) for files without filetype extensions?
(When publishing this site, I set the correct content type in Apache's .htaccess file so that the files get interpreted as HTML, but WEBrick/adsf don't seem to support .htaccess.)

A: You should be writing those to /output/blog/hello-world/index.html instead. That makes them work seamlessly in nanoc view, Apache (with no .htaccess), even by just opening the site files in your browser (assuming you're using relativized links).


text:
Q: Using a json to create MySQL table If I have a list of json objects that describe SQL columns, like so:
[{'type': 'int4', 'id': '_id'},
{'type': 'text', 'id': 'month'},
{'type': 'text', 'id': 'town'}]

Is there any native features in MySQL that allows me to create a table using this list of json objects, instead of hardcoding my CREATE TABLE statement?
A sample create table statement would be:
CREATE TABLE house
             (_id integer PRIMARY KEY,
              month varchar,
town varchar)

A: No, MySQL does not have any built-in features to infer a table design from your JSON sample.


text:
Q: Error in deploying SQL CLR Error1:

The following error might appear if you deploy a SQL CLR project that was built for a version of the .NET Framework that is incompatible with the target instance of SQL Server: "Deploy error SQL01268: CREATE ASSEMBLY for assembly failed because assembly failed verification". To resolve this issue, open the properties for the project, and change the .NET Framework version.

Error2:

Deploy error SQL01268: .Net SqlClient Data Provider: Msg 6503, Level 16, State 12, Line 1 Assembly 'system.servicemodel, version=3.0.0.0, culture=neutral, publickeytoken=b77a5c561934e089.' was not found in the SQL catalog.
    An error occurred while the batch was being executed.

A: Have to install System.ServiceModel in Sql Server 2008 and it worked after that.
Happy Coding :)


text:
Q: I'm not in "wheel" group, but I can "su -" I don't understand. In BSD if I want to run su -, I have to add myself to wheel group.
Is this not true in Linux?
[test@centos ~]$ uname -a
Linux centos 4.18.0-193.19.1.el8_2.x86_64 ...
[test@centos ~]$ cat /etc/group | grep wheel
wheel:x:10:
[test@centos ~]$ cat /etc/group | grep test
test:x:1001:
[test@centos ~]$ su -
Password:
Last login: Wed Oct 14 ...
[root@centos ~]# whoami
root

A: It depends on the Linux distribution, but in CentOS, there's no special relationship between su and wheel out of the box:
% docker run --rm -it centos:8
[root@58212abdad65 /]# grep wheel /etc/pam.d/ -r
/etc/pam.d/su:# Uncomment the following line to implicitly trust users in the "wheel" group.
/etc/pam.d/su:#auth     sufficient  pam_wheel.so trust use_uid
/etc/pam.d/su:# Uncomment the following line to require a user to be in the "wheel" group.
/etc/pam.d/su:#auth     required    pam_wheel.so use_uid

As you can see, you can configure it to behave like the BSD you use.
In some other distros, the first option might be enabled (allowing wheel users to su without needing a password), but I don't remember which ones.

A: When invoked as aforementioned, the su command will ask for a root/superuser password; group membership is irrelevant, as long as you know the password. Now, if you were using sudo su, you could assign group(s) superuser rights; wheel and sudo are (2) groups most often used out-of-the-box, especially on single-user systems.


text:
Q: Connect to other users Outlook in Azure Logic App I have constructed a LogicApp Standard that manipulates Outlook Tasks. The "Outlook Tasks Connector" allows me to nominate an account to use when doing this, but the Actions only give me access to that account's Task Lists.
How do I go about creating a LogicApp Standard that manipulates Outlook Tasks (and Calendar etc.) for a user defined at runtime by a parameter ? Is there a different Connector or Action I should be using for this ?

A: If you're unable to change the connection action on action then your best bet is to look at using the relevant Graph API.
https://learn.microsoft.com/en-us/graph/api/todotasklist-post-tasks?view=graph-rest-1.0&tabs=http
It will allow you to adjust the parameters rather than relying on a single connection.


text:
Q: Is this scala parallel array code threadsafe? I want to use parallel arrays for a task, and before I start with the coding, I'd be interested in knowing if this small snipept is threadsafe:
import collection.mutable._

var listBuffer = ListBuffer[String]("one","two","three","four","five","six","seven","eight","nine")
var jSyncList  = java.util.Collections.synchronizedList(new java.util.ArrayList[String]())
listBuffer.par.foreach { e =>
    println("processed :"+e)
    // using sleep here to simulate a random delay
    Thread.sleep((scala.math.random * 1000).toLong)
    jSyncList.add(e)
}
jSyncList.toArray.foreach(println)

Are there better ways of processing something with parallel collections, and acumulating the results elsewhere?

A: The code you posted is perfectly safe; I'm not sure about the premise though: why do you need to accumulate the results of a parallel collection in a non-parallel one? One of the whole points of the parallel collections is that they look like other collections.
I think that parallel collections also will provide a seq method to switch to sequential ones. So you should probably use this!

A: For this pattern to be safe:
listBuffer.par.foreach { e => f(e) }

f has to be able to run concurrently in a safe way. I think the same rules that you need for safe multi-threading apply (access to share state needs to be thread safe, the order of the f calls for different e won't be deterministic and you may run into deadlocks as you start synchronizing your statements in f).
Additionally I'm not clear what guarantees the parallel collections gives you about the underlying collection being modified while being processed, so a mutable list buffer which can have elements added/removed is possibly a poor choice. You never know when the next coder will call something like foo(listBuffer) before your foreach and pass that reference to another thread which may mutate the list while it's being processed.
Other than that, I think for any f that will take a long time, can be called concurrently and where e can be processed out of order, this is a fine pattern.
immutCol.par.foreach { e => threadSafeOutOfOrderProcessingOf(e) }

disclaimer: I have not tried // colls myself, but I'm looking forward at having SO questions/answers show us what works well.

A: The synchronisedList should be safe, though the println may give unexpected results - you have no guarantees of the order that items will be printed, or even that your printlns won't be interleaved mid-character.
A synchronised list is also unlikely to be the fastest way you can do this, a safer solution is to map over an immutable collection (Vector is probably your best bet here), then print all the lines (in order) afterwards:
val input = Vector("one","two","three","four","five","six","seven","eight","nine")
val output  = input.par.map { e =>
  val msg = "processed :" + e
  // using sleep here to simulate a random delay
  Thread.sleep((math.random * 1000).toLong)
  msg
}
println(output mkString "\n")

You'll also note that this code has about as much practical usefulness as your example :)

A: This code is plain weird -- why add stuff in parallel to something that needs to be synchronized? You'll add contention and gain absolutely nothing in return.
The principle of the thing -- accumulating results from parallel processing, are better achieved with stuff like fold, reduce or aggregate.

A: The code you've posted is safe - there will be no errors due to inconsistent state of your array list, because access to it is synchronized.
However, parallel collections process items concurrently (at the same time), AND out-of-order. The out-of-order means that the 54. element may be processed before the 2. element - your synchronized array list will contain items in non-predefined order.
In general it's better to use map, filter and other functional combinators to transform a collection into another collection - these will ensure that the ordering guarantees are preserved if a collection has some (like Seqs do). For example:
ParArray(1, 2, 3, 4).map(_ + 1)

always returns ParArray(2, 3, 4, 5).
However, if you need a specific thread-safe collection type such as a ConcurrentSkipListMap or a synchronized collection to be passed to some method in some API, modifying it from a parallel foreach is safe.
Finally, a note - parallel collection provide parallel bulk operations on data. Mutable parallel collections are not thread-safe in the sense that you can add elements to them from different threads. Mutable operations like insertion to a map or appending a buffer still have to be synchronized.


text:
Q: onclick keeps calling javascript function HTML:

Pseudo Random Quote Machine

      <button id = "getMessage" class = "btn btn-primary">
        Get Random Quote
      </button>
      <button id = "tweet" class = btn btn-primary>Tweet this!
      </button>

Javascript:
function randomQuotes()
{
  //array of quotes
  var quotes = [ "\"Operator! Give me the number for 911!\" - Homer J. Simpson", "\"I\'m normally not a praying man, but if you\'re up there, please save me Superman\" - Homer J. Simpson", "\"I\'m in no condition to drive...wait! I shouldn\'t listen to myself, I\'m drunk!\" - Homer J. Simpson", "\"A Degenerate, Am I? Well You Are A Festizo. See, I Can Make Up Words Too, Sister\" - Peter Griffen", "\"Victory Shall Be Mine!\" - Stewie Griffen", "\"He's a spy, blow him up. I'm gonna go take a shit.\" - Rick Sanchez", "\"Ohh yea, you gotta get schwifty. \" - Rick Sanchez", "\"Yo! What up my glip glops!\" - Rick Sanchez", "\"WUBBA LUBBA DUB DUBS!!! \" - Rick Sanchez", "\"Existence is pain to a meeseeks Jerry, and we will do anything to alleviate that pain.\" - Mr. Meeseeks", " \"It\'s morphine time\" - TheRussianBadger"];

  var randNum = Math.floor((Math.random() * quotes.length));
  document.getElementById("quoting").innerHTML = quotes[randNum];
}

function tweetThis()
{
  var tweetToShare = document.getElementById("quoting").innerHTML;
  var tweetUrl = 'https://twitter.com/share?text=' +   encodeURIComponent(tweetToShare) + ".";
  window.open(tweetUrl);
}

document.getElementById("getMessage").onclick = function(){randomQuotes();}
document.getElementById("tweet").onclick = function(){tweetThis();}

Basically, any time I click either of the two buttons the function keeps being called over and over again. Here is the code running in Code Pen
I guess my questions would be:

*

*why would the functions be called more than one time ?

*What should I do to either stop the functions from being called multiple times or prevent it from happening in the first place?

A: functions seem to be called only one time on chrome. Maybe your browser cached an old script: maiusc+f5 to clean


text:
Q: Search string using Function - Oracle I am trying to search a string using the input values passed to my Oracle function. Following is the code[modified since I cannot paste the original code]:
CREATE OR REPLACE FUNCTION uf_search_address
(
   street  IN VARCHAR2,
   city    IN VARCHAR2
)
RETURN NUMBER
IS RCVD_PERSON_ID NUMBER;
BEGIN
   SELECT PERSON_ID INTO RCVD_PERSON_ID
   FROM T_PARTICIPANTS
   WHERE COMPLETE_ADDRESS LIKE street[?] OR COMPLETE_ADDRESS LIKE city[?]
   RETURN (RCVD_PERSON_ID);
END;

But the query fails to return anything(it compiles though).
How can I use the LIKE functionality with the parameters passed?

A: The way to use like with parameters is to use the concatenation operator || so your function would be like the following, which would return anything that begins with street or city:
create or replace function uf_search_address ( P_street IN varchar2
                                             , P_city IN varchar2
                                               ) return number is

   rcvd_person_id number;

begin

   select person_id
     into rcvd_person_id
     from t_participants
    where complete_address like P_street || '%'
       or complete_address like P_city || '%'
          ;

   return rcvd_person_id;

exception when no_data_found then
   return null;

end;
/
show error

However If there's more than one value that matches this query it will fail. As the chances are you have more than one person per city it makes it fairly likely that what you're trying to do will never work. Note also the exception handler as if there's no matches for your query Oracle will throw and error as well.
You will need to make some sort of decision in the code:
This can either be done in SQL, for instance by using rank. In the example below timestamp would be the date of entry into the table for a very simplistic ranking system:
select person_id
  into rcvd_person_id
  from ( select person_id
           from ( select person_id
                       , rank() over ( order by timestamp desc ) as rnk
                    from t_participants
                   where complete_address like P_street || '%'
                      or complete_address like P_city || '%'
                         )
          where rnk = 1
                )

Alternatively you could make your decision in PL\SQL by bulk collecting everything into a type and doing some looping.


text:
Q: Fire and forget with async Consider this code:
public async Task<Status> SendMessage(Message message)
{
    List<IMessage> _messageDispatchers = new List<IMessage>();
    try
    {
        Object[] args = new Object[] { _message };
        IMessage endpoint = (IMessage)Activator.CreateInstance(Type.GetType(_message.AgentDLLName), args);
        _messageDispatchers.Add(endpoint);

        foreach (IMessage dispatcher in _messageDispatchers)
        {
            await Task.Run(() => dispatcher.SendMessage(_message));
        }
        return await Task.Run(() => Status.Success);
    }
    catch (Exception ex)
    {
        logger.Log(LoggerLevel.Error, ex.Message);
        return Status.EmailSendingFailed;
    }

}

the SendMessage:
public async Task<Status> SendMessage(OutboundMessage outboundmessage)
{
    string strMessage = string.Empty;
    string subject = string.Empty;
    MessageServices objService = new MessageServices();
    try
    {
        var config = (from SmtpConfigurationElement ms in AppConfiguration.Instance.Smtps
                      where ms.Key == "smtp"
                      select ms).Single();

        SmtpClient smtpClient = new SmtpClient(config.Host);
        smtpClient.Port = Convert.ToInt32(config.port);
        smtpClient.EnableSsl = true;
        smtpClient.Credentials = new NetworkCredential(config.UserName, config.Password);

        string[] strToList = outboundmessage.ToList.Split(';');
        MailMessage mail = new MailMessage();
        mail.From = new MailAddress(outboundmessage.FromAddress);

        if (strToList.Length > 0)
        {
            for (int j = 0; j < strToList.Length; j++)
            {
                mail.To.Add(strToList[j]);
            }
        }
        else
        {
            _LOGGER.Log(LoggerLevel.Information, "SMTP Mail Send failed as ToList is not correct");
            return Status.Failed;
        }

        if (!string.IsNullOrEmpty(outboundmessage.CCList))
        {
            string[] strCCList = outboundmessage.CCList.Split(';');
            if (strCCList.Length > 0)
            {
                for (int k = 0; k < strCCList.Length; k++)
                {
                    mail.CC.Add(strToList[k]);
                }
            }
        }

        if (!string.IsNullOrEmpty(outboundmessage.Attachments))
        {
            System.Net.Mail.Attachment attachment;
            attachment = new System.Net.Mail.Attachment(outboundmessage.Attachments);
            mail.Attachments.Add(attachment);
        }

        strMessage = await objService.ReplaceMessageWithPlaceholders(outboundmessage.PlaceholderValues, outboundmessage.MessageBody);
        subject = await objService.ReplaceMessageWithPlaceholders(outboundmessage.PlaceholderValues, outboundmessage.Subject);
        mail.Body = strMessage;
        mail.Subject = subject;
        mail.IsBodyHtml = true;
        await Task.Run(() => smtpClient.Send(mail));

        return Status.Success;
    }
    catch (Exception ex)
    {
        return Status.Failed;
    }
}

And the call to SendMessage:
public Status MarketingEmail(OutboundMessage _message)
{
    try
    {
        _message.MessageCreatedDate = System.DateTime.Now;
        processor.SendMessage(_message);
        return Status.Success;
    }
    catch (Exception ex)
    {
        _LOGGER.Log(LoggerLevel.Error, "Error in Marketing Email" + ex.ToString());
        return Status.InsertFailed;
    }
}

The whole idea is to make a workflow in which sending of the email is the last task and that should be a fire and forget thing.
Now the call to processor.SendMessage(_message) has a suggestion like this:

Because this call is not awaited, execution of the current method
  continues before the call is completed. Consider applying the 'await'
  operator to the result of the call.

Which is a valid thing since async & await need to be used together.
Questions:

*

*Will the current approach work without any trouble if the suggestion is ignored?
(I am asking this since this is still in the development stage and I can make the suggested design changes now rather than face any critical issues later.)

*What is the suggested best practice to design a workflow considering the said requirement?

A: The current approach will "work" in the sense that it will continue on to return Status.Success; without waiting for the call to processor.SendMessage(_message); to complete.
However, since that call was fired & forgotten, and that SendMessage overload doesn't do any logging in the catch block, you run the risk of emails failing to be sent but nobody getting notified about it.
A common approach for async email sending is this: Stash the email somewhere else (typically a message queue or a database), and then set up a separate async process that reads the queued emails and sends them. If it succeeds, it flags the email as sent. If it fails, it tries again (up to a certain time limit or # of retries), and then if it gives up, it can trigger a notification or set a flag that can be checked later.
Then your code will basically be saying "okay, the email was successfully queued", instead of "okay, the email was sent". Moving the actual sending to a separate process is much more reliable.


text:
Q: Did Harry ever trim Hedwig's talons? In the Harry Potter series, many of the youth occupying Hogwarts have a pet. Pets are often considered to be a good way to teach children responsibility, as it lets them learn to care for another creature with a relatively low cost of failure (a new toad, perhaps).
Those who have an owl are removed from some of that responsibility, as unlike other pets owls do not reside in the students dormitories. So, while we see Ron administer rat tonic to his pet Death Eater, and Hermione fuss over... whatever it is that she's got, there's very little screen time given to the relationship between Harry and Hedwig.
So... I wonder if Harry ever took a personal interest in the care of his pet? Or was she simply a mail delivery (plot) device?

A: Hedwig was Harry's pet but she was not always kept in the cage like muggles (we) keep our pet birds. Other than in Harry Potter and the Chamber of Secrets, Hedwig was allowed to fly out to deliver letters and also allowed to hunt.
There are references in the book about this:
Vacation Time:

Harry copied these words on to three separate pieces of parchment the moment he reached the desk in his dark bedroom. He addressed the first to Sirius, the second to Ron and the third to Hermione. His owl, Hedwig, was off hunting; her cage stood empty on the desk.

Harry Potter and the Order of the Phoenix, Chapter 3, The Advance Guard

Hedwig hooted happily at Harry from her perch on top of a large wardrobe, then took off through the window; Harry knew she had been waiting to see him before going hunting.

Harry Potter and the Half-Blood Prince, Chapter 5, Excess of Phlegm
The owls at Hogwarts Owlery were free to move out of the school for hunting. There are couple of references to this
During stay at Hogwarts:

The sun was high in the sky now and when Harry entered the Owlery the glassless windows dazzled his eyes; thick silvery beams of sunlight crisscrossed the circular room in which hundreds of owls nestled on rafters, a little restless in the early-morning light, some clearly just returned from hunting.

Harry Potter and the Order of the Phoenix, Chapter 14, Percy and Padfoot

The many perches were half- empty; every now and then, another owl would swoop in through one of the windows, returning from its night's hunting with a mouse in its beak.

Harry Potter and the Goblet of Fire, Chapter 29, The Dream
I am giving these examples because even though Hedwig was Harry's pet she almost lived her life like a wild owl. Going out at night, hunting and stuff. Normally birds/animals that do hunting do not need special attention (as long as they are not injured).

Talons are made of keratin and continue growing throughout a bird's life as they are continually worn down through use.

Referred from http://birding.about.com/od/Bird-Glossary-S-T/g/Talon.htm
Harry did care about Hedwig.

Hmm," said Professor Grubbly-Plank, her pipe waggling slightly as she talked. "Looks like something's attacked her. Can't think what would have done it, though. Thestrals will sometimes go for birds, of course, but Hagrid's got the Hogwarts Thestrals well-trained not to touch owls."
Harry neither knew nor cared what Thestrals were; he just wanted to know that Hedwig was going to be all right. Professor McGonagall, however, looked sharply at Harry and said, "Do you know how far this owl's traveled, Potter?"

Harry Potter and the Order of the Phoenix, Chapter 17, Educational Decree Number Twenty-Four

A second's relief, and then another burst of green light. The owl screeched and fell to the floor of the cage.
  "No—NO!"
  The motorbike zoomed forward; Harry glimpsed hooded Death Eaters scat- tering as Hagrid blasted through their circle.
  "Hedwig—Hedwig—"
But the owl lay motionless and pathetic as a toy on the floor of her cage. He could not take it in in, and his terror for the others was paramount. He glanced over his shoulder and saw a mass of people moving, flares of green light, two pairs of people on brooms soaring off into the distance, but he could not tell who they were—
  "Hagrid, we've got to go back, we've got to go back!" he yelled over the thun- derous roar of the engine, pulling out his wand, ramming Hedwig's cage into the floor, refusing to believe that she was dead. "Hagrid, TURN AROUND!"

Harry Potter and the Deathly Hallows, Chapter 4, The Seven Potters
In short Harry cared for Hedwig, it was just that owl's were low maintenance pets.


text:
Q: Upload an image with AFNetworking 2.0 I can't understand why this is so hard. All the tutorials and articles online seem to be talking about the 1.0 api, which is pretty useless.
I've tried a few different ways and get different results. What am I doing wrong?

*

*upload task - this seems to not be using a multipart form, wtf?
NSMutableURLRequest *request = [self.manager.requestSerializer multipartFormRequestWithMethod:@"POST"
                                                                                URLString:[[NSURL URLWithString:url relativeToURL:[NSURL URLWithString:ApiBaseUrl]] absoluteString]
                                                                                parameters:@{}
                                                                  constructingBodyWithBlock:nil];

NSProgress *progress;
NSURLSessionUploadTask *task = [self.manager uploadTaskWithRequest:request
                                                        fromData:data
                                                        progress:&progress
                                               completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
                                                 if (error) {
                                                   NSLog(@"[error description] = %@", [error description]);
                                                 } else {
                                                   NSLog(@"success!");
                                                 }
                                               }];

[task resume];

*post with a block - this seems not to attach anything
[self.manager POST:url
           parameters:@{}
constructingBodyWithBlock:^(id <AFMultipartFormData> formData) {
    [formData appendPartWithFileData:data
                                name:@"post[picture]"
                            fileName:@"picture.jpg"
                            mimeType:@"image/jpeg"];
}
              success:^(NSURLSessionDataTask *task, id response) {
                NSLog(@"Success");
              }
              failure:^(NSURLSessionDataTask *task, NSError *error) {
                NSLog(@"Error: %@", error);
              }];

*simple post - this seems to almost work...but not
[self.manager POST:url
        parameters:@{@"post[picture][]":data}
           success:^(NSURLSessionDataTask *task, id response) {
             NSLog(@"Success");
           }
           failure:^(NSURLSessionDataTask *task, NSError *error) {
             NSLog(@"Error: %@", error);
           }];

I would love 1 to work, but I'm not sure why it doesn't.

A: What Ray Lillywhite describes works perfectly fine (I would've made a comment on his post, but my reputation is too low).

*

*Get the correct version of AFNetworking, containing this fix for updating progress when using multipart requests. At the moment of writing, that version is HEAD.

*Create a NSMutableURLRequest with the help of multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error:.

*

*Build your form data with the help of one of the appendPartWith... methods.

*Get a (upload) data task by calling the right uploadTaskWith... method. You NEED to use uploadTaskWithStreamedRequest:progress:completionHandler: if you want to use the NSProgress input parameter.

A: For a properly formed "multipart/form-data" body, you need to use use the body construction block while creating the request. Otherwise the upload task is using the raw data as the body. For example, in your AFHTTPSessionManager subclass:
NSString *urlString = [[NSURL URLWithString:kPhotoUploadPath relativeToURL:self.baseURL] absoluteString];
NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:params constructingBodyWithBlock:^(id <AFMultipartFormData> formData) {
    [formData appendPartWithFileData:photo.data name:@"photo" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
}];

NSURLSessionUploadTask *task = [self uploadTaskWithStreamedRequest:request progress:progress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
    if (error) {
        if (failure) failure(error);
    } else {
        if (success) success(responseObject);
    }
}];
[task resume];

Or, if you don't need to track upload progress, you can simply use:
[self POST:kPhotoUploadPath parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileData:photo.data name:@"photo" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
} success:^(NSURLSessionDataTask *task, id responseObject) {
    if (success) success(responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
    if (failure) failure(error);
}];


text:
Q: what is the reason for Window.location.href not working sometimes? jsp page for submit button onclick function in javascript. when i click button first time not redirected to CallService.jsp. I click the button two to three times after that only that page will be redirected.
Pls give me the solution or reason
My Code

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

User Login

<form name="userlogin" method="post">

User Name : <input type="text" name="uname" id="uname">

Password : <input type="text" name="pwd" id="pwd">

<input type="submit" value="Submit" onclick="sample(this);" >
<input type="reset" value="Cancel">

</form>

CallService.jsp
<%

  String uname = request.getParameter("username");
  //String pwd = request.getParameter("password");

  out.println(uname);

%>

A: Your button type is
<input type="submit" value="Submit" onclick="sample(this);" >

replace it with:
<input type="button" value="Submit" onclick="sample(this);" >

or
Call your function when submitting form like this:
<form method="post" name="fromname" onsubmit="yourfunction()">

A: Try this:
window.location.href = "CallService.jsp?username="+uname;

You are submitting form and redirecting to another form same time. It's not right

A: <input type="submit" value="Submit" onclick="sample(this);" >

You cannot submit and redirect this.
In your servlet / jsp where the form is submitted, redirect the page.

A: please try:
function sample()
{

    var uname = document.getElementById("uname").value;
    //var pwd = document.getElementById("pwd").value;

    window.location.href("CallService.jsp?username="+uname);
    //FUNCTION MUST RETURN FALSE!!
    return false;
}

<input type="submit" value="Submit" onclick="return sample(this);" >

this way js function will need to be evaluted before making postback

A: Why dont you try redirecting from you java class, like this

actionResponse.sendRedirect("CallService.jsp");

A: Since you are fetching the data using javascript here :
var uname = document.getElementById("uname").value;

theres no need to use a 'submit' button. Try to change
<input type="submit" value="Submit" onclick="sample(this);" >

into
<input type="button" value="Submit" onclick="sample(this);" >


text:
Q: MergeSort Liguagem C estou fazendo um trabalho para a faculdade e estou tento um pequeno problema no meu código pois é a primeira vez que estou tendo contato com MergeSort. Eu estou tentando fazer com eu a saída dele na tela seja do tipo:

Loja 1: 1
Loja 2: 8
loja 3: 7
Loja 4: 8
Loja 5: 3
Loja 6: 3
Loja 7: 7
Loja 8: 5

Ao invés de apenas:

1, 8, 7, 8, 3, 3, 7, 5

#include <stdio.h>

#define max 7

int a [8] = { 1, 8, 7, 8, 3, 3, 7, 5};
int b [7];

void merging (int low, int mid, int high){
    int l1, l2, i;

    for (l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++){
        if (a[l1] <= a[l2])
            b [i] = a[l1++];
        else
            b[i] = a[l2++];
    }

    while(l1 <= mid)
        b[i++] = a[l1++];

    while(l2 <= high)
        b[i++] = a[l2++];

    for (i = low; i <= high; i++)
        a[i] = b[i];
}

void sort(int low, int high){
    int mid;

    if(low < high){
        mid = (low + high) / 2;
        sort(low, mid);
        sort(mid + 1, high);
        merging(low, mid, high);
    }else{
        return;
    }
}

int main(){
    int i;

    printf("Lista antes da classificação:\n\n");

    for(i = 0; i <= max; i++)
        printf("%d ", a[i]);

    sort(0, max);

    printf("\n\nLista após a classificação:\n\n");

    for(i = 0; i <= max; i++)
        printf("%d ", a[i]);
}

A: Pelo que entendi, este é seu retorno atual:

1, 8, 7, 8, 3, 3, 7, 5

Sendo assim, o que você precisa fazer é ao invés de imprimir apenas "numero, ", você imprime o texto que precisa:
printf("Loja %d: %d\n", i, a[i]);


text:
Q: Can you use an op-amp like this to detect current? For a model train track, I'd like a simple circuit which can detect current. In the past, I used an opto-coupler in combination with 2 diodes. A current flowing through these diodes would cause a voltage drop of 1.4 V over the opto-coupler. This was enough to steer the opto-coupler open. The 1.4 V voltage drop was a problem, because it lets trains make a noticeable jump in speed. So I am looking for a replacement.
There are other methods to detect current, but most of them are relative large circuits with too many components.
So I drew this experimental circuit. The idea is that a very small current flowing through a 0.2 Ω resistor, would create a voltage over the op-amp, causing it to drive the LED when this voltage is positive. I am aware that the voltage would be negative 50% of the time. But an Arduino can filter the signal further.

So my question is: Will this circuit work? Is the connection between the 0 V and 16 V supply needed? Or would it work without it as well?

A: That will work with a single-supply op-amp like LM358. The connection between 0V and 16VAC is necessary (or something like that). It would be best to add a resistor in series with the non-inverting input of the op-amp since the input doesn't like it when applied voltages go much below zero.
Note: because Vos of the op-amp can be positive or negative, you cannot predict the state of the output with no current (could be either high or low). You could either add circuitry, use an op-amp with Vos or trim, or detect changes in your firmware- it will go high and low at the VAC frequency.
Note that if your VAC is higher than mains frequency (for PWM, for example), the op-amp may not be able to keep up. The last time I had a model train, the controller looked like this but I imagine things have moved on since then.

A: Seems simple, but you should be concerned about some points:

*

*any intermittent contact in the rails could generate high voltage, caused by motor inductance, which I sincerely don't know how it would be managed in a scaled model train and its rails.

*depending of current needed by train's motor, voltage drop in 0R2 might be too small (still ok) but might be above 0.4Vpeak, if any current exceeds 2A. In this case, an OpAmp as LM358, according to the datasheet, would withstand Input Voltages from -0.3V to +28V.

So in the above scenario, the input side of LM358 is NOT protected.
Suggestions:
1 - I would suggest adding in parallel to your 0R2 sensing resistor another 2 Schotkky diodes (as 1N5817, 18 or 19) in anti-parallel to limit the maximum voltage drop to +/- 0.3V (up to 1A) or +/- 0.6V (up to 5A for 100cycles > 1s).
2 - Then, using a voltage divider of R1= 10K (between 0R2 sensing and +input) and R2= 2K2 (between +input and Ground), would further limit Negative Voltages (< 0.3V) and Positive ones to never apply input voltage above Vsupply = 5V.
3 - Output LED will be powered in the "rectified" sensed AC. In case its flicker in the optocoupler might not be OK, adding almost any diode + electrolytic capacitor, between OpAmp and output resistor will solve that flicker. Oversizing the capacitor might even stretch the pulse duration, if also desired.
With such output, you could even drive the base of any medium power transistor as TIP31 to drive lamps, solenoids or relays directly (reminding to use a diode to absorb inductance's voltage spike).
Summary:
I would give a try in your idea using an LM358, but protected by 2 diodes and a voltage divider. Any LED + resistor at the output will give you optical feedback of its functionality, where the output could then be used to further drive any desired load.


text:
Q: C# Generics/Design Patterns: Should I use the template method? Scenario:
(If anyone has answered/viewed my questions recently this will be somewhat familar)
I have 3 different web services which expose a set of objects that have commonality. I've written wrapper classes and conversion logic using generic methods to change between the intermediary objects and the service object.
I have an interface for the Webservice, let it be called IService for the purpose of this question. I have 3 implementation classes Service1Impl, Service2Impl and Service3Impl. Each of these referencing a different web service and using my aforementioned generic methods to convert between the appropriate objects.
These are injected into my ServiceWrapper class at runtime via the constructor (a factory is used to create the appopriate implementation of the ISerivice
e.g:
_service = ServiceWrapper.GetServiceWrapper("2");

Will give me a ServiceWrapper instantiated with the Service2Impl.
(Dammit diagrams would be hella useful!)
Ok so each implementation of IService has a method called for arguments sake.. GetProperties:
public IProperty[] GetProperties(string item, IProperty[] properties)
{
    Property[] props = ServiceObjectFactory.CreateProperties<Property>(properties);
    Property[] result = _service.GetProperties(item, props);
    return ServiceObjectFactory.CreateProperties(result);
}

This looks a little confusing (I think I'm going to refactor the names).
Basically what is happening is:

*

*The call to this function from ServiceWrapper is made with the intermediary objects (IProperty) (as you can see from the parameters).

*The intermediary objects are converted to Property objects which are service specific.

*The result comes back as service specific Property objects.

*The result is converted to the intermediary objects before being passed back to the ServiceWrapper.
Now, this code is going to be exactly the same for Service1Impl, Service2Impl and Service3Impl. Except of course that the types used are different.
Can anyone think of a way to do this so that I don't have the same code 3 times?
N.B: This is not true of every method in each Implementation. Just most of them.

A: I think in general, if you want your code to have different type signatures, you'll have to write the code three different times. Since the types are different, it's not "the same code" at all.
You could put what you have into an inherited method and then wrap the results in each subclass.

A: I am not sure if it fits to your scenario but reading through your question Inversion of Control comes me on mind.