text:
Q: Android: Intermitent application flow issue I'm facing with an intermittent application flow issue.
Here, I've got a Login screen where I'm able to login for the first time. But when I'm logging out and/or re-loging in, I'm unable to traverse further. As a work around, I need to uninstall my application and reinstall it and the flow is ok.
Can anyone please guide me on the possible issue.
LoginActivity.java
        GetWebServiceManager passwordExpiryWSManager = new GetWebServiceManager();

        //to check network connectivity (data connection/Wi-Fi)
        ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInformation = connectionManager.getActiveNetworkInfo();

        if (networkInformation != null && networkInformation.isConnected() == true) {
            try {
//              passwordExpiryString = passwordExpiryWSManager.execute("http://172.25.164.143:8088/api/Login/GetExpiredPassword/?lContactKey=" + username.getText().toString()).get();
                passwordExpiryString = passwordExpiryWSManager.execute(AppConstants.URL + "/Login/GetExpiredPassword/?lContactKey=" + username.getText().toString()).get();

                jsonObjectPassExpiry = new JSONObject(passwordExpiryString);
                jsonArrayPassExpiry = jsonObjectPassExpiry.getJSONArray("LstLoginDetail");
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            /*
             * Converting JSON string response from Webservice into Java Object
             * */
            if (jsonArrayPassExpiry != null) {
                Gson gson = new Gson();
                LoginTO[] loginExpTO = gson.fromJson(jsonArrayPassExpiry.toString(), LoginTO[].class);
                loginListPassExpiry = Arrays.asList(loginExpTO);
                intent = getIntent();

                if (loginListPassExpiry.get(0).getlSuccess() == 1) {
                    intent.setClass(getApplicationContext(), PortfolioSummaryFragmentActivity.class);
//                  intent.putExtra("sToken", loginList.get(0).getsToken());
                    startActivity(intent);
                } else {
                    intent.setClass(getApplicationContext(), PasswordExpiryActivity.class);
//                  intent.putExtra("sToken", loginList.get(0).getsToken());
                    startActivity(intent);
                }
            } else {
                Toast.makeText(getApplicationContext(), "Service is not responding. Please try again later!!", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(getApplicationContext(), "Network connection unavailable. Please check your data plan or Wi-Fi connection!!", Toast.LENGTH_SHORT).show();
        }

Logout.java
public class LogoutActivity extends Activity {
    private TextView successResponse;
    private Intent intent;
    private Button btnLLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.logout_success);

        successResponse = (TextView) findViewById(R.id.txtvwLSuccessMessage);
        btnLLogin = (Button) findViewById(R.id.btnLLogin);

        intent = getIntent();
        successResponse.setText(intent.getStringExtra("successResponse"));
    }

    public void Login(View v) {
        btnLLogin.setTextColor(getResources().getColor(R.color.black));
        intent = new Intent(this, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    public void onBackPressed() {
        finish();
    }
}

A: please use intent = new Intent(LogoutActivity.this, LoginActivity.class); instead of intent = new Intent(this, LoginActivity.class);
beside this use
most important
Add android:launchMode="singleTask " to the activity element in your manifest for Activity LoginActivity


text:
Q: Do android APKs include any identifying or user data Scenario:

*

*Someone buys/downloads my apps from the play store.

*They then do an adb pull /data/app/com.example.myapp.apk on my apps

*They then sideload it on another device/distribute it online

Can I:

*

*Via my app identify it was not legitimately purchased/downloaded?

*Download my apps from said website and verify the same person downloaded them?

*Find any identifying information/user data inside the apk?

A: I can only answer number 3:
Reading: https://android.stackexchange.com/a/28138
It seems no user data will be in the APK, I don't know about the play store data though.

A:
Can I:
  Via my app identify it was not legitimately purchased/downloaded?

It depends how your app can be purchased. But even then that will be pretty hard to do that, especially this will be prone to spoofing on rooted devices, so if your app is a standalone product and does not require any account on your servers to be used, then it may be really painful and at some point not worth the efforts maybe.

Download my apps from said website and verify the same person downloaded them?

No.

Find any identifying information/user data inside the apk?

No. There's none.

A:
Via my app identify it was not legitimately purchased/downloaded?

Aside from the security key which guarantees that the contents of the apk are not tampered with, the apk on it's own does not identify where it came from. If you need extra security measures against pirating, you have to look for other solutions, e.g. account checking, web-based identification, etc

Download my apps from said website and verify the same person downloaded them?

If you mean that whether Google Play will identify you as the person that originally purchased the app, the answer is no. If the app is paid Google Play will realize that you have not paid for it. If the app is not paid then Google Play will simply add that to the library of apps that you have and/or installed

Find any identifying information/user data inside the apk?

There is no user data in the apk since the apk is the same file for any device that installs it. However, some apps might store data locally which means that through adb pull an untrusted party might be able to pull your user data from your phone. Most apps don't store anything locally because of this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Application Insights SDK C# - Log full telemetry and dependencies only on requests that have failed We're trying to cut down the costs of our Application Insights instance, currently we don't have Adaptive Sampling enabled as we find it often doesn't record a dependency that is required so doesn't give us a full picture, especially when a request has failed.
So my thinking was to only log the Request without any dependencies if the request was successful, and log all the Dependencies if the Request was not successful.
I thought this would be fairly easy using the TelemetryProcessor Filter functionality. However, as far as I can see there is no link within the SDK between the telemetry i.e. I cannot see how a Request telemetry links to the Dependency telemetry, meaning I cannot stop the SDK logging the Dependency as I cannot check if the Request was successful.
The WebAPI is running .Net6, C# using Microsoft.ApplicationInsights.AspNetCore 2.20.0
Has anyone else had this problem or can think of a solution? Many thanks


text:
Q: django social auth , create user model with email as primary key I am trying to integrate django social auth for my website which will have Facebook and Google login. I am trying to customize the user model to make email as primary key.
Any advice ?
I tried creating a UserModel also but ended up with errors.
i tried creating a pipeline enter code here
from social_auth.backends.pipeline.user import create_user
def custom_create_user(request, *args, **kwargs):
      print kwargs
      return create_user(request, args, kwargs)

My aim is to have a site with Facebook And Google - oauth2 login with email as primary key !

A: Well I am doing facebook login for my ios app. What I am doing is

*

*Login to facebook from my app and get the facebook access token

*Send the facebook email and access token to the django backend

*Then what I do is, instead of using the django default authenticate method which takes the username and password to authenticate a user, I overwrite my own authenticate method. Doing this is really easy just read Django Custom Authentication

*In my custom authentication class I verify the email-token pair sent from the front using fb sdk for python and that is it. After than I can login the user using the django in built login


text:
Q: Convert character to html in R What's the prefered way in R to convert a character (vector) containing non-ASCII characters to html? I would for example like to convert
  "ü"

to
  "ü"

I am aware that this is possible by a clever use of gsub (but has anyone doen it once and for all?) and I thought that the package R2HTML would do that, but it doesn't.
EDIT: Here is what I ended up using; it can obviously be extended by modifying the dictionary:
char2html <- function(x){
  dictionary <- data.frame(
    symbol = c("ä","ö","ü","Ä", "Ö", "Ü", "ß"),
    html = c("ä","ö", "ü","Ä",
             "Ö", "Ü","ß"))
  for(i in 1:dim(dictionary)[1]){
    x <- gsub(dictionary$symbol[i],dictionary$html[i],x)
  }
  x
}

x <- c("Buschwindröschen", "Weißdorn")
char2html(x)

A: This question is pretty old but I couldn't find any straightforward answer... So I came up with this simple function which uses the numerical html codes and works for LATIN 1 - Supplement (integer values 161 to 255). There's probably (certainly?) a function in some package that does it more thoroughly, but what follows is probably good enough for many applications...
conv_latinsupp <- function(...) {
  out <- character()
  for (s in list(...)) {
    splitted <- unlist(strsplit(s, ""))
    intvalues <- utf8ToInt(enc2utf8(s))
    pos_to_modify <- which(intvalues >=161 & intvalues <= 255)
    splitted[pos_to_modify] <- paste0("&#0",  intvalues[pos_to_modify], ";")
    out <- c(out, paste0(splitted, collapse = ""))
  }
  out
}

conv_latinsupp("aeiou", "àéïôù12345")
## [1] "aeiou"   "àéïôù12345"

A: The XML uses a method insertEntities for this, but that method is internal. So you may use it at your own risk, as there are no guarantees that it will remain to operate like this in future versions.
Right now, your code could be accomplished using
char2html <- function(x) XML:::insertEntities(x, c("ä"="auml", "ö"="ouml", …))

The use of a named list instead of a data.frame feels kind of elegant, but doesn't change the core of things. Under the hood, insertEntities calls gsub in much the same way your code does.
If numeric HTML entities are valid in your environment, then you could probably convert all your text into those using utf8ToInt and then turn safely printable ASCII characters back into unescaped form. This would save you the trouble of maintaining a dictionary for your entities.


text:
Q: C++ static member variable of nested class in template class I made a template class Block and wanted to cache some data for each instance type of Block. For this reason I created an inner class Cache which is storing and initialising the data often used by Block class instances. But the compiler (Visual Studio 2017, C++17) is not accepting the static member variable definition and the error message is not helping me. Whats wrong with my code and how I can accomplish my goal?
Errors:
Error  C2061   syntax error: identifier 'Cache'
Warnings:
Warning    C4346   'Cache': dependent name is not a type
template<int D>
class Block
{
private:
    class Cache
    {
    public:
        int mData[D];
    public:
        Cache();
    };
private:
    static Cache mCache;
public:
    Block();
};

template<int D>
Block<D>::Cache Block<D>::mCache; // Syntax error "Cache"!

template<int D>
inline Block<D>::Block()
{
    // Use cache data.
    cout << Block<D>::mCache.mData[0] << endl;
}

template<int D>
inline Block<D>::Cache::Cache()
{
    // Initialise cache data.
    mData[0] = D;
}

A: add typename
template<int D>
typename Block<D>::Cache Block<D>::mCache;

You can read https://en.cppreference.com/w/cpp/language/dependent_name, but put it short, compiler don't know if it's a type.


text:
Q: Would the global variable inside a submodule be reloaded each time I call a function? I have my library structured as such:
/topmost
   /__init__.py
   /submodule
       /__init__.py

With the submodule.__init__.py, there are several functions that makes use of global variables to communicate with each other:
import pickle

def function1(input):
    global _object1
    try:
        _object1
    except NameError:
        _object1 = pickle.load(open('model1.pkl', 'rb'))
    return _object1.func1(input)

def function2(input):
    global _object2
    try:
        _object2
    except NameError:
        _object2 = pickle.load(open('model1.pkl', 'rb'))
    # Use function1 to do something to the input
    return _object2.func2(function1(input))

And for the user, they won't be able to access any of the _object1 or _object2 form the topmost and in the topmost.__init__.py, only the functions from submodule were imported:
from __future__ import absolute_import
from topmost.submodule import *

And when the users use the topmost library, they will only be expose to:
>>> import topmost
>>> topmost.function1('foo bar')
>>> topmost.function2('foo bar bar')
>>> topmost.function1('blah blah black sheep')

When the first instance of topmost.function1('foo bar') is called, the interpreter should kick-in the global _object1 within the topmost.submodule scope. But would the _object1 be destructed after the topmost.function1 receives the returned value?
More importantly, when the second instance of topmost.function1('blah blah black sheep') is called in the usage snippet above, would the _object1 = pickle.load(open('model1.pkl', 'rb')) be reloaded?

A: Global variables linger.  They do not get destructed by a garbage collection.  The module submodule will keep its set global variables until such a module-global variable gets unset explicitly using del or if the module gets unloaded itself which normally doesn't happen.
Your usage of global variables in this fashion looks a bit fishy to me, though.  It is not a very clean way of writing code.
Why not setting the variables in general upon importing them?  You could set them to None and check for them having this value instead of catching NameErrors.

A: As Alfe alludes to, you are using global vars in a weird way.
If you must use global variables, I would recommend that you rewrite the code:
import pickle
_model1 = None  # here we define the global we wish to load the
                # first time either function is called

def load_model1():
    global _model1
    if not _model1:
        _model1 = pickle.load(open('model1.pkl', 'rb'))
        # No need to write two functions for loading model1
    return _model1

def function1(input):
    return load_model1().func1(input)

def function2(input):
    # Use function1 to do something to the input
    return load_model1().func2(function1(input))


text:
Q: How to align UILabel text in paragraph I have a small issue in setting text alignment as per client requirement. Client want text to be aligned in paragraph manner with numbers in separate line. Please see the below image the number have 19 pixels padding and text aligned in paragraph manner with 41 pixels padding.

If we set left alignment to label we will get the second line below the numeric.

I tried search for solution but not able to succeed.
Thanks in advance.

A: You'll need to set different attributes for the question part and the answer part. You're already doing this to control the font, so it shouldn't be a big change. You need to set the paragraph style for each section. For the question section, you need to set the firstLineHeadIndent to 19 and the headIndent to 41. For the answer section, you need to set both to 41.
NSMutableParagraphStyle *questionStyle = [[NSMutableParagraphStyle alloc] init];
questionStyle.firstLineHeadIndent = 19;
questionStyle.headIndent = 41;
NSDictionary *questionAttributes = @{
    NSParagraphStyleAttributeName: questionStyle,
    NSFontAttributeName: [UIFont systemFontOfSize: 20]
};

NSMutableParagraphStyle *answerStyle = [questionStyle mutableCopy];
answerStyle.firstLineHeadIndent = questionStyle.headIndent;
NSDictionary *answerAttributes = @{
    NSParagraphStyleAttributeName: answerStyle,
    NSFontAttributeName: [UIFont systemFontOfSize: 16]
};

NSMutableAttributedString *richText = [[NSMutableAttributedString alloc] init];
[richText appendAttributedString:[[NSAttributedString alloc]
     initWithString:questionText attributes:questionAttributes]];
[richText appendAttributedString:[[NSAttributedString alloc]
    initWithString:answerText attributes:answerAttributes]];

label.attributedText = richText;

A: One possibility:

*

*Use an NSAttributedString with a custom NSParagraphStyle. The first line indent can be different from the other lines (left margin).

Another possibility:

*

*Use a web view. What you describe is easy to configure using CSS.

A: Try this
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.alignment = NSTextAlignmentLeft;
[self.titleString drawWithRect:CGRectMake(xOffset, yOffset, titleLabelSize.width, titleLabelSize.height)
                               options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine
                            attributes:@{ NSParagraphStyleAttributeName:paragraphStyle}
                               context:nil];


text:
Q: Inserting entity in CoreData and EXC_BAD_ACCESS signal I am writing a program that synchronizes with a server. Synchronization is run in foreground but using LRResty and delegates to get the responses. Randomly, while I run the synchronization, I get EXC_BAD_ACCESS signal running this code or some other insertion/relationship adding in CoreData:
WorkoutExerciseSet *set = [NSEntityDescription insertNewObjectForEntityForName:@"WorkoutExerciseSet" inManagedObjectContext:mObjContext];

Therefore I was thinking the error is given because this code isn't actually run on the main thread. Could that be the reason? Which is the best way to solve it?

A: The only possible source of EXC_BAD_ACCESS in the line of code given is that the mObjContext has a nil value. You are losing your NSManagedObjectContext object somewhere along the line.
Based on that one line of code, you are probably not using assessors correctly. The managed object context is almost always an attribute of the object holding the insertion code so the line should probably look like:
WorkoutExerciseSet *set = [NSEntityDescription insertNewObjectForEntityForName:@"WorkoutExerciseSet" inManagedObjectContext:self.mObjContext];

... to make sure the context object is properly accessed. Likewise, when you set the attribute value it should be:
self.mObjContext=someManagedObjectContext;


text:
Q: API field configuring I see timestamp variable in api getting converted to 2 hours ahead and stored what time zone it is?
I want to know what timezone configuration is set to store how to set it for cet time

A: I will try to explain you how i do it for PsotgreSQL Here is an example that should help. If you have a timestamp with a timezone, you can convert that timestamp into any other timezone. If you haven't got a base timezone it won't be converted correctly.
SELECT now(),
   now()::timestamp,
   now() AT TIME ZONE 'CST',
   now()::timestamp AT TIME ZONE 'CST'

Output:
-[ RECORD 1 ]---------------------------
now      | 2018-09-15 17:01:36.399357+03
now      | 2018-09-15 17:01:36.399357
timezone | 2018-09-15 08:01:36.399357
timezone | 2018-09-16 02:01:36.399357+03


text:
Q: How to store a reference to STDOUT/STDERR inside a variable I can call a shell script like so:
foo --out-file=build/logs/foo.out --err-file=build/logs/foo.err

and in the
script I have something like so
#!/bin/bash
OUTFILE=null
ERRFILE=null

while [[ $# -gt 0 ]]
do
  key="$1"

  case $key in
    -o|--out-file)
    OUTFILE=$2
    shift
    shift
    ;;
    case $key in
    -e|--err-file)
    ERRFILE=$2
    shift
    shift
    ;;
    *)
    shift
    ;;
  esac
done
if [ "$OUTFILE" != null ] && [ "$ERRFILE" != null ]
then
  ls > $OUTFILE 2>$ERRFILE
elif [ "$OUTFILE" != null ]
then
  ls > $OUTFILE
elif [ "$ERRFILE" != null ]
then
  ls 2>$ERRFILE
else
  ls
fi

Is there any way to set OUTFILE and ERRFILE to hold the values to STDOUT/STDERR so I can just initialize them to that (ie. OUTFILE=$STDERR) to avoid so man if/elif/else statements?

A: What you can do is perform the redirect with the exec command, which redirects for the rest of the script.
while [[ $# -gt 0 ]]
do
  key="$1"

  case $key in
    -o|--out-file)
        exec >"$2"
        shift 2
        ;;
    -e|--err-file)
        exec 2>"$2"
        shift 2
        ;;
    *)
        shift
        ;;
  esac
done

Then the ls command will write to the files without needing its own redirection.


text:
Q: Using an if-else statement to conditionally define a function in `R` In R, I'm defining the function lengths depending on the value of a parameter previously set:
if(condition == 1){
    lengths <- function(vector) {
        n <- ceiling(length(vector)/2)
    }
}
else if(condition == 2){
    lengths <- function(vector) {
        n <- length(vector)
    }
}
else if(condition == 3){
    lengths <- function(vector) {
        n <- length(vector)*2
    }
}
else{
    lengths <- function(vector) {
        n <- length(vector)+10
    }
}

Defining a function conditionally in this way seems just a bit... messy.  Is there a better way?

A: You could use switch:
lengths <- function(vector, condition) {
  switch(condition,
    ceiling(length(vector)/2),
    length(vector),
    length(vector)*2,
    length(vector)*+10)
}

This function provides behavior more like your example code:
lengths <- function(vector, condition) {
  switch(as.character(condition),
    `1`=ceiling(length(vector)/2),
    `2`=length(vector),
    `3`=length(vector)*2,
    length(vector)*+10)
}

...and this function will be defined by the value of condition:
condition <- 1
lengths <- switch(as.character(condition),
    `1`=function(vector) ceiling(length(vector)/2),
    `2`=function(vector) length(vector),
    `3`=function(vector) length(vector)*2,
    function(vector) length(vector)*+10)
lengths
# function(vector) ceiling(length(vector)/2)

A: A quick hack based on CSGillespie's suggestion:
length.lut  <-  cbind(c(0.5,1,2,1,),c(0,0,0,10))

lengths <- function(vector, condition) vector*length.lut[condition,1] + length.lut[condition,2]


text:
Q: How to convert day,month,year into date format? I have been trying to run a python script that converts day,month,year into date format.
I have attempted the following script;
# dateconvert2.py
# Converts day month and year numbers into two date formats

def main():
    # get the day month and year
    day, month, year = eval(input("Please enter day, month, year numbers: "))

    date1 = str(month)+"/"+str(day)+"/"+str(year)

    months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "Novemeber", "December"]
    monthStr = months[month-1]
    date2 = monthStr+" " + str(day) + ", " + str(year)

    print("The date is", date1, "or", date2+ ".")
