text:
Q: JQuery: Open/Close Menu, Opens but doesn't close I'm trying to do a menu that hides on the left side and when we click on the button it opens or closes. I have the following code but the menu just opens, the code for closing isn't working, someone have a clue about what I did wrong?

var menu = function() {

  /* Open Menu*/

  $('.js_open_seta').click(function() {
    $('.js_menu').animate({
      left: "0px"
    }, 200);

    $(".js_open_seta").addClass("js_close_seta");
    $(".js_open_seta").removeClass("js_open_seta");

  });

  /* Close Menu*/

  $('.js_close_seta').click(function() {
    $('.js_menu').animate({
      left: "-240px"
    }, 200);

    $(".js_close_seta").addClass("js_open_seta");
    $(".js_close_seta").removeClass("js_close_seta");

  });

};

$(document).ready(menu);
body{
 background: url("imagens/exp.jpg");
 background-repeat: no-repeat;
 background-size: 1280px 800px;
 padding: 0;
 margin: 0;
 border: 0;
}

.js_menu{
 background: #4d4d4d;
 top: 0px;
 left: -240px;
 position: fixed;
   width: 310px;
 height: 100%;
 text-align: center;
 font-family: 'Lato', sans-serif;
 color: #ffffff;
 z-index: 50;
 padding: 0;
 margin: 0;
 border: 0;
}

#js_exp, #js_open{
 float: left;
 background:  #4d4d4d;
 height: 100%;
}

#js_exp{
 width: 240px;
}

#js_open{
 border-left: #ff0000;
 width: 70px;
 text-align: center;
 vertical-align: middle;
}

#js_seta{
 margin-top: 325px;
 width: 70px;
 height: 70px;
}
        <link href='http://fonts.googleapis.com/css?family=Lato:400,700' rel='stylesheet' type='text/css'>

    SMPC
    NGC Informática(2015)
    NGC Informática (2015-2016)

A:     var menu = function() {

    $('#js_seta').click(function() {

    var check = $("#js_seta").hasClass("js_open_seta");

        if(check) {
            $('.js_menu').animate({
                left: "0px"
            }, 200);

            $(".js_open_seta").addClass("js_close_seta");
            $(".js_open_seta").removeClass("js_open_seta");

        } else {
            $('.js_menu').animate({
                left: "-240px"
            }, 200);

            $(".js_close_seta").addClass("js_open_seta");
            $(".js_close_seta").removeClass("js_close_seta");

        }

    });

};

$(document).ready(menu);

This works


text:
Q: Как написать функцию выводящую количество пробелов переданных в параметр? Как написать функцию, которая бы принимала в параметр число, и выводила количество пробелов этого числа?
Например: space (3); и выводится 3 пробела.
Я пробовал решить эту задачу с помощью цикла, но
выводился только один пробел.
Заранее спасибо!

A: Если ориентироваться на современные браузеры, то есть метод у строк
" ".repeat(n);

Если требуется поддержка древних браузеров, то
Array(n + 1).join(" ");

