text:
Q: oAuth verification for using Twitter API with Python I'm trying to get the oauth request_token for Twitter as described here, making a call to "oauth/request_token": https://dev.twitter.com/docs/auth/implementing-sign-twitter
I'm generating the params using the encode_params function in here: https://github.com/sixohsix/twitter/blob/master/twitter/oauth.py
I then wrap the returned string in a dict with they key "Authorization" and dump it into the Headers of the Post request I'm making using the python request library. Here's the two lines I use to create the request.
ep = "OAuth " + auth.encode_params(baseUrl, method, params)
response = requests.post(baseUrl+method, headers={ "Authorization" : ep})

The eventual header looks like this (consumer_key modified):
{'Accept': '*/*',
 'Accept-Encoding': 'gzip, deflate, compress',
 'Authorization': 'OAuth oauth_callback=http%253A%252F%252Fec2-54-244-189-248.us-west-2.compute.amazonaws.com%252Fct%252Ftwitter_login_handler%252F&oauth_consumer_key=xxx&oauth_nonce=14937468581358710045&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1366568033&oauth_version=1.0&oauth_signature=kiYucZzPY%2FXy2WyJliJ6YcggVzQ%3D',
 'Content-Length': '0',
 'User-Agent': 'python-requests/1.2.0 CPython/2.7.3 Linux/3.5.0-21-generic'}

However, I'm still getting a 401 response that says: 'Failed to validate oauth signature and token'
Any idea what I'm doing wrong? Any help would really be appreciated.

A: I can't speak to the script you reference, but if you're willing to try another library as the author of rauth I can recommend it. Here's a working Twitter example. Hope that helps.

A: I ended up using python-oauth2. Their instructions were a little out of date, so I updated them and submitted a pull request. As of right now, it's not been accepted, but here's a link to the forked repo with the updated instructions.

A: Hopefully this helps someone else...
From the code referenced by maxcountryman - it has a comment that I had not found elsewhere till then :
# Get a real consumer key & secret from https://dev.twitter.com/apps/new
That helped me progress a lot...
Cheers, Ian
.


text:
Q: How to execute inline scripts retrieved from a JQuery Ajax request when content security is enabled in php I'm working on a project where I have a content security policy enabled that only allows inline scripts with a nonce to be executed.
header("Content-Security-Policy: script-src 'nonce-".$nonce."';");

and so on the page my script tags have the nonce inserted in them as such:
<script nonce="<?php echo $nonce; ?>" src="/static/js/global.js"></script>

This works perfectly fine for the most part, but my site also loads the page using an ajax request and some of the pages that are loaded via ajax requests also have script tags in them as such.
<script nonce="<?php echo $nonce; //the same nonce as before ?>"></script>

The nonce is generated and stored on a session basis so each of the script tags in the ajax request should have the same nonce as the original page, but for some reason I get this error in the chrome console:

jquery.min.js:2
Refused to execute inline script because it violates the following
Content Security Policy directive: "script-src
'nonce-YTQ4NTU4NzU1YTlkZGY5MmYzNDZlMTc0MDRhNGNiZTk='". Either the
'unsafe-inline' keyword, a hash
('sha256-88nUYsb1c+aRY8mvRZ5hGPAkvH3REgfxFMQa6iIP4GY='), or a nonce
('nonce-...') is required to enable inline execution.

How do I make it so that the script tags loaded via the ajax request also get executed.

A: I figured out the cause for anyone else who runs into this issue in the future. It has to do with the way script tags work, and how JQuery appends them. When using the .append() or .html() functions, JQuery will start by appending the script tag, but immediately after it does that, the browser will check the new script tag for the existence of the nonce. Since JQuery does not add the nonce as an attribute before appending the script tag, that new script tag now gets disabled by the browser for missing the nonce when it was created. The workaround was to make my own function to append the scripts that works like the following below:
//create a script tag node
let node = document.createElement("script");

//this is the element where the script will get appended
let vr = document.getElementById("change-region");

//insert your nonce here from wherever you retrieve it from
let nonce = "sd234r8hf8wresiu"; //insert your nonce here from wherever you get your nonce

//add the nonce to the new script node we made
node.setAttribute("nonce", nonce);

//add the source of your script
node.setAttribute("src", "/source/of/script");

//append the node of the script element and it should be accepted by the browser this time
vr.appendChild(node);

redpajama_set_name: RedPajamaStackExchange


text:
Q: render from another method I have two urls defined in my urls.py one to go to homepage.html and one to go to unauthorized.html. I created the following in my views.py. My goal was to have a common method called "check_authorized" and to call that from my homepage method and if it met a condition here if 'isFoo' is false to call 'unauthorized' method so that it can redirect to the unauthorized.html. However when I call homepage.html it doesn't redirect to that page instead it stays on homepage.html ( I even removed the if block so that the code path hist the 'unauthorized' method directly). Here is the view.py
def check_authorized(request):
    ctx = RequestContext(request)
    posixGroups = []
    #Have some logic to add groups

    ctx['isFoo'] = 'foo' in posixGroups
    if not ctx['isFoo']:
        unauthorized(request)
    return ctx

def unauthorized(request):
    ctx = RequestContext(request)
    return render_to_response('unauthorized.html', ctx)

def homepage(request):
    ctx = check_authorized(request)
    return render_to_response('homepage.html', ctx)

In my Urls.py I have in the url patterns
(r'^unauthorized', views.unauthorized),
(r'', views.homepage),

Update:
Adding decorator class
def check_authorized(request, login_url=None):
    def is_authorized(u):
        user = request.META['REMOTE_USER']
        posixGroups = []
        #Code to get posix groups
        isFoo  = 'foo' in posixGroups

        if not isFoo:
            return False
        return True
    return user_passes_test(is_authorized, login_url=login_url)

def unauthorized(request):
    ctx = RequestContext(request)
    return render_to_response('unauthorized.html', ctx)

@check_authorized(login_url='unauthorized')
def homepage(request):
    ctx = check_authorized(request)
    return render_to_response('homepage.html', ctx)

Error
Exception Type: TypeError
Exception Value:
check_authorized() takes at least 1 argument (1 given)

A: This is a very good use case for a decorator, like login_required:
from django.contrib.auth.decorators import login_required

@login_required(login_url='/accounts/login/')
def my_view(request):
    ...

It would redirect the user to the login_url if it is not authenticated.
So, since you have a custom logic that decides whether to redirect the user to login_url or not, you need a custom decorator that would be similar to Django built-in decorators:
from django.contrib.auth.decorators import user_passes_test

def check_authorized(request, login_url=None):
    def is_authorized(user):
        # Have some logic that returns True/False
        ...
    return user_passes_test(is_authorized, login_url=login_url)

@check_authorized(login_url='unauthorized/')
def homepage(request):
    return render_to_response('homepage.html')

Also see:

*

*group_required decorator


text:
Q: If X is normally distributed, and c is a constant, is cX also normally distributed? If $X\sim N(\mu, \sigma^2)$, and if $c$ is a constant, is $cX$ also normally distributed? How do you show it?
If yes, does this apply to other distributions? So if $Y$ follows some type of distribution, will $cY$ also follow that distribution?
Thank you very much!

A: The answer to your first question is yes:  if $c \ne 0$ and $c \in \mathbb R$, then $cX \sim \operatorname{Normal}(c\mu, |c|\sigma)$ if $X$ is normal with mean $\mu$ and standard deviation $\sigma$.  This is because the normal distribution belongs to a location-scale family:  its PDF is $$f_X(x) = \frac{1}{\sqrt{2\pi}\sigma} e^{-(x-\mu)^2/(2\sigma^2)}, \quad -\infty < x < \infty.$$  Then $Y = cX$ will have PDF $$f_Y(y) = \frac{1}{|c|} f_X(y/c),$$ and a little algebra will show that this is also a normal PDF.  I have left this second part as an exercise.
The answer to your third question, the answer is no: some distributions do not have a scale parameter.  Obvious examples are:  the binomial distribution and Poisson distribution.  These have discrete support on nonnegative integers.
There are continuous random variables that also do not have scale parameters:  one example is the Beta distribution $$X \sim \operatorname{Beta}(a,b), \quad a > 0, b > 0$$ has the PDF $$f_X(x) = \frac{\Gamma(a + b)}{\Gamma(a)\Gamma(b)} x^{a-1} (1-x)^{b-1}, \quad 0 < x < 1.$$  $cX$ is not itself Beta for obvious reasons similar to the discrete support examples:  the support is no longer $(0,1)$.


text:
Q: ¿Cómo pasar un parametro/argumento multilinea a un ejecutable mediante un batch? Tengo el siguiente problema. Resulta que tengo un programa que necesita que se le pase ciertos parámetros/argumentos de esta forma.
programa.exe    parametro1="valor1"     parametro2="valor2"    parametro3="valor3"
El problema es que el valor de uno de estos parámetros es un texto que tiene varias líneas (muchas líneas) y no tengo ni idea de cómo hacer para setear este parámetro.
He pensado que lo más fácil sería tener el texto escrito en un archivo e intentar pasárselo haciendo algo así.
programa.exe parametro1 = < "archivo.txt"
Pero así no funciona.
¿Alguna idea de cómo poder hacer esto?

A: para  multilineas en CMD se usa el caracter ^
C:\>echo linea 1^
More? continua en ^
More? otra linea
linea 1continua en otra linea

C:\>

para usarlo en un .bat es lo mismo:
testmulti.bat
echo linea 1^
continua en ^
otra linea

C:\>testmulti.bat

C:\>echo linea 1continua en otra linea
linea 1continua en otra linea

Nota: tener en cuenta que tanto el ^ como el nueva línea se remueven al procesar, así que si esperas un espacio entre dos palabras hay que ponerlo delante del ^ como en la segunda línea.
Edit: para agregar saltos de línea usamos el truco de Ken
@echo off
REM Crear una variable para Newline (las dos líneas en blanco son requeridas)
set NLM=^

set NL=^^^%NLM%%NLM%^%NLM%%NLM%

echo linea 1^
continua en ^
otra linea separada%NL%por un salto de^
 linea y%NL%%NL%dos mas ^
algo asi deberia funcionar

C:\>testmulti.bat
linea 1continua en otra linea separada
por un salto de linea y

dos mas algo asi deberia funcionar

Más ejemplos y explicaciones de cómo funciona el ^ y el NL en:
https://stackoverflow.com/a/6379861/1423096
y en:
https://stackoverflow.com/a/4455750/1423096


text:
Q: Swift - Updating values of a multidimensional NSMutableDictionary In the Playground example below I'm trying to modify a multidimensional  NSMutableDictionary. Can someone please explain the correct way to modify a multidimensional mutable dictionary?
import Cocoa