main()

The result should look like;
>>> Please enter day, month,  and year numbers: 24, 5, 2003
The date is 5/24/2003 or May 24, 2003.

As I ran the program, an error appeared saying that the line;
    monthStr = months[month-1]

had an index error.
What can I do to improve this? Please help

A: If
monthStr = months[month-1]

had an index error, it means month was either smaller than 1 or bigger than 12. You could check it's in the correct range before this line.
A few notes

*

*eval is dangerous, and not needed in this case. You could use split, map and int to extract the integers.

*you could use format with %02d to show the dates, if you want to write it yourself

*strftime and strptime do exactly what you want. They parse a string to datetime and display a datetime in any given format.

*calendar already has month_name. The list has 13 elements though, and the first one is empty.

Modified code :
def main():
    # get the day month and year
    day, month, year = map(int, input("Please enter day, month, year numbers: ").split(','))

    date1 = '%02d/%02d/%d' % (day, month, year)

    months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
    if month > 0 and month < 13:
        month_str = months[month-1]
        ## alternative :
        # import calendar
        # month_str = calendar.month_name[month]
        date2 = '%s %d, %d' % (month_str, day, year)
        print("The date is", date1, "or", date2+ ".")
    else:
        print("Invalid month")
main()

As an example :
Please enter day, month, year numbers: 24,12,2017
The date is 24/12/2017 or December 24, 2017.

but :
Please enter day, month, year numbers: 24,0,2017
Invalid month

A: day, month, year = eval(input("Please enter day, month, year numbers: "))

eval() is unnecessary here, assuming your user knows to separate with commas you can just use:
day, month, year = input("Please enter comma seperated day, month, year numbers: ")