Но этот код вернёт строчку из функции, а вот куда вы собрались выводить не ясно.
Если в консоль, то все просто:
function space (n){
    console.log(" ". repeat (n));
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: RecyclerView onClickListener Doesn't Work I can't pass intent by clicking reckclerview onclickListener from adapter. When I clicked any item then application is stopped. Here is the Log Cat....
Process: com.example.ilias.materialdsgn, PID: 3685
java.lang.NullPointerException: Attempt to invoke virtual method
java.lang.String android.content.Context.getPackageName() on a null object reference
at android.content.ComponentName.<init>(ComponentName.java:128)
at android.content.Intent.<init>(Intent.java:4449)
at com.example.ilias.materialdsgn.VivzAdapter$MyViewHolder.onClick(VivzAdapter.java:72)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)`

and my Adapter code is...
public class VivzAdapter extends RecyclerView.Adapter<VivzAdapter.MyViewHolder>{

private LayoutInflater infater;
List<Information> data= Collections.emptyList();
private Context context;

public VivzAdapter(Context context, List<Information> data){
    infater=LayoutInflater.from(context);
    this.data=data;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view= infater.inflate(R.layout.custom_row, parent,false);
    MyViewHolder viewHolder=new MyViewHolder(view);
    return viewHolder;
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    Information current=data.get(position);
    holder.title.setText(current.iconName);
    holder.icon.setImageResource(current.iconId);

}

@Override
public int getItemCount() {
    return data.size();
}
public void delete(int position){
    data.remove(position);
    notifyItemRemoved(position);
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
    TextView title;
    ImageView icon;

    public MyViewHolder(View itemView) {
        super(itemView);
        itemView.setOnClickListener(this);
        title= (TextView) itemView.findViewById(R.id.listText);
        icon= (ImageView) itemView.findViewById(R.id.listIcon);
        icon.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        context.startActivity(new Intent(context, SubActivity.class));
    }
}

}

A: try editing this (paste this.context = context;):
public VivzAdapter(Context context, List<Information> data){
    this.context = context;
    infater=LayoutInflater.from(context);
    this.data=data;
}


text:
Q: Leaflet: Smooth lines between points without control points? Goal
I want to connect points using a polycurve or curved lines in Leaflet in a scalable way. If possible, without defining control points.
Approach
I'm using the Leaflet.curve plugin which offers quadratic and cubic bezier curves. I took a screenshot and created a jsfiddle (https://jsfiddle.net/p1zx5k73/28/) of only a limited set of connected points. The js code is further below.

Problem
My approach is not scalable with the Leaflet-curve plugin since I need to create a control point for all inter-points connections each.
lng = Point_One[0] + 0.5 + ((Point_Two[0] - Point_One[0]) / 2)
lat = Point_One[1] + 0.5 + ((Point_Two[1] - Point_One[1]) / 2)
...

I can automate getting the mid-point between two points and its direction (+/-), but I don't know how to automate offsetting the control point. The length between points varies. In practice, I have hardcoded the size of the offset. If you look closely, you can see that the curves are not equally distributed between points which would also be nice.
Questions

*

*Are there any good frameworks to draw smooth lines between points in
Leaflet?

I have read about Raphael, but it no longer seems to be available(?).

*Is there a way to optimize the way I use the Leaflet-curve plugin?

I assume I could have bigger/smaller offsets dependent on inter-points distance.

*Are there any QGIS plugins to create splines/smooth lines between points (in a dataset) and export these as a geojson layer?

I have no experience with, but read about the Spline and CadTools Plugins.
var Mapnik = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 19,
    attribution: '© OpenStreetMap'
});

var mymap = L.map('mapid', {
    layers: [Mapnik]
}).setView([49.165804, 39.517246], 4);

var Warsaw = [52.233333, 21.016667];
var Brest = [52.133333, 23.666667];
var Moscow = [55.75, 37.616667];
var Yekaterinburg = [56.833333, 60.583333];

var curved_line = L.curve(['M', Warsaw,
    'Q', [Warsaw[0] + 0.5 + ((Brest[0] - Warsaw[0]) / 2), Warsaw[1] + 0.5 + ((Brest[1] - Warsaw[1]) / 2)],
    Brest,
    [Brest[0] - 3.5 + ((Moscow[0] - Brest[0]) / 2), Brest[1] - 3.5 + ((Moscow[1] - Brest[1]) / 2)],
    Moscow,
    [Moscow[0] + 3.5 + ((Yekaterinburg[0] - Moscow[0]) / 2), Moscow[1] + 3.5 + ((Yekaterinburg[1] - Moscow[1]) / 2)],
    Yekaterinburg,
      ], {
  fillColor: 'green',
  weight: 4,
  opacity: 1,
  color: 'green',
  fillOpacity: 1,
  lineCap: 'round'
});

var straight_line = L.curve(['M', Warsaw,
'L', Brest, Moscow, Yekaterinburg, {
    fillColor: 'blue',
    weight: 2,
    opacity: 0.5,
    color: 'blue',
    fillOpacity: 0.5,
    lineCap: 'round'
}]);

mymap.addLayer(straight_line);
mymap.addLayer(curved_line);


text:
Q: JOptionPane in JavaFX? Can we use a JOptionPane in JavaFX? If yes, then how?
Is there a way that I can popup a message via a dialog box in a JavaFX program as I can do through javax.swing with JOptionPane.showMessageDialog()? If not, is there any other alternative?

A: From Cay Horstmann's new book Java SE8 for the Really Impatient (Pearson 2014), s. 4.2, he outlines using

Label message = new Label("Cay's message");

as part of his class which extends the Application Class. He describes using a setScene as follows:

stage.setScene(new Scene(message));

The result is a dialog box with the message.
Alternatively, the JavaFX 8 API describes Class SwingNode, which,

is used to embed a Swing content into a JavaFX application


text:
Q: Apache not calling the Smart HTTP CGI I'm setting up a git server with git-http-backend and Smart HTTP but Apache doesn't seem to be calling the Smart HTTP CGI:
$ curl http://localhost/repo/myproject.git/info/refs?service=git-receive-pack
2ddf56592a0f55456b8c42dc9f2cb9289f083f53        refs/heads/1.0.x
55079bb13d9af8a9164ad0d24b654cbfe119bc7e        refs/heads/master

Here's my config:
<VirtualHost *:8000>
  ServerName localhost
  DocumentRoot /opt/local/apache2/htdocs/repo

  SetEnv GIT_PROJECT_ROOT /opt/local/apache2/htdocs/repo
  SetEnv GIT_HTTP_EXPORT_ALL

  ScriptAlias /repo/ /usr/libexec/git-core/git-http-backend/
  AliasMatch ^/repo/(.*/objects/[0-9a-f]{2}/[0-9a-f]{38})$          /opt/local/apache2/htdocs/repo/$1
  AliasMatch ^/repo/(.*/objects/pack/pack-[0-9a-f]{40}.(pack|idx))$ /opt/local/apache2/htdocs/repo/$1

  ScriptAliasMatch \
    "(?x)^/repo/(.*/(HEAD | \
    info/refs | \
    objects/(info/[^/]+ | \
        [0-9a-f]{2}/[0-9a-f]{38} | \
        pack/pack-[0-9a-f]{40}\.(pack|idx)) | \
    git-(upload|receive)-pack))$" \
    /usr/libexec/git-core/git-http-backend/$1

  <Directory "/usr/libexec/git-core/">
    Options +ExecCGI
    Allow From All
  </Directory>

  <LocationMatch "^/repo/.*/git-receive-pack$">
    AuthType Basic
    AuthName "Git"
    Require valid-user
    AuthUserFile /etc/apache2/other/htpasswd
  </LocationMatch>
</VirtualHost>

Here's the output of httpd -S:
VirtualHost configuration:
wildcard NameVirtualHosts and _default_ servers:
*:8000                 localhost (/private/etc/apache2/other/gitrepo.conf:1)
Syntax OK

And I have got http.receivepack enabled (= true) in my server-side git config:
[http]
  receivepack = true

Any ideas of what I should do?

A: Well, since that's in the virtualhost for :8000, I would presume you'd want to curl http:// localhost:8000/, not http:// localhost/. Beyond that, just make sure mod_cgi is enabled.


text:
Q: javascript type issue: Uncaught TypeError: Object 0 has no method 'draw' Just experimenting with JS + canvas and i seem to have hit a wall.
the "aim" of my minimal application is to click at any random place on the canvas, press the draw button and squares draw where you clicked.
coming from an OO background... i (tried) to use OO, which in js i dont fully have the grasp of.
but basically i have a custom Square object
function Square(l, w, x, y) {

    this.length = l;
    this.width  = w;
    this.posx   = x - l/2;
    this.posy   = y - w/2;

    //test
    //ctx.fillStyle = "rgb(20,0,0)";
    //ctx.fillRect(this.posx,this.posy,this.length,this.width);

    this.draw = function() {

        ctx.fillStyle = "rgb(20,0,0)";
        ctx.fillRect(this.posx,this.posy,this.length,this.width);

    }
}

which i add to an array every time the user clicks...
here is the event handler for when i click on the canvas.
function addTo(evt) {

    pos = getMousePos(evt);
    var sq = new Square(50, 50, pos.x, pos.y);
    list.push(sq);

    output.innerText = "("+sq.posx+","+sq.posy+")";
}

and here is where i (attempt) to draw the squares.
function renderStack() {

    //alert(list);
    canvas.width = canvas.width;
    for(var o in list) o.draw();

}

and this is the error:
Uncaught TypeError: Object 0 has no method 'draw'

i get a similar error trying to access the variables for that object.
It seems that after i add them to the list js forgets about what type they are? - because when i print the array it is full of [Object object]'s
thanks.

A: for ... in ... gives you an object's keys and not its contents.
So on an Array you will receive both the indices of the stored elements and the names of any other enumerable properties.
Instead, you should use:
for (var i = 0; i < list.length; ++i) {
     list[i].draw();
}

A: for(var o in list)

o is the index (or property) of array. You will access what's stored at that index by list[o].
But for the arrays, it is better to use for loop as shown by Alnitak than for-in.
Update:
For-in is to be used when you need to loop through all the properties. Since array is an object it has indices and properties. So for-in will iterate through all the indices and properties. for-in is better for objects.
e.g.
var obj = { p1: 1, p2: 2};

for(var prop in obj) {
   //...
}


text:
Q: Yii2 filter Sum data in GridView I'm trying display and filter data which I got via SQL SUM operator.
I have 2 table employee and department. Table employee contains department_id filed and salary filed. I need display all department and total SUM salary for every department.
I followed this guide, but GridView does not  display any data.
Here is action:
public function actionIndex()
{
    $searchModel = new DepartmentFrontendSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    return $this->render('index',
        [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,

        ]
    );
}

Model:
class DepartmentFrontendSearch extends DepartmentFrontend

public $employee_count;
public $salary;

public function rules() {
    return [

        [['employee_count','salary','name'], 'safe']
    ];
}

public function search($params) {

    $query = DepartmentFrontend::find();
    $subQuery = Employee::find()
        ->select('department_id, SUM(salary) as salary_amount')
        ->groupBy('department_id');
    $query->leftJoin(['salarySum' => $subQuery], 'salarySum.department_id = id');

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);
    $dataProvider->setSort([
        'attributes' => [
            'name',
            'salary'
        ]
    ]);

    $this->load($params);

    if (!$this->validate()) {
        return $dataProvider;
    }

    $query->andFilterWhere(['like', 'name', $this->name]);
    $query->andWhere(['salarySum.salary_amount' => $this->salary]);
    return $dataProvider;
}

GRID:
   echo GridView::widget([
   'dataProvider' => $dataProvider,
   'filterModel' => $searchModel,
   'columns' => [
       ['class' => 'yii\grid\SerialColumn'],
       'salary_amount',
       'employee_count',
       'name',

   ],

]);
So, can anybody tell me what I did wrong?

A: If You need  a filter for the alias salary_amount  you should add a specific var for this (do the fact salary_amount is an alias for sum(salary) the var $salary is not useful)
public $employee_count;
public $salary;
public $salary_amount;

otherwise use salary as alias too
the  in your filter you are using
$query->andWhere(['salarySum.salary_amount' => $this->salary]);

But salary_amount is the result of an aggregation so you should use      having(SUM(salary) = $this->salary_amount)
 $query->having('SUM(salary) = ' . $this->salary_amount);


text:
Q: How can I make that the object will scale automatic up/down nonstop? Now I'm using the F key to make it scale up or down.
But I want to add another method for example AutoScaling that when calling it in Update it will scale up first once finished scaling up it will scale down and then up again and so no nonstop.
The Scaling script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Scaling : UnityEngine.MonoBehaviour
{
    public GameObject objectToScale;
    public GameObject lookAtTarget;
    public float duration = 1f;
    public Vector3 minSize;
    public Vector3 maxSize;
    public bool scaleUp = false;
    public Coroutine scaleCoroutine;
    public bool scalingHasFinished = false;

    public void Inits()
    {
        scalingHasFinished = false;
        objectToScale.transform.localScale = minSize;
    }

    public IEnumerator scaleOverTime(GameObject targetObj, Vector3 toScale, float duration, Camera objectToScaleCamera)
    {
        float counter = 0;
        Vector3 startScaleSize = targetObj.transform.localScale;

        while (counter < duration)
        {
            counter += Time.deltaTime;
            targetObj.transform.localScale = Vector3.Lerp(startScaleSize, toScale, counter / duration);

            if (scaleUp)
            {
                var lookPos = lookAtTarget.transform.position - objectToScale.transform.position;
                lookPos.y = 0;
                var rotation = Quaternion.LookRotation(lookPos);
                objectToScale.transform.rotation = Quaternion.Slerp(objectToScale.transform.rotation, rotation, counter / duration);
            }
            else
            {
                var lookPos = lookAtTarget.transform.position - objectToScale.transform.position;
                lookPos.y = 0;
                var rotation = Quaternion.LookRotation(objectToScaleCamera.transform.forward);//SwitchCameras.GetCurrentCamera().transform.forward);//Camera.main.transform.forward);
                objectToScale.transform.rotation = Quaternion.Slerp(objectToScale.transform.rotation, rotation, counter / duration);
            }

            yield return null;
        }

        scalingHasFinished = true;
    }

    public IEnumerator scaleOverTime(GameObject targetObj, Vector3 toScale, float duration, float rotationSpeed)
    {
        float counter = 0;
        Vector3 startScaleSize = targetObj.transform.localScale;

        while (counter < duration)
        {
            counter += Time.deltaTime;
            targetObj.transform.localScale = Vector3.Lerp(startScaleSize, toScale, counter / duration);

            targetObj.transform.Rotate(Vector3.up * rotationSpeed * Time.deltaTime, Space.Self);

            yield return null;
        }
    }
}

And the script that use the scaling :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectsManipulation : UnityEngine.MonoBehaviour
{
    //Camera
    public Camera playerCamera;

    //Scaling
    private bool canScale = true;
    private Scaling scaling;

    //Lights
    public DimLights dimlights;
    private Coroutine lightCoroutine;

    //Colors
    private Colors colors;

    //Rotating
    private bool stopRotation = false;
    private Rotating rotating;

    private void Start()
    {
        scaling = GetComponent<Scaling>();
        scaling.Inits();

        colors = GetComponent<Colors>();
        colors.Start();

        rotating = GetComponent<Rotating>();
    }

    // Use this for initialization
    void Update()
    {
        if (playerCamera != null)
        {
            //Scaling
            if (Input.GetKeyDown(KeyCode.F) && canScale == true)
            {
                Scaling();
            }
        }

        //Rotate
        if (Input.GetKey(KeyCode.R) && !scaling.scaleUp)
        {
            rotating.x += Time.deltaTime * rotating.rotationSpeed;
            scaling.objectToScale.transform.localRotation = Quaternion.Euler(0, 0, rotating.x);
            rotating.keyPressed = true;
        }
        if (Input.GetKeyUp(KeyCode.R))
        {
            rotating.keyPressed = false;
        }

        if (!rotating.keyPressed && !scaling.scaleUp && rotating.rotateBack == false
            && DetectInteractable.detected == false)
        {
            scaling.objectToScale.transform.rotation = Quaternion.LookRotation(playerCamera.transform.forward);
        }

        if (DetectInteractable.detected == true && !scaling.scaleUp && stopRotation == false)
        {
            rotating.x += Time.deltaTime * rotating.rotationSpeed;
            scaling.objectToScale.transform.localRotation = Quaternion.Euler(0, 0, rotating.x);
        }
    }

    public void Scaling()
    {
        //Flip the scale direction when F key is pressed
        scaling.scaleUp = !scaling.scaleUp;

        //Stop old coroutine
        if (scaling.scaleCoroutine != null)
            StopCoroutine(scaling.scaleCoroutine);

        if (lightCoroutine != null)
            StopCoroutine(lightCoroutine);

        //Scale  up
        if (scaling.scaleUp)
        {
            //Start new coroutine and scale up within 5 seconds and return the coroutine reference
            rotating.rotateBack = false;
            scaling.scaleCoroutine = StartCoroutine(scaling.scaleOverTime(scaling.objectToScale, scaling.maxSize, scaling.duration, playerCamera));
            if (dimlights.lightsOnOff == false)
                lightCoroutine = StartCoroutine(dimlights.dimLightOverTime(1, scaling.duration));
        }

        //Scale Down
        else
        {
            //Start new coroutine and scale up within 5 seconds and return the coroutine reference
            rotating.rotateBack = true;
            scaling.scaleCoroutine = StartCoroutine(scaling.scaleOverTime(scaling.objectToScale, scaling.minSize, scaling.duration, playerCamera));
            if (dimlights.lightsOnOff == false)
                lightCoroutine = StartCoroutine(dimlights.dimLightOverTime(0, scaling.duration)); ;
        }
    }
}

And in third script I want to call a method that will be in the ObjectsManipulation script maybe the same method Scaling maybe he will get a bool and if the bool is true make it scaling up/down automatic if it's not true make it use a key.
This is the script for testing the Scaling :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScalingTest : MonoBehaviour
{
    ObjectsManipulation om;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        om.Scaling();
    }
}

For example in the Update maybe to do : om.Scaling(false); for using the F key and om.Scaling(true); for automatic.
Update of what I have tried :
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;

public class ConversationTrigger : MonoBehaviour
{
    public List<Conversation> conversations = new List<Conversation>();

    [HideInInspector]
    public int dialogueIndex;

    [HideInInspector]
    public int conversationIndex;

    private bool triggered = false;
    private bool activateButton = false;
    private DialogueManager dialoguemanager;
    private bool startDialogue = false;

    private void Start()
    {
        dialogueIndex = 0;
        dialoguemanager = FindObjectOfType<DialogueManager>();
    }

    public IEnumerator PlayConversation(int index)
    {
        this.conversationIndex = index;

        if (conversations.Count > 0 &&
            conversations[index].Dialogues.Count > 0)
        {
            for (int i = 0; i < conversations[index].Dialogues.Count; i++)
            {
                if (triggered == false)
                {
                    if (dialoguemanager != null)
                    {
                        dialoguemanager.StartDialogue(conversations[index].Dialogues[i]);
                    }

                    while (DialogueManager.dialogueEnded == false)
                    {
                        yield return null;
                    }
                }
            }
        }
    }

    public void SaveConversations()
    {
        string jsonTransform = JsonHelper.ToJson(conversations.ToArray(), true);
        File.WriteAllText(@"d:\json.txt", jsonTransform);
    }

    public void LoadConversations()
    {
        string jsonTransform = File.ReadAllText(@"d:\json.txt");
        conversations.Clear();
        conversations.AddRange(JsonHelper.FromJson<Conversation>(jsonTransform));
    }
}

And using it like this :
StartCoroutine(conversationTrigger.PlayConversation(0));

Where conversationTrigger is public ConversationTrigger conversationTrigger;
But it's not working good at all. It's starting the conversation index 0 but then play only the first dialogue sentences twice and then never continue to the next dialogue there are two dialogues in this case. And then it stop.
It should play all the dialogues of the current conversation.
Something in the PlayConversation method is wrong.

A: I'm sorry to say your post is long and contains many redundant codes, so I haven't carefully read it, this is a simple reference about making a zoom animation by script.
float minScale; // Minimum scale value
float maxScale; // Maximum scale value
Transform target; // Target to scale

void Update()
{
    float scale = Mathf.PingPong(Time.time, maxScale - minScale) + minScale;
    target.localScale = new Vector3(scale, scale, scale);
}


text:
Q: Azure Application Insights logging for Python Application - Set Exception properties explicitly I am trying to send Exceptions from my Python application running in Azure App service to the designated Azure Application Insights instance. I am using OpenCensus python library for this purpose.
The basic logging and exception are successfully reaching to App Insight.
In addition to this i would like to know if there is a way where I can configure the Exception attributes like: problemId or any other attributes explicitly to reflect specific value for easier alerting (like send email to specific group based on problemId).
Any suggestion/pointers would be super helpful

A: You can add custom properties to your log messages (not only exception, but all other log types too like trace, event etc.) in the extra keyword argument by using the custom_dimensions field. These properties appear as key-value pairs in customDimensions in Azure Monitor. Then you can query, see or configure alert based on that.
For this feature to work, you need to pass a dictionary to the custom_dimensions field. If you pass arguments of any other type, the logger ignores them.
NOTE: OpenCensus Python doesn't automatically track and send exception telemetry. They're sent through AzureLogHandler by using exceptions through the Python logging library. You can add custom properties just like with normal logging.
import logging

from opencensus.ext.azure.log_exporter import AzureLogHandler

logger = logging.getLogger(__name__)
# TODO: replace the all-zero GUID with your instrumentation key.
logger.addHandler(AzureLogHandler(
    connection_string='InstrumentationKey=00000000-0000-0000-0000-000000000000')
)

properties = {'custom_dimensions': {'key_1': 'value_1', 'key_2': 'value_2'}}

# Use properties in exception logs
try:
    result = 1 / 0  # generate a ZeroDivisionError
except Exception:
    logger.exception('Captured an exception.', extra=properties)

You can view customDimentions in Azure Portal like below (just example, not actual as per above code):

You can see the same in Kusto Query like below:

And you can query on those and configure alerts based on that (below image shows traces, for exceptions, it would be exceptions table):


text:
Q: Windows 10: Poor Performance for Playing Game & Screen Capture I hope this is the best StackExchange site to ask questions about optimizing system performance. If not, I apologize, & please direct me to the appropriate site.
My current system is one of the best I have ever had. It is not the best gaming system, but I am not running high end games. The issue comes when I record/capture videos of some games that I play. I end up with choppy/jumpy/jittery videos. As it happens with multiple games & recording software, I am concluding that there is some issue with the system's performance, as opposed to it being the fault of a specific app.
My system is an HP Pavilion 24-b217c. I am running Windows 10 64-bit:

It has two graphics chips: Intel(R) HD Graphics 630 & NVIDIA GeForce 930MX. The Intel chip uses 1GB of system memory & the NVIDIA chip has 2GB of its own dedicated memory.
GPUs info:

By default, apps use the Intel chip. But I can change that for each individual app in graphics settings: "Power saving" uses the Intel. Setting to "High performance" tells the system to use the NVIDIA chip for the app when it is launched:

I have also disabled most system visual effects settings:

The software that I am currently using to capture my screen is Captura. I have also tried OBS Studio & the command line FFmpeg with the same or similar results (Note: all these apps are FFmpeg/libav-based). I have also tested the built-in Xbox Game Bar that comes with Windows 10. It seems to suffer less from jitter, but the game itself suffers & is captured in the video, albeit less often. Also, I haven't found any settings in the Xbox Game Bar to change capture quality or resolution, which I absolutely want.
The games that I am playing are 2D platformers, such as Mega Man Unlimited, Mega Man Rock Force, Mega Man Rock N Roll, & Street Fighter X Megaman. Changing which GPU is used does not appear to change performance for any of these games.
Also, I am running COMODO Internet Security. I have tried shutting this off when I record, but it doesn't seem to make a differenece.
The issue isn't consistent. At times my video will be choppy, & other times not. I am wondering if it is being caused by I/O speed, either the recording software writing to the hard drive or some other background application. But I think perhaps it is not directly related to the recording software as I sometimes get choppy gameplay even if I am not recording. It does appear that after restarting my system, I do get a bit better performance for a period.
According to the task manager, about 38% of my CPU is being used, 49% of system memory, 13% of the Intel GPU, & 22% of the NVIDIA GeForce GPU during gameplay & recording. That is with a browser window with multiple tabs & a text editor open (which usually are not when I am recording) & no other foreground apps. So those system resources seem to be okay:

I'm curious if the issue I am having is specific to my system or if there are any known issues with Windows 10 performance that I am unaware of & things I can do to try & fix it. I am also open to screen capture software suggestions. I prefer open source solutions but am willing to try out others. It appears that most of the actively developed open source screen capturing software that I have found is based on FFmpeg/libav.
--- Edit ---
I should note that on older systems with less resources, I haven't had near as many problems capturing gameplay in the past as I do with this one.


text:
Q: use server NIC on an pc instead of pc NIC? I want to know if I can use a "server NIC" which is PCIe (like HP server NICs) and install that on my desktop pc PCIe slot and have more features and also more ethernet ports to work with? is that possible and work???
if anyone has that experience and could help?
thank you.

A: Obvious hardware requirements aside:
This depends on whether there is a driver for your PCs operating system.
If not compatible you could try to force install a driver by editing its .inf file.
I once successfully used this guide, although this is the other way around (client hardware for server OS).


text:
Q: look like css wont reload but not all the times when I visit the page most of the times it is ok .
but some times when I keep pressing refresh or  for example if I am in a another page and then came back to that page via a link , page wont be shown right ,look likes it could not load the CSS file .
I delete the CSS and then I reload the page and I saw page is just like those times that I mention above , so I am pretty sure it is about page's CSS .
Next when page is disorder I click on refresh and page gets right
another thing I should add is ,always I have this problem with large screens browsers like in laptop or pc but never experience this problem with tablet or phone and small devices
I design that web site with Nice page so every page has 2 CSS (nicepage.css and page.css)files ,and 2
JS files
you can visit the page here :
https://www.drhosseinchi.ir/docs/first/
so what can I do ?

A: Looks like you are a beginner to web development. You need to read more about "cache". Browsers usually cache files such as css to save user's data. Try renaming your css file or make it internal by moving it to page header section and everything should work.


text:
Q: integrating R dataframes and performing operations based on column values I'm pretty new to R and so am having some difficulty with dataframes. I have two R dataframes that have different information and am wondering if there is a way to integrate one into the other in a meaningful way. I could not find a simple solution searching around, so I am hoping someone can help or give suggestions.
Specifically, I have an example dataframe as follows:
Scaffold  Start  Stop
E1        1      4
E1        5      12
E2        2      10
E3        1      10
E4        2      13

It represents start and stop sites for particular genes along a scaffold, with each row representing a specific gene.
Now I have a second output dataframe that reports FST stats for each individual site on a given scaffold:
Scaffold Site  FST
E1       1     0.1
E1       2     0.5
E1       3     0.6
E1       4     0.6
E1       5     0.8
E1       6     0.6
E1       7     0.4
E1       8     0.3
E2       2     0.2
E2       6     0.3
E2       7     0.5
E2       8     0.5
E2       9     0.6
E3       3     0.7
E3       5     0.7
E3       7     0.8
E4       2     0.8
E4       5     0.6
E4       6     0.5
E4       9     0.2

What I want to do is take the data from the second frame and integrate it into the first by calculating the average and max FST values for those intervals per row, to end up with something like this:
Scaffold  Start  Stop  Average.FST  Max.FST
E1        1      4     0.45         0.6
E1        5      12    0.53         0.8
E2        2      10    0.42         0.6
E3        1      10    0.73         0.8
E4        2      13    0.53         0.8

final <- data.frame("Scaffold" = c("E1","E1","E2","E3","E4"),
                    "Start" = c(1,5,2,1,2),
                    "Stop" =  c(4,12,10,10,13),
                    "Average FST" = c(0.45,0.53,0.42,0.73,0.53),
                    "Max FST" = c(0.6,0.8,0.6,0.8,0.8))

Thus, it's very similar to the first dataframe but integrates information from the second. Is there anyway to do this efficiently in R?

A: Here is a simple solution using dplyr;
First I join to get all information related to each Scaffold from the second dataframe then using mutate I choose only those relevant (within the period) and then I get the average and maximum of the values.
library(dplyr)

df1 <-
  data.frame(
    Scaffold = c("E1", "E1", "E2", "E3", "E4"),
    Start = c(1, 5, 2, 1, 2),
    Stop = c(4, 12, 10, 10, 13)
  )

df2 <-
  data.frame(
    Scaffold = c("E1", "E1", "E1", "E1", "E1", "E1", "E1", "E1", "E2",
                 "E2", "E2", "E2", "E2", "E3", "E3", "E3", "E4", "E4", "E4", "E4"),
    Site = c(1, 2, 3, 4, 5, 6, 7, 8, 2, 6, 7, 8, 9, 3, 5, 7, 2, 5, 6, 9),
    FST = c(0.1, 0.5, 0.6, 0.6, 0.8, 0.6, 0.4, 0.3, 0.2, 0.3, 0.5, 0.5,
            0.6, 0.7, 0.7, 0.8, 0.8, 0.6, 0.5, 0.2)
  )

result <-
  df1 %>%
  inner_join(df2, by = c("Scaffold")) %>%
  mutate(FST = ifelse(Site >= Start & Site <= Stop, FST, NA)) %>%
  group_by(Scaffold, Start, Stop) %>%
  summarize(Average.FST = round(mean(FST, na.rm = TRUE), 2),
            Max.FST = max(FST, na.rm = TRUE))

result

# # A tibble: 5 x 5
# # Groups:   Scaffold, Start [5]
# Scaffold Start  Stop Average.FST Max.FST
# <fct>    <dbl> <dbl>       <dbl>   <dbl>
#   E1           1     4        0.45     0.6
#   E1           5    12        0.52     0.8
#   E2           2    10        0.42     0.6
#   E3           1    10        0.73     0.8
#   E4           2    13        0.52     0.8

A: We can use a join in data.table with by as .EACHI
library(data.table)
out <- setDT(df2)[df1, .(AverageFST = mean(FST), MaxFST = max(FST)),
      on = .(Scaffold, Site >= Start, Site <= Stop), by = .EACHI]
setnames(out, 2:3, c('Start', 'Stop'))[]
#  Scaffold Start Stop AverageFST MaxFST
#1:       E1     1    4  0.4500000    0.6
#2:       E1     5   12  0.5250000    0.8
#3:       E2     2   10  0.4200000    0.6
#4:       E3     1   10  0.7333333    0.8
#5:       E4     2   13  0.5250000    0.8

A: In base R, we can first merge then subset and finally use aggregate to get required information.
aggregate(FST~Scaffold+Start+Stop,
        subset(merge(df1, df2), Site >= Start & Site <= Stop),
        function(x) c(average = mean(x, na.rm = TRUE), max = max(x, na.rm = TRUE)))

#  Scaffold Start Stop FST.average FST.max
#1       E1     1    4        0.45    0.60
#2       E3     1   10        0.73    0.80
#3       E2     2   10        0.42    0.60
#4       E1     5   12        0.53    0.80
#5       E4     2   13        0.53    0.80

data
df1 <- structure(list(Scaffold = structure(c(1L, 1L, 2L, 3L, 4L), .Label = c("E1",
"E2", "E3", "E4"), class = "factor"), Start = c(1, 5, 2, 1, 2
), Stop = c(4, 12, 10, 10, 13)), class = "data.frame", row.names = c(NA, -5L))

df2 <- structure(list(Scaffold = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L, 4L), .Label = c("E1",
"E2", "E3", "E4"), class = "factor"), Site = c(1, 2, 3, 4, 5,
6, 7, 8, 2, 6, 7, 8, 9, 3, 5, 7, 2, 5, 6, 9), FST = c(0.1, 0.5,
0.6, 0.6, 0.8, 0.6, 0.4, 0.3, 0.2, 0.3, 0.5, 0.5, 0.6, 0.7, 0.7,
0.8, 0.8, 0.6, 0.5, 0.2)), class = "data.frame", row.names = c(NA, -20L))


text:
Q: How to do nested tabs(sub tabs) using backbone controller and views? I am beginner in Backbone development and I am trying to develop a Lifecycle management using Backbone. The project contains four main tabs, with subtabs in every tab. I created the main tabs using controllers, models and views etc. I also added navigation slider
That is all working fine, but I am confused about how to load the sub tabs within a main tab. My main question is, where do I start the controller for the sub tabs? Is it from the initialize method of the main tab's controller?
Code Overview:
- Main controller loads the collection and models for each tab
- Main controller shows the view of each tab when the main tab is clicked
// Declare pages collection
var mainpages = new TST.Collections.Pages([ new SCL.Models.Page({
    id : 1,
    name : "Main Tab1",
    route : "!/tab1",
    _controller : TST.Controllers.Tab1
}), new SCL.Models.Page({
    id : 2,
    name : "Main Tab2",
    route : "!/tab2",
    _controller : TST.Controllers.Tab2
}) ], {
    current : 1
});

// show the main layout
var layout = new TST.Layouts.Main({
    collection : mainpages
});
this.options.region.show(layout);

// show the menu
var menu = new TST.Views.Nav({
    collection : mainpages
});
layout.menu.show(menu);

Regions are declared in Main layout.
And shows each tab on tab click using -> self.content.show(options.view, self.options.collection.goRight); where self = this
The controllers of each tab look like this
SCL.Routers.Tab1= Backbone.Marionette.AppRouter.extend({
    appRoutes : {
        "!/request" : "start"
    }
});

  SCL.Controllers.Tab1= TST.Framework.Controller.extend({
    initialize : function(options) {
        this.layout = new TST.Layouts.Tab1();
        this.router = new TST.Routers.Tab1({
            controller : this
        });
    },

    start : function() {
        app.vent.trigger("page:change", {
            view : this.layout
        });
    }
});

So now, How can I load a sub tabs under the Tab1??
Please share your ideas and help me... Thanks in advance!

A: Based on Derick Bailey's original article (http://lostechies.com/derickbailey/2012/04/05/composite-views-tree-structures-tables-and-more/), I've written a blog post on a similar problem here: http://davidsulc.com/blog/2013/02/03/tutorial-nested-views-using-backbone-marionettes-compositeview/
You should be able to apply the content from the blog post to solve your own challenge, since it's very similar in nature.


text:
Q: extracting the url/uri of the link after I load the HTML content in the web view using navigate function, and click on a link in HTML content I am not able to understand how to get the url of the link I am clicking on ?...I want to update the url in the address bar (text box) as I click on the link .. I even tried using this but still not getting the url
WebView1.LoadCompleted += new Windows.UI.Xaml.Navigation.LoadCompletedEventHandler(load_Completed);

private void load_Completed(object sender, NavigationEventArgs e)
{
   AddressBar.Text = WebView1.Source.AbsoluteUri;
}


text:
Q: Use Python __repr__() for 2D List Is there a way to make __repr__() return a 2d list so that it prints row by row in Python?
My attempt is below. I can't see how I can insert new lines, like in print("..", end="\n").
class Board:
    def __init__(self, rows = 6, cols=7, fill=0):
        self.rows = rows
        self.cold = cols
        self.symbol = fill
        self.board = [[fill] * cols for row in range(rows)]

    def __repr__(self):
        return str([self.board[i] for i in range(len(self.board))])

board = Board()
print(board)

A: You really shouldn't be using __repr__() for this use – let's call it .format() instead, maybe?
Either way, you'll want to generate lines out of the characters with no separator (''.join(...)), then join those lines with '\n':
def format(self):
    return '\n'.join([''.join(str(c) for c in row) for row in self.board])


text:
Q: iOS load a tableview depending on GPS position I have some records in a DB that, between other data, contains a city name.
I want to load in a tableview only the data where the city matches the user's city.
I have already used the reverse Geocoding to get the user's city:
[self.geoCoder reverseGeocodeLocation: location completionHandler:
 ^(NSArray *placemarks, NSError *error) {

     CLPlacemark *placemark = [placemarks objectAtIndex:0];
     country = [placemark.addressDictionary valueForKey:@"Country"];
     city = [placemark.addressDictionary valueForKey:@"City"];
     NSString *title = [NSString stringWithFormat:NSLocalizedString(@"You're in %@", nil),city];

     NSLog(@"%@", title);
     [locationController.locationManager stopUpdatingLocation];
 }];

The problem is that the city name is localized. For example: I live in Zaragoza, Spain and I've set a DB record containing the city "Zaragoza".
But my phone language is Italian and as a city name I get "Saragozza" that does not matches the field in the DB record.
Any idea on how to do this?
EDIT: Since I'm using Parse as a backend for this app, I've just found the method whereKey:nearGeoPoint:withinMiles in their API that will solve my problem. I've changed the DB record to be a "geopoint" instead of a city name and I'll load all the records within X miles from the user location.
Anyways, I will keep this question open because I'd like to know how to do it without using Parse's API.


text:
Q: SQL - Hard time building a "complex" request I've got three tables :

*

*conversations (contains private conversations)

*conversations-members - structure : convId | userId (contains all ids of members participating to a conversation so multiple people can talk together. One user participating to a conversation equals one row)

*users (users table, classic)

What I am trying to do is :
Users have friends. So, the user browsing my application can open a conversation from his friends' ids.
So, first, I want to look up in conversations-members if there is an existing conversation ONLY between user's Id and his friend's Id and then, pick up the conversation id in conversations table that conversations-members gave me.
Is it possible to do this in one request? If I have to do two requests, I don't even know how to build the first one (find the rows that contain user's Id and friend's Id that have conversation Id in common).
My first idea was to make a single conversations table which would also contain member's Id in the form of a string like "55,105,85,22" and then parse it to get an array, but I think the way I want to do it gives me more options and could be simpler if I manage to handle the SQL requests I need.

A: To find conversations involving just two particular users, you can do something like this.
SELECT convId, COUNT(*)
  FROM `conversations-members`
 WHERE userId IN (FIRST_USER, SECOND_USER)
 GROUP BY convId
HAVING COUNT(*) = 2

The HAVING line filters out any conversation with any users besides the two you want.
You can use that as a subquery:
SELECT whatever
  FROM conversations
 WHERE convId IN (
          SELECT convId
            FROM `conversations-members`
           WHERE userId IN (FIRST_USER, SECOND_USER)
           GROUP BY convId
          HAVING COUNT(*) = 2
       )

If you wanted conversations with your two users and any other users, you could change the subquery to HAVING COUNT(*) >= 2.
Pro tip: SQL thinks hyphens - mean subtraction. Avoid them in column and table names.

A: It's not recommended to use a column with multiple values.
When you have a relation 1-N, normally you need to use a table with two keys, for example, ConvID - UserID. Your index are created by these two columns, for don't allow to generate a duplicate (an UserID two times on the same ConvID, for example).
But, in response to your question, yes, it's possible to do that search. You need to search for an entry on your SQL table where two different IDs are on the same line. You can do it with LIKE clause, but it's not a good option (I think it's the worst possible WHERE clause).
The syntax will be as follows:
SELECT convId FROM conversations-members WHERE userId LIKE '%id1%' AND userId LIKE '%id2%'

For some additional recommendation, if your conversations are always a pair of people, use two new fields on your "conversations" table. If your conversation can have from one to N members, use the "conversations-members" as suggested at the start of the answer.


text:
Q: Добавление/удаление/изменение exif у файла Доброго времени суток, ХешКодовцы!
Очередная задачка повисла у меня. По интернету поискал и выяснил, что существует такая вещь как пользовательские атрибуты файла под название Exif. Все что смог найти, так это работа с metadata exif для картинок, но насколько я понимаю, данная информация может принадлежать не только картинкам, но и произвольному взятому файлу. Я прав?.. Данные свойства наблюдаются же у doc, xls документов. Значит теоретически, можно эти свойства повесить на любой файл.
У меня есть база данных. Хотелось бы ее описание запихнуть в exif, чтобы через свойства файла можно было бы узнать краткие сведения о ней, а не производить подключение и считывать некоторые данные из служебных таблиц. База данных формируется при помощи кода написанного на C#. Хотелось бы обойтись от посторонних готовых решений, а реализовать это все самостоятельно, если есть такая возможность. Если есть готовые решения в виде подключаемых модулей (dll), то ссылки на них пригодятся, в случае, если не получится реализовать функционал полностью самостоятельно.
PS: Решения в виде готовых продуктов не подходит, т.к. работа с файлами производится потоковое, по мере необходимости, и использование дополнительного продукта не приемлемо.
Заранее спасибо за Вашу помощь!
A:
Я прав?

Нет.  Exif только для картинок/фотографий.
Обычно в каждом типе документов используется свой формат метаданных.
Для изображений это:

*

*
Exif (англ. Exchangeable Image File Format) - чаще всего.

*
XMP - используется программами Adobe

XMP – гибкая платформа метаданных (Extensible Metadata Platform – XMP). Этот формат создан для добавления информации в файл. Формат XMP разработан так, что файл может прочитать любая программа, в том числе не умеющая работать с XMP. XMP используется в PDF, фотографии и редактировании изображений.

*

*IPTC

В файлах TIFF (Tagged Image File Format) есть теги, но они большей частью описывают технические параметры изображения, хотя есть поля для наименования и геометок
В System.Drawing.Imaging есть средства для манипуляции Exif данными. Тут пример программы для считывания и записи метаданных.
Для EXIF и XMP  есть готовая библиотека:  http://bitmaptagger.codeplex.com/
Для музыкальных файлов есть свои форматы метаданных. Среди них:

*

*
ID3 разных версий

*
APE

*
Vorbis comments
Для манипуляции ними используется:

*

*
TagLib Sharp

*
IdSharp
и другие
Метаданные (автор, заголовок, организация и т.д.) в документах Office Open XML (*.docx,  *.xlsx) извлекаются и редактируются с помощью библиотек Open XML SDK
UPD.
Если это всё происходит в пределах одного компьютера и на дисках используется NTFS, то можно попробовать сохранять эту служебную информацию в альтернативных потоках данных, а потом сделать утилиту которая бы считывала и отображала то что вам надо. Или же проще - ложить ваш файл базы данных в архив, а вместе с ним какой-нибудь META-INF или manifest.xml или ещё что-то в этом роде, в котором будет эта служебная информация. И соответственно утилиту для её считывания и отображения.


text:
Q: Playing DASH streaming video from a DRM protected app inside another app without the decryption key I need to play a video streaming in an on OTT platform app inside a VR application. Similar to how Netflix presents an environment VR Video player.
This is the link to one of such apps for reference: https://play.google.com/store/apps/details?id=com.tv.v18.viola&hl=en
So basically this app uses DASH streaming for their video
and it is DRM encrypted
We need to provide a VR plugin to this app but we wont get the key to their encryption we need to figure out some other way to play their video directly on our plugin. So i need to know how you can do that can you run the app window inside the VR environment or maybe stream the particular video from their website into the VR environment. http://www.voot.com/# is the website link.
Any inputs on the way to implement this are welcome.

A: The role of DRM is to protect against all unauthorized use. If a solution to this exists, it's very poor DRM. DRM does not just protect decoding. It protects access to the pixel buffer and rendering stages (HDCP). You need access to the pixel buffer to render it to a 3D surface.  If the DRM allowed for that, you could just write the pixel buffer to disk. Thus defeating the DRM. If you need alternate rendering, you need to speak to the DRM vendor.


text:
Q: Retaining order of moving elements in a list I've created a section of spans that when clicked on move into another html element and when clicked on while within the target element returns back to the section of spans.
My question is, how can I return the clicked span back to it's ORIGINAL position in the list of spans?
I can think of one way that might work and would involve using CSS child selectors, but that can become very complicated and I'm looking for a more intuitive way.
As it happens now, the span in question returns to the end of the list.

   <?php
    $query = 'SELECT * FROM genres ORDER BY genre DESC';
    $genres = mysqli_query($db, $query);
    while($row = mysqli_fetch_assoc($genres)){
        echo "";
        echo ucfirst($row['genre']);
        echo "";

The above simply outputs the data into seperate spans styled to be clickable elements that look similar to buttons.
When a span is clicked on it is moved into an empty div.
My Jquery:
$("span.genre").click(function(){
    // remove the span and move it to the empty div
    $(this).remove().appendTo('div#genres_select');

    // remove span from the empty div and puts it back in the list
    $('div#genres_select span.genre').click(function(){
        $(this).remove().appendTo('div#genres');
});

What is interesting and that I like is that when a clicked span is moved out of the list, all the other elements conform to fill it's space.
Ideally, I'm looking for the exact reverse action of clicking on a span, as if you pushed the rewind button.
Thanks in advance

A: Add the position to the dom.
  $pos = 0
  while($row = mysqli_fetch_assoc($genres)){
    echo "";
    echo ucfirst($row['genre']);
    echo "";
    $pos++
  }

The javascript looks for the lower neighbor
   $('div#genres_select span.genre').click(function(){
    var pos = $(this).attr("orgPos");
    var neighbor = false;
    $('#genres span.genre').each(function(){
            if (!neighbor && ($( this ).attr("orgPos") < pos ))
                  neighbor = $( this );
           })
    $(this).remove();
    sibling.after(this)
   }

You will need to figure out what to do if it is the first element or only one element in the list.


text:
Q: How can I get selected time and add class via jQuery? My HTML is dynamic and like that:

            21
            Jan
            15

And I want get this time and print console via jQuery:
var selectedDate = $('.date');
console.log(selectedDate);

But result is not correct. How can I fix it?
EDIT:
Ok, I solve my problem with that:
console.log(selectedDate.text());

Now, I want add class if event is a past event.
 if (selectedDate < now) {
        $('.event').addClass('past');
      }

But not any error or result.

A: Try this:
selectedDate = $(".date > .month").text() + " "
             + $(".date > strong:nth-child(1)").text() +
        " 20"+ $(".date > .year").text();

console.log(selectedDate); // Jan 21 2015

You could, of course, re-arrange those to output the date according to the format you want -


text:
Q: Multiple nested dictionaries within a nested dictionary Thanks to SO I have created a desired nested dictionary with the right keys from the following DataFrame:
df = pd.DataFrame({'name': ['jake','martin','justin'], 'date': ['6/7/2021','1/1/2031','1/4/2011'], 'country':['Russia','USA','Australia'],
'city 1':['Moscow','New York','Sidney'], 'city 2':['St. Petersburg','Los Angeles','Brisbane'], 'kids':[5,3,1], 'Feature 1':['some','feature','here'], 'Feature 2':['some2','feature2','here2']})

that looks like this:
   name      country   city 1    city2           kids   Feature1   Feature2   date
0  jake      Russia    Moscow    St. Petersburg  5       some       some2     1/1/2031
1  martin    USA       New York  Los Angeles     3       feature    feature2  4/4/2021
2  justin    Australia Sidney    Brisbane        1       here       here2     2/3/2015

Eventual goal:
to create a nested dictionary that looks like this:
{jake: {'name':'jake', 'Russia': {'city1':'Moscow', 'city2': 'St. Petersburg'}, '5': {'Feature1':'some', 'Feature1':'some2'}, 'date': '1/1/2031'}, martin: {}}
So my goal is to create nested dictionaries within a nested dictionary and I've tried different approaches including the use of defaultdict but unfortunately without a success.
Here is the code I've used to create a nested dictionary with the 1st level of nesting:
{jake: {'name':'jake', 'country':'Russia', 'city1':'Moscow', ...}}
df.set_index('name', inplace=True, drop=False)
d = df.transpose().to_dict()

I've also tried to create a separate dictionary and then append it but no success. Any help very appreciated.

A: if i understood you correctly, maybe iterating over the dataframe's rows and setting the values for the dictionary is a solution:
for index, row in df.iterrows():
    my_dict[row['name']] = {'name': row['name'],
                            row['country']: {'city 1':row['city 1'], 'city 2':row['city 2']},
                            'kids': row['kids'],
                            'date':row['date'],
                            'features':[row['Feature 1'], row['Feature 2']]}

my_dict

Output:
{'jake': {'Russia': {'city 1': 'Moscow', 'city 2': 'St. Petersburg'},
  'date': '6/7/2021',
  'features': ['some', 'some2'],
  'kids': 5,
  'name': 'jake'},
 'justin': {'Australia': {'city 1': 'Sidney', 'city 2': 'Brisbane'},
  'date': '1/4/2011',
  'features': ['here', 'here2'],
  'kids': 1,
  'name': 'justin'},
 'martin': {'USA': {'city 1': 'New York', 'city 2': 'Los Angeles'},
  'date': '1/1/2031',
  'features': ['feature', 'feature2'],
  'kids': 3,
  'name': 'martin'}}


text:
Q: How to convert a groupby().mean() into a callable object? I have the following very simple model in which I encounter an error message while I run it. The error is
Traceback (most recent call last):
File "mltest.py", line 63, in <module>
pred = B.predict(ms,r[0:10])
File "mltest.py", line 54, in predict
return map(self.means['score'][X], X)
TypeError: 'Series' object is not callable

The models structures as below:
from sklearn.base import BaseEstimator, ClassifierMixin
import pandas as pd

class MeanClassifier(BaseEstimator, ClassifierMixin):
    def __init__(self):
        pass

    def fit(self, X, y):
        self.name = X
        self.scores = y
        self.data = pd.DataFrame({"name": self.name, "score": self.scores})
        #print(self.data)
        self.means = self.data.groupby(["name"]).mean()
        #print(self.means)
        return self

    def predict(self, X):
        return map(self.means['score'][X], X)

Then I have a list of X (names)and y (scores)for model fitting and prediction. As I am testing my code, I just use the same data for model fitting and prediction.
names = ["John", "Mary", "Suzie", "John", "John", "Mary", "Suzie"]
scores = [80, 70, 75, 90, 92, 82, 88]
B = MeanClassifier()
Bfit = B.fit(names, scores)
Bpred = B.predict(names)

Obviously, the error comes from the datatype after I employ groupby(['name']).mean(). This object is not callable and therefore map does not work here. Could anyone give me a suggestion how to solve this problem? Thank you!!

A: In your estimator class, self.means is a DataFrame with index name and a single column called score. Change your predict function to
def predict(self, X):
    return self.means.loc[X, 'score']

.loc takes an index label (or list thereof) and a column label (or list thereof), so the above returns a Series (because you're accessing one column) with the values in the column score for all the names in X.


text:
Q: dijit.form.ComboBox not working with dojox.data.JsonRestStore I have my store defined as follows:
my_store = new dojox.data.JsonRestStore({
    target: '/my/rest/url/to/get/data'
});

And I defined ComboBox to work with that store:
myComboBox = new dijit.form.ComboBox({
    store: my_store,
    searchAttr: "name",
    pageSize: 20,
    autoComplete: true,
    hasDownArrow: false,
    highlightMatch: "all",
    style: "width: 80%; height: 17px; float: left",
    onChange: function () {
        // Do something with my tree
    },
    labelFunc: function (item, store) {
        var splits = item.path[0].split("/");
        var label = item.name[0] + " ("
            + splits.slice(0, splits.length - 1).join("/") + ")";
        return label;
    }
}, "searchBox");

But I can't make it working. ComboBox doesn't show anything.
But when I use dojo.data.ItemFileReadStore it works fine.
Could you please suggest any solution?
BTW, I need to use JsonRestStore because I do lazy loaded tree with it.

A: Please check the network tab in your browser's console to verify if the rest call is happening. May be fully qualified url is required. Ex: 'http://localhost//my/rest/url/to/get/data'
Alternatively you can use dojo.xhrGet to return the Json result and create  dojo.data.ItemFileReadStore out of that. This will also load the combobox when you actually do the ajax call.
Thanks


text:
Q: Index going out of range in bisect_left in Python 3 I'm writing this piece of code, in which I've used bisect_left function from the bisect module which is a first-party module of Python. I'm using it with two parameters only i.e. sorted_list and target(the one for which I have to find the suitable index value).
The issue is: If my target is greater than the sum of lowest value and highest value, the function is returning the index = len(sorted_li), due to which I'm getting index error. I can use try and except but more than that I'm curious to know why it is behaving like so.
Following is my code:
from bisect import bisect_left

li = [10,15,3,6,10]
k  = 19

def binary_search(sorted_list,target):

    index = bisect_left(sorted_list,target)

    print(index)

    if sorted_list[index] == target:
        return index

    else:
        return False

def function(sorted_li,k):

    """
    Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
    For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
    """

    print(sorted_li)

    for i in range(len(sorted_li)):

        print('Next iteration')

        print(sorted_li[i])

        target = k - sorted_li[i]

        j = binary_search(sorted_li,target)

        if j:
            if j != i:
                print(sorted_li[i])
                print(sorted_li[j])
                return True
            else:
                if j + 1 < len(sorted_li):
                    if sorted_li[j+1] == target:
                        print(sorted_li[i])
                        print(sorted_li[j+1])
                        return True
                if j - 1 > 0:
                    if sorted_li[j-1] == target:
                        print(sorted_li[i])
                        print(sorted_li[j-1])
                        return True
    return False

if __name__ == "__main__":

    li.sort()
    a = function(li,k)
    print(a)

It's output is as follows:

but when I'm changing k to 18, the code is working fine, the output is as follows:

I've tried with various sets of numbers for the same. The output remains the same.

A: You're using bisect_left which has next purpose: it looking for the insertion point for x (which is target in your case) in a to maintain sorted order.
So for your case when you call first binary_search first time for 16 (19 - 3), it compare your number with items in li list using binary algorithm and then it returns position for insert 5, because in your list [3, 6, 10, 10, 15] insertion point should be after 15 which is correct.
If you open documentation you can find next method in searching sorted list
which does exactly you need, it searching for the exact item in list and return position of it if it exists either it raises ValueError because item not found.
def index(a, x):
    'Locate the leftmost value exactly equal to x'
    i = bisect_left(a, x)
    if i != len(a) and a[i] == x:
        return i
    raise ValueError


text:
Q: Get nodes based on various date rules I need to get a list of nodes, based on 2 rules, both related to a date field (myDate in this example).
I currently have the following, that only takes one of the 2 rules, which is checking if the date field is empty;
var results = root.Descendants("myDocType")
    .Where(x => !x.GetProperty("myDate").HasValue)
    .OrderBy("myDate desc");

In the same Where clause, i need to check for:

*

*The date is empty OR

*The date is today or earlier (just the date, not the time of day)

So i basically need to add the last requirement to my Where clause. But how?

A: Found the solution:
var results = root.Descendants("myDocType")
   .Where(x => !x.GetProperty("myDate").HasValue
             || x.GetPropertyValue<DateTime>("myDate") >= DateTime.Now.Date)
   .OrderBy("myDate desc");


text:
Q: adding play-services-maps dependancy auto adds glEsVersion 2.0 requirement I'd like to integrate with Google Play Services Maps module.
Since the maps manifest declare:
<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true"/>

Gradle's manifest merger adds this block to the resulting manifest making my app not supported on devices running OpenGL 1.0, however my Maps feature is not mandatory, and I do want to support these devices.
I've tried adding to my own manifest one of these:
<uses-feature
    android:glEsVersion="0x00010000"
    android:required="false" />

or
<uses-feature
    android:glEsVersion="0x00010000"
    android:required="false"
    tools:replace="glEsVersion,required" />

or
<uses-feature
    android:glEsVersion="0x00010000"
    android:required="false"
    tools:node="remove"
    tools:replace="glEsVersion,required"/>

But nothing works, either it automatically chooses the one with the highest value (2.0), or it adds both blocks to the resulting manifest, still making my app require 2.0

A: I was able to solve it using build.gradle hacks, by manually overriding the merged manifest source.
However I would prefer a more elegant way using Gradle's manifest merger tools (tools:node, tools:replace, etc.)
I removed the glEsVersion from AndroidManifest, and added the following to my build.gradle:
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            output.processManifest.doLast {
                def manifestOutFile = output.processManifest.manifestOutputFile
                def newFileContents = manifestOutFile.getText('UTF-8').replace("android:glEsVersion=\"0x00020000\"", "android:glEsVersion=\"0x00010000\"")
                manifestOutFile.write(newFileContents, 'UTF-8')
            }
        }
    }


text:
Q: something concerning finite projections Let $A$ be a Baer *-ring. Let $x$ be an isometry (meaning $x^*x=1$ where $1$ is the unit of $A$).
Let $e$ be a finite projection in $A$ such that $ex^ne=ex^n$ for every $n\geq0$.

Q. Can we say that $e\leq \inf x^nx^{*n}$

Remark. $x^nx^{*n}$ is a projection for every $n\geq1$.


text:
Q: Node JS and Nginx routing I'm having a little bit of trouble rerouting my server:80 to my node js app running in port 9999.
I have my nginx setup like so:
server {
    listen  80;
    server_name mydomain.com;

    location / {
            proxy_pass http://principal-domain.com:9999/;
    }

    location ~/\.ht {
            deny all;
    }
}

But obviously only / is being rerouted. If I make a request to /api I get a 502 Bad Gateway.
Anyone knows how to fix this? Apply the rerouting for all routes in mydomain.com?


text:
Q: Sql server update multiple columns from another table I have read lots of post about how to update multiple columns but still can't find right answer.
I have one table and I would like update this table from another table.
Update table1
set (a,b,c,d,e,f,g,h,i,j,k)=(t2.a,t2.b,t2.c,t2.d,t2.e,t2.f,t2.g,t2.h,t2.i,t2.j,t2.k)
from
(
  SELECT ..... with join ... where ....

) t2
    where table1.id=table2.id

If I running only select statement (between brackets) then script return values but not working with update

A: TSQL does not support row-value constructor. Use this instead:
UPDATE table1
SET a = t2.a,
    b = t2.b,
    (...)
FROM
(
SELECT ..... with join ... WHERE ....
) t2
WHERE table1.id = table2.id

A: You don't need to use a sub-query you can also simply do the following....
Update t1
set t1.a  = t2.a
   ,t1.b  = t2.b
   ,t1.c  = t2.c
   ,t1.d  = t2.d
   .......
from table1 t1
JOIN table2 t2  ON t1.id = t2.id
WHERE .......

A: The above solution will work only for MSSQL.
In case of MySql you just need to first declare the tables
UPDATE
      table1 t1 ,table2 t2
set
      t1.field=t2.field
where
      t1.id=t2.id;

In my case this worked..!!

A: The UPDATE  SET commands implicitly apply on the table specified by , and it is not possible to specify the table on the SET operation.
Edit: Specify only the column name you want to update, do not mention the table.


text:
Q: using enums across files without defining them in a header for example I have
enu.cpp
enum ena{
    X, Y
};

and main.cpp
#include <iostream>
#include "header.h"

using namespace std;

int main(){

    ena a = X;

}

how do I declare (not define) the enum in a header file so that I can use ena in main.cpp.
Please note that I don't want to define the enum in the header, but just want the compiler to know (through the header file) that the definition of the enum ena exists in some cpp file (in this case enu.cpp)
basically I want to forward declare an enum.


text:
Q: Can't align an element in flexbox I'm currently trying to align the last element in a flexbox with a height higher than its elements at the bottom of the flexbox, but I can't manage to do it. I know I can use align-content: stretch which is the default behavior, but I don't want gaps between my elements.
I just want "More Stuff" to be at the bottom of the box and aligned to the right, and I can't figure out how to do it by reading through the flexbox spec.
https://jsfiddle.net/k8dec2bx
HTML:

      Stuff

      More Stuff

CSS:
.flex{
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
  width: 500px;
  height: 600px;
  box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.75);
}

img{
  width: 100%;
  height: 250px;
}

.flex div{
  width: 100%;
}

.bottom{
  align-self: flex-end;
  text-align: right;
}

A: First you need to put flex-direction: column on your .flex element as you're attempting to align items vertically. From here it's just a matter of manipulating flex-grow and flex-shrink to your desired result.
If you want the .bottom element hard up against the bottom, all you need to do is tell the other element (which I've given a class of .top to make things clearer) that it should grow to take up all the available space. This can be done with flex-grow: 1.
This can be seen in the following:

.flex {
  display: flex;
  flex-wrap: wrap;
  flex-direction: column; /* New */
  align-content: flex-start;
  width: 500px;
  height: 600px;
  box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.75);
}

img {
  width: 100%;
  height: 250px;
}

.flex div {
  width: 100%;
}

.top {
  flex-grow: 1; /* New */
}

.bottom {
  align-self: flex-end;
  text-align: right;
}

      Stuff

      More Stuff

A: It's easier to see if you put different colored backgrounds on your divs but your two elements are 100% width and on top of eachother in the center of the page because of the flex-wrap: wrap.
So, to align or justify the elements you need to set a flex direction first. (Setting the direction as either row of column changes what is considered the main axis you can see a diagram on MDN)
Row will set the main axis as left-right and column will set the main axis as  up-down.
After that you can use Justify-content: space-beween to space the elements as much as possible in the box div along the main axis. (align-contentcontrols whatever is set as the opposite axis)
    .flex{
      display: flex;
      flex-wrap: wrap;
      flex-direction: column;
      justify-content: space-between;
      align-content: flex-start;
      width: 500px;
      height: 600px;
      box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.75);
    }


text:
Q: How to set a flag in array of objects and render items I am trying to render the particular object in an array. Where should i set the flag?Need Single loop
mappedData = (data) => {
return data.map((item) => {...logic}
}

Here is my  sample object which returns
item:[
{id: 1, entry_id: 1, name: 'test', email: 'foo@bar.com', isFirst:true},
{id: 2, entry_id: 1, name: 'test', email: 'bar@foo.com', isFirst:false},
{id: 3, entry_id: 2, name: 'test', email: 'foo@bar.com', isFirst:true},
{id: 4, entry_id: 2, name: 'test', email: 'bar@foo.com', isFirst:false},
{id: 5, entry_id: 1, name: 'test', email: 'joe@ocean.com', isFirst:true},
{id: 6, entry_id: 2, name: 'test', email: 'foo@bar.com', isFirst:false},
{id: 7, entry_id: 2, name: 'test', email: 'foo@bar.com', isFirst:false},
];

How to set flag? and render 2 different div's which contains entry_id 1 in div and entry_id 2  in another div
render(){
return(
if(this.mappedData.entry_id =1){

All entry_id 1 data should appear

}
if(this.mappedData.entry_id =2){

All entry_id 2  data should appear

}

Most welcome on different solution with single loop

A: The simplest way I can think of is to have your two divs separately and then run individual loops in each with returning null (in your false case):
Code could look like this, (assuming item is your array):

{item.map((x) => {
  if(x.entry_id === 1){
      return
{x.name}

  }
 return null;

})}

{item.map((x) => {
  if(x.entry_id === 2){
     return
{x.name}

  }
 return null;
})}

If item is an object property, just replace item.map with data.item.map
Link

*

*You can also make separate loops at top by filtering and show them.

*You can also filter your array and then map inside the curly braces, if you are concerned about the null
EDIT:
OP wanted a solution with single loop. It can be achieved using this:

  let div1 = [];
  let div2 = [];

  item.forEach((x) => {
    if (x.entry_id === 1) {
      div1.push(
{x.name}
);
    } else {
      div2.push(
{x.name}
);
    }
  });

  return (

      {
        <>
          {div1}
          {div2}
        </>
      }

  );

Updated Link


text:
Q: singleton pattern with __new__ doesn't work in python 2 I try to implement singleton pattern in python 2 but it doesn't work, but it works in python 3, someone help me explain why?
class Singleton:

    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

obj1 = Singleton()
obj2 = Singleton()

print(obj1)
print(obj2)

output:
<__main__.Singleton instance at 0x7fab8b625e60>
<__main__.Singleton instance at 0x7fab8b5e4710>

A: First of all in python2 you must be inherited from object to make __new__ magic works.
Because old-style class doesn't have __new__ method at all.
So with added prints you will got:
>>> class Singleton:
...     _instance = None
...     def __new__(cls):
...         print('__new__')
...         if cls._instance is None:
...             print('create')
...             cls._instance = super().__new__(cls)
...         return cls._instance
...
>>> obj1 = Singleton()
>>> obj2 = Singleton()
>>>
>>> print(obj1)
<__main__.Singleton instance at 0x7f47dcccecb0>
>>> print(obj2)
<__main__.Singleton instance at 0x7f47dcccef80>

As you can see python2 doesn't call __new__ at all. It just calls empty __init__ in your case and creates two different objects.
Secondly, in python2 you need rewrite super() call as it was changed in python3.
So corrected code will be:
>>> class Singleton(object):
...     _instance = None
...     def __new__(cls):
...         print('__new__')
...         if cls._instance is None:
...             print('create')
...             cls._instance = super(Singleton, cls).__new__(cls)
...         return cls._instance
...
>>> obj1 = Singleton()
__new__
create
>>> obj2 = Singleton()
__new__
>>>
>>> print(obj1)
<__main__.Singleton object at 0x7f47dccd9590>
>>> print(obj2)
<__main__.Singleton object at 0x7f47dccd9590>

For more information about singletons you can reed here: Creating a singleton in Python


text:
Q: A bipartite graph $G$ such that for any partition $X$ and $Y$, $\alpha(G)> \max \{X,Y\}$ The question is

Construct a bipartite graph $G$ such that for any partition $X$ and $Y$, $\alpha(G)> \max \{X,Y\}$. Explain.

I did this graph:

Here it works, $\alpha (G) =9$ (marked in blue box), and each partition is $7$. However, if we flip the red circled vertices so that the $3$ top vertices become in $Y$-partition $Y$ will be equal to $9$, which violates what I want to prove. Is there any way to fix my graph?

A: When you flip the graph then y will have cardinality 9 and maximal independant set will become 9 .
So it proves what you are trying to prove.


text:
Q: Reading PNG meta data on the web I've recently written a Python module that writes meta tags and values to PNG images using PIL, with the intent to have a webpage read the tags and sort the images accordingly (I'm not interested in the default stuff like Camera Type, I attach tags like "CarModel" if I've just been to a rally for example.
Does anyone recommend a way of reading the PNG meta?  I'm using PHP at the moment (http://stackoverflow.com/questions/2190236/how-can-i-read-png-metadata-from-php at the bottom) which is great for the reason that it only pics up the tags I've added, but annoying as I can't figure away of building a neat array with the data for many pictures.  Can javascript do this?
Sorry If I've been rubbish at explaining, but I'll re-explain if needs be.

A: you should have a look at the following php function - exif_read_data
PS: javascript can't do that as far as I know

A: i had a similar task. I had to write physical dimensions and additional metadata to PNG files. I have found some solutions and combined it into one small library.
png-metadata
it could read and write PNG metadata. it could be used on client and server side.
May be it will help somebody.
Here how you can read PNG metadata in the Browser:
        function loadFileAsBlob(url){
            return new Promise((resolve, reject) => {
                var xhr = new XMLHttpRequest();
                xhr.open('GET', url, true);
                xhr.responseType = 'blob';
                xhr.onload = function(e) {
                    if (this.status === 200) {
                        resolve(this.response);
                        // myBlob is now the blob that the object URL pointed to.
                    }else{
                        reject(this.response);
                    }
                };
                xhr.send();
            })
        };

        const blob = await loadFileAsBlob('1000ppcm.png');
        metadata = readMetadataB(blob);

A: Here is a link to a Javascript library that claims to be able to read image metadata:
http://blog.nihilogic.dk/2008/08/imageinfo-reading-image-metadata-with.html

A: The nihilogic Javascript libraries are indeed very useful for client-side EXIF reading and parsing; but that only applies to JPEG images, as the metadata is supported only in the JPEG and TIFF format (and the TIFF format only supported natively by Safari browser).
PNG can include metadata but not in the form of IPTC or EXIF fields as JPEG or TIFF formats allow.


text:
Q: Why two ViewSets have identical url in DRF? Why two different viewsets have identical url? How can I change it?
router = routers.DefaultRouter()
router.register(r'general-worker', GeneralWorkerViewSet)
router.register(r'full-info-worker', FullInfoWorkerViewSet)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/v1/', include(router.urls)),
    path('api/v1/drf-auth/', include('rest_framework.urls')),
]

json from http://127.0.0.1:8000/api/v1/
{
    "general-worker": "http://127.0.0.1:8000/api/v1/full-info-worker/",
    "full-info-worker": "http://127.0.0.1:8000/api/v1/full-info-worker/"
}

A: i can not solve your example, we have not enough information.
I can imagine, it can help:
router.register(r'general-worker', GeneralWorkerViewSet, basename='generalWorker')
router.register(r'full-info-worker', FullInfoWorkerViewSet, basename='fullInfoWorker')

try to use basename parameter.
docs here:
https://www.django-rest-framework.org/api-guide/routers/


text:
Q: Horizontal Recycler View Not Showing Anything I have a horizontal recycler view in a relative layout, everything looks OK but in the layout it doesn't show any item of the recycler view.There are some same questions on the Website but I can't find the problem.Here's the code:
RecyclerView Adapter:
public class ExamDetailRecyclerViewAdapter extends
    RecyclerView.Adapter<ExamDetailRecyclerViewAdapter.DetailViewHolder> {

private String[] examNameList;
private Integer[] examImageIds;
private String[] examPriceList;

private static Activity activity;

public ExamDetailRecyclerViewAdapter(Activity activity,
        String[] examNameList, Integer[] examImageIds,
        String[] examPriceList) {
    this.examNameList = examNameList;
    this.activity = activity;
    this.examImageIds = examImageIds;
    this.examPriceList = examPriceList;

}

@Override
public int getItemCount() {
    return examNameList.length;
}

@Override
public long getItemId(int position) {
    return position;
}

public DetailViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(
            R.layout.exam_detail_hlistview_item, viewGroup, false);

    return new DetailViewHolder(itemView);
}

public static class DetailViewHolder extends RecyclerView.ViewHolder
        implements OnClickListener {

    TextView examNameTextView;
    ImageView examImageView;
    TextView examPriceTextView;
    RatingBar examRatingBar;

    public DetailViewHolder(View v) {
        super(v);

        examNameTextView = (TextView) v
                .findViewById(R.id.exDetail_hListView_exam_name);
        examImageView = (ImageView) v
                .findViewById(R.id.exDetail_hListView_image);
        examPriceTextView = (TextView) v
                .findViewById(R.id.exDetail_hListView_exam_price);
        examRatingBar = (RatingBar) v
                .findViewById(R.id.exDetail_hListView_exam_rating_bar);
         v.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent i = new Intent(v.getContext(), ExamDetailActivity.class);
        activity.startActivity(i);
    }
}

@Override
public void onBindViewHolder(DetailViewHolder detailViewHolder, int i) {
    // TODO Auto-generated method stub
    detailViewHolder.examNameTextView.setText(examNameList[i]);
    String num = displayNumbertoFarsi(examPriceList[i]);
    detailViewHolder.examPriceTextView.setText(num);
    detailViewHolder.examImageView.setImageResource(examImageIds[i]);
    detailViewHolder.examRatingBar
            .setOnRatingBarChangeListener(new OnRatingBarChangeListener() {

                @Override
                public void onRatingChanged(RatingBar ratingBar,
                        float rating, boolean fromUser) {

                    Toast.makeText(activity,
                            "Rating Value: " + String.valueOf(rating),
                            Toast.LENGTH_SHORT).show();
                }
            });
}
}

Recycler view layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/ir.elenoon.bazmoon"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<include
    android:id="@+id/toolbar_exam"
    layout="@layout/toolbar" />

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" >

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@+id/about_exam_bottom_layout"
        android:background="@color/chromatic_grey"
        android:scaleType="fitXY"
        android:scrollbars="vertical" >

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/bg" >

            <RelativeLayout
                android:id="@+id/fourth_partition"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/third_partition"
                android:layout_marginBottom="15dp"
                android:layout_marginLeft="30dp"
                android:layout_marginRight="30dp"
                android:layout_marginTop="15dp"
                android:background="@drawable/button_border"
                android:padding="12dp" >

                <app.textView.custemFont.TextViewPlus
                    android:id="@+id/about_exam_same_exams_title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_alignParentTop="true"
                    android:layout_margin="5dp"
                    android:text="@string/about_exam_same_exams_title"
                    android:textColor="#000000"
                    android:textStyle="bold"
                    app:customFont1="DroidNaskhRegularSystemUI.ttf" />

                <android.support.v7.widget.RecyclerView
                    android:id="@+id/exam_detail_hListView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/about_exam_same_exams_title"
                    android:background="#000000"
                    android:focusable="false"
                    android:paddingBottom="20dp"
                    android:paddingTop="20dp"
                    android:scrollbars="horizontal" />
            </RelativeLayout>
        </RelativeLayout>
    </ScrollView>
</RelativeLayout>

</LinearLayout>

Recyler view item xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/ir.elenoon.bazmoon"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:orientation="horizontal"
android:padding="5dp" >
<ImageView
    android:id="@+id/exDetail_hListView_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginBottom="5dp"
    android:layout_marginTop="5dp"
    android:contentDescription="@string/image_button_contentDescription"
    android:scaleType="fitXY"
    android:src="@drawable/icon_luncher" />

<app.textView.custemFont.TextViewPlus
    android:id="@+id/exDetail_hListView_exam_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginBottom="5dp"
    android:layout_marginTop="5dp"
    android:text="exam_name"
    android:textColor="@color/black"
    app:customFont1="DroidNaskhRegularSystemUI.ttf" />

<RelativeLayout
    android:id="@+id/bottom_grid_view_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <app.textView.custemFont.TextViewPlus
        android:id="@+id/exDetail_hListView_exam_price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_gravity="right"
        android:layout_marginBottom="5dp"
        android:layout_marginTop="5dp"
        android:layout_toRightOf="@+id/exDetail_hListView_exam_rating_bar"
        android:text="exam_price"
        android:textColor="@color/black"
        app:customFont1="Byekan.ttf" />

    <RatingBar
        android:id="@+id/exDetail_hListView_exam_rating_bar"
        style="@style/foodRatingBarSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:isIndicator="true"
        android:numStars="5"
        android:rating="3"
        android:stepSize="0.1" />
</RelativeLayout>

</LinearLayout>

Main Activity:
public class ExamDetailActivity extends AppCompatActivity {

String[] examNameList = { "Java", "C", "C++", "C#", "Jsp",
        "Microsoft .Net", "Android", "PHP", "Jquery", "JavaScript" };

String[] examPriceList = { "1000 ت", "2000 ت", "3000 ت", "4000 ت",
        "5000 ت", "6000 ت", "7000 ت", "8000 ت", "9000 ت", "10 000 ت" };
// Keep all Images in array
Integer[] examImageIds = { R.drawable.s1, R.drawable.s2, R.drawable.s3,
        R.drawable.s4, R.drawable.s5, R.drawable.s6, R.drawable.s7,
        R.drawable.s8, R.drawable.s9, R.drawable.s10 };

ExamDetailRecyclerViewAdapter mDetailHListViewAdapter;

private RecyclerView recyclerView;

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

    recyclerView = (RecyclerView) findViewById(R.id.exam_detail_hListView);
    recyclerView.setHasFixedSize(true);
    LinearLayoutManager llm = new LinearLayoutManager(this);
    llm.setOrientation(LinearLayoutManager.HORIZONTAL);
    recyclerView.setLayoutManager(llm);

    ExamDetailRecyclerViewAdapter examDetailHListViewAdapter = new ExamDetailRecyclerViewAdapter(
            this, examNameList, examImageIds, examPriceList);

    recyclerView.setAdapter(examDetailHListViewAdapter);

}}

A: As pointed out by Rohan the WRAP_CONTENT as a height does not work with the RecyclerView for a simple solution try setting a
android:minHeight="...dp" on the RecyclerView
If you don't mind me suggesting, your implementation for RecyclerView's adapter looks a little complex. Maybe organize exam namelists, pricelists and image ids into a common class. For e.g.
public class Exam {
    String examName;
    String price;
    int imageId;

    // getter and setters for exame name, price, and image id
}

Now rather than having numerous parameters in your constructor you'd have a constructor like this.
List<Exam> examList;

public ExamDetailRecyclerViewAdapter(Activity activity, List<Exam> examList) {
    this.examList = examList;
    this.activity = activity;
}

Your onBindViewHolder would look something like this:
@Override
public void onBindViewHolder(DetailViewHolder detailViewHolder, int position) {
    // TODO Auto-generated method stub
    Exam exam = examList.get(position);
    detailViewHolder.examNameTextView.setText(exam.getExamName());
    String num = displayNumbertoFarsi(exam.getPrice();
    detailViewHolder.examPriceTextView.setText(num);
    detailViewHolder.examImageView.setImageResource(exam.getImageId());
    detailViewHolder.examRatingBar
            .setOnRatingBarChangeListener(new OnRatingBarChangeListener() {

                @Override
                public void onRatingChanged(RatingBar ratingBar,
                        float rating, boolean fromUser) {

                    Toast.makeText(activity,
                            "Rating Value: " + String.valueOf(rating),
                            Toast.LENGTH_SHORT).show();
                }
            });
    }
}

A: You may want to refer to the following thread
How do I make WRAP_CONTENT work on a RecyclerView
Wrap_content generally does not work for a RecyclerView. You need a custom LayoutManager and override onMeasure.

A: wrap_content doesn't work with the default LinearLayoutManager, use this library instead
https://github.com/serso/android-linear-layout-manager
edit :
this is how to do it
add the following dependency to your module build.gradle
compile 'org.solovyev.android.views:linear-layout-manager:0.5@aar'

and then in your code
LinearLayoutManager layoutManager = new org.solovyev.android.views.llm.LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);

A: Late but useful
set orientation = horizontal in recyclerview will work horizontal layout of recyclerview


text:
Q: JUnit before test parameters Is there a way to give test somesort of parameters that need to be used before the test is run. Like log in with different account or something like that?
I want to test a webpage. The webpage has different behaviour depending on the user who is logged in. Before each test i would like to switch the user who is logged in. Is there a way to let @Before know what user i want to log in with?

A: You can write helper methods which will do your login. You can use these methods in your tests, depending on what you want to test/check.
@Test
public void deleteUserComment() {
    int adminId = this.loginAsAdministrator();
    /*
    ...
    */
}

@Test
public void saveSettings() {
    int userId = this.loginAsUser();
    /*
    ...
    */
}

A: int x = 0;

@BeforeEach
public void beforeEach() {
    switch(x) {
        case 0:
            //Log in with user 1
            break;
        case 1:
            //Log in with user 2
            break;
    }
    x++:
}

Should work.


text:
Q: Azure .NET API - MissingMethodException I've a problem since many days.
I'm using the Azure.Fluent package in my program and I must to create a ResourceGroup, but when I create it or list themw, I got the MissingMethodsException and I don't know why. And I've never founded any solution to this.
This is my code :
            AzureCredentials cred = SdkContext
            .AzureCredentialsFactory
            .FromServicePrincipal(
                ClientId,
                ServicePrincipalPassword,
                AzureTenantId,
                AzureEnvironment.AzureGlobalCloud
            );

        var azure = Azure
            .Configure()
            .Authenticate(cred)
            .WithSubscription(AzureSubscriptionId);

        var resourceGroup = azure.ResourceGroups.List();

Thanks in advance !
EDIT
This is the detailed error I have :

System.MissingMethodException: 'Méthode introuvable : 'System.Threading.Tasks.Task`1 Microsoft.Rest.Azure.Authentication.UserTokenProvider.LoginSilentAsync(System.String, System.String, System.String, System.String, Microsoft.Rest.Azure.Authentication.ActiveDirectoryServiceSettings, Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache)'.'