let player = "Player 1"
let characterName = "Magic Glop"
let strength = 23
let defense = 220
let type = "fire"

var example: NSMutableDictionary = ["id":1,
               "player":player,
               "characters":
                    ["character-name":characterName,
                     "stats":
                        ["strength":strength,
                         "defense":defense,
                         "type":type
                        ]
                    ]
                ]

// My first attempt to update character-name.
example["characters"]!["character-name"] = "New Name"
// Error: Cannot assign to immutable expression of type 'AnyObject?!'

// Next I tried updating the value of "characters">"stats">"type" with .setObject
example["characters"]!["stats"]!!.setObject("water", forKey: "type")
// Documentation: .setObject adds a given key-value pair to the dictionary. If the key already exists in the dictionary, the object takes its place.
// Error: Execution was interrupted, reason: EXC_BAD INSTRUCTION (code=EXC_i386_INVOP, suncode=0x0).

Thanks in advance!

A: Class approach: You can update var to let for non-editable parameters.
class Player {
  let id: Int
  var name: String
  var characters = [Character]()

  init(id: Int, name: String) {
    self.id = id
    self.name = name
  }

  /**
  Add new char to Player
  */
  func addNewCharacter(new: Character) {
    self.characters.append(new)
  }
}

class Character {
  var name: String
  var strength: Int
  var defense: Int
  var type: String

  init(name: String, strength: Int, defense: Int, type: String) {
    self.name = name
    self.strength = strength
    self.defense = defense
    self.type = type
  }
}

func createPlayer() {
    let player1 = Player(id: 1, name: "Bodrum")

    // create new char and add to the player1 named Bodrum
    let char1 = Character(name: "Magic Glop", strength: 23, defense: 220, type: "fire")
    player1.addNewCharacter(char1)

    print("old name:\(player1.characters[0].name), old type:\(player1.characters[0].type)")

    // update char1's parameters
    player1.characters[0].name = "Yalikavak"
    player1.characters[0].type = "water"

    print("new name:\(player1.characters[0].name), new type:\(player1.characters[0].type)")
  }

// old name:Magic Glop, old type:fire
// new name:Yalikavak, new type:water

A: check this answer.
let player = "Player 1"
        let characterName = "Magic Glop"
        let strength = 23
        let defense = 220
        let type = "fire"

        var example: [String: AnyObject] = ["id":1,
            "player":player,
            "characters":
                ["character-name":characterName,
                    "stats":
                        ["strength":strength,
                            "defense":defense,
                            "type":type
                    ]
            ]
        ]

        print(example)

        var charDic = example["characters"] as! [String: AnyObject]
        charDic["character-name"] = "New Name" // change value for key character-name

        var statsDic = charDic["stats"] as! [String: AnyObject]
        statsDic["type"] = "water" // change the value for type

        charDic["stats"] = statsDic // assign updated dic for key stats

        example["characters"] = charDic // assign updated dic for key chacracters

        print(example)


text:
Q: PEP-8 for function calls I recently started working with Python/Django and I heard about the PEP 8 conventions. After having read PEP8 I had a better sense how to 'style' my code but I learned programming with Java and I used to just do whatever I like. Could you suggest how to put my example into PEP-8? much appreciated.
result = urllib.urlretrieve(
                            "https://secure.gravatar.com/avatar.php?"+
                            urllib.urlencode({
                                            'gravatar_id': hashlib.md5(email).hexdigest(),
                                            'size': srt(size)
                                            })
                            )

A: Try downloading code style linters such as pep8 (a program which checks your code to see if it matches PEP 8 requirements) or pylint. You can find a more comprehensive list and comparison of Python style checkers here: What are the comprehensive lint checkers for Python?
In fact, there's a pep8 checker available online: http://pep8online.com/
If we run your code through that, it tells you:
Code    Line  Column    Text
E126    2     29        continuation line over-indented for hanging indent
E225    2     70        missing whitespace around operator
E126    4     45        continuation line over-indented for hanging indent
E501    4     80        line too long (90 > 79 characters)
W292    7     30        no newline at end of file

The fixed version of your code would look more like this:
result = urllib.urlretrieve(
    "https://secure.gravatar.com/avatar.php?" +
    urllib.urlencode({
        'gravatar_id': hashlib.md5(email).hexdigest(),
        'size': srt(size)
    })
)

In essence, the main PEP 8 violation you had was that you were indenting too much. A single indent is fine -- you don't need to align to the opening paren of the function calls. Python is also insistent that your lines don't go beyond 80 characters, but fixing the over-indentation also fixed that issue.

A: Use more variables. Not only are lines easier to read, the complete code is easier to understand:
base = "https://secure.gravatar.com/avatar.php"
params = urllib.urlencode({'gravatar_id': hashlib.md5(email).hexdigest(),
                           'size': srt(size)})
url = "{}?{}".format(base, params)
result = urllib.urlretrieve(url)

A: This may not be suggested by PEP8, but for readability you could break it up like this:
base = "https://secure.gravatar.com/avatar.php?"
params = urllib.urlencode({'gravatar_id': hashlib.md5(email).hexdigest(),
                           'size': srt(size)})
result = urllib.urlretrieve(base+params)

Note that autopep8 is a utility for formatting Python code to conform with PEP8. In this case, it transforms your original code to
result = urllib.urlretrieve(
    "https://secure.gravatar.com/avatar.php?" +
    urllib.urlencode({
    'gravatar_id': hashlib.md5(email).hexdigest(),
    'size': srt(size)
    })
)


text:
Q: Touch event (onClickListener) not triggered for recyclerView In this i have added SetoNclicklistener for recyclerview itself but when i click the recycler view nothing gets triggered ..please help
Main Activity
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    recyclerView = (RecyclerView) findViewById(R.id.view);

    getOverflowMenu();

    android.support.v4.app.LoaderManager loaderManager = getSupportLoaderManager();
    android.support.v4.content.Loader<Cursor> loader=loaderManager.getLoader(loader_id);
    if(loader!=null) {
        loaderManager.initLoader(loader_id, null, this);
    }
    else
    {
        loaderManager.restartLoader(loader_id,null,this);
    }
 recyclerView.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         Toast.makeText(getApplicationContext(),"touched",Toast.LENGTH_SHORT).show();;
     }
 });

}

Recycler Adapter
`public class RecycleAdapter extends RecyclerView.Adapter {
private   int total_items=0;
private Context context;
private Cursor lcursor;

public RecycleAdapter(Context mcontext,Cursor cursor) {
    context=mcontext;
    lcursor=cursor;

}

@Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view= LayoutInflater.from(context).inflate(R.layout.item_view, parent, false);
    RecyclerViewHolder recyclerViewHolder=new RecyclerViewHolder((view));

    return recyclerViewHolder;

}

@Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
   if(!lcursor.moveToPosition(position)) {

       return;
   }
    String todo=(lcursor.getString(lcursor.getColumnIndex(DatabaseContract.Column.COLUMN_TODO_NAME)))+" "+
            (lcursor.getString(lcursor.getColumnIndex(DatabaseContract.Column.COLUMN_TODO)));
   String time=lcursor.getString(lcursor.getColumnIndex(DatabaseContract.Column.COLUMN_TODO_TIME));
    holder.item_desc.setText(todo);
    holder.item_date.setText(time);
    holder.itemView.setTag(lcursor.getColumnIndex(DatabaseContract.Column._ID));

}

@Override
public int getItemCount() {
    return lcursor.getCount();
}

public  class RecyclerViewHolder extends RecyclerView.ViewHolder
{

    private TextView item_desc,item_date;
    public RecyclerViewHolder(View itemView) {
        super(itemView);
        item_desc=(TextView)itemView.findViewById(R.id.item_desc);
        item_date=(TextView)itemView.findViewById(R.id.item_date);
    }

}

}

A: @Override
  public void onBindViewHolder(RecyclerViewHolder holder, int position) {
   if(!lcursor.moveToPosition(position)) {

    return;
 }
 String todo=(lcursor.getString(lcursor.getColumnIndex(DatabaseContract.Column.COLUMN_TODO_NAME)))+" "+
        (lcursor.getString(lcursor.getColumnIndex(DatabaseContract.Column.COLUMN_TODO)));
 String time=lcursor.getString(lcursor.getColumnIndex(DatabaseContract.Column.COLUMN_TODO_TIME));
holder.item_desc.setText(todo);
holder.item_date.setText(time);
    holder.itemView.setTag(lcursor.getColumnIndex(DatabaseContract.Column._ID));

holder.itemView.setOnClickListener(new View.OnClickListener() {
     @Override
    public void onClick(View v) {
       // here you can perform any operation on perticuler view
  }
}
}

you will get position of view

A: try this :
use a custom RecyclerItemClickListener to get the click event
recyclerView.addOnItemTouchListener(
            new RecyclerItemClickListener(getApplicationContext(), new RecyclerItemClickListener.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    // TODO Handle item click
                    Toast.makeText(getApplicationContext(), (position).toString(), Toast.LENGTH_LONG).show();
                   Toast.makeText(getApplicationContext(),"touched",Toast.LENGTH_SHORT).show();;

                }
            })
    );

Now define the class like:
 import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
    GestureDetector mGestureDetector;
    private OnItemClickListener mListener;

    public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
        mListener = listener;
        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
        View childView = view.findChildViewUnder(e.getX(), e.getY());
        if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
            mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
        }
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }

    public interface OnItemClickListener {
        public void onItemClick(View view, int position);
    }
}

For details see this link: http://sapandiwakar.in/recycler-view-item-click-handler/


text:
Q: What is the difference between Node* p and Node *p? In this line of code:
Node* insert(Node *head,int data)

What is the difference between Node* insert and Node *head?
Are they both pointers? And which is better?


text:
Q: Dispatch redux action in callback I have started working with redux in react-native and I encountered problem, when I am dispatching action in onLoadStart function for Image component, the callback is firing and I see that action is called and I see Loading... on screen, but when I am dispatching in onLoadEnd function nothing happen(callback loadEnd is not fired, app looks like frozen). When I use console.log in both places code is working fine. Could someone tell me what am I doing wrong?
 class DisplayImage extends Component {

    loadStart() {
      this.props.iLoadingFunction(true);
    }
    loadEnd() {  // <- this function is not fired
      this.props.iLoadingFunction(false);
    }

    render() {
        if (this.props.isLoading) {
            return <Text>Loading…</Text>;
        }
        return (
          <View>
              <Image
                source={{uri: 'https://test.com/image'}}
                onLoadStart={this.loadStart.bind(this)}
                onLoadEnd={this.loadEnd.bind(this)}
               />
          </View>
        );
    }
}

const mapStateToProps = (state) => {
    return {
        isLoading: state.isLoading
    };
};
const mapDispatchToProps = (dispatch) => {
    return bindActionCreators({ iLoadingFunction }, dispatch);
};

export default connect(mapStateToProps, mapDispatchToProps)(DisplayImage);

action and reducer
export function iLoadingFunction(bool) {
    return {
        type: 'IS_LOADING',
        isLoading: bool
    };
}

export function iLoadingFunction(state = false, action) {
    switch (action.type) {
        case 'IS_LOADING':
            return action.isLoading;
        default:
            return state;
    }
}

A: I think the issue is coming from the order that actions and renders are occurring in.  Let's look at the render function:
render() {
    if (this.props.isLoading) {
        return <Text>Loading…</Text>;
    }
    return (
      <View>
          <Image
            source={{uri: 'https://test.com/image'}}
            onLoadStart={this.loadStart.bind(this)}
            onLoadEnd={this.loadEnd.bind(this)}
           />
      </View>
    );
}

The first time the component mounts this.props.isLoading is false, so the component renders
<View>
    <Image
      source={{uri: 'https://test.com/image'}}
      onLoadStart={this.loadStart.bind(this)}
      onLoadEnd={this.loadEnd.bind(this)}
     />
</View>

The Image mounts, begins loading the image and dispatches this.props.iLoadingFunction(true).
At this point isLoading updates in the store are triggers a re-render of the component.  This time this.props.isLoading is true so the component renders
<Text>Loading…</Text>

Now the original Image has been removed from the hierarchy.  I'm not actually sure if it continues to download the image, but the onLoadEnd handler does not fire as the component expecting to handle it has been removed.
To get around this, I would leave the Image in the hierarchy and just include or exclude the Text based on this.props.isLoading, like so
render() {
    return (
      <View>
          { this.props.isLoading && <Text>Loading…</Text> }
          <Image
            source={{uri: 'https://test.com/image'}}
            onLoadStart={this.loadStart.bind(this)}
            onLoadEnd={this.loadEnd.bind(this)}
           />
      </View>
    );
}

A: The best solution to use callbackable-actions standardized actions.
I recommend using the redux-cool package to do that
npm install redux-cool

import {actionsCreator} from "redux-cool"
const callback = () => {
    console.log("Hello, I am callback!!!")
}
const callbackable_action = actionsCreator.CALLBACKABLE.EXAMPLE(1, 2, 3, callback)
console.log(callbackable_action)
//      {
//          type: "CALLBACKABLE/EXAMPLE",
//          args: [1, 2, 3],
//          cb: [[Function callback]],
//          _index: 1
//      }
callbackable_action.cb()
//      "Hello, I am callback!!!"

for more info, see: Redux Cool


text:
Q: compile C in CentOS face error: undefined reference to I compiled C in CentOS and face this error:

cc -c -o obj/BT.o BT.c -I./include -I/usr/dialogic/inc
cc -o BT obj/BT.o obj/util.o -I./include -I/usr/dialogic/inc -L/usr /dialogic/lib
obj/BT.o: In function 'main':
BT.c:(.text+0x52): undefined reference to `gc_Start'
collect2: ld returned 1 exit status
make: *** [BT] Error 1

