text:
Q: Facebook Login for Swift with facebook iOS SDK 4.9.1 I got trouble with facebook iOS SDK 4.9.1 on integrating facebook login using swift. and main trouble is unable to find any guideline regarding it for swift.
http://www.brianjcoleman.com/tutorial-how-to-use-login-in-facebook-sdk-4-0-for-swift/
http://swiftdeveloperblog.com/facebook-sdk-ios-login-example-with-swift/
IOS Swift and Facebook SDK
I try to implement below but it doesn't work at all.
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        if (FBSDKAccessToken.currentAccessToken() != nil)
        {
            // User is already logged in, do work such as go to next view controller.
        }
        else
        {
            let loginView : FBSDKLoginButton = FBSDKLoginButton()
            self.view.addSubview(loginView)
            loginView.center = self.view.center
            loginView.readPermissions = ["public_profile", "email", "user_friends"]
            loginView.delegate = self
        }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

A: This is for viewcontroller :
import FBSDKLoginKit
class ViewController: UIViewController,FBSDKLoginButtonDelegate {
@IBOutlet weak var fbLoginView: FBSDKLoginButton!

override func viewDidLoad() {
    super.viewDidLoad()

    if(FBSDKAccessToken.currentAccessToken() == nil){
        print("Not Logged ")
    }
    else{
        print("Logged In")
    }
    fbLoginView.readPermissions = ["public_profile","email","user_birthday"]
    fbLoginView.delegate = self

    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!)
{
    if error == nil
    {
        print("login complete")
        let request = FBSDKGraphRequest(graphPath:"me", parameters:["fields":"name,gender,birthday,first_name,last_name,email"])
        request.startWithCompletionHandler
            {
                (connection, result, error) in
                if error != nil
                {
                    print ("error \(error)")
                }
                else if let userData = result as? NSDictionary
                {

                   var frstname = userData["first_name"] as? String
                   var lastname =  userData["last_name"] as? String
                   var gender = userData["gender"] as? String
                   var birthday = userData["birthday"] as? String
                   var email = userData["email"] as? String

                    print(result)
                }
        }
    }
    else
    {
        print(error.localizedDescription)
    }

}
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!)
{
   print("user logged out")
}

}

A: In App Delegate override the following method as :
func application(application: UIApplication,openURL url: NSURL, sourceApplication: String?,annotation: AnyObject) -> Bool
{
    return FBSDKApplicationDelegate.sharedInstance().application(application,openURL: url,sourceApplication: sourceApplication,annotation: annotation)
}

A: Swift 5+
In App Delegate override the following method as :
    func application(application: UIApplication,openURL url: NSURL, sourceApplication: String?,annotation: AnyObject) -> Bool
{
    return ApplicationDelegate.sharedInstance().application(application,openURL: url,sourceApplication: sourceApplication,annotation: annotation)
}


text:
Q: how send an object from view to Controller AngularJS + ASP.net MVC? send an object with a quantity of data from the View to the Controller in ASP.net MVC and AngularJS
VIEW
var Person = {};
Person.IdPerson = 69425;
Person.Year = new Date().getFullYear();

$http.post('/API/Update_Person', { params: { Person: Person } }).then(function (response) {

});

CONTROLLER
public JsonResult Update_Person(ModelPerson Person)
{
    var person = (from c in db.Person where c.IdPerson == Person.IdPerson && c.Year == Person.Year select c).FirstOrDefault();

    return new JsonResult { Data = "OK", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

more effective method than this?
$http({
    method: "post",
    url: "/API/Person",
    datatype: "json",
    data: JSON.stringify(Person)
}).then(function (response) {

});

A: You can follow the below Approach for passing the data to API controller:

var Person = {};
Person.IdPerson = 69425;
Person.Year = new Date().getFullYear();

$http.post('/API/Update_Person', Person, {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                }).then(function (response) {
                    console.log(response);
                }, function(error){
                    console.log(error);
                });

redpajama_set_name: RedPajamaStackExchange


text:
Q: Debugging keypresses in Vim For some reason my Vim has gotten pretty slow when I try to switch from Insert mode to Normal mode - sometimes I have to wait 2 seconds to make a switch, sometimes I have to press  twice. It may be related to plugins (I have many of them installed at the moment) or to my own mappings.
How can I debug keypresses in Vim (for example, print to the log what actually happens when I press a certain key)?

A: You can capture a full log of a Vim session with vim -V20vimlog. After quitting Vim, examine the vimlog log file for suspect commands.
However, for this timing issue, there's probably an easier approach: The delay can only be caused by either a mapping on the <Esc> key (especially in the terminal you have to deal with the ambiguity with escape codes, which also start with Escape), or by code run on InsertLeave. So, check whether something's mapped:
:verbose imap <Esc>

and list (and then disable one by one) the autocmds:
:verbose autocmd InsertLeave


text:
Q: How can I exactly identify the element which an eventlistener has fired from? I am building a slide show in a modal window! First I click on one of the 12 images on the website...then the            modal window opens which contains a window with a slideshow... the picture (img) which I clicked should be seen (as a background-image) as the first picture in the slideshow.
The pictures on the webpage are in a div with the id pic_cnt
In the div of the modal slideshow window (id modal_window) there are 12 divs (for each picture) with the class modal_pic! Every div with this class has the background-image in the same order as the img on the webpage but with opacity 0.
I added an eventlistener to each img on the page which opens the modal window! How can I connect the clicked img with the same background-image? When an img is clicked a class (.current) to the same background-image in the modal window should be added to change the opacity to 1. Please help!

let modal = document.getElementById('modal');
let clickedPic = document.querySelectorAll('#pic_cnt img');
let modalPic = document.querySelectorAll('#modal_window div');

for (let i = 0; i < clickedPic.length; i++) {
  clickedPic[i].addEventListener('click', openModal)
}

function openModal() {
  modal.style.display = "block";
}
#modal {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 2;
  background-color: rgba(1, 1, 1, .8);
}

#modal_window {
  background-color: white;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  height: 55%;
  width: 55%;
}

.modal_pic {
  width: 100%;
  height: 100%;
  ;
  position: absolute;
  opacity: 0;
}

.current {
  opacity: 1;
}

A: In the event listener, this is the element you clicked on. You can get the parent DIV, and then get its index in the pic_cnt DIV, then use that index to find the corresponding DIV in the modal.

let modal = document.getElementById('modal');
let clickedPic = document.querySelectorAll('#pic_cnt img');
let modalPic = document.querySelectorAll('#modal_window div');

for (let i = 0; i < clickedPic.length; i++) {
  clickedPic[i].addEventListener('click', openModal)
}

function openModal() {
  modal.style.display = "block";
  let index = Array.from(this.parentElement.parentElement.children).indexOf(this.parentElement);
  console.log(index);
  for (let i = 0; i < modalPic.length; i++) {
    modalPic[i].style.opacity = i == index ? 1 : 0;
  }
}
#modal {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 2;
  background-color: rgba(1, 1, 1, .8);
}

#modal_window {
  background-color: white;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  height: 55%;
  width: 55%;
}

.modal_pic {
  width: 100%;
  height: 100%;
  ;
  position: absolute;
  opacity: 0;
}

.current {
  opacity: 1;
}

Pic 1

Pic 2

Pic 3

Pic 4

Pic 5

Pic 6

Pic 7

Pic 8

Pic 9

Pic 10

Pic 11

Pic 12

A:
FYI: when you run example it takes couple seconds for me to event get
  fired

I got rid of most of the divs and kept only one, sine you only need one div and you can replace the inside content of it on every click depending on image.
I used

$(e.target)

which gives you the item that has been clicked(Read Check which element has been clicked with jQuery). Once you have access to that element you can do the rest. I then pass that target element to your openmodal() function and update the div content.
comment if anything is unclear.

  let modal_div = document.getElementById('modal');
$('img').click(function(e) {
  console.log(e)
  var modal = $('.modal_pic');
  var target = $(e.target);
  openModal(target);
}
 );

function openModal( target) {

 $('.modal_pic').append(target[0])
  modal_div.style.display = "block";
}
#modal {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 2;
  background-color: rgba(1, 1, 1, .8);
}

#modal_window {
  background-color: white;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  height: 55%;
  width: 55%;
}

.modal_pic {
  width: 100%;
  height: 100%;
  ;
  position: absolute;

}

.current {
  opacity: 1;
}


text:
Q: Create new data frame from unique values of certain columns I have
df = pd.DataFrame({"A": [2000,2001,2000,2000,2001,2001], "B": [1,1,2,2,2,1], "C": [4,4,6,10,10,10]})

    A       B   C
0   2000    1   4
1   2001    1   4
2   2000    2   6
3   2000    2   10
4   2001    2   10
5   2001    2   10

I would like to create a new dataframe with one observation for each unique combination of A,B and have a new column C or C_min which is the minimum (or, say, mean) of the values of C in the rows corresponding to the combination of A,B in question.
So the desired output would be something like:

    A       B   C_min
0   2000    1   4
1   2000    2   6
2   2001    1   4
3   2001    2   10

How do I do this? Thanks


text:
Q: Issue with the "more/less info" profile button When opening the complete profile panel with the more info button, the panel gets its full size.
When closing it with the less info button, it becomes a size that is different from the size displayed when I click back on the menu button (in the top bar).
When you click more info, less info and on the top bar profile button, you should see a little glitch.
Is that normal?


text:
Q: Call Java code from C I use the JNI interface to invoke Java code from C code.
While compiling I use the following command:
gcc -g -I/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.0.x86_64/include/ -I/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.0.x86_64/include/linux/ -L/usr/bin/java -L/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.0.x86_64/jre/lib/amd64/server/ -ljvm calljava.c
And I use the following code to create the JVM:
JNIEnv* create_vm()
{
    JavaVM* jvm;
    JNIEnv* env;
    JavaVMInitArgs args;
    JavaVMOption options[1];
    args.version = JNI_VERSION_1_2;
    args.nOptions = 1;
    options[0].optionString = "-Djava.class.path=<classpath>";
    args.options = options;
    args.ignoreUnrecognized = JNI_FALSE;
    JNI_CreateJavaVM(&jvm, (void **)&env, &args);
    return env;
}

My question is:
Is the path to the JVM hardcoded in the binary?
Can we specify the path to the java executable at runtime?
If there is a way to do that can anyone help me with the compile time flags that can be used for that?
Thanks in advance!

A: The "java executable" is not used at all.  When you compile and link your code, you link against a shared library, the location of which is determined by the system at runtime when you launch your executable.
Unless you dynamically load the jvm shared library yourself from a known location (and subsequently look up and call the functions therein), the system is going to determine the "path to the JVM".
Usually if you want to run against a specific version, you would include that version in your application's distribution, and configure the launch of your application to ensure that the proper shared library is used (either via scripts which set the environment appropriately, dynamically loading it, or other system-specific methods).