A: I test it well in my site with Microsoft.Azure.Management.Fluent version 1.10.0 and Microsoft.Azure.Management.ResourceManager.Fluent version 1.10.0.
And create and list resourcegroup with the following code:
var credentials = SdkContext.AzureCredentialsFactory.FromFile(@"D:\azurecred.txt"); //get azure credentials from file
var azure = Azure
    .Configure()
    .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
    .Authenticate(credentials)
    .WithDefaultSubscription();
var account = azure.StorageAccounts.List();
var rg = azure.ResourceGroups.Create();
var resourceGrouplist = azure.ResourceGroups.List();

The credential contains clinetid, clientkey, tenantid and subscriptionid.
If you still have any problem, please show me more detailed information like what your fluent SDK version and you use .net or .net core and so on.

A: This issue was fixed in Azure Fluent SDK a while ago. Please reference latest (v.1.18.0 at the moment) nuget packages.


text:
Q: The atime of a NFS directory does not get updated I have been trying to stat a directory in my file share that got mounted from NFS Server  [which is VM Debian 8.11], After i've touched a file in the directory and read the directory content by ls ,the atime,mtime and ctime got modified ,So things went fine here,And then i did the same on my file share that mounted from physical machine [which is Debian 7.9], the atime of the directory remains the same though i have touched and lsed the directory. both of these file share were mounted by realtime,I wonder why does it happen. when I just ran mount on the physical machine[NFS SERVER] ,I could see most of its local files are mounted with noatime
tmpfs on /run type tmpfs (rw,nosuid,noexec,relatime,size=26352140k,mode=755)
/dev/sda2 on /lib/live/mount/medium type ext4 (rw,noatime,user_xattr,data=ordered)
/dev/loop0 on /lib/live/mount/rootfs/filesystem.squashfs type squashfs (ro,noatime)
tmpfs on /lib/live/mount/overlay type tmpfs (rw,relatime)
tmpfs on /lib/live/mount/overlay type tmpfs (rw,noatime,mode=755)
aufs on / type aufs (rw,noatime,si=b3e6ae3b999120a9,noxino)
tmpfs on /run/lock type tmpfs (rw,nosuid,nodev,noexec,relatime,size=5120k)
tmpfs on /run/shm type tmpfs (rw,nosuid,nodev,noexec,relatime,size=52704260k)
/dev/sda2 on /var/lib/dsnet-config type ext4 (rw,noatime,user_xattr,data=ordered)
/dev/sda2 on /var/log type ext4 (rw,noatime,user_xattr,data=ordered)
/dev/sda2 on /var/spool/rsyslog type ext4 (rw,noatime,user_xattr,data=ordered)
/dev/sda2 on /var/lib/dsnet-core type ext4 (rw,noatime,user_xattr,data=ordered)
/dev/sda2 on /var/lib/dsnet-md type ext4 (rw,noatime,user_xattr,data=ordered)
/dev/sda2 on /etc/corosync type ext4 (rw,noatime,user_xattr,data=ordered)
/dev/sda2 on /var/lib/heartbeat type ext4 (rw,noatime,user_xattr,data=ordered)