I already linked to library  -L/usr /dialogic/lib but i don't know why it does not link when create binary file
Please, any one can suggest me something ?

A: check if you had saved your.c file and also check of spelling of the functions' definition and their calls .


text:
Q: In Angular, how can I run a small script on each component that gets loaded? (diagnostic purposes) I want to run certain diagnostic lines of Javascript as I develop that will console log the alt attribute on all <img> tags in the HTML, for instance.  This is purely for testing and will not go to production of course.  On a single component I would normally run this within the ngAfterContentInit() and/or ngOnChanges() lifecycle hooks, so it would run this script whenever the images in the HTML have been loaded and rendered.
The JS would just be something simple like getElementsByTagName('img')[0].getAttribute('alt'), but how can I run this each time a component is displayed, so I can check these kinds of things without adding an import to each individual component?  Is there something I can do in the AppModule for instance that controls the components that are loaded?  I would like to run these kinds of scripts on dynamically/lazily loaded components too, if that is possible.

A: You can use a custom directive for this purpose, Define global img selector in custom directive. Then use ElementRef class to access image alt attributes value.
import { Directive, ElementRef, isDevMode, OnInit } from '@angular/core';
@Directive({
  selector: 'img',
})
export class ImgDirective implements OnInit {
  constructor(private element: ElementRef) {}

  ngOnInit() {
    if (isDevMode) {
      console.log(this.element.nativeElement.getAttribute('alt'));
    }
  }
}

Working Example


text:
Q: Are groovy variables null-initialized, or is this an IntelliJ bug? IntelliJ highlights the 'foo' variable in gray, and says "assignment is not used". What I want to know is - it is right or not...
If this were java and not groovy, I know it wouldn't be right.
public class Foo
{
  public Foo()
  {
    Foo foo = null; // this 'foo' instance is gray ("assignment not used")
    try
    {
      foo = new Foo()
      // ...
    }
    finally
    {
      if (foo != null)
        foo.release();
    }

  }

  public void release(){}
}

A: Groovy (and Java) local variables must be explicitly initialized before use. Java Language Specification: Initial Values of Variables.

A local variable (§14.4, §14.14) must be explicitly given a value
  before it is used, by either initialization (§14.4) or assignment
  (§15.26), in a way that can be verified using the rules for definite
  assignment (§16 (Definite Assignment)).

A: It is a bug. I've created an issue http://youtrack.jetbrains.net/issue/IDEA-81188


text:
Q: Calculating the trace of a 3x3 matrix over the rationals when its determinant is 0
I encountered a problem where I had a $3\times 3$ matrix $A$ with rational numbers entries and it was given that $A^3=2A$ and $A$ could not be the zero matix. I was asked to calculate the trace of the square of $A$, namely $tr(A^2)$.

I could find that the determinant $\det(A)=0$ because otherwise it had to be $\sqrt8$ or $-\sqrt8$. This comes from $\det(A)^3=8\det(A)$. Since $\sqrt8$ is not rational the determinant has to be $0$. Is there a way to express $tr(A^2)$ in terms of $\det(A)$?

A:
If $A^3=2A$, then its characteristic polynomial is $x^3-2x$.

Indeed, $x^3-2x=x(x^2-2)$ is a decomposition into irreducibles in $\mathbb Q[x]$. Now, the minimal polynomial of $A$ cannot be $x$ because $A\ne0$ or $x^2-2$ because then $\det(A)^2=8$, which cannot happen over $\mathbb Q$. Therefore, the minimal polynomial is $x^3-2x$ and so coincides with the characteristic polynomial.

The characteristic polynomial of a $3\times3$ matrix $A$ is
$$
x^3 - tr(A) x^2 + \frac{tr(A)^2 - tr(A^2)}{2}x - \det(A)
$$

See characteristic polynomial in terms of trace and determinant for 4x4 matrices.
Comparing coefficients, we get
$tr(A)=0$ and so $tr(A^2)=4$.

A: Experiment with
$$
A = \left(
\begin{array}{rrr}
0 & 1 & 0 \\
2 & 0 & 0 \\
0 & 0 & 0 \\
\end{array}
\right)
$$
For example, find $A^3$ and compare that with $2A$
Also find $A^2$    and its trace


text:
Q: PL/SQL Developer displays does not display Hebrew characters properly
Hi all,
I've uploaded a photo of the way I see dates in PL/SQL Developer, I see question marks instead of the full date (need to look like "02-Aug-2013 13:50:21.663" for instance, as seen on other computers)...
If someone have any idea what on my preferences makes it look like this - I'd love to know...
Thanks!
UPDATE:
NLS Parameters:

NLS DB Parameters:

A: The issue seems to be due to mismatch between NLS parameters in client and database. For such questions, always remember to post the OS details, DB version up to 4 decimals.
To check the the parameter values:
SELECT * FROM v$nls_parameters;
SELECT * FROM nls_database_parameters;

*

*Set the NLS_DATE_LANGUAGE in client exactly same as that of Database. In your case, NLS_DATE_LANGUAGE in database is AMERICAN.

*Set the environment variable for NLS_LANG as :
[NLS_LANGUAGE]_[NLS_TERRITORY].[NLS_CHARACTERSET]
so, set it as AMERICAN_AMERICA.WE8MSWIN1252

*Another observation is that, your other NLS parameters also needs to be changed in client to match with that of Database. Else, you will find similar issues every now and then, just not with DATE.

A: I would like to leave here a solution that has nothing to do with the national language settings, and, as the post that lead me to this itself states, 9 out of 10 cases of problems like yours (I was having just the same) - are fixed following this solution, instead.
I have been messing with the NLS for a while to no avail. I then just ended up in this post and this was what solved my problem.
In a short, if the font chosen to display SQL results is one that does not support the language you are trying to display in, then it will not work. In my case, needing to display Hebrew, I was able to do so simply by picking Tahoma as the display font, as suggested, again, by the post aforementioned.
Here is a screenshot showing the procedure:
Preferences -> User Interface -> Fonts -> Grid -> Select

A: You may try changing 'Date Format', 'Timestamp Format', 'Timestamp TZ Format'
to "DD-MON-YYYY HH24:MI:SS" (minus quotes) or in the format you want.
Access the preferences from Tools->Preferences->Database->NLS


text:
Q: How can I get a single category of question in a quiz app using Laravel Eloquent I want to select a single category of questions that the user can select with options. I have tried doing this with a resource I found online.
The category page:
@foreach($categories as $category)

{{$category->name}}

id}}" class="button">Learn more

        @endforeach

Here is the TestController I'm using, the show controller is might to select questions and options with the category_id at random:
namespace App\Http\Controllers;

use App\Category;
use App\Http\Requests\StoreTestRequest;
use App\Option;

class TestsController extends Controller
{
    public function show($id)
    {
        $categories = Category::find($id)->with(
            ['categoryQuestions' => function ($query) {
                $query->inRandomOrder()
                    ->with(
                        ['questionOptions' => function ($query) {
                            $query->inRandomOrder();
                        }]
                    );
            }]
        )
            ->whereHas('categoryQuestions')
            ->get();

        return view('client.test', compact('categories'));
    }

    public function store(StoreTestRequest $request)
    {
        $options = Option::find(array_values($request->input('questions')));

        $result = auth()->user()->userResults()->create(
            [
            'total_points' => $options->sum('points')
            ]
        );

        $questions = $options->mapWithKeys(
            function ($option) {
                return [$option->question_id => [
                        'option_id' => $option->id,
                        'points' => $option->points
                    ]
                ];
            }
        )->toArray();

        $result->questions()->sync($questions);

        return redirect()->route('client.results.show', $result->id);
    }
}