text:
Q: Correlated Subquery in MySQL unable to include "column" in main where stmt Using the following query, to include a correlated subquery, I would like to be able to find records from the main query where PhotoCount (which is the subquery) are > # i.e., > 1 or >5
I have tried doing
WHERE PhotoCount > #
WHERE (SELECT COUNT(operatorID) FROM tbl_photos p WHERE p.operatorID =  aoh.operatorID AND p.img_creator = 'Daniël E. Cronk') > #
However, all of these yield "unknown column" error
I have tried adding in @PhotoCount:= and then doing WHERE PhotoCount but this yields No results.
SELECT af.frameID, af.msn AS afMSN, af.ln AS afLN, af.aircraft_type AS toestelA, af.aircraft_cat AS afAircraftCat, af.airframe_status, aoh.operatorID, aoh.aircraftframeID, aoh.msn, aoh.ln, aoh.lvmID, aoh.toestel, aoh.aircraft_cat, aoh.reg, aoh.delivered, aoh.delivery_comment, aoh.engines, aoh.configuration, aoh.fleet_number, aoh.aircraft_name, aoh.special_colors, aoh.comments, aoh.exit_date, aoh.last_updated, lvm.luchtvaartmaatschappijID AS lvmid, lvm.luchtvaartmaatschappij AS lvmnaam, lvm.sm_logo, (SELECT COUNT(operatorID) FROM tbl_photos p WHERE p.operatorID =  aoh.operatorID AND p.img_creator = 'Daniël E. Cronk') AS PhotoCount

            FROM tbl_aircraft_frame af

            LEFT JOIN tbl_aircraft_operator_history aoh
            ON af.msn = aoh.msn AND af.aircraft_cat = aoh.aircraft_cat

            LEFT JOIN tbl_toestel t
            ON af.aircraft_cat = t.toestelID

            LEFT JOIN tbl_luchtvaartmaatschappij lvm
            ON aoh.lvmID = lvm.luchtvaartmaatschappijID

A: If you want use a column from the SELECTyou need to use HAVING instead of WHERE
SELECT
    af.frameID,
    af.msn AS afMSN,
    af.ln AS afLN,
    af.aircraft_type AS toestelA,
    af.aircraft_cat AS afAircraftCat,
    af.airframe_status,
    aoh.operatorID,
    aoh.aircraftframeID,
    aoh.msn,
    aoh.ln,
    aoh.lvmID,
    aoh.toestel,
    aoh.aircraft_cat,
    aoh.reg,
    aoh.delivered,
    aoh.delivery_comment,
    aoh.engines,
    aoh.configuration,
    aoh.fleet_number,
    aoh.aircraft_name,
    aoh.special_colors,
    aoh.comments,
    aoh.exit_date,
    aoh.last_updated,
    lvm.luchtvaartmaatschappijID AS lvmid,
    lvm.luchtvaartmaatschappij AS lvmnaam,
    lvm.sm_logo,
    (SELECT
            COUNT(operatorID)
        FROM
            tbl_photos p
        WHERE
            p.operatorID = aoh.operatorID
                AND p.img_creator = 'Daniël E. Cronk') AS PhotoCount
FROM
    tbl_aircraft_frame af
        LEFT JOIN
    tbl_aircraft_operator_history aoh ON af.msn = aoh.msn
        AND af.aircraft_cat = aoh.aircraft_cat
        LEFT JOIN
    tbl_toestel t ON af.aircraft_cat = t.toestelID
        LEFT JOIN
    tbl_luchtvaartmaatschappij lvm ON aoh.lvmID = lvm.luchtvaartmaatschappijID
HAVING PhotoCount > 10


text:
Q: How to modify index.js file in create-react-app I am trying to modify the entry point file index.js in the create-react-app pre-configured project. I am trying to connect the project to mongodb, add a body-parser and api file in index.js but I get an error when I edit index.js.
Index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
ReactDOM.render(App, document.getElementById('root'));

My code:
const express = require('express');
const app = express()
const bodyParser = require('body-parser')
const mongoose = require('mongoose')

mongoose.connect('mongodb://localhost/treedb')
mongoose.Promise = global.Promise
app.use(bodyParser.json())

//initialize routes
app.use('/api', require('./routes/api'))

Error:
TypeError: Cannot read property 'prototype' of undefined
in file node_modules/express/lib/response.js:58:

var res = Object.create(http.ServerResponse.prototype);

This error occurs when I start the app with "npm start" and "react-scripts start" is run. My code is fine when I run "node index.js" but the import statements cause an error instead. Any ideas how to edit the index.js file without causing an error? Thanks.

A: As mentioned by @skyboyer you seem to be using Create React App for purposes it was not meant for. Create-React-App is a toolkit which enables you to quickly start developing react based web application without having to worry with the hassle of setting up & maintaining webpack configs and other such things. You seem to be trying to setup an API server which connects to your MongoDB.
If you just want to create an express app to serve as your API server, without any react based front end, you shouldn't use CRA to set it up.
Most probably, you need to have both: a client side webapp (React based) and a Server side API app (express based), in this case, you have two options:

*

*Same project, but two source directories. You can create a folder on the same level as the src but with a different name: dataSrc for e.x. and then you can modify your package.json to start both servers. I would not recommend this, except for learning  purposes, as this will become tricky for you to maintain and when you need to bundle and deliver to prod, this will become tricky.

*Create a new project for your API server, which is separate from your web app.

In both cases, for development, you will need to configure the Create React App to proxy the data requests to your API server.
Hope this gives you some clarity. Feel free to ask for clarification if something still confuses you.

A: I think the issue has to do with your trying to run a client side application on the server by doing this node index.js.
It could also be that you have both your server and client files named index.js which is not advisable except they are tucked away in separate folders.
As a last minute check, run npm install to ensure the required dependencies are installed correctly, then run node index.js.


text:
Q: iOS: Is secure enclave shared between app extensions? I am working on a app where a encryption key is saved into the secure enclave. So my question is if this data is also shared with the app extensions, i.e. Siri / Notification Center widget / Watch App?

A: App Group keychain items can be shared between the app and the app extension. See the instructions in Sharing Access to Keychain Items Among a Collection of Apps
SecItemCopyMatching will return an item saved by the app and queried for within the extension.
I use this approach in my app.
Note you do not have direct access to the secure enclave. This is where the private key is saved. You do however have access to the Keychain items (encrypted by the secure enclave private key).


text:
Q: Find the maximum value of a function of $x$ for a given range of values of $x$ What is the most efficient and reasonable way to find the maximum value of a function of $x$ within a given range of $x$ values?
For example, given the function $f(x)=3\sin(x)+0.01x^2$, how can I find the maximum between $x=0$ and $x=37$, inclusive.  I'm not really looking for the specific answer to this, but the general principle that can be used for any equation.  I seem to have forgotten how to do this.

A: You take the derivative $f^\prime$ and find out the points $x$ where it's zero: $f^\prime (x) \stackrel{!}{=} 0$
$f^\prime (x)$ is the slope at $x$. If it's zero it means that you have a found either a minimum, a maximum or a saddle point. You're not interested in saddle points though so you want to check that the points where $f^\prime$ is zero also have the property that $f^{\prime \prime}$ is non-zero. $f^{\prime \prime}$ gives you a measure for the "curvature" of $f$ at that point. Saddle points are horizontal hence have $f^{\prime \prime}$ equal to zero.
Edit As pointed out in the comment by Ronald, $f^{\prime \prime} = 0$ is not a sufficient condition to be at a saddle point. There are functions that satisfy this condition at points where they don't have a saddle point, such as for example $f(x) = x^4$ at $0$. In general you need to look at the first derivative that's non-zero, this is called "higher-order derivative test".
Note that for example if $f$ is a function like $f(x) = x$ then it won't have any points where $f^\prime$ is zero and yet it will attain a maximum at the right end of your interval. To detect this case you simply have to remember to also check $f(a)$ and $f(b)$ if your function is defined on $[a,b]$.
For this you need $f$ to be differentiable. Luckily, your example and probably many of the functions you'll have to find mins and maxs for will be differentiable.

A: For a differentiable function, you can take the derivative, check all points where it is zero (or do a second derivative test) and check the endpoints of the interval.  In this particular case, you can't analytically solve for zeros of the derivative.  You can search numerically for zeros of the derivative or for maxima of the function.

A: I believe the question has not been answered.
E.g. if you take the function   x(x-2)^2   and impose the restriction that x is between 0 and 3 then the calculus style maximum by differentiation is at (0.67,1.19) but the true maximum within the range is (3,3) - simply because the function is largest at that point, even though the gradient is not zero.
Unfortunately - I don't know the general answer to this question - I came here looking to find the answer!
Oh. I am so stupid: realised after that the largest value must either be the calculus maximum, or at an endpoint of the range. There are no other possibilities - hence the question is quite simple in the end.


text:
Q: A way to talk about complex analysis without parameterizations In the way that we got rid of the rieman integral for most purposes (not including complex analysis) with the lesbeague integral, which is much more "clean", is there a way to get rid of parameterizations in complex analysis? I know that the integrals there are independent of it, as is rieman integral via rieman sums.
Another motivation for this, is that it feels "ungeneral" to have to deal with domains that have a boundery is pathwise smooth, wouldn't it be much better if could talk complex analysis on arbitary open connected sets?


text:
Q: How to add for loop in python? I'm creating new files from originally existing ones in the mdp folder by changing a couple of lines in those files using python. I need to do this for 1000 files. Can anyone suggest a for loop which reads all files and changes them and creates new in one go?
This way I have to change the the number followed by 'md_' in the path and it's tedious because there are a 1000 files here.
I tried using str() but there was a 'could not read file error'
fin = open("/home/abc/xyz/mdp/md_1.mdp", "rt")
fout = open("/home/abc/xyz/middle/md_1.mdp", "wt")