may only work in 2.x see comments below, sorry for confusion
then regarding inputs you should validate your data:
if 1 <= month <= 12:
    if (month in [1,3,5,7,8,10,12]) and (day != 31):
        print 'error'
    elif (month in [4,6,9,11]) and (day != 30):
        print 'error'
    elif (month==2) and (day not in [28,29]):
        print 'error'
else:
    print 'error'


text:
Q: Max return value if empty query I have this query:
int maxShoeSize = Workers
    .Where(x => x.CompanyId == 8)
    .Max(x => x.ShoeSize);

What will be in maxShoeSize if company 8 has no workers at all?
UPDATE:
How can I change the query in order to get 0 and not an exception?

A: I know this is an old question and the accepted answer works, but this question answered my question about whether such an empty set would result in an exception or a default(int) result.
The accepted answer however, while it does work, isn't the ideal solution IMHO, which isn't given here. Thus I am providing it in my own answer for the benefit of anyone who is looking for it.
The OP's original code was:
int maxShoeSize = Workers.Where(x => x.CompanyId == 8).Max(x => x.ShoeSize);

This is how I would write it to prevent exceptions and provide a default result:
int maxShoeSize = Workers.Where(x => x.CompanyId == 8).Max(x => x.ShoeSize as int?) ?? 0;

This causes the return type of the Max function to be int?, which allows the null result and then the ?? replaces the null result with 0.

EDIT
Just to clarify something from the comments, Entity Framework doesn't currently support the as keyword, so the way to write it when working with EF would be:
int maxShoeSize = Workers.Where(x => x.CompanyId == 8).Max<[TypeOfWorkers], int?>(x => x.ShoeSize) ?? 0;

Since the [TypeOfWorkers] could be a long class name and is tedious to write, I've added an extension method to help out.
public static int MaxOrDefault<T>(this IQueryable<T> source, Expression<Func<T, int?>> selector, int nullValue = 0)
{
    return source.Max(selector) ?? nullValue;
}

This only handles int, but the same could be done for long, double, or any other value type you need. Using this extension method is very simple, you just pass in your selector function and optionally include a value to be used for null, which defaults to 0. So the above could be rewritten like so:
int maxShoeSize = Workers.Where(x => x.CompanyId == 8).MaxOrDefault(x => x.ShoeSize);

Hopefully that helps people out even more.

A: int maxShoeSize=Workers.Where(x=>x.CompanyId==8)
    .Max(x=>(int?)x.ShoeSize).GetValueOrDefault();

(assuming that ShoeSize is of type int)
If Workers is a DbSet or ObjectSet from Entity Framework your initial query would throw an InvalidOperationException, but not complaining about an empty sequence but complaining that the materialized value NULL can't be converted into an int.

A: int maxShoeSize = Workers.Where(x => x.CompanyId == 8)
                         .Select(x => x.ShoeSize)
                         .DefaultIfEmpty(0)
                         .Max();

The zero in DefaultIfEmpty is not necessary.

A: Max() won't return anything in that case.
It will raise InvalidOperationException since the source contains no elements.

A: Max will throw System.InvalidOperationException "Sequence contains no elements"
class Program
{
    static void Main(string[] args)
    {
        List<MyClass> list = new List<MyClass>();

        list.Add(new MyClass() { Value = 2 });

        IEnumerable<MyClass> iterator = list.Where(x => x.Value == 3); // empty iterator.

        int max = iterator.Max(x => x.Value); // throws System.InvalidOperationException
    }
}

class MyClass
{
    public int Value;
}

A: NB: the query with DefaultIfEmpty() may be significantly slower.
In my case that was a simple query with .DefaultIfEmpty(DateTime.Now.Date).
I was too lazy to profile it but obviously EF tried to obtain all the rows and then take the Max() value.
Conclusion: sometimes handling InvalidOperationException might be the better choice.

A: int maxShoeSize = Workers.Where(x => x.CompanyId == 8)
                     .Select(x => x.ShoeSize)
                     .DefaultIfEmpty()
                     .Max();

A: If this is Linq to SQL, I don't like to use Any() because it results in multiple queries to SQL server.
If ShoeSize is not a nullable field, then using just the .Max(..) ?? 0 will not work but the following will:
int maxShoeSize = Workers.Where(x = >x.CompanyId == 8).Max(x => (int?)x.ShoeSize) ?? 0;

It absolutely does not change the emitted SQL, but it does return 0 if the sequence is empty because it changes the Max() to return an int? instead of an int.

A: You can use a ternary within .Max() to handle the predicate and set its value;
// assumes Workers != null && Workers.Count() > 0
int maxShoeSize = Workers.Max(x => (x.CompanyId == 8) ? x.ShoeSize : 0);

You would need to handle the Workers collection being null/empty if that's a possibility, but it would depend on your implementation.

A: You can try this:
int maxShoeSize = Workers.Where(x=>x.CompanyId == 8).Max(x => x.ShoeSize) ?? 0;

A: You could check if there are any workers before doing the Max().
private int FindMaxShoeSize(IList<MyClass> workers) {
   var workersInCompany = workers.Where(x => x.CompanyId == 8);
   if(!workersInCompany.Any()) { return 0; }
   return workersInCompany.Max(x => x.ShoeSize);
}


text:
Q: Remove an object from a list based on an attribute of another list with linq I have the following class to store objects from a REST API call from SharePoint:
 [Serializable]
public class DocumentSearchResult
{
    public string TotalCount { get; set; }
    public string DocumentPath { get; set; }
    public string DocumentTitle { get; set; }
    public string DocumentSize { get; set; }
    public string DocumentAuthor { get; set; }
    public string DocumentDescription { get; set; }
    public string DocumentFileExtension { get; set; }
    public double DocumentRank { get; set; }
    public Int64 DocumentDocId { get; set; }
    public Int64 DocumentWorkId { get; set; }
    public DateTime DocumentWrite { get; set; }
    public string DocumentParentLink { get; set; }
    public DateTime DocumentLastModifiedDate { get; set; }
    public string DocumentFileType { get; set; }

    //These next set of properties are used for Viewing the results in embedded or preview
    public string DocumentRedirectedEmbededURL { get; set; }
    public string DocumentRedirectPreviewURL { get; set; }
    public string DocumentRedirectURL { get; set; }

}

I create a list of these objects in my code:
var docReturnResult = new List<DocumentSearchResult>();

I have another list I create using:
var filterList = this.Where(x => x.TenantId == TenantId);

this will return an IQueryable list that contains a value I need to filter the second list.  The filterList has an attribute called SharePointId (x => x.SharePointId) that I need to use to filter the docReturnResult list.  So I need to compare the filterList SharePointId to the docReturnResult DocumentDocId and remove any objects in the docReturnResult list that don't match the SharePointId's in the filterList.
This is what I tried last:
 var trimResults = new DocumentSearchResult();
            trimResults = docReturnResult.RemoveAll(x => x.DocumentDocId != filterList.Where(y => y.SharePointId));

but I get an error:

Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type.

Any help is much appreciated.

A: Try this, it should remove all documents from docReturnResult where match is not found in filterList
docReturnResult.RemoveAll(x => !filterList.Any(y => y.SharePointId == x.DocumentDocId));

Root cause of your error -
 x.DocumentDocId != filterList.Where(y => y.SharePointId)

Right hand side will return IQuarable object and you are trying to compare it with DocumentDocId which will not work.
Edit
You don't need a new variable trmResults, as RemoveALL on docReturnResult will trim the same object, so you can just return docReturnResult
return docReturnResult.RemoveAll(x => !filterList.Any(y => y.SharePointId == x.DocumentDocId));


text:
Q: How to trace a JSP Is there any way to trace a JSP to determine where it's giving me an error. I get a java.lang.NullPointerException, but I have no idea which part of the code is causing it. Is there any statement I can use to trace where the error occurs?

A: Look at these links.
http://www.eclipse.org/webtools/initial-contribution/IBM/evalGuides/ServerToolsEval.html
debug JSP from eclipse

A: Look for the corresponding .java file and set a break point in that at the line throwing the NPE.
A JSP gets compiled to a .java file, before being passed to javac for compilation.


text:
Q: Appending (uint8_t)0x00 to a std::string causes ambiguous overload error on cygwin? Am I going crazy, or is this a bug with the cygwin g++ compiler?
This works:
std::string record;
record += (uint8_t)1;

It also is totally cool with appending a const variable with value 0:
const uint8_t tZero = 0x00;
std::string record;
record += tZero;

However, running this code causes an ambiguous operator overload error:
std::string record;
record += (uint8_t)0;

The candidates it provides make no sense given the explicit cast, especially since one of the candidates seems to be identical to what is given in the error:
sources/logger.cpp:55:20: error: ambiguous overload for `operator+=' (operand types are `std::string {aka std::basic_string<char>}' and `uint8_t {aka unsigned char}')
    record += (const uint8_t)0;

note: candidates:
    operator+=(const basic_string& __str)
    operator+=(const _CharT* __s)
    operator+=(_CharT __c)

This error also does NOT appear in visual studio, it compiles and appends a 0x00 byte just as I expect.
For reference, I'm using strings as buffers for binary log data. There's probably a better container to use, but being able to += bytes in is too useful to not have.
Does cygwin have a bug with its string implementation, or is this supposed to cause an error since it's 0? I don't mind using a const variable to fix the error, but it will look weird since this process is repeated multiple times through the code with other values.

A: This is a fairly recent change to the C++ language. Nowadays, your code should call operator+=(_CharT). In the past, your code should fail due to an ambiguity even with const uint8_t tZero = 0x00;. You're dealing with a compiler that's partially implemented that change.
Before that change to the language, any integer constant expression with a value of zero was implicitly convertible to any pointer type and yielded a null pointer. That's why (uint8_t)0 could be converted to char, or to const char *.
Now, only a literal 0 can be converted to pointer types. tZero, or even (uint8_t)0, should no longer convert to const char *. This resolves the ambiguity: only the conversion to char still remains as a possibility.


text:
Q: Зачем нужен фабричный метод? Допустим есть вот такая реализация фабричного метода:
abstract class Creator
    {
        public abstract Product FactoryMethod();
    }

    class ConcreteCreatorA : Creator
    {
        public override Product FactoryMethod() { return new ConcreteProductA(); }
    }

    abstract class Product
    {}

    class ConcreteProductA : Product
    {}

Какая выгода нам от создания объекта через Creator, если точно так же можно его создать через new? Когда нужно использовать именно фабричный метод, и какое преимущество нам это может дать?

A: Выгод может быть много. Некоторые:

*

*Вы можете дать имя вашему конструктору. Например:
Point PointCreator.FromPolar(double r, double phi)

PointCreator.FromPolar читается намного лучше, чем new Point(1, 0).

*Раз уж вы даёте имя, вы можете иметь несколько конструкторов с одинаковыми сигнатурами:
Point PointCreator.FromPolar(double r, double phi) { ... }
Point PointCreator.FromCartesian(double x, double y) { ... }

или например
DateTime DateTime.FromSeconds(double seconds) { ... }
DateTime DateTime.FromMilliseconds(double ms) { ... }

*Вы можете создавать объекты не данного типа, а любого производного, причём конкретный тип может быть скрыт внутри фабрики (так что у вашего остального кода не будет зависимости от этого конкретного типа).