web.php
// User
Route::group(['as' => 'client.', 'middleware' => ['auth']], function () {
    Route::get('home', 'HomeController@redirect');
    Route::get('dashboard', 'HomeController@index')->name('home');
    Route::resource('/test', 'TestsController');
    Route::get('results/{result_id}', 'ResultsController@show')->name('results.show');
    Route::get('send/{result_id}', 'ResultsController@send')->name('results.send');
});

This is the Blade file from the resource I'm using:
@extends('layouts.home')

@section('content')

Test

                    @if(session('status'))

                                    {{ session('status') }}

                    @endif

                    <form method="POST" action="{{ route('client.test.store') }}">
                        @csrf
                        @foreach($categories as $category)

{{ $category->name }}

                                    @foreach($category->categoryQuestions as $question)

last)mb-3 @endif">

{{ $question->question_text }}

                                                <input type="hidden" name="questions[{{ $question->id }}]" value="">
                                                @foreach($question->questionOptions as $option)

                                                        <input class="form-check-input" type="radio" name="questions[{{ $question->id }}]" id="option-{{ $option->id }}" value="{{ $option->id }}"@if(old("questions.$question->id") == $option->id) checked @endif>
                                                        id }}">
                                                            {{ $option->option_text }}

                                                @endforeach

                                                @if($errors->has("questions.$question->id"))

                                                        {{ $errors->first("questions.$question->id") }}

                                                @endif

                                    @endforeach

                        @endforeach

                                <button type="submit" class="btn btn-primary">
                                    Submit
                                </button>

                    </form>

@endsection

How can the Testcontroller be made to select questions and answer from a single category and save the result from the user's answers?

A: public function index()
    {
        $questions = Category::select('categories.name', 'question_result.points')
            ->join('questions', 'categories.id', '=', 'questions.category_id')
            ->join('question_result', 'questions.id', '=', 'question_result.question_id')
            ->join('results', 'question_result.result_id', '=', 'results.id')
            ->where('results.user_id', auth()->id())
            ->get();

        return view('client.home', compact('questions'));
    }


text:
Q: Do sth specific if an optional parameter (TRUE) is passed in the function call I'm coding a function for freecodecamp and I can't quite figure out how to pass a second optional argument (in this case it has to be True) and print something different depending if the optional arg is present or not.
instructions are : Create a function that receives a list of strings that are arithmetic problems and returns the problems arranged vertically and side-by-side. The function should optionally take a second argument. When the second argument is set to True, the answers should be displayed.
PS: I don't want to cheat, just can't figure out the 2nd arg part
I tried using
def arithmetic_arranger(problems, *args):
but I don't know how to use the conditional to indicate the function to show the result if 2nd arg is True
code so far is [https://github.com/Tarufetti/practica-public-/blob/f4a5e09c7f755d50b588575c6199188470408da9/arithmetic_formatter(NEWedit)]

A: I think you need something like that:
def arithmetic_arranger(problems, bool_var=False):
    if bool_var:
       #do something if an optional True argument is passed


text:
Q: Symfony doesnt auto increment id I have a database called cardb which is populated by a SQL file which made some cars. They have ID's starting from 1 up to 30. When I try to create new Car it works the first time and creates a car with id 0 then when it tries to do it again it again tries to make an entry with 0.
Here is the error

An exception occurred while executing 'INSERT INTO cars (Make, Model, TravelledDistance) VALUES (?, ?, ?)' with params ["fock", "fock", 320]:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0' for key 'PRIMARY'

Here is my entity
    /**
 * Cars
 *
 * @ORM\Table(name="cars")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\CarsRepository")
 */
class Cars
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="Make", type="string", length=255)
     */
    private $make;

    /**
     * @var string
     *
     * @ORM\Column(name="Model", type="string", length=255)
     */
    private $model;

    /**
     * @var int
     *
     * @ORM\Column(name="TravelledDistance", type="bigint")
     */
    private $travelledDistance;

    /**
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Parts", inversedBy="cars")
     * @ORM\JoinTable(
     *  name="PartCars",
     *  joinColumns={
     *      @ORM\JoinColumn(name="Part_Id", referencedColumnName="id")
     *  },
     *  inverseJoinColumns={
     *      @ORM\JoinColumn(name="Car_Id", referencedColumnName="id")
     *  })
     */
    private $parts;
    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set make
     *
     * @param string $make
     *
     * @return Cars
     */
    public function setMake($make)
    {
        $this->make = $make;

        return $this;
    }

    /**
     * Get make
     *
     * @return string
     */
    public function getMake()
    {
        return $this->make;
    }

    /**
     * Set model
     *
     * @param string $model
     *
     * @return Cars
     */
    public function setModel($model)
    {
        $this->model = $model;

        return $this;
    }

    /**
     * Get model
     *
     * @return string
     */
    public function getModel()
    {
        return $this->model;
    }

    /**
     * Set travelledDistance
     *
     * @param integer $travelledDistance
     *
     * @return Cars
     */
    public function setTravelledDistance($travelledDistance)
    {
        $this->travelledDistance = $travelledDistance;

        return $this;
    }

    /**
     * Get travelledDistance
     *
     * @return int
     */
    public function getTravelledDistance()
    {
        return $this->travelledDistance;
    }

    /**
     * @return mixed
     */
    public function getParts()
    {
        return $this->parts;
    }

}

It is auto generated Entity which has auto increment annotation.
What could be the problem?

A: The annotation
 * @ORM\GeneratedValue(strategy="AUTO")

won't make PHP create a unique ID. You can see from the insert statement that PHP doesn't provide an ID value at all.
That annotation tells the ORM what kind of column it is, but it depends on the database to generate the value. You can check the documentation for more details.
Based on the way your code looks, it appears you used the console to generate the entity, but I assume the fact that the database isn't doing the id properly means that you created the cars table by hand rather than using doctrine:schema:update, which is fine if that's the way you need/want to do it, but you'll have to alter your table to make the id column an autoincrement.


text:
Q: Varchar or int for many records? For a site like Facebook, does it use int or varchar? For example, for the number of posts on Facebook, there are billions or trillions. So do you use int for each post id or do you use varchar? The max for int is  2,147,483,647 so I'm confused. Please help, thanks.

A: there's also a BIGINT.
The signed range is -9223372036854775808 to 9223372036854775807.
The unsigned range is 0 to 18446744073709551615.
That's more than enough :)

A: As @Sammitch mentioned, UUID can generate a long value that has a much larger range than a 32-bit int. UUID generates a 128-bit value.
Also consider that a primary key can be a compound primary key, so you can expand the number of possibilities greatly.
You asked about user id. I did consulting for a site that ran out of values for their signed 32-bit INT user id. The reason was that because of a bug, they were skipping 1000 or more values for each new user that was created. So they ran out of values much faster than if they had been incrementing user ids 1 at a time.
I helped them upgrade their userid to BIGINT. We had to do this in the user table and in about 30 other tables that referenced the user table (because it would do no good to allow larger values for userid when the other tables are still using INT and can't reference the larger values).
See also my answer to Integer overflow what will be next.


text:
Q: How to start a remote kernel on a machine with two ip addresses? Suppose I have a local machine with ip address 204.XX.40.10 and a remote machine.
And the remote machine has two network card, so it has two ip addresses: 204.XX.40.21 and 192.0.2.100, and only the 204.XX.40.21 one can be reached from outside.
I tried the guide in the documentation but I can't get the remote kernel working.
It turns out that the main link is successfully connected but the other links are listening at the private ip address 192.0.2.100 on the remote machine. Here are information I get after login to the remote machine.
[user@remote ~]$ lsof -i 4 -a
COMMAND     PID USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME
MathKerne 71149 user   16u  IPv4 4045791      0t0  TCP remote:43021->204.XX.40.10:54201 (ESTABLISHED)
MathKerne 71149 user   17u  IPv4 4045790      0t0  TCP remote:34952->204.XX.40.10:54200 (ESTABLISHED)
MathKerne 71149 user   20u  IPv4 4045795      0t0  TCP 192.0.2.100:55230 (LISTEN)
MathKerne 71149 user   21u  IPv4 4045797      0t0  TCP 192.0.2.100:49758 (LISTEN)
MathKerne 71149 user   22u  IPv4 4045800      0t0  TCP 192.0.2.100:59492 (LISTEN)
MathKerne 71149 user   23u  IPv4 4045802      0t0  TCP 192.0.2.100:48302 (LISTEN)

So is it possible to let the other two links using the public ip address?


text:
Q: svn: revision file lacks trailing newline I wanted to commit a change in a file that is under subversion control:
svn ci some-file -m "some-comment"

but I receive a
svn: Commit failed (details follow):
svn: Revision file lacks trailing newline

from a quick search on the internet, I was unable to find an authorative answer how to proceed in such a case. So, if somebody here is knowledgable, I'd be very grateful.
Edit/Update: The version is:
c:\>svn --version
svn, version 1.6.5 (r38866)
   compiled Sep  1 2009, 13:23:06

and
c:\>svnadmin, version 1.6.5 (r38866)
   compiled Sep  1 2009, 13:23:06

Copyright (C) 2000-2009 CollabNet.
Subversion is open source software, see http://subversion.tigris.org/
This product includes software developed by CollabNet (http://www.Collab.Net/).

The following repository back-end (FS) modules are available:

* fs_fs : Module for working with a plain file (FSFS) repository.

A: This is a repository message. What version of Subversion are you using. This is a very old error that has been fixed long ago.
It took me a while, but I found the fix.
This is a problem in the repository itself and not the client.


text:
Q: Xcode Server Integration Error I have enabled Xcode server in Xcode 9. I am able to create a BOT but when I am trying to integrate, getting below error
Assertion: Creating archive failed: xcodebuild exited with status 65.

I have added distribution certificate & provisioning profile but still facing the same issue.
I have followed below links but no success
Link1
Link2
Link3
Please help how to resolve this issue. Any idea or suggestion would be great.


text:
Q: Uncaught ReferenceError: require is not defined - Target to es6 i am getting the Uncaught ReferenceError: require is not defined in jasmine unit test with karma.
this my karma.conf.js file.
tsconfig.json - target "target": "es6"
module.exports = function (config) {
  config.set({
    basePath: './',
    frameworks: ['jasmine'],
    files: [
      'node_modules/reflect-metadata/Reflect.js',
      'node_modules/systemjs/dist/system-polyfills.js',
      'node_modules/systemjs/dist/system.src.js',
      { pattern: 'node_modules/rxjs/**/*.js', included: false, watched: false },
      { pattern: 'node_modules/rxjs/**/*.js.map', included: false, watched: false },
      { pattern: 'dist/dev/**/*.js', included: false, watched: true },
      { pattern: 'node_modules/systemjs/dist/system-polyfills.js', included: false, watched: false }, // PhantomJS2 (and possibly others) might require it
      'dist/**/*.spec.js',
    ],
    proxies: { },
    exclude: [    ],
    preprocessors: {
      'dist/**/!(*spec).js': ['coverage']
    },
    reporters: ['mocha', 'coverage'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: [
      'PhantomJS',
      'Chrome'
    ],
    singleRun: false,
    client: {    }
  });
};

A: Recommend compiling your code with additionally --module commonjs and using a karma plugin that understands commonjs i.e. https://github.com/karma-runner/karma-commonjs


text:
Q: Java jLabel on top of another listener I want to read if one jLabel is on top of another. I drag jLabel1 on top of jLabel2 and drop it there and do something if it is on top. Code:
package javaapplication5;

import java.awt.Component;
import java.awt.Point;

public class NewJFrame extends javax.swing.JFrame {
    boolean OptionsDrag = false, OptionsDrop = false;
    private Point initialLoc;
    private Point initialLocOnScreen;
    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        initComponents();
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMaximumSize(new java.awt.Dimension(400, 300));
        setMinimumSize(new java.awt.Dimension(400, 300));
        getContentPane().setLayout(null);

        jLabel1.setBackground(new java.awt.Color(0, 0, 255));
        jLabel1.setOpaque(true);
        jLabel1.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mousePressed(java.awt.event.MouseEvent evt) {
            jLabel1MousePressed(evt);
        }
        public void mouseReleased(java.awt.event.MouseEvent evt) {
            jLabel1MouseReleased(evt);
        }
    });
    jLabel1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
        public void mouseDragged(java.awt.event.MouseEvent evt) {
            jLabel1MouseDragged(evt);
        }
    });
    getContentPane().add(jLabel1);
    jLabel1.setBounds(90, 130, 48, 48);

    jLabel2.setBackground(new java.awt.Color(0, 255, 255));
    jLabel2.setOpaque(true);
    jLabel2.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseEntered(java.awt.event.MouseEvent evt) {
            jLabel2MouseEntered(evt);
        }
    });
    getContentPane().add(jLabel2);
    jLabel2.setBounds(230, 80, 48, 48);

    jLabel3.setText("showed");
    jLabel3.setVisible(false);
    getContentPane().add(jLabel3);
    jLabel3.setBounds(40, 30, 37, 20);

    pack();
}// </editor-fold>