for line in fin:
fout.write(line.replace('integrator               = md', 'integrator
= md-vv'))
fin = open("/home/abc/xyz/middle/md_1.mdp", "rt")
fout = open("/home/abc/xyz/mdb/md_1.mdp", "wt")

for line in fin:
fout.write(line.replace('dt                       = 0.001', 'dt
= -0.001'))

fin.close()
fout.close()

A: os.listdir(path) is your friend:
import os

sourcedir = "/home/abc/xyz/mdp"
destdir = "/home/abc/xyz/middle"

for filename in os.listdir(sourcedir):
    if not filename.endswith(".mdp"):
        continue

    source = os.path.join(sourcedir, filename)
    dest = os.path.join(destdir, filename)

    # with open(xxx) as varname makes sure the file(s)
    # will be closed whatever happens in the 'with' block
    # NB text mode is the default, and so is read mode
    with open(source) as fin, open(dest, "w") as fout:
        # python files are iterable... avoids reading
        # the whole file in memory at once
        for line in fin:
            # will only work for those exact strings,
            # you may want to use regexps if number of
            # whitespaces vary etc
            line = line.replace("dt = 0.001", "dt = -0.001")
            line = line.replace(
                'integrator               = md',
                'integrator    = md-vv'
                )
            fout.write(line)

A: Assuming you want to edit all files that are located in the mdp folder you could do something like this.
import os

dir = "/home/abc/xyz/mdp/"
for filename in os.listdir(dir):
    with open(dir + filename, "r+") as file:
        text = file.read()
        text = text.replace("dt = 0.001", "dt = -0.001")
        file.seek(0)
        file.write(text)
        file.truncate()

This will go through every file and change it using str.replace().
If there are other files in the mdp folder that you do not want to edit, you could use and if-statement to check for the correct file name. Add something like this to encase the with open statement.
if filename.startswith("md_")


text:
Q: References to a class just ported to Swift appear as forward class objects I just ported a new class to Swift to overcome an issue with protocols I had encountered. Yet, after finally fixed all issues associating to the porting, all references to the methods of the class in other objective-c classes are reported as:

"Property ... cannot be found in forward class SwiftClass"

I found a few references to this problem on the web in which it seems the order of inclusion matters, but in all of my class the *-Header.h inclusion is the last one. What could be the problem and how to fix it?

A: In fact this time it was right even if the error reporting is sadistic. I had capitalized the class to adopt the Apple suggestion notation expecting the compiler to guide me in the renaming; instead all references to the old name, rather than reporting a normal error consequent to a missing class, reported that funny error taking very far away.
Yet now I get an even funnier error on the alloc operations:

No known class method for selector 'alloc'

... that weird component...!

A: This one is fixed by remembering to inherit from NSObject in the Swift class. In brief the lesson is to be absolutely not creative when porting classes to Swift, at least when not yet experienced, as the error messaging is misleading, to say the least.


text:
Q: how to convert mysql TIMESTAMPDIFF to oraclesql query TIMESTAMPDIFF(HOUR, pk.consprtydate, rs.consprtydate)
wanted the difference of hours from two dates and extract the hours in oracle sql

A: In oracle, you can easily achieve it by substracting two date fields as following:
Date2 - Date1  -- returns number of days between dates
(Date2 - Date1)/24 -- returns number of days between dates
MONTHS_BETWEEN(Date1, Date2) -- returns number of months between dates

Cheers!!

A: It depends on the datatype. IF they are of Oracle type TIMESTAMP, then follow the methods already answered here
If they are of type date, then - as said by Tejash- simple subtraction gives the difference in days that you would then need to round to hours. (integer portion will be days = 24 hours, and the decimal portion will be in fractions of a day)
e.g.) to round down to the integer number of hours without a fractional part:
(days * 24 hours, plus the fraction of a day * 86400 seconds in a day / 3600 seconds in an hour)
SELECT   trunc(date1 - date2) * 24    +  trunc((mod (date1-date2,1) * 86400) / 3600)
FROM DUAL


text:
Q: Passing variables to template on class creation inside IntelliJ Plugin I am creating a Java class inside an IntelliJ plugin using:
new JavaDirectoryServiceImpl().createClass(directory, className, templateName);

I would like to pass parameters that are used within the template. how can i do so?

A: new JavaDirectoryServiceImpl() is absolutely not intended for use by plugin developers. The correct way to create a file from template with parameters is FileTemplateUtil.createFromTemplate().


text:
Q: Error al trabajar con foreach Buenas tardes, al tratar de traer imágenes de la base de datos la página me manda los siguientes errores:

Notice: Undefined variable: fotos in C:\xampp\htdocs\proyectoCarrito2\views\index.view.php on line 72
  Warning: Invalid argument supplied for foreach() in
  C:\xampp\htdocs\proyectoCarrito2\views\index.view.php on line 72

En la parte del index.php tengo el siguiente código:
    <?php

session_start();
if(empty($_SESSION['idUsuario']) && empty($_SESSION['Tipo'])){
    include 'conexion.php';
    include 'views/index.view.php';

    $fotos_por_pagina = 16;

    $pagina_actual = (isset($_GET['p']) ? (int)$_GET['p'] : 1);
    $inicio = ($pagina_actual > 1) ? $pagina_actual * $fotos_por_pagina - $fotos_por_pagina : 0;

    $conexion = conexion('proyecto', 'root', '');

    if (!$conexion) {
        die();
    }

    $statement = $conexion->prepare("
        SELECT SQL_CALC_FOUND_ROWS * FROM timagen LIMIT $inicio, $fotos_por_pagina
    ");

    $statement->execute();
    $fotos = $statement->fetchAll();

    if (!$fotos) {
        header('Location: index.php');
    }

    $statement = $conexion->prepare("SELECT FOUND_ROWS() as total_filas");
    $statement->execute();
    $total_post = $statement->fetch()['total_filas'];

    $total_paginas = ceil($total_post / $fotos_por_pagina);
}else{

header("Location: formularios/form_cliente.php");
}

?>

Y en la parte de la vista que es index.view.php tengo lo siguiente:

    <?php foreach($fotos as $foto):?>

        <a href="fotos.php?id=<?php echo $foto['idImagen']; ?>">
            <img src="images/bd<?php echo $foto['Imagen'] ?>" alt="<?php echo $foto['Descripcion'] ?>">

    <?php endforeach;?>

Espero puedan ayudarme. Gracias.

A: Mira en tu código HTML la sentencia foreach tienes mal; para una sola instrucción:
foreach (expresión_array as $valor)
   sentencia

o
foreach (expresión_array as $clave => $valor)
   sentencia

para varias instrucciones
foreach (expresión_array as $valor) {
   sentencia1
   sentencia2
   sentencia3
   ...
   sentenciaN
}

o
foreach (expresión_array as $clave => $valor) {
   sentencia1
   sentencia2
   sentencia3
   ...
   sentenciaN
}

Para los casos <?php echo CADENAoVALOR ?> y similares te sugiero <?= CADENAoVALOR ?>; es una sola instrucción que usas el echo.
foreach en PHP

A: Lo único que hice fue poner el include del archivo, al final de mi código y se soluciono, en vez de el código anterior lo cambie por lo siguiente:
    <?php

session_start();
if(empty($_SESSION['idUsuario']) && empty($_SESSION['Tipo'])){
    include 'conexion.php';

    $fotos_por_pagina = 16;

    $pagina_actual = (isset($_GET['p']) ? (int)$_GET['p'] : 1);
    $inicio = ($pagina_actual > 1) ? $pagina_actual * $fotos_por_pagina - $fotos_por_pagina : 0;

    $conexion = conexion('proyecto', 'root', '');

    if (!$conexion) {
        die();
    }

    $statement = $conexion->prepare("
        SELECT SQL_CALC_FOUND_ROWS * FROM timagen LIMIT $inicio, $fotos_por_pagina
    ");

    $statement->execute();
    $fotos = $statement->fetchAll();

    if (!$fotos) {
        header('Location: index.php');
    }

    $statement = $conexion->prepare("SELECT FOUND_ROWS() as total_filas");
    $statement->execute();
    $total_post = $statement->fetch()['total_filas'];

    $total_paginas = ceil($total_post / $fotos_por_pagina);

include 'views/index.view.php';
}else{

header("Location: formularios/form_cliente.php");
}

?>


text:
Q: Resize Image With Coordinate in CI I'm trying implementing crop image with coordinate. but the it doesn't success if for the coordinate. my code is :
function image_thumb($image_path, $height, $width, $x=0, $y=0)
{
    // Get the CodeIgniter super object
    $CI =& get_instance();

    // Path to image thumbnail
    $image_thumb = dirname($image_path) . '/' . $height . '_' . $width . '.jpg';

    if( ! file_exists($image_thumb))
    {
        // LOAD LIBRARY
        $CI->load->library('image_lib');

        // CONFIGURE IMAGE LIBRARY
        $config['x_axis']            = $x;
        $config['y_axis']             = $y;
        $config['image_library']    = 'gd2';
        $config['source_image']        = $image_path;
        $config['new_image']        = $image_thumb;
        $config['maintain_ratio']    = TRUE;
        $config['height']            = $height;
        $config['width']            = $width;
        $CI->image_lib->initialize($config);
        $CI->image_lib->resize();
        $CI->image_lib->clear();
    }

    return '';
}

Help me please ...

A: Maybe it's because you are not using the right function...
$CI->image_lib->resize();

Don't you mean crop()?
$CI->image_lib->crop();

I hate saying this, but RTM.

Here is a function that can crop and resize simultaneously:
function ImageCR($source, $crop = null, $scale = null, $destination = null)
{
    $source = @ImageCreateFromString(@file_get_contents($source));

    if (is_resource($source) === true)
    {
        $size = array(ImageSX($source), ImageSY($source));

        if (isset($crop) === true)
        {
            $crop = array_filter(explode('/', $crop), 'is_numeric');

            if (count($crop) == 2)
            {
                $crop = array($size[0] / $size[1], $crop[0] / $crop[1]);

                if ($crop[0] > $crop[1])
                {
                    $size[0] = $size[1] * $crop[1];
                }

                else if ($crop[0] < $crop[1])
                {
                    $size[1] = $size[0] / $crop[1];
                }

                $crop = array(ImageSX($source) - $size[0], ImageSY($source) - $size[1]);
            }

            else
            {
                $crop = array(0, 0);
            }
        }

        else
        {
            $crop = array(0, 0);
        }

        if (isset($scale) === true)
        {
            $scale = array_filter(explode('*', $scale), 'is_numeric');

            if (count($scale) >= 1)
            {
                if (empty($scale[0]) === true)
                {
                    $scale[0] = $scale[1] * $size[0] / $size[1];
                }

                else if (empty($scale[1]) === true)
                {
                    $scale[1] = $scale[0] * $size[1] / $size[0];
                }
            }

            else
            {
                $scale = array($size[0], $size[1]);
            }
        }

        else
        {
            $scale = array($size[0], $size[1]);
        }

        $result = ImageCreateTrueColor($scale[0], $scale[1]);

        if (is_resource($result) === true)
        {
            ImageFill($result, 0, 0, IMG_COLOR_TRANSPARENT);
            ImageSaveAlpha($result, true);
            ImageAlphaBlending($result, true);

            if (ImageCopyResampled($result, $source, 0, 0, $crop[0] / 2, $crop[1] / 2, $scale[0], $scale[1], $size[0], $size[1]) === true)
            {
                if (preg_match('~gif$~i', $destination) >= 1)
                {
                    return ImageGIF($result, $destination);
                }

                else if (preg_match('~png$~i', $destination) >= 1)
                {
                    return ImagePNG($result, $destination, 9);
                }

                else if (preg_match('~jpe?g$~i', $destination) >= 1)
                {
                    return ImageJPEG($result, $destination, 90);
                }
            }
        }
    }

    return false;
}

Use it like this:
// resize to 400x400 px
ImageCR('path/to/sourceImg.jpg', null, '400*400', 'path/to/outputImg.jpg');

// crop to a 1:1 ratio (square) from the center
ImageCR('path/to/sourceImg.jpg', '1/1', null, 'path/to/outputImg.jpg');

// crop to a 1:1 ratio (square) from the center AND resize to 400x400 px
ImageCR('path/to/sourceImg.jpg', '1/1', '400*400', 'path/to/outputImg.jpg');

// crop to a 1:1 ratio (square) from the center AND resize to 400 px width AND maintain aspect ratio
ImageCR('path/to/sourceImg.jpg', '1/1', '400*', 'path/to/outputImg.jpg');

// crop to a 1:1 ratio (square) from the center AND resize to 400 px height AND maintain aspect ratio
ImageCR('path/to/sourceImg.jpg', '1/1', '*400', 'path/to/outputImg.jpg');

Play arround with the options, if you have any doubt just let me know.

A: I've got the answer. image_lib doesnt support crop and resize simultaneously. SO i must make some modification of the code.
/**
     * Image Process Using GD/GD2
     *
     * This function will resize or crop
     *
     * @access  public
     * @param   string
     * @return  bool
     */
    function image_process_gd($action = 'resize', $org_w = 0, $org_h = 0)
    {
        $v2_override = FALSE;
        // If the target width/height match the source, AND if the new file name is not equal to the old file name
        // we'll simply make a copy of the original with the new name... assuming dynamic rendering is off.
        if ($this->dynamic_output === FALSE)
        {
            if ($this->orig_width == $this->width AND $this->orig_height == $this->height)
            {
                if ($this->source_image != $this->new_image)
                {
                    if (@copy($this->full_src_path, $this->full_dst_path))
                    {
                        @chmod($this->full_dst_path, DIR_WRITE_MODE);
                    }
                }

                return TRUE;
            }
        }

        // Let's set up our values based on the action
        if ($action == 'crop')
        {
            //  Reassign the source width/height if cropping
            $this->orig_width  = $this->width;
            $this->orig_height = $this->height;

            // GD 2.0 has a cropping bug so we'll test for it
            if ($this->gd_version() !== FALSE)
            {
                $gd_version = str_replace('0', '', $this->gd_version());
                $v2_override = ($gd_version == 2) ? TRUE : FALSE;
            }
        }
        else if ($action == 'resize')
        {
            // If resizing the x/y axis must be zero
            $this->x_axis = 0;
            $this->y_axis = 0;
        } else {
            $this->orig_width  = $org_w;
            $this->orig_height = $org_h;
        }

        //  Create the image handle
        if ( ! ($src_img = $this->image_create_gd()))
        {
            return FALSE;
        }

        //  Create The Image
        //
        //  old conditional which users report cause problems with shared GD libs who report themselves as "2.0 or greater"
        //  it appears that this is no longer the issue that it was in 2004, so we've removed it, retaining it in the comment
        //  below should that ever prove inaccurate.
        //
        //  if ($this->image_library == 'gd2' AND function_exists('imagecreatetruecolor') AND $v2_override == FALSE)
        if ($this->image_library == 'gd2' AND function_exists('imagecreatetruecolor'))
        {
            $create = 'imagecreatetruecolor';
            $copy   = 'imagecopyresampled';
        }
        else
        {
            $create = 'imagecreate';
            $copy   = 'imagecopyresized';
        }

        /*echo '
 Coordinate' . $this->x_axis . " x " . $this->y_axis;
        echo '
 Destination size' .$this->width . " x " . $this->height;
        echo '
 Originl Size' . $this->orig_width. " x " . $this->orig_height;*/
        $dst_img = $create($this->width, $this->height);
        $copy($dst_img, $src_img, 0, 0, $this->x_axis, $this->y_axis, $this->width, $this->height, $this->orig_width, $this->orig_height);

        //  Show the image
        if ($this->dynamic_output == TRUE)
        {
            $this->image_display_gd($dst_img);
        }
        else
        {
            // Or save it
            if ( ! $this->image_save_gd($dst_img))
            {
                return FALSE;
            }
        }

        //  Kill the file handles
        imagedestroy($dst_img);
        imagedestroy($src_img);

        // Set the file to 777
        @chmod($this->full_dst_path, DIR_WRITE_MODE);

        return TRUE;
    }

invoke:
//set image library configuration
            $config['image_library']    = 'gd2';
            $config['source_image']     = $src_path;
            $config['new_image']        = $des_path;
            $config['maintain_ratio']   = FALSE;
            $config['width']            = 150;
            $config['height']           = 150;
            $config['orig_width']       = $width;
            $config['orig_height']      = $height;
            $config['x_axis']           = $x;
            $config['y_axis']           = $y;
            $this->image_lib->initialize($config);

            //process thumb and reset the original with and height
            $this->image_lib->image_process_gd('thumb', $width, $height);


text:
Q: Error in integrating inmobi sdk in main.xml here is my xml error report
    The following classes could not be instantiated:
- com.inmobi.androidsdk.IMAdView (Open Class, Show Error Log)
See the Error Log (Window > Show View) for more details.
Tip: Use View.isInEditMode() in your custom views to skip code when shown in Eclipse

and code of main.xml is like this
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<com.inmobi.androidsdk.IMAdView
    android:id="@+id/imAdview"
    android:layout_width="320dp"
    android:layout_height="50dp"
    android:layout_alignParentBottom="true"
    adSize="15"
    appId="a521d7b121144753a4709e018826c487" />

Didn't get issue here ,why i am getting this error ,suggest some solution.
Thanks

A: Please use the following code in your xml
<com.inmobi.monetization.IMBanner android:layout_width="320dp"
android:layout_height="50dp" android:id="@+id/banner"
adSize="15" appId="YOUR-APP-ID" />
The code you are using is from the old integration guidelines. This will not work for the latest InMobi sdk. For more details please check https://www.inmobi.com/support/integration/23817448/22051163/android-sdk-integration-guide/


text:
Q: Does "All additive functions are linear" imply every set of reals has the Baire property? This is a follow-up to my previous question. In that question, I asked whether "All additive functions are linear" imply every set of reals is measurable. The answer is no. So, a natural follow-up is, does "All additive functions are linear" imply every set of reals has the Baire property? Just to be clear, the background theory is ZF set theory without the axiom of choice.

A: No. It follows from "Every set of reals is Lebesgue measurable", which is known by the work of Shelah to be independent from the Baire proprety. This was shown by Shelah to be consistent in his paper

Shelah, Saharon, On measure and category, Isr. J. Math. 52, 110-114 (1985). ZBL0602.03013.

It's almost the same proofs as those that show that the Baire property implies continuity also work for Lebesgue measurability, and I am guessing they will also work for a number of other properties which may very well be independent as well.


text:
Q: error: file ./boot' not found, after installing Ubuntu 20.04 on an external SSD I've decided recently to install Ubuntu on an external SSD. I want to use it as a "work OS" that I could plug anywhere.
After some research, I found that with usb 3.0 throughput, there are no problems running an OS from an external drive.
I have also found this recent guide to install a portable ubuntu on an external drive.
I've managed to install ubuntu 20.04 (rather than 19.10 in his tutorial) which works quite well but is bound to the computer where I installed it.
So in order to manage this issue, while being on a "Try ubuntu" thumb drive session, they describe how to mount the external device with the fresh ubuntu install, to change the mount points in /mnt/etc/fstab and to chroot in it for installing grub on the efs partition. (If you wanna check, part E of his guide)
The problem is that I have followed each steps carefully 3 times, but when I boot on this device with another computer that only has a W10 on it, my screen freezes with this error: error: file ./boot' not found. I have checked on my SSD and the /boot/* directory does exist.
The message on my screen when I boot on the external SSD
I have tried different arguments with grub-install but nothing seems to change.
Do you have any ideas as to why another computer couldn't find the grub installation on my SSD?


text:
Q: Remove the word Kapitel (chapter) from the header I want to remove the word Kapitel (chapter) from the header. I want to display only the number of the chapter and the name.
main.tex
\documentclass[12pt]{report}
\usepackage[a4paper, left={2.5cm}, right={2cm}, top={3cm}, bottom={3cm}, headheight=15pt]{geometry}
\usepackage[ngerman]{babel}
\usepackage[utf8]{inputenc}
\usepackage{blindtext}
\usepackage{titlesec}

\titleformat{\chapter}
  {\normalfont\LARGE\bfseries}{\thechapter}{1em}{}
\titlespacing*{\chapter}{0pt}{-10pt}{40pt}

\input{vorlage.tex}

\usepackage{fancyhdr}
\usepackage{lipsum}% just to generate text for the example

\fancypagestyle{plain}{%
  \fancyhf{}%
  \fancyhead[L]{\nouppercase{\leftmark}}%
  \fancyfoot[R]{\thepage}}
\pagestyle{plain}

\begin{document}

%% TITLESEITE %%
 \Title
      {Test1}
      {Test2}
      {xy}
      {zz}
      {zz}
      {test}
      {test}
      {17. Oktober 2021}
\clearpage
%% INHALT %%

\pagenumbering{roman}
\chapter*{\abstractname}
\addcontentsline{toc}{chapter}{\abstractname}
\markboth{\abstractname}{}
\newpage
\tableofcontents
\clearpage
%% TEXT %%
\pagenumbering{arabic}
\blinddocument

\blinddocument

\end{document}

vorlage.txt
\newcommand{\Title}[8]{

\begin{titlepage}

        \normalfont \normalsize
        \newcommand{\HRule}{\rule{\linewidth}{0.5mm}}

        \center
        \includegraphics[width=2.5in]{img/hft.png} \\[4ex]
        {\LARGE \textsc{Title}} \\[4ex]
        {\Large #1 #2}\\
           \vspace*{8ex}
        \HRule \\[0.4cm]
        { \huge \bfseries #3}\\[0.4cm]
        \HRule \\[1.5cm]
          \vspace*{8ex}
        {\Large #4\\
                #5\\}

    \vspace*{16ex}
    \begin{flushleft}
        {\large
        Betreuung: \\
        #6 \\
        #7 \\
        \vspace*{4ex}
        #8 \\}
    \end{flushleft}

    \end{titlepage}

}

What I have

What I want

What I got with @PietervanOostrum
\fancypagestyle{plain}{%
  \fancyhf{}%
  \fancyhead[L]{\nouppercase{\leftmark}}%
  \fancyfoot[R]{\thepage}}
\pagestyle{plain}
\renewcommand{\chaptermark}[1]{\markboth{\thechapter. #1}}


text:
Q: Android. How to resize window to make room for view when keyboard already showing? I have screen with search view at the top and RecyclerView (parent is ScrollView). When search result is empty I'm showing TextView with text "Nothing found". The problem is that the text is covered by the keyboard. I'm using ADJUST_RESIZE and when the keyboard rises the content is resized so that the text is visible on the screen and not hidden behind the keyboard.
But I have a slightly different case, when the keyboard is already visible, but there is no TextView, but then at the end of the search, if nothing is found, I show the TextView.
And in this case, the screen is no longer resized. Is it possible to initiate a screen resize in such a way that the TextView rises above the keyboard and becomes visible? And will such an operation be resource-intensive?
Please, help me.


text:
Q: Best practice for consent page for authorization code flow with IdentityServer4? I am having a microservice system with backend and frontend hosted on different servers. To authorize and authenticate a user in my frontend app I use 'Resource Owner Password Credentials' flow to obtain an access token (since frontent app is trusted).
Now I want to implement authorization code flow to give permissions to 3rd party apps to act on the user's behalf. To do it, I need the login page and the consent page.
In default examples for IdentityServer4 for this flow, views for login and consent pages are returned by identity server itself (and, maybe, it even use session cookies between login page and consent page).
Since my frontent app is fully trusted, how could I have login and consent screens in this app to reduce duplication?
Maybe, I could make endpoint in identity server to issue the token for the third party app, given that user has access token obtained in trusted frontend app?


text:
Q: HtmlHelper on ActionLink in Razor I use MVC3 Razor and have a link
Edit

I have written HtmlHelper
public static MvcHtmlString MyHelper(this HtmlHelper helper, string name, string href, string @class = null)
        {
            var builder = new TagBuilder("a");
            builder.MergeAttribute("href", href);
            builder.AddCssClass(@class);
            builder.InnerHtml = name;
            return new MvcHtmlString(builder.ToString());
        }

and this link is bad
@Html.MyHelper("Edit","@Url.Action('Edit', 'Obj', new { id = RSAuth.UserId })", "gray-butt right")

A: Can you try this?
@Html.MyHelper("Edit",Url.Action('Edit', 'Obj', new { id = RSAuth.UserId }), "gray-butt right")

remove the quote for Url.Action, because it is a function that return a string


text:
Q: Magento cron not running properly.any other methods For some strange reason my cron jobs are not running anymore the last in magento 2.3.4 cron jobs on the server are running well without any problems.But after some time cron not running.Can you help me to running without any delay.

A: kindly check your db when its last time triggered using this query and check  your sytem log and exception log  to get what problem occurs which causes its stoppage:
SELECT * FROM cron_schedule ORDER BY  schedule_id DESC LIMIT 1

OR:
you can run the cron by command:
php bin/magento cron:run


text:
Q: How to check if a proto has the same filename as another in the entire schema with buf linter/breaking change detector? I would like to know if it's possible to check if two protos in my entire schema have the same filename with buf linter/breaking change detector rules. This may be interesting to me for preventing future issues on my project.
For example, if I have:
syntax = "proto3";

package example.protos.foo;

option csharp_namespace = "Example.Modules.Foo";
option objc_class_prefix = "CMS";

message Foo {
  // My foo_id.
  string foo_id = 1;
  // My string example filed.
  string foo_string = 2;
}

And another proto with same filename and another package:
syntax = "proto3";

package example.protos.bar

option csharp_namespace = "Example.Modules.Foo";
option objc_class_prefix = "CMS";

message Foo {
  // My foo id.
  string foo_id = 1;
  // Example string field.
  string bar_string = 2;
}

It's possible to prevent this in generation protos time?
I couldn't find a rule to prevent this in the defined linter and breaking change detector rules provided by documentation.


text:
Q: Tornado/Python error unable to comprehend I got a simple piece of code for playing around with the addition/subtraction of date/
def calculate(self, datemonthyear, add): #not handled the condition for years between 00 and 09.
        year = datemonthyear % 100
        datemonthyear = datemonthyear / 100
        date = datemonthyear % 100
        month = datemonthyear / 100
        leapyear = (year % 4 == 0 or year==0)
        print month
        print date
        print year
        print ((leapyear and date + add > 29) or (not(leapyear) and date + add > 28))
        if (month == 2 and ((leapyear and date + add > 29) or (not(leapyear) and date + add > 28))):
            print "1"
            return "301" + str(year)
        elif month == 3 and leapyear and date + add < 1:
            print "2"
            return "229" + str(year)
        elif month == 3 and not(leapyear) and date + add < 1:
            print "3"
            return "228" + str(year)
        elif month in [1,3,5,7,8,10,12]:
            print "4"
            if month == 12 and date + add > 31:
                return "101" + str((year + 1)%100)
            elif month == 1 and date + add < 1:
                return "1231" + str((year - 1)%100)
            elif month == 8 and date + add < 1:
                return "731" + str(year)
            elif date + add > 31:
                return str(month + 1) + "01" + str(year)
            elif date + add < 1:
                return str(month - 1) + "30" + str(year)
        elif month in [2,4,6,9,11]:
            print "5"
            if date + add > 30:
                return str(month + 1) + "01" + str(year)
            elif date + add < 1:
                return str (month -1) + "31" + str(year)
        print "Has to come here"
        return str(month) + str(date + add) + str(year)

When i call
print "22820 " + self.calculate(22820, 1)

It throws up this error
E 120731 15:27:04 web:1064] Uncaught exception GET / (::1)
    HTTPRequest(protocol='http', host='localhost:8881', method='GET', uri='/', version='HTTP/1.1', remote_ip='::1', body='', headers={'Accept-Language': 'en-US,en;q=0.8', 'Accept-Encoding': 'gzip,deflate,sdch', 'Host': 'localhost:8881', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.151 Safari/535.19', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Connection': 'keep-alive', 'Cookie': '_xsrf=2328f244ddf94402884f39490aeed347', 'Cache-Control': 'max-age=0'})
    Traceback (most recent call last):
      File "/Library/Python/2.7/site-packages/tornado-2.3-py2.7.egg/tornado/web.py", line 1021, in _execute
        getattr(self, self.request.method.lower())(*args, **kwargs)
      File "trends.py", line 33, in get
        print "22820 " + self.calculate(22820, 1)
    TypeError: cannot concatenate 'str' and 'NoneType' objects

This basically means calculate is returning None but I am not able to debug it

A: The quick answer is that when month == 0 you miss all of the if statements and end up in the default return case for the function with is the value None.  You cannot concatenate a  string with the None value.

A: Some observations that were too long for a comment:
I just want to confirm that this statement:
print "22820 " + self.calculate(22820, 1)
Needs to be called from within a method of the same class where you have calculate defined, and that the calling method, needs to be called from an instance of that class.
not is not a function, so not(foo) doesn't make any sense - unless you have your own version of a function called not, in which case you should rename it.


text:
Q: Read content of external script tag with jquery A common pattern for loading backbone templates is something like:
<script type='text/template' id='foo'>
    my template
</script>

----
var whatever = $('#foo').html();

I would like to include the script in an external file like so:
<script type='text/template' id='foo' src='myTemplate.tpl'></script>

But the html() of foo is now empty.
I watched the browser pull the template file down, but I am not sure if it is in the page dom or not. Is there a simple way to reference the content of the script in javascript, or did the browser simply ignore it and throw out the result?

A: I think to actually execute externally loaded script you have to do an eval() of the contents. You're not adding it to the DOM really since it's script, you're adding it to the JS runtime. There might be other ways of doing it but eval() is generally considered a security hole since malicious code could be evaluated.
What I tend to do is generate template sections on the server so I know all my JS is there when the DOM is ready.

A: If the point is execute an action just after the script has been loaded you can put a onload attribute on the script tag. If you want to download the content in runtime, then you could use the async download strategy (like Gats pointed).
It´s important keep in mind some important points when using templates for jquery templates in external files, there is an interesting article about jquery templates with external files, you must check it.


text:
Q: android:media controller I am playing the video in activity,I need to show/hide the topbar view along with media controller.so when media controller is in screen at that my top view should be visible and when the media controller hide ,my top view should be invisible.
  Can anyone tell me if there any listener is there in android.
  i have try with onTouch
private OnTouchListener mTouchListener = new OnTouchListener() {
         public boolean onTouch(View v, MotionEvent event) {

                   if(v.getVisibility()==View.VISIBLE){
                       Log.d("TOUCH","ok");
                   }else{
                       Log.d("TOUCH","NO");
                   }
}

But the it is not working perfectly.
Thank you.

A: I have done this using the inherite media controller class inside the my activity using this code,
class MyMedia extends MediaController{

        public MyMedia(Context context) {
            super(context);
       }

      @Override
     public void show() {
          super.show();
          topbar.setVisibility(View.VISIBLE);

    }

     @Override
    public void hide() {
         super.hide();
         topbar.setVisibility(View.GONE);

    }

Thank you.

A: This might help to hide the media controller if mediacontroller.hide didn't work
    VideoView videoHolder = new VideoView(contex);
    MediaController controller=new MediaController(this);
    controller.hide();
    controller.setVisibility(View.GONE);
    videoHolder.setMediaController(controller);


text:
Q: How to update only modified values (EntityFramework 5.0)? I have this entity, want to update using entityframework
 EmployeeModel employee = new EmployeeModel
    {
        Id = 1000, //This one must
        FirstName = modifiedValue,
        Email = modifiedValue,
        LastName = originalValue,
        Phone = originalValue
    };

Code to update
_db.ObjectStateManager.ChangeObjectState(employee, EntityState.Modified);
_db.SaveChanges();

This is the SQL statement got once updated
Update Employee set Id=1138,FirstName='modifiedValue',Email='modifiedValue',LastName= 'OriginalValue',phone='originalValue' where Id=1138

But I am expecting this
Update Employee set FirstName='modifiedValue', Email='modifiedValue' where Id=1138.

I dont know what I am missing here. Please let me know.

A: This is the solution I got
 var entity = _db.CreateObjectSet<Employee>();
 entity.Detach(employee);
 entity.Attach(employee);

 foreach (string modifiedPro in employeeModel.ModifiedProperties){
  _db.ObjectStateManager.GetObjectStateEntry(employee).SetModifiedProperty(modifiedPro);}

  _db.SaveChanges();

Only modified values in the sql update statement
Update Employee set FirstName='modifiedValue', Email='modifiedValue' where Id=1138.

If anybody knows better answer than this, Please post your suggestions

A: This problem is common when dealing with DTOs. An employee entity is fetched from the database, mapped to a DTO and sent over the wire. The client then modifies this DTO and sends it back to the server.
When you touch (set) a property on an EF entity, EF will assume that the value has been changed. Even if the old value and the new value are exactly the same.
The same problem occurs when you map the DTO to a new Entity and attach it to EF and updating its status to 'Modified'.
Using AutoMapper:
// This will result in the full update statement
var employee = AutoMapper.Mapper.Map<EmployeeDto, Employee>(dto);

// This will result in a smaller update statement (only actual changes)
var employee = dbContext.Employees.Find(dto.Id);
AutoMapper.Mapper.Map(dto, employee);

Or, manually (I would avoid doing this, but just for the sake of completeness):
// This will result in a smaller update statement (only actual changes)
var employee = dbContext.Employees.Find(dto.Id);
if (employee.Email != dto.Email )
    employee.Email = dto.Email;

There are probably some other ways for dealing with this problem... but using AutoMapper together with Entity Framework correctly is definitely one of the easiest ways.

A: You can try this way
public update(Person model)
{
    // Here model is model return from form on post
    var oldobj = db.Person.where(x=>x.ID = model.ID).SingleOrDefault();

    var UpdatedObj = (Person) Entity.CheckUpdateObject(oldobj, model);

    db.Entry(oldobj).CurrentValues.SetValues(UpdatedObj);
}

public static object CheckUpdateObject(object originalObj, object updateObj)
{
   foreach (var property in updateObj.GetType().GetProperties())
   {
      if (property.GetValue(updateObj, null) == null)
      {
         property.SetValue(updateObj,originalObj.GetType().GetProperty(property.Name)
         .GetValue(originalObj, null));
      }
   }
   return updateObj;
}


text:
Q: How to reference a requirements.txt in the pyproject.toml of a setuptools project? I'm trying to migrate a setuptools-based project from the legacy setup.py towards modern pyproject.toml configuration.
At the same time I want to keep well established workflows based on pip-compile, i.e., a requirements.in that gets compiled to a requirements.txt (for end-user / non-library projects of course). This has important benefits as a result of the full transparency:

*

*100% reproducible installs due to pinning the full transitive closure of dependencies.

*better understanding of dependency conflicts in the transitive closure of dependencies.

For this reason I don't want to maintain the dependencies directly inside the pyproject.toml via a dependencies = [] list, but rather externally in the pip-compiled managed requirements.txt.
This makes me wonder: Is there a way to reference a requirements.txt file in the pyproject.toml configuration, without having to fallback to a setup.py script?

A: Use dynamic metadata:
[project]
dynamic = ["dependencies"]
[tool.setuptools.dynamic]
dependencies = {file = ["requirements.txt"]}


text:
Q: Ring theory - irreducibility and primes Let $D$ be an integral domain and let $a\in D$. Suppose that every pair of elements $a,b\in D$ (not both zero) have a $\gcd c$ such that $c=as+bt$ for some $s,t\in D$. Prove that if $d\in D$ is irreducible then it is prime.
I know that in a PID we have an element is irreducible iff it is prime, but I can't see how to use this in this example. I thought initially we could assume $d$ to be irreducible, with $d=ab$ so that $a$ or $b$ must be $1$ by definition of irreducibility. We require $c=1$ for primality but there doesn't seem to be an easy way of proving this.


text:
Q: Two Databases with LINQ - Compilation errors in generated code I have added LINQ-to-SQL classes to two different databases in a single VB.Net project. But doing this as created numerous compilation errors in the generated code.
In the file FirstDB.designer.vb the errors are:-
2 of: 'Protected Overridable Sub SendPropertyChanged(propertyName As String)' has multiple definitions with identical signatures.
2 of: 'Protected Overridable Sub SendPropertyChanging()' has multiple definitions with identical signatures.
2 of: 'Public Sub New()' has multiple definitions with identical signatures.

In the file SecondDB.designer.vb the errors are:-
2 of: 'emptyChangingEventArgs' is already declared as 'Private Shared emptyChangingEventArgs As System.ComponentModel.PropertyChangingEventArgs' in this class.
2 of: 'PropertyChanged' is already declared as 'Public Event PropertyChanged(sender As Object, e As System.ComponentModel.PropertyChangedEventArgs)' in this class.
2 of: 'PropertyChanging' is already declared as 'Public Event PropertyChanging(sender As Object, e As System.ComponentModel.PropertyChangingEventArgs)' in this class.
2 of: Attribute 'TableAttribute' cannot be applied multiple times.
2 of: Method 'OnCreated' cannot be declared 'Partial' because only one method 'OnCreated' can be marked 'Partial'.
2 of: Method 'OnLoaded' cannot be declared 'Partial' because only one method 'OnLoaded' can be marked 'Partial'.
2 of: Method 'OnValidate' cannot be declared 'Partial' because only one method 'OnValidate' can be marked 'Partial'.

These errors appear in the error list immediately after I save the tables in the second class. I have tried recreating both classes from scratch, and I have tried qualifying all the table names with the database name this:-
FirstDB.dbo.mytable
SecondDB.dbo.mytable

in the properties before saving the class; there are some table names common to both databases but I believe I have qualified all of them.
Does anyone know what is causing this and what to do about it? I could in principle edit the generated files, but that seems like a large number of changes to make that could disappear at any time.

A: Since asking this question I have found that including the classes for the two databases in two separate projects has cured the problem. I don't know what effect this would have if I attempted a Linq-to-SQL query involving both databases, but I have no plans to do that.


text:
Q: How could patch method in Rails update only some attributes while the other attributes are blank? I have these questions while reading the Ruby On Rails Tutorial in
here
The validation of User class is:
class User < ActiveRecord::Base
   before_save { self.email = email.downcase }
   validates :name, presence: true, length: { maximum: 50 }
   VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
   validates :email, presence: true, length: { maximum: 255 }
              format: { with: VALID_EMAIL_REGEX },
              uniqueness: { case_sensitive: false }
   has_secure_password
   validates :password, length: { minimum: 6 }, allow_blank: true
   .
   .
   .
end

In test,while patching a updated user information to the route of the user like this:
def setup
  @user = users(:michael)
end
.
.
.
test "successful edit" do
  get edit_user_path(@user)
  assert_template 'users/edit'
  name  = "Foo Bar"
  email = "foo@bar.com"
  patch user_path(@user), user: { name:  name,
                                email: email,
                                password:              "",
                                password_confirmation: "" }
  assert_not flash.empty?
  assert_redirected_to @user
  @user.reload
  assert_equal name,  @user.name
  email, @user.email
end

The test would pass and only the user's name and email would be updated and password won't change.
If the validation of the password doesn't include the "allow_blank:true",this test would fail.
So I don't understand that: When the test passed which means the password could be blank, why it wouldn't change the password to be blank? How could Rails know I just want to update some of the attributes?

A: has_secure_password adds a  password= setter method method to your model which discards empty? input when setting the password.
irb(main):012:0> "".empty?
=> true

This prevents users from choosing a blank password. If you dont want to take my word for it you can easily test this:
test "does not change password to empty string" do
  patch user_path(@user), user: { name:  name,
                                  email: email,
                                  password:              "",
                                  password_confirmation: "" }
  @user.reload
  assert_false @user.authenticate("")
end

However what your validation does do is that if the user sets a password it must be over 6 characters:
test "does not allow a password less than 6 characters" do
  patch user_path(@user), user: { name:  name,
                                  email: email,
                                  password:              "abc",
                                  password_confirmation: "abc" }
  assert assigns(:user).errors.key?(:password)
end

(PS. this is something that is better tested in a model test than a controller test)


text:
Q: Syntax error: Non-declaration statement outside function body, but everything there is declaration This doesn't work:
package main

var formatter string = "fmt"

import (
    formatter
)

func main() {
    fmt.Println(formatter)
}

I got: syntax error: non-declaration statement outside function body
Even though everything there is declaration.

A: Per the Go specification:

Each source file consists of a package clause defining the package to
which it belongs, followed by a possibly empty set of import
declarations that declare packages whose contents it wishes to use,
followed by a possibly empty set of declarations of functions, types,
variables, and constants.
SourceFile       = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } .

This means that top-level declarations such as var formatter string = "fmt"  must come after any import declarations, if any import declarations are present. Technically, you're getting this error because the definition of declaration does not include import declarations (despite the name), and your source code has an import declaration after a top-level declaration, where an import declaration is not allowed to be.
Furthermore, the Import declarations section shows that import paths must be string literals, so even if it weren't for the ordering issue, you still wouldn't be able to do what you're attempting.


text:
Q: Cannot create an android sql database with more than 2 columns I have searched as much as I could and cannot find any help. I was to create a database with obviously more than 2 columns. Is there anywhere someone can point me to a source to help me out. Also should I use a different database for performance.
The error message I get is:
CursorWindow Bad request for field slot 0,2. numRows = 3. numColumns = 2
@Override
public void onCreate(SQLiteDatabase db) {
    String sql = String
            .format("CREATE TABLE %s (%s INTEGER PRIMARY KEY, %s INTEGER NOT NULL, %s TEXT NOT NULL, %s INTEGER NOT NULL, %s INTEGER NOT NULL, %s INTEGER NOT NULL, %s INTEGER NOT NULL, %s INTEGER NOT NULL, %s INTEGER NOT NULL, %s INTEGER NOT NULL, %s INTEGER NOT NULL, %s INTEGER NOT NULL, %s REAL NOT NULL, %s REAL NOT NULL, %s REAL NOT NULL, %s REAL NOT NULL, %s INTEGER NOT NULL, %s INTEGER NOT NULL, %s INTEGER NOT NULL, %s INTEGER NOT NULL, %s INTEGER NOT NULL, %s INTEGER NOT NULL, %s INTEGER NOT NULL, %s INTEGER NOT NULL);",
                    EXERCISES_TABLE, COL_ID, EXERCISE_ID, NAME,
                    TYPE_OF_TRAINING, WEIGHT_BEST, SETS_BEST, REPS_BEST,
                    SETS, REPS, WEIGHT_GOAL, SETS_GOAL, REPS_GOAL,
                    DISTANCE, TIME, BEST_TIME, BEST_DISTANCE, BEST_DATE,
                    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
                    SATURDAY);

    db.execSQL(sql);
}

Also the way I am attempting to retrieve the data:
public List<Exercise> getExerciseList() {
    List<Exercise> retEx = new ArrayList<Exercise>();

    SQLiteDatabase db = getReadableDatabase();

    String sql = String.format("SELECT %s, %s FROM %s ORDER BY %s",
            EXERCISE_ID, SATURDAY, EXERCISES_TABLE, COL_ID);

    Cursor cursor = db.rawQuery(sql, null);

    while (cursor.moveToNext()) {
        int id = cursor.getInt(0);
        String name = cursor.getString(1);
        int typeOfTraining = cursor.getInt(2);
        int weightBest = cursor.getInt(3);
        int setsBest = cursor.getInt(4);
        int repsBest = cursor.getInt(5);
        int sets = cursor.getInt(6);
        int reps = cursor.getInt(7);
        int weightGoal = cursor.getInt(8);
        int setsGoal = cursor.getInt(9);
        int repsGoal = cursor.getInt(10);
        float distance = cursor.getFloat(11);
        float time = cursor.getFloat(12);
        float bestTime = cursor.getFloat(13);
        float bestDistance = cursor.getFloat(14);
        int bestDate = cursor.getInt(15);
        int sunday = cursor.getInt(16);
        int monday = cursor.getInt(17);
        int tuesday = cursor.getInt(18);
        int wednesday = cursor.getInt(19);
        int thursday = cursor.getInt(20);
        int friday = cursor.getInt(21);
        int saturday = cursor.getInt(22);

        retEx.add(new Exercise(name, weightBest, setsBest, repsBest, sets,
                reps, weightGoal, setsGoal, repsGoal, distance, time,
                bestTime, bestDistance, bestDate, typeOfTraining, id,
                sunday, monday, tuesday, wednesday, thursday, friday,
                saturday));
    }

    db.close();

    return retEx;
}

A: You are crating database with plenty of columns successfuly.
The way You select is a problem.
String sql = String.format("SELECT %s, %s FROM %s ORDER BY %s",
            EXERCISE_ID, SATURDAY, EXERCISES_TABLE, COL_ID);

This will crate query like this
SELECT EXERCISE_ID, SATURDAY FROM EXERCISES_TABLE ORDER BY COL_ID

You are selecting only 2 columns  EXERCISE_ID and SATURDAY.
But You expect Your result to have all columns.
String sql = String.format("SELECT * FROM %s ORDER BY %s",
                 EXERCISES_TABLE, COL_ID);

This should work ;]


text:
Q: How do I move the panel in Visual Studio Code to the right side? It's at the bottom by default.
For example in the following image ,panel(Section D) is at the bottom, instead I want it to move to the rightside i.e., in the area where README.md editior shown in Editor Groups(Section C).
Image Credits: (https://code.visualstudio.com/images/codebasics_hero.png)

A: As of October 2018 (version 1.29) the button in @mvvijesh's answer no longer exists.
You now have 2 options.
Right click the panel's toolbar (nowhere else on the panel will work) and choose "move panel right/bottom":

Or choose "View: Toggle Panel Position" from the command palette.
Source: VSCode update notes: https://code.visualstudio.com/updates/v1_29#_panel-position-button-to-context-menu

A: Hope this will help someone.
-> open to keyboard shortcut
-> search for "workbench.action.togglePanelPosition"
-> assign your desired shortcut
I've assigned keybinding "cmd+`"
{
  "key": "cmd+`",
  "command": "workbench.action.togglePanelPosition"
}

now I can toggle the terminal by pressing "cmd + `"

A: VSCode 1.42 (January 2020) introduces:

Panel on the left/right
The panel can now be moved to the left side of the editor with the setting:
"workbench.panel.defaultLocation": "left"

This removes the command View: Toggle Panel Position (workbench.action.togglePanelPosition) in favor of the following new commands:

*

*View: Move Panel Left (workbench.action.positionPanelLeft)

*View: Move Panel Right (workbench.action.positionPanelRight)

*View: Move Panel To Bottom (workbench.action.positionPanelBottom)

A: Click menu option View > Appearance > Move Side Bar Right or in settings.json:
"workbench.panel.defaultLocation": "right"

A: You can do the same in insider's edition, There is an option on right top corner to switch to the panel to sidebar https://code.visualstudio.com/insiders/
terminal at the bottom side

terminal at the right side

A: With v1.64.2 they have brought back the command View: Move Panel Right (or Left).  You can put the Panel (which typically has the Terminal/Output/etc. in it) as a vertical column on the left or right side - next to the Side Bar or Side Panel if you wish.

They are working on a fix for the change wrought by v1.64, should be in Insiders v1.65 02/08/2022.
Just use the View: Move Panel Right/Left/Bottom command from the Command Palette.

[Outdated answer, see above.]
As of Stable v1.64 the setting "Wokbench.panel.defaultLocation": "right" will no longer work.

Replacing Panel Location
As mentioned above, the new Side Panel provides similar functionality
as moving the Panel to the left or right, yet improves on this by not
forcing the move of the original panel. Along with view drag and drop
between panels, the new Side Panel is replacing the option to move the
bottom Panel.
In light of that, we have deprecated the
workbench.panel.defaultLocation setting as well as the Move Panel...
commands in favor of similar commands Move Views From Panel To Side
Panel (workbench.action.movePanelToSidePanel) and Move Views From
Side Panel To Panel (workbench.action.moveSidePanelToPanel). The old
commands will remap to the appropriate new command providing the
similiar behavior. Though, we recommend updating your keybindings to
the new commands.

*

*from https://github.com/microsoft/vscode-docs/blob/vnext/release-notes/v1_64.md#replacing-panel-location
This is in favor of using the new Side Panel, which can be in addition to the previous Side Bar (where the Explorer, SCM views traditionally are) and the Panel (where Terminal, Output, etc. traditionally are).  So you can have 3 panel-types of views.  See more at the v1.64 Release Notes: https://github.com/microsoft/vscode-docs/blob/vnext/release-notes/v1_64.md#new-side-panel

A:
This answer is for people that just want their terminal on the   right side (shown above), and don't care about the panel.

*

*Show vscode's Command Palette with keyboard shortcut command + shift + p or ctrl + shift + p

*Type in "terminal editor"

*Choose option that says Terminal: Create New Terminal in Editor Area to the Side

A: In version 1.55.2.
Go to View --> Appearance --> Move Panel Right

A: Click menu option View > Appearance > Move to Side Bar Right. Once side bar moves to right, option "Move Side Bar Right" changes to "Move to Side Bar Left".

A: I don't know since which version it change but the 1.11.2 has an option in View tab which can change the left bar to the right and vice versa

A: "Wokbench.panel.defaultLocation": "right"
Open settings using CTRL+., search for terminal and you should see this setting at the top. From the drop down below the settings explanation, choose right. See the screenshot below.

A: As sample as this from the GUI. View->Appearance->Move Side Bar Right

A: For people looking for an answer (on how to move the side panel):
You can press
ctrl + , (Or cmd + , on OSX)
and add the following option to your user settings JSON file:
"workbench.sideBar.location": "right"

A: As of June 2019 this setting can be found through searching 'Panel' - if you want to change the default there is an option for it as shown in the screenshot:

A: I'm using Visual Studio Code v1.24.0 on a Mac.
By default, the Panel will appear on the bottom (You can change the default as well. Please refer to @Forres' answer: Moving Panel in Visual Studio Code to right side)
Here's the bottom/right toggle button for VS Code Panel:

Once I click on this button, the Panel moves to the right.

Moving it back is a little tricky though. As you can see, some of the buttons are hidden. This is because the width of the panel when it's aligned right is too small. We need to expand the column to see all the buttons.
This is how it'll look upon expansion:

Now, if you want to move the Panel back to the bottom, click on the toggle bottom/top button again.

A: For Visual Studio Code v1.31.1, you can toggle the panel session via the View menu.

*

*Go to the View Menu.

*Via the Appearance option, click on Toggle Panel Position

A: "workbench.panel.defaultLocation": "right",

A: Go to Command Palette from the wheel icon on the bottom left --> search and enter "settings" menu --> search "panel" in the search bar --> Select Default location as "right" instead of the "bottom".
Reload VS Code, and you're good to go.

A: By default, ⌘J toggles the (bottom) panel.  If all your views are on the side panel, make ⌘J toggle the side panel by doing:
Code > Preferences > Keyboard Shortcuts > "Command+J" > Right-click > Remove Keybinding
Code > Preferences > Keyboard Shortcuts > View: Toggle Side Panel > Add Keybinding > ⌘J

A: Go to view, then appearence. Then select move panel bottom.

A: The panel opens on the right by default.
Note that this setting needs to be in a new folder to take effect.
If VSCode has opened the folder before, the panel will still use the old location.
"workbench.panel.defaultLocation": "right",


text:
Q: How to add fade animation while initializing slick slider dynamically I am using a vue js plugin for slick slider. It's https://github.com/staskjs/vue-slick. I am loading the slider dynamically using v-for loop. Here is how I am re initializing when changing image data.
watch: {
        sliderImage(){
          this.$refs.slick.destroy()
          this.$nextTick(() => {
            this.$refs.slick.create()

          })
        }
    },

Actually I am using two buttons to switch between different sliders and I am changing image data sliderImage in my method. Thus my watcher destroy the previous slider and create again with new images which is fine. But when creating new slide it loads immediately without any smooth transitions effect. How can I achieve a smooth fade transition?
Any idea would be really helpful.
Edit
My components looks like this
<slick ref="slick" :options="slickOptions">
 <div class="height-100%" v-for="m in sliderImage">
   <div :class="{'sliding':isSlide}">
         <img :src="'/uploads/'+m" alt="" @click="hideBottom">
        </div>
 </div>
</slick>

My methods that changes data
showEnt()
  {
      this.sliderImage=this.entImage;
  },
  showExt(){
    this.sliderImage=this.extImage;
  }


text:
Q: Is it possible to show two alignments in textview using iphone sdk? In my app i need to show Arabic text and English text in a textview. The Arabic text should be right aligned the English text should be left aligned.
Is it possible with a textview? I have tried using a webview instead of a textview, and I am getting what I need. But scrolling the webview is very slow.

A: You need to use the same name for the property, selectionString instead of selctionString.
Or you need to declare the property name and make it synthesize:
@synthesize selctionString = selectionString; // Missing "e"


text:
Q: How to extend BitBake class I'm building an image with Yocto, and need to patch a BitBake class in the upstream tree. I do not want to modify the upstream sources and would prefer to add the modification to a local layer.
For a BitBake recipe, I'd use a .bbappend file. What should be used for a class?

A: Create classes folder in your meta layer and create a new class, e.g. myclass.bbclass. Inherit original class with inherit original-bitbake-CLASS and add whatever functionality you need.
Then use the new bbclass instead of the original.

A: @lukaszgard method works except for one minor issue. BBFILE_PRIORITY does not provide override capability for bbclass and conf files, it only works for recipes (.bb). This is based on a section of the Yocto manual, Prioritizing Your Layer where it says

Note: It is possible for a recipe with a lower version number PV in a layer that has a higher priority to take precedence.
Also, the layer priority does not currently affect the precedence order of .conf or .bbclass files. Future versions of BitBake might address this.

A method I found that works is to create a bblayer, create and apply changes of the required bbclass and then in /build/conf/bblayers.conf, place the created bblayer above the layer that you are trying to override.
This is based on another section of the Yocto manual which says

Note: During a build, the OpenEmbedded build system looks in the layers from the top of the list down to the bottom in that order.

An example:
BBLAYERS ?= " \
  ${TOPDIR}/../layers/<layer with new bbclass> \
  ${TOPDIR}/../layers/<layer with old bbclass> \
"

A: Generally with .bbclass files there is lack of similar approach like we have with appending recipes (.bbappends). Proposed by @Oleksandr-Kravchuk solution is good but have some limitations. When You have to modify some functions or makes more complex changes, then I would prefer to copy this class file to my metadata layer and make adaptations there. Finally bitbake based on configuration in layer (conf/layer.conf file) - BBFILE_PRIORITY will decide to take this class file comes from layer with higher priority lever - without touching recipes.


text:
Q: How do I fix 'npm ERR! Test Fail' or get a verbose readout on the error so I can figure out how to resolve it? I just completed a global install of nodemon, then I installed mocha dependencies but when I run 'npm test' in a separate tab, the test loads but fails completely and I receive the error message: 'npm ERR! Test Failed. See above for more details'.
I read through the text above the error message but it's just the failed test run. Meanwhile the first tab reads: [nodemon] starting node server/index.js so I don't understand the error issue. I tried to get clarification using 'man npm' but didn't have any success.
Is there a solution or a way to get more info on the npm error?

A: I figured out the second half of my question, which was how to get a more verbose readout on the npm test error so I can figure out how to resolve it.
Type: npm test node-name
In my case the node was nodemon.
When I just typed 'npm test' I didn't get much of an explanation on why the test failed. But when I added the name of the node I was testing it resulted in a detailed response on the error that I couldn't understand on my own. With the help of my instructor, we worked it out from there.
I'll leave the question posted in case it can help someone else or in case I forget and need to circle back to my own question!


text:
Q: Close AlertDialog when window padding area clicked I'm trying to close a dialog on click outside, but when I click on the area of the left or right side of dialog it doesn't get closed. I researched it a bit, and figured out that it's the padding of DecorView that creates that transparent space on sides, but I haven't found any way to make it clickable

A:
Close AlertDialog when window padding area clicked

Sorry, you can't do this. Its not possible AFAIK. You should try with setCanceledOnTouchOutside

Sets whether this dialog is canceled when touched outside the window's
  bounds. If setting to true, the dialog is set to be cancelable if not
  already set.

dialogOBJ.setCanceledOnTouchOutside(true);

A: Do you try cancel on outside touch function like this
 dialog.setCanceledOnTouchOutside(true);

A: Try to add this line to your dialog:
dialog.setCanceledOnTouchOutside(true);

And now the dialog will get closed when the user will click the screen.

A: Try this:
alertDialog.setOnTouchListener{
    alertDialog.dismiss()
}


text:
Q: R: Using different DFs to get third DF with specific info from first 2 I have two data frames, df1 has information about a publication's year, outlet name, total articles in this publication in a year, and a cumulative sum of articles over the period of time I'm studying. df2 has a random sample of article IDs, with potential values ranging from 1 to the total number of articles given by df1$cumsum.
What I need to do is to grab each article ID in df2 and identify in which publication and year it falls under, using the information contained in df1.
Here's a minimally reproducible example:
set.seed(890)
df1 <- NULL
df1$year <- c(2000:2009, 2000:2009)
df1$outlet <- c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,2,2,2,2,2,2,2,2,2)
df1$article_total <- sample(1:200, 20, replace = T)
df1$cumsum <- cumsum(df1$article_total)
df1 <- as.data.frame(df1)

df2 <- NULL
df2$art_num <- sample(1:2102, 100, replace = T) # get random sample of article IDs for the total number of articles I have in this db
df2 <- as.data.frame(df2)

Ideally, I would also like to calculate an article's ID in each year. For example, in the data above, outlet 1 has 14 articles in the year 2000 and 168 in 2001 (cumsum = 183). If I have an article ID of 156, I would like to know that it is the 142th article in the year 2001 of publication 1. And so on and so forth for every article ID I have in this database.
I was thinking I should do this with a for loop, but I'm 100% lost in writing it. Here's what I began writing, but I have a feeling I'm not on the right track with it:
for i in 1:nrow(df2$art_num){
  article_number <- df2$art_num[i]
  if (article_number %in% df1$cumsum){ # note: cumsum should be an interval before doing this?
    # get article number, year, publication in new df
    # also calculate article ID in each year/publication
  }
}

Thanks in advance for any help! I'm still lost with writing loops in R...
#######################
EDITED EXAMPLE as per Frank's suggestion
set.seed(890)
df1 <- NULL
df1$year <- c(2000:2002, 2000:2002)
df1$outlet <- c(1, 1, 1, 2,2,2)
df1$article_total <- sample(1:50, 6, replace = T)
df1$cumsum <- cumsum(df1$article_total)
df1 <- as.data.frame(df1)

df2 <- NULL
df2$art_id <- c(66, 120, 77, 156, 24)
df2 <- as.data.frame(df2)

Here's the output I'm looking for:
  art_id outlet year article_number
1     66      1 2002             19
2    120      2 2000             35
3     77      1 2002             30
4    156      2 2001             35
5     24      1 2000             20

This example shows my ideal output in df3, which I calculated/built by hand. It has one column with the article's ID, the appropriate outlet, the year, and a new variable art_number. This is different than the article ID in that I calculated it from df1$cumsum and df3$art_id. In this example, the first row shows that the first article in my database has an ID of 66. I obtain a art_number value of 19 because this article (id = 66) is the 19th article published in the year 2002 by outlet 1. I calculated this value by looking at the article ID, locating the year and outlet based on the df1$cumsum, and then substracting the art_id value from the df1$cumsum value for the previous year. So for this specific article, I calculated df3$art_number = df3$art_id[1,1] - df1$cumsum[2,4]
I need to do this calculation for every article in my data base so I don't do this process by hand forever.

A: I think your data structure makes sense, though it would be easier with one additional column, for the first article in a year and outlet:
library(data.table)
setDT(df1); setDT(df2)

df1[, art_cstart := shift(cumsum(article_total), fill=0L) + 1L]

   year outlet article_total cumsum art_cstart
1: 2000      1             4      4          1
2: 2001      1            43     47          5
3: 2002      1            38     85         48
4: 2000      2            36    121         86
5: 2001      2            39    160        122
6: 2002      2             8    168        161

Now, we can do a rolling update join, "rolling" each art_id to the previous cumsum and computing each desired column:
df2[, c("outlet", "year", "art_num") := df1[df2, on=.(cumsum = art_id), roll=-Inf, .(
  x.year,
  x.outlet,
  i.art_id - x.art_cstart + 1L
)]]

   art_id outlet year art_num
1:     66   2002    1      19
2:    120   2000    2      35
3:     77   2002    1      30
4:    156   2001    2      35
5:     24   2001    1      20

How it works

*

*x[i, on=, roll=, j] is the syntax for a join, looking up each row of i in x.

*In this join j evaluates to a list of columns, .(...) shorthand for list(...).

*Column assignment is done with (colnames) := .(...).

The assignment is to the existing table df2 instead of unnecessarily creating a new table.
For details on how data.table syntax works, see the startup messages...
> library(data.table)
data.table 1.10.4
  The fastest way to learn (by data.table authors): https://www.datacamp.com/courses/data-analysis-the-data-table-way
  Documentation: ?data.table, example(data.table) and browseVignettes("data.table")
  Release notes, videos and slides: http://r-datatable.com

A: This is the code you need I think:
df3 <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(df3) <- c("articleNumber", "year", "publication")
for(i in 1:nrow(df2$art_num)){
 for(j in 1:nrow(df1$cumsum)) {
  if ((df2$art_num[i] >= df1$cumsum[j]) && (df2$art_num[i] <= df1$cumsum[j + 1])){
    # note: cumsum should be an interval before doing this? NOT REALLY SURE
    # WHAT YOU NEED HERE
    # get article number, year, publication in new df
    df3[i, 1] <- df2$art_num[i]
    df3[i, 2] <- df1$year[j]
    df3[i, 3] <- df1$outlet[j]
    # also calculate article ID in each year/publication ISN'T THIS
    # art_num?
  }
}


text:
Q: Java Regex: how to capture multiple matches in the same line I am trying to match a regex pattern in Java, and I have two questions:

*

*Inside the pattern I'm looking for there is a known beginning and then an unknown string that I want to get up until the first occurrence of an &.

*there are multiple occurrences of these patterns in the line and I would like to get each occurrence separately.

For example I have this input line:

1234567 100,110,116,129,139,140,144,146 http://www.gold.com/shc/s/c_10153_12605_Computers+%26+Electronics_Televisions?filter=Screen+Refresh+Rate%7C120HZ%5EScreen+Size%7C37+in.+to+42+in.&sName=View+All&viewItems=25&subCatView=true   ISx20070515x00001a          http://www.gold.com/shc/s/c_10153_12605_Computers+%26+Electronics_Televisions?filter=Screen+Refresh+Rate%7C120HZ&sName=View+All&subCatView=true 0   2819357575609397706

And I am interested in these strings:
Screen+Refresh+Rate%7C120HZ%5EScreen+Size%7C37+in.+to+42+in.

Screen+Refresh+Rate%7C120HZ

A: If i know that I might need other query parameters in the future, I think it'll be more prudent to decode and parse the URL.
String url = URLDecoder.decode("http://www.gold.com/shc/s/c_10153_12605_" +
            "Computers+%26+Electronics_Televisions?filter=Screen+Refresh+Rate" +
            "%7C120HZ%5EScreen+Size%7C37+in.+to+42+in.&sName=View+All&viewItems=25&subCatView=true"
            ,"utf-8");
Pattern amp = Pattern.compile("&");
Pattern eq = Pattern.compile("=");
Map<String, String> params = new HashMap<String, String>();
String queryString = url.substring(url.indexOf('?') + 1);
for(String param : amp.split(queryString)) {
    String[] pair = eq.split(param);
    params.put(pair[0], pair[1]);
}
for(Entry<String, String> param : params.entrySet()) {
    System.out.format("%s = %s\n", param.getKey(), param.getValue());
}

Output
subCatView = true
viewItems = 25
sName = View All
filter = Screen Refresh Rate|120HZ^Screen Size|37 in. to 42 in.

A: Assuming the known beginning is filter=**, the regular expression pattern (?:filter=\\*\\*)(.*?)(?:&) should get you what you need.  Use Matcher.find() to get all occurrences of the pattern in a given string.  Using the test string you provided, the following:
final Pattern p = Pattern.compile("(?:filter=\\*\\*)(.*?)(?:&)");
final Matcher m = p.matcher(testString);
int cnt = 0;
while (m.find()) {
    System.out.println(++cnt + ": G1: " + m.group(1));
}

Will output:
1: G1: Screen+Refresh+Rate%7C120HZ%5EScreen+Size%7C37+in.+to+42+in.
2: G1: Screen+Refresh+Rate%7C120HZ**

A: in your example, there is sometimes a "**" at the end before the "&".  but basically, (assuming "filter=" is the start pattern you are looking for) you want something like:
"filter=([^&]+)&"

A: Using the regular expression (?<=filter=\*{0,2})[^&]*[^&*]+ in java:
Pattern p = Pattern.compile("(?<=filter=\\*{0,2})[^&]*[^&*]+");
String s = "1234567 100,110,116,129,139,140,144,146 http://www.gold.com/shc/s/c_10153_12605_Computers+%26+Electronics_Televisions?filter=**Screen+Refresh+Rate%7C120HZ%5EScreen+Size%7C37+in.+to+42+in.&sName=View+All**&viewItems=25&subCatView=true   ISx20070515x00001a          http://www.gold.com/shc/s/c_10153_12605_Computers+%26+Electronics_Televisions?filter=**Screen+Refresh+Rate%7C120HZ**&sName=View+All&subCatView=true 0   2819357575609397706";
Matcher m = p.matcher(s);
while (m.find()) {
    System.out.println(m.group());
}

EDIT:
Added [^&*]+ to the end of the regex to prevent the ** from being included in the second match.
EDIT2:
Changed regular expression to use lookbehind.

A: The regex you're looking for is
Screen\+Refresh\+Rate[^&]*

You could use Matcher.find() to find all matches.

A: are you looking for a string that follows with "filter=" and ignores the first "*" and is end with the first "&".
your can try the following:
String str = "1234567 100,110,116,129,139,140,144,146 http://www.gold.com/shc/s/c_10153_12605_Computers+%26+Electronics_Televisions?filter=**Screen+Refresh+Rate%7C120HZ%5EScreen+Size%7C37+in.+to+42+in.&sName=View+All**&viewItems=25&subCatView=true   ISx20070515x00001a          http://www.gold.com/shc/s/c_10153_12605_Computers+%26+Electronics_Televisions?filter=**Screen+Refresh+Rate%7C120HZ**&sName=View+All&subCatView=true 0   2819357575609397706";
    Pattern p = Pattern.compile("filter=(?:\\**)([^&]+?)(?:\\**)&");

    Matcher matcher = p.matcher(str);
    while(matcher.find()){
        System.out.println(matcher.group(1));
    }