text:
Q: Why won't these nested unscoped blocks work to remove default_scope in Rails 4 when they work in Rails 3? My question
It seems like Rails 4 is ignoring nested unscoped blocks (whereas they were ok in Rails 3). I've been Googling like crazy and can't find anything indicating a change here. Any ideas how I can get this working in Rails 4?
What I'm doing
I'm using default_scope for multi-tenancy as shown in #388 Multitenancy with Scopes. Some admins will be admin of multiple tenants, and I want to show them aggregated data in a report. I'm doing this by using unscoped blocks. I'm also preloading associated objects because 1) It's more efficient and 2) I need to get all the associated objects in one place so I don't have to keep using unscoped blocks in my views. To preload the associated objects, I'm using nested unscoped blocks.
I had this working in my app on Rails 3.2.17, but now that I've upgraded to Rails 4.0.1.rc1, it no longer works.
A simple example to illustrate the difference
Below, I'll show what I'm getting in the Console. This example is much simpler than what I actually want to do, but I think it's the easiest way to show what's going on.
Loading development environment (Rails 3.2.17)
1.9.3-p374 :001 > s = nil
   => nil
1.9.3-p374 :002 > Submission.unscoped { Checklist.unscoped { s = Submission.preload(:checklist).find(3269) }}
  Submission Load (27.8ms)  SELECT "submissions".* FROM "submissions" WHERE "submissions"."id" = $1 LIMIT 1  [["id", 3269]]
  Checklist Load (0.6ms)  SELECT "checklists".* FROM "checklists" WHERE "checklists"."id" IN (17)
 => #<Submission id: 3269, user_id: nil, workday_id: 17, checklist_id: 17, note: nil, submitted: false, submitted_at: nil, created_at: "2014-03-12 01:06:03", updated_at: "2014-03-12 01:06:03", for_date: "2014-03-11", tenant_id: 2, position: 1, department_id: nil, status: "blank">
1.9.3-p374 :003 > s
 => #<Submission id: 3269, user_id: nil, workday_id: 17, checklist_id: 17, note: nil, submitted: false, submitted_at: nil, created_at: "2014-03-12 01:06:03", updated_at: "2014-03-12 01:06:03", for_date: "2014-03-11", tenant_id: 2, position: 1, department_id: nil, status: "blank">
1.9.3-p374 :004 > s.checklist
 => #<Checklist id: 17, name: "Open", description: "Chores Required To Open Store Front", creator_id: 2, created_at: "2013-09-23 21:55:23", updated_at: "2013-09-23 21:55:23", archived: false, archived_at: nil, ancestry: nil, tenant_id: 2>

So, I'm loading a submission and preloading its associated checklist. Then I can confirm that both the submission and its associated checklist are available.
If I switch to my Rails 4 environment (both working on the same database), here is what I see:
 Loading development environment (Rails 4.1.0.rc1)
 1.9.3-p374 :001 > s = nil
  => nil
 1.9.3-p374 :002 > Submission.unscoped { Checklist.unscoped { s = Submission.preload(:checklist).find(3269) }}
   Submission Load (0.4ms)  SELECT  "submissions".* FROM "submissions"  WHERE "submissions"."id" = $1 LIMIT 1  [["id", 3269]]
   Checklist Load (0.6ms)  SELECT "checklists".* FROM "checklists"  WHERE "checklists"."tenant_id" IS NULL AND "checklists"."id" IN (17)
  => #<Submission id: 3269, user_id: nil, workday_id: 17, checklist_id: 17, note: nil, submitted: false, submitted_at: nil, created_at: "2014-03-12 01:06:03", updated_at: "2014-03-12 01:06:03", for_date: "2014-03-11", tenant_id: 2, position: 1, department_id: nil, status: "blank">
 1.9.3-p374 :003 > s
  => #<Submission id: 3269, user_id: nil, workday_id: 17, checklist_id: 17, note: nil, submitted: false, submitted_at: nil, created_at: "2014-03-12 01:06:03", updated_at: "2014-03-12 01:06:03", for_date: "2014-03-11", tenant_id: 2, position: 1, department_id: nil, status: "blank">
 1.9.3-p374 :004 > s.checklist
  => nil

I'm running exactly the same code, but only the Submission is available - its associated checklist is nil.
FWIW, I can duplicate this in Rails 3.2.17 if I run this in the Console. NOTE: The difference here is I'm only using a Submission.unscoped {} block and not nesting the Checklist.unscoped {} block.
  Loading development environment (Rails 3.2.17)
  1.9.3-p374 :001 > s = nil
   => nil
  1.9.3-p374 :002 > Submission.unscoped { s = Submission.preload(:checklist).find(3269) }
    Submission Load (3.6ms)  SELECT "submissions".* FROM "submissions" WHERE "submissions"."id" = $1 LIMIT 1  [["id", 3269]]
    Checklist Load (0.4ms)  SELECT "checklists".* FROM "checklists" WHERE "checklists"."tenant_id" IS NULL AND "checklists"."id" IN (17)
   => #<Submission id: 3269, user_id: nil, workday_id: 17, checklist_id: 17, note: nil, submitted: false, submitted_at: nil, created_at: "2014-03-12 01:06:03", updated_at: "2014-03-12 01:06:03", for_date: "2014-03-11", tenant_id: 2, position: 1, department_id: nil, status: "blank">
  1.9.3-p374 :003 > s
   => #<Submission id: 3269, user_id: nil, workday_id: 17, checklist_id: 17, note: nil, submitted: false, submitted_at: nil, created_at: "2014-03-12 01:06:03", updated_at: "2014-03-12 01:06:03", for_date: "2014-03-11", tenant_id: 2, position: 1, department_id: nil, status: "blank">
  1.9.3-p374 :004 > s.checklist
   => nil

UPDATE
I went digging into the Rails source and I can see that the "unscoped" method is the same in 3.2-stable as current master, BUT that method calls "relation.scoping" and that method is substantially different between the two branches. I'm not sure if there's been a bug introduced, or if the expected behavior has changed.
For reference:
current master
def unscoped
  block_given? ? relation.scoping { yield } : relation
end

relation.scoping
def scoping
  previous, klass.current_scope = klass.current_scope, self
  yield
ensure
  klass.current_scope = previous
end

current_scope
def current_scope #:nodoc:
  ScopeRegistry.value_for(:current_scope, base_class.to_s)
end

3.2-stable
def unscoped #:nodoc:
  block_given? ? relation.scoping { yield } : relation
end

relation.scoping
def scoping
  @klass.with_scope(self, :overwrite) { yield }
end

Link to with_scope method...
def with_scope
  # Pretty long and involved method
  # See Line 60 in the linked doc
end

A: It looks like I've stumbled into a Rails 4 bug. As far as I can tell, using unscoped and eager loading together is currently not possible in Rails 4 as it seems that 'unscoped' essentially doesn't nest or chain.
Here's the issue on Github:
Using Includes and Unscoped #11036
What I ended up doing (for now) is to create unscoped associations (now available in Rails 4) where I needed them. Here's an example (from the gist I added to the Github issue):
class Submission < ActiveRecord::Base
  default_scope { where(tenant_id: Tenant.current_id) }

  belongs_to :checklist
  ###### This unscoped association is my workaround in Rails 4
  ###### You'll want comment out if testing in Rails 3
  belongs_to :unscoped_checklist, -> { unscope(where: :tenant_id) }, foreign_key: :checklist_id, class_name: "Checklist"
  belongs_to :tenant
end

So, I can just call submission.unscoped_checklist to get around the default_scope. Note, however, that this will not work in conjunction with eager loading. For example, this will not work:
Submission.unscoped.preload(:unscoped_checklist).where(id: 1)

The Submission will be returned, but subsequently calling submission.unscoped_checklist will return nil.
So I'm currently not able to eager load unscoped associations, but I have figured out how to get to the unscoped associations when I need them.

A: I ran into the same issue on a Spree-based Rails project, and ran through a bunch of failed approaches before implementing this crutch:
https://gist.github.com/coderifous/33e24f7e63800e169b03a16eb7eebb5b
I preferred this to other approaches because it doesn't involved monkey-patching, or any other clever tricks.  It simply clears (and later restores) the default_scopes array.
In my project, dropped that file in lib/default_scope_crutch.rb, and then wrapped my code with something like this:
disable_default_scopes(Product, User) {
  @orders = Order.preload(:product, :user).page(1).per(10)
  @orders.load
}

I would much prefer an ActiveRecord-provided way of doing this, but I'm not aware of one.  Hopefully this can be useful for others that run into this issue.


text:
Q: Is it possible to use Google Sign-In from an SDK inside of an App/Game? I am building an SDK that developers will have inside of their games/apps. I am trying to find out how to get Google Sign-in to work. It is trying to use the bundle id of the game itself instead of the bundle id of my sdk.
Thanks in advance

A: For anyone else inquiring. We got this to work by first adding in the url schemes via google into our sdk and then adding the url scheme of sdk bundle id to the game/app, which we did via a compile script

redpajama_set_name: RedPajamaStackExchange


text:
Q: zsh: create file and open in editor Does anyone know of any neat shortcuts to create a file and open it in an editor (in my case Sublime) at the same time?
Something like touch some/nice/file.txt | st ... or touch some/nice/file.txt && ...something
(st being my sublime shortcut, which can take an argument)
touch some/nice/file.txt && st some/nice/file.txt works of course, but involves repeating the file name, and it would be nice to do it without!
Thanks in advance

A: You can put an alias in your .zshrc to shorten it to whatever you want. Just add a line like
alias to='to(){ touch $1; st $1 }; to '

to your zshrc.
Now if you type 'to some/nice/file.txt' in your shell it should make the file and open it. You will need to reload the terminal once or use 'source .zshrc' before it can work.


text:
Q: Java compare object of efficiency In Java inside compare Hashcode  of  String Object and direct compare  String Object both Who is more efficient  and Why is that
  public static void main(String[] args) {
     String a = "Hello";
     String b="Hello";
     int i = a.hashCode();
     System.out.println(i);
     int v = b.hashCode();
     System.out.println(v);

     if (i==v){
        System.out.println("ture");
      }else {
        System.out.println("false");
    }
    }

A: hashCodes are a shortcut, not a real test of equality. Two objects that are equal should have the same hash code, but the opposite is not necessarily true. E.g., the strings "BBAa" and "AaBB" have the same hash code (at least with OpenJDK 8, they both are 2031744), but are definitely not equal.

A: hashcode on String is buffererized the first computation can be long but it becomme shorter at the second call but equality and hashcode did'nt mean the same thing at all !
the only relationships between equality and hashcode equalityare these one :
different hashcode => unequality
equality => same hashcode
those ones are COMPLETELY FALSE :
same hashCode => equality
unequality => different hashcode


text:
Q: Google Sheets: Calculate the number of coloured cells IF the check box is marked I am trying to calculate the number of coloured cells in a column where the check box is also marked.
For example, in column F, there are 2 green cells in rows with marked check boxes.  I have failed to work out a formula that would help me do this.  I am using the function by colour add-on to count number of coloured cells.
Any help would be greatly appreciated.

Sheet

A: Explanation:

*

*I would use a custom function to do that and then use it as a formula in the sheet.
Please read more about custom functions and their limitations.

*They are not refreshed as regular formulas but only when an argument changes. Please look online for workarounds on this issue if it is a bottleneck in your project.
Solution:
Click on Tools => Script editor on the top menu of the spreadsheet file, copy & paste the below code into a blank script and click on save.
function countColors(checkboxesColumn,colorColumn,hexCode) {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getActiveSheet();
  const values = sh.getRange(checkboxesColumn).getValues().flat();
  const colors = sh.getRange(colorColumn).getBackgrounds().flat();
  return values.filter((v,i)=>v==true && colors[i]==hexCode).length;
}

then you can use that function in your sheet as =countColors("C3:C","F3:F","#b7e1cd"):


text:
Q: Как на андроид организовать динамическую загрузку ресурсов? Пишу небольшое приложение и встала задача по организации меню в котором каждая кнопка содержит картинку в виде логотипа или фото(неважно), текст-название и информацию по ней. Я разобрался с текстовой частью. Организовал небольшое АПИ посредством JSON и подгружаю его в приложение, а теперь стоит вопрос как быть с картинками? Т.е. как их загрузить на устройство, куда так чтобы я мог их использовать при построении меню из лист вью, как я понимаю стандартные ресурсы я заменять не могу. Буду рад любой помощи! Простите за такой сумбурный вопрос!
A: Посмотрите на библиотеку Universal Image Loader. Возможно это то, что вам нужно.


text:
Q: herenow api has been rolled out. Is there any way to get the checkedin userdetail? We have integrated hereNow api in our appliction to show the checked in customers for the particular venue. Now because of the policy change in the hereNow api we are not getting any results. Is there any way to get the checkedin user details for the venue without being as a store manager?
Thanks,
Shiva

A: No. The identities of users currently checked in to a venue are only available to apps making requests on the behalf of friends, other people checked in to the venue, or to a manager of the venue.


text:
Q: Remove numbers at the beginning and end of a string I've got the following vector:
words <- c("5lang","kasverschil2","b2b")

I want to remove "5" in "5lang" and "2" in "kasverschil2". But I do NOT want to remove "2" in "b2b".

A: You can use gsub which uses regular expressions:
gsub("^[0-9]|[0-9]$", "", words)
# [1] "lang"        "kasverschil" "b2b"

Explanation:
The pattern ^[0-9] matches any number at the beginning of a string, while the pattern [0-9]$ matches any number at the end of the string. by separating these two patterns by | you want to match either the first or the second pattern. Then, you replace the matched pattern with an empty string.

A:  gsub("^\\d+|\\d+$", "", words)
 #[1] "lang"        "kasverschil" "b2b"

Another option would be to use stringi
 library(stringi)
 stri_replace_all_regex(words, "^\\d+|\\d+$", "")
  #[1] "lang"        "kasverschil" "b2b"

Using a variant of the data set provided by the OP here are benchmarks for 3 three main solutions (note that these strings are very short and contrived; results may differ on a larger, real data set):
words <- rep(c("5lang","kasverschil2","b2b"), 100000)

library(stringi)
library(microbenchmark)

GSUB <- function() gsub("^\\d+|\\d+$", "", words)
STRINGI <- function() stri_replace_all_regex(words, "^\\d+|\\d+$", "")
GREGEXPR <- function() {
    gregexpr(pattern='(^[0-9]+|[0-9]+$)', text = words) -> mm
    sapply(regmatches(words, mm, invert=TRUE), paste, collapse="")
}

microbenchmark(
    GSUB(),
    STRINGI(),
    GREGEXPR(),
    times=100L
)

## Unit: milliseconds
##        expr       min        lq    median        uq       max neval
##      GSUB()  301.0988  349.9952  396.3647  431.6493  632.7568   100
##   STRINGI()  465.9099  513.1570  569.1972  629.4176  738.4414   100
##  GREGEXPR() 5073.1960 5706.8160 6194.1070 6742.1552 7647.8904   100

A: Get instances where numbers appear at the beginning or end of a word and match everything else. You need to collapse results because of possible multiple matches:
gregexpr(pattern='(^[0-9]+|[0-9]+$)', text = words) -> mm
sapply(regmatches(words, mm, invert=TRUE), paste, collapse="")


text:
Q: Least squares fit, unknown intercerpt I have three data points through which I have to fit a straight line of the form Y=m*X+C. I want the line to have pre-determined slope 'm' but the constant'C' can change to get the least error while fitting using matlab. Can someone help me out?

A: Just do the math:
C= mean(Y)-m*mean(X)
assuming Y is the vector containing the y coordinates, and X the x coordinates.
Reference: http://hotmath.com/hotmath_help/topics/line-of-best-fit.html

A: If you opt to use the Curve Fitting Toolbox the solution is as follows.
To start generate some data
m = 3;
x = (1:10).';
y = m*x + 2 + randn(size(x));

then select the model to fit and set the bounds for its coefficients
ft = fittype('poly1');
opts = fitoptions('Method', 'LinearLeastSquares');
opts.Lower = [m -Inf];
opts.Upper = [m  Inf];

finally call the fitting routine
[fitresult, gof] = fit(x, y, ft, opts);

The intercept is stored in fitresult.p2.


text:
Q: Error:(31, 5) uses-sdk:minSdkVersion 9 cannot be smaller than version 14 declared in library I m trying to use Gabriele Mariotti card library , From github using https://github.com/gabrielemariotti/cardslib.
Currently I'm using Android Studio, so I have added the dependencies to my build gradle file as mentioned in the documentation.
This is what my gradle file looks like
apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.0.1"

    defaultConfig {
        applicationId "com.vt"
        minSdkVersion 9
        targetSdkVersion 21
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {
    compile project(':facebookSDK')
    compile project(':addslidepanel30')
    compile 'com.android.support:support-v4:21.0.1'
    compile 'com.google.android.gms:play-services:+'
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile files('libs/android-support-v7-palette.jar')
    compile files('libs/universal-image-loader-1.9.3-with-sources.jar')
    compile files('libs/volley.jar')

    //Core
    compile 'com.github.gabrielemariotti.cards:cardslib-core:2.0.1'

    //Optional for built-in cards
    compile 'com.github.gabrielemariotti.cards:cardslib-cards:2.0.1'

    //Optional for RecyclerView
    compile 'com.github.gabrielemariotti.cards:cardslib-recyclerview:2.0.1'

    //Optional for staggered grid view
    compile 'com.github.gabrielemariotti.cards:cardslib-extra-staggeredgrid:2.0.1'

    //Optional for drag and drop
    compile 'com.github.gabrielemariotti.cards:cardslib-extra-dragdrop:2.0.1'

    //Optional for twoway  (coming soon)
    //compile 'com.github.gabrielemariotti.cards:cardslib-extra-twoway:2.0.1'
}

But I keep getting this message error
Error:(31, 5) uses-sdk:minSdkVersion 9 cannot be smaller than version 14 declared in library C:\Users\SAM-PC\AndroidStudioProjects\vt1.3.0.0 newDB\vt1300newDB\build\intermediates\exploded-aar\com.github.gabrielemariotti.cards\library\1.9.1\AndroidManifest.xml
Error:(31, 5) Execution failed for task ':vt1300newDB:processDebugManifest'.
> Manifest merger failed : uses-sdk:minSdkVersion 9 cannot be smaller than version 14 declared in library C:\Users\SAM-PC\AndroidStudioProjects\vt1.3.0.0 newDB\vt1300newDB\build\intermediates\exploded-aar\com.github.gabrielemariotti.cards\library\1.9.1\AndroidManifest.xml
    Suggestion: use tools:overrideLibrary="it.gmariotti.cardslib.library" to force usage

I have tried to change the version of the card lib to the stable, But I'm keep getting the same error
dependencies {
    //Core card library
    compile 'com.github.gabrielemariotti.cards:library:1.9.1'

    //Extra card library, it is required only if you want to use integrations with other libraries
    compile 'com.github.gabrielemariotti.cards:library-extra:1.9.1'
}

PS : I'm new to Android Studio , My project works just fine in Eclipse , but I m trying to Migrate to Android Studio since it s recommended by google .so I would really appreciate your help.

A: Add the following to your manifest:
<uses-sdk android:targetSdkVersion="22" android:minSdkVersion="14"
          tools:overrideLibrary="it.gmariotti.cardslib.library"/>

More info can be found here.

A: You should change your AndroidManifest.xml like this:
<uses-sdk android:targetSdkVersion="22" android:minSdkVersion="14"
      tools:overrideLibrary="it.gmariotti.cardslib.library"/>

You need to change minSdkVersion of your project to 14 or change that of it.gmariotti.cardslib.library  to 9. Because the minSdkVersion of the imported  library is 14.


text:
Q: yii relations trough one table is it possible in Yii 1.1.14 to connect these tables using one "object_rel" table?
object_rel:

*

*id

*owner_id (e.g. location record id)

*owner_type (e.g. 2 = location)

*slave_id (e.g. program record id)

*slave_type (e.g. 1 = program)

location(type = 2):

*

*id

*...

program(type = 1):

*

*id

*...

category(type = 3):

*

*id

*...

or i have to write some custom fancy stuff?
I have tried MANY_TO_MANY with no luck...

A: Unfortunately, I don't think this is possible with relations, as they require you to specify the model-class. However, you could define something like this in your model for object_rel:
private static $modelTypes = array(
    1 => Program::model(),
    2 => Location::model(),
    3 => Category::model(),
);

public static function getOwner($object)
{
    $data = self::$db->createCommand()
               ->select('owner_id, owner_type')
               ->from('object_rel')
               ->where('owner_id = :object_id', array(':object_id' => $object->id))
    ->queryRow(true); // assuming every object only has one owner

    // no results found
    if ($data === false) {
        return false;
    }

    $model = self::$modelTypes[data['owner_type']];
    return $model->findByPk(data['owner_id']);
}


text:
Q: Converting to a portable file path public static String getPortableFilePath(String target)
{
Pattern ptr=Pattern.compile("[\\|/]+");
Matcher mtr=ptr.matcher(target);
return mtr.replaceAll(File.separator);
}

public static void main(String[] args)
{
   System.out.println(getPortableFilePath("C:///Program Files////Java\\jdk1.6.0_23/bin"));
}

In the above code I am trying to replace all the Forward and Backward slashes with the current systems File Separator. Code compiles fine when put into a class, but when executed it gives an array index out of bounds exception. Any guesses why?
The Exception:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1

at java.lang.String.charAt(Unknown Source)
at java.util.regex.Matcher.appendReplacement(Unknown Source)
at java.util.regex.Matcher.replaceAll(Unknown Source)
at Files.getPortableFilePath
at Files.main

A: You method is (a) misnamed and (b) unnecessary. Misnamed because it doesn't return a portable file path, it returns a path for the current system; unnecessary because if you just use / everywhere Java will operate correctly on all platforms. There is never a need to use backslashes in Java filenames.

A: You need to get two backslashes through to the regex engine.  Otherwise it will think you are escaping the next character.  So use
"[\\\\/]+"

for the pattern string.  That way it resolves to the pattern
[\\/]+

This is the problem with the string and the regex notation both using backslashes, and there being no way to skip the string interpolation stage.
And don't use a vertical pipe in a square-bracket charclass: it is a literal there.

A: Thanks for the answers guys. Finally found the issue.
I replaced the
Pattern ptr=Pattern.compile("[\\\\/]+");

with
Pattern ptr=Pattern.compile("[\\\\\\\\|/]+");

as noted by tchrist, this was needed but still it didn't fix the error.
The error was fixed by replacing the
return mtr.replaceAll(File.separator);

line with
return mtr.replaceAll(File.separator+""+File.separator);

Since I am working in windows environment, the File.separator returned "\" which itself worked as an escape character and the error was displayed, and that is why the original code worked fine on Jim Blackler's Mac because the File.separator for him was not "\".
But still I could not make sense with the StringIndexoutOfBounds exception, what does this exception had to do here.


text:
Q: Dependency Injection by @Produce annotation in this example this is a simple number-guess example to demonstrate dependency injection in Java EE 7. What I don't quite understand is the two injected fields in Game.java, "maxNumber" and "randomNumber". I understand that they can be injected because there are two @produce methods in Generator.java, @Produce int next() and @Produce int getMaxNumber().
However, the method name "next()" doesn't match "randumNumber" injected in Game.java. How does this work?
Also, I tried changing "getMaxNumber()" to something else "getMMMaxNumber()" in Generator.java. The program still works fine. So, I really don't understand how these two fields are injected into Game.java from Generator.java.
Please help understand this. Thanks really in advance.
Game.java
package org.jboss.as.quickstarts.numberguess;
@SuppressWarnings("serial")
@Named
@SessionScoped
public class Game implements Serializable {
/**
 * The number that the user needs to guess
 */
private int number;

/**
 * The users latest guess
 */
private int guess;

/**
 * The smallest number guessed so far (so we can track the valid guess range).
 */
private int smallest;

/**
 * The largest number guessed so far
 */
private int biggest;

/**
 * The number of guesses remaining
 */
private int remainingGuesses;

/**
 * The maximum number we should ask them to guess
 */
@Inject
@MaxNumber
private int maxNumber;

/**
 * The random number to guess
 */
@Inject
@Random
Instance<Integer> randomNumber;

public Game() {
}

public int getNumber() {
    return number;
}

public int getGuess() {
    return guess;
}

public void setGuess(int guess) {
    this.guess = guess;
}

public int getSmallest() {
    return smallest;
}

public int getBiggest() {
    return biggest;
}

public int getRemainingGuesses() {
    return remainingGuesses;
}

@PostConstruct
public void reset() {
    this.smallest = 0;
    this.guess = 0;
    this.remainingGuesses = 10;
    this.biggest = maxNumber;
    this.number = randomNumber.get();
}
}

Generator.java
@SuppressWarnings("serial")
@ApplicationScoped
public class Generator implements Serializable {

private java.util.Random random = new java.util.Random(System.currentTimeMillis());

private int maxNumber = 100;

java.util.Random getRandom() {
    return random;
}

@Produces
@Random
int next() {
    // a number between 1 and 100
    return getRandom().nextInt(maxNumber - 1) + 1;
}

@Produces
@MaxNumber
int getMaxNumber() {
    return maxNumber;
}
}

MaxNumber.java
@Target({ TYPE, METHOD, PARAMETER, FIELD })
@Retention(RUNTIME)
@Documented
@Qualifier
public @interface MaxNumber {

}

Random.java
@Target({ TYPE, METHOD, PARAMETER, FIELD })
@Retention(RUNTIME)
@Documented
@Qualifier
public @interface Random {

}

A: Injection is not done by method name, but rather the two values are distinguished by their qualifiers @Random and @MaxNumber.  The respective method names of the @Produce-annotated methods are not relevant, they only need to return a matching type.


text:
Q: iPhone: Weather report APIs library I am planning to add weather report for selected country->state->city, for daily, weekly, monthly averages. I have googled it and also went through couple of discussion on stackoverflow threads and I got confused! Could anyone please tell me if there is already Weather report APIs library available? What could be the best way to implement my requirements? I am just expecting overview so that I don't chose wrong path.
Thanks.

A: See WorldWeatherOnline.

A: I compiled a set of information about different weather APIs looking for a similar solution. My general consensus was the WorldWeatherOnline seemed to be the best bang for the buck (free) and seemed pretty feature rich.
http://michaelwelburn.com/2011/11/02/comparing-weather-apis/
UPDATE (12/18/2013): This response was from 2011, since that time some different providers have made updates. I tried to keep the link semi-up to date, but you'll want to take the list provided and do your own research.


text:
Q: How to place components above React Native Modal? I'm developing an app using React Native. Right now, I have a FAB button which I'm using the react-native-circular-action-menu and I'm using the React Native Modal to open a modal. The problem is the Modal occupies the entire screen and I placed a View inside of the Modal component to adjust the width and size of the modal. I managed the size the modal using the view and setting transparency true for the modal.
However, I couldn't click on the FAB button as the modal's component is actually on top of it. I want to place the FAB button on top of the modal and on top of all components in the app. Is there any way to do it?
Thank you.


text:
Q: If $f_{n}(x) =\frac{\arctan(nx)}{\sqrt {n+x}}$ then $\{f_n(x)\}_{n=1}^\infty$ converges uniformly over $[0;+\infty)$ How to prove that if $$f_{n}(x) =\frac{\arctan(nx)}{\sqrt {n+x}}\space \text{for}\space n\in \mathbb{N},$$ then the functional sequence $\{f_n(x)\}_{n=1}^\infty$ converges uniformly over the set $[0;+\infty)$?

A: The key observation is that the function $x \mapsto \arctan x$ is bounded on $[0, + \infty)$ by $\pi/2$, therefore
\begin{align*}
\sup_{x \in [0, +\infty)}|f_n(x) - 0| = \sup_{x \in [0, +\infty)}\frac{\arctan(nx)}{\sqrt{n + x}} \leq \frac{\pi}{2\sqrt{n}} \to 0
\end{align*}
as $n \to \infty$, hence $f_n(x)$ converges to $0$ uniformly on $[0, +\infty)$.

A: HINT:
$$|\arctan(x)|\le \pi/2$$
and
$$\frac{1}{\sqrt{n+x}}\le\frac{1}{n}$$


text:
Q: How to detect which row [ tr ] is clicked? In javascript, how can we detect which row of the table is clicked? At present what i am doing is, i am binding the the method at run time like this.
onload = function() {
    if (!document.getElementsByTagName || !document.createTextNode) return;
    var rows = document.getElementById('my_table').getElementsByTagName('tbody')[0].getElementsByTagName('tr');
    for (i = 0; i < rows.length; i++) {
        rows[i].onclick = function() {
            alert(this.rowIndex + 1);
        }
    }
}

[ copied from [ http://webdesign.maratz.com/lab/row_index/ ] ]
But i don't like this approach. Is there any alternative? My problem is just to get the index of the row which is clicked.

*

*No jQuery please :D.

A: You can use event delegation for that. Basically you add one clickhandler to your table. This handler reads out the tagname of the clicked element and moves up the DOM tree until the containing row is found. If a row is found, it acts on it and returns. Something like (not tested yet, but may give you ideas):
    var table = document.getElementById('my_table');
    table.onclick = function(e) {
       e = e || event;
       var eventEl = e.srcElement || e.target,
           parent = eventEl.parentNode,
           isRow = function(el) {
                     return el.tagName.match(/tr/i));
                   };

       //move up the DOM until tr is reached
       while (parent = parent.parentNode) {
           if (isRow(parent)) {
             //row found, do something with it and return, e.g.
              alert(parent.rowIndex + 1);
              return true;
           }
       }
       return false;
   };

A: The this keyword can be used to get the parentNode of the cell, which is a <tr> element.  The <tr> element has a property for the row number, .rowIndex.
The Event:
onclick='fncEditCell(this)'

The Function:
window.fncEditCell = function(argThis) {
    alert('Row number of Row Clicked: ' + argThis.parentNode.rowIndex);
};

Full Working Example Here:
jsFiddle
Dynamically Set OnClick Event
Use .setAttribute to inject a click event:
cell2.setAttribute("onmouseup", 'editLst(this)');

Example of Dynamically Creating a Table:
for(var prprtyName in rtrnTheData) {
  var subArray = JSON.parse(rtrnTheData[prprtyName]);

  window.row = tblList.insertRow(-1);

  window.cell1 = row.insertCell(0);
  window.cell2 = row.insertCell(1);
  window.cell3 = row.insertCell(2);
  window.cell4 = row.insertCell(3);
  window.cell5 = row.insertCell(4);
  window.cell6 = row.insertCell(5);
  window.cell7 = row.insertCell(6);
  window.cell8 = row.insertCell(7);
  window.cell9 = row.insertCell(8);

  cell1.setAttribute("onmouseup", 'dletListing(this.title)');
  cell1.setAttribute("title", "'" + subArray.aa + "'");

  cell2.setAttribute("onmouseup", 'editLst(this)');
  cell2.setAttribute("title", "'" + subArray.aa + "'");

  cell1.innerHTML = "Dlet";
  cell2.innerHTML = "Edit";
  cell3.innerHTML = subArray.ab;
  cell4.innerHTML = "$" + subArray.ac;
  cell5.innerHTML = subArray.ad;
  cell6.innerHTML = subArray.ae;
  cell7.innerHTML = subArray.af;
  cell8.innerHTML = subArray.ag;
  cell9.innerHTML = subArray.meet;
};

A: This uses sectionRowIndex to get the index in the containing tBody.
function getRowIndex(e){
 e= window.event || e;
 var  sib, who= e.target || e.srcElement;
 while(who && who.nodeName!= 'TR') who= who.parentNode;
 if(who){
  alert(who.sectionRowIndex+1)
  if(e.stopPropagation) e.stopPropagation();
  else e.cancelBubble= true;
  // do something with who...
 }
}

onload= function(){
 document.getElementById('my_table').onclick= getRowIndex;
}

A: I tried Alan Wells written answer, but it was returning, undefined.
So, I modified a little, to get the row index as follows:
argThis.rowIndex

This will return the row index for the row clicked.

modify the <tr> tag:
<tr onclick="fncEditCell(this)" >
Then, add a script tag at the bottom of the HTML:
<script>
  window.fncEditCell = function(argThis) {
    alert('Row number of Row Clicked: ' + argThis.rowIndex);
};
</script>

As an example, you can see this image:


text:
Q: How to embed html codings in python tkinter Can anyone please help me how I can use html codings in python GUI?
Suppose I want to use html forms in my tkinter frame or geolocation map from html in my tkinter window..


text:
Q: Install program that has to be run as administrator Background: I am by no means a windows security / user permissions expert. I have an application (written in C#), that has to be able to write / delete files & folders in its root directory, write / delete files elsewhere on the disk, write/modify values in System Registry (Local Machine) and start & stop other applications and services. I figure that I need administrator privileges for at least some of those actions.
I tried running this and on computers with UAC turned off it works great without any additional settings. However on computers with UAC turned on (any level above 'never notify' in Windows 7) it will crash. I need it to work on all computers.
Up to now I would just manually check the "run this program as administrator" checkbox and everything would be fine. However now we have decided that we will allow customers to install this software on their own, and it needs to run "out of the box".
I have a deployment project in Visual Studio 2008 that installs everything and writes the necessary start up data in registry. What I need to do now is to set the "Run this program as Administrator" flag. I am guessing this isn't quite as simple as I'd like it to be.
So What is the proper way of doing this? This program is started on startup, and it would be irritating for our customers if UAC would pop up (and possibly dim the screen) every time they restart their computer.
Thank you for your help.
EDIT: Thank you for your replies. I realise that working around UAC would be frowned  upon, and I can see that Microsoft does not support "white lists" so it would ask for permission only once. That's fine I can respect that, however I do have some follow up questions:

*

*Can you provide me with a link that will show me how to properly elevate the program to correct elevated state? Is there any literature on what are the options, etc... Basicly I'd love a UAC 101 guide.

*Is there a way to elevate the security status when I need the extra privileges (and only then prompt with UAC). Basicly this applications runs in the background, doing mostly nothing for most of the time. Every now and again it will check some files (at this point I will require to be able to write to disk and read the registry (read only is fine at this point), however since it's a temporary folder it wouldn't matter where I'd put it. If there is a location where the application can write without any privileges that would be perfect.)
However at some point I will need to preform all the rest of the tasks (user needs to confirm this action anyway) so if UAC would prompt at this point that would be no problem. Is there a way to elevate it just at this point, and then return it to default permissions?

*Will such a solution work with older versions of Windows, including Vista and Xp (and perhaps older?) What would it take to make it work?

A: The proper way is to elevate when the program starts, with the UAC prompt (which you can set via the program's manifest) - attempting to be clever and bypass it is frowned upon.
Think about it - if you could install something which would elevate automatically without the UAC prompt ... what would be the point of UAC?
To add a UAC manifest to a program you simply add the manifest in a project and edit it. A sample manifest for UAC is here. If you want to elevate at the last possible moment then you need a spawn separate process - you cannot elevate an existing process. So separate that bit out and then start it using
Process.StartInfo.UseShellExecute = true;
Process.StartInfo.Verb = "runas";

A: You need to rethink how your application works. You're quite correct that it would be annoying to display an elevation prompt on login. So don't do it. On the other hand, you may well have tasks which you need to perform using administrative access.
So you have two choices:

*

*Change your tasks so that they no longer require administrative elevation (e.g., write your files elsewhere).

*Break your application into a Windows service component and a user interface component. The service component can run under an elevated account (hopefully the least-elevated account necessary to perform the tasks you need to do). The user interface component can talk to the service (via named pipes or similar) when necessary.

A: You can split your program into two components:

*

*a user application running without elevation

*a Windows service that is responsible for the tasks that require elevation

Since you're using .NET, communication between the components is probably easiest done using WCF.
And as a side note: Programmatically modifying files under C:\Program Files is not considered good practice and might lead to a number of other problems. Windows has dedicated places for storing configuration settings and other program data.


text:
Q: Facebook Meta Tag og:image PHP condition I used that PHP code for og:image meta tag but it doesn't work, it's right but it doesn't call the right source of the image.
<?php JFactory::getDocument(); $document->addCustomTag('<meta property="og:image" content="http://www.sell4masari.com/images/com_adsmanager/ads/<?php.$img->image?>" />');?>

So I will appreciate any help from anyone.

A: You're putting the <?php tags inside the quotes, so it is not being processed:
content="[...]/ads/<?php.$img->image?>" />');

You need to build the string through concatenation, like so:
<?php JFactory::getDocument(); $document->addCustomTag('<meta property="og:image" content="http://www.sell4masari.com/images/com_adsmanager/ads/' . $img->image . '" />');?>


text:
Q: What is the best way to return a vector from a function in c++ I have a function that returns an array like this:
vector<string> GetString()
{
   vector<string> s;
   s.push_back("one");
   s.push_back("two");
   s.push_back("three");
   return s;
}

and I'm calling it in this way:
   vector<string> mystrings=GetStrings();

I can implement it as follows too:
void GetString(vector<string> & s)
{
   s.push_back("one");
   s.push_back("two");
   s.push_back("three");
}

and call it in this way:
 vector<string> mystrings;
 GetStrings(mystrings);

Which one is better?
Does version one copy a vector to another? If yes then it is slow if the vector is big.

A: This is largely an issue of personal preference, and whatever coding conventions you may be required to work with.
Prior to C++11, the second approach would sometimes have been considered preferable. The performance is guaranteed to be good because there is no unnecessary copying. The first approach, on the other hand, has the potential (in theory) to invoke a fairly expensive copy constructor.
In practice though, an optimisation called copy elision often avoids the copy constructor, meaning the performance is just as good either way. It's not guaranteed though, as it can depend on factors such as compiler settings/capabilities.
C++11 introduced move semantics though. It offers an alternative way to eliminate the copying, and is built-in to the language specification (rather than being an optional compiler optimisation). From a readability point-of-view, that can make the first option preferable, as it's perhaps more obvious what your code is doing.

A:
Which one is better?

They do different things. Use the first if you want a vector containing just those strings; use the second if you want to be able to append those strings to an existing vector.
If you want the semantics of the first version, then that's "better" in the sense of being easier to use correctly, and harder to use incorrectly.

Is version one copies a vector to another?

In modern C++, definitely not: returning a local variable and initialising from a temporary are both done by moving, not copying. Even if you're stuck with a pre-C++11 compiler, both copies should be elided. If your compiler doesn't support move semantics or copy elision, then you really should throw it away.


text:
Q: Is it possible to make a file writable only through decryption? Now, it may sound silly, but here is the idea:
I want to make so that to write on a file the user (even if is the root user) will need a key. The first thing that may have popped onto your mind may be:
"Why not just encrypt the file?"
My idea is to do this on certain configuration files. They can't be encrypted, or the system would crash. Also, with this approach, I would still be able to read the files and see how they are set up.
I know this fundamentally sounds very against the linux system's logic: why would the root user prevent itself from having power over his own system? The answer is: I am the root user and I want to protect me from myself. But for real: chmod -w file is, of course, easily reversed.
This may be fundamentally impossible, but I figured there was no harm in asking.

A: You're looking for an integrity protection system, not for an encryption system.
In theory...

*

*One way to achieve this is using digital signatures – they're usually made using an asymmetric key pair (such as RSA or ECDSA). After performing writes you use the private key to sign the final file, and whenever reads are performed the OS uses the public key to verify the signature and match it against the contents.
(You might be familiar with using SSH pubkeys – well, they're exactly the same thing. SSH pubkeys work by signing the login challenge which the server can verify i.e. "read", but no one except you can "write".)
Linux appears to support this through the IMA/EVM subsystem.

*Another way to achieve this is using a plain hash that's just stored in a place that even root is not allowed to modify. For example, Linux has the dm-verity subsystem, which is often used on embedded devices – the entire "/" filesystem is read-only and its hash is stored in a separate flash area accessible only by the bootloader.
In practice...

*

*Root can bypass these mechanisms by simply using mount --bind to overlay a different file on top of your "verified" file. For example, even if you make /etc/sudoers completely unwritable, root can create a new file in /tmp and use mount --bind /tmp/sudoers /etc/sudoers to make the same file appear inside /etc. As this happens at the VFS layer, it is completely unaffected by any lower-layer security protections.

*So if you really want to constrain root, you'll need some of the above mechanisms and you'll need Secure Boot and you'll need SELinux or other similar "mandatory access control" system, just to create additional hoops to jump through.

*Or really just remove your own root privileges completely.

A: Linux has FUSE, an API to implement file systems in use space.
Think of some way to store a key or keys (in a different, or at the beginning of each file). Think of some way to have the user communicate a key to unlock the file for writing. For example by requiring that key as the first part of the write (maybe with fixed length). Or by providing an additional companion file you need to write the key to. Think of some way to automatically lock the file again, e.g. after a tinmeout.
The take the example implementation and modify it with these ideas. Done.


text:
Q: how to get last 10 records form sql table in asc order select top(10) from customer order by customer_id desc

A: This work fine in MS SQL but for MySQL we would have to go
SELECT * FROM customer ORDER BY customer_id DESC LIMIT 10

A: select *
from (select top 10 * from customer order by customer_id desc) a
order by  customer_id

A: It seems you're missing the column list that you'd like retrieved from the table.
Consider:
select top(10)
*
from customer order by customer_id desc

or
select top(10)
customer_id, customer_name
from customer order by customer_id desc

A: you can use:
    SELECT * FROM customer ORDER BY customer_id DESC LIMIT 10


text:
Q: Program for Ubuntu that opens .mbf format? I just cleaned up a computer and installed linux on it in place of vista. I made a backup of everything that was needed to be kept on a USB and transferred it to Linux. Now the only files that I have that aren't supported are some Microsoft Money files. The file format is .mbf. Is there an alternative program for Microsoft Money that is available for Ubuntu that can open and read these files just as effectively?
I'll most likely be installing windows 7 over Linux if the version of 7 I have is compatible, since this will be a general house computer with multiple users, so the issue will be resolved that way. However, I'd personally like to keep Linux on it in place of windows, so if there is a program for it I can do that instead.
Thanks for any help! It's always appreciated.

A: I've used GnuCash before, which I've found excellent. I've never used Microsoft Money though, so I can't compare the features directly. You can import from Microsoft Money, although you'll have to export in QIF format first.
If you hate GnuCash, and really want to go back to Microsoft Money, you can always install it via Wine or a Virtual Windows machine (e.g. through VirtualBox).


text:
Q: iOS 11 webview audioplayer in background Since update on iOS 11 my audioplayer in a webview stops when the app is in background. On iOS 10 the player keeps playing.
Anyone else having the same problem and a fix for this?


text:
Q: how to call this variable in my array editcase I have a session called $_SESSION['data']
And I have a text input called 'lengtezijde'
I already used foreach on the session:
foreach ($_SESSION['data'] as $key => $data);

And if I want to use my input from lengtezijde, I tried it like this:
echo $_SESSION['data'][$_GET['key'];

but then it is an array and I want the input value.
How do I go a layer deeper in the array to use the value?

A: Please try this inside the foreach loop:
echo $data['lengtezijde'];

or
echo $_SESSION['data'][$key]['lengtezijde'];

We have seen $key will have indexing value 0.
Note:  as looping on session data you will get $data value as when print $data:
Array ( [hoogte] => 1 [kleur] => 1 [lengtezijde] => 800 [toevoegen] => toevoegen )

So you can get directly the value of lengtezijde by using as :
$data['lengtezijde']; inside the foreach loop.

A: Try this ....
echo $_SESSION['data'][$key]['lengtezijde'];

A: It is not clear how you set the value of the array. If you set the array value in the for-loop like this:
foreach ($_SESSION['data'] as $key => $data);
    $data['lengtezijde'] = "some value";

Then to get the value you must do something like this:
$key = $_GET['key']; //or the key to the index you want
echo $_SESSION['data'][$key]['lengtezijde'];


text:
Q: Why doesn't "AutomaticRedirectAfterSignOut = true;" work for redirecting "post-logout" in the following context? The main application is a ASP.NET Core 2.2 Web Application using Razor Pages.

*

*User accesses the application URL & gets redirected to IdentityServer4 login screen

*User successfully login

*User Logsout and gets redirected to "You have been logged out screen" of IdentityServer4 after successfully skipping the logout confirmation prompt.

*This step fails: The user is NOT automatically redirected to the login page of IdentityServer4. He is instead redirected to a page where he is informed that he has logged off, here he is also asked if he wants to go to the login page, which is where i want him to be automatically redirected to without any prompts.

What I have tried so far:

*

*In IDP >> Quickstart >> Account >> AccountOptions >> public static bool AutomaticRedirectAfterSignOut = true; (this should be regarded as set to true the entire post)

*In IDP >> Startup >> ConfigureServices >> .AddOpenIdConnect >>
options.SignedOutCallbackPath = "/signout-callback-oidc"; Adding this line of code did not help.

*I tried running using Chrome, Firefox, Edge - the issue persisted

Code from IDP Startup.cs
public void ConfigureServices(IServiceCollection services)
        {
            // adds MVC framework services
            services.AddMvc();
            /*// adds services Razor Pages and ASP.NET MVC require
            .AddRazorPagesOptions(options => {options.Conventions.AddPageRoute("/index", "home"); });*/

            // dependency injection of services
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();                     // registers an IHttpContextAccessor so we can access the current HttpContext in services by injecting it
            services.AddScoped<IThisHttpClient, ThisHttpClient>();                                  // registers an "ThisHttpClient"
            services.AddScoped<IOrderService, OrderService>();
            services.AddScoped<IAccountService, AccountService>();
            services.AddLogging();

            // adding open id connect authentication
            services
                .AddAuthentication(options =>
                {
                    options.DefaultScheme = "Cookies";
                    options.DefaultChallengeScheme = "oidc";
                })
                .AddCookie("Cookies")                                       // configures the cookie handler and enables the application to use cookie based authentication for the default scheme

                // The below handler creates authorization requests, token and other requests, and handles the identity token validation
                // "oidc" ensure when part of application requires authentication, "OpenIdConnect" will be triggered by default
                .AddOpenIdConnect("oidc", options =>
                {
                    options.SignInScheme = "Cookies";                       // matches the default scheme for authentication, ensures that succesful authentication result will be stored in a our applications "cookie"
                    options.Authority = "https://localhost:44370/";         // the authority is set to be the identity provider (the authority responsible for the IDP part of the OIDC flow), the middleware will use this value to read the metadata on the discovery end point, so it knows where to find different endpoints ad other information
                    options.ClientId = "3TL";                               // must match client ID at IDP level
                    options.ResponseType = "code id_token";                 // one of response type of the Hybrid ground to be used
                    //options.CallbackPath = new PathString("...");         // allows the change of the redirect Uri from inside the IdentityServerConfig (hand made class)
                    //options.SignedOutCallbackPath = new PathString("...") //
                    options.Scope.Add("openid");                            // required scope which requires in sub value being included
                    options.Scope.Add("profile");                           // ensures profile related claims are included
                    options.Scope.Add("roles");                             // requesting a CUSTOM MADE scope (check IDP scopes/roles for details)
                    options.SaveTokens = true;                              // allows the middleware to save the tokens it receives from the identity provider so we can easelly use them afterwards
                    options.ClientSecret = "test_secret";                   // must match secret at IDP level
                    options.GetClaimsFromUserInfoEndpoint = true;           // enables GETing claims from user info endpoint regarding the current authenticate user
                    //options.ClaimActions.Remove("amr");                   // allows us to remove CLAIM FILTERS (AKA this ensures the AMR(Authentication Method Reference) claim is dispalyed and not filtered out)
                    options.ClaimActions.DeleteClaim("sid");                // removing unnecessary claims from the initial cookie (session ID at level of IDP)
                    options.ClaimActions.DeleteClaim("idp");                // removing unnecessary claims from the initial cookie (the Identity Provider)
                    options.ClaimActions.DeleteClaim("name");               // removing unnecessary claims from the initial cookie (removing this type of data reduces the cookie size)
                    options.ClaimActions.DeleteClaim("given_name");         // removing unnecessary claims from the initial cookie (removing this type of data reduces the cookie size)
                    options.ClaimActions.DeleteClaim("family_name");        // removing unnecessary claims from the initial cookie (removing this type of data reduces the cookie size)
                    options.ClaimActions.MapUniqueJsonKey("role", "role");  // adding the CUSTOM MADE claim to the claims map
                    //options.SignedOutCallbackPath = "/signout-callback-oidc";     // NOTE THIS DOES NOT WORK
                });
        }

Code from IDP Config.cs
public static IEnumerable<Client> GetClients()
        {
            return new List<Client>
            {
                /// IMPORTANT: The client details declared in here must be matched with their exact copy on the client
                new Client
                {
                    ClientId = "3TL",
                    ClientName = "3 Tier Logistics",
                    //using hybrid flow to authenticate users
                    AllowedGrantTypes = GrantTypes.Hybrid,
                    // limits the URIs the user can be redirected to after getting authenticated or logging out
                    RedirectUris = {"https://localhost:44321/signin-oidc" },
                    PostLogoutRedirectUris = { "https://localhost:44321/signout-callback-oidc" },
                    AllowedScopes =                                     // configures the allowed scopes for this particular client (aka what user info to share from all the available)
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        "roles"
                    },
                    ClientSecrets =
                    {
                        new Secret("test_secret".Sha256())
                    }
                }
            };
        }

Code from Application Server Logout Page
public class LoginModel : PageModel
    {
        private OrderService orderService;
        private string targetUrlRegisterClient;
        [BindProperty]
        public Client Client { get; set; }

        public void OnGet()
        {
            Task.Run(() => HttpContext.SignOutAsync("Cookies"));
            Task.Run(() => HttpContext.SignOutAsync("oidc"));
        }

        public void OnPost()
        {
            targetUrlRegisterClient = "http://localhost:8080/server_war_exploded/root/api/registerclient";
            orderService = new OrderService();
            Task<string> response = orderService.PostRegisterClientAsync(Client, targetUrlRegisterClient);
        }
    }

Debug output of logout hit
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:44321/Login
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker:Information: Route matched with {page = "/Login"}. Executing page /Login
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker:Information: Executing handler method Client_Customer.Pages.LoginModel.OnGet with arguments ((null)) - ModelState is Valid
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker:Information: Executed handler method OnGet, returned result .
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker:Information: Executing an implicit handler method - ModelState is Valid
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker:Information: Executed an implicit handler method, returned result Microsoft.AspNetCore.Mvc.RazorPages.PageResult.
Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler:Information: AuthenticationScheme: oidc signed out.
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler:Information: AuthenticationScheme: Cookies signed out.
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker:Information: Executed page /Login in 69.7362ms
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/2.0 GET https://localhost:44370/connect/endsession?post_logout_redirect_uri=https%3A%2F%2Flocalhost%3A44321%2Fsignout-callback-oidc&id_token_hint=eyJhbGciOiJSUzI1NiIsImtpZCI6IjA5MmI0Yjk0MjQzNjJiZmQ3ZWM3Y2MyMDU1NGFiMTZlIiwidHlwIjoiSldUIn0.eyJuYmYiOjE1NTc5MDkzNzAsImV4cCI6MTU1NzkwOTY3MCwiaXNzIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6NDQzNzAiLCJhdWQiOiIzVEwiLCJub25jZSI6IjYzNjkzNTA2MTYwMzY3NjQyMC5ZMkl6WTJReVlqRXRZMlF5TXkwME5UTmlMVGhpWkdFdFlqQTBNRGsxTVRWak1qazRNak5rTVdaaU1XRXRNV1EwTXkwME0yVTBMVGsxTlRNdFlUTmpZalEwWlRVd1pHSm0iLCJpYXQiOjE1NTc5MDkzNzAsImF0X2hhc2giOiJWWHVYRHJZcTZNWnF3X2N2T0h3eDNnIiwic2lkIjoiNGViNzQ5ZjA5ZGQ4MjNkNzI5NmQzMjU1NWU5MGJiMDYiLCJzdWIiOiIyMjIyIiwiYXV0aF90aW1lIjoxNTU3OTA5MzY3LCJpZHAiOiJsb2NhbCIsImFtciI6WyJwd2QiXX0.NzqA4kILvZgjlTd6dhku6827dG-_9MkJpAH11inQ0-biR0GXP7fkrklIRy8DgxDh8zEriNMUSM8gd9E_p7Zn4hn-HRZ5MJf1hOHfyo3Pdih0sgZ6eNzOvAManiLgNb85n6hcNx04H7PRLHjlZOR01dYkjZrnRCNTWLnVlrsu3xmnonagOtvtF5a_QuZqVJvUedqxby95RH-U5AuqW2pdPTQfzQVZBvUXrAdJGj6wOXwHCn9TSpRJcH4OPtWOMvP8Z84Iiz8vH_lK_qtBUkcSmjs_kOt_qFeGYgDE_xv71HMa0HhcbJlQ-GPwTJu2cA0teGUby33Sj-td92A7y1v5mQ&state=CfDJ8IMSTeB9liZHhYIais0HVw5svLoMCzrej-fgkjkCV_TaQjqMXAXfoVdkgkWNdpnCfCNjv9hXQ_qcU3uSC7KVbJaFghyxVZD1b3eL8Yeb_G8gnDDGoJYODAljLU_pki5M9aZbR_UbjmpgodcofaWnccPgRlLOf3nSTH1eiS2zoe8n&x-client-SKU=ID_NETSTANDARD2_0&x-client-ver=5.3.0.0
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 94.0857ms 302 text/html; charset=utf-8
IdentityServer4.Hosting.EndpointRouter:Debug: Request path /connect/endsession matched to endpoint type Endsession
IdentityServer4.Hosting.EndpointRouter:Debug: Endpoint enabled: Endsession, successfully created handler: IdentityServer4.Endpoints.EndSessionEndpoint
IdentityServer4.Hosting.IdentityServerMiddleware:Information: Invoking IdentityServer endpoint: IdentityServer4.Endpoints.EndSessionEndpoint for /connect/endsession
IdentityServer4.Endpoints.EndSessionEndpoint:Debug: Processing signout request for 2222
IdentityServer4.Validation.EndSessionRequestValidator:Debug: Start end session request validation
IdentityServer4.Validation.TokenValidator:Debug: Start identity token validation
IdentityServer4.Stores.ValidatingClientStore:Debug: client configuration validation for client 3TL succeeded.
IdentityServer4.Validation.TokenValidator:Debug: Client found: 3TL / 3 Tier Logistics
IdentityServer4.Test.TestUserProfileService:Debug: IsActive called from: IdentityTokenValidation
IdentityServer4.Validation.TokenValidator:Debug: Calling into custom token validator: IdentityServer4.Validation.DefaultCustomTokenValidator
IdentityServer4.Validation.TokenValidator:Debug: Token validation success
{
  "ClientId": "3TL",
  "ClientName": "3 Tier Logistics",
  "ValidateLifetime": false,
  "Claims": {
    "nbf": 1557909370,
    "exp": 1557909670,
    "iss": "https://localhost:44370",
    "aud": "3TL",
    "nonce": "636935061603676420.Y2IzY2QyYjEtY2QyMy00NTNiLThiZGEtYjA0MDk1MTVjMjk4MjNkMWZiMWEtMWQ0My00M2U0LTk1NTMtYTNjYjQ0ZTUwZGJm",
    "iat": 1557909370,
    "at_hash": "VXuXDrYq6MZqw_cvOHwx3g",
    "sid": "4eb749f09dd823d7296d32555e90bb06",
    "sub": "2222",
    "auth_time": 1557909367,
    "idp": "local",
    "amr": "pwd"
  }
}
IdentityServer4.Validation.EndSessionRequestValidator:Information: End session request validation success
{
  "ClientId": "3TL",
  "ClientName": "3 Tier Logistics",
  "SubjectId": "2222",
  "PostLogOutUri": "https://localhost:44321/signout-callback-oidc",
  "State": "CfDJ8IMSTeB9liZHhYIais0HVw5svLoMCzrej-fgkjkCV_TaQjqMXAXfoVdkgkWNdpnCfCNjv9hXQ_qcU3uSC7KVbJaFghyxVZD1b3eL8Yeb_G8gnDDGoJYODAljLU_pki5M9aZbR_UbjmpgodcofaWnccPgRlLOf3nSTH1eiS2zoe8n",
  "Raw": {
    "post_logout_redirect_uri": "https://localhost:44321/signout-callback-oidc",
    "id_token_hint": "***REDACTED***",
    "state": "CfDJ8IMSTeB9liZHhYIais0HVw5svLoMCzrej-fgkjkCV_TaQjqMXAXfoVdkgkWNdpnCfCNjv9hXQ_qcU3uSC7KVbJaFghyxVZD1b3eL8Yeb_G8gnDDGoJYODAljLU_pki5M9aZbR_UbjmpgodcofaWnccPgRlLOf3nSTH1eiS2zoe8n",
    "x-client-SKU": "ID_NETSTANDARD2_0",
    "x-client-ver": "5.3.0.0"
  }
}
IdentityServer4.Endpoints.EndSessionEndpoint:Debug: Success validating end session request from 3TL
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 60.2054ms 302
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/2.0 GET https://localhost:44370/Account/Logout?logoutId=CfDJ8IMSTeB9liZHhYIais0HVw7kc9GyTnHxoDNbRDCp7qA3cjwUvTmwOc8iOz2QeBz21IjWognFICseoXkQwH-eQJtXY9bWxa1vP3GLUz98cWKI1VMcnArspUbxRT9bcUF1ZrmloS7t_Us-uV9Ipa-VkgSUmLZfXAWa2f-WXPIv3VRmGwLNV7dqQa_pQOTkyDoiW_ddGElcwit15bJ3BLS6f52dYIU5fzjlSBtzGqT516-usiS-wmfacbACtJQn1VaEahKiBnW7X1gI4PRhQhCZF-IFzeXjESuMigwFyUay7K79DOZCqJ7ReU-RZ7GR1TsFsnqS8212Dr10hkznljRMnDeB6CZbB87LorJxZvf_eH33NBhzJzCZ1bwvPoz_vJeQoHO50P1IfNUGZjO8Y7pYimUC52SCe0jCKUUF8a5t_HZHMNVvtoCgC8b42zHE9rM5ms25BWLTFsgQH6wJFG09fmI5Eu_ICWCTm7XbQxMsBLK8cXdyIb_g1ccqaoz1gohMtpfciokB5_xInN1EcResbtkRUNeLO5DN_c5aFX5QZrC-HJVqxLAdKzZ4coL-x06s8Emvu9w3S1ZjlYLZCPMKHfK1LKgAFnqq1rUEV9PDtwmWDe_gz9ga45MHyMYrrFTswq2ut2gylVFbnb9nEt-g4OWzC6Mqi1mq6Y9CmWefYDwmbsyO-hM9r-p3bZVgYCJkw77zP0UDzFndpM_82gwMau8PH85qxEk1Hz3kJJxilbvAOX1lowfBBymXZH1M0qaiIVS0V2MPL19ySkhIiBQZs7rYcsXMU-wILzhm_729Xt9TxUwZxRFgwngE2fFizgyG_g
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Route matched with {action = "Logout", controller = "Account"}. Executing action IdentityServer4.Quickstart.UI.AccountController.Logout (IdentityServer)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executing action method IdentityServer4.Quickstart.UI.AccountController.Logout (IdentityServer) with arguments (CfDJ8IMSTeB9liZHhYIais0HVw7kc9GyTnHxoDNbRDCp7qA3cjwUvTmwOc8iOz2QeBz21IjWognFICseoXkQwH-eQJtXY9bWxa1vP3GLUz98cWKI1VMcnArspUbxRT9bcUF1ZrmloS7t_Us-uV9Ipa-VkgSUmLZfXAWa2f-WXPIv3VRmGwLNV7dqQa_pQOTkyDoiW_ddGElcwit15bJ3BLS6f52dYIU5fzjlSBtzGqT516-usiS-wmfacbACtJQn1VaEahKiBnW7X1gI4PRhQhCZF-IFzeXjESuMigwFyUay7K79DOZCqJ7ReU-RZ7GR1TsFsnqS8212Dr10hkznljRMnDeB6CZbB87LorJxZvf_eH33NBhzJzCZ1bwvPoz_vJeQoHO50P1IfNUGZjO8Y7pYimUC52SCe0jCKUUF8a5t_HZHMNVvtoCgC8b42zHE9rM5ms25BWLTFsgQH6wJFG09fmI5Eu_ICWCTm7XbQxMsBLK8cXdyIb_g1ccqaoz1gohMtpfciokB5_xInN1EcResbtkRUNeLO5DN_c5aFX5QZrC-HJVqxLAdKzZ4coL-x06s8Emvu9w3S1ZjlYLZCPMKHfK1LKgAFnqq1rUEV9PDtwmWDe_gz9ga45MHyMYrrFTswq2ut2gylVFbnb9nEt-g4OWzC6Mqi1mq6Y9CmWefYDwmbsyO-hM9r-p3bZVgYCJkw77zP0UDzFndpM_82gwMau8PH85qxEk1Hz3kJJxilbvAOX1lowfBBymXZH1M0qaiIVS0V2MPL19ySkhIiBQZs7rYcsXMU-wILzhm_729Xt9TxUwZxRFgwngE2fFizgyG_g) - Validation state: Valid
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler:Information: AuthenticationScheme: idsrv signed out.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action method IdentityServer4.Quickstart.UI.AccountController.Logout (IdentityServer), returned result Microsoft.AspNetCore.Mvc.ViewResult in 24.8267ms.
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor:Information: Executing ViewResult, running view LoggedOut.
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor:Information: Executed ViewResult - view LoggedOut executed in 19.1822ms.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action IdentityServer4.Quickstart.UI.AccountController.Logout (IdentityServer) in 48.1906ms
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 59.083ms 200 text/html; charset=utf-8
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/2.0 GET https://localhost:44370/lib/bootstrap/css/bootstrap.css
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/2.0 GET https://localhost:44370/icon.png
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/2.0 GET https://localhost:44370/lib/jquery/jquery.js
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 17.4182ms 404
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 16.464ms 404
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/2.0 GET https://localhost:44370/css/site.css
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 20.1358ms 404
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 8.4111ms 404
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/2.0 GET https://localhost:44370/lib/bootstrap/js/bootstrap.js
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/2.0 GET https://localhost:44370/js/signout-redirect.js
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/2.0 GET https://localhost:44370/connect/endsession/callback?endSessionId=CfDJ8IMSTeB9liZHhYIais0HVw4UP5MHpGg4UIrZ1rPYhDNKZ0T8aLNc6sQ00tDxQN7898mdUQGymNjElfE09nHu53Jcmj2OlrmLZdqwrS33_ea8BVUC1KpYuh1NtSAGTbqHF-Z4GVqWLIM3--4-kv1Jwggs2PBPjytq65cjCge00Zg2lNQEsKjgNxupv-gNwSWvdklOEQ9gRuGAd8dTXhUJqHomK7a87OWqQvuE1hQieeDesgtCSaVhC9-CcaEJycYkOkmyrxFrOWG4Npw6smPd-XU
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 7.3577ms 404
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 7.7551ms 404
IdentityServer4.Hosting.EndpointRouter:Debug: Request path /connect/endsession/callback matched to endpoint type Endsession
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.2.4\System.Net.Security.dll'. Symbols loaded.
IdentityServer4.Hosting.EndpointRouter:Debug: Endpoint enabled: Endsession, successfully created handler: IdentityServer4.Endpoints.EndSessionCallbackEndpoint
IdentityServer4.Hosting.IdentityServerMiddleware:Information: Invoking IdentityServer endpoint: IdentityServer4.Endpoints.EndSessionCallbackEndpoint for /connect/endsession/callback
IdentityServer4.Endpoints.EndSessionCallbackEndpoint:Debug: Processing signout callback request
IdentityServer4.Stores.ValidatingClientStore:Debug: client configuration validation for client 3TL succeeded.
IdentityServer4.Validation.EndSessionRequestValidator:Debug: No client front-channel logout URLs
IdentityServer4.Validation.EndSessionRequestValidator:Debug: No client back-channel logout URLs
IdentityServer4.Endpoints.EndSessionCallbackEndpoint:Information: Successful signout callback.
IdentityServer4.Endpoints.EndSessionCallbackEndpoint:Debug: No client front-channel iframe urls
IdentityServer4.Endpoints.EndSessionCallbackEndpoint:Debug: No client back-channel iframe urls
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 103.2685ms 200 text/html; charset=UTF-8
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/2.0 GET https://localhost:44370/favicon.ico
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 1.9017ms 404
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/2.0 GET https://localhost:44370/favicon.ico
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 2.2642ms 404
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/2.0 GET https://localhost:44370/favicon.ico
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 2.4325ms 404

The core problem:
I want to be redirected to the login page of the IDP which i can not currently achieve, and i need help to understand what am I doing wrong.
P.S. I am 3rd semester at IT University and this is the first time I am using IndetityServer4, I hope to use it for all my future applications, thank you for your patience.

A: If you're looking for the signout-redirect.js:
window.addEventListener("load", function () {
    var a = document.querySelector("a.PostLogoutRedirectUri");
    if (a) {
        window.location = a.href;
    }
});


text:
Q: TypeScript Union Question (using two objects) interface A {
  profile: string;
  name: string;
  c: number;
  d: number;
}

interface B {
  title: string;
  profile: string;
  a: number;
  b: number;
}

function abFunc(obj: B | A) {
  return obj.name || obj.title
}

Like the interface above, there is data A or B. The above data also have overlapping properties.
How should we define the type in the function below?
'A|B' is used, so only duplicate properties are available.
error message
Property 'name' does not exist on type 'B | A'.
Property 'name' does not exist on type 'B'.

A: You would need to discriminate the union, for example with the operator in :
function abFunc(obj: B | A) {
  return 'name' in obj ? obj.name : obj.title
}

Playground


text:
Q: how to set break point on all function start in c++ file using visual studio 2008 I have more than 100 files as source. Each of these files are atleast 1000 lines. In order to debug the sequence of calls, I want to put a break point on all the functions for all the files. There are plenty of COM Pointers in all the files.

*

*Is it even possible with VS 2008 to set multiple break points?

*I know this is a crazy idea, any optimization suggestion?

A: You might be able to use a custom prologue to add a machine debug break to every function in the compilation unit.
http://msdn.microsoft.com/en-us/library/6xy06s51(v=vs.80).aspx

A: maybe I'm not understanding you correctly, but have you tried using the debug features "Step Into (F11)", "Step Over (F10)", and "Step Out (Shift+F11)"? That would effectively do the same thing I would imagine since you want to stop at each function call anyway.


text:
Q: Reading text file as array I want to transform a text file into an array, here is what the text file looks like
code 1 #Updated 12/15/2000
{
Reezena of Confinement
}
code 2 #Added in v2.0
{
Neil
}
code 3 #Added in V1.0
{
Jansen
}
code 4 #Updated 12/15/2000
{
Gellos
}

and what it should like after its done
array(
'1' => "Reezena of Confinement",
'2' => "Neil",
'3' => "Jansen",
'4' => "Gellos",
)

Ive tryed this:
preg_match_all('/{(.*?)}/s', $html, $matches);

//HTML array in $matches[1]
echo "
";
print_r($matches[1]);
echo "
";

However its missing the "code XXX"
somehow i need to grab it
thx in advance

A: Make use of the file() on PHP
<?php
$arr=file('new.txt'); //Save all the content what you pasted in a file named new.txt
for($i=2;$i<count($arr);$i=$i+4)
{
    echo $arr[$i];
    echo "
";
}

OUTPUT:
Reezena of Confinement
Neil
Jansen
Gellos

A: Try this:
    $str = file_get_contents ( 't.txt' );

    preg_match_all ( '@code\s+(\d+)[^{]*{([^}]+)}@', $str, $matches );

    $result = array ();

    foreach ( $matches [1] as $k => $id )
    {
        $result [$id] = trim ( $matches [2] [$k] );
    }

    var_dump ( $result );

A: My solution without any preg-like functions;
$txt = "code 1 #Updated 12/15/2000
{
Reezena of Confinement
}
code 2 #Added in v2.0
{
Neil
}
code 3 #Added in V1.0
{
Jansen
}
code 4 #Updated 12/15/2000
{
Gellos
}";

$lines = explode("\n", $txt);

$array = array();
$key = NULL;

foreach($lines as $line) {
    if(trim($line) === '{' || trim($line) === '}') {
        continue;
    }
    if(substr($line, 0, 4) == 'code') {
        $exploded = explode(' ', $line);
        $key = $exploded[1];
        continue;
    }
    if(isset($key)) {
        $array[$key] = $line;
        $key = NULL;
    }
}
echo "
";
print_r($array);
echo "
";

Results;
Array
(
    [1] => Reezena of Confinement
    [2] => Neil
    [3] => Jansen
    [4] => Gellos
)


text:
Q: Organic material creation in UDK I'm trying to generate my own procedural map in UDK to create an organic ooze material.
I have searched the docs at epic and I couldn't find a location to cover the topic of creating movement/transitions within the map. Is there a way with unreal script to code the variances in the surface over time?
I was assuming I could transition between 3-4 images but I can't find the solution.

A: I was confused by procedural. Procedural in games means to generate a level or the world from a (randomly generated) number.
For your question, it is possible to fade/blend from one texture to another in a material in UDK. But UnrealScript is not the best point to start.
Use the lerp node in the material editor for that. Plug texture 1 in A and textures 2 in B. Calculate a value between 0 and 1 to blend between the two and plug that in Alpha of the lerp node.
You can chain multiple lerp node together by plugging a lerp node in the B of another lerp node, but I suggest that to get it working for just 2 textures to understand how it works first.
You can calculate the blending value/Alpha dependent on time by using the time node.
As you are properly not familiar with materials in UDK, I suggest that you watch this excellent tutorial video about materials from 3DBuzz. This will give you the basic understanding how materials in UDK work. After that you will know what exactly I was trying to explain in this post. 1 hour may seem a bit long, but it is easy to understand and follow and I watched the whole thing, too, when I started with UDK.


text:
Q: How to get the last date of given month and year in java I have the date with the following format for user given months and year  e.g. 02/15 MM/yy format. I want to find last date of the month if it is leap year it should return 29 else not need to return 28. Can anybody tell how to do?

A: In Java 8 you can do the following:
private static final String DATE_PATTERN = "MM/yy";

public int getLastDayOfMonth(String dateString) {
    DateTimeFormatter pattern = DateTimeFormatter.ofPattern(DATE_PATTERN);
    YearMonth yearMonth = YearMonth.parse(dateString, pattern);
    LocalDate date = yearMonth.atEndOfMonth();
    return date.lengthOfMonth();
}

In earlier versions of Java you can:
public int getLastDayOfMonth(String dateString) throws ParseException {
    DateFormat dateFormat = new SimpleDateFormat(DATE_PATTERN);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(dateFormat.parse(dateString));
    return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
}


text:
Q: interpreting Cramer's V results I want to measure the magnitude and direction of a relation between two nominal variables: profession and hood. I choose to use Cramer's V based on this explanation.
import pandas as pd
import numpy as np
import scipy.stats as scis

# compute cramer's stat
def cramers_stat(contingency_table):
    chi2 = scis.chi2_contingency(contingency_table)
    print('chi2 p-value: ', chi2[1])
    if chi2[1] < 0.05:
        n = contingency_table.values.sum()
        return np.sqrt(chi2[0] / (n*(min(contingency_table.shape)-1)))
    else:
        return 'no relation'

# create df
hoods = pd.DataFrame({
    'profession': np.random.choice([
        'painter',
        'plumber',
        'statistician'
    ], 200, p=[.2,.4,.4])
})

# fill hood value with trends
def hood(value):
    if value == 'painter':
        return np.random.choice(['Uptown', 'Downtown', 'Burbs'], p=[.8,.1,.1])
    elif value == 'plumber':
        return np.random.choice(['Uptown', 'Downtown', 'Burbs'], p=[.3,.5,.2])
    elif value == 'statistician':
        return np.random.choice(['Uptown', 'Downtown', 'Burbs'], p=[.2,.7,.1])

hoods['hood'] = hoods.profession.apply(hood)

Frequencies
pd.crosstab(hoods.profession, hoods.hood)

#hood          Burbs  Downtown  Uptown
#profession
#painter           4         4      35
#plumber          12        46      25
#statistician      3        55      16

Results
cramers_stat(pd.crosstab(hoods.hood, hoods.profession))

#chi2 p-value:  4.17294374904e-11
#0.36905673033287301

Question 1
This V statistic tells me that there is a relation between profession and hood. Without other V statistics for context, how do I tell how strong this is? What is the plain english statement I can make about the statistic magnitude and direction?
Question 2
Does this statistic allow me to make statements about the strength of individual hoods and individual professions? For example, "painters are significantly more likely to live in Uptown (Cramer's V=0.35, p=4.7e-10)"?

A: Edit: Answer to Question 1:
The Cramer's V statistic doesn't show direction.  On a 2 x 2 table, phi shows direction with positive or negative sign, but directionality doesn't make much sense in a larger table of nominal categories.
There is no absolute interpretation of an effect size statistic like Cramer's V.  It is always relative to the discipline and the expectations of the experiment. For a couple of points about this, see the comments to my answer at this link.  That being said, the interpretations from Cohen 1988 are often used as typical interpretations. There is a table of interpretations here.
Edit: Answer to Question 2:
To answer the question of which Profession is associated with which Hood, there a few approaches.  One is to simply look at the percentage of counts within, say, each Profession.  If Painter is 10% Uptown, 20% Downtown, and 70% Burbs, that is helpful information.  Sometimes standardized residuals or odds ratio is used for this purpose.  You could also break the table into smaller components, such as a 1 x 3 table for each profession, and look at p-value and effect size statistics for each.  Graphical representation (spine plot, mosaic plot, bar plot) is also helpful.
It doesn't make much sense to use the omnibus Cramer's V statistic as evidence for e.g. the association within a specific profession.
Edit:Note
It appears that the function to calculate Cramer's V works correctly.

A: Maybe a comment to add to the answer provided by Sal Mangiafico: in fact, Cramer's V does not tell the direction of the association (as you asked for in Question 1), but for this purpose you can user Theil's U. In contrast to Cramer's V, Theil's U is an asymmetric measure, and it tells you the direction of the association between two categorical variables. Check this post for more information. ;)


text:
Q: Loop with if statements is not working properly in C I'm trying to write a loop with some if statements in it, and the problem with the loop is that the user is going to enter a choice, either H or S. However, when the user enters S, the program goes straight to the H statement and goes through that and after it, it goes to the other statement.
Let me show you with the code:
int decision(struct CardDeck *deck) {
    char choice;
    printf("Value is %d\n", deck->ValueOfSecondPlayer);
    while (deck->ValueOfSecondPlayer <= 21)
    {
        if (deck->ValueOfSecondPlayer == 21) {
            printf("Blackjack!");
        }
        if (deck->ValueOfSecondPlayer > 21) {
            printf("Sorry, you lose");
        }
        if (deck->ValueOfSecondPlayer < 21) {
            printf("Would you like to hit or stand?\n");
            scanf("%c", &choice);
        }
        if (choice == 'H' || choice == 'h'); {
            printf("You wish to hit; here's your card\n");
            deck->ValueOfSecondPlayer += printCards(deck);
            printf("Your total is now %d\n", deck->ValueOfSecondPlayer);
        }
        if (choice == 'S' || choice == 's') {
            printf("You wished to stay\n");
            break;
        }
    }
}

So the output I'm getting when I enter S is:
Value is 18
Would you like to hit or stand?
S
You wish to hit; here's your card
Jack of Clubs
Your total is now 28
You wished to stay
Pess any key to continue . . .

And when I enter H the program runs like this:
Value is 16
Would you like to hit or stand?
h
You wish to hit; here's your card
4 of Clubs
Your total is now 20
Would you like to hit or stand?
You wish to hit; here's your card
2 of Spades
Your total is now 22
Press any key to continue . . .

So my problem here is that the program goes into the choice H and h even though I use S or s.
If anyone can tell me what I'm doing wrong and how to fix the problem, I would be grateful!

A: You have a semicolon after the if statement for the h one.

A: See notes in comments.
int decision(struct CardDeck *deck) {
    char choice;
    printf("Value is %d\n", deck->ValueOfSecondPlayer);
    while (deck->ValueOfSecondPlayer <= 21)
    {
        // ------> NOTE you should clear choice in each iteration
        choice = 0;

        // ------> NOTE probably need to break out of while here
        if (deck->ValueOfSecondPlayer == 21) {
            printf("Blackjack!");
        }
        // ------> NOTE this will never execute
        // you should move this to the hit block
        if (deck->ValueOfSecondPlayer > 21) {
            printf("Sorry, you lose");
        }
        if (deck->ValueOfSecondPlayer < 21) {
            printf("Would you like to hit or stand?\n");
            scanf("%c", &choice);
        }
        // ------> NOTE you have a ';' after the closing parenthesis
        if (choice == 'H' || choice == 'h'); {
            printf("You wish to hit; here's your card\n");
            deck->ValueOfSecondPlayer += printCards(deck);
            printf("Your total is now %d\n", deck->ValueOfSecondPlayer);
        }
        if (choice == 'S' || choice == 's') {
            printf("You wished to stay\n");
            break;
        }
    }
}


text:
Q: why UINavigationBar color change after return form aAnother viewController with diferente color i have my base View controller with it´s embbed navigation controller so i set ist collor , when segue are executed the new view has it owns navigationbar color and it changes to it but after return to the back view this view takes the color from the previuos one.
i´m setting the color of the navigationbar like this
 override func viewDidLoad() {
    self.navigationController?.navigationBar.barTintColor = appDelegate.verde
}

its a defined color in the Appdelegate to be green color in the
in the next one i change in the color of the navigationbar the same way as above.

A: You change the color of the UINavigationBar and it remains changed unless you explicitly change it to something else. UINavigationBar does not depend on viewControllers - it's above them.
In order to have different color for each viewController when navigating between them back and forth, change UINavigationBar's color in viewWillAppear(_ animated: Bool).
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    self.navigationController?.navigationBar.barTintColor = appDelegate.verde
}

A: Instead of viewDidLoad you may put this code in viewWillAppear. This will be invoked each time the view is about to be presented so it will override any color changes for other views.


text:
Q: invalidate NSTimer inside dispatch_async I am creating a game, and inside the game I need to get a time counter.
I works great but when I scroll the map it stops and then when I finish scrolling it start again. I fix this with dispatch_async. Here is the code
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

                timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self  selector:@selector(timeNext) userInfo:nil repeats:NO];

                [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

                [[NSRunLoop currentRunLoop] run];
            });

Timer:
__block NSTimer *timer;

But if the app goes to the background I need to stop this times (and when it get active it starts again).
With this way I can scroll the map and the timer works well I try:
- (void)timeNext {
    [timer invalidate];
    }

and didin't work. Anyone knows how to stop it? or any other idea to accomplish this task?

A: Don't create your timer on a global queue's thread and then start a run loop on that thread.
Just create your timer on the main thread (main run loop), and add it to the tracking run loop mode.  A timer can be added to multiple run loop modes.
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self  selector:@selector(timeNext) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];

A: If you're using UIScrollView to scroll via your game world, timer will be paused while scroll is tracking touches - you need to setup timer to use it with different mode - UITrackingRunLoopMode, e.g.
[[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];

instead of
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

This will allow your timer to fire events while controls such as scroll is tracking user's touches.
[EDIT]
You create timer e.g. via
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;

then add this timer to runloop (basically, you should add it to your app main runloop):
NSTimer* timer = [NSTimer timerWithTimeInterval:1./60. target:self selector:@selector(tick) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];

A: I use NSRunLoopCommonModes instead of UITrackingRunLoopMode, everythings looks fine. The main thread ui operation will not block tick function anymore.
NSTimer* timer = [NSTimer timerWithTimeInterval:1./60. target:self selector:@selector(tick) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];


text:
Q: Applying a pixel Shader to a texture within a sprite with SlimDX Direct3D9 So, I am very new to Developing with DirectX, I'm slowly getting there... But!
I have this which instantiates the Direct3D9 runtime, creates a device and loads a Pixel Shader. - I can confirm the Pixel shader is loaded as 1) it works in other applications not developed by me. 2) I can break and see that all the various porperties are available and 3) no errors are reported.
Here is the setup.
Direct3DInstance = new SlimDX.Direct3D9.Direct3D();
                SlimDX.Direct3D9.PresentParameters PP = new SlimDX.Direct3D9.PresentParameters();
                PP.Windowed = true;
                PP.BackBufferHeight = PAN_Video.ClientSize.Height;
                PP.BackBufferWidth = PAN_Video.ClientSize.Width;
                PP.BackBufferCount = 0;
                PP.BackBufferFormat = SlimDX.Direct3D9.Format.R5G6B5;
                PP.PresentationInterval = SlimDX.Direct3D9.PresentInterval.Immediate;
                PP.DeviceWindowHandle = PAN_Video.Handle;

                Direct3DDevice = new SlimDX.Direct3D9.Device(Direct3DInstance, 0, SlimDX.Direct3D9.DeviceType.Hardware, PAN_Video.Handle, SlimDX.Direct3D9.CreateFlags.HardwareVertexProcessing, PP);

                string error = null;
                SlimDX.Direct3D9.ShaderBytecode SBC = SlimDX.Direct3D9.ShaderBytecode.Compile(File.ReadAllText(@"C:\Users\Marcus\Desktop\scanlines.txt"), null, null, "main", "ps_3_0", SlimDX.Direct3D9.ShaderFlags.UseLegacyD3DX9_31Dll, out error);

                SlimDX.Direct3D9.PixelShader PS = new SlimDX.Direct3D9.PixelShader(Direct3DDevice, SBC);
                Direct3DDevice.PixelShader = PS;

Here is the Shader - its not mine but one I am using to test with.
// hlslf output by Cg compiler
// cgc version 3.1.0013, build date Apr 18 2012
// command line args: -profile hlslf -po version=110
//vendor NVIDIA Corporation
//version 3.1.0.13
//profile hlslf
//program main_fragment
//semantic main_fragment.s_p : TEXUNIT0
//semantic uIntensity
//var sampler2D s_p : TEXUNIT0 : _s_p 0 : 2 : 1
//var float uIntensity :  : _uIntensity : -1 : 1
//var float2 texcoord : $vin.TEXCOORD0 : TEXCOORD0 : 0 : 1
//var float2 wpos : $vin.WPOS : WPOS : 1 : 1
//var float4 main_fragment : $vout.COLOR : COLOR : -1 : 1
//default uIntensity = 100

#
pragma pack_matrix(row_major)

struct input
{
    float2 _video_size;
    float2 _texture_size;
    float2 _output_size;
};

float _TMP1;
float _TMP0;
uniform float _uIntensity;

// main procedure, the original name was main_fragment
float4 main( in float2 _texcoord: TEXCOORD0, in float2 _wpos: VPOS, uniform sampler2D _s_p: TEXUNIT0): COLOR0
    {

        float4 _temp;

        _temp = tex2D(_s_p, _texcoord);
        _TMP0 = floor(_wpos.y / 2.00000000000000000E000 f);
        _TMP1 = floor(_wpos.y);
        if(_TMP0 != _TMP1 / 2.00000000000000000E000 f)
        { // if begin
            _temp.xyz = _temp.xyz * _uIntensity;
        } // end if
        return _temp;
    } // main end

Now then, I thought the moment you load a Shader it is applied to all rendered output, but obviously I'm wrong.
Below is what happens every 2-5 Milliseconds- all video is rendered out to screen so all the D3D stuff is working, but the loaded pixel shader is not making any difference.
Interface.VideoInfo VI = Interface.EX_GetVideoBuffer();
        Direct3DDevice.Clear(SlimDX.Direct3D9.ClearFlags.Target, Color.Black, 1.0f, 0);

        using (System.Drawing.Bitmap WindowsBMP = new System.Drawing.Bitmap(VI.Width, VI.Height, VI.Stride, System.Drawing.Imaging.PixelFormat.Format16bppRgb565, VI.Buffer))
        {

            BitmapData WindowsBPMData  = WindowsBMP.LockBits(new Rectangle(0, 0, VI.Width, VI.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            byte[] Data = new byte[WindowsBPMData.Stride * WindowsBPMData.Height];

            Marshal.Copy(WindowsBPMData.Scan0, Data, 0, Data.Length);
            WindowsBMP.UnlockBits(WindowsBPMData);

            using (SlimDX.Direct3D9.Texture TEX = new SlimDX.Direct3D9.Texture(Direct3DDevice, WindowsBPMData.Width, WindowsBPMData.Height, 0, SlimDX.Direct3D9.Usage.None, SlimDX.Direct3D9.Format.A8R8G8B8, SlimDX.Direct3D9.Pool.Managed))
            {

                DataRectangle DR = TEX.LockRectangle(0, SlimDX.Direct3D9.LockFlags.Discard);
                DR.Data.Position = 0;
                DR.Data.Write(Data, 0, Data.Length);
                DR.Data.Close();
                TEX.UnlockRectangle(0);
                using (SlimDX.Direct3D9.Sprite S = new SlimDX.Direct3D9.Sprite(Direct3DDevice))
                {
                    Direct3DDevice.BeginScene();

                    S.Begin(SlimDX.Direct3D9.SpriteFlags.None);
                    S.Draw(TEX, Color.Transparent);

                    S.End();
                    Direct3DDevice.EndScene();
                    Direct3DDevice.Present(new Rectangle(0, 0, WindowsBPMData.Width, WindowsBPMData.Height), new Rectangle(0, 0, PAN_Video.Width, PAN_Video.Height));
                }
            }

         }

I know I'm missing some stuff - but all examples I have come across deal with rendering wireframes and alike - I'm rendering images from a native Lib and all I have is the Pixel Buffer.
Please be gentle as this DirectX stuff is all very new for me.

A: You didn't set the uniforms / shader variables so you shouldn't expect any sensible output. I guess I would expect uIntensity to be 0 so you should get extreme scanlines, but I guess it could be 1.0 also (in which case you wouldn't see it.) Then again, if your window is scaled down 50% after applying scanlines, you might not see the scanlines.
In short, don't test with such a simpler pixel shader. Test with a pixel shader that returns float4(1,0,0,1);.

A: I couldn't fulfil my dream in providing shader support in my project (Sega Genesis Emulator)
I instead used a framework called ReShade, in essence it allows output from  a DirectX enabled application to have its render intercepted by a modified driver (d3d9.dll), this hook allows loading precompiled shaders using a varient of HLSL.
you simply drop the driver in the applications directory, then any calls to DirectX are managed by this driver.
I had results instantly.
Resahde Website


text:
Q: Resolving automatic and manual dependencies I´m having a little bit of trouble sorting a way to manage automatic resolved and manual dependencies in my classes.
Let´s say I have two classes to calculate prices: one calculates how much I will charge for shipping and the other how much I will charge for the entire order. The second uses the first in order to sum the shipping price to the entire order price.
Both classes have a dependency to a third class that I will call ExchangeRate which gives me the exchange rate I should use for price calculation.
So far we have this chain of dependency:
OrderCalculator -> ShippingCalculator -> ExchangeRate
I´m using Ninject to resolve these dependencies and this was working until now. Now I have a requirement that the rate returned by ExchangeRate class will vary upon a parameter that will be provided in the Constructor (because the object won´t work without this, so to make the dependency explicit it´s placed on the constructor) coming from a user input. Because of that I can no longer resolve my dependencies automatically.
Whenever I want to the OrderCalculator or any other classes that depends on ExchangeRate I cannot ask the Ninject container to resolve it to me since I need to provide the parameter in the constructor.
What do u suggest in this case?
Thanks!
EDIT: Let's add some code
This chain of objects is consumed by a WCF service and I'm using Ninject as the DI container.

public class OrderCalculator : IOrderCalculator
{
        private IExchangeRate _exchangeRate;
        public OrderCalculator(IExchangeRate exchangeRate)
        {
                _exchangeRate = exchangeRate;
        }
        public decimal CalculateOrderTotal(Order newOrder)
        {
                var total = 0m;
                foreach(var item in newOrder.Items)
                {
                        total += item.Price * _exchangeRate.GetRate();
                }
                return total;
        }
}

public class ExchangeRate : IExchangeRate
{
        private RunTimeClass _runtimeValue;
        public ExchangeRate(RunTimeClass runtimeValue)
        {
                _runtimeValue = runtimeValue;
        }
        public decimal GetRate()
        {
                //returns the rate according to _runtimeValue
                if(_runtimeValue == 1)
                        return 15.3m;
                else if(_runtimeValue == 2)
                        return 9.9m
                else
                        return 30m;
        }
}

//WCF Service
public decimal GetTotalForOrder(Order newOrder, RunTimeClass runtimeValue)
{
    //I would like to pass the runtimeValue when resolving the IOrderCalculator depedency using a dictionary or something
    //Something like this ObjectFactory.Resolve(runtimeValue);
    IOrderCalculator calculator = ObjectFactory.Resolve();
    return calculator.CalculateOrderTotal(newOrder);
}

A: As always, when you have a partial dependency on a run-time value, the solution is an Abstract Factory.
Something like this should work:
public interface IExchangeRateFactory
{
    ExchangeRate GetExchangeRate(object runTimeValue);
}

Now inject an IExchangeRateFactory into your consumers instead of ExchangeRate and use the GetExchangeRate method to convert the run-time value to an ExchangeRate instance.
Obviously you will also need to provide an implementation of IExchangeRateFactory and configure NInject to map the interface to your implementation.

A: You may find injecting factory delegates or providers to be useful. Both are pretty much impls of Mark's (+1d) answer.

A: I ended up doing something totally different.
Before I call the ObjectFactory to resolve the dependencies for me I create a new instance of the IExchangeRate using the runTimeValue and tell the IoC/DI container to use it instead of creating a new one. This way the whole chain of objects is preserved and there is no need for factories.

//WCF Service
public decimal GetTotalForOrder(Order newOrder, RunTimeClass runtimeValue)
{
    IExchangeRate ex = new ExchangeRate(runtimeValue);
    IOrderCalculator calculator = ObjectFactory.With<IExchangeRate>(ex).GetInstance();
    return calculator.CalculateOrderTotal(newOrder);
}

But since Ninject doesn't have a way to do this (only Rebind which is not what I want) I changed my container to StructureMap.
Thanks guys for all your help! Really appreciate it!

A: Move that initialization out of the constructor.

A: Updated based on the code:
//WCF Service
public decimal GetTotalForOrder(Order newOrder, RunTimeClass runtimeValue)
{
    //I would like to pass the runtimeValue when resolving the IOrderCalculator depedency using a dictionary or something
    //Something like this ObjectFactory.Resolve(runtimeValue);
    IOrderCalculator calculator = ObjectFactory.Resolve();
    return calculator.CalculateOrderTotal(newOrder);
}

Notice how this method only wants runtimeValue so that it can pass it to something else?  This is happening because object construction and runtime responsibilities are mixed.  I think you should be asking for a IOrderCalculator in the constructor for this method.
So this method just becomes:
//WCF Service
public decimal GetTotalForOrder(Order newOrder, IOrderCalculator calculator)
{
    return calculator.CalculateOrderTotal(newOrder);
}

Now, when you construct your IOrderCalculator you should pass runtimeValue to it's constructor.  It's a bit hard to answer when we do not know what runtimeValue is or where it comes from.