private void jLabel1MousePressed(java.awt.event.MouseEvent evt) {
    Component comp = (Component)evt.getSource();
    initialLoc = comp.getLocation();
    initialLocOnScreen = evt.getLocationOnScreen();
}

private void jLabel1MouseReleased(java.awt.event.MouseEvent evt) {
    Component comp = (Component)evt.getSource();
    Point locOnScreen = evt.getLocationOnScreen();

    int x = locOnScreen.x - initialLocOnScreen.x + initialLoc.x;
    int y = locOnScreen.y - initialLocOnScreen.y + initialLoc.y;
    comp.setLocation(x, y);
    OptionsDrop = true;
}

private void jLabel1MouseDragged(java.awt.event.MouseEvent evt) {
    Component comp = (Component)evt.getSource();
    Point locOnScreen = evt.getLocationOnScreen();

    int x = locOnScreen.x - initialLocOnScreen.x + initialLoc.x;
    int y = locOnScreen.y - initialLocOnScreen.y + initialLoc.y;
    comp.setLocation(x, y);
    OptionsDrag = true;
}

private void jLabel2MouseEntered(java.awt.event.MouseEvent evt) {
    if(OptionsDrag == true && OptionsDrop == true){
        jLabel3.setVisible(true);
    }
}

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {

    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            new NewJFrame().setVisible(true);
        }
    });
}
    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    // End of variables declaration
}

I can move jLabel1 but when it's dropped on other label named Preview_1 it does nothing.
I saw that when i drag and drop it's fine but it works only when i enter with the mouse on cyan block. Is it possible to do it when blue box goes on top of cyan instead mouse?

A: *

*I would first off rename variables so that they make the code self commenting. Yes this is a simple example program, but this little change can make all the difference.

For instance:
private javax.swing.JLabel mobileLabel;
private javax.swing.JLabel fixedLabel;
private javax.swing.JLabel notificationLabel;

*

*I would not add a MouseListener to the fixedLabel since you don't really care if the mouse is over it, but rather if the dragged component is.

*Rather the intersection test should be in the mobileLabel's MouseListener.

*One way to test for intersection is to extract the Rectangles of the two components (or use a for loop if you must loop through several components, extracting Rectangles as you go), and then testing if one Rectangle intersects another.

*I'm not sure if you want to center the mobileLabel on the fixedLabel if there is overlap. If so, you can get the position of the fixed one and use that to set the position of the mobile one.

*Another possible solution is to use Java's drag and drop functionality.

For example:
import java.awt.Color;
import java.awt.Component;
import java.awt.Point;
import java.awt.Rectangle;

@SuppressWarnings("serial")
public class NewJFrame2 extends javax.swing.JFrame {
   private static final String OVERLAID = "Overlaid!";
   boolean OptionsDrag = false, OptionsDrop = false;
   private Point initialLoc;
   private Point initialLocOnScreen;

   public NewJFrame2() {
      initComponents();
   }

   private void initComponents() {
      mobileLabel = new javax.swing.JLabel("Mobile");
      mobileLabel.setForeground(Color.white);
      fixedLabel = new javax.swing.JLabel("Fixed");
      notificationLabel = new javax.swing.JLabel();

      setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
      setMaximumSize(new java.awt.Dimension(400, 300));
      setMinimumSize(new java.awt.Dimension(400, 300));
      getContentPane().setLayout(null);

      mobileLabel.setBackground(new java.awt.Color(0, 0, 255));
      mobileLabel.setOpaque(true);
      mobileLabel.addMouseListener(new java.awt.event.MouseAdapter() {
         public void mousePressed(java.awt.event.MouseEvent evt) {
            jLabel1MousePressed(evt);
         }

         public void mouseReleased(java.awt.event.MouseEvent evt) {
            jLabel1MouseReleased(evt);
         }
      });
      mobileLabel.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
         public void mouseDragged(java.awt.event.MouseEvent evt) {
            jLabel1MouseDragged(evt);
         }
      });
      getContentPane().add(mobileLabel);
      mobileLabel.setBounds(90, 130, 48, 48);

      fixedLabel.setBackground(new java.awt.Color(0, 255, 255));
      fixedLabel.setOpaque(true);
// !!     fixedLabel.addMouseListener(new java.awt.event.MouseAdapter() {
//         public void mouseEntered(java.awt.event.MouseEvent evt) {
//            jLabel2MouseEntered(evt);
//         }
//      });
      getContentPane().add(fixedLabel);
      fixedLabel.setBounds(230, 80, 48, 48);

      //!! notificationLabel.setText("showed");
      // !! notificationLabel.setVisible(false);
      getContentPane().add(notificationLabel);
      // notificationLabel.setBounds(40, 30, 37, 20); //!!
      notificationLabel.setLocation(40, 30);  //!!
      notificationLabel.setSize(notificationLabel.getPreferredSize()); //!!

      pack();
   }

   private void jLabel1MousePressed(java.awt.event.MouseEvent evt) {
      Component comp = (Component) evt.getSource();
      initialLoc = comp.getLocation();
      initialLocOnScreen = evt.getLocationOnScreen();
   }

   private void jLabel1MouseReleased(java.awt.event.MouseEvent evt) {
      Component comp = (Component) evt.getSource();
      Point locOnScreen = evt.getLocationOnScreen();

      int x = locOnScreen.x - initialLocOnScreen.x + initialLoc.x;
      int y = locOnScreen.y - initialLocOnScreen.y + initialLoc.y;
      comp.setLocation(x, y);
      OptionsDrop = true;

      if (compIntersectsFixed(comp)) {

         // if you want to place the mobileLabel directly on top
         // of the fixedLabel
         comp.setLocation(fixedLabel.getLocation());
         repaint();
         notificationLabel.setText(OVERLAID);
         notificationLabel.setSize(notificationLabel.getPreferredSize());
      } else {
         notificationLabel.setText("");
      }
      revalidate();
      repaint();
   }

   private boolean compIntersectsFixed(Component comp) {
      Rectangle compRect = comp.getBounds();
      Rectangle fixedRect = fixedLabel.getBounds();
      if (compRect.intersects(fixedRect)) {
         return true;
      }
      return false;
   }

   private void jLabel1MouseDragged(java.awt.event.MouseEvent evt) {
      Component comp = (Component) evt.getSource();
      Point locOnScreen = evt.getLocationOnScreen();

      int x = locOnScreen.x - initialLocOnScreen.x + initialLoc.x;
      int y = locOnScreen.y - initialLocOnScreen.y + initialLoc.y;
      comp.setLocation(x, y);
      OptionsDrag = true;
   }

// !!  private void jLabel2MouseEntered(java.awt.event.MouseEvent evt) {
//      if (OptionsDrag == true && OptionsDrop == true) {
//         notificationLabel.setVisible(true);
//      }
//   }

   public static void main(String args[]) {

      try {
         for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
               .getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
               javax.swing.UIManager.setLookAndFeel(info.getClassName());
               break;
            }
         }
      } catch (ClassNotFoundException ex) {
         java.util.logging.Logger.getLogger(NewJFrame2.class.getName()).log(
               java.util.logging.Level.SEVERE, null, ex);
      } catch (InstantiationException ex) {
         java.util.logging.Logger.getLogger(NewJFrame2.class.getName()).log(
               java.util.logging.Level.SEVERE, null, ex);
      } catch (IllegalAccessException ex) {
         java.util.logging.Logger.getLogger(NewJFrame2.class.getName()).log(
               java.util.logging.Level.SEVERE, null, ex);
      } catch (javax.swing.UnsupportedLookAndFeelException ex) {
         java.util.logging.Logger.getLogger(NewJFrame2.class.getName()).log(
               java.util.logging.Level.SEVERE, null, ex);
      }

      java.awt.EventQueue.invokeLater(new Runnable() {
         @Override
         public void run() {
            new NewJFrame2().setVisible(true);
         }
      });
   }

   // !! name changes
   private javax.swing.JLabel mobileLabel;
   private javax.swing.JLabel fixedLabel;
   private javax.swing.JLabel notificationLabel;
}