*Вы можете сделать дополнительные действия после окончательного построения объекта. Например, вы можете зарегистрировать объект в списке всех активных объектов. С конструктором такое не очень удобно, т. к. вам придётся делать это либо в конструкторе базового класса, и выкладывать ссылку на недоконструированный объект (что может привести к понятным проблемам, если кто-то в этот момент обратится к объекту), либо дублировать код во всех потомках (что не всегда возможно, и непроверяемо, так что провоцирует баги).
Или вы можете сделать дополнительную инициализацию свойств объекта, если вам это нужно:
WebRequest InitWebRequest(string uri)
{
    var request = WebRequest.Create(uri);
    request.Credentials = new NetworkCredential(Settings.Login, Settings.Password);
    return request;
}

*Вы не можете сделать конструктор асинхронным, а фабричный метод — можете. В самом фабричном методе вы можете вызвать конструктор и async-метод для инициализации.
async SerialDevice Create(PortInfo portInfo)
{
    var device = new SerialDevice(portInfo);
    await device.Connect();
    return device;
}

A: Проблема в самом операторе new. Используя его, вы каждый раз создаёте экземпляр конкретного типа. А фабричный метод позволяет абстрагироваться от конкретных типов и передать ответственность за создание экземпляров реализации этого паттерна. На выходе вы получаете некий абстрактный тип Product, который обладает теми или иными интересующими вас свойствами, но конкретная реализация которого вам не важна.


text:
Q: XTEA encryption in PHP and decryption in C I'm trying to establish communication between a website and an Arduino. I need to authenticate all the messages from my website to the Arduino, so I have found that the less time expensive way is using XTEA cryptography.
My PHP code for the website is:
mcrypt_encrypt(MCRYPT_XTEA, 'qwertyuiasdfghjk', 'asdfasdf', MCRYPT_MODE_ECB);

where "qwertyuiasdfghjk" is a 128 bits key and "asdfasdf" is a 64 bits message.
On the Arduino side I'm using:
void _xtea_dec(void* dest, const void* v, const void* k)
{
    uint8_t i;
    uint32_t v0=((uint32_t*)v)[0], v1=((uint32_t*)v)[1];
    uint32_t sum=0xC6EF3720, delta=0x9E3779B9;
    for(i=0; i<32; i++)
    {
        v1 -= ((v0 << 4 ^ v0 >> 5) + v0) ^ (sum + ((uint32_t*)k)[sum>>11 & 3]);
        sum -= delta;
        v0 -= ((v1 << 4 ^ v1 >> 5) + v1) ^ (sum + ((uint32_t*)k)[sum & 3]);
    }
    ((uint32_t*)dest)[0]=v0; ((uint32_t*)dest)[1]=v1;
}

where the parameters are:
char dest[9]; //Destination
char v[9]; //Encrypted message
char k[17]; //Key

but my decrypted message is far away from the original message... It still having 64 bits, but it is totally different...
What should I do?
(This is the first time that I ask a question here, usually I all my questions are solved somewhere in Stack Overflow...)

A: Most likely your cipher keys are different. Make sure they are the same in both ends.
C:
  // "annoying monkey"
  uint32_t key[4] = {0x6f6e6e61, 0x676e6979, 0x6e6f6d20, 0x0079656b };

PHP:
 mcrypt_encrypt(MCRYPT_XTEA, 'annoying monkey', 'data', MCRYPT_MODE_ECB);

A: As far as I remember, the XTEA specification did not provide test vectors and your code does not seem to care about endianness. Most probably it is a matter of key or data assumed/being in the wrong endian. Look at the implementation of mcrypt_encrypt function in the PHP source.


text:
Q: Wanted to create dynamic string in C , but instead of that program makes infinite loop of input char char *increaseSize(char *myString,int size) {

    char *newString = (char*)malloc((size + 1) * sizeof(char));//new char[size + 1];

    for (int i = 0; i < size; i++) {
        if(myString[i] != '\0')
        newString[i] = myString[i];
    }
    newString[size - 1] = getch();
    printf("%c",newString[size - 1]);
    newString[size] = '\0';
    free(myString);

    return newString;
}

int main()
{

    int size = 1;
    char *myString = (char*)malloc((size + 1) * sizeof(char));
    myString[0] = '\0';
    do{
        myString = increaseSize(myString, size);
        size++;

    } while (myString[size - 1] != 13 || myString[size - 1] != '\n');
    printf("\n");
    free(myString);
    return 0;
}

Would like to know why after input "Enter" my loop does not stop.

A: Look at this line:
} while (myString[size - 1] != 13 || myString[size - 1] != '\n');

The condition is "while A is true or B is true" where either A or B is always going to be true since they complement each other! Because that condition is "I have an X, if X is not equal to two things simultaneously..."
Solution:
} while (myString[size - 1] != 13 && myString[size - 1] != '\n');

A: Your loop condition is always true:
} while (myString[size - 1] != 13 || myString[size - 1] != '\n');

Suppose myString[size - 1] is equal to '\n'.  The second condition is false but the first is true.  And because the logical OR operator || evaluates to true if either of the operands evaluate to true, then the result is true.  The same applies if myString[size - 1] is 13 (better: '\r').
What you want is the logical AND operator &&, which requires both operands to be true to evaluate to true:
} while (myString[size - 1] != '\r' && myString[size - 1] != '\n');

A: The first problem in your code is this statement:
size++;

After returning from increaseSize() you are increasing modifying size value (doing size++) and then checking for myString[size - 1] value.
Move size++ above increaseSize() call:
size++;
myString = increaseSize(myString, size);

Second problem is || used in while condition:
while (myString[size - 1] != 13 || myString[size - 1] != '\n');

Replace || with &&:
while ((myString[size - 1] != 13) && (myString[size - 1] != '\n'));

After making above changes, you will face one more problem with your code.
When you enter a character and press Enter key, the \n character will be in input buffer and in next call to increaseSize() function the getch() will read that stray \n character and program will exit. You need to clean up the input buffer after reading character from user.


text:
Q: Cordova error -> failed to fetch platform wp8 Error: Failed to fetch platform wp8
Probably this is either a connection problem, or platform spec is incorrect.
Check your connection and platform name/version/URL.
Error: cmd: Command failed with exit code 1 Error output:
npm ERR! code E404
npm ERR! 404 Not Found: wp8@latest


text:
Q: How can I monitor disk access for a certain file? I want to use performance monitors to determine when a file is being accessed (read/write). Is this possible? If not, is there any other way?
My OS is Windows Server 2008 R2, and I am writing the code in C#.

A: For what its worth, you can use FileSystemWatcher to monitor writes to a specific file.

A: Unfortunately I don't think there is an API available for doing this using managed code.  If you need to hook a file system read or write event, you should look into writing a filter driver.  Filter drivers are pretty low-level constructs and if it's only to do performance monitoring then it's probably not worth it. This API is often utilized by anti-virus or backup/replication software developers.


text:
Q: How can I make screenshot of the part of the screen with ImageMagick? I use Windows 8. I have coordinates of the part of the screen and I want to make screenshot only of that rectangle. How can I do it with ImageMagick?

A: If you have at least ImageMagick 6.8.9-0 you can do the following to take a screenshot of part of your screen:
convert screenshot: -crop 100x100+500+500 screenshot.png

In example above,  -crop operation cuts out a rectangle that is 100x100 (width and height) at position 500x500 (x and y of the top left corner of the rectangle). And if your computer has multiple monitors you can specify an index screenshot:[1]. The index of the monitor starts with 0, so first monitor will have index 0.
convert screenshot:[1] -crop 100x100+500+500 screenshot.png


text:
Q: What is the correct syntax to do arithmetic for length and dimensionless macros? I want to set papersize based on PSTricks settings. The PSTricks settings may be a value without dimension and/or a value with dimension.
Honestly I have not read the TeXBook because of my laziness. I just read some examples from others but I don't know the hidden theory. For short, I have two questions as follows.

*

*why does the following calculation not work? How should I do arithmetic for values with dimension and without dimension.

*what is the best practice to reduce the rounding error for complicated length and dimensionless value calculation?

\documentclass{minimal}
\usepackage{pstricks}
\psset
{
    xunit=2cm,
    yunit=1cm
}

\newcommand\Left{-4}
\newcommand\Right{4}
\newcommand\Bottom{-4}
\newcommand\Top{4}
\newcommand\Padding{0}

\topmargin=-72.27pt
\oddsidemargin=-72.27pt
\parindent=0pt
\paperwidth=\dimexpr\Right\psxunit-\Left\psxunit+2\Padding\psxunit\relax
\paperheight=\dimexpr\Top\psyunit-\Bottom\psyunit+2\Padding\psyunit\relax
\special{papersize=\the\paperwidth,\the\paperheight}

\begin{document}
\begin{pspicture}(\Left,\Bottom)(\Right,\Top)
\psframe(\Left,\Bottom)(\Right,\Top)
\end{pspicture}
\end{document}

A: You are actually doing \psxunit times 4-(-4)+20 = 28.
\paperwidth=\dimexpr\psxunit*\numexpr(\Right-\Left+2*\Padding)\relax

The 2\Padding bit expands to "20".

A: Because egreg's suggestion using \numexpr cannot be used for non-integer values, I have to use my own as follows. It works but it seems to be too complicated and needs further simplification.
\documentclass{minimal}
\usepackage{pstricks}
\psset
{
    xunit=1cm,
    yunit=1cm
}

\newcommand\Left{-1}
\newcommand\Right{1}
\newcommand\Bottom{-1}
\newcommand\Top{1}
\newcommand\Padding{0.35}

\topmargin=\dimexpr\Padding\psyunit-72.27pt\relax
\oddsidemargin=\dimexpr\Padding\psxunit-72.27pt\relax
\parindent=0pt
\paperwidth=\dimexpr\Right\psxunit-\Left\psxunit+2\dimexpr\Padding\psxunit\relax\relax
\paperheight=\dimexpr\Top\psyunit-\Bottom\psyunit+2\dimexpr\Padding\psyunit\relax\relax
\special{papersize=\the\paperwidth,\the\paperheight}

\begin{document}
\begin{pspicture}[showgrid](\Left,\Bottom)(\Right,\Top)
\psframe(\Left,\Bottom)(\Right,\Top)
\end{pspicture}
\end{document}


text:
Q: Can imbalance in class ratio in training and testing set cause poor validation accuracy? I'm participating in a hackathon where we are supposed to predict whether a user is interested in jobs given features  like gender, city, training hours, experience, current company etc.
In training set there are about 90% who are not interested in jobs while only 10% who are.
But in the public testing set they have released there are 50% of each of those 2 classed and my validation accuracy is not going above 55% while training accuracy is 99%.
Both testing and training data have missing values and I'm imputing it using RBM.
My question is:
Validation accuracy is terrible because of the imbalance in ratio of classes or is it due to wrongly imputing the missing values?

A: Explanation:
Ok I think you need to resample your data first, because your algorithm learns that most of the people are not interessted in jobs and that's true if we just look at the distribution of your training data (90% not interested, 10% interested). Your algorithm just assumes the answer is always "not interested". That's why you reach a high accuracy on the training set.
In your test data the distribution changed to 50%:50%. Your algorithm still assumes all persons are "not interested" and fails in predicting the interested ones. (Your accuracy decreases on the test set to roughly 50%)
How to solve this problem:
Resample your training data to match the 50%:50% distribution in the training set. There are different resampling methods available. Some examples are:

*

*Under-Sampling

*Over-Sampling

*Synthetic Minority Over-Sampling Technique (SMOTE)

Under-Sampling: downsamples the majority class by removing items. In your case it would be (10% interested and 10% not interseted).The disadvantage is that you would just learn on 20% of the available training data.
Over-Sampling: upsamples the minority class by adding redundant points. Advantage: You would use all your data.
Disadvantage: Could lead to overfitting.
SMOTE: a more sophisticated over-sampling method, whichs adds synthetic samples.
I would try to start using simple over- and check if this solves your problem.
For python you could use the so called imbalanced-learn package, which contains all of the stated methods here.


text:
Q: Swift_TransportException Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required " I am new to Laravel and looking to enhance my skills in using Laravel framework 5.4. But I don't know what to do when I encounter this error: 1/1) Swift_TransportException Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required Is it .

A: make sure that you are using the mail credential in .env file. i think you try to send mail without using the mail credentials.so,
create credentials on sendgrid or any mail service for send mail and put these credentials in .env file.

MAIL_DRIVER=smtp
MAIL_HOST=smtp.sendgrid.net
MAIL_PORT=587
MAIL_USERNAME=your credentials username
MAIL_PASSWORD=your secret key
MAIL_ENCRYPTION=tls

A: replace this
'username' => env('ivanedu947@gmail.com'),
'password' => env('password'),
to this
'username' => env('MAIL_USERNAME','miemail@gmail.com'),
'password' => env('MAIL_PASSWORD','password'),
and on php line comand key
php artisan config:cache
and its must be works


text:
Q: ExtJS 4 code assist in Aptana 3 I started using ExtJS 4 framework for generating chart report in a web app development project.
I am looking for up-to-date code assist for ExtJS 4 to release me from too much typing. I tried for long to find one, but it looks like all of them are out-of-date.
If anyone currently using ExtJS 4 code assist in Aptana (or some other IDE). Please give me a hand. Thanks!

A: Great! Finally find this thread which answers my question.
Download extjs4.1.beta-v0.1.sdocml can add code hinting into your ExtJS 4 Aptana project.
There is a lot instructions for adding Spket plugin to Eclipse/Aptana for ExtJS support. But it just never works for me...Not sure if anyone used it and get it worked out.
UPDATE: I am using WebStorm for ExtJS 4 development now, it has very good ExtJS support. Actually all the js files included in the project can be identified in WebStorm and thus code hinting is listed.


text:
Q: java struts2 very strange behaviour while using iterator public class UserAction{
 private UserData user;
 //getter, setter
  public String Load() {
        user = UserDao.getInstance().getItem(getUserContext().getId());
        request.getSession().setAttribute("item", user);
        return super.Load();
    }
}

public class PropertyAction {
    private List <PropertyData> propertyList;
    //getter, setter
    @Override
    public String execute() throws Exception {
        propertyList=PropertyDao.getInstance().getItems();
        return "list";
    }
}

jsp:
<s:iterator value="propertyList" var="item">
    ${item.name}
    ${item.thema}
    ${item.desc}
</s:iterator>

I want to show very strange behaviour of Struts2.

*

*I click property link -> then run PropertyAction.execute() and it display above jsp.

*I click user link -> then run UserAction.Load()

*I click property link -> then run PropertyAction.execute() and error has been shown "UserData has no property thema".

I spy what happened and I notice that I set setAttribute with name "item". So if I use var="item" in my iterator in jsp,  it doesn not use value from propertyList but from session !
My question is it is correct behaviour  ?

A: This is defined behavior; whether or not it's "correct" is debatable.
Because you're using JSP EL, the Struts request wrapper is responsible for resolving JSP EL expressions. The normal application scopes are searched first (e.g., application, session, request). If nothing is found, only then will the value stack be queried for matching expressions.
If you accessed item via non-JSP EL means, e.g., the <s:property> tag, only the value stack would be queried, and you'd get the expected behavior.
When you mix ELs results are not always what you'd expect, so you must be aware how the frameworks in question relate to each other.


text:
Q: Increase right margin of header I want to include a graphic into the header but this should be placed outside the page margins. I have
\documentclass[a4paper,11pt,naustrian]{article}
\usepackage[left=2.5cm, right=4.5cm, top=2cm, bottom=2cm,  showframe]{geometry} % for margins on a A4paper

\usepackage{lastpage}
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhf{}
\renewcommand{\headrulewidth}{0pt}
%\renewcommand{\footrulewidth}{0pt}
\setlength\headheight{61pt}
\addtolength{\textheight}{-61.0pt}
\rhead{
\includegraphics[height=2cm]{MyLogo}}

\usepackage{kantlipsum}
\begin{document}
    \kant[1-8]
\end{document}

So the logo ends at the frame, i.e. 4.5cm from the right page. But I would like to shift the logo so it ends with a distance to the right paper frame of 2.5cm.
I didn't find any solutions.
Using luatex 1.13.2

A: I would do it with pictureenvironment
\documentclass[a4paper,11pt,naustrian]{article}
\usepackage[left=2.5cm, right=4.5cm, top=2cm, bottom=2cm, showframe]{geometry} % for margins on a A4paper

\usepackage{lastpage}
\usepackage{fancyhdr}
\usepackage{graphicx}
\usepackage{kantlipsum}

\pagestyle{fancy}
\fancyhf{}
\renewcommand{\headrulewidth}{0pt}
%\renewcommand{\footrulewidth}{0pt}
\setlength\headheight{61pt}
\addtolength{\textheight}{-61.0pt}

\rhead{
    \begin{picture}(0,0) \put (0,0){
            \includegraphics[height=2cm]{MyLogo}}
    \end{picture}
}

\begin{document}
    \kant[1-8]
\end{document}


text:
Q: QIWI API. Получаем баланс в Гугл таблицу Пытаюсь получить в гугл таблице баланс кошелька Киви. Делаю через Apps Script.
function bankbalans() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Прайс");
  var row = sheet.getRange(2,2);

  var options = {
    method: "GET" ,
    headers: {
    "Bearer" : "6d42cc2caf5da45d19d54bf37f3e7ea"
   }
   }
var response = UrlFetchApp.fetch("https://edge.qiwi.com/funding-sources/v2/persons/79173824745/accounts",options);
Logger.log (response)

}

Получаю в ответ ошибку. Токен и номер правильный. Почему не могу получить авторизацию?
Exception: Request failed for https://edge.qiwi.com returned code 401. Truncated server response: {"serviceName":"funding-sources","errorCode":"auth.unauthorized","description":"Unauthorized access","userMessage":"Unauthorized access","dateTime"... (use muteHttpExceptions option to examine full response)

https://developer.qiwi.com/en/qiwi-wallet-personal/#balance

A: Вы неверно добавляете заголовок. В документации явно написано:

Итоговый заголовок, добавляемый в каждый запрос к API QIWI Кошелька:
Authorization: Bearer U1QtOTkwMTAyLWNud3FpdWhmbzg3M


text:
Q: Populate a DataTable with MySQL Database I'm trying to build a CRUD application. I have a MySQL database of a large amount of records and would like to use a JQuery DataTable rather than trying to code out a table from scratch. The problem I have, is that I can see the table on my site, but I cannot get it to pull in the data from MySQL.
I've tried reading many site and forums including the official documentation on DataTable's website, but none of it makes sense to me.
What do I need to do to fix this? I've been working on this project for a solid week and am getting frustrated.
<?php

/*
 * DataTables example server-side processing script.
 *
 * Please note that this script is intentionally extremely simple to show how
 * server-side processing can be implemented, and probably shouldn't be used as
 * the basis for a large complex system. It is suitable for simple use cases as
 * for learning.
 *
 * See http://datatables.net/usage/server-side for full details on the server-
 * side processing requirements of DataTables.
 *
 * @license MIT - http://datatables.net/license_mit
 */

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Easy set variables
 */

// DB table to use
$table = 'members';

// Table's primary key
$primaryKey = 'id';

// Array of database columns which should be read and sent back to DataTables.
// The `db` parameter represents the column name in the database, while the `dt`
// parameter represents the DataTables column identifier. In this case simple
// indexes
$columns = array(
    array( 'db' => 'id', 'dt' => 0 ),
    array( 'db' => 'name',  'dt' => 1 ),
    array( 'db' => 'residential_address', 'dt' => 2 ),
    array( 'db' => 'mailing_address', 'dt' => 3 ),
    array( 'db' => 'precinct', 'dt' => 4)
    array( 'db' => 'age', 'dt' => 5 ),
    array( 'db' => 'ethnicity',  'dt' => 6 ),
    array( 'db' => 'gender', 'dt' => 7 ),
    array( 'db' => 'party', 'dt' => 8 ),
    array( 'db' => 'race', 'dt' => 9 ),
    array( 'db' => 'phone', 'dt' => 10 )
);

// SQL server connection information
$sql_details = array(
    'user' => 'root',
    'pass' => '',
    'db'   => 'ccrp_db',
    'host' => 'localhost'
);

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * If you just want to use the basic configuration for DataTables with PHP
 * server-side, there is no need to edit below this line.
 */

require( 'ssp.class.php' );

echo json_encode(
    SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);
?>

Below is also my HTML code for reference:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">

  <title>Cabarrus County Republican Party | Member Database</title>

  <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">

  <link href="css/sb-admin-2.min.css" rel="stylesheet">

  <link href="vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet">

  CCRP

          Database

        User Interface

          Menu

Update Database

            Add New Members
            Email (beta)
            Mass Email (beta)

User Account

            Login
            Register
            Forgot Password

        <button class="rounded-circle border-0" id="sidebarToggle"></button>

          <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">

          </button>

          <form class="d-none d-sm-inline-block form-inline mr-auto ml-md-3 my-2 my-md-0 mw-100 navbar-search">

              <input type="text" class="form-control bg-light border-0 small" placeholder="Search for..." aria-label="Search" aria-describedby="basic-addon2">

                <button class="btn btn-primary" type="button">

                </button>

          </form>

                <form class="form-inline mr-auto w-100 navbar-search">

                    <input type="text" class="form-control bg-light border-0 small" placeholder="Search for..." aria-label="Search" aria-describedby="basic-addon2">

                      <button class="btn btn-primary" type="button">

                      </button>

                </form>

                Valerie Luna

                  Profile

                  Settings

                  Activity Log

                  Logout

Members List

Cabarrus County Republican Party

                      ID
                      Name
                      Residential Address
                      Mailing Address
                      Precinct
                      Age
                      Ethnicity
                      Gender
                      Party
                      Race
                      Phone Number

                      ID
                      Name
                      Residential Address
                      Mailing Address
                      Precinct
                      Age
                      Ethnicity
                      Gender
                      Party
                      Race
                      Phone Number

            Copyright © Casco Signs Inc. 2019

Ready to Leave?

          <button class="close" type="button" data-dismiss="modal" aria-label="Close">
            ×
          </button>

Select "Logout" below if you are ready to end your current session.

          <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
          Logout

A: Now that you've got your MySQL data into JSON using PHP, use DataTable's AJAX option to make it reflect your table:
$(document).ready(function() {
    $('#example').DataTable( {
        "processing": true,
        "serverSide": true,
        "ajax": "../server_side/scripts/server_processing.php" // your php file
    });
});

A: Though I see that it is fixed, I share this so that others reading this topic can get help.
Here is one of the solutions:
After getting json response, you can populate datatable by following the practice based on this jsfiddle link:
http://jsfiddle.net/gh/get/jquery/2.2/chennighan/RapidlyPrototypeJavaScript/tree/master/lesson4/
$(function() {
  $("#example").DataTable();

  // Premade test data, you can also use your own
  var testDataUrl = "https://raw.githubusercontent.com/chennighan/RapidlyPrototypeJavaScript/master/lesson4/data.json"

  $("#loadData").click(function() {
    loadData();
  });

  function loadData() {
    $.ajax({
      type: 'GET',
      url: testDataUrl,
      contentType: "text/plain",
      dataType: 'json',
      success: function (data) {
        myJsonData = data;
        populateDataTable(myJsonData);
      },
      error: function (e) {
        console.log("There was an error with your request...");
        console.log("error: " + JSON.stringify(e));
      }
    });
  }

  // populate the data table with JSON data
  function populateDataTable(data) {
    console.log("populating data table...");
    // clear the table before populating it with more data
    $("#example").DataTable().clear();
    var length = Object.keys(data.customers).length;
    for(var i = 1; i < length+1; i++) {
      var customer = data.customers['customer'+i];

      // You could also use an ajax property on the data table initialization
      $('#example').dataTable().fnAddData( [
        customer.first_name,
        customer.last_name,
        customer.occupation,
        customer.email_address
      ]);
    }
  }
})();


text:
Q: webob cookies I am not able to set cookies using following statements
        self.request.headers['Cookie'] = 'uniqueid = ',unique_identifier
        self.request.headers['Cookie'] = 'nickname = ',nickname

as
     self.request.cookies
is returning null dictionary in another request.
environment is python on google app engine

A: Changing the cookies in the request does nothing to the cookie on the client.
You need to set the "Set-Cookie" header in the response to the client.
You could use something like this (untested by me) Google App Engine Cookie class

A: The WebOb Reference explains set_cookie well - if youre on a framework using the WebOb Response (not valid for Google App Engine, it uses an own Repsonse)


text:
Q: Change drop-down labels for Django UserAdmin I have a User model with a timezone field on it:
class User(AbstractBaseUser, PermissionsMixin):
    timezone = models.CharField(
        max_length=64,
        choices=[(tz, tz) for tz in pytz.common_timezones],
        default="UTC",
    )

When viewed in Django admin, this creates a drop-down list of timezones, but only of the names. I would like to dynamically generate labels for this drop-down that add the offset as a prefix (e.g. +02:00) and sort the list by that. I know I can create these by doing something like:
choices=[
    (tz, display_with_offset(tz))
    for tz in pytz.common_timezones
],

where display_with_offset generates the required label, but I think this would only calculate it when the migrations are run and would ignore any daylight savings changes that happen throughout the year for some regions.
My admin file looks like this:
class MyUserAdmin(UserAdmin):
    fieldsets = [
        ("Info", {"fields": ("timezone")}),
    ]

admin.site.register(models.User, MyUserAdmin)

Is there a way I can dynamically set the drop-down labels?

A: You can create a ModelForm and override the choices. For example:
class UserAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
      super().__init__(*args, **kwargs)
      self.fields['timezone'].choices = [
          (tz, display_with_offset(tz)) for tz in pytz.common_timezones
      ]

    class Meta:
        model = User
        fields = '__all__'

class MyUserAdmin(UserAdmin):
    fieldsets = [
        ("Info", {"fields": ("timezone")}),
    ]
    form = UserAdminForm

More information can be found in documentation.


text:
Q: How do you save an array to session storage? I've read a few similar threads, but the solutions are not working for me. The page I am working on has filters for a gallery of images. Each time I click on a filter the images with reload according to that filter via a JSON file.
If I want to apply multiple filters I would need the ones chosen prior to the reload to save in an array variable.
This is the code I have for this
let filterArray = []

sessionStorage.setItem('filterArray', JSON.stringify(filterArray))

let savedArr = JSON.parse(sessionStorage.getItem('filterArray'))

Right now I don't have the page reload set up but after clicking on a filter and refreshing the page I would expect to be able to log the 'savedArr' variable but when I do I get this:

Uncaught ReferenceError: savedArr is not defined
      at :1:13

A: You can't log savedArr after you refresh the page, you need to redefine it.
The data in session storage will persist, but your variable declarations will not.
Call the declaration line again after you reload the page and you will have access to the data.
let savedArr = JSON.parse(sessionStorage.getItem('filterArray'))


text:
Q: Xcode Git issues with Google Drive/Dropbox Apparently XCode should recognize a git repo automatically, but after doing git init and my initial commit, XCode is not seeing the repo. I have my entire project and git repo in Google Drive, and I suspect that is causing some issue? What do I have to do to get XCode to read .git files in Google Drive?
EDIT
I tried doing a git init, add and commit to a project in my local drive and XCode still didn't recognize the git store, so this may not be a G Drive/Dropbox issue.

A: Don't put a Git repo on Dropbox or Google Drive. It is terrible. Dropbox, on sync, can scramble all git's internal files and screw it up your whole repository.
Instead, use a Git service. For something private, I recommend BitBucket.
Exemplifying:
Imagine you put your main repository on Dropbox. You sync your dropbox in another computer and pushes to it. The connection drops from that computer. You go to other computer, make another commit and pushes into the main repository. Everything goes fine.
Dropbox starts to sync in this computer. At the same time, the other computer starts to sync, too. But internally, there are lots of different files on the repo. How Dropbox knows how to keep and organize these files?
Simple answer: it doesn't. It will damage your repository, and that's nothing you can do about it. And this is not some kind of "it will almost never happen". It will happen, very soon.
And about the real question:
I never used Xcode, but I had similar issues with Eclipse. It's simple, though: Xcode does not know about the repo because you did not tell him that is a repo. To see how to do that on Xcode, you could see here.


text:
Q: DomSanitizationService is not a function As people always say there is no question called a dumb question.
I am learning Angular 2.0 following the official tutorial now. It is using rc2.0 as I can see from the packageconfig file. I was trying to suppress the frame work complaining the "Unsafe" url in the iFrame tag.
I have checked the instructions from this Stack Overflow Question
and followed everything that's been shown in the LIVE Plunker.
My VS Code doesn't complain anything in the compile time but from the Chrome inspector I can see the error.

Following are the TS file of my project.

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute }       from '@angular/router';
import { ParcelsService } from './parcels.service';
import { SafeResourceUrl, DomSanitizationService } from '@angular/platform-browser';
import { Parcel } from './mock-parcels';
@Component({
  template: `

Parcels

"{{parcel.checkUrl}}"

      <button (click)="gotoHeroes()">Back</button>

  `,
  providers:[ParcelsService, DomSanitizationService]
})
export class HeroDetailComponent implements OnInit, OnDestroy  {
  parcel: Parcel;
  safeUrl : SafeResourceUrl;
  private sub: any;
  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private service: ParcelsService,
    private sanitizer: DomSanitizationService) {}
  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
       let id = +params['id']; // (+) converts string 'id' to a number
       this.parcel = this.service.getParcel(id);
     });
     this.safeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.parcel.checkUrl);

  }
  ngOnDestroy() {
    this.sub.unsubscribe();
  }
  gotoHeroes() { this.router.navigate(['/heroes']); }
}

Has anyone ever come across similar issue? Please help to find what I have done wrong.
Thanks

A: You have to import and provide the BROWSER_SANITIZATION_PROVIDERS:
import { BROWSER_SANITIZATION_PROVIDERS,
         SafeResourceUrl,
         DomSanitizationService } from '@angular/platform-browser';

and in your providers array:
providers: [ParcelsService, BROWSER_SANITIZATION_PROVIDERS]

UPDATE: for the final release things changed a little

import { __platform_browser_private__,
         SafeResourceUrl,
         DomSanitizer } from '@angular/platform-browser';

and add it to the providers like so:
providers: [ParcelsService, __platform_browser_private__, BROWSER_SANITIZATION_PROVIDERS]

UPDATE FOR ANGULAR 4+: since Angular 4, there's some changes:

Now, you don't have to pass DomSanitizer to providers. You can import directly in your component and grab it in the component's constructor. Same goes for SafeResourceUrl.
Also:

*

*__platform_browser_private__ is no longer in @angular/platform-browser.

*BROWSER_SANITIZATION_PROVIDERS is no longer in @angular/platform-browser. It is now implemented [as a provider] into BrowserModule which can be imported from @angular/platform-browser.

*P.S. BrowserModule is usually added into your app.module
module's imports array.

A: Update for Angular 7:  The export has been renamed   eBROWSER_SANITIZATION_PROVIDERS in angular/platform-browser/src/private_export.d.ts


text:
Q: Annotating optional param with @Nullable in google app engine Endpoints drops the parameter @ApiMethod(name = "foo")
public void foo(@Nullable @Named("bar") String bar, User auth) throws OAuthRequestException

ends up generating an API where the foo method takes NO bar parameter. If I do not annotate with @Nullable, and just pass null from the client, I get an exception at runtime.
I'm sure this must be supported and I'm just doing something stupid. Thanks.

A: After a lot of googling, found the answer here
@Nullable @Named in GAE / Android Sample
Basically, endpoints will generate a setXXX method which will accept your optional parameter. You ARE allowed to pass null to it so no need for if/else check where you only invoke the set API if your param is not null. Nifty.

A: was delayed understood without an example, here I write to compliment response of @Creos
collectionResponse = myApiService.activityByDay(idWebSafeFamily, token.getToken(), token.getTokenIdWebSafe(), nextPageToken).setIdUser(idUser).execute();


text:
Q: Equal Probability Game with 3 Players I have a probability question that I've solved the "long" way using a probability table, and I'm wondering if there is a faster way to solve this?
"For a 3-player game, the first person to win 4 rounds wins. They are equally matched, so the probability any one of them wins a round is 1/3. The players are forced to quit after 6 rounds, with player A having won 3 rounds, player B having won 2 rounds, and player C 1 round. At this point, the probability of player A winning should be...?"
I figured out that they need to do at most 4 more rounds (rounds 7, 8, 9, and 10), and that there are 81 total rows in my table. They're filled out and I have an answer (player 1 wins 57/81 possible rounds). BUT --- it just seems like so much work! Is there a more efficient way to solve a problem like this?
Edit to add: I'm going to look more into Pascal's work where I think I may find an answer (since this is based on some of his early work) --- but other ideas are always appreciated!

A: You don't actually have to make the whole chart; you can count the relevant outcomes fairly easily without doing so.
As you say, the game must finish in at most $4$ more rounds; it takes $4$ more rounds if $B$ wins one and $C$ wins two of the next $3$ rounds, at which point each player has won $3$ rounds.
Imagine that they go ahead and play $4$ more rounds, even if one of them wins the game before the $4$ rounds are complete. There are $3^4=81$ possible sequences of winners of these $4$ rounds. We want to count the sequences in which $A$ gets a win before $B$ gets $2$ or $C$ gets $3$ and divide this number by $81$. We can count them separately for each possible position of $A$'s first win.

*

*There are $3^3=27$ sequences that start with $A$, since there are $3$ choices for the winner of each of the last $3$ rounds; all of them are wins for $A$.

*There are $2\cdot3^2=18$ sequences in which $B$ or $C$ wins the first round and $A$ wins the second; these are also all wins for $A$.

*There are $2\cdot3=6$ sequences that start $BCA$ or $CBA$, and $3$ more that start $CCA$; these too are wins for $A$. (That is, if $A$'s first win is the third round, $A$ wins the game unless $B$ won the first two rounds.)

*Finally, $A$ wins the game in the fourth round if and only if $B$ wins one of the first three rounds and $C$ wins two, so $A$ wins the game with the $3$ sequences $CCBA,CBCA$, and $BCCA$.
$A$ therefore wins the game in $27+18+9+3=57$ of the $81$ possible outcomes, or with probability $\frac{57}{81}=\frac{19}{27}$.


text:
Q: How to create a "Waze like" progress button in Android: I'm looking for a way to produce a button with progress functionality (the button is pressed at the end of the progress...) like in Waze, here in an example (the "Go now" button):

I found this solution:
Create rectangle border progress bar in android
And here is the result of the implementation made there:

But unfortunately this is not good enough (I can't changes the button corner radius to something round and the side progresses moving in a different speed the the top and the bottom progress).
From a check I made the Waze app creates the progress using a canvas and by painting paths on it. How can this be done?


text:
Q: A word describing physical or online address I'm working on an application that tracks accredited activities doctors can participate in and gain credits. These can be seminars, online courses etc. What should I call the field whose value can be either a physical address (i.e. the address of a hotel) or a URL?
Could 'venue' be used when referring to a URL of an online course?

A: Location.

a place where something happens or exists; the position of something

Oxford

A Uniform Resource Locator (URL), colloquially termed a web address, is a reference to a web resource that specifies its location (emphasis added)

Wikipedia
The term location is well known both in the sense of a web address, and a physical place.


text:
Q: How get navigation control from a button? I know if I used a view controller I can use this:
var scanner = new MobileBarcodeScanner(this.NavigationController);

How do I know what navigation I am using inside of button I need use?
public class BarReaderButtonRenderer : ButtonRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
    {
        base.OnElementChanged(e);

        // I tried this but don't worked
        var scanner = new MobileBarcodeScanner(this.NavigationController);

        // I tried this but do
        var scanner = new MobileBarcodeScanner(this);

        Element.Clicked += async(s_, e_) => {
            // Setup our button
            // Tell our scanner to use the default overlay
            scanner.UseCustomOverlay = false;

            //We can customize the top and bottom text of the default overlay
            scanner.TopText = "Hold camera up to barcode to scan";
            scanner.BottomText = "Barcode will automatically scan";

            //Start scanning
            var result = await scanner.Scan ();

            HandleScanResult(result);
        };
    }
}

I can't use this code inside a button render. Or did someone this before?
The project is a shared application for iOS and Android.

A: The code for creating the scanner should stay inside the view controller/activity/page. You can still use the custom button and add the code you need to the Clicked event handler.
var myCustomButton = new BarReaderButton();

myCustomButton.Clicked += async(s, e) => {
        var scanner = new MobileBarcodeScanner();
        scanner.UseCustomOverlay = false;

        //Start scanning
        var result = await scanner.Scan ();

       //Do something with the result
    };

If this is Xamarin.Forms you will also have to use platform specific code inside the Page code as the barcode reader requires a Context on Android:
#if __IOS__
var scanner = new MobileBarcodeScanner();
#elif __ANDROID__
var scanner = new MobileBarcodeScanner(Forms.Context);
#endif


text:
Q: Javascript object with .push() method I want to create javascript object using .push() Method and create Key Value Pair.
I have tried it, but it doesn't work.
$("input[name^=ang_nama]").each(function() {
   arr_nama.push($(this).attr('id'):$(this).val());
});

Any solutions?

A: You seem to want this :
var arr_nama = [];
$("input[name^=ang_nama]").each(function() {
   var obj = {};
   obj[this.id] = $(this).val();
   arr_nama.push(obj);
});

A few observations :

*

*don't use $(this).attr('id') when you can use this.id !

*you have to initialize the array before you push to it

*you can't directly create an object literal with a dynamic property name, you must create the object first

Another cleaner solution would be
var arr_nama = $("input[name^=ang_nama]").map(function() {
   var obj = {};
   obj[this.id] = $(this).val();
   return obj;
}).get();

Demonstration
Note that this creates an array. If what you wanted is a unique object, use this :
var arr_nama = {};
$("input[name^=ang_nama]").each(function() {
   arr_nama[this.id] = $(this).val();
});

Demonstration

A: Try
var obj = {};
obj[$(this).attr('id')] = $(this).val();
arr_nama.push(obj);

A: Try this, add curly braces while pushing
$("input[name^=ang_nama]").each(function() {
     arr_nama.push( { $(this).attr('id'):$(this).val() } );
});


text:
Q: Get Yoast Plugin infos on publish_post Wordpress I'm trying to get yoast plugin infos on publish_post, I know that get_post_meta is fired after publish_post but don't see how could I grab the posted values on publish_post...I thought by getting $_POST values it could work, but seems not.
My code so far is:
add_action( 'publish_post', 'post_published_notification');
function post_published_notification( $ID, $post ) {
            $url = $post->post_name;
            $yoast_seo_title = get_post_meta($ID, '_yoast_wpseo_title', true);
            $yoast_meta_desc = get_post_meta($ID, '_yoast_wpseo_metadesc', true);
}

Thanks in advance for your help.
EDIT: Can't hook on save_post or it would be fired twice...

A: Answering to myself:
add_action( 'publish_post', 'post_published_notification');
function post_published_notification( $ID, $post ) {
            $url = $post->post_name;
            if(isset($_POST["yoast_wpseo_title"]) && !empty($_POST["yoast_wpseo_title"])){
                $yoast_seo_title = $_POST["yoast_wpseo_title"];
            }
            if(isset($_POST["yoast_wpseo_metadesc"]) && !empty($_POST["yoast_wpseo_metadesc"])){
                $yoast_meta_desc = $_POST["yoast_wpseo_metadesc"];
            }
}


text:
Q: Incorrect Value after using Fundamental Theorem of Calculus I am trying to solve $$\lim_{x\to 0} \frac{\int_{0}^{x^2} x^2 e^{-t^2} dt}{-1+e^{-x^4}} $$ using The Fundamental Theorem of Calculus (FTC).
I already know that the answer is -1,
Using FTC (correct me if I am wrong) we get:
$$
\lim_{x\to 0} \frac{x^2 e^{-x^4}}{-1+e^{-x^4}}
$$
Which has the result of - $\infty$
I can't seem to know what I am doing wrong.
Thanks in advance

A: Since this is a $\frac{0}{0}$ limit, you can use L'Hospital's Rule. To do so, factor the numerator as $x^2 g(x)$, where $$g(x) = \int_{0}^{x^2} e^{-t^2} dt$$
You are allowed to pull the $x^2$ outside of the integrand as the integral is with respect to $t$. Use FTC (and the product rule) to calculate the derivative of the numerator when you apply L'Hospital's Rule. Then clean up the resulting mess and repeat. Eventually, you should end up with a limit of $-1$.

A: Using the fundamental theorem of calculus you should replace the integral
$$
\int_0^{x^2} e^{-t^2} dx \simeq1 \cdot x^2 = x^2
$$
becaus the mean value of $e^{-t^2}$ near $t=0$ is just 1, and the length of your interval is $x^2$, hence the limit you want is
$$
\lim_{x \to 0 } \frac{x^4}{e^{-x^4}  -1}  = -1
$$

A: You can also do some pre-processing of the term. It is equal to
$$
\left(\frac{e^{-x^4}-1}{x^4}\right)^{-1}·\frac{\int_0^{x^2}e^{-t^2}dt}{x^2}
$$
and thus the limit can be computed by product and quotient rule as
$$
\left(\lim_{h\to 0}\frac{e^{-h}-1}{h}\right)^{-1}·\lim_{s\to 0}\frac{\int_0^{s}e^{-t^2}dt}{s}
$$
which are two difference quotients for the functions $f(x)=e^{-x}$ with $f'(x)=-e^{-x}$ and $g(x)=\int_0^{s}e^{-t^2}dt$ with $g'(x)=e^{-x^2}$.


text:
Q: Opening new window/tab without using `window.open` or `window.location.href` I want to generate a link that is clicked right after creating, but nothing happens
Code:
var link = $("");
link.attr("href", "/dostuff.php");
link.attr("target", "_blank");
link.click();

The attributes are set correctly:
var link = $("");
link.attr("href", "/dostuff.php");
link.attr("target", "_blank");
var linkcheck = link.wrap('
').parent().html();
console.log(linkcheck);

This returns:

No errors

UPDATE
I tried to append it, bind click to it, click it and remove it
var link = $("");
link.attr(
{
    id    : "linky",
    href  : "/dostuff.php",
    target: "_blank"
});
$("body").append(link);
$("#linky").on("click", function() { console.log("Link clicked"); });
$("#linky").click();
$("#linky").remove();

The click action is being executed, but the default action (open the link) isn't..

UPDATE2
I have found the solution: creating and submitting a <form>! See my answer.

A: I have the answer. Apparently jQuery doesn't support the default behavior of links clicked programmatically
Creating and submitting a form works really well though (tested in Chrome 26, FF 20 and IE 8):
var form = $("<form></form>");
form.attr(
{
    id     : "newform",
    action : "https://google.nl",
    method : "GET",
    target : "_blank"        // Open in new window/tab
});

$("body").append(form);
$("#newform").submit();
$("#newform").remove();

What it does:

*

*Create a form

*Give it attributes

*Append it to the DOM so it can be submitted

*Submit it

*Remove the form from the DOM

Now you have a new tab/window loading "https://google.nl" (or any URL you want, just replace it). Unfortunately when you try to open more than one window at once this way, you get an Popup blocked messagebar when trying to open the second one (the first one is still opened).

A: Regarding your updated script: If you get the selector right ($("#linky")) it works.
var link = $("Hello");
link.attr("href", "/dostuff.php");
link.attr("target", "_blank");
$("body").append(link);
$("#linky").on("click", function() {alert("hai");});
$("#linky").click();
$("#linky").remove();

A: var link = $("");
link.attr("href", "/dostuff.php");
link.attr("target", "_blank");
$("body").append(link);
$("linky").live("click", function() {alert("hai"); $(this).remove()});
$("linky").click();
//$("linky").remove();

So you actually react on the click event.
And YES! The question is why would you want to do this?


text:
Q: How to control loading data in angularFire Suppose I have a Firebase like this:

In a factory I create a model:
.factory ('$model', function ($firebase) {
    var ref = new Firebase('https://xxxxx.firebaseio.com/admins/proefje');
    var model = $firebase (ref); // this loads all the data!
    model.loaded = false;

And in my controller I use the model:
.controller('DailyCtrl', function ($scope, $model) {
    $scope.title = 'Daily';
    $scope.data = $model.daily.data;

There are 2 problems:

*

*when the controller is activated, data is still beeing loaded. I think I have to restructure the app a bit to solve this.

*As parts of the data get quite large, I want to control how much data is loaded. I do not want to load all data at once. I tried the limit() function, but that seems not implemented in angularFire. Its not in the docs. I could try to load parts over the $child() function, but the I would still be loading an entire table.
Any thouhts on this?

A: To solve (1), you can make use of the resolve() method in ngRoute. This way you can wait for the the 'loaded' event from $firebase(ref) to fire before reaching the controller.
AngularFire does support limits, simply pass ref.limit() to the $firebase method. You may also directly use the Firebase API as appropriate.


text:
Q: How to add a line break with conditional operators OK, stupid newbie question: how do you make a line break only when it's needed?
I'm creating a basic address listing and only want to include a line of an address if it isn't blank.  How do I keep the blank line from printing?  I've tried including the break and new line tags, and tried using puts and quotation marks of both varieties and escaping the slashes but can't seem to display the address correctly.
Is there a way to have each line of the address to print on its own line or simply omit the line if there is no info to put on it?
Here's the current version of the code:

Main Address

<%= if @vendor.address1 || null
             @vendor.address1  #need a break here
           end %>
      <%= if @vendor.address2 || null
             @vendor.address2 #need a break here
           end %>
      <%= @vendor.city %>, <%= @vendor.state %> <%= @vendor.zip %>

A: This is how I would do it:

  Main Address

<% unless @vendor.address1.blank? %>
  <%= @vendor.address1 %>

<% end %>
<% unless @vendor.address2.blank? %>
  <%= @vendor.address2 %>

<% end %>
  <%= @vendor.city %>, <%= @vendor.state %> <%= @vendor.zip %>

By the way: the || null in your code is not valid Ruby. null does not exist, it should be nil. But even if you had used nil, your code does not do what you expect it to do. For these kind of things, you'd better use blank?.

A:
Main Address

<%= @vendor.address1%><%=
 if @vendor.address1.blank? %>
          <%=  @vendor.address2%><%=
 if @vendor.address2.blank? %>
          <%= @vendor.city %>, <%= @vendor.state %> <%= @vendor.zip %>


text:
Q: How to create a relations between primary key and foreign key in Django models and POST values into DB I have a Django app which is basically an Online shopping. Right now I have two models: User_details and Extend_user_details.
In User_details I have(Username, Firstname, lastname, email, etc..). Now after that i need to extend  User_details Model with Other Fields so I have Created another Model  Extend_user_deatils consisting of (Mobile , Age) columns.
Now I need to Link those Two Models, for that I have written a logic with Foreign Key Reference as:
class User_details(models.Model):                                                     #Table 1
    id = models.AutoField(primary_key=True, db_column='user_id')
    username = models.CharField(max_length=50)
    first_name = models.CharField(max_length=50, blank=True, null=True)
    last_name = models.CharField(max_length=50, blank=True, null=True)
    email = models.CharField(max_length=50)

class Extend_user_details(models.Model):                                              #Table 2
    user =models.ForeignKey(User_details, on_delete=models.CASCADE,db_column='user_id')
    mobile = models.BigIntegerField(blank=True, null=True)
    age = models.IntegerField(blank=True, null=True)

When I Open Django admin Page and Post the Data it is Working Fine and Values are posting into DB.
When I register as a User from register page . ForeignKey Column(user) from Table2 is showing Null .apart from that all the inputs is posting into DB as shown Screenshot
Is there any way to solve this issue?

A: sometimes when you are creating foreignKey, Django will make a separate table in DB to store the foreignkey values especially when you use the  shell to do queries


text:
Q: How to use the same clicked.connect function for multiple buttons? I am working on a GUI in pyqt5, that using a database (sqlite3). First, I'm uploading the entire data into a QTableWidget. Then, depending on the user filter parameters (2 comboboxes and 2 free text lineEdits which are signaled by 1 button), the filtering function is called and the data is filtered. The user may do another filter afterwards, and the table will be filtered again according to the new request.
The filter function is called upon one of three conditions:

*

*The first combobox text changed ("comboType")

*The second combobox text changed ("comboMaterial")

*The button "Filter Ac/AL" clicked ("pbFilter ALAc")

The question: the filtering is always initializes when the "comboType" text is changed only (since it's the first signal). When the user wants to filter according to the second or third conditions, the function can not be called and the filtering can not be conducted. The script is stuck until the first condition will occur (call the comboType.currentTextChanged.connect).
Is there any way to "jump" to the second or third condition when clicked?
### Apply first filter when ComboBox changed###

            self.uiCoresDBWin.comboType.currentTextChanged.connect(lambda: updateCoresTable())
            self.uiCoresDBWin.comboMaterial.currentTextChanged.connect(lambda: updateCoresTable())
            self.uiCoresDBWin.pbFilterALAc.clicked.connect(lambda: updateCoresTable())
`your text`
        def updateCoresTable():
            db = sqlite3.connect("ferrite_cores_db.db")
            cursor = db.cursor()
            typeIndex = self.uiCoresDBWin.comboType.currentIndex()+1
            typeData = self.uiCoresDBWin.comboType.currentText()
            materialIndex = self.uiCoresDBWin.comboMaterial.currentIndex()
            materialData = self.uiCoresDBWin.comboMaterial.currentText()
            typedAc = self.uiCoresDBWin.leAe.text()
            typedAL = self.uiCoresDBWin.leAL.text()
            if typeIndex == 0 and materialIndex == 0 and typedAc == '' and typedAL == '':
                result = cursor.execute("SELECT * from ferrite_cores")
            elif typeIndex == 0 and materialIndex == 0 and typedAc == '' and typedAL != '':
                result = cursor.execute("SELECT * from ferrite_cores WHERE AL >=?", (typedAL,))
            elif typeIndex == 0 and materialIndex == 0 and typedAc != '' and typedAL == '':
                result = cursor.execute("SELECT * from ferrite_cores WHERE Aef >=?", (typedAc,))
            elif typeIndex == 0 and materialIndex != 0 and typedAc != '' and typedAL != '':
                result = cursor.execute("SELECT * from ferrite_cores WHERE Aef >=? and AL >=?", (typedAc, typedAL))
            elif typeIndex == 0 and materialIndex != 0 and typedAc == '' and typedAL == '':
                result = cursor.execute("SELECT * from ferrite_cores WHERE Material ==?", (materialData,))
            elif typeIndex == 0 and materialIndex != 0 and typedAc == '' and typedAL != '':
                result = cursor.execute("SELECT * from ferrite_cores WHERE Material ==? and AL >=?", (materialData, typedAL))
            elif typeIndex == 0 and materialIndex != 0 and typedAc != '' and typedAL == '':
                result = cursor.execute("SELECT * from ferrite_cores WHERE Material ==? and Aef >=?", (materialData, typedAc))
            elif typeIndex == 0 and materialIndex != 0 and typedAc != '' and typedAL != '':
                result = cursor.execute("SELECT * from ferrite_cores WHERE Material ==? and Aef >=? and AL >=?", (materialData, typedAc, typedAL))
            elif typeIndex != 0 and materialIndex == 0 and typedAc == '' and typedAL == '':
                result = cursor.execute("SELECT * from ferrite_cores WHERE Type == ?", (typeData,))
            elif typeIndex != 0 and materialIndex == 0 and typedAc == '' and typedAL != '':
                result = cursor.execute("SELECT * from ferrite_cores WHERE Type ==? and AL >=?", (typeData, typedAL))
            elif typeIndex != 0 and materialIndex == 0 and typedAc != '' and typedAL == '':
                result = cursor.execute("SELECT * from ferrite_cores WHERE Type ==? and Aef >=?", (typeData, typedAc))
            elif typeIndex != 0 and materialIndex == 0 and typedAc != '' and typedAL != '':
                result = cursor.execute("SELECT * from ferrite_cores WHERE Type ==? and AL >=? and Aef >=?", (typeData, typedAL, typedAc))
            elif typeIndex != 0 and materialIndex != 0 and typedAc == '' and typedAL == '':
                result = cursor.execute("SELECT * from ferrite_cores WHERE Type ==? and Material ==?", (typeData, materialData))
            elif typeIndex != 0 and materialIndex != 0 and typedAc == '' and typedAL != '':
                result = cursor.execute("SELECT * from ferrite_cores WHERE Type ==? and Material ==? and AL >=?", (typeData, materialData, typedAL))
            elif typeIndex != 0 and materialIndex != 0 and typedAc != '' and typedAL == '':
                result = cursor.execute("SELECT * from ferrite_cores WHERE Type ==? and Material ==? and Aef >=?", (typeData, materialData, typedAc))
            elif typeIndex != 0 and materialIndex != 0 and typedAc != '' and typedAL != '':
                result = cursor.execute("SELECT * from ferrite_cores WHERE Type ==? and Material ==? and Aef >=? and AL >=?", (typeData, materialData, typedAc, typedAL))
            self.uiCoresDBWin.CoresTab.setRowCount(0)
            for row_number, row_data in enumerate(result):
                self.uiCoresDBWin.CoresTab.insertRow(row_number)
                for column_number, data in enumerate(row_data):
                    self.uiCoresDBWin.CoresTab.setItem(row_number, column_number, QtWidgets.Q


text:
Q: Is it possible to reload the CLR? I'm fiddling with a project where the CLR is hosted within a C application. Is there a supported way to unlink the CLR and relaunch it?

A: Instead of trying to reload the CLR, you could load and host all of your information in an AppDomain you create.
You could then manage the life of the AppDomain, including unloading the entire AppDomain and loading a new one.
This will provide most of the benefits that reloading the CLR would provide, without actually trying to unload the CLR.

A: I don't have the book before my right now, but I believe (accroding to Customization the Common Language Runtime) it is not possible to do that. You can unload, i.e. "disable" it, but then you cannot reload it in the same process instance.


text:
Q: How do I set the background color of a readonly textbox in Winforms? I have several textboxes in a Winforms window.
These textboxes need to be set to readonly in the design.
(I don't want to use labels, because some of these are multiline).
I would like to keep the original background color and not display the "disabled" grey color for the background.
How do I do this?
Thanks

A: Set the Background property of the control.