Q: Setter Property Required primitive dependency is not explicitly defined I have Asp.Net MVC Application and I have used structuremap,
I use custom ThrottleAttribute ActionFilter.
follow rate limiting in asp.net mvc
public enum TimeUnit
{
    Minute = 60,
    Hour = 3600,
    Day = 86400
}

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class ThrottleAttribute : ActionFilterAttribute
{
    public TimeUnit Time { get; set; }
    public int Count { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var seconds = Convert.ToInt32(Time);

        var key = string.Join(
            "-",
            seconds,
            filterContext.HttpContext.Request.HttpMethod,
            filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
            filterContext.ActionDescriptor.ActionName,
            filterContext.HttpContext.Request.UserHostAddress
        );

        // increment the cache value
        var cnt = 1;
        if (HttpRuntime.Cache[key] != null)
        {
            cnt = (int)HttpRuntime.Cache[key] + 1;
        }
        HttpRuntime.Cache.Insert(
            key,
            cnt,
            null,
            DateTime.UtcNow.AddSeconds(seconds),
            Cache.NoSlidingExpiration,
            CacheItemPriority.Low,
            null
        );

        if (cnt >= Count)
        {

            filterContext.Result = new ContentResult
            {
                Content = "You are allowed to make only " + Count + " requests per " + Time.ToString().ToLower()
            };
            filterContext.HttpContext.Response.StatusCode = 429;
        }
    }
}

after I use ThrottleAttribute throw Exception:

Setter Property 'Time' (ActionFilters.TimeUnit): Required primitive dependency is not explicitly defined

And my ActionFilter Registry:
public class ActionFilterRegisteryClass : StructureMap.Registry
{
    public ActionFilterRegisteryClass(Func<StructureMap.IContainer> containerFactory)
    {
        For<IFilterProvider>().Use(
            new StructurMapFilterProvider(containerFactory));

        Policies.SetAllProperties(x =>
        {
            x.Matching(p =>
                p.DeclaringType.CanBeCastTo(typeof(ActionFilterAttribute)) &&
                (
                    p.DeclaringType.Namespace.StartsWith("MyNamespace")
                ) &&
                !p.PropertyType.IsPrimitive &&
                p.PropertyType != typeof(string)
                );
        });
    }
}

Exception is fire in:     container.BuildUp(filter.Instance);
public class StructurMapFilterProvider : FilterAttributeFilterProvider
{
    private readonly Func<StructureMap.IContainer> _Container;

    public StructurMapFilterProvider(Func<StructureMap.IContainer> container)
    {
        _Container = container;
    }

    public override IEnumerable<Filter> GetFilters(ControllerContext controllerContext,
        ActionDescriptor actionDescriptor)
    {
        var filters = base.GetFilters(controllerContext, actionDescriptor);

        var container = _Container();

        foreach (var filter in filters)
        {
            container.BuildUp(filter.Instance);

            yield return filter;
        }
    }
}

Setter Property 'Time' (ActionFilters.TimeUnit): Required primitive dependency is not explicitly defined

What should I do?
How explicitly defined PrimitiveTypes?

A: The problem was in Registering ActionFilterClass in structuremap. I have changed it as follows:
public class ActionFilterRegisteryClass : StructureMap.Registry
{
    public ActionFilterRegisteryClass(Func<StructureMap.IContainer> containerFactory)
    {
        For<IFilterProvider>().Use(
            new StructurMapFilterProvider(containerFactory));

        Policies.SetAllProperties(x =>
        {
            x.Matching(p =>
                p.DeclaringType.CanBeCastTo(
                !p.PropertyType.IsPrimitive &&
                !p.PropertyType.IsEnum &&
                p.PropertyType != typeof(string));
        });
    }
}


Q: Making Test(s) Fail if the `application-context` Encounters an Exception When running mvn clean install against my Maven project, Build Success showed up.
However, running an individual test in IntelliJ showed that a test had failed since my test-application-context had encountered a RuntimeException.
Since this application-context failed to start the test environment, a few Maven tests did not run since they depended on the test-application-context to start up. But, even though these tests were skipped, Build Success still appeared.
I'd like Maven to fail those "skipped" tests if the application-context encounters a RuntimeException.
How can I configure the POM to show these tests as failures?


Q: Stepper on tableview cell (swift) I put stepper both outlets and action into tableview cell and using protocol delegate to connect it to tableview. When i tapped stepper in first row, stepper value appear normaly in first row but its also appear in some random row. how to fix this?
TableViewCell
protocol ReviewCellDelegate{
    func stepperButton(sender: ReviewTableViewCell)
}

class ReviewTableViewCell: UITableViewCell {
   @IBOutlet weak var countStepper: UIStepper!
   @IBOutlet weak var stepperLabel: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

@IBAction func stepperButtonTapped(sender: UIStepper) {
    if delegate != nil {
        delegate?.stepperButton(self)
        stepperLabel.text = "x \(Int(countStepper.value))"

    }
}

ViewController
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellIdentifier = "reviewCell"
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! ReviewTableViewCell

    var imageView: UIImageView?
    let photoG = self.photos[indexPath.row]
    imageView = cell.contentView.viewWithTag(1) as? UIImageView
    //let layout = cell.goodiesImage
    let tag = indexPath.row // +1
    cell.tag = tag
    photoG.fetchImageWithSize(CGSize(width: 1000, height: 1000), completeBlock: { image, info in
        if cell.tag == tag {
            imageView?.image = image
            cell.goodiesImage.image = image
        }
    })

func stepperButton(sender: ReviewTableViewCell) {
    if let indexPath = tableView.indexPathForCell(sender){
        print(indexPath)
    }
}

A: Reset the value of stepper while loading your cell. you can reset the cell property values in cell's prepareForReuse method. add the following method in your ReviewTableViewCell class.
 override func prepareForReuse()
 {
   super.prepareForReuse()

   countStepper.value = 0.0
 }

A: In tableViewCell VC:
1 - add these field
var cellDelegate: cellProtocol?
var index: IndexPath?

2 - then add this in the delegate:
func onStepperClick(index: Int, sender: UIStepper)

3 - when you have dragged your stepper over as an action use this:
@IBAction func cellStepper(_ sender: UIStepper) {
    cellDelegate?.onStepperClick(index: (index?.row)!, sender: sender)
    sender.maximumValue = 1  //for incrementing
    sender.minimumValue = -1 //for decrementing
    //this will make sense later
}

In ViewController
1 - add these to the tableView function that has the cellAtRow variable.
cell.cellDelegate = self
cell.index = indexPath

2 - Use this instead of your stepperButton function
func onStepperClick(index: Int, sender: UIStepper) {
    print(index)

    if sender.value == 1.0{
        //positive side of stepper was pressed
    }else if sender.value == -1.0{
        //negative side of stepper was pressed
    }

    sender.value = 0  //resetting to zero so sender.value produce different values on plus and minus

}

Hope this works for you

A: As mentioned by @A-Live, your component is being reused and so need to be updated.
So in your view controller:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellIdentifier = "reviewCell"
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! ReviewTableViewCell

    var imageView: UIImageView?
    let photoG = self.photos[indexPath.row]
    imageView = cell.contentView.viewWithTag(1) as? UIImageView
    //let layout = cell.goodiesImage
    let tag = indexPath.row // +1
    cell.tag = tag
    photoG.fetchImageWithSize(CGSize(width: 1000, height: 1000), completeBlock: { image, info in
    if cell.tag == tag {
        imageView?.image = image
        cell.goodiesImage.image = image
    }
})
    cell.countStepper.value = XXX[indexPath.row].value; //Here you update your view
    cell.stepperLabel.text = "x \(Int(cell.countStepper.value))" //And here

And
func stepperButton(sender: ReviewTableViewCell) {
    if let indexPath = tableView.indexPathForCell(sender){
        print(indexPath)
        XXX[sender.tag].value = sender.counterStepper.value //Here you save your updated value
}

A: NOTE:
1.MY Cell class is just normal..All changes are in viewcontroller class
2.I have taken stepper and over it added ibAddButton with same constraint as ibStepper
class cell: UITableViewCell {

    @IBOutlet weak var ibAddButton: UIButton!
    @IBOutlet weak var ibStepper: UIStepper!
    @IBOutlet weak var ibCount: UILabel!
    @IBOutlet weak var ibLbl: UILabel!
}

1.define empty int array [Int]()
var countArray = [Int]()
2.append countArray with all zeros with the number of data u want to populate in tableview
 for arr in self.responseArray{
        self.countArray.append(0)
   }

3.in cell for row at
func tableView(_ tableView: UITableView, cellForRowAt indexPath:
 IndexPath) -> UITableViewCell {

         let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! cell
         let dict = responseArray[indexPath.row] as? NSDictionary ?? NSDictionary()
         cell.ibLbl.text = dict["name"] as? String ?? String()
         if countArray[indexPath.row] == 0{
             cell.ibAddButton.tag = indexPath.row
             cell.ibStepper.isHidden = true
             cell.ibAddButton.isHidden = false
             cell.ibCount.isHidden = true
             cell.ibAddButton.addTarget(self, action: #selector(addPressed(sender:)), for: .touchUpInside)
         }else{
             cell.ibAddButton.isHidden = true
             cell.ibStepper.isHidden = false
             cell.ibStepper.tag = indexPath.row
             cell.ibCount.isHidden = false
             cell.ibCount.text = "\(countArray[indexPath.row])"
             cell.ibStepper.addTarget(self, action: #selector(stepperValueChanged(sender:)), for: .valueChanged)}
    return cell
     }

4.objc functions
 @objc func stepperValueChanged(sender : UIStepper){
     if sender.stepValue != 0{
         countArray[sender.tag] = Int(sender.value)
     }
     ibTableView.reloadData()
 }
 @objc func addPressed(sender : UIButton){

     countArray[sender.tag] = 1//countArray[sender.tag] + 1
     ibTableView.reloadData()
 }


Q: How to fix a database login issue? I'm a beginner, and I want to ask about a problem I've got with my app. I try to log with the data I put into the database but it recognizes nothing.
Here's the code of the DatabaseHelper Java file. I think the problem is with my checkData_pseudo_pass function.
Thanks in advance for the response!
DatabaseHelper.java
package com.example.tp5;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "database.db";
    public static final String TABLE_NAME = "tp4_table";
    /*
    public static final String COL_1 = "ID";
    public static final String COL_2 = "NOM";
    public static final String COL_3 = "PRENOM";
    public static final String COL_4 = "PSEUDO";
    public static final String COL_5 = "PASS";
    */

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT,NOM TEXT,PRENOM TEXT,PSEUDO TEXT,PASS TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
        onCreate(db);
    }

    public boolean InsererData(String nom, String prenom, String pseudo, String pass){
        SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("nom",nom);
        contentValues.put("prenom",prenom);
        contentValues.put("pseudo", pseudo);
        contentValues.put("pseudo", pass);
        long result = sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
        if(result == -1){
            return false;
        }else{
            return true;
        }
    }
    /*
    public boolean insertData(String nom, String prenom, String pseudo, String pass) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_2,nom);
        contentValues.put(COL_3,prenom);
        contentValues.put(COL_4,pseudo);
        contentValues.put(COL_5,pass);

        long result = db.insert(TABLE_NAME,null ,contentValues);
        if(result == -1)
            return false;
        else
            return true;
    }
    */

    public Cursor getAllData() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
        return res;
    }
    /*
    public Boolean checkData_Pass(String pass){
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res_pass = db.rawQuery("select * from tp4_table where PASS=? ",new String[]{pass});
        if(res_pass.getCount()>0) return false;
        else {
            return true;
        }
    }
    */

    public Boolean checkData_pseudo_pass(String pseudo, String pass){
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res_unique = db.rawQuery("select * from tp4_table where PSEUDO=? and PASS=?", new String[]{pseudo, pass});
        if(res_unique.getCount()>0) return false;
        else {
            return true;
        }
    }

}

MainActivity3.java
package com.example.tp5;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity3 extends AppCompatActivity{

    DatabaseHelper myDb_connexion; // création de l'objet mydb de type DatabaseHelper

    private Button valider_connexion2 = null;
    private EditText pseudo_connexion = null;
    private EditText pass_connexion = null;

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

        myDb_connexion = new DatabaseHelper(this);

        valider_connexion2  = findViewById(R.id.button3);
        pseudo_connexion =  findViewById(R.id.edit_pseudo_connexion);
        pass_connexion = findViewById(R.id.edit_pass_connexion);

        //EditText textView_pseudo = (EditText) findViewById(R.id.edit_pseudo_connexion);
        //EditText textView_pass = (EditText) findViewById(R.id.edit_pass_connexion);

        valider_connexion2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String _str_pseudo = pseudo_connexion.getText().toString().trim();
                String _str_pass = pass_connexion.getText().toString().trim();

                Intent intent3 = new Intent(MainActivity3.this, MainActivity4.class);
                Boolean check_Pseudo_Pass = myDb_connexion.checkData_pseudo_pass(_str_pseudo, _str_pass);
                //Si Check_Pseudo_Pass affiche le pseudo et le pass
                //if (check_Pseudo_Pass == true && !str_pseudo.equals("") && !str_pass.equals(""))
                if (check_Pseudo_Pass == true)
                {
                    intent3.putExtra("pseudo", _str_pseudo);
                    intent3.putExtra("pass", _str_pass);
                    startActivity(intent3);

                    Toast.makeText(MainActivity3.this,"Connexion réussie !",Toast.LENGTH_SHORT).show();
                }
                else {
                    Toast.makeText(MainActivity3.this,"Connexion raté !",Toast.LENGTH_SHORT).show();
                }

                // Question 7:Connexion unique Login="Admin",pass="root" et Extra enregistre le pseudo et le mot de passe pour le récupérer à la pas MainActivité
                /*
                Intent intent3 = new Intent(MainActivity3.this, MainActivity4.class);
                // if (!str_pseudo.equals("") && !str_pass.equals("") ) {
                if (str_pseudo.equals("Admin") && str_pass.equals("root") ) {
                    intent3.putExtra("pseudo", str_pseudo);
                    intent3.putExtra("pass", str_pass);
                    Toast.makeText(MainActivity3.this,"Connexion réussie !",Toast.LENGTH_SHORT).show();
                    startActivity(intent3);
                }else{
                    Toast.makeText(MainActivity3.this,"Connexion raté !",Toast.LENGTH_SHORT).show();
                }
                */
            }
        });
    }
}

A: Consider this method:
public Boolean checkData_pseudo_pass(String pseudo, String pass){
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res_unique =
        db.rawQuery("select * from tp4_table where PSEUDO=? and PASS=?",
                    new String[]{pseudo, pass});
    if (res_unique.getCount() > 0) {
         return false;
    } else {
        return true;
    }
}

This returns false if any of the rows in tp4_table matches the given pseudo and pass and true otherwise.
In other words, it fails if the username and password are correct.
The logic of the test is backwards.  It should be:
    if (res_unique.getCount() > 0) {
        return true;
    } else {
        return false;
    }

or better still, just this:
    return res_unique.getCount() > 0;

If you still have a problem after this change, then it is somewhere else in the code.  For example, you may not have populated the database correctly.

And you should return boolean not Boolean.
And you should fix the numerous stye errors in your code, starting the many cases of identifiers that do not follow the style rules:

*

*variable names and method names start with a lowercase letter

*no underscores (_) as in variable names, method names, class names or package names

*use camel case instead of underscores between words (except for constant names).


Q: QT Compile on Linux: Cross Compilation failed with mxe / mingw / Linux, Debian I cannot compile the Windows Wallet, it shows me everytime this Error:
What have I missed here?
I am Using Debian.
Source Code: https://github.com/rat4/blackcoin
Content of compile-gtc.sh:
#!/bin/bash
MXE_INCLUDE_PATH=/mnt/mxe/usr/i686-w64-mingw32.static/include
MXE_LIB_PATH=/mnt/mxe/usr/i686-w64-mingw32.static/lib

i686-w64-mingw32.static-qmake-qt5 \
    BOOST_LIB_SUFFIX=-mt \
    BOOST_THREAD_LIB_SUFFIX=_win32-mt \
    BOOST_INCLUDE_PATH=$MXE_INCLUDE_PATH/boost \
    BOOST_LIB_PATH=$MXE_LIB_PATH \
    OPENSSL_INCLUDE_PATH=$MXE_INCLUDE_PATH/openssl \
    OPENSSL_LIB_PATH=$MXE_LIB_PATH \
    BDB_INCLUDE_PATH=$MXE_INCLUDE_PATH \
    BDB_LIB_PATH=$MXE_LIB_PATH \
    MINIUPNPC_INCLUDE_PATH=$MXE_INCLUDE_PATH \
    MINIUPNPC_LIB_PATH=$MXE_LIB_PATH \
    QMAKE_LRELEASE=/mnt/mxe/usr/i686-w64-mingw32.static/qt5/bin/lrelease blackcoin-qt.pro

make -f Makefile.Release

After some minutes i started ./compile-gtc.sh I got this Error:

/mnt/mxe/usr/i686-w64-mingw32.static/lib/libdb_cxx.a(os_pid.o):os_pid.c:(.text+0x25):
  undefined reference to `pthread_self' collect2: error: ld returned 1
  exit status Makefile.Release:427: recipe for target
  'release/blackcoin-qt.exe' failed make: *** [release/blackcoin-qt.exe]
  Error 1

Thank you,


Q: How in Powershell see all XML Levels I have a test xml and I want to get the value from this line ATTRIBUTE NAME="News- offers_OPT_EMAIL">F
so I can check for the value F or T
if I do below I can get the title but how do I get the above line value.
[xml]$xml = Get-Content testFile.xml
$xml
$xml.CUSTOMERS.CUSTOMER.NAME.TITLE

sample XML code
<?xml version="1.0" encoding="UTF-8"?>
<CUSTOMERS xml:lang="en">
    <CUSTOMER CREATED_DATE="2018-01-01 05:18:53.0" GROUP_ID="" ID="95656565">
        <NAME>
            <TITLE>M</TITLE>
            <FIRST_NAME>Joe</FIRST_NAME>
            <LAST_NAME>Smith</LAST_NAME>
        </NAME>
        <GENDER/>
        <DATE_OF_BIRTH/>
        <ADDRESS>
            <ADDRESS_LINE_1>1 White House</ADDRESS_LINE_1>
            <ADDRESS_LINE_2>Old Ave</ADDRESS_LINE_2>
            <ADDRESS_LINE_3/>
            <TOWNCITY>LONDON</TOWNCITY>
            <COUNTY/>
            <POSTCODE>18659</POSTCODE>
            <COUNTRY>France</COUNTRY>
        </ADDRESS>
        <ADDRESS>
            <ADDRESS_LINE_1>175 avenue de la division Leclerc</ADDRESS_LINE_1>
            <ADDRESS_LINE_2/>
            <ADDRESS_LINE_3/>
            <TOWNCITY>Antony</TOWNCITY>
            <COUNTY/>
            <POSTCODE>92160</POSTCODE>
            <COUNTRY>France</COUNTRY>
        </ADDRESS>
        <CONTACT_DETAILS>
            <TELEPHONE MARKETING_OPT_IN="F" TYPE="MOBILE">0123456789</TELEPHONE>
            <EMAIL MARKETING_OPT_IN="F">johnsmith@gmail.com</EMAIL>
        </CONTACT_DETAILS>
        <ATTRIBUTE NAME="News- offers_OPT_EMAIL">F</ATTRIBUTE>
        <NOTE>NA</NOTE>
    </CUSTOMER>

A: You could use SelectSingleNode or SelectNodes with an XPath expression. There are several options to achieve what you want, depending on your intention, but this would be one way to do it:
# finde the nodes
$nodes = $xml.SelectNodes("//*[local-name()='ATTRIBUTE'][@NAME='News- offers_OPT_EMAIL']")
# get value
$nodes.InnerText

Or if the value of the attribute doesn't matter, simply do:
$xml.customers.customer.attribute.'#text'


Q: String concatenation without libraries in C I am having trouble concatenating strings in C without library function.
I tried the following:
#include <stdio.h>

struct word {
  char *str;
  int wordSize;
};

void concat(struct word words[], int arraySize, int maxSize) { // word array, its size, and max size given
  char result[maxSize];
  int resultSize = 0;
  struct word tmp;

  for (int i = 0; i < arraySize; i++) {
    tmp = words[i];
    for (int j = 0; j < words[i].wordSize; j++,  resultSize++) {
      result[resultSize + j] = tmp.str[j];
    }
  }

  puts(result);
}

For example, if the struct array words contain [{"he", 2}, {"ll", 2}, {"o", 1}], the result should be hello. However, this code prints h�l�o where the second and fourth letters are questionmark. Can anyone help me debug this?

A: Keep it simple and the bugs will fix themselves. Don't mix up the position in the result buffer with the loop iterators. No need for temporary variables.
#include <stdio.h>

typedef struct {
  char *str;
  int wordSize;
} word;

void concat(word words[], int arraySize, int maxSize) {
  char result[maxSize];
  int count=0;

  for(int i=0; i<arraySize; i++)
  {
    for(int j=0; j<words[i].wordSize; j++)
    {
      result[count]= words[i].str[j];
      count++;
    }
  }
  result[count] = '\0';

  puts(result);
}

int main()
{
  word w[3] = { {"he", 2}, {"ll", 2}, {"o", 1} };
  concat(w, 3, 128);
}

A: In this for loop
for (int j = 0; j < words[i].wordSize; j++,  resultSize++) {
  result[resultSize + j] = tmp.str[j];
}

you are incrementing resultSize and j simultaneously while you need to increase only the variable j and after the loop increase the variable resultSize by j.
But in any case the function is wrong because there is no check that resultSize is less than maxSize.
And moreover the built string is not appended with the terminating zero '\0'. As a result this statement
puts(result);

invokes undefined behavior.
There is no need to create the variable length array
char result[maxSize];

just to output the concatenated string.
The function can be declared and defined the following way as it is shown in the demonstrative program below.
#include <stdio.h>

struct word {
  char *str;
  int wordSize;
};

void concat( const struct word words[], size_t arraySize, size_t maxSize )
{
    for ( size_t i = 0, j = 0; i < maxSize && j < arraySize; j++ )
    {
        for ( size_t k = 0; i < maxSize && k < words[j].wordSize; i++, k++ )
        {
            putchar( words[j].str[k] );
        }
    }

    putchar( '\n' );
}

int main(void)
{
    struct word words[] =
    {
        { "he", 2 }, { "ll", 2 }, { "o", 1 }
    };
    const size_t arraySize = sizeof( words ) / sizeof( *words );

    concat( words, arraySize, 5 );

    return 0;
}

The program output is
hello

A: You have a couple of problems here. result[resultSize + j] means you are effectively skipping over half the characters in result. Secondly, if you copy the entire string, including the null character, puts will stop printing the result string at the end of the first word itself. So you need to skip copying the string terminator and put it in at the end of your whole concatenated string.
#include <stdio.h>

struct word {
  char *str;
  int wordSize;
};

void concat(struct word words[], int maxSize) { // word array and max size given
  char result[maxSize];
  int resultSize = 0;
  struct word tmp;

  for (int i = 0; i < 3; i++) {
    tmp = words[i];
    // Keep copying the words to result, one after the other
    // But drop the last NULL character
    for (int j = 0; j < (words[i].wordSize - 1); j++,  resultSize++) {
      result[resultSize] = tmp.str[j];
    }
  }
  // Put the NULL character in after all words have been copied
  result[resultSize] = 0;
  puts(result);
}

struct word mywords[] =
{
  { "TestWord", sizeof("TestWord")},
  { "TestWord2", sizeof("TestWord2")}
};

int main(void)
{
  concat(mywords, 100);
  return 0;
}


Q: Instragram - Redirect URI dose not match with registered - Objective C I am getting error while Login with oAuth for Instagram, it says the redirectURI is wrong. I have researched on it and I have checked many answers on stackoverflow but its not helpful for me.
Here is the complete detail of what I did in my application.
1) I set my ClientId in pList for redirect URI :

2) I have added ig and authorize while creating the URI:

3)Now, I set ClientID in Instragram API :

And Here is my RedirectURI :
https://instagram.com/oauth/authorize?response_type=token&redirect_uri=igdd5fb08a33444af0b2b9c9420e69bc35%3A%2F%2Fauthorize&scope=relationships&client_id=dd5fb08a33444af0b2b9c9420e69bc35
When I fire the URl after login, it gives me the following error:

Can anyone help to find out where I am going wrong ?
Thanks,

A: The redirect URI you're providing is not what you have defined in your client settings.
1) Go to http://instagram.com/developer/clients/manage/
2) For your desired client/application, look for REDIRECT URI.

3) Make sure you provide the same redirect uri in your request as it is defined in your client/application settings. In your case, https://api.instagram.com/oauth/authorize/?response_type=token&redirect_uri=REDIRECT-URI&client_id=CLIENT-ID
Note: You may provide an optional scope parameter to request additional permissions outside of the “basic” permissions scope.
Note: You may provide an optional state parameter to carry through any server-specific state you need to, for example, protect against CSRF issues.
At this point, we present the user with a login screen and then a confirmation screen where they approve your app’s access to his/her Instagram data.
4) Once a user successfully authenticates and authorizes your application, instagram will redirect the user to your redirect_uri with a code parameter that you’ll use to request the access_token like http://your-redirect-uri?code=CODE.
For more information to learn about authentication process [Link]
tl;dr. The Redirect URI you send to /authorized must be same as the registered URI in your app.


Q: c++ rhel confd cdb_get returns elements in a weird order encountring a weird issue with confd. Items are indexed by uint key - when i use configuration with 9 items or lower, everything is ok - cdb_get with index 1 returns the first item, index two the seconds and so on.
When i add the 10th item - the 1st item I query i get the correct one  ( 1 id ) but when i query for the second item i'll get the 10th item ( like they are sorted in a "stringy" manner, and not int although they are declared as uint in yang schema ).
Struggling with this for few days, does anyone have an idea how to correct the return order?
Thanks


Q: How to display or hide JSON data on a page based on a string value? I have a form which has an Email field.  There is also an option to hide or show email address on a web page depending on which radio button was selected ("YES" or "No").
So, when exclude_email="No" the email should not be displayed. I know it is a conditional statement, but I am lost here...

A: You could do it inline when building the string.
$(function() {
    var people = [];
    $.getJSON('data2.json', function(data) {
        $.each(data, function(i, f) {
            var tblRow = "" + "" +
                f.name + "" + "" +
                f.title + "" + "" +
                f.company + "" + "" + "" +
                (f.exclude_email == "No" ? '' : f.email) + "" + "" + "" + "" +
                f.comment + "" + "" + ""

            $(tblRow).appendTo("#userdata tbody");
            if (f.exclude_email == "No") this.hide(email);
        });
    });
});

A: This worked! Thank you!

$(function() {
var people = [];
$.getJSON('data2.json', function(data) {
       $.each(data, function(i, f) {
          var tblRow = "" + "" + f.name + "" + "" + f.title + "" + "" + f.company + "" +
           "" + "" + (f.exclude_email == "Yes" ? '' : f.email) + "" + "" + "" + "" + f.comment + "" + "" + ""
      $(tblRow).appendTo("#userdata tbody");

 });

});
});


Q: Caption package with beamer changing tables to figures I have a weird problem Whenever I use the caption package with beamer class on Mac OS (Windows works fine), Tables labels are changed to Figures (only started happening recently) .. I wonder what could be the problem.
See preamble of my latex presentation:
\documentclass[english,usenames,dvipsnames]{beamer}
\usepackage{mathptmx}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{booktabs}
\usepackage{amsmath}
\usepackage{amssymb}

\makeatletter

\providecommand{\tabularnewline}{\\}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Textclass specific LaTeX commands.
% this default might be overridden by plain title style
\newcommand\makebeamertitle{\frame{\maketitle}}%
% (ERT) argument for the TOC
\AtBeginDocument{%
  \let\origtableofcontents=\tableofcontents
  \def\tableofcontents{\@ifnextchar[{\origtableofcontents}{\gobbletableofcontents}}
  \def\gobbletableofcontents#1{\origtableofcontents}
}
\numberwithin{equation}{section}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% User specified LaTeX commands.
%\usetheme{Warsaw}
% or ...
%\usetheme{Madrid}
\usetheme{CambridgeUS}
\usecolortheme{beaver}
%\renewcommand{\tabcolsep}{0.2 cm}
\usepackage{textpos}
\usepackage{enumerate}
%\usepackage[shortlabels]{enumitem}
%\usepackage{anyfontsize}
\usepackage{multicol}
\usepackage{setspace}
\usepackage{latexsym}
%\setbeamertemplate{caption label separator}{: }
\usepackage[utf8]{inputenc}
\usepackage{mathtools}
\usepackage{algorithm, algorithmic}
\renewcommand\thesubsection{\Alph{subsection}}
%\usepackage{algpseudocode}
\usepackage{graphicx}
%\usepackage{longtable}
\usepackage{bm}
\usepackage{wrapfig}
\usepackage{ragged2e}
\usepackage{lipsum}
\usepackage{fancybox}
\usepackage{listings}
\usepackage{cite}
\usepackage{color}
\usepackage{xcolor}
\usepackage{tikz}
\usepackage{tikz-network}

\usepackage{caption}

\usepackage{diagbox}
\setbeamercovered{transparent}
% or whatever (possibly just delete it)
\usepackage{multirow}
%\usepackage{algorithm2e}
%\usepackage{algorithmicx}
%\usepackage{float}
\setbeamertemplate{caption}[numbered]
\algsetup{linenosize=\small}

\renewcommand{\makebeamertitle}
{
\begingroup
\setbeamertemplate{footline}{}
\setbeamertemplate{navigation symbols}{}
\frame{\titlepage}
\endgroup
}

\makeatother

\begin{document}
\title[]{Example}
\author[latex forum]{example\and \\ \bigskip{}
}
\institute[]{%\includegraphics[scale=0.07]{institution-logo-filename} \\\\
}
\date[October 2019]{}

\makebeamertitle

%\beamerdefaultoverlayspecification{<+->}

\addtocounter{framenumber}{-1}

\section{Introduction}
\begin{frame}{CIs Disruptions Examples}

\begin{table}
\begin{tabular*}{12cm}{@{\extracolsep{\fill}}ll}
\toprule
Date & \multicolumn{1}{c}{Disruption}\tabularnewline
\midrule
\midrule
{\scriptsize{}November 1965} & {\scriptsize{}Blackout in ten states in the northeastern US affected
30 million people.}\tabularnewline
\midrule
\midrule
{\scriptsize{}July 1977} & {\scriptsize{}In New York’s suburbs,10 million people to lose power
for over 24 h.}\tabularnewline
\midrule
\midrule
{\scriptsize{}December 1978} & {\scriptsize{}Blackout in part of France due to voltage collapse.}\tabularnewline
\midrule
\midrule
{\scriptsize{}January 1981} & {\scriptsize{}1.5 million customers in Idaho, Utah, and Wyoming were
affected for 7 h.}\tabularnewline
\midrule
\midrule
{\scriptsize{}March 1982} & {\scriptsize{}Over 900 000 lost power for 1.5 h due to high-voltage
line failure in Oregon.}\tabularnewline
\midrule
\midrule
{\scriptsize{}December 1994} & {\scriptsize{}2 million customers from Arizona to Washington State
lost power.}\tabularnewline
\midrule
\midrule
{\scriptsize{}July 1996} & {\scriptsize{}Blackouts for 2 million customers in 14 states for approximately
6h.}\tabularnewline
\midrule
{\scriptsize{}August 2003} & {\scriptsize{}Northeastern United States and Canada cascading outages}\tabularnewline
\bottomrule
\end{tabular*}

\caption{\label{tab:Disruptions-Examples}Power Disruptions Examples}
\end{table}
\end{frame}
%

\end{document}

A: This looks like a clear bug. The code sets the code for the table to figure:
\@ifclassloaded{beamer}{%
  \caption@InfoNoLine{beamer document class}%
  \let\caption@ORI@figure\figure
  \def\figure{\caption@settype{figure}\caption@ORI@figure}
  \let\caption@ORI@table\figure %<------------------------HERE
  \def\table{\caption@settype{table}\caption@ORI@table}
}{}

Report it to the maintainer.

A: Beamer's version of table must be getting replaced by the caption package.  Simply restore it after caption is loaded using
\makeatletter
\renewenvironment{table}[1][]{%
  \def\@captype{table}%
  \par\nobreak\begin{center}\nobreak}
  {\par\nobreak\end{center}\nobreak}
\makeatother

Alternatively, one can save and restore table using:
\let\beamertable=\table
\let\beamerendtable=\endtable
\usepackage{caption}
\let\table=\beamertable
\let\endtable=\beamerendtable


Q: Building a table from Python nested dictionaries with missing values Here's the current data structure I have:
{'bin1': {'A': 14545,
          'B': 18579,
          'C': 5880,
          'D': 20771,
          'E': 404396},
 'bin2': {'A': 13200,
          'B': 12279,
          'C': 5000,
          'D': 16766,
          'E': 200344},
 [...] }

And I'd like to write to a table, in the form:
        A     B     C    D     E
bin1  14545 18579 5880 20771 494396
bin2  13200 12279 5000 16766 200344
...

Currently I'm using a crude print loop (where d == the dictionary described above):
# print the table header
labs = [i for i in d[d.keys()[0]]]
print "bin" + "\t" + "\t".join(labs)

# loop and print the values
for j in d:
    print j + "\t" + "\t".join(map(str, [d[j][q] for q in d[j]]))

Which appeared to work (despite obviously being unordered), however in my output I've found that some nested dictionaries don't contain all fields A-E. I guess one way to do this is to rebuild the dictionary, maybe using a more appropriate matrix-type data structure and fill in the missing values with 0, but given I have this huge nested dictionary to hand, is there a smarter way of printing the output shown above that could handle missing elements?

A: Using pandas:
import pandas as pd

data = {'bin1': {'A': 14545,
          'B': 18579,
          'C': 5880,
          'D': 20771,
          'E': 404396},
        'bin2': {'A': 13200,
          'D': 16766,
          'E': 200344},
        }

df = pd.DataFrame(data).T
df.fillna(0, inplace=True)
print(df)

prints
          A      B     C      D       E
bin1  14545  18579  5880  20771  404396
bin2  13200      0     0  16766  200344

The df.fillna(0) replaces missing values with 0.

A: You can use d[j].get(q, '0') instead of d[j][q] to fill in 0 for all missing entries:
# print the table header
labs = sorted(max(d.values(), key=len))
print "bin" + "\t" + "\t".join(labs)

# loop and print the values
for j in d:
    print j + "\t" + "\t".join(str(d[j].get(q, '0')) for q in labs)

I also made some slight modifications to the other parts of the code so the columns are ordered.


Q: Using generic class as type parameter I would like to use a generic class as a type parameter for another generic class.
At first my class definition was like this:
class Foo<T, R extends BaseDto> {}

Then my requirements changed and I had to use a wrapper/holder class for my R type
My attempt so far: (Gives compile-time error: class or interface expected on Bar<R>)
class Bar<T extends BaseDto> {
    private T dto;
    public Bar(T dto) {
        this.dto= dto;
    }
    // getters and setters
}
class Foo<T, Bar<R>> {
    private T entity;
    private R dto;
    // getters and setters
}

I can not use it as Foo<T, Object> because then the clients using this class would not know that they actually need a cast from Object to Bar.
How would I implement such behaviour?

A: Instead of changing the class header, replace everywhere in the class where you used R with Bar<R>.
So the class header stays the same:
class Foo<T, R extends CustomClass>

But let's say you have a field of type R. That needs to be changed to Bar<R>:
Bar<R> someField;

A: It looks like what you need may be:
class Foo<T, R extends CustomClass, S extends Bar<R>>

A: You would use
class Foo<T extends CustomClass, R extends Bar<T>> {}

If Bar is fixed, i.e., if the user does not need another class extending Bar, then you need to get rid of R and just use Bar<T> inside Foo


Q: How to get cumulative sum of unique IDs with group by? I am very new to python and pandas working on a pandas dataframe which looks like
Date     Time           ID   Weight
Jul-1     12:00         A       10
Jul-1     12:00         B       20
Jul-1     12:00         C       100
Jul-1     12:10         C       100
Jul-1     12:10         D       30
Jul-1     12:20         C       100
Jul-1     12:20         D       30
Jul-1     12:30         A       10
Jul-1     12:40         E       40
Jul-1     12:50         F       50
Jul-1     1:00          A       40

I am trying to achieve group by date, Time and ids and apply cumulative sum such that if an id is present in the next time-slot the weight is only added once(uniquely). The resulting data frame would look like this
Date     Time           Weight
Jul-1     12:00         130     (10+20+100)
Jul-1     12:10         160     (10+20+100+30)
Jul-1     12:20         160     (10+20+100+30)
Jul-1     12:30         160     (10+20+100+30)
Jul-1     12:40         200     (10+20+100+30+40)
Jul-1     12:50         250     (10+20+100+30+40+50)
Jul-1     01:00         250     (10+20+100+30+40+50)

This is what I tried below, however this is still counting the weights multiple times:
df=df.groupby(['date','time','ID'])['Wt'].apply(lambda x: x.unique().sum()).reset_index()
df['cumWt']=df['Wt'].cumsum()

Any help would be really appreciated!
Thanks a lot in advance!!

A: The code below uses pandas.duplicate(), pandas.merge(), pandas.groupby/sum and pandas.cumsum() to come to the desired output:
# creates a series of weights to be considered and rename it to merge
unique_weights = df['weight'][~df.duplicated(['weight'])]
unique_weights.rename('consider_cum', inplace = True)

# merges the series to the original dataframe and replace the ignored values by 0
df = df.merge(unique_weights.to_frame(), how = 'left', left_index=True, right_index=True)
df.consider_cum = df.consider_cum.fillna(0)

# sums grouping by date and time
df = df.groupby(['date', 'time']).sum().reset_index()

# create the cumulative sum column and present the output
df['weight_cumsum'] = df['consider_cum'].cumsum()
df[['date', 'time', 'weight_cumsum']]

Produces the following output:


Q: jQuery Validate plugin is validating a field which has become "disabled" I have a field gender? which enables is Pregnant? if gender is set to FEMALE,
then if is Pregnant? field is unanswered, it's flagged as invalid.
If you go back and set gender? to MALE  The validation still flags is Pregnant? as invalid, even though it has been disabled.
jQuery says disabled fields are ignored.  I even tried:
jquery.validate validating disabled field
ignore: ":hidden"

What am I missing?

A: this is a valid problem, with this markup
<form>

    Male:
    <input type="radio" name="gender" value="male" />
    Female:
    <input type="radio" name="gender" value="female" />

    Pregnant:
    <input type="radio" name="pregnant" value="yes" />
    Not Pregnant:
    <input type="radio" name="pregnant" value="no" />

<input type="submit" />
</form>

and this script
$('[name=gender]').click(function () {
    var disabled = $(this).val() === 'male';
    $('[name=pregnant]').attr('disabled', disabled);

    // UNCOMMENT THIS TO FIX
    // if ($('[name=pregnant]').hasClass('error')) {
    //    $('form').validate().form();
    // }
});

$('input').addClass('required');

$('form').validate({
    ignore: ":disabled",
    errorPlacement: function (error, element) {
        error.appendTo(element.parent("div"));
    },
    submitHandler: function () {
        alert('form is ok');
    }
});

to reproduce the problem:

*

*click female

*click submit

*error message shows - this is correct

*click male - error message still shows

*click submit - form is valid

so as @ioan says you need to try and get rid of this error message as it is confusing, even though the form is valid the error message is still there

*

*problem -  http://jsfiddle.net/YzCHJ/4/

*a possible solution -  http://jsfiddle.net/YzCHJ/5/

A: The .validate() ignore: option works as follows:

ignore, Default: ":hidden"
  Elements to ignore when validating, simply filtering them out. jQuery's not-method is
  used, therefore everything that is accepted by not() can be passed as this option.

http://docs.jquery.com/Plugins/Validation/validate#toptions
Working Demo: http://jsfiddle.net/us9aE/
HTML:
<form id="myform">
     <input type="text" name="field" disabled="disabled" />

</form>

jQuery:
$(document).ready(function() {
    $('#myform').validate({
        ignore: ":disabled"
    });
});

If you'd like more specific help, please show your relevant HTML, your jQuery, and optionally create a jsFiddle demo.

A: The disabled fields are ignored during the validation phase BUT if the validation phase comes into action before the field has been disabled, the error message will still be there.
You can try to simply remove the validation message by cleaning the validation errors and re-validate the form.


Q: react/prop-types and flow My .eslintrc looks like this and I am using flow:
{
  "extends": [
    "plugin:flowtype/recommended",
    "plugin:react/recommended",
    "prettier",
    "prettier/flowtype",
    "prettier/react"
  ],
  "plugins": [
    "flowtype",
    "react",
    "prettier"
  ],
  "parserOptions": {
    "ecmaVersion": 2016,
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true
    }
  },
  "env": {
    "es6": true,
    "node": true
  },
  "rules": {
    "prettier/prettier": ["error", {
      "singleQuote": true,
      "trailingComma": "none",
      "bracketSpacing": true,
      "jsxBracketSameLine": false,
      "parser": "flow"
    }]
  },
  "settings": {
    "flowtype": {
      "onlyFilesWithFlowAnnotation": true
    }
  }
}

I am still getting react react/prop-types even though I am using flow.
Is this correct and should I just turn them off?

A: PropTypes are for runtime type checking, while Flow is for static type checking. Both serve their own purpose, not all type errors can be caught during compilation, so PropTypes helps you with those; Flow can catch some errors early - before you interact with your app, or even load it to the browser.


Q: Terraform breaking Azure Logic App connections I am creating an Azure Logic App (using it to unzip to a blob storage). For this I need the Logic App workflow and a connection to the blob storage. I create the empty Logic App Workflow with Terraform and the actual Logic App implementation with Visual Studio that I just then deploy to the Logic App created with tf.
I use following tf code to create the empty Logic App Workflow:
resource "azurerm_logic_app_workflow" "logic_unzip" {
  name                    = "ngh-${var.deployment}-unziplogic"
  resource_group_name     = "${azurerm_resource_group.rg.name}"
  location                = "${azurerm_resource_group.rg.location}"
}

As the Logic App needs connection to the Blob storage I will use following template to create it:
resource "azurerm_template_deployment" "depl_connection_azureblob" {
        name                    = "azureblob"
        resource_group_name     = "${azurerm_resource_group.rg.name}"

        template_body = <<DEPLOY
{
        "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
        "contentVersion": "1.0.0.0",
        "parameters": {
                "connection_name": {"type": "string"},
                "storage_name": {"type": "string"},
                "storage_access_key": {"type": "string"},
                "location": {"type": "string"},
                "api_id": {"type": "string"}
        },
        "resources": [{
                "type": "Microsoft.Web/connections",
                "name": "[parameters('connection_name')]",
                "apiVersion": "2016-06-01",
                "location": "[parameters('location')]",
                "scale": null,
                "properties": {
                        "displayName": "[parameters('connection_name')]",
                        "api": {
                                "id": "[parameters('api_id')]"
                        },
                        "parameterValues": {
                                "accountName": "[parameters('storage_name')]",
                                "accessKey": "[parameters('storage_access_key')]"
                        }
                },
                "dependsOn": []
        }]
}
DEPLOY
        parameters              = {
                "connection_name"       = "azureblob"
                "storage_name"          = "${azurerm_storage_account.sa-main.name}"
                "storage_access_key"    = "${azurerm_storage_account.sa-main.primary_access_key}"
                "location"              = "${azurerm_resource_group.rg.location}"
                "api_id"                = "${data.azurerm_subscription.current.id}/providers/Microsoft.Web/locations/${azurerm_resource_group.rg.location}/managedApis/azureblob"
        }
        deployment_mode         = "Incremental"
}

Running plan and apply, these work perfect. In Visual Studio I can then create the Logic App and use the azureblob connection to select the correct blob storage.
Now, when I have deployed the Logic App Workflow from Visual Studio and run terraform plan I get following changes:
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  ~ update in-place

Terraform will perform the following actions:

  ~ azurerm_logic_app_workflow.logic_unzip
      parameters.$connections: "" => ""
      parameters.%:            "1" => "0"

Plan: 0 to add, 1 to change, 0 to destroy.

Running the apply command now will break the Logic App as it removes the bound connection. Clearly the Visual Studio deploy has created the binding between the Logic App and the connection.
How can I tell Terraform not to remove the connections (created by the Visual Studio deploy) from the Logic App?

A: Terraform is not aware of the resources deployed in the arm template, so it detects the state change and tries to "fix" that. I dont see any CF resources for logic app connections, so seeing how it detects that parameters.connections changed from 0 to 1 adding your connection directly to the workflow resource might work, but CF mentions : Any parameters specified must exist in the Schema defined in workflow_schema, but I dont see connections in the schema, which is a bit weird, but I assume I'm misreading the schema
you can also use ignore_changes:
lifecycle {
    ignore_changes = [
        "parameters.$connections"
    ]
}

according to the comments and this
reading:
https://www.terraform.io/docs/configuration/resources.html#ignore_changes


Q: How to copy Folder directory including Root volume folder on Windows? I would like to copy Recursively the full C:\Test Folder with all subdirectories including the Test folder and the folders permisions. I tried using the following commands but it only copies the files:
Powershell:
`Get-ChildItem -Path -Recurse C:\Test | Copy-Item -Destination F:\ -Recurse -Con
tainer`

Robocopy:
robocopy C:\Test F:\ /s /e

A: Robocopy has several options to preserve properties, but if you want to preserve it all use "/copyall":
robocopy "c:\test" "f:\test" /copyall /e
Also note that using a trailing slash for folder names is not allowed since it escapes the quote. These are good:
robocopy "c:\test" "f:" /copyall /e
robocopy "c:\test" "f:\test" /copyall /e

These are bad:
robocopy "c:\test" "f:\" /copyall /e
robocopy "c:\test" "f:\test\" /copyall /e


Q: std::transform() and toupper(), no matching function I tried the code from this question C++ std::transform() and toupper() ..why does this fail?
#include <iostream>
#include <algorithm>

int main() {
  std::string s="hello";
  std::string out;
  std::transform(s.begin(), s.end(), std::back_inserter(out), std::toupper);
  std::cout << "hello in upper case: " << out << std::endl;
}

Theoretically it should've worked as it's one of the examples in Josuttis' book, but it doesn't compile http://ideone.com/aYnfv.
Why did GCC complain:
no matching function for call to ‘transform(
    __gnu_cxx::__normal_iterator<char*, std::basic_string
        <char, std::char_traits<char>, std::allocator<char> > >,
    __gnu_cxx::__normal_iterator<char*, std::basic_string
        <char, std::char_traits<char>, std::allocator<char> > >,
    std::back_insert_iterator<std::basic_string
        <char, std::char_traits<char>, std::allocator<char> > >,
    <unresolved overloaded function type>)’

Am I missing something here? Is it GCC related problem?

A: Just use ::toupper instead of std::toupper. That is, toupper defined in the global namespace, instead of the one defined in std namespace.
std::transform(s.begin(), s.end(), std::back_inserter(out), ::toupper);

Its working : http://ideone.com/XURh7
Reason why your code is not working :  there is another overloaded function toupper in the namespace std which is causing problem when resolving the name, because compiler is unable to decide which overload you're referring to, when you simply pass std::toupper. That is why the compiler is saying unresolved overloaded function type in the error message, which indicates the presence of overload(s).
So to help the compiler in resolving to the correct overload, you've to cast std::toupper as
(int (*)(int))std::toupper

That is, the following would work:
//see the last argument, how it is casted to appropriate type
std::transform(s.begin(), s.end(), std::back_inserter(out),(int (*)(int))std::toupper);

Check it out yourself: http://ideone.com/8A6iV

A: Problem
std::transform(
    s.begin(),
    s.end(),
    std::back_inserter(out),
    std::toupper
);

no matching function for call to ‘transform(__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::back_insert_iterator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, <unresolved overloaded function type>)’

This is a misleading error; the interesting part is not that there's "no matching function" for the call, but why there's no matching function.
The why is that you're passing a function reference of an "<unresolved overloaded function type>" as an argument, and GCC prefers to error on the call rather than on this overload resolution failure.

Explanation
First, you should consider how the C library is inherited in C++. <ctype.h> has a function int toupper(int).
C++ inherits this:

[n3290: 21.7/1]: Tables 74, 75, 76, 77, 78, and 79 describe headers
  <cctype>, <cwctype>, <cstring>, <cwchar>, <cstdlib>
  (character conversions), and <cuchar>, respectively.
[n3290: 21.7/2]: The contents of these headers shall be the same as
  the Standard C Library headers <ctype.h>, <wctype.h>,
  <string.h>, <wchar.h>, and <stdlib.h> and the C Unicode TR
  header <uchar.h>, respectively [..]
[n3290: 17.6.1.2/6]:Names that are defined as functions in C shall
  be defined as functions in the C++ standard library.

But using <ctype.h> is deprecated:

[n3290: C.3.1/1]: For compatibility with the Standard C library, the
  C++ standard library provides the 18 C headers (D.5), but their use is
  deprecated in C++.

And the way to access the C toupper is through the C++ backwards-compatibility header <cctype>. For such headers, the contents are either moved or copied (depending on your implementation) into the std namespace:

[n3290: 17.6.1.2/4]: [..] In the C++ standard library, however, the declarations
  (except for names which are defined as macros in C) are within
  namespace scope (3.3.6) of the namespace std. It is unspecified
  whether these names are first declared within the global namespace
  scope and are then injected into namespace std by explicit
  using-declarations (7.3.3).

But the C++ library also introduces a new, locale-specific function template in header <locale>, that's also called toupper (of course, in namespace std):

[n3290: 22.2]: [..] template <class charT> charT toupper(charT c,
  const locale& loc); [..]

So, when you use std::toupper, there are two overloads to choose from. Since you didn't tell GCC which function you wish to use, the overload cannot be resolved and your call to std::transform cannot be completed.

Disparity
Now, the OP of that original question did not run into this problem. He likely did not have the locale version of std::toupper in scope, but then again you didn't #include <locale> either!
However:

[n3290: 17.6.5.2]: A C++ header may include other C++ headers.

So it just so happens that either your <iostream> or your <algorithm>, or headers that those headers include, or headers that those headers include (etc), lead to the inclusion of <locale> on your implementation.

Solution
There are two workarounds to this.

*

*You may provide a conversion clause to coerce the function pointer into referring to the overload that you wish to use:
std::transform(
   s.begin(),
   s.end(),
   std::back_inserter(out),
   (int (*)(int))std::toupper  // specific overload requested
);

*You may remove the locale version from the overload set by explicitly using the global toupper:
std::transform(
   s.begin(),
   s.end(),
   std::back_inserter(out),
   ::toupper                  // global scope
);

However, recall that whether or not this function in <cctype> is available is unspecified ([17.6.1.2/4]), and using <ctype.h> is deprecated ([C.3.1/1]).
Thus, this is not the option that I would recommend.

(Note: I despise writing angle brackets as if they were part of header names — they are part of #include syntax, not header names — but I've done it here for consistency with the FDIS quotes; and, to be honest, it is clearer...)

A: std::transform(s.begin(), s.end(), s.begin(),
std::bind(&std::toupper<char>, std::placeholders::_1, std::locale()));

If you use vc toolchain,please include locale


Q: String to javascript in Firefox extension (without eval(), setTimeout or new Function) I'm passing strings such as "getElementById('div1')" or "getElementsByName('div2')" from a remote server depending on the page the user opens. How can I run these as javascript in the page without using any of the above mentioned functions.

A: var head = document.getElementsByTagName('head')[0],
    script = document.createElement('script');
script.innerHTML = 'alert("hello");';
head.appendChild(script);

A: You may be able to use document.write. I don't know if you can use that for javascript, but I recommend that the server should pass codes plus an element name to the client, and then execute a certain method based off of that.


Q: Specific object selection in xcode Is there way to select object by their specific tag without the use of a loop?
So instead:
for (UIImageView *someObject in [self.view subviews]) {
    if (someObject.tag == someInteger) {
         [someObject removeFromSuperview];
    }
}

Use something with a more direct approach like:
[[UIImageView.whereTagEquals someInteger] removeFromSuperview];

Although I think if there was such an option it would work the same way. It would loop "behind the scene" all the UIImageViews and do something if it found the right one.
Or maybe someone can help me get the same desired result with a different approach. I notice that because of too much loops my game starts to slow down at a certain point.
Thank you!

A: A one liner you can use is -[UIView viewWithTag:], but this will likely loop internally as well. A faster approach for lots of views is to use an NSDictionary (NSNumber instances as keys plus views as values). Dictionaries use hashes internally so they're faster in most cases.

A: Try this:
[[self.view viewWithTag:someInteger] removeFromSuperview];


Q: Get list of answers per city I have this db:
Users-table:
+----+---------+
| id | city_id |
+----+---------+

city_id -> references id on city

Cities-table:
+----+------+
| id | city |
+----+------+

Answers-table:
+----+---------+
| id | user_id |
+----+---------+

user_id -> references id on users

Now I want a query with this result:
+-----------+--------+
| City-name | amount |
+-----------+--------+
| New York  | 500    |
+-----------+--------+

I tried several joins, count, dinstincts but no success. Think it should be quite easy but didnt manage to do it.
My query:
SELECT cities.name, COUNT(answers.id) FROM answers
JOIN users ON users.id = answers.user_id
JOIN cities on users.city_id = cities.id

but gives me only 1 city..

A: You need to add GROUP BY cities.name
SELECT cities.name, COUNT(answers.id) FROM answers
JOIN users ON users.id = answers.user_id
JOIN cities on users.city_id = cities.id
GROUP BY cities.name

This will tell MySQL that you want the COUNT to be grouped by cities. Without this, mysql will group everything together and count it all.

A: You should be aggregating to get a count, etc. So something like:
SELECT      COALESCE(c.city, '<Unknown>') AS Cityname,
            COUNT(a.id) AS amount

FROM        Answers AS a

LEFT JOIN   Users AS u
    ON      a.user_id = u.id

LEFT JOIN   Cities AS c
    ON      u.city_id = c.id

GROUP BY    c.city


Q: How browsers will convert mixins to regular css In Less and Sass we make use of lots of mixins, how does the browser compile or converts those mixins to regular CSS and apply those styles?

A: The browser DOES NOT convert pre-processed (LESS, SCSS, Compass) CSS rules.
You need to use a build script/compiler BEFORE linking a normal CSS file to your HTML. This process converts SCSS/LESS -> CSS for your browser to render.
You can use Webpack, Grunt, Gulp, or even desktop/GUI tools to do this.
You can also use a javascript parser to inject the final CSS into the page onLoad but this has performance implications and IS NOT recommended.


Q: QAF Reports are not populated in dashboard.htm
*

*Got the latest code here: https://github.com/infostretch/qaf-report.

*Extracted dashboard directory & dashboard.htm to the project root directory.

*Ran QAF tests.

*Opened dashboard.htm during test run & also after test run.

*Tried to open dashboard.htm in Google Chrome, Firefox & Safari after giving permissions to access local files. But Dashboard.htm did not load anything. A spinning icon is displayed continously even after several minutes.

Am I missing anything here?

A: If you are accessing reports locally as file protocol, browser may have restriction to access local files. In such case follow the steps to allow local file access from file for the browser you are using.
Firefox:
go to about:config
set security.fileuri.strict_origin_policy:false.

Safari:
Click on the Develop menu in the menu bar.
Select Disable Local File Restrictions.

If develop menu is not available, Click on the Edit > Preferences > Advanced tab. Check "Show Develop menu in the menu bar.
chrome:
Close down your Chrome browser (make sure you close all instances if you have multiple windows open)
Go to Run and type the following command: chrome.exe --allow-file-access-from-file.
Hit enter.

Reference from local-report-access

A: I just want to give more clarity by making little corrections to the existing steps mentioned here:
https://github.com/infostretch/qaf-report#local-report-access
When you are opening report "dashboard.htm" from local file system, your browser may have local file access restrictions.
In that case, you can do following setings:

*

*Firefox:

*

*Enter "about:config" in the browser url field & click on the button "Accept the Risk & Continue".

*In the "search preference name" field, enter "security.fileuri.strict_origin_policy" & click Enter & click on the toggle button towards the right to set it FALSE.

*Safari:

*

*Click on the Develop menu in the menu bar.

*Select Disable Local File Restrictions.

If develop menu is not available,
1. Click on the Safari > Preferences > Advanced tab(in MAC, Safari > Preferences > Advanced tab).
2. Check "Show Develop menu in the menu bar.

*

*Chrome:

*In Windows PC:

*

*Close down your Chrome browser (make sure you close all instances if you have multiple windows open)

*Go to Run and type the following command: chrome.exe --allow-file-access-from-file.

*In MAC

*

*Open your terminal anywhere, make sure Google Chrome is currently not running, copy paste this line and hit enter:

open /Applications/Google\ Chrome.app --args --allow-file-access-from-files


Q: Elasticsearch: Filter Query not working I've been working to change my query to a filter in Elasticsearch using the java api. I've made sure that the fields I am running searches on are set to "not_analzed".
Here is the java code for the filter:
FilterBuilder andFilter = FilterBuilders.andFilter(FilterBuilders.termFilter("thread_name", keyword), FilterBuilders.termFilter("site_name", "test_site"));

    QueryBuilder filteredQuery = QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), andFilter);

    SearchResponse threadResponse = client.prepareSearch("thread_and_messages").setQuery(filteredQuery).setSize(20).setFrom(firstRowOffset).execute().actionGet();

This then gets translated to this in JSON:
"filtered" : {
"query" : {
  "match_all" : { }
},
"filter" : {
  "and" : {
    "filters" : [ {
      "term" : {
        "thread_name" : "apple"
      }
    }, {
      "term" : {
        "site_name" : "test_site"
      }
    } ]
  }
}
}

When I try to do any searches it won't return the document I'm looking for which is thread_name: Apple and site_name: test_site.
Also when I run this using a curl command it won't find that document either.
Can anyone see what I'm doing wrong here?

A: You can use must clause.That will perform and operation
 "query": {
    "bool": {
        "must": [
           {
               "query_string": {
                  "default_field": "thread_name",
                  "query": "apple"
               }
           },
           {
               "query_string": {
                  "default_field": "site_name",
                  "query": "test_site"
               }

           }
        ]
    }
  }


Q: Curved arrow along a circle MATPLOTLIB I need to plot some curved arrows which should lie on a circle.
I tried with patches.FancyArrowPatch, but I could not find a connectionstyle able to follow a circle.
Is there any connectionstyle that I can use to get the arrows of the shape I need?
Thanks for any help.
This is an example of code I tried:
from matplotlib import pyplot as plt, patches
from math import pi, sin,cos

fig,ax=plt.subplots()
ax.set_xlim(-1.05,1.05)
ax.set_ylim(-1.05,1.05)

# reference circle
circ=patches.Circle((0,0),radius=1.0,fill=False,lw=1, color='C0',zorder=10)
ax.add_patch(circ)

style="Simple,tail_width=0.5,head_width=3,head_length=6"
kw = dict(arrowstyle=style, color="C1")

ang1=pi/6
ang2=pi/3
rad=0.17
arc=patches.FancyArrowPatch((cos(ang1),sin(ang1)), (cos(ang2),sin(ang2)),connectionstyle="arc3,rad={}".format(rad),shrinkA=0,shrinkB=0,**kw)
ax.add_patch(arc)

ang1=pi/2
ang2=pi
rad=0.4
arc=patches.FancyArrowPatch((cos(ang1),sin(ang1)), (cos(ang2),sin(ang2)),connectionstyle="angle3, angleA=180, angleB=270",shrinkA=0,shrinkB=0,**kw)
ax.add_patch(arc)

ang1=5*pi/4
ang2=0
rad=0.7
arc=patches.FancyArrowPatch((cos(ang1),sin(ang1)), (cos(ang2),sin(ang2)),connectionstyle="arc3,rad={}".format(rad),shrinkA=0,shrinkB=0,**kw)
ax.add_patch(arc)
ax.axis('off')
ax.set_aspect('equal')

and this is the result:


Q: Drawable from String in Android How do I get a Drawable resource if I have the String (its name) as it appears in the drabale folder?
int categoryPicIndex = myCursor.getColumnIndex(CookingContract.CategoryEntry.COLUMN_PIC_CATEGORY);
String categoryPic = myCursor.getString(categoryPicIndex);

At this point I have the string that I would use to call R.drawable.___ .
How can I solve the problem?

A: If "yourImageView" is the ImageView and you want to set background of it and the name of image is "imageName"
yourImageView.setImageResource(context.getResources().
                getIdentifier("drawable/" + imageName, null,context.getPackageName()));

But i should say sorry as it doesn't really give you drawable  but it gives Resource, But i hope this will help you use the string name of drawable file.


Q: domain class field not being displayed on view page I am unable to view all of the below fields when I run my grails app the " Cost" field is not being displayed on the view page, the fields are displayed on the add page. If I remove the "name" field the "cost" field is then displayed. Is there a field limit that im not aware of ?
package racetrack

class Race {

    String name
    Date startDate
    String city
    String state
    BigDecimal distance
    BigDecimal cost
    Integer maxRunners = 100000

    static constraints = {

        name()
        startDate()
        city()
        state()
        distance()
        cost()
        maxRunners()
    }

}

List.gsp -
<%@ page import="racetrack.Race" %>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <meta name="layout" content="main" />
        <g:set var="entityName" value="${message(code: 'race.label', default: 'Race')}" />
        <title><g:message code="default.list.label" args="[entityName]" /></title>

            <g:message code="default.home.label"/>
            <g:link class="create" action="create"><g:message code="default.new.label" args="[entityName]" /></g:link>

<g:message code="default.list.label" args="[entityName]" />

            <g:if test="${flash.message}">

${flash.message}

            </g:if>

                            <g:sortableColumn property="id" title="${message(code: 'race.id.label', default: 'Id')}" />

                            <g:sortableColumn property="name" title="${message(code: 'race.name.label', default: 'Name')}" />

                            <g:sortableColumn property="startDate" title="${message(code: 'race.startDate.label', default: 'Start Date')}" />

                            <g:sortableColumn property="city" title="${message(code: 'race.city.label', default: 'City')}" />

                            <g:sortableColumn property="state" title="${message(code: 'race.state.label', default: 'State')}" />

                            <g:sortableColumn property="distance" title="${message(code: 'race.distance.label', default: 'Distance')}" />

                    <g:each in="${raceInstanceList}" status="i" var="raceInstance">

                            <g:link action="show" id="${raceInstance.id}">${fieldValue(bean: raceInstance, field: "id")}</g:link>

                            ${fieldValue(bean: raceInstance, field: "name")}

                            <g:formatDate date="${raceInstance.startDate}" />

                            ${fieldValue(bean: raceInstance, field: "city")}

                            ${fieldValue(bean: raceInstance, field: "state")}

                            ${fieldValue(bean: raceInstance, field: "distance")}

                    </g:each>

                <g:paginate total="${raceInstanceTotal}" />

A: Assuming you're referring to the scaffolded list view, the scaffolding only renders six fields.
The basic logic (from src/templates/scaffolding/list.gsp) is:
props.eachWithIndex { p, i ->
    if(i == 0 {
        // render the field as a link to the show view
    } else if(i < 6) {
        // render the field value
    }
}

Note that the list of properties includes the id. Since you define six fields in your constraints, the last one's not being displayed (only the id + first five are).
Edit
To "fix" this, you have some options:

*

*Update the scaffolded list view code:

*

*First, run grails install-templates

*Open up src/templates/scaffolding/list.gsp

*Find the code segment above and change the condition
Note that this will change the rendering for all scaffolded and generated list views.

*Generate the view and update it manually.
It looks like you've already generated the view, so you'll just need to update it. Note that if you generate it again, it will overwrite your changes.


Q: XSD for soap result not working I want to check a soap response against a xsd.
Here is the xml soap response:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <GetHTMLResponse xmlns="http://www.webserviceX.NET">
            <GetHTMLResult>
                Test
            </GetHTMLResult>
        </GetHTMLResponse>
    </soap:Body>
</soap:Envelope>

Here is my XSD:
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:import namespace="http://schemas.xmlsoap.org/soap/envelope/" schemaLocation="http://schemas.xmlsoap.org/soap/envelope/"/>
<xs:element name="GetHTMLResponse">
  <xs:complexType>
    <xs:sequence>
        <xs:element  name="GetHTMLResult" minOccurs="0" maxOccurs="1">
            <xs:simpleType>
                <xs:restriction base="xs:string">
                </xs:restriction>
            </xs:simpleType>
         </xs:element>
    </xs:sequence>
</xs:complexType>

I get this error:
Cvc-elt.1: Cannot Find The Declaration Of Element 'soap:Envelope'.
Why is this happening?

A: Try checking the SOAP response against the following XSD file.  I added elements for the outer <soap:Envelope> and <soap:Body> tags which are present in the SOAP response.
<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org"
xmlns:tns="http://www.w3.org/2003/05/soap-envelope">

<xs:element name="Envelope" type="tns:envType">
  <xs:complexType name="envType">
    <xs:sequence>
      <xs:element name="Body" type="tns:bodyType">
        <xs:complexType name="bodyType">
          <xs:sequence>
            <xs:element name="GetHTMLResponse">
              <xs:complexType>
                <xs:sequence>
                  <xs:element name="GetHTMLResult" minOccurs="0"
                              maxOccurs="1" type="xs:string">
                    <xs:simpleType>
                      <xs:restriction base="xs:string">
                      </xs:restriction>
                    </xs:simpleType>
                  </xs:element>
                </xs:sequence>
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
  </xs:complexType>
</xs:element>

</xs:schema>


Q: Is this the correct way of presenting the formula in code I am creating a pokemon like game, I am currently trying to add the damage calculations into my game but I am not good at maths or reading formulas, the code I have wrote:
func take_damage(move,attacker):
    var modifier : float = rand_range(0.85,1.0)
    var a : float = ((2.0 * attacker.level) / 5) + 2
    var b : float = a * move.power * (attacker.attack() / defence()) + 2.0
    var c : float = b / 50
    var damage = round(c * modifier)
    current_health -= damage

    print(damage)
    print(a)
    print(b)

and here is a link to where I found pokemons damage calculation with a formula:
https://bulbapedia.bulbagarden.net/wiki/Damage
What I want to know is, what I have wrote in my code the same as the formula, thanks!


Q: How can I model a ordered, variable-length series of string collections in a database? I'm developing an application which has very specific/odd database requirements.
I need to store collections of strings. If it helps, one string per collection is designated as "canonical", and the others are "alternatives". The list of collections needs to be ordered, so that I can easily get e.g. the 8th string collection in the list. Finally, I need to be able to insert arbitrary amounts of collections into any point in the list.
Obviously a relational database with a simple incremental id column would be great for this except for the fact that you have to be able to insert collections into any point in the list. Then you'd have to update every single item after the inserted one, which isn't ideal.
I'm new to databases. I barely know how to use relational databases, much less anything else. Should I use SQL for this, or should I ditch relational databases for a NoSQL approach? I'm lost.

A: For structured ordering in a database, you'll want a column to store the ordering. An int is fine, but a decimal can make updates a little easier. Don't use the name "order" for the column, as it's a keyword, consider "display_order".
You can create a self-referencing table. A "canonical" term has a null parent id, an "alternative" does not.
create table terms (
  term_id int primary key,
  term text not null,
  parent_term_id int null references terms(term_id),
  display_order int not null,

  unique (parent_term_id, term),
  unique (parent_term_id, display_order)
);

Add a canonical term:
inset into terms (term_id, term, parent_id, display_order) values
(1, 'United Kingdom', null, 0);

Add alternative terms, associated w the above:
inset into terms (term_id, term, parent_id, display_order) values
(2, 'Great Britain', 1, 0),
(3, 'England', 1, 1);

You can use Recursive Common Table Expressions (except in MySQL) to efficiently query this structure.
See Using a sort order column in a database table regarding updating your order column.

A: Another form of structuring data in an RDBMS is nested sets. I've played around with them and if they meet your need, they can be vastly superior to self-referential designs.
One important consideration is that the ratio of data "movement" (inserts, deletes, updates to change the position) to queries must be low. In other words, the data should be relatively stable.
With a nested set design, just one self-join is all that is needed to traverse an entire tree to any arbitrary depth. No recursion! That alone makes it a big selling point for me. :)
Unfortunately, while there is information available on the Internet, it is all fairly basic. But if you don't mind playing around to get familiar with it, you just might be glad you did.


Q: Error: Cannot fit requested classes in a single dex file (# methods: 67593 > 65536) How to solve this error I'm getting in Android Studio:

Error: Cannot fit requested classes in a single dex file (# methods: 67593 > 65536)

cant build my project now

A: Do this 4 step
1: Add this library in dependencies of the app build.gradle :
implementation 'com.android.support:multidex:1.0.3'
2: Add in the defaultConfig of the app build.gradle :
defaultConfig {
    //other configs
    multiDexEnabled true //add this line
}

3: Create new Java class like this :
public class ApplicationClass extends MultiDexApplication {
    @Override
    public void onCreate() {
           super.onCreate();
    }
}

4: Add this to your manifest (in application tag):
<application
    android:name=".ApplicationClass"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name">

A: Same situation happened in my Visual Studio 2019 Xamarin project, and the way to solve this problem is just like what mentioned in the link:
Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536
multiDexEnabled true

By checking the Enable multiDex checkbox in the option page of the ***.Droid project solves the problem.

A: Before you take any decision, as said in Google documentation :

Before configuring your app to enable use of 64K or more method
  references, you should take steps to reduce the total number of
  references called by your app code, including methods defined by your
  app code or included libraries.

So try to remove useless importation in your app gradle and do a nice clean project or do multidex
Source : https://developer.android.com/studio/build/multidex


Q: Choosing Windows Phone IsolatedStorage My web service returns some data. I want to cache it.
Do I use this and serialize it to a file?
IsolatedStorageFile.GetUserStoreForApplication()

Or do I use this and stick it into the Dictionary?
IsolatedStorageSettings.ApplicationSettings

A: For caching data I would stick it in a file in IsolatedStorage.
It is a little more work, but you can write a simple enough wrapper around it.
It is conceivable that IsolatedStorageSettings.ApplicationSettings will one day be synced between devices using SkyDrive, this is the direction Microsoft are taking with Windows 8. So you should stick to using it for it's purpose which is application based settings.


Q: Plotting fixed plot area I have simple question, how can I plot fixed height barplots, i.e. stretching the plot area only change margins not the bararea, like the following:
> A <- 4
> plot (A)

> barplot(A, col = "green4")

When I strech are, bar area also get increases.

Edits: I want to keep the box size constant even the plot gets stretched.

A: by splitting the screen into multiple parts, you can achieve that partially:
split.screen(c(3,1))
A <- 4
barplot(A, col="green4")

A: Are you looking to just expand the y axis. Look at ylim?

A: What you might be looking for is to fix your aspect ratio. This can be achieved using asp:
barplot(A, col = "green4", asp = 1)

See also this post to R-help.
On a more philosophical note, when the height of the bar changes, there is no change in surface area. barplot only draws a sequence of bars, where the x axis is an ordinal (ordered categorical) variable which makes it impossible to calculate a surface area. The height of the bar is the only changing variable. I would recommend drawing these kinds of timeseries using a simple line plot.
So instead of:
a = runif(100)
b = 1:100
barplot(a)

use:
plot(b, a, type = "l")

or switch to my favorite plotting package, ggplot2:
require(ggplot2)
theme_set(theme_bw())
qplot(b, a, geom = "line")


Q: PGFPlots: how to achieve different colored bars with symbolic coordinates and a single \addplot command? I have the following:
\documentclass{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}

\begin{document}
\begin{tikzpicture}
\begin{axis}[
xbar,
xmin=0,
xmax=290,
xlabel={Mentions},
ylabel={Title words},
symbolic y coords={
    {Devices},
    {Data},
    {Scheme},
    {Authentication},
    {Key},
    {Secure},
    {Lightweight},
    {Security},
    {Elliptic Curve Cryptography},
    {Wireless Sensor Networks},
    {Internet of Things},
    {Cryptography}
},
ytick=data,
nodes near coords, nodes near coords align={horizontal},
]
\addplot coordinates {
(33,{Devices})
(47,{Data})
(49,{Scheme})
(52,{Authentication})
(61,{Key})
(68,{Secure})
(73,{Lightweight})
(78,{Security})
(111,{Elliptic Curve Cryptography})
(115,{Wireless Sensor Networks})
(246,{Internet of Things})
(257,{Cryptography})
};
\end{axis}
\end{tikzpicture}
\end{document}

I want to color some bars of this chart in a different color. The fact that there is a single \addplot command along with that there are symbolic coordinates, makes it pretty difficult for me.


Q: How do I sync my contacts FROM my iPhone 6 8.1.3 TO my macbook pro Yosemite 10.10.1? I can't seem to get my contacts from my iPhone to my mac or to my iCloud account. my contacts from my mac and iCloud match, but I have way more contacts in my phone. And no matter what I do, I can't seem to get them from my phone to my mac/icloud. quite annoying.

A: 8.1.3 no longer allows offline syncing. Instead, you must be connected to the Internet and logged into iCloud to sync contacts. I learned this by troubleshooting similar issue with Apple Care.


Q: How can I fix a "conflicting requests" kernel module error when running dnf update on Fedora 32? Background: I'm running Fedora 32 on a Thinkpad. Current kernel version is as follows:
Linux 5.8.4-200.fc32.x86_64 x86_64
Problem: It was working as expected for several months, but now when I run dnf update the following error is given:
Error:
 Problem 1: package kernel-modules-extra-5.7.15-200.fc32.x86_64 requires kernel-uname-r = 5.7.15-200.fc32.x86_64, but none of the providers can be installed
  - conflicting requests
 Problem 2: package kernel-5.7.15-200.fc32.x86_64 requires kernel-core-uname-r = 5.7.15-200.fc32.x86_64, but none of the providers can be installed
  - conflicting requests

Current situation / what I've tried: My (current, likely incorrect) understanding is that this older kernel package is being specified by some other package, and can't be installed because it's older and does not appear in the default repos.
I can get non-kernel packages to update by running dnf --excludepkgs=kernel\* , but I'd like to 1) understand, and 2) fix this error so that I can get kernel updates normally.
I have researched the error somewhat (see links below), but none of the similar conflict errors match my situation very closely, and I'm reluctant to remove or disable the denoted module(s) without understanding what that might do.
All guidance much appreciated!
Links I've investigate to date:
(https://www.linux.org/threads/how-to-fix-problem-conflicting-requests-on-dnf-install-on-centos.29322/)
("package X requires Y, but none of the providers can be installed")
(https://askbot.fedoraproject.org/en/question/133821/dnf-upgrade-conflicting-requests/)
(yum update returns kernel error) NOTE: this one looks similar, but the config file fix suggested here is not applicable to my configuration

A: Try this:
dnf remove $(rpm -qa | grep 5.7.15-200)


Q: the if statement syntax in the jsp mvc, jsp and bootstrap in which i am passing 2 model attributes

*

*model.addAttribute("map",map)

*model.addAttribute("size",SIZE)
now on the jsp i want to iterate over this map and want to check if map value matches the SIZE varibale value for which i tried below syntax

        < c:forEach items="${maps}" var="buttonName"  varStatus="counter">

                           <c:if test="${buttonName.key} == ${SIZE}">
                                 <button type="button" id="a" >cat</button>
                            </c:if>

         < /c:forEach>

but this is not working , please let me know if the if syntax is correct ?

A: ${} is not used to enclose a single variable but the whole statement. And you should use eq instead of ==. So the correct syntax is:
${buttonName.key eq SIZE}


Q: WebSocket - c# .NET Não achei quase nada sobre WebSockets + .NET no google, gostaria de saber como é feito esse servidor utilizando o .NET futuramente a ideia é criar um aplicativo e um hardware (Arduino) que faça comunicação com esse servidor WebSocket.
É possível criar um servidor WebSocket em ConsoleAplication ou ServiceWindows? ou somente em asp.net (pagina web)? como é criado esse servidor? em JavaScript? ou tem como faze-lo utilizando o C# mesmo? eu pesquisei bastante, mas ainda está um pouco vago a lógica do WebSocket, se alguém puder compartilhar um código simples só pra entender mesmo como funciona o WebSocket agradeceria muito!

A: Você poderá rodar o servidor no console se usar asp net core (inclusive no linux).
O ideal é escrever utilizando o signalr (módulo npm) para facilitar a sua vida, permitindo implementar o web socket sem ter muito conhecimento.
Para rodar o servidor no console basta rodar o comando dotnet run na pasta do projeto ou dando o play no visual studio usando a opção console, não lembro o nome mas você verá duas, uma usando IIS Express e a outra o console.
Para saber mais sobre o signalr acesse o tutorial (em inglês) https://dotnetthoughts.net/getting-started-with-signalr-using-aspnet-core/

A: O SignalR par amim hoje é a melhor solução dem websocket c#.
Acho que vale estudar um pouco sobre ele.
Utilizo em algumas aplicações minhas, é muito simples de fazer e gerenciar as conexões.
Você pode escolher se conectar a todos usuarios, um usuario ou grupo de usuario.
Esse tutorial do Eduardo Pires me ajudou muito: http://www.eduardopires.net.br/2013/04/aspnet-signalr-introducao-e-utilizacao/

A: Sim é possível criar um websocket utilizando console application. Ele é criado utilizando C# mesmo e você pode encontrar um código de exemplo neste artigo na documentação oficial.
Neste link da MDN tem um tutorial "Escrevendo um servidor WebSocket em C #"


Q: Element vs. Generic Type  I wonder why Swift uses Element rather than Generic <T> in the following example.
What is the difference between Element vs T

A: From Generics:

Type Parameters
Type parameters specify and name a placeholder type, and are written immediately after the function’s name, between a pair of matching angle brackets (such as <T>).
Naming Type Parameters
In most cases, type parameters have descriptive names, such as Key and Value in Dictionary<Key, Value> and Element in Array<Element>, which tells the reader about the relationship between the type parameter and the generic type or function it’s used in. However, when there isn’t a meaningful relationship between them, it’s traditional to name them using single letters such as T, U, and V, such as T in the swapTwoValues(_:_:) function above.

So
func createArray<Element>(element: Element) -> [Element] { ... }
func createArray<T>(element: T) -> [T] { ... }
func createArray<Rumpelstilzchen>(element: Rumpelstilzchen) -> [Rumpelstilzchen] { ... }

are identical functions. Here the placeholder type is the element type of the returned array, therefore Element is a suitable “descriptive name.”
But it makes no difference otherwise, is it up to you to choose a name for the placeholder, balancing between readability and conciseness.

A: T is not particularly traditional. In FP, Backus uses T, but ML, from around the same time, uses a. Haskell uses a, Scala uses A. There's a mix of choices.
Swift, however, has strong reasons to use descriptive names. First, it's a quite descriptive language. Types are named with fully spelled-out words. Methods typically are literate in construction. Variables and properties are rarely abbreviated. There's no reason that type parameters should be uniquely obscure.
It also matches well with associated types which are quite naturally verbose. What would you call Collection's index type besides Index? Why should its "element" type be specially abbreviated? And if Array implements Collection, why should it create a distinct name (T) that it would then have to associate with Collection's Element? Why would you special-case all this just to make the type name unintuitive?
The deeper question would be, why wouldn't Array's element be called Element?


Q: How to use TestScheduler in RxJava How should I use RxJava's TestScheduler? I come from a .NET background but the TestScheduler in RxJava does not seem to work the same way as the test scheduler in .NET rx.
Here is sample code that I want to test
Observable<Long> tick = Observable.interval(1, TimeUnit.SECONDS);
contactsRepository.find(index)
  .buffer(MAX_CONTACTS_FETCH)
  .zipWith(tick, new Func2<List<ContactDto>, Long, List<ContactDto>>() {
    @Override
    public List<ContactDto> call(List<ContactDto> contactList, Long aLong) {
      return contactList;
    }
  }).subscribe()

I've tried:
subscribeOn(testScheduler)
testScheduler.advanceTimeBy(2, TimeUnit.SECONDS);
testScheduler.triggerActions();

with no luck.

A: I made a little example of how to use a TestScheduler. I think it's very similar to the .NET implementation
@Test
public void should_test_the_test_schedulers() {
    TestScheduler scheduler = new TestScheduler();
    final List<Long> result = new ArrayList<>();
    Observable.interval(1, TimeUnit.SECONDS, scheduler)
        .take(5)
        .subscribe(result::add);
    assertTrue(result.isEmpty());
    scheduler.advanceTimeBy(2, TimeUnit.SECONDS);
    assertEquals(2, result.size());
    scheduler.advanceTimeBy(10, TimeUnit.SECONDS);
    assertEquals(5, result.size());
}

https://github.com/bric3/demo-rxjava-humantalk/blob/master/src/test/java/demo/humantalk/rxjava/SchedulersTest.java
EDIT
According to your code : you should pass the scheduler to the Observable.interval operation, as this is what you want to control :
    TestScheduler scheduler = new TestScheduler();

    Observable<Long> tick = Observable.interval(1, TimeUnit.SECONDS, scheduler);
    Subscription toBeTested = Observable.from(Arrays.asList(1, 2, 3, 4, 5))
            .buffer(3)
            .zipWith(tick, (i, t) -> i)
            .subscribe(System.out::println);

    scheduler.advanceTimeBy(2, TimeUnit.SECONDS);

A: you have some class:
public class SomeClass {
  public void someMethod() {
    Observable<Long> tick = Observable.interval(1, TimeUnit.SECONDS);
    contactsRepository.find(index)
      .buffer(MAX_CONTACTS_FETCH)
      .zipWith(tick, new Func2<List<ContactDto>, Long, List<ContactDto>>() {
        @Override
        public List<ContactDto> call(List<ContactDto> contactList, Long aLong) {
          return contactList;
        }
      }).subscribe()
  }
}

Look up [Observable.interval][1] in the docs and you will see it operates on the computation scheduler, so lets override that in our test.
public class SomeClassTest {
  private TestScheduler testScheduler;

  @Before
  public void before() {
    testScheduler = new TestScheduler();
    // set calls to Schedulers.computation() to use our test scheduler
    RxJavaPlugins.setComputationSchedulerHandler(ignore -> testScheduler);
  }

  @After
  public void after() {
    // reset it
    RxJavaPlugins.setComputationSchedulerHandler(null);
  }

  @Test
  public void test() {
    SomeClass someInstance = new SomeClass();
    someInstance.someMethod();

    // advance time manually
    testScheduler.advanceBy(1, TimeUnit.SECONDS);
  }

This solution is an improvement to the accepted answer as the quality, integrity and simplicity of the production code is maintained.


Q: Project with Match in aggregate not working in mongodb I am trying to fetch data based on some match condition. First I've tried this:
Here ending_date is full date format
    Offer.aggregate([
    {
        $match: {
            carer_id : req.params.carer_id,
            status : 3
        }
    },
    {
        $group : {
            _id : { year: { $year : "$ending_date" }, month: { $month : "$ending_date" }},
            count : { $sum : 1 }
        }
    }],
    function (err, res)
    { if (err) ; // TODO handle error
         console.log(res);
    });

which gives me following output:
[ { _id: { year: 2015, month: 11 }, count: 2 } ]

Now I want to check year also, so I am trying this:
    Offer.aggregate([
    {
        $project: {
            myyear: {$year: "$ending_date"}
        }
    },
    {
        $match: {
            carer_id : req.params.carer_id,
            status : 3,
            $myyear : "2015"
        }
    },
    {
        $group : {
            _id : { year: { $year : "$ending_date" }, month: { $month : "$ending_date" }},
            count : { $sum : 1 }
        }
    }],
    function (err, res)
    { if (err) ; // TODO handle error
         console.log(res);
    });

which gives me following output:
 []

as you can see, _id has 2015 as a year, so when I match year it should be come in array. But I am getting null array. Why this?
Is there any other way to match only year form whole datetime?
Here is the sample data
{
    "_id": {
        "$oid": "56348e7938b1ab3c382d3363"
    },
    "carer_id": "55e6f647f081105c299bb45d",
    "user_id": "55f000a2878075c416ff9879",
    "starting_date": {
        "$date": "2015-10-15T05:41:00.000Z"
    },
    "ending_date": {
        "$date": "2015-11-19T10:03:00.000Z"
    },
    "amount": "850",
    "total_days": "25",
    "status": 3,
    "is_confirm": false,
    "__v": 0
}
{
    "_id": {
        "$oid": "563b5747d6e0a50300a1059a"
    },
    "carer_id": "55e6f647f081105c299bb45d",
    "user_id": "55f000a2878075c416ff9879",
    "starting_date": {
        "$date": "2015-11-06T04:40:00.000Z"
    },
    "ending_date": {
        "$date": "2015-11-16T04:40:00.000Z"
    },
    "amount": "25",
    "total_days": "10",
    "status": 3,
    "is_confirm": false,
    "__v": 0
}

A: You forgot to project the fields that you're using in $match and $group later on. For a quick fix, use this query instead:
Offer.aggregate([
{
    $project: {
        myyear: { $year: "$ending_date" },
        carer_id: 1,
        status: 1,
        ending_date: 1
    }
},
{
    $match: {
        carer_id: req.params.carer_id,
        myyear: 2015,
        status: 3
    }
},
{
    $group: {
        _id: {
            year: { $year: "$ending_date" },
            month: { $month: "$ending_date" }
        },
        count: { $sum: 1 }
    }
}],
function (err, res)
{
    if (err) {} // TODO handle error
    console.log(res);
});

That said, Blakes Seven explained how to make a better query in her answer. I think you should try and use her approach instead.

A: You are doing so many things wrong here, that it really warrants an explanation so hopefully you learn something.
Its a Pipeline

It's the most basic concept but the one people do not pick up on the most often ( and even after continued use ) that the aggregation "pipeline" is just exactly that, being "piped" processes that feed input into the each stage as it goes along. Think "unix pipe" |:
ps -ef | grep mongo | tee out.txt

You've seen something similar before no doubt, and it's the basic concept that output from the first thing goes to the next thing and then that manipulates to give input to the next thing and so on.
So heres the basic problem with what you are asking:
    {
        $project: {
            myyear: {$year: "$ending_date"}
        }
    },
    {
        $match: {
            carer_id : req.params.carer_id,
            status : 3,
            $myyear : "2015"
        }
    },

Consider what $project does here. You specify fields you want in the output and it "spits them out", and possibly with manipulation. Does it output these fields in "addition" the the fields in the document? No It does not. Only what you ask to come out actually comes out and can be used in the following pipeline stage(s).
The $match here essentially asks for fields that are no longer present, because you only asked for one thing in the output. The same problem occurs further down as again you ask for fields you removed earlier and there simply is nothing to reference, but also everything was already removed by a $match that could not match anything.
Also, that is not how field projections work as you have entered
So just use a range for the date

        { "$match": {
            "carer_id" : req.params.carer_id,
            "status" : 3,
            "ending_date": {
                "$gte": new Date("2015-01-01"),
                "$lt": new Date("2016-01-01")
            }
        }},
        { "$group": {
            "_id": {
                "year": { "$year": "$ending_date" },
                "month": { "$month": "$ending_date" }
            },
            "count": { "$sum": 1 }
        }}

Why? Because it just makes sense. If you want to match the "year" then supply the date range for the whole year. We could play silliness with $redact to match on the extracted year value, but that is just wasted processing time.
Doing this way is the fastest to process and can actually use an index to process faster. So don't otherthink the problem and just ask for the date range you want.

A: If you want your aggregation to work you have to use $addFields instead of $project in order to keep status and carer_id in the object you pass to the $match
{
        $addFields: {
            myyear: {$year: "$ending_date"}
        }
    },
    {
        $match: {
            carer_id : req.params.carer_id,
            status : 3,
            $myyear : "2015"
        }
    },