text:
Q: Enable FDF Support for PHP Version 5.6.24 How to Enable FDF Support for PHP Version 5.6.24?
I have a Version before that is PHP Version 5.2.17.
Which has the FDF Support working.
fdf
FDF Support:  enabled
FdfTk Version:    5.0
But when I upgrade the version to PHP Version 5.6.24. It is not working.
I have all the files in the Place.

*

*In PHP.ini, I added the line. extension=php_fdf.dll

*in PHP/ext folder I have the file in place php_fdf.dll

*in PHP/ folder I have the file in place fdftk.dll
I have Windows server 2008 r2 and IIS 7.
I have restart the server and IIS many time, but still the fdf support is not enabled.
But still it not come in the phpinfo page.
Please guide me , what I have to do, to make it work.

A: The extensions are compiled for every PHP version. So of you have 5.2 before you can't run the same DLLs with PHP 5.5. Then you need newer DLLs for the right version in you case PHP 5.5.
I hope you get a newer version otherwise you have to look for a new solution.

A: Everything you can do with FDF you can also do with XFDF, the XML flavor of FDF. Because it's XML, you won't need a special library to work with it and can use the most current version of PHP.
You can read the XFDF Specification here...
https://partners.adobe.com/public/developer/en/xml/XFDF_Spec_3.0.pdf


text:
Q: Adding two corresponding array elements and return the resultant array Facing segmentation fault in the following code . Can anyone help me fix it?
#include<stdio.h>

int* multiply(int *arr1, int *arr2, int m);

int main(void){
    int m = 0;

    printf("Enter size of array1 and array2 >");
    scanf("%d",&m);

    int arr1[m],  arr2[m];
        printf("First array>");

    for(int i = 0; i < m; ++i){
        scanf("%d", &arr1[i]);
    }
    printf("Second array> ");
    for(int j = 0; j < m; j++)
       scanf("%d", &arr2[j]);

    int* result = multiply(arr1, arr2, m);

    for(int i = 0; i < m; ++i){
        printf("%d ", result[i]);
    }

}

int* multiply(int *arr1, int *arr2, int m){
    int res[m];
    printf("ok");
    for(int i = 0; i < m; ++i){
        res[i] = arr1[i] + arr2[i];
    }
    printf("ok");
    return res;
}

Output should show like
Enter size of array1 and array2 >3
First array>5 1 7
Second array> 2 4 2
The resultant > 7 5 9
My output
Enter size of array1 and array2 >3
First array>5 1 7
Second array> 2 4 2
Segmentation fault

A: The program has undefined behavior because the function multiply returns a pointer to the local array res that will not be alive after exiting the function. So after exiting the function the returned pointer will be invalid.
int* multiply(int *arr1, int *arr2, int m){
    int res[m];
    printf("ok");
    for(int i = 0; i < m; ++i){
        res[i] = arr1[i] + arr2[i];
    }
    printf("ok");
    return res;
}

You need to allocate memory dynamically for the array.
Also the parameters that denote arrays should have qualifier const because passed arrays are not changed within the function.
The function can be declared and defined the following way.
int * multiply( const int *arr1, const int *arr2, size_t n )
{
    int *res = NULL;

    if ( n != 0 && ( res = malloc( n * sizeof( int ) ) ) != NULL )
    {
        for( size_t i = 0; i < n; ++i )
        {
            res[i] = arr1[i] + arr2[i];
        }
    }

    return res;
}

In main you should write
int* result = multiply(arr1, arr2, m);

if ( result != NULL )
{
    for(int i = 0; i < m; ++i){
        printf("%d ", result[i]);
    }
}

free( result );

A: In the multiply function, pass m as a constant integer, because the size of array number is always a constant.
int* multiply(int *arr1, int *arr2, const int m){
    int res[m];
    printf("ok");
    for(int i = 0; i < m; ++i){
        res[i] = arr1[i] + arr2[i];
    }
    printf("ok");
    return res;
}

Do not forget to change the declaration of the function on line 3.

A: The return varible of your function is local so it does not exist outside of the function scope, what I mean once you return a stack allocated variable from a function it scopes ends right then and there (unless that variable is defined as static), it is erased from the memory.
There are three fixes for it:

*

*make your return value variable static (this will preserve its value even when function's scope end);

*make your function void and instead pass the return value as a parameter to your function.

*use global variables for storing your result (highly discouraged though, but in your case it wont be a bad practice).


text:
Q: MVC versus WebForms It seems to me like there's a lot of sheeping going on, with everyone jumping on the MVC bandwagon.
Almost everyone is declaring WebForms as evil and satan without much persuasion. Then they go on to say that Controls are evil and they shouldn't be in a Web app. How are you going to show anything without any controls?
I remember when WebForms first came out and everybody loved them. I guess in a few years, people will sheep on to the next thing and declare MVC evil because you had to actually create controls to use MVC and they'll say you have to develop an application and not worry about the controls.
The way I see it MVC can be achieved in WebForms by not including the RunAt in the Form tag.
Then if you want to retrieve data, just use Ajax.
Can someone persuade me on why I should use MVC and not WebForms?

A: In Webforms:

Both Viewstate and Postbacks have been made lot of problems and increased complexity of the web application development. Many web pages having hundreds of KB size of Viewstate that affected the performance of the applications sometime.
Developers do not have the control of the rendering HTML of web forms and Server controls that render html with mixed inline style and deprecated tags that does not follows standards.
The page life cycle of the Web Form is too complex and has the tightly coupling between all things in the ASP.net framework and a single class is used both to display output and handles user input.
Unit testing is almost an impossible task. Today unit testing is very important in modern software development especially when we following agile methodologies and practices. Since web is a stateless thing, Events, Postbacks and Viewstate are not a good way.

With asp.net MVC all these things are simplified
If these things don't apply to you and you enjoy using Webforms then stick with what you do best. Don't try to fix something thats not broken.
For more detail refer to : Shiju's blog of ASP.net MVC Vs ASP.net Web Form

A: I see the key advantages of MVC as:

*

*Much cleaner and simpler architecture.  No more guessing which event you have handle to hook up your data correctly.  No more having to insert a hook to "fix" a data binding problem because the framework doesn't do exactly what you want.

*The framework doesn't get your way as much.

*Decoupled architecture makes much more of the code more easily tested.

*More closely aligned with the architecture of the web.  For people coming from a WebForms background this may not seem to be an advantage until you embrace it and design for it instead of trying to write WebForms-like applications in MVC.  Fortunately, I had explored Ruby on Rails some before using ASP.NET MVC and had already started to write my WebForms apps in a more RESTful way.

*History/Ubiquity -- despite the fact that Microsoft is just rolling it out, MVC is a well-known and highly respected pattern.  It's widely used for lots of web applications in many frameworks.   Learning MVC will give you a leg up if you need to switch to a different technology where they are also doing MVC -- say RoR or Java/Struts.

The disadvantages:

*

*Microsoft's implementation is new and not as mature.

*Few third-party "controls"/plugins for round-trip use -- generic grids and such, though there are lots of plugins on the client-side via jQuery.

*Requires unlearning some paradigms from WebForms to effectively use it.

*The framework doesn't do as much heavy lifting for you; you'll have to learn some Javascript and write more client-side code because the framework won't inject it for you.

A: WebForms is a great framework, but it does requires for you to dig in and understand it. And yes, you should still be an expert in HTML and JavaScript. Every complaint that I ever hear about WebForms comes from someone who didn't take time to understand WebForms. Here are my answers to a few of them.
ViewState is Evil and will slow down the page
This reminds me of the programmers who made everything a global variable. You can certainly do it, but you SHOULD NOT! It's the same with WebForms and ViewState. Don't use ViewState unless you need to, and then only sparingly. There is nothing wrong in adding 1000 characters of view state to the html, if it will bring better user experience and/or speed up development time. You can experience the same problem in MVC by littering the page with hundreds of hidden input controls, and yes I've seen it. And by the way, ViewState is not "magical" it simply stores some data in a single input control and also encrypts it for good measure.
WebForms generates "ugly" html and is littered with long ids
Well, first of all, nobody actually looks at generated hmtl (did you look at google.com for example, it's a mess?!). Second, if you really care about generating specific html, it takes less than an hour to create your own re-usable component or control, with html of your choosing. Or you can take existing control, override rendering and use that control instead. Once again, you have to know where to go and how to do it, but once you know, it will be a great productivity boost without any sacrifices. Long ids are automatically generated to ensure uniqueness across the page. If you ever get a chance to develop a complex MVC view, you'll notice that you will inventing your own long id pattern, so that you can parse the form fields correctly on posting.
WebForms disallows multiple forms per page
I've been developing for 10 years and only once did I need multiple forms. And then I figured out that I didn't. You do have to understand HTTP requests and responses and how to achieve them with WebForms, but if you do, you'll never need multiple forms, nor will you ever think about "forms" at all.
WebForms pages are not testable
Absolutely not true. Even if you don't like MVP (which I don't), there are other techniques to test anything you want to test. It is true that if you just use pages in WebForms as is and put all logic in code-behid, it's probably not going to be testable and it's not a good idea. However, just like in MVC or Windows Forms applications, you can and you should, at least for complex views, create intermediary layers such as views and controllers. I prefer encapsulating functionality into user controls which implement an interface or inherit a base class. Then the page on which user controls reside on acts like a "master controller". Individual views, or user controls in this case, can be tested because they all implemement an interface or base class.
JavaScript is hard to do in WebForms
JavaScript is actually easier to implement in WebForms than in MVC. You sure have more options! But once again, you have to know WebForms well in order to realise this. In WebForms you can "inject" javacript with reusable components and controls. Or you can use it just like in MVC or plain HTML after changing a setting on the page to keep ASP implementing id naming scheme.
Having said all this, what does WebForms have to offer that MVC does not? Encapsulation and reusability of presentation components is by far the biggest, in my opinion. For complex views, I develop individual components (server or user controls) and than a custom controller or presentation factory weaves all of them into place. Additionally, design-time html is far cleaner in WebForms than in MVC, making design and styling a lot easier for properly trained graphic designers. It's cleaner because there is no programming code in design-time html, only markup (I don't use data binding expressions). And of course prototyping is much much easier in WebForms. For prototypes I will normally ignore all of the best practices and resort to wizards and ugly code-behind code that hits the database directly.
I could go on, but the main point I'd like to make is that WebForms and MVC are very different patterns and require different sets of knowledge and mindset to deliver great solutions. Both require as much of Web/HTTP/CSS knowledge as you can get. If I had to make one recommendation, generally, but not always, for high-traffic public website (such as blog) I may lean towards MVC. For complex web application, either internal/Intranet or membership external/Internet application, I would lean towards WebForms.

A: You shouldn't arbitrarily decide between one or the other; don't plump for the MVC framework just because it's the new kid on the block and everyone's singing its praises, especially not if you're comfortable with doing things using Web Forms. Practically every existing system is going to be using the older, more established technology, and there's nothing wrong with that.
While it's true that the MVC framework does allow for even easier separation of concerns (after all, that's what the MVC pattern is for), it also brings with it the responsibility of writing more HTML, and I think a slightly greater understanding of how the web works; not necessarily an unreasonable requirement, but you could argue it'll slightly slow you down the first few times you set about using it.
To be honest, I agree that Web Forms takes a lot of undeserved flack. Granted, there's a lot of magic going on in the background, and you get less control over some of the HTML output, but it's not exactly impossible to style with CSS (you end up using !important a lot, perhaps), and it's also not impossible to get some separation of concerns, even if it doesn't meet the purist's view of what that might be. You can still write pretty horrible code using the MVC framework. If you're looking to throw together something quickly, and you're good with Web Forms, then you're going to be able to achieve that very quickly, and it's nothing to be ashamed of, is it?
That's not to say, of course, that you should stick to your guns and ignore MVC either; it's a good framework (in fact, it's a very good framework) and it does confer several benefits which you might want to take advantage of in the long run. You also have to remember that it doesn't automatically nullify everything you learned about ASP.NET 2.0, either; a lot of the supporting architecture is embraced in the MVC framework, including things like the membership providers.

A: WebForms work fine and if you like them, continue to use them.
Three of the big advantages to MVC model as I see it are:
ViewState is gone, which could create a fairly sizable amount of traffic over the wire.
URLs can be remapped to mean something as is all the rage now.
Scaffolding.  I don't know, personally I think this is satan and encourages terrible programming habits, but other seem to think its a beautiful idea.
It also encourages a a proper separation between business logic and presentation by enforcing the Model-View-Controller pattern, but good  WebForm code can mostly do that as well.
So, really, if you are fine with the overhead of WebForms, and ok with ugly URLs and don't want scaffolding, stick with WebForms.
EDIT:  Oh, I did miss one major advantage of "clean" urls.  And MVC application is much friendlier for SEO.  It also gives you fine control over HTML, but frankly, I don't consider that much of a step forward.

A: I think part of the problem, is that many people don't realise that MVC isn't an M$ invention, nor is it a replacement for webforms.  Certainly, people like "new" things, and people like to throw buzzwords around, particularly to improve their resumes...
Finally .NET developers have some choice, and with that choice, they are being thrust some degree of responsibility for the decisions they make.  I'm not surprised many webforms developers are nervous about this responsibility.  It's not been there before.  Ultimately, it can make you a better developer, or a worse one.  It's now up to you.
People loved webforms, because it was better than ASP (Classic).  And yes, in 5 - 10 years, I'm sure someone/group much smarter than I, will evolve a new paradigm/pattern.
Be careful with the sheep lable, as in a way, by holding onto a vendor specific pattern (webforms) you are potentially a bigger "sheep".
MVC is now across a variety of platforms, and means your potential to develop meaningful and stable solutions to problems can be dramatically increased.  Or decreased.  It's ultimately up to you.  If you're not ready to go, then wait for ASP.NET MVC to mature.  But don't close your mind to anything, particularly a pattern that is very very well established!
I recommend reading Rob Connery's extremely inflammatory blog.  He certainly strummed my pain with his fingers!  Then go and read RoR stuff, Cake, and Struts.  All of these will start showing you the vision that the guys who brought MVC to .NET have (~ish) and hopefully will inspire you to see problems differently!

A: There have been several, more detailed, answers here, so rather than repeat anything they have said I'll try to keep my answer a bit more succinct.  You shouldn't, necessarily use MVC over webforms, just as you shouldn't use webforms over MVC - they are both tools and are more, or less, appropriate in different situations.  I was first exposed to MVC quite a few years ago on J2EE, when .NET was first coming out (I'm not sure the ASP.NET MVC was available at that time).  It gives a really nice, clean framework and gives more "web" applications (i.e. request/response), but you can also add in a lot more client-side functionality using AJAX - I have done some really funky things using AJAX on a php app I wrote a while ago and that is all usable under MVC.
There are some things that MVC does better and some things that webforms do better, but if you don't know both technologies you can't choose the best one for the current project you are doing, so please don't do yourself a disservice - go and learn MVC.  Even if you never use it directly, it may still give you useful "theory" knowledge you can apply in other tools.  I try to learn as many different things as I can, as the more strings to my bow I have, the less likely it is that I will not be able to solve a problem (for example, in that php app, I used php, hooked into a bit of ASP, and even had DOS and *NIX batch/script files performing certain functions - each tool had its place and was best suited to the job to which it was allocated).

A: Not me. MVC is pretty cool in a resume, but for our customers (those who pay for our work), it's not a show stopper.
They usually want applications that are right, fast and secure. That's all. They will not want to change the third layer of the client part in three years ! In three years, they will change every thing or nothing at all.
Layers are fun to architect and to code, but they cost a lot to create and to maintain and they are not relevant to our customers. MVC is pretty cool but really useless and expensive.
Unless, of course, you are developping applications for 4 OS and 3 plateforms... But you will then be a minority.
:o)

A: This is a stupid discussion - they are different, ASP.NET MVC and WebForms are different technologies! I'm using MVC for all new projects, but when I am faced with a need for RAD I use WinForms, because it is simple and there are a lot of controls already written by gurus.
Stop discussing this. Who wants to understand difference? Just try both technologies and you will understand by yourself.


text:
Q: storing the result of a for loop into array and revrse it? I want to store the result of the for loop in an array then reverse it.
Example:
When I run the program and enter 5 the answer will be

54321

I want it to be

12345

int num;
int index = 0;
Console.Write("Number: ");
num = int.Parse(Console.ReadLine());
for (int x = num; x > 0; x--)
{
    index = Convert.ToInt32(index + x);
    Console.Write(x);
}
Console.WriteLine("\nThe sum is: {0}", index);
Console.ReadLine();

A: How about this?
Console.Write("Number: ");
var num = int.Parse(Console.ReadLine());   // parse console input
var range = Enumerable.Range(1, num);   //generate array of values from 1 to num
var str = String.Concat(range.Select(x => x.ToString()));   //concatenate array of values
Console.WriteLine(str);     // write string
var sum = range.Sum(); // get sum of array
Console.WriteLine("\nThe sum is: {0}", sum);   // write sum
Console.ReadLine();   // pause

A: Try this
For auto increment to total length
Use this
Console.WriteLine("Input length");
int length;
if (!int.TryParse(Console.ReadLine(), out length))
{
    Console.WriteLine("Invalid number");
}
else
{
    int[] array = new int[length];
    for (int i = length; i > 0; i--)
    {
        array[length - i] = i;
    }
    Console.WriteLine("Array is");
    foreach (var i in array)
    {
        Console.WriteLine(i);
    }
    Console.WriteLine("Reverse Array is");
    foreach (var i in array.Reverse())
    {
        Console.WriteLine(i);
    }
}
Console.ReadKey();

To take every number from user, try this
private static void Main(string[] args)
{

    Console.WriteLine("Input length");
    int length;
    if (!int.TryParse(Console.ReadLine(), out length))
    {
        Console.WriteLine("Invalid number");
    }
    else
    {
        int[] array = new int[length];
        for (int i = length; i > 0; i--)
        {
            int input;
            Console.WriteLine("Input number");
            if (!int.TryParse(Console.ReadLine(), out input))
            {
                Console.WriteLine("Invalid number");
                input = 0;
            }
            array[length - i] = input;
        }
        Console.WriteLine("Array is");
        foreach (var i in array)
        {
            Console.WriteLine(i);
        }
        Console.WriteLine("Reverse Array is");
        foreach (var i in array.Reverse())
        {
            Console.WriteLine(i);
        }
    }
    Console.ReadKey();
}

A: Ok, none of those responses really would do what you asked for, but I mut say your example is really misleading.
Try this:
public int[] ArrayAndReverse(int Number)
{

    int[] data = new int[Number];
    int index =
    for (int x = Number; x > 0; x--)
    {
        index = Convert.ToInt32(index + x);
        Console.Write(x);
    }
    return data.Reverse().ToArray();

}

now in your console code you can do:
Console.Write("Number: ");
num = int.Parse(Console.ReadLine());
int[] data = ArrayAndReverse(number);
foreach(int i in data)
    Console.Write(i);

Also, not sure why your loop is already reversed, I suppose as I said this example is really misleading, else you can just use:
int[] data = Enum.Range(1, number).ToArray();

This will give you already the array in the right order.


text:
Q: Android cant see attr style Im working with leanback library
implementation "com.android.support:leanback-v17:27.1.1"

this library has layout
android.support.v17.leanback.R.layout.lb_action_2_lines

<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/lb_action_button"
android:layout_width="wrap_content"
android:layout_height="@dimen/lb_action_2_lines_height"
style="?attr/detailsActionButtonStyle"
android:lines="2"
/>

But styles not working.... ?attr/detailsActionButtonStyle
If i create custom layout and change style="?attr/detailsActionButtonStyle" to style="@style/Widget.Leanback.DetailsActionButtonStyle", then i can see correct styles
I tried rebuild project, clean project, tried remove and add leanback in dependencies - nothing.
How can I understand the problem in the studio or gradle?

A: It looks like you are using the wrong theme, please, check that your theme is Theme.Leanback.


text:
Q: Do people agree on what dx is in Riemann integration? I've been rather curious about what the official rigorous understanding of the dx term in a Riemann integral is. Of course, we could use the formal definition of a Riemann integral but I have seen on Wikipedia other proposed ways of defining the differential of some function (we'll call x), dx. The classic high school teacher approach is to say it's a "very small change in x", or rather a small change in a linear approximation of x. However, as someone who studies differential geometry, I am wondering how this can be interpreted as the exterior derivative of a function x, in which dx is a 1-form. Do we then reinterpret $\int{f(x)}\,dx$ as being the integral of a 1-form? And how then can we consider a 1-form to be a "small change in x"?

A: This question has been asked a million times on this site in one form or another. But I suppose it can't hurt to answer it again since it is so natural a question but also so typically badly answered.
The short answer to your title question is yes: there is agreement about what the $dx$ means — but only once you get precise about exactly what kind of integral you're talking about. The one-dimensional baby's-first-integral in $\mathbb{R}$ can be interpreted in many different ways that only come apart once you move to integration in more general spaces.
If you're thinking about $\int_{[a,b]}f dx$ as giving the integral of a density $f$ over an unoriented interval $[a,b]$, then $dx$ generally denotes a measure. Example: if $f$ measures mass per unit length over a rod, then the integral gives the mass of the rod. This generalizes easily to higher-dimensional Euclidean spaces: the "area element" $dA$ and the "volume element" $dV$ are really measures. In differential geometry you want to integrate such things not just over subsets of Euclidean space but over abstract manifolds. In that case you don't have a measure, but you do have the differential geometric analog of a measure called a density.
If, however, you're thinking about $\int_a^bfdx$ as giving the integral of $f$ over the oriented interval $[a,b]$, then $dx$ generally denotes a differential form. Example: if $f$ measures the rate of change of some quantity as a function of $x$, then the integral gives the total change in the quantity as $x$ ranges from $a$ to $b$ — that's the fundamental theorem, which is just a special case of Stokes theorem, which is a theorem that depends crucially on orientations and thus on differential forms. There is a connection between differential forms and densities, however. Densities are in some sense the natural objects to integrate: they're defined whether you have an orientation or not. You can only integrate a differential form if you have an orientation, by contrast — and indeed the whole point of the orientation is that it provides enough information to turn the differential form into a density, which can then be integrated.
If you reject all this seeming abstract nonsense and insist on an answer in the case of the most familiar, calculus 101 one-dimensional Riemann integral of a bounded real function $f$ on $[a,b]$, the answer is that the $dx$ is literally meaningless, a mere piece of suggestive notation. The value of the integral, if it exists, is solely a function of $f$ and of $[a,b]$; the best notation to emphasize this is $\int_{[a,b]}f$, with no $dx$ at all.

A: The title doesn't really match the question, but perhaps it suffices to say that $d x$ is a 1-form which is the exterior derivative of the function $x$, i.e. the identity function on $\mathbb{R}^1$.
This function takes $x$ to $x$, hence the name $x$; compare e.g. when we write $\sin(x)$ for the function that takes $x$ to $\sin(x)$.  (These are both abuses of notation; the latter should just be called $\sin$ when we're talking about the function, while the former should be called ${\rm id}$ or something.)


text:
Q: Changing the layout & design for a specific set of products On 3 of my products I wanted to change the look & feel along with the layout
As an example, I want to move the product title so I have created a new child theme like below
/app/design/frontend/[Vendor]/[Child_Theme_Name]/Magento_Catalog/layout/catalog_product_view.xml
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <move element="page.main.title" destination="main" before="-"/>
    </body>
</page>

/app/design/frontend/[Vendor]/[Child_Theme_Name]/registration.php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::THEME,
    'frontend/[Vendor]/[Child_Theme_Name]',
    __DIR__
);

/app/design/frontend/[Vendor]/[Child_Theme_Name]/theme.xml
<theme xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/theme.xsd">
     <title>Child Theme Name</title>
     <parent>[Vendor]/[Parent_Theme_Name]</parent>
     <media>
         <preview_image>media/preview.jpg</preview_image>
     </media>
 </theme>

In the admin, I have selected that child theme and then cleared all the cache

Unfortunately, the product detail page then doesn't change. If I make that change in the parent theme the product detail changes but it naturally affects all products which I don't want.
Can anyone advise on what I am doing wrong?

A: No need for a child theme. Just rename your layout file like this: catalog_product_view_id_{id}.xml
Source: https://devdocs.magento.com/guides/v2.4/frontend-dev-guide/layouts/product-layouts.html
Or create a layout handle catalog_product_view_special.xml
with your special layout and apply it on your products
using <update handle="catalog_product_view_special"/>
HTH, Tom


text:
Q: Active Record - automatically generating markdown in the model I'm writing a Ruby module to provide automatic markdown generation on blog posts etc.
The code so far looks like this:
class Post < ActiveRecord::Base
  contains_markdown
end

module MarkdownMixin
  def contains_markdown
    # HELP! :)
  end
end

ActiveRecord::Base.send :extend, MarkdownMixin

That code seems to be working (i.e. my unit tests don't throw any 'not defined' errors etc.). The Post table contains an input and formatted column.
Where I've written # HELP I want to inject code to the Post model so that whenever a change is made to input, formatted is recalculated (using a Markdown engine). Something like (pseudo-code):
def on_input_changed
  @formatted = Redcarpet.new(@input).to_html
end

Now I'm still really getting my head around Ruby mixins so my brain's slightly spinning trying to work out what incantation to call in my module.
So far I've found this article quite useful, but can't work out how to apply it here.

A: I think the easiest way would be to use a before_save where you make the transformation.
def contains_markdown
  before_save do |record|
    record.formatted = Redcarpet.new(record.input).to_html
  end
end


text:
Q: Scene transition of SKScene with UIKit elements (UIButtons, UILabel, ...) I have a menu which is a SKScene with a SKSpriteNode as as background and with 3 UIButtons and 1 UILabel.
When the user clicks the button, this scene transition is triggered :
view?.presentScene(GameScene(size: view!.bounds.size), transition: SKTransition.fadeWithDuration(2))

The scene does change (the background changes) but all my UIElements are still in place.
Is there a proper way to remove them along the scene transition ? By proper way I mean that the garbage collector should at some point free the menu scene from the memory (which cannot be done if there are still UIElements on it).

A: If you want the buttons to be released then you will have to remove them from the view.
It is worth considering though if this really necessary?  Is the amount of memory reclaimed worth the additional cost to re-add these buttons later? assuming you can return to the menu.
There are a few options for making a visually appealing transition using both SpriteKit and UIKit elements.  Although I wouldn't necessarily recommend them.

*

*Animate the buttons off screen manually, by adjusting the frame or alpha.

*Remove the transition from the SKScene and animate a transition of the UIView using transitionWithView:duration:options:animations:completion:
 or transitionFromView:toView:duration:options:completion:
If you can't create an effect using either of these options that is satisfactory then it is probably worth reimplementing your scene/view to use only SpriteKit elements.

A: You have two options here. First is to keep using the UIKit elements and actively removing them when transitioning to your game scene. For example, you can set up a method for doing the same when the button for the game is pressed:
func hideButtons () {
    //Hide your buttons and label here.
    btn.hidden = true //Either hide it
    btn.removeFromSuperview() //or remove it altogether.
    ...
}

And then call this method just before you present the scene.
self.hideButtons()
view?.presentScene(GameScene(size: view!.bounds.size), transition: SKTransition.fadeWithDuration(2))

Alternatively, you can implement a button in the SKScene itself, using the touch delegates.
Declare a SKSpriteNode with the same frame as your button. When you detect a touch on the button, trigger the scene change.
Another option is using a class like AGSpriteButton. It has a setup system very similar to that of a UIButton.


text:
Q: Why doesn't resharper suggest removing redundant access modifiers? Resharper is superb, as any fule kno.
However, if I declare a method such:
private void MethodName() { //code in here }

or an enum:
public enum SomeEnum { Value1, Value2 }

Resharper doesn't suggest removing the redundant access modifiers... why not?

A: Most likely, because you configured it like this: ReSharper -> Options -> Languages -> C# -> Formatting Style -> Other -> Use explicit private / internal modifier

A: It doesn't suggest removing redundant comments either. It recognises that some of the content of the code file, while technically redundant to a compiler, enhances code readability, and hence maintainability.

A: By default not having an access modifier is a StyleCop violation (if you're picky enough to turn ALL the rules on).


text:
Q: Unexpected Polymorphism Behaviour In Java if same method overloaded and overridden I have been doing some changes in my project where I found some weird or rather I will say unexpected behaviour of Polymorphism in Java. I have replicated same behaviour in a Poc given below.
1. CommonInterface.java
package com.general;

public interface CommonInterface {

    public void getViews(String str);

    public void getViews(String str, Long id);

}

2. GenericUtility.java
package com.general;

public class GenericUtility implements  CommonInterface{

    @Override
    public void getViews(String str) {
        System.out.println("This is getViews (single param)from  GenericUtility");
        getViews(str, null);
    }

    @Override
    public void getViews(String str, Long id)  {
        System.out.println("This is getViews (multi-param) from  GenericUtility");
    }

}

3. CustomUtility.java
package com.general;

public class CustomUtility extends GenericUtility {

    @Override
    public void getViews(String str) {
        System.out.println("This is getViews (single param)from  CustomUtility");
        super.getViews(str);
    }

    @Override
    public void getViews(String str, Long id) {
        System.out.println("This is getViews (multi-param) from  CustomUtility");
        super.getViews(str, null);
    }

}

4. Main.java
package com.general;

public class Main {

    public static void main(String[] args) {
        GenericUtility utility = new CustomUtility();
        String str = "Random String";
        utility.getViews(str);
    }
}

After running Main.java , my expected output is
This is getViews (single param)from  CustomUtility
This is getViews (single param)from  GenericUtility
This is getViews (multi-param) from  GenericUtility

But output that I get is
This is getViews (single param)from  CustomUtility
This is getViews (single param)from  GenericUtility
This is getViews (multi-param) from  CustomUtility
This is getViews (multi-param) from  GenericUtility

I am not able to understand why com.general.GenericUtility#getViews(java.lang.String) is calling com.general.CustomUtility#getViews(java.lang.String, java.lang.Long)
Is this expected behaviour and what is it that I don't know ?
Thanks in advance.

A: Java uses runtime virtual dispatch for calls to instance methods (that is, those that aren't static). That still applies to calls to this; that's how, for example, an abstract class can define an abstract method createResultObject to be implemented by subclasses and use that method in its doProcessing method.
In your case, the object is a CustomUtility, so calls to this.getViews(String, String) are dispatched to CustomUtility, which then uses super internally.

A: When GenericUtility.getViews(String) calls getViews(str, null);, the getViews(String, Long) implementation that will be invoked is CustomUtility.getViews(String, Long).
That's because CustomUtility overrides that method too. Irrespective of where the method is called from (including the superclass), a call to an overridden method will cause the overriding implementation to run. The only thing that can change this is the subclass explicitly invoking the method using super.
So here's roughly what is happening:

*

*main calls utility.getViews(str);, which causes overriding
CustomUtility.getViews(String) to run.

*CustomUtility.getViews(String) calls super.getViews(str), which
causes GenericUtility.getViews(String) to run.

*GenericUtility.getViews(String) calls getViews(str, null), which
causes the overriding CustomUtility.getViews(String, Long) to run
(contrary to what you expected)

*CustomUtility.getViews(String, Long) calls
super.getViews(str, null), which calls
GenericUtility.getViews(String, Long) to run.