Ain't sure whether the above mounts has to deal with my problem , yet these are the only oddity I have been seeing between them.
And one more question to ask if I give a NFS request like MKDIR() will this call take the time info from client or it does take it from the NFS SERVER

A: Modern Linux systems do not record directory access times unless the filesystem is mounted with the diratime option. This is because updating access time has a significant performance impact and directory access times, unlike access times of regular files, are not very useful because they are very frequently updated (as soon as someone runs ls in the directory, when updating the locate database, …).
If you want directory access times to be recorded, you need to mount the filesystem with the diratime option on the server. (In principle you should also pass diratime on the client but I think the NFS driver, unlike most other filesystems, ignores this option and lets the server update directory atimes implicitly.)


text:
Q: Is flexible layouts hard to make and maintain, time consuming than fixed width layout? Is flexible layouts hard to make and maintain, time consuming than fixed width layout?
Is flexible layout means only to give width height and font in em or %?
What is main benefit of flexible layout to the desktop and mobile users?
And if we make flexible layout then should be give images width and height in em or `% also to images scale along with layout div and font size.
Should we make everything flexible Header, footer, sidebar, content area?
Is there any cons of flexible layout? I heard one about longer paragraph is not good for readability.
If client is happy with fixed width layout even should we make layout flexible (to show our skills to others) if client don't mind if we don't ask for extra money? or we should make layout flexible only on demand.

A: Flexible layouts are more difficult to develop than fixed with layouts. Setting width in % is one possibility to create flexible layouts. You can also use JS to scale the text a.s.o.
The benefit of flexible layouts is that it fills every screen and horizontal scrollbars never appear. Images should be fixed width because most browser don't do a very good job of scaling images.
Not every single element has to be flexible, but a flexible content area doesn't help you much if the header remains fixed and creates a scrollbar.

A: I generally develop a site with a fluid structure that is kept at some fixed width by the main containing element.  That way, I can easily make changes to the overall page width without manually modifying every element whose width needs to be changed.  Essentially, this requires that you set the main container's width in pixels and all of the inner elements as percentages of that containing element.
If you do need to create a fluid layout, a better way to deal with the wide content area would be to use max-width to limit just how far certain elements can extend.  This should prevent content flow issues while still allowing other parts of your layout to take full advantage of the user's screen size.
To allow for text resizing, leave the height for containing elements undefined, so they can expand as needed when the text size is changed.