Q: Yii2 - Unknown error in renderSelectOptions method when using active dropDownList I'm getting an error when the aforementioned method gets called during the use of activeForm's dropDownList. What's weird is that I have already made other dropDownLists in a similar manner and they're working normally.
The error is:
PHP Warning – yii\base\ErrorException
strcmp() expects parameter 2 to be string, object given

The _form code for generating the list is as follows:
$lista_unidades = ArrayHelper::map(Unidad::find()->where('institucion="Carabineros de Chile"')->asArray()->all(), 'id_unidad', 'nombre');

asort($lista_unidades);

$form->field($model, 'id_unidad_que_diligencia')->dropDownList($lista_unidades, ['prompt' => 'Seleccione...']);

Yii2 provides the following information about the error (links to images):
First, Second
Any help will be greatly appreciated.
EDIT:
The Model Class:
<?php

namespace app\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;

/**
 * This is the model class for table "orden_judicial".
 *
 * @property string $id_orden_judicial
 * @property string $causa_rit
 * @property string $causa_ruc
 * @property string $causa_rol
 * @property string $fecha_emision
 * @property string $tipo
 * @property string $estado
 * @property string $id_unidad_que_direcciona
 * @property string $id_unidad_que_diligencia
 * @property string $id_unidad_que_redirecciona
 *
 * @property AdjuntoOrdenJudicial[] $adjuntoOrdenJudicials
 * @property Aviso[] $avisos
 * @property Persona[] $rutPersonas
 * @property Dilgienciamiento[] $dilgienciamientos
 * @property Unidad $idUnidadQueDirecciona
 * @property Unidad $idUnidadQueDiligencia
 * @property Unidad $idUnidadQueRedirecciona
 */
class OrdenJudicial extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
     public static function tableName()
    {
        return 'orden_judicial';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['fecha_emision', 'tipo', 'estado', 'id_unidad_que_direcciona', 'id_unidad_que_diligencia'], 'required'],
            [['fecha_emision'], 'safe'],
            [['id_unidad_que_direcciona', 'id_unidad_que_diligencia', 'id_unidad_que_redirecciona'], 'integer'],
            [['causa_rit', 'causa_ruc', 'causa_rol', 'tipo', 'estado'], 'string', 'max' => 100]
        ];
    }

    public function behaviors() {
        return [
                [
                    'class' => TimestampBehavior::className(),
                    'createdAtAttribute' => 'fecha_emision',
                    'updatedAtAttribute' => false,
                    'value' => new Expression('NOW()'),
                ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id_orden_judicial' => 'Número de orden',
            'causa_rit' => 'Causa RIT',
            'causa_ruc' => 'Causa RUC',
            'causa_rol' => 'Causa ROL',
            'fecha_emision' => 'Fecha de Emisión',
            'tipo' => 'Tipo',
            'estado' => 'Estado',
            'id_unidad_que_direcciona' => 'Tribunal o Fiscalía',
            'id_unidad_que_diligencia' => 'Unidad Policial',
            'id_unidad_que_redirecciona' => 'Unidad que Redirecciona',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAdjuntoOrdenJudicials()
    {
        return $this->hasMany(AdjuntoOrdenJudicial::className(), ['id_orden_judicial' => 'id_orden_judicial']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAvisos()
    {
        return $this->hasMany(Aviso::className(), ['id_orden_judicial' => 'id_orden_judicial']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRutPersonas()
    {
        return $this->hasMany(Persona::className(), ['rut_persona' => 'rut_persona'])->viaTable('aviso', ['id_orden_judicial' => 'id_orden_judicial']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getDilgienciamientos()
    {
        return $this->hasMany(Dilgienciamiento::className(), ['id_orden_judicial' => 'id_orden_judicial']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getIdUnidadQueDirecciona()
    {
        return $this->hasOne(Unidad::className(), ['id_unidad' => 'id_unidad_que_direcciona']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getIdUnidadQueDiligencia()
    {
        return $this->hasOne(Unidad::className(), ['id_unidad' => 'id_unidad_que_diligencia']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getIdUnidadQueRedirecciona()
    {
        return $this->hasOne(Unidad::className(), ['id_unidad' => 'id_unidad_que_redirecciona']);
    }
}

And the Controller Class with the relevant action:
<?php

namespace app\controllers;

use Yii;
use app\models\OrdenJudicial;
use app\models\OrdenJudicialSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;

/**
 * OrdenJudicialController implements the CRUD actions for OrdenJudicial model.
 */
class OrdenJudicialController extends Controller
{

    (...)

    public function actionCreate()
    {

        $model = new OrdenJudicial();

        $model->estado = "En Creacion";

        $idUnidadQueDiligencia = Yii::$app->getUser()->identity->getIdUnidad();

        $model->id_unidad_que_diligencia = $idUnidadQueDiligencia;

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id_orden_judicial]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    (...)
}

A: Could be your id_unidad_que_diligencia si an object an not a single value.
$idUnidadQueDiligencia = Yii::$app->getUser()->identity->getIdUnidad();

$model->id_unidad_que_diligencia = $idUnidadQueDiligencia;

try chech this situation using
var_dump($model->id_unidad_que_diligencia)

then if is not a flat string value adjust you code for gettin the proper value.


Q: Embedding Instagram post using editor js in react-native I'm trying to embed an instagram post using editor js on react-native. I'm unable to find any approaches similar to,
https://www.npmjs.com/package/editorjs-youtube-embed
Any help would be appreciated.

A: This worked for me
Editor JS Links
Simply add as follows under tools:
embed: {
        class: Embed,
        config: {
          services: {
            instagram: true,
          },
        },
      },


Q: Is it possible to control axis number independently of tickSize? Essentially I want to draw something like this: http://i.stack.imgur.com/JEKOg.png (the gridlines, not the graph).
It seems if tickSize is set to one (below) then there are a bunch of lines drawn with their corresponding axis number below them.
xaxis, yaxis: {
    show: true,
    min: -20,
    max: 20,
    tickSize: 1,
    tickLength: 0
}

If it's not set (below), the graph'll automatically draw one every 5 units along with their numbers
xaxis, yaxis: {
    show: true,
    min: -20,
    max: 20,
    tickLength: 0
}

I want gridlines every 1 unit but numbers every 5 but I don't see a method to do it.

A: You can manually specify the tick labels with an array:
ticks: [[0, "0"], [1, ""], [2, ""], [3, ""], [4, ""], [5, "5"]],

Or, you can specify a function to do it:
ticks: function(axis) {
    var tickArray = [[0,"0"]];
    for(var i=axis.min; i<axis.max+1; i++) {
         var label = i%5?"":i;
         tickArray.push([i, label]);
    }
    return tickArray;
},

Demo: http://jsfiddle.net/jtbowden/gryozh7x/
You can also use a tickFormatter:
tickSize: 1,
tickFormatter: function (val, axis) {
    return val%5?"":val;
}

Demo: http://jsfiddle.net/jtbowden/gryozh7x/1/


Q: How to bind linesements point to xml data in WPF I have some data
<Array>
    <Element Value="30"/>
    <Element Value="50"/>
    <Element Value="10"/>
</Array>

Now I want to create a curve using this data. I think to use the LineSegments. But I can't understand how to bind the LineSegment Points to this data?
I mean, is there any syntax that helps to write instead of
<GeometryDrawing.Geometry>
  <PathGeometry>
    <PathFigure>
      <LineSegment Point="0,30"/>
      <LineSegment Point="20,50"/>
      <LineSegment Point="40,10"/>
    </PathFigure>
  </PathGeometry>
</GeometryDrawing.Geometry>

something like this:
<GeometryDrawing.Geometry>
  <PathGeometry>
    <PathFigure>
      <LineSegment Point={Binding ????}/>
    </PathFigure>
  </PathGeometry>
</GeometryDrawing.Geometry>

The main problem is how to bind the coordinates to point structure of a linesegment using binding.
Thanks in advance!

A: In stead of converting array of points into LineSegment collection, you can simply use PolyLineSegment. If the Binding just need to work intially (turn array of points to PointCollection of the PolyLineSegment intially, after that every changes made on the array of points won't trigger updating to the PolyLineSegment), you can do something like this:
public MainWindow(){
   InitializeComponent();
   //set DataContext
   //Initialize your Points here ...
   //...
   DataContext = this;
}
public Point[] Points {get;private set;}

Here is the converter used to convert the array of points to PointCollection:
public class PointArrayToPointCollection : IValueConverter {
   object IValueConverter.Convert(object value, Type targetType,
                                  object parameter, CultureInfo culture) {
      var points = value as IEnumerable<Point>;
      if(points != null) return new PointCollection(points);
      return Binding.DoNothing;
   }
   object IValueConverter.ConvertBack(object value, Type targetType,
                                      object parameter, CultureInfo culture) {
      throw new NotImplementedException();
   }
}

Then in XAML code:
<Window x:Class="yourNameSpace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:yourNameSpace"/>
  <Window.Resources>
     <local:PointArrayToPointCollection x:Key="pointsToPointCollection"/>
  </Window.Resources>
  <Image>
     <Image.Source>
        <DrawingImage>
           <DrawingImage.Drawing>
             <GeometryDrawing>
               <GeometryDrawing.Pen>
                  <Pen Brush="Red" Thickness="1"></Pen>
               </GeometryDrawing.Pen>
               <GeometryDrawing.Geometry>
                  <PathGeometry>
                    <PathFigure>
                       <PolyLineSegment Points="{Binding Points,
                          Converter={StaticResource pointsToPointCollection}}"/>
                    </PathFigure>
                  </PathGeometry>
               </GeometryDrawing.Geometry>
             </DrawingImage.Drawing>
        </DrawingImage>
     </Image.Source>
  </Image>
</Window>

This answer may not exactly solve your problem but the idea of using PolyLineSegment should point you to the right direction.
Update:
Well I just thought you need some actual code run in real application. If you need just XAML code to test (or play with) right in KXAML editor, there is no reason for you to use XML data here. Because we need exactly a PointCollection for the Points property of a PolyLineSegment, so using any other kind of data will require some conversion (which can be done only via code behind). So we can just need to specify the PointCollection as an instance right in XAML code, it can be like this:
<Page.Resources>
  <PointCollection x:Key="points">
     <Point>0,30</Point>
     <Point>20,50</Point>
     <Point>40,10</Point>
  </PointCollection>
</Page.Resources>
<Grid>
  <Grid.Background>
   <DrawingBrush>
      <DrawingBrush.Drawing>
          <GeometryDrawing>
             <GeometryDrawing.Pen>
                <Pen Brush="Red" Thickness="1"></Pen>
             </GeometryDrawing.Pen>
             <GeometryDrawing.Geometry>
                <PathGeometry>
                   <PathFigure>
                       <PolyLineSegment Points="{StaticResource points}"></PolyLineSegment>
                   </PathFigure>
                </PathGeometry>
             </GeometryDrawing.Geometry>
          </GeometryDrawing>
      </DrawingBrush.Drawing>
    </DrawingBrush>
  </Grid.Background>
</Grid>

I understand that you may have a collection of more continuous points (which can shape a nearly curvy line). If you want some perfect curve, you can try playing with BezierSegment, PolyBezierSegment, QuadraticBezierSegment, PolyQuadraticBezierSegment like this:
<Grid>
 <Grid.Background>
   <DrawingBrush Stretch="None" Viewport="0.2,0.2,0.6,0.6">
      <DrawingBrush.Drawing>
          <GeometryDrawing>
             <GeometryDrawing.Pen>
                <Pen Brush="Red" Thickness="1"></Pen>
             </GeometryDrawing.Pen>
             <GeometryDrawing.Geometry>
                <PathGeometry>
                   <PathFigure>
                       <PolyBezierSegment Points="10,10 200,150 300,30 320,10 330,-100 20,30">
                       </PolyBezierSegment>
                   </PathFigure>
                </PathGeometry>
             </GeometryDrawing.Geometry>
          </GeometryDrawing>
      </DrawingBrush.Drawing>
   </DrawingBrush>
 </Grid.Background>
</Grid>

Or you can even try using the so-called mini Path language to define the PathGeometry like this:
<Grid>
  <Grid.Background>
   <DrawingBrush Stretch="None" Viewport="0.2,0.2,0.6,0.6">
      <DrawingBrush.Drawing>
          <GeometryDrawing Geometry="M0,0 C10,10 200,150 300,30 320,10 330,-100 20,30">
             <GeometryDrawing.Pen>
                <Pen Brush="Red" Thickness="1"></Pen>
             </GeometryDrawing.Pen>
          </GeometryDrawing>
      </DrawingBrush.Drawing>
   </DrawingBrush>
  </Grid.Background>
</Grid>

The mini path language works due to the implicit GeometryConverter. You can use this mini language for PathFigureCollection (converted by PathFigureCollectionConverter) and the Data property of a Path shape.


Q: C# XML serializing with attributes for every element I want to create the following xml:
 <StartLot>
      <fileCreationDate level="7">201301132210</fileCreationDate>
      <fmtVersion level="7">3.0</fmtVersion>
 </StartLot>

Below is the Serialization code:
[Serializable]
class StartLot
{
    public fileCreationDate{get; set;}

    [XmlAttribute("level")]
    public string level = "7";

    public fmtVersion{get; set;}

    [XmlAttribute("level")]
    public string level = "7"; ??
}

Since I already declared attribute level, how do I add the last attribute?

A: You can use a wrapped class to store both values, as in the example below:
public class StackOverflow_15441384
{
    const string XML = @"<StartLot>
                               <fileCreationDate level=""7"">201301132210</fileCreationDate>
                               <fmtVersion level=""7"">3.0</fmtVersion>
                            </StartLot>";
    public class StartLot
    {
        [XmlElement("fileCreationDate")]
        public LevelAndValue FileCreationDate { get; set; }
        [XmlElement("fmtVersion")]
        public LevelAndValue FmtVersion { get; set; }
    }
    public class LevelAndValue
    {
        [XmlAttribute("level")]
        public string Level { get; set; }
        [XmlText]
        public string Value { get; set; }
    }
    public static void Test()
    {
        XmlSerializer xs = new XmlSerializer(typeof(StartLot));
        StartLot sl = (StartLot)xs.Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(XML)));
        Console.WriteLine("FCD.L = {0}", sl.FileCreationDate.Level);
        Console.WriteLine("FCD.V = {0}", sl.FileCreationDate.Value);
        Console.WriteLine("FV.L = {0}", sl.FmtVersion.Level);
        Console.WriteLine("FV.V = {0}", sl.FmtVersion.Value);
    }
}

A: I always find Linq To Xml easier to use
var xDoc = XDocument.Parse(xml); /* XDocument.Load(filename); */

var items = xDoc.Root.Descendants()
                .Select(e => new
                {
                    Name = e.Name.LocalName,
                    Level = e.Attribute("level").Value,
                    Value = e.Value
                })
                .ToList();


Q: Swift Firebase persistence I'm trying to enable Firebase Persistence but my code keeps crashing with:

terminating with uncaught exception of type NSException

I have tried the line of code under my viewDidLoad as well as under DataService but I still get the same crash. what do I need to do to resolve this problem I'm facing
import UIKit
import Firebase

class HomeTeamSelectionVC: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!

    var club: Clubs!
    var player = [Players]()
    var playerFirstName = String()
    var playerLastName = String()
    var playerSelected: Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()

        FIRDatabase.database().persistenceEnabled = true //Correct use of????

        CLUB_KEY = ""
        CLUB_KEY = club.clubKey

        tableView.dataSource = self
        tableView.delegate = self

        DataService.ds.REF_PLAYERS.queryOrdered(byChild: "clubKey").queryEqual(toValue: club.clubKey).observe(.value, with: { (snapshot) in

            print("PLAYERS_COUNT: \(snapshot.childrenCount)")
            print("PLAYERS_SNAPSHOT: \(snapshot)")

            self.player = []
            if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {

                for snap in snapshots {
                    if let playerDict = snap.value as? Dictionary<String, AnyObject> {
                        let key = snap.key

                        let players = Players(playerKey: key, dictionary: playerDict)
                        self.player.append(players)

                    }
                }
            }
            //            self.tableView.reloadData()
        }) { (error) in
            print(error.localizedDescription)
            print("CHET: local error")
        }
    }

    func numberOfSections(in tableView: UITableView) -> Int {

        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return player.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let players = player[indexPath.row]
        if let cell = tableView.dequeueReusableCell(withIdentifier: "HomeTeamPlayersCell") as? HomeTeamPlayersCell {
            cell.configureCell(players)
            return cell
        } else {
            return HomeTeamPlayersCell()
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let players: Players!
        players = player[indexPath.row]

        print (players.playerKey)
        print (players.playerFirstName)
        print (players.playerLastName)

        dismiss(animated: true, completion: nil)
    }
}

A: From Firebase documentation for persistenceEnabled property:

Note that this property must be set before creating your first Database reference and only needs to be called once per application.

As such, the standard practice is to set it once in your AppDelegate class. For instance:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    FIRApp.configure()
    FIRDatabase.database().persistenceEnabled = true
    ...
    return true

}


Q: Gmail email contents transfer to google spreadsheet I ask for help. Help me to finish the script. It is necessary to transfer the contents of mail gmail, to Google table. There is a script, but it only transfers the date and subject of the letter, and the message itself does not. Help, that it is possible to correct. Thanks
 function getGmailData() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var threads = GmailApp.search("is:unread in:inbox", 0, 1);
  for (var t=0; t<threads.length; t++) {
    sheet.appendRow([threads[t].getDate(), threads[t].getFirstMessageSubject()])
  }
}

A: How about a following modification?
Modification points :

*

*In order to retrieve messages from threads, getMessages() is used.

*In order to retrieve each message from messages retrieved by getMessages(), it retrieves using one more "for loop".

*For each mail, the Date, From, Subject and Body can be retrieved by getDate(), getFrom(), getSubject() and getPlainBody(), respecrively.

Modified script :
function getGmailData() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var threads = GmailApp.search("is:unread in:inbox", 0, 1);
  var res = [];
  for (var t=0; t<threads.length; t++) {
    var msgs = threads[t].getMessages();
    for (var u=0; u<msgs.length; u++) {
      var m = msgs[u];
      res.push([m.getDate(), m.getFrom(), m.getSubject(), m.getPlainBody()]);
    }
  }
  sheet.getRange(sheet.getLastRow() + 1, 1, res.length, res[0].length).setValues(res);
}

If I misunderstand your question, I'm sorry.
Edit :
When you want to retrieve mails from today, you can use newer_than: and after: operators.
In the case of using newer_than:
var threads = GmailApp.search("newer_than:1d in:inbox", 0, 1);

In the case of using after:
var today = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'yyyy/MM/dd');
var threads = GmailApp.search("after:" + today + " in:inbox", 0, 1);


Q: FilteredPaste.js working with textarea I am working with jQuery plugin called FilteredPaste.js that removes all HTML elements when copy and pasted to a input. I want to apply it to textarea element but it does not seems to work. Nothing gets pasted. The example uses contenteditable but I need to use textarea instead. Or any alternative plugin suggestion is welcome.
Here is what I have so far.
  jQuery(document).ready(

    function() {

        $("#content").filteredPaste({
            "filters" : ["default"]
        });

    }
  );

http://jsfiddle.net/9M3vh/


Q: Creating menu for NSSegmentedControl using XIB How do we create menu for a particular segment using xib for NSSegmentedControl ?

A: You just drag an NSMenu from the object library and release it over the segment you want it to be attached to.


Q: While loggin in via fb to website, my function TestApi doesn't collect user data I am trying to create login via facebook on the website. Unfortunately, while user is logged in and the function TestAPI() is triggered, I can't get the data from the user.
 function TestAPI(){
   FB.api('/me?fields=id,name,email', function response (){
     if (response && !response.error){
       console.log(response);
       buildProfile (response);
     }
   })
 }

 function buildProfile(user){
   let profile = `

 $(user.name)

 $(user.id)

 $(user.email)
`;

   document.getElementById('profile').innerHTML = profile;
 }

I've got following communicates in console:
sdk.js:108 Uncaught TypeError: Cannot set property 'innerHTML' of
null
at buildProfile (volunteer_system.html:65)
at response (volunteer_system.html:50)
at a.__wrapper.a.__wrapper (sdk.js:108)
at D (sdk.js:123)
at Object.b.onload (sdk.js:119)
at sdk.js:119
at sdk.js:50
at XMLHttpRequest.c.onreadystatechange (sdk.js:119)

A:
I get the function instead of data

console.log(response);
This prints out the function instead of the response data, because response is the name of your function, not the name of the argument passed to the function. Consider the change below:
function TestAPI() {
    FB.api('/me?fields=id,name,email', function(response) {
        if (response && !response.error) {
            console.log(response);
            buildProfile (response);
        }
   });
}

TypeError: Cannot set property 'innerHTML' of null

This means that document.getElementById('profile') is returning null, it's possible that an element with this id does not exist in your DOM, but this is difficult to confirm without you sharing a code excerpt of the HTML you're trying to modify. You should have an element that looks something like this:


Q: Ember: How to link to sections and actions (without nesting routes) Let's say that I have a blog where each post can have several sections and comments and I'd like to use a hard-links to navigate and operate on this. There are several samples using some pseudo-code, of course they doesn't work, just demonstring my intends :)
Of course /blog.html#/posts/1 uses PostRoute, PostController etc and uses :post_id for finding object - that's obvoius.

*

*How can I pass (and then access) additional params which doesn't change the controller but I can use them to navigation. ie /blog.html#/posts/1?section=123 should use the same route, controller and view as it was just Post, but I'd like to read the section and just navigate to section with #123

*/blog.html#/posts/1/?comments=456 - actually should behave like section from point 1, but navigates to comment and optionally add some class to the container.

*Other case: I'd like to go to section 123 AND additionally edit it with link like: /blog.html#/posts/1?section=123&action=edit. Now I'm using a button with an action like {{action editSection section}} and {{#if isEdit}} but I'd like to be able to reflect this in URL and also go to this state from URL (de facto my post can have several different modes not only preview/edit, therefore it should be accesible by the link).

I hope that cases makes sense, TBH I have no idea in which direction should I go. Tried with nested routes, but I'd like to avoid changing the controller. Also have no concept how to reflect the action in the URL...
I'm using Ember 1.1.2

A: You can use the model method of the route to handle such parameters, separate them from the model parameter and set the appropriate controller state.
Another approach would be to use nested routes that will render un-nested views(and controllers) - as explained towards the bottom here.


Q: Trying to toggle style CSS link "href" on click Jquery Trying to do a dark-mode toggle on click of element

*

*toggle div class = .dark__mode

*css link class = .css-link

*css link href variable = style__old

I am learning jquery and i think there is a major problem with reasoning and structure of code
The link href changes at first but doesn't change back
Please help and or if using a checkbox option is better
window.onload = function(){

    var  style__old = $(".css-link").attr("href");

    $(".dark__mode").click(function(){

            if (style__old == "css/style.css"){
                var style__new = style__old.replace("style.css","dark-mode.css");
                $(".css-link").attr("href", style__new);
            }
            else
            if (style__old == "css/dark-mode.css"){
                style__old.replace("dark-mode.css","style.css");
                $(".css-link").attr("href", "style__old");
            }
    }

);}

A: The approach you're using of dynamically changing the loaded stylesheet is not very reliable.
A much better approach is to put all the relevant styles in to the page, in separate stylesheets, then toggle() a class on a low level element, such as the body, and hang all your selectors off that.
In practice it would look something like this:

jQuery($ => {
  $('.dark__mode').on('click', (e) => {
    e.preventDefault();
    $('body').toggleClass('dark');
  })
});
/* Normal layout */
div { color: #0C0; }
a { color: #C00; }

/* Dark layout */
body.dark {
  background-color: #333;
  color: #FFF;
}
body.dark div { color: #CCC; }
body.dark a { color: #CC0; }

Toggle

Lorem ipsum dolor sit

  Amet consectetur adipcing elit


Q: How can I determine the window controlled by an instance of NSWindowController ? How can I determine the window controlled by an instance of NSWindowController ? According to Apple's docs, sending the controller the 'window' accessor message returns  "The window owned by the receiver."  But when I use it on an instance loaded from a NIB via initWithWindowNibPath:owner: it always returns 0.
I've searched unsuccessfully through Apple's AppKit docs for another message that might work better. (It's possible that a function that returns the content _view for the window in question would also work, since my ultimate goal is to be able to access the contained Views via their Tag fields.)
Maybe I'm misunderstanding the purpose of this window accessor? If so, is there a method that will allow me to determine the actual window controlled by my NSController instance?
thanks


Q: Show loading image on redirection I have two pages x.php and y.php, I am redirecting the page x.php to y.php. I am redirecting the  page by form post method.
y.php is pulling some more data from mysql database and it is taking 3 to 4 seconds to load that page, I need to show progress bar (loading image) while page loads.
This is what, I am doing,
a html page is submitting to remote server x.PHP page and x.PHP page is pulling data from mysql database and based on the type of data it redirects to y.PHP, this redirection is done by automatic form submit using Javascript.
I need to show loading image on both html to x.php and x.php to y.php.
I tried with echoing image tag on top of x.PHP page, it is working in Mozilla and not an other browsers.
How can I achieve this; can anyone help me?

A: I think that the only way to do this is to use AJAX - either on x.php to load y.php, or on y.php to load data.

A: you need to use jquery.  ı am using this code for that.
when your request start its load a loading image to page. when data return with success function it loading the data to page.
    $('#something').change(function(){ // change, click doesnt matter

    $('#load').html(""); // loading img

    $.post(
            'select.php?do=load', // your y.php
            {s:value},
            function(answer){

            $('#load').html("");
            $('#page').html(answer);

            }
    );

});

A:
Hope it helps


Q: Screen Resolution CentOS 8 - VMware System: CentOS8
I am using VMware ESXi
I can easily change a resolution to 1400x1050, but after reboot/shutdown returns to default resolution (800x600).
I set the .vmx file settings:
svga.vramSize = "67108864"
svga.minWidth="1400"
svga.minHeight="1050"
svga.maxWidth="1400"
svga.maxHeight="1050"
svga.autodetect = "FALSE" -- changing to "TRUE" it doesn't help either

A: Ok... So just for information.
Solution (workaround) is:
When logging in (entering the password), select the cog and change from:
Standard (Wayland display server)
to
Classic (X11 display server)
then the last selected correct resolution will automatically be loaded.
This option will also be remembered after reboot (Classic)


Q: Sample code for unit testing api controllers Is there an sample code that shows unit testing a controller that inherits from the api controller?
I am trying to unit test a POST but it is failing. I believe I need to set up the HttpControllerContext for testing but don't know how
Thanks

A: this code should demonstrate the basics of a post test. Assumes you have a repository injected into the controller. I am using MVC 4 RC not Beta here if you are using Beta the Request.CreateResponse(... is a little different so give me a shout...
Given controller code a little like this:
public class FooController : ApiController
{
    private IRepository<Foo> _fooRepository;

    public FooController(IRepository<Foo> fooRepository)
    {
        _fooRepository = fooRepository;
    }

    public HttpResponseMessage Post(Foo value)
    {
        HttpResponseMessage response;

        Foo returnValue = _fooRepository.Save(value);
        response = Request.CreateResponse<Foo>(HttpStatusCode.Created, returnValue, this.Configuration);
        response.Headers.Location = "http://server.com/foos/1";

        return response;
    }
}

The unit test would look a little like this (NUnit and RhinoMock)
        Foo dto = new Foo() {
            Id = -1,
            Name = "Hiya"
        };

        IRepository<Foo> fooRepository = MockRepository.GenerateMock<IRepository<Foo>>();
        fooRepository.Stub(x => x.Save(dto)).Return(new Foo() { Id = 1, Name = "Hiya" });

        FooController controller = new FooController(fooRepository);

        controller.Request = new HttpRequestMessage(HttpMethod.Post, "http://server.com/foos");
        //The line below was needed in WebApi RC as null config caused an issue after upgrade from Beta
        controller.Configuration = new System.Web.Http.HttpConfiguration(new System.Web.Http.HttpRouteCollection());

        var result = controller.Post(dto);

        Assert.AreEqual(HttpStatusCode.Created, result.StatusCode, "Expecting a 201 Message");

        var resultFoo = result.Content.ReadAsAsync<Foo>().Result;
        Assert.IsNotNull(resultFoo, "Response was empty!");
        Assert.AreEqual(1, resultFoo.Id, "Foo id should be set");

A: Using AutoFixture, I usually do something like this:
[Theory, AutoCatalogData]
public void PostToCollectionReturnsCorrectResponse(
    CategoriesController sut,
    CategoryRendition categoryRendition)
{
    HttpResponseMessage response = sut.Post(categoryRendition);

    Assert.Equal(HttpStatusCode.Created, response.StatusCode);
}

See this other SO answer for more details about this approach.

A: Sample code for unit testing API controller with async fundtion in C#

*

*Prepare test Models:
        using System;
        namespace TestAPI.Models
        {
            public class TestResult
            {
                public DateTime Date { get; set; }
                public bool Success { get; set; }
                public string Message { get; set; }
            }
        }

*Prepare test controller
        using TestAPI.Models;
        using System;
        using System.Net;
        using System.Threading.Tasks;
        using System.Web.Http;
        using System.Web.Http.Description;

        namespace TestAPI.Controllers
        {
            public class TestController : ApiController
            {
                public TestController()
                {
                }

                [HttpPost]
                [ResponseType(typeof(TestResult))]
                [Route("api/test/start")]
                public async Task<IHttpActionResult> StartTest()
                {
                    DateTime startTime = DateTime.Now;
                    var testProcessor = new TestAsync();
                    await testProcessor.StartTestAsync();

                    HttpStatusCode statusCode = HttpStatusCode.OK;
                    return Content(statusCode, new TestResult
                    {
                        Date = DateTime.Now,
                        Success = true,
                        Message = "test"
                    });
                }

            }
        }

*unit test async controller with result check from response
        using Microsoft.VisualStudio.TestTools.UnitTesting;
        using TestAPI.Controllers;
        using TestAPI.Models;
        using System.Web.Http;
        using System.Threading.Tasks;
        using System.Net;
        using System.Web.Script.Serialization;

        namespace Unit.Tests.Controllers
        {
            /// <summary>
            /// Summary description for ControllerTest
            /// </summary>
            [TestClass]
            public class ControllerTest
            {
                private TestController _testController;
                [TestInitialize]
                public void estAPI_Initializer()
                {
                    _testController = new TestController();
                    var configuration = new HttpConfiguration();
                    System.Net.Http.HttpRequestMessage request = new System.Net.Http.HttpRequestMessage();
                    request.Headers.Add("Authorization", "Bearer 1232141241");
                    request.Headers.Add("ContentType", "application/json");
                    _testController.Request = request;
                    _testController.Configuration = configuration;
                }

                [TestCategory("Unit test")]
                [TestMethod]
                public async Task API_Async_Controller_Test()
                {
                    IHttpActionResult asyncResponse = await _testController.StartTest();
                    var cToken = new System.Threading.CancellationToken(true);
                    var rResult = asyncResponse.ExecuteAsync(cToken);
                    Assert.IsNotNull(rResult);
                    Assert.IsNotNull(rResult.Result);
                    Assert.AreEqual(rResult.Result.StatusCode, HttpStatusCode.OK);
                    Assert.IsNotNull(rResult.Result.Content);
                    var rContent = rResult.Result.Content;

                    string data = await rContent.ReadAsStringAsync();
                    Assert.IsNotNull(data);
                    JavaScriptSerializer JSserializer = new JavaScriptSerializer();
                    var finalResult = JSserializer.Deserialize<TestResult>(data);

                    Assert.IsNotNull(finalResult);
                    Assert.IsTrue(finalResult.Success);
                }
            }
        }

A: I've created a general solution for calling some action and getting HttpResponseMessage as Dictionary which is very convenient for usage.
First some extension for the dictionary:
public static class DictionaryExtensions
{
    public static void AddRange<T, S>(this Dictionary<T, S> source,
                                      Dictionary<T, S> collection)
    {
        if (collection == null)
        {
            throw new NullReferenceException("Collection is null");
        }

        foreach (var item in collection)
        {
            source.Add(item.Key, item.Value);
        }
    }
}

Now request creating part:
public class RequestCreator
{
    protected static void FirstPart(ApiController controller,
                                    HttpMethod method,String actionUrl)
    {
        // Creating basic request message with message type and requesting
        // url example : 'http://www.someHostName/UrlPath/'
        controller.Request = new HttpRequestMessage(method, actionUrl);

        // Adding configuration for request
        controller.Request.Properties.
          Add(HttpPropertyKeys.HttpConfigurationKey,new HttpConfiguration());
    }

    protected static Dictionary<String, Object> SecondPart
                                                 (HttpResponseMessage response)
    {
        // Adding basic response content to dictionary
        var resultCollection = new Dictionary<String, Object>
        {
            {"StatusCode",response.StatusCode},
            {"Headers",response.Headers},
            {"Version",response.Version},
            {"RequestMessage",response.RequestMessage},
            {"ReasonPhrase",response.ReasonPhrase},
            {"IsSuccessStatusCode",response.IsSuccessStatusCode}
        };

        var responseContent = response.Content;
        // If response has content then parsing it and
        // getting content properties
        if (null != responseContent)
        {
            var resultMessageString = response.Content.
                                               ReadAsStringAsync().Result;
            resultCollection.AddRange((new JavaScriptSerializer()).
                                       DeserializeObject(resultMessageString)
                                               as Dictionary<String, Object>);
        }

        return resultCollection;
    }
}

And finally response message to dictionary converter class:
public class HttpResponseModelGetter : RequestCreator
{
    public Dictionary<String, Object>
                 GetActionResponse(ApiController controller,HttpMethod method,
                          String actionUrl,Func<HttpResponseMessage> callBack)
    {
        FirstPart(controller, method, actionUrl);
        var response = callBack();
        return SecondPart(response);
    }
}

public class HttpResponseModelGetter<T> : RequestCreator
{
    public Dictionary<String, Object>
             GetActionResponse(ApiController controller,HttpMethod method,
                String actionUrl,Func<T,HttpResponseMessage> callBack,T param)
    {
        FirstPart(controller, method, actionUrl);
        var response = callBack(param);
        return SecondPart(response);
    }
}

public class HttpResponseModelGetter<T1,T2> : RequestCreator
{
    public Dictionary<String, Object>
        GetActionResponse(ApiController controller,HttpMethod method,
             String actionUrl,Func<T1,T2,HttpResponseMessage> callBack,
             T1 param1,T2 param2)

    {
        FirstPart(controller, method, actionUrl);
        var response = callBack(param1,param2);
        return SecondPart(response);
    }
}
//and so on...

and usage :
var responseGetter = new HttpResponseModelGetter();
var result = responseGetter.GetActionResponse(controller,HttpMethod.Get,
                    "http://localhost/Project/api/MyControllerApi/SomeApiMethod",
                                              controller.SomeApiMethod);

Boolean isComplete = Boolean.Parse(result["isComplete"].ToString());


Q: ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[NavbarComponent -> NavbarComponent I am trying to make a login with google Auth on Firebase and when I login and try to load another component or a page I get the following. I have been trying to fix this bug for a whole day now and am very fed up. If anyone could help it would be appreciated.
My entire project is public at https://github.com/domilx/ProjetBocal-Angular
ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[NavbarComponent -> NavbarComponent -> NavbarComponent]:
  NullInjectorError: No provider for NavbarComponent!
get@http://localhost:4200/vendor.js:120414:27

Here is my code
Navbar.component.html:

  <mat-toolbar color="primary">
    <button routerLink="dashboard" mat-button aria-label="Home">
      <mat-icon>home</mat-icon>
      Projet Bocal
    </button>

    <button mat-button aria-label="Classroom">
      <mat-icon>class</mat-icon>
      Classroom
    </button>

    <button mat-button aria-label="Links">
      <mat-icon>links</mat-icon>
      Links
    </button>

    <button mat-button aria-label="Logout" *ngIf="auth.user$ | async as user" (click)="auth.signOut()">
      <mat-icon>exit_to_app</mat-icon>
      Logout, {{ user.displayName }}
    </button>

    <button routerLink="settings" mat-icon-button aria-label="settings" *ngIf="auth.user$ | async as user">
      <mat-icon>settings</mat-icon>
    </button>

  </mat-toolbar>

Auth.service.ts
import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/compat/firestore';
import { Router } from '@angular/router';
import { Observable, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { User } from './user.model';
import { AngularFireAuth }  from '@angular/fire/compat/auth';
import { GoogleAuthProvider } from 'firebase/auth';

@Injectable({ providedIn: 'root' })
export class AuthService {
  user$: Observable<User | null | undefined>;
  constructor(
    private afAuth: AngularFireAuth,
    private afs: AngularFirestore,
    private router: Router,
  ) {
    this.user$ = this.afAuth.authState.pipe(
      switchMap(user => {
        if (user) {
          return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
        } else {
          return of(null);
        }
      })
    );
  }

  async googleSignin() {
    const provider = new GoogleAuthProvider();
    const credential = await this.afAuth.signInWithPopup(provider);
    return this.updateUserData(credential.user);
  }

  async signOut() {
    await this.afAuth.signOut();
    return this.router.navigate(['/']);
  }

  private updateUserData(user) {
    // Sets user data to firestore on login
    const userRef: AngularFirestoreDocument<User> = this.afs.doc(`users/${user.uid}`);

    const data = {
      uid: user.uid,
      email: user.email,
      displayName: user.displayName,
      photoURL: user.photoURL
    };

    return userRef.set(data, { merge: true });

  }
}

Auth.guard.ts
import { Injectable } from '@angular/core';
import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  Router
} from '@angular/router';
import { Observable } from 'rxjs';

import { AuthService } from './auth.service';
import { tap, map, take } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private auth: AuthService, private router: Router) {}

  canActivate(next, state): Observable<boolean> {
    return this.auth.user$.pipe(
      take(1),
      map(user => !!user), // <-- map to boolean
      tap(loggedIn => {
        if (!loggedIn) {
          console.log('access denied');
          this.router.navigate(['/']);
        }
      })
    );
  }
}

App.module.ts
import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { initializeApp, provideFirebaseApp } from '@angular/fire/app';
import { getAuth, provideAuth } from '@angular/fire/auth';
import { AngularFireModule } from '@angular/fire/compat';
import { AngularFireAuthModule } from '@angular/fire/compat/auth';
import { AngularFireDatabaseModule } from '@angular/fire/compat/database';
import { AngularFirestoreModule } from '@angular/fire/compat/firestore/';
import { getFirestore, provideFirestore } from '@angular/fire/firestore';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RouterModule } from '@angular/router';
import { environment } from '../environments/environment';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AboutComponent } from './components/pages/about/about.component';
import { ContactComponent } from './components/pages/contact/contact.component';
import { ClassroomComponent } from './components/pages/dashboard/classroom/classroom.component';
import { DashboardComponent } from './components/pages/dashboard/dashboard/dashboard.component';
import { LinksComponent } from './components/pages/dashboard/links/links.component';
import { HomeComponent } from './components/pages/home/home.component';
import { SettingsComponent } from './components/pages/settings/settings.component';
import { FooterComponent } from './components/shared/footer/footer.component';
import { NavbarComponent } from './components/shared/navbar/navbar.component';
import { MaterialModule } from './material.module';
import { AuthService } from './services/auth.service';
import { AuthGuard } from './services/auth.guard';

@NgModule({
  declarations: [
    AppComponent,
    NavbarComponent,
    FooterComponent,
    AboutComponent,
    SettingsComponent,
    ContactComponent,
    DashboardComponent,
    HomeComponent,
    ClassroomComponent,
    LinksComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    RouterModule,
    MaterialModule,
    FormsModule,
    ReactiveFormsModule,
    HttpClientModule,
    AngularFireAuthModule,
    AngularFirestoreModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireDatabaseModule,
    provideFirebaseApp(() => initializeApp(environment.firebase)),
    provideFirestore(() => getFirestore()),
    provideAuth(() => getAuth()),

  ],
  providers: [
    AngularFirestoreModule,
    AngularFireModule,
    AngularFireAuthModule,
    AngularFireDatabaseModule,
    AuthGuard,
    AuthService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

App-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { SettingsComponent } from './components/pages/settings/settings.component';
import { AboutComponent} from './components/pages/about/about.component';
import { ContactComponent} from './components/pages/contact/contact.component';
import { DashboardComponent } from './components/pages/dashboard/dashboard/dashboard.component';
import { HomeComponent } from './components/pages/home/home.component';
import { AuthGuard } from './services/auth.guard';

const routes: Routes = [
  {path:'', component:HomeComponent},
  {path:'settings', component:SettingsComponent,  canActivate: [AuthGuard] },
  {path:'home', redirectTo:'/', pathMatch:'full'},
  {path:'about', component:AboutComponent,  canActivate: [AuthGuard] },
  {path:'contact', component:ContactComponent,  canActivate: [AuthGuard] },
  {path:'dashboard', component:DashboardComponent,  canActivate: [AuthGuard] },
];
  @NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
  })
export class AppRoutingModule { }

navbar.component.ts
import { Component, OnInit } from '@angular/core';
import { RouterModule } from '@angular/router';
import { AuthService } from '../../../services/auth.service';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {

  constructor(public auth: AuthService) { }
  ngOnInit(): void {
  }

}

A: I found the issue..
In my dashboard.component.ts I had imported the NavBar for test a long while ago and forgot to remove it:
import { NavbarComponent } from './../../../shared/navbar/navbar.component';
import { Component, OnInit,EventEmitter,Output } from '@angular/core';
import { RouterModule } from '@angular/router';
import { AuthService } from '../../../../services/auth.service';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {

  @Output() isLogout = new EventEmitter<void>()
  constructor(NavbarComponent : NavbarComponent, public auth: AuthService) { }

  ngOnInit(): void {

  }

}

Just had to remove
NavbarComponent : NavbarComponent


Q: Insert Multiple Array in Array to Store in Cart CodeIgniter I have array from foreach loop like this :
Array (
    [id] => 2
    [qty] => 1
    [price] => 130000
    [name] => 0002/PNBP/411971/1/02/18
)
Array (
    [id] => 3
    [qty] => 1
    [price] => 120000
    [name] => 0003/PNBP/411971/1/02/18
)
Array (
    [id] => 4
    [qty] => 1
    [price] => 150000
    [name] => 0004/PNBP/411971/1/02/18
)

I want insert data array in array like this :
Array(
    Array (
        [id] => 2
        [qty] => 1
        [price] => 130000
        [name] => 0002/PNBP/411971/1/02/18
    ),
    Array (
        [id] => 3
        [qty] => 1
        [price] => 120000
        [name] => 0003/PNBP/411971/1/02/18
    ),
    Array (
        [id] => 4
        [qty] => 1
        [price] => 150000
        [name] => 0004/PNBP/411971/1/02/18
    )
);

I try and code like this :
$data = array();
foreach ($_POST['id_kuitansi'] as $id_kuitansi){
    $detail_kuitansi = $this->kuitansi_model->detail($id_kuitansi);
    $i = $this->input;
    $data = array(
      'id' => $id_kuitansi,
      'qty' => '1',
      'price' => $detail_kuitansi['nilai'],
      'name' => $detail_kuitansi['no_kuitansi']
    );
    print_r($data);
    //$this->cart->insert($data);
}

A: Try this,
$data = array();
foreach ($_POST['id_kuitansi'] as $id_kuitansi){
    $detail_kuitansi = $this->kuitansi_model->detail($id_kuitansi);
    $i = $this->input;
    $data[] .= array(
      'id' => $id_kuitansi,
      'qty' => '1',
      'price' => $detail_kuitansi['nilai'],
      'name' => $detail_kuitansi['no_kuitansi']
    );
    print_r($data);
    //$this->cart->insert($data);
}

You were simply reassigned the values to $data each while you need to append the array value to the $data array

A: Problem solved with this code :
foreach ($_POST['id_kuitansi'] as $id_kuitansi)
{
    $detail_kuitansi = $this->kuitansi_model->detail($id_kuitansi);
    $i = $this->input;
    $data[] = array(
      'id' => $id_kuitansi,
      'qty' => '1',
      'price' => $detail_kuitansi['nilai'],
      'name' => $detail_kuitansi['no_kuitansi']
    );
}
//print_r($data);
$this->cart->insert($data);

Thanks Mohammad...

A: whenever we need to insert multiple data in single query, then we can user batch for inserting data. such as,
$data = $arrInsert = array();
foreach ($_POST['id_kuitansi'] as $id_kuitansi){
    $detail_kuitansi = $this->kuitansi_model->detail($id_kuitansi);
    $i = $this->input;
    $data = array(
      'id' => $id_kuitansi,
      'qty' => '1',
      'price' => $detail_kuitansi['nilai'],
      'name' => $detail_kuitansi['no_kuitansi']
    );
    //print_r($data);
    $arrInsert[] = $data;
    //$this->cart->insert($data);
}
$this->db->insert_batch('tableName', $arrInsert);

In insert batch you can replace tableName with your table name.


Q: How to compare two sentences by considering the space only in dynamic portion? I need to compare two sentences. First one is defined in a database like below.
var text1 = "Dear {#dynamic#} {#dynamic#} Welcome to MAX private ltd"

Then the text which comes from customer is given below.
"var text2 = "Dear joe harry Welcome to MAX private ltd"

Here in place of dynamic there could be any value that customer can substitute and send as an input ( 0- 10) is the character limit for dynamic content.
I need to compare both the sentences and return the response. Problem here is, we should not consider spaces in the other portion of the sentence except for dynamic part. For example,
   "var text3 = "Dear joe harry Welcome to MA Xprivatel td"

While comparing text1 with text3 , it should be valid even though we have spaces near the MA Xprivatel td". But for dynamic portion , if {#dynamic#}{#dynamic#} comes continuously, it can be 20 characters max including spaces. If two
{#dynamic#} {#dynamic#} with spaces, max character limit can be 21 including spaces.
My current code is below,
   text1 = text1.replace(/(^|.)\s($|.)/g, (x, g1, g2) => (x == "} {" ? "}\\s+{" : g1 + "\\s\*" + g2));
   var separators_regex = /{#dynamic#}|((\s\*))/gi;
   text1= text1.replace(separators_regex, (x, y) => y ? y : ".{0,10}");
   let regex1 = RegExp("^" + text1+ "$", "i");
   if (!regex1.test(text2)) {  // or regex1.test(text3)
        Status = "Fail"
    }

Whatever I try, at some scenario it is failing. The above code is failing for text3.
Im stuck with these for too long. Can anybody please help me with this?

A: You can use

var text2 = "Dear 1234567890 12345678901 Welcome to MAX private ltd"
var text1s = ["Dear {#dynamic#} {#dynamic#} Welcome to MAX private ltd {#dynamic#}"];
var text2 = "Dear joe harry Welcome to MAX private ltd";
for (var text1 of text1s) {
  var rx = new RegExp(text1.replace(/\s*(\{#dynamic#}(?:\s*\{#dynamic#})*)/g, (x, y) =>
    '\\s*.{0,' + ((y.match(/\{#dynamic#}/g) || ['']).length * 10 + (y.match(/\s/g) || '').length) + '}'))
  console.log(rx)
  console.log(rx.test(text2))
}

This means:

*

*Sequences of possibly whitespace-separated {#dynamic#} chunks are replaced with the necessary .{0,x} patterns

*If there are spaces in between, these are added up to x

*If there are leading whitesapces, they will be made optional, \s* will replace any amount of whitespaces.


Q: Function decide where to store the pallets I would like to store the pallets into pallet rack "PRD6" if my typeID = 1, else I would like to store them into pallet rack "PRD7". My agent type is Pallet. I don't know how to build up the function. I'm currently learning java basics but I don't know either how to declare the variables. I read it in the help document but it doesn't help. Thank you for helping.

A: the correct syntax is the following:
agent.typeID==1 ? PRD6 : PRD7

but if you have lots of options, you should call a function here that returns a PalletRack and generate the if/else statement in that function


Q: Opened mat-menu items should be close after other mat-menu items clicked (i.e should be act as an mat-tab) Opened mat-menu items should be closed when other mat-menu items clicked ...
And i tried Mat-trigger methods but no use in that
Here is the code
In that I used an reusable component to trigger data of mat-menu items through @Input and I need an functionality like as mat-tab methods for these code .
When I use trigger method trigger.toArray().forEach its not looped to another items its looped for once only,So I cant set that correctly
<ng-container *ngIf="!child">
    <div
        class="sample"
        [matMenuTriggerFor]="matMenu"
        [matMenuTriggerData]="item"
        #trigger="matMenuTrigger" >
        <ng-container *ngTemplateOutlet="itemTemplate; context: {$implicit: item}"></ng-container>
    </div>
</ng-container>

<mat-menu  backdropClass="custom__menu"
    [overlapTrigger]="false"
    #matMenu="matMenu" xPosition="before" >

    <ng-container *ngFor="let item of item.children;">

        <ng-container *ngIf="(item.hidden && !item.hidden(item)) || !item.hidden">

            <!-- Basic -->
            <ng-container *ngIf="item.type === 'basic'" >
                <div

                    [disabled]="item.disabled"
                    mat-menu-item>
                    <horizontal-navigation-basic-item
                        [item]="item"
                        [name]="name"></horizontal-navigation-basic-item>
                </div>
            </ng-container>

        </ng-container>

    </ng-container>

</mat-menu>

<ng-template
    let-item
    #itemTemplate>

    <div
       (click)="triggerChangeDetection(item)"

     </div>

 </ng-template>


Q: Label position and size i have a network of labeled nodes based on sizes. But I can't get the labels to be smaller and off the node and not overlapping.
import networkx as nx
import matplotlib.pyplot as plt

"Create a Blank Graph Page"
G = nx.Graph()

"Single Node"
#G.add_node(1)
#G.add_node(2)

"Single Edge"
#G.add_edge(1,2)

"Many Nodes"
NxNodeList = ["fish","water","and","in","plant","of","to","aquarium","rock","blue","relationship","tank","are","is","swimming","color","for","yellow","coral","with","good","other","ecosystem","different","environment","fishtank","that","between","green","need","be","filter","goldfish","on","each","orange","living","can","oxygen","school","small","there","it","life","live","red","rule","see","together","dependent","many","species","they","family","gravel","have","pebbles","same","algae","all","around","community","don't","provides","underwater","decorations","eats","feed","food","must","none","some","survive","animals","big","cleans","grass","habitat","hide","home","keeps","know","large","like","mates","reaction","reef","saltwater","sand","so","stone","system","this","types","white","alive","aquatic","filled","from","glass","group","has","humans","nature","or","seaweed","their","them","tree","air","allows","along","beautiful","bottom","breathe","by","cannot","circulating","cooperating","direction","exist","friendly","give","grey","harmony","into","items","light","love","made","makes","mom","ocean","owner","person","place","places","plastic","produce","sea","structure","sure","symbiosis","things","through","up","variety","1","2","3","act","action","applies","as","away","because","broke","bunch","caretakers","clear","coexisting","creatures","dad","decoration","do","either","excellent","flower","form","full","getting","great","greenery","grouper","grow","healthy","helping","homes","how","inside","interact","just","lets","lighting","lights","little","marriage","me","merge","more","multiple","near","not","part","pet","picture","pipe","plankton","plants","pretty","pump","react","rely","schools","sealife","seaweeds","seem","seen","shelter","similar","smaller","space","still","supply","survival","swim","symbiotic","then","therefore","unity","varying","vase","very","waste","well","without","yet","6","able","adapt","adds","aerator","alabaster","alone","also","any","apart","apparently","appear","appears","applicable","archive","arrived","at","attention","awesome","baby","back","based","being","belong","best","biology","bit","blend","boring","bright","bubbles","builded","bushes","called","captivity","carnivorous","cave","chain","change","cleaning","coexistence","cohabiting","collar","comfortable","compatible","complex","conditions","confused","connected","contrast","cool","create","decor","designs","dippy","direct","dishes","distance","distract","docile","dropped","ecological","enjoy","enjoyment","entertain","essential","etc","evenly","everything","exhale","fake","falls","farmer","fauna","feel","female","few","find","fishbowl","fishing","floor","flowing","flows","freely","fresh","freshwater","functioning","gang","gather","get","gills","go","golden","grew","groovy","groups","growing","hand","happy","he","help","helps","here","hides","hiding","hippy","hold","holding","holds","holes","homeowners","household","idea","imprison","improve","including","incredibly","inductive","interested","interesting","job","join","jug","kinds","larger","leaves","lit","lonely","lots","loving","lucky","maintain","male","marine","matter","may","maybe","medium","most","motion","multicolored","needed","no","nome","nothing","office","offspring","ok","one","ones","organisms","ornamental","ornaments","others","outside","parent","partners","parts","peacefully","peer","perspective","pink","pitcher","plantlife","play","pot","pots","predators","principle","prisoners","pvc","real","really","reed","relies","rest","right","salinity","salt","science","screensaver","seabed","seagrass","seeing","settled","several","share","shark","shine","sibling","side","single","size","smooth","someone","spaced","stay","stripe","substrate","supplies","supplying","supports","sweet","take","tandem","temperature","than","thermometer","these","think","three","thrive","tolerate","too","top","toward","trees","tubes","under","undersea","understand","unsure","upon","used","uses","usually","various","vegetation","viewed","wallpaper","walls","want","what","which","work","world","you","your"]
G.add_nodes_from(NxNodeList)

node_sizes = [404,154,79,67,62,61,61,56,49,41,41,40,32,30,28,26,24,23,21,20,19,19,17,16,16,16,16,15,15,15,14,14,14,14,13,13,12,11,11,11,11,11,10,10,10,10,10,10,10,9,9,9,9,8,8,8,8,8,7,7,7,7,7,7,7,6,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,4,4,4,4,4,4,4,4,4,4,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]

"Draw and Show Graph"
nx.draw(G,with_labels=True,node_size=node_sizes)
plt.savefig("NetworkGraph_part1.png")

Which creates this mess:
enter image description here

A: You must specify figsize together with dpi to get the plot big enough and has proper resolution. For the text's size, specify smaller font_size. For example, the relevant code is as follows:-
fig, ax = plt.subplots(figsize=(12,9), dpi=360)
nx.draw(G, with_labels=True, node_size=node_sizes, font_size=4)


Q: print all SubClass in a SuperClass and all SuperClass in a SubClass I want in SuperClass print all subClasses and in a subClasses  print all SuperClasses:
class SuperClass():
    def Print(self):
        print('my sub classes are : ')
        #print all childs

class Sub1(SuperClass,...):
    def Print(self):
        print('My parents are :')
        #print all SuperClasses

class Sub2(SuperClass,...):
    def Print(self):
        print('My parents are :')
        #print all SuperClasses

SuperClass has Print that print all classes that inherit from , and Sub  has Print method that print all his SuperClasses . how do that ?

A: Python classes have three attributes that help here:

*

*class.__subclasses__(); a method that returns all subclasses of the class.

*class.__bases__, a tuple of the direct parent classes of the current class.

*class.__mro__, a tuple with all classes in the current class hierarchy. Find the current class object in that tuple and everything following is a parent class, directly or indirectly.
Using these that gives:
class SuperClass(object):
    def print(self):
        print('my sub classes are:', ', '.join([
            cls.__name__ for cls in type(self).__subclasses__()]))

class Sub1(SuperClass):
    def print(self):
        print('My direct parents are:', ', '.join([
            cls.__name__ for cls in type(self).__bases__]))
        all_parents = type(self).__mro__
        all_parents = all_parents[all_parents.index(Sub1) + 1:]
        print('All my parents are:', ', '.join([
            cls.__name__ for cls in all_parents]))

Demo:
>>> SuperClass().print()
my sub classes are: Sub1
>>> Sub1().print()
My direct parents are: SuperClass
All my parents are: SuperClass, object


Q: Reset form to empty values new to redux-form... I was looking at an example from redux-form docs where one can initialize form values from initialValues (forked example here: https://codesandbox.io/s/6v3n9lwnpr).
Is it possible to have functionality where one can use 'Undo Changes' to reset form to InitialValues, but also have another button to reset to empty form?

A: If you go to the redux-form documentation, you will find what you need under the action creator section. With that, let's answer your questions.

one can use 'Undo Changes' to reset form to InitialValues

In its documentation, Redux-Form lists out a couple of actions that you can use. You can either use an action creator or used an action that is already bound to the dispatch. For your requirement, you'll need to use the library's reset function
a) using action creator
import { reset } from 'redux-form';

...// then inside a function you can dispatch the reset action.
resetMyForm() {
 const action = reset('myFormName');
 dispatch(action);
}

b) using an action already bound to the dispatch
I wont type this since there is an example in the library on GitHub here
And as for

button to reset to empty form

similar to the initial answer but you would have to use the clearFields function instead.
Hope this helps.


Q: Issue in starting the nginx web platform open-resty in wsl-ubuntu I'm currently running Ubuntu using wsl-2 in windows and when I tried out an Open Resty tutorial for dynamic redirection, it was running well.
I configured kind cluster and setup nginx ingress to tryout ingress services and it also worked fine. But after this when I tried to start the Open Resty the same way as before, the nginx web platform fails to start.
I also checked using $which openresty and got the output /usr/bin/openresty. So this confirms that it is properly installed as well.
I want to know whether using nginx in both the kind cluster and using Open Resty causes this issue or is there any other reason for this issue?
Command used -  $sudo service openresty start
Output -  * Starting full-fledged web platform nginx                                                        [fail]
Note - Redirection using lua scripts is working but still the openresty service status is  * nginx is not running


Q: Cannot compare http request response using Result I have a class that defines a send function to make an http request that returns a Result type.
Result is a system-defined type basically is a generic enum that contains 2 possible values: .success(...) and .failure(...)
public typealias ResultCallback<Value> = (Result<Value, Error>) -> Void
class NetworkManager: NetworkManagerType{

    func send(_ requestUrl: URL, completion: @escaping
    ResultCallback<(response: HTTPURLResponse, data: Data)>)  // equivalent to (Result<(response: HTTPURLResponse, data: Data), Error>)
 ...
}

In my unit test I would be able to compare expected Result objects with the actual Result returned by the send function.
func testFailureResponse() {
        // PREPARE MOCK DATA
        session.mockHttpResponse = mockFailedHttpResponse
        session.mockData = mockData
        session.mockError = NetworkManagerError.httpRequestFailed(response: mockFailedHttpResponse, data: mockData)

        // MAKE REQUEST
        netManager.send(myTaxyUrl, completion:  {  (result: Result<(response: HTTPURLResponse, data: Data), Error>) -> ()  in
              let expectedResult = Result<(response: HTTPURLResponse, data: Data), Error>.failure(  NetworkManagerError.httpRequestFailed(response: mockFailedHttpResponse, data: mockData))

              XCTAssertTrue( expectedResult == result) // !! Errors here!!
              ...
}

The errors are:

*

*' (Self.Type) -> (Self, Self) -> Bool'
requires that '(response: HTTPURLResponse, data: Data)' conform to
'Equatable'

*Type '(response: HTTPURLResponse, data: Data)' does not conform to
protocol 'Equatable'

It seems that saying the tuple does not conform to protocol Equatable, still it is possible to equate my tuples:
let t1 = (response: mockFailedHttpResponse, data: mockData)
let t2 = (response: mockFailedHttpResponse, data: mockData)
print(t1 == t2) // true

So, given that swift doesn't allow to enforce Equatability on a tuple type ( because a tuple it is not a named type), how can I compare actual and expected results?


Q: Fultter GridView scrolling I have try to set physics to enable scrolling function, but it will scroll the whole screen.
Only red box available to scroll
How can I set to another Widget is fix position, only enable scrolling in GridView?
Only want to scrollable in GridView, Please refer to the photo, That's is more clearly to understand.
child: Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('Sanfield Mobile App'),
        actions: <Widget>[
            IconButton(
              icon: Icon(
                Icons.exit_to_app,
                color: Colors.white,
              ),
              onPressed: () {
                showConfirmLogoutDialog(context,'Confirm logout','Do you want to logout?');
            },
          )
        ],
      ),
      drawer: CustomDrawer(),
        body:SingleChildScrollView(
            physics: new NeverScrollableScrollPhysics(),
            child:Column(
            children: <Widget>[
            Card(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  ListTile(
                  leading:
                  image(),
                  title: Text(updateDate),
                  subtitle: Text(weatherDetails),
                ),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: <Widget>[
                  RichText(
                    text: TextSpan(
                      style: new TextStyle(
                      fontSize: 24.0,
                      color: Colors.black,
                    ),
                  children: <TextSpan>[
                    TextSpan(text: mintemp.toString()+' C - ', style: new TextStyle(color: Colors.lightBlue)),
                    TextSpan(text: maxtemp.toString()+' C ', style: new TextStyle(color: Colors.red)),
                    TextSpan(text: '       Update:'+updateTime, style: new TextStyle(color: Colors.black,fontSize: 14)),
                ],
              ),
              ),
              ],
            ),
          ],
        ),
      ),
      Container(
        height: 80,
            child: new ListView.builder(
              itemCount: 6,
              itemBuilder: (context, index){
                return new Card(child: new Container(
                //width: MediaQuery.of(context).size.width,
                 width:320,
                 height: 80,
                 child: new Text('Hello'),alignment: Alignment.center,));
              }, scrollDirection: Axis.horizontal,
            ),
          ),
          Container(
            height: 889,
           child:GridView.count(
                    physics: ScrollPhysics(),
                    primary: false,
                    padding: const EdgeInsets.all(10),
                    crossAxisSpacing: 10,
                    mainAxisSpacing: 10,
                    crossAxisCount: 3,
                    children: <Widget>[
                      Container(
                        padding: const EdgeInsets.all(20),
                        decoration: BoxDecoration(
                          image: DecorationImage(
                            image: AssetImage(
                                'images/hkphoto.jpg'),
                            fit: BoxFit.fill,
                          ),
                          shape: BoxShape.circle,
                        ),
                        child: InkWell(
                          /*onTap: () => Navigator.push(
                              context, MaterialPageRoute(builder: (context) =>)
                            ),*/ // handle your onTap here
                        ),
                      ),
                      InkWell(
                          child:Container(
                                    padding: const EdgeInsets.all(8),
                                    child: const Text('phs'),
                                    color: Colors.teal[200],
                          ),
                          /*onTap: () => Navigator.push(
                              context, MaterialPageRoute(builder: (context) =>
                            )
                          ),*/
                      ),
                      InkWell(
                        child:Container(
                          padding: const EdgeInsets.all(8),
                          child: const Text('whs'),
                          color: Colors.teal[200],
                        ),
                        /*onTap: () => Navigator.push(
                            context, MaterialPageRoute(builder: (context) =>
                          ),
                        ),*/
                      ),
                      InkWell(
                        child:Container(
                          padding: const EdgeInsets.all(8),
                          child: const Text('whs'),
                          color: Colors.teal[200],
                        ),
                        /*onTap: () => Navigator.push(
                            context, MaterialPageRoute(builder: (context) =>
                          ),
                        ),*/
                      ),
                      InkWell(
                        child:Container(
                          padding: const EdgeInsets.all(8),
                          child: const Text('whs'),
                          color: Colors.teal[200],
                        ),
                        /*onTap: () => Navigator.push(
                            context, MaterialPageRoute(builder: (context) =>
                          ),
                        ),*/
                      ),
                      InkWell(
                        child:Container(
                          padding: const EdgeInsets.all(8),
                          child: const Text('whs'),
                          color: Colors.teal[200],
                        ),
                        /*onTap: () => Navigator.push(
                            context, MaterialPageRoute(builder: (context) =>
                          ),
                        ),*/
                      ),
                ],
              )
              ),
            ]
          ),
        )
      )

A: Remove the SingleChildScrollView at the top-level of the body and set the scrollPhysics of the GridView to AlwaysScrollableScrollPhysics().

A: Try removing the SingleChildScrollView like this:
Column(
        children: <Widget>[
        Card(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              ListTile(
              leading:
              image(),
              title: Text(updateDate),
              subtitle: Text(weatherDetails),
            ),
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: <Widget>[
              RichText(
                text: TextSpan(
                  style: new TextStyle(
                  fontSize: 24.0,
                  color: Colors.black,
                ),
              children: <TextSpan>[
                TextSpan(text: mintemp.toString()+' C - ', style: new TextStyle(color: Colors.lightBlue)),
                TextSpan(text: maxtemp.toString()+' C ', style: new TextStyle(color: Colors.red)),
                TextSpan(text: '       Update:'+updateTime, style: new TextStyle(color: Colors.black,fontSize: 14)),
            ],
          ),
          ),
          ],
        ),
      ],
    ),
  ),
  Container(
    height: 80,
        child: new ListView.builder(
          itemCount: 6,
          itemBuilder: (context, index){
            return new Card(child: new Container(
            //width: MediaQuery.of(context).size.width,
             width:320,
             height: 80,
             child: new Text('Hello'),alignment: Alignment.center,));
          }, scrollDirection: Axis.horizontal,
        ),
      ),
      Container(
        height: 889,
       child:GridView.count(
                physics: ScrollPhysics(),
                primary: false,
                padding: const EdgeInsets.all(10),
                crossAxisSpacing: 10,
                mainAxisSpacing: 10,
                crossAxisCount: 3,
                children: <Widget>[
                  Container(
                    padding: const EdgeInsets.all(20),
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage(
                            'images/hkphoto.jpg'),
                        fit: BoxFit.fill,
                      ),
                      shape: BoxShape.circle,
                    ),
                    child: InkWell(
                      /*onTap: () => Navigator.push(
                          context, MaterialPageRoute(builder: (context) =>)
                        ),*/ // handle your onTap here
                    ),
                  ),
                  InkWell(
                      child:Container(
                                padding: const EdgeInsets.all(8),
                                child: const Text('phs'),
                                color: Colors.teal[200],
                      ),
                      /*onTap: () => Navigator.push(
                          context, MaterialPageRoute(builder: (context) =>
                        )
                      ),*/
                  ),
                  InkWell(
                    child:Container(
                      padding: const EdgeInsets.all(8),
                      child: const Text('whs'),
                      color: Colors.teal[200],
                    ),
                    /*onTap: () => Navigator.push(
                        context, MaterialPageRoute(builder: (context) =>
                      ),
                    ),*/
                  ),
                  InkWell(
                    child:Container(
                      padding: const EdgeInsets.all(8),
                      child: const Text('whs'),
                      color: Colors.teal[200],
                    ),
                    /*onTap: () => Navigator.push(
                        context, MaterialPageRoute(builder: (context) =>
                      ),
                    ),*/
                  ),
                  InkWell(
                    child:Container(
                      padding: const EdgeInsets.all(8),
                      child: const Text('whs'),
                      color: Colors.teal[200],
                    ),
                    /*onTap: () => Navigator.push(
                        context, MaterialPageRoute(builder: (context) =>
                      ),
                    ),*/
                  ),
                  InkWell(
                    child:Container(
                      padding: const EdgeInsets.all(8),
                      child: const Text('whs'),
                      color: Colors.teal[200],
                    ),
                    /*onTap: () => Navigator.push(
                        context, MaterialPageRoute(builder: (context) =>
                      ),
                    ),*/
                  ),
            ],
          )

Let me know if it doesnt work


Q: Handling tap on Pushpin in a fixed Map I have a Map control showing a few Pushpins. I do not want the user to navigate in the map so I disable it. But I do want the user to be able to tap on a Pushpin (and in the event I navigate to a detail page).
However when the Map.IsEnabled is false, the Pushpins don't seem to receive any gestures either. I've also tried using IsHitTestVisible, but with no luck.
Some code showing what I'm trying to do. Does anyone have any ideas?
<maps:Map Name="Map"
          VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
          CopyrightVisibility="Collapsed" LogoVisibility="Collapsed" ScaleVisibility="Collapsed" ZoomBarVisibility="Collapsed"
          IsEnabled="False">
    <maps:MapItemsControl ItemsSource="{Binding TheCollection}">
        <maps:MapItemsControl.ItemTemplate>
            <DataTemplate>
                <maps:Pushpin Name="Pin" Location="{Binding Coordinate}" Content="{Binding Ix}">
                    <maps:Pushpin.Background>
                        <SolidColorBrush Color="{StaticResource PhoneAccentColor}"/>
                    </maps:Pushpin.Background>

                    <toolkit:GestureService.GestureListener>
                        <toolkit:GestureListener Tap="PinTap"  />
                    </toolkit:GestureService.GestureListener>
                </maps:Pushpin>
            </DataTemplate>
        </maps:MapItemsControl.ItemTemplate>
    </maps:MapItemsControl>
</maps:Map>

A: Setting IsEnabled to false prevents the Map control from responding to user input, which affects the child Pushpin as you've seen. If you want the map to be read-only but the Pushpin to respond to gestures then I think you have two options:

*

*Handle all the gesture events on the Map control and set e.Handled to true, which will prevent the Map itself from processing the event, but should leave the PushPin free to handle the tap gesture.

*Create a WriteableBitmap of the Map and show that instead, and then display the Pushpin on top (NOTE: I suspect that the Pushpin control won't work outside of the Map control, so you'd need to create/re-template a control to look like a Pushpin).

UPDATE: The events that you need to handle on the Map to make it appear "read-only" but remain enabled are MapPan and MapZoom.

A: So here's how I solved it after a lot of testing and browsing MSDN. It turns out that things are a bit different in the Map control on Windows Phone (see MSDN). There are new behaviors and events compared to normal Silverlight.
<maps:Map Name="Map"
          VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
          CopyrightVisibility="Collapsed" LogoVisibility="Collapsed" ScaleVisibility="Collapsed" ZoomBarVisibility="Collapsed"
          MapZoom="Map_MapZoom" MapPan="Map_MapPan">
    <maps:MapItemsControl ItemsSource="{Binding TheCollection}">
        <maps:MapItemsControl.ItemTemplate>
            <DataTemplate>
                <maps:Pushpin Name="Pin" Location="{Binding Coordinate}" Content="{Binding Ix}">
                    <maps:Pushpin.Background>
                        <SolidColorBrush Color="{StaticResource PhoneAccentColor}"/>
                    </maps:Pushpin.Background>

                    <toolkit:GestureService.GestureListener>
                        <toolkit:GestureListener Tap="PinTap"  />
                    </toolkit:GestureService.GestureListener>
                </maps:Pushpin>
            </DataTemplate>
        </maps:MapItemsControl.ItemTemplate>
    </maps:MapItemsControl>
</maps:Map>

...

private void Map_MapPan(object sender, MapDragEventArgs e)
{
    e.Handled = true;
}

private void Map_MapZoom(object sender, MapZoomEventArgs e)
{
    e.Handled = true;
}


Q: How to use table valued parameter with the IN keyword Edit:
I tried to replace:
@LocationIDs NVARCHAR(MAX) = null,

with
@LocationIDs LocationIdArray READONLY,

but now I get an error saying:

Must declare the scalar variable "@LocationIDs".

--END EDIT--
I have this stored procedure that I need to address:
CREATE PROCEDURE [dbo].[spAP_GetTechnician_Door_Unlock]
    @LocationIDs NVARCHAR(MAX) = NULL,
    @AlarmDateFrom DATETIME = NULL,
    @AlarmDateTo DATETIME = NULL,
    @TechnicianID INT = NULL,
    @LocationId INT = NULL
AS
BEGIN
    IF (@LocationIDs = 'x')
    BEGIN
        SELECT @LocationIDs = dbo.fn_GetAll_Location_Id()
    END

    DECLARE @query NVARCHAR(MAX);

    SET @query = 'WITH CTE AS (SELECT ROW_NUMBER() OVER(ORDER BY al.Alarm_Log_ID desc)AS RowNumber,
 isnull(t.Technician_ID,'''')[Technician_ID], (isnull(t.Last_Name,'''') +'' ''+  isnull(t.Name,''''))  TechnicianName,isnull(t.Emailid,'''') as EmailID,isnull(t.phone,'''') as Phone,dbo.fNAP_DateFormat(al.Alarm_date) as Alarm_date,
 Al.Site_ID,s.Name as SiteName,al.point_Address,l.location_Name,l.Location_ID ,shs.StatusData
from z_EntityMast_Alarm_Log al
left join  z_EntityMast_Technician t on al.Technician_ID=t.Technician_id
left join z_EntityMast_Site s on s.Site_ID=al.Site_ID
left join z_EntityMast_Location l on s.Location_ID=l.Location_id
left join z_EntityMast_Site_Hardware_Status shs on s.site_id=shs.siteid
left join z_SysVar_Alarm_Type_00004 at on al.Alarm_Type=at.ID
where at.Is_Linkable=1 and al.Alarm_Type !=70'
if(isnull(@LocationId,0)!=0)
set @query=@query+' and s.Location_ID ='+convert(varchar(12),@LocationId);
else
set @query=@query+' and s.Location_ID in ('+@LocationIDs+')';
if(isnull(@AlarmDateFrom,0)!=0 and @AlarmDateFrom !='')
set @query=@query+'and (DATEDIFF(DAY,'''+convert(varchar(30),@AlarmDateFrom)+''', al.Alarm_Date)>=0 and  DATEDIFF(DAY,'''+convert(varchar(30),@AlarmDateTo)+''',al.Alarm_Date)<=0)';
if(isnull(@TechnicianID,0)!=0)
set @query=@query+'and t.Technician_ID ='+ convert(varchar(10),@TechnicianID);
set @query=@query + ')';
set @query=@query +'select * from CTE ';

    -- PRINT @query
    EXEC (@query)
END

I need to optimize it and I have to use table valued parameters for the LocationIds parameter, instead of it using NVARCHAR(MAX).
The problem is in this line of code:
SET @query  = @query + ' and s.Location_ID in ('+@LocationIDs+')';

My question is: how does one replace that line of code and replace it with a table valued parameter in such a way that the concatenation would still work?
Thanks!

A:
SET @query  = @query + ' and s.Location_ID in ('+@LocationIDs+')';
  My question is: how does one replace that line of code and replace it
  with a table valued parameter in such a way that the concatenation
  would still work?

Suppose your LocationIdArray has this definition:
create type LocationIdArray as table (LocationId int);

Then your IN should look like this:
and s.Location_ID in (select LocationId from @LocationIDs)

This won't work within your exec because @LocationID is in the outer scope respect to exec, you can pass it as a parameter in sp_executesql but the best you can do is to rewrite your dynamic query to static one as there is no reason to use dynamic code here.


Q: how to call custom data from Django User models im using the built in User model of django and have added few custom fields one of them being the user type, i want to set up conditional statements according to the e_type
this is my code.
models.py
from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
from django.contrib import auth
from django.conf import settings

class User(auth.models.User,auth.models.PermissionsMixin,models.Model):
    EMPLOYEE='em'
    MANAGER='mn'
    USER_TYPE=[
        (EMPLOYEE,'employee'),
        (MANAGER,'manager'),
     ]
    e_type=models.CharField(max_length=2,choices=USER_TYPE,default=EMPLOYEE)
    no_of_leaves=models.IntegerField(null=False,validators=[MinValueValidator(1),
                                   MaxValueValidator(24)],default=24)

    def __str__(self):
        return "@{}".format(self.username)

views.py
from django.shortcuts import render
from django.contrib.auth import views as auth_views
from .models import *
from django.views.generic import TemplateView

def home(request):
    user=request.user.e_type
    return render(request,"leaveApp/home.html")


Q: Get current user in angular using firebase? Currently trying to build an app using ionic v2 & firebase v3.
Unfortunately I'm struggling to simply grab hold of the logged in user's details.
In my app.ts, I connect correctly to my firebaseapp and the logged in user is recognised and the user is shown the homepage:
import {Component} from '@angular/core';
import {Platform, ionicBootstrap, NavController} from 'ionic-angular';
import {StatusBar} from 'ionic-native';
import {HomePage} from './pages/home/home';
declare var firebase:any;
import {Data} from './providers/data/data';
import {LoginPage} from './pages/login/login';

@Component({
  template: '<ion-nav [root]="rootPage"></ion-nav>',
  providers: [Data]
})
export class MyApp {
  rootPage: any = LoginPage;

  constructor(platform: Platform) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();

      // Initialize Firebase
      var config = {
        apiKey: "xxxx",
        authDomain: "xxxx.firebaseapp.com",
        databaseURL: "https://xxxx.firebaseio.com",
        storageBucket: "xxxx.appspot.com",
      };

      firebase.initializeApp(config);

      firebase.auth().onAuthStateChanged((user) => {
        if (user) {
          // If there is a user, take him to home page.
          console.log("User is logged in!");
          //console.log(user);
          this.rootPage = HomePage;
        } else {
          // If there is no user logged in, send to login page.
          this.rootPage = LoginPage;
        }
      });
    });
  }
}

ionicBootstrap(MyApp);

Then in another of my files where I wish to retrieve the logged in user's ID using
var authData = firebase.auth().currentUser();

I get the following error in my console:
EXCEPTION: Error: Uncaught (in promise): EXCEPTION: Error in :0:0
ORIGINAL EXCEPTION: TypeError: firebase.auth(...).currentUser is not a function
ORIGINAL STACKTRACE:
TypeError: firebase.auth(...).currentUser is not a function
    at new AddItemPage (http://localhost:8100/build/js/app.bundle.js:97:40)
    at DebugAppView._View_AddItemPage_Host0.createInternal (AddItemPage_Host.template.js:20:27)
    at DebugAppView.AppView.create (http://localhost:8100/build/js/app.bundle.js:30016:21)
    at DebugAppView.create (http://localhost:8100/build/js/app.bundle.js:30228:44)
    at ComponentFactory.create (http://localhost:8100/build/js/app.bundle.js:29245:36)
    at ViewContainerRef_.createComponent (http://localhost:8100/build/js/app.bundle.js:30436:45)
    at http://localhost:8100/build/js/app.bundle.js:53117:47
    at ZoneDelegate.invoke (http://localhost:8100/build/js/zone.js:323:29)
    at Object.onInvoke (http://localhost:8100/build/js/app.bundle.js:35470:41)
    at ZoneDelegate.invoke (http://localhost:8100/build/js/zone.js:322:35)
ERROR CONTEXT:
[object Object]

I'm confused as to why currentUser() is not a function, when the documentation says it is?
https://firebase.google.com/docs/auth/web/manage-users#get_the_currently_signed-in_user
Thanks!

A: the documentation says that
firebase.auth().currentUser NOT firebase.auth().currentUser() is the correct way to get the user


Q: Database error in model using Code Igniter Error:
(POST http://localhost/codeigniter/Purchase/transaction/update?id=7 500 (Internal Server Error)
Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near ''supp_id2` =
s.`supp_id` WHERE p.purch_id =' at line 1

SELECT p.*, s.supp_name FROM purchase as p LEFT JOIN supplier as s ON
p.'supp_id2` = s.`supp_id` WHERE p.purch_id =

Filename: C:/xampp/htdocs/codeigniter/system/database/DB_driver.php

Line Number: 691

this is the Controller of my code, this is where the transaction is located at
function transaction($txn = null) {
    switch ($txn) {
        case 'list':

            $response['data']=$this->Purchase_model->get_all_purchase();
            echo json_encode($response);

        break;

        case 'create':
            $purchase =
            array(
                'po_number' => $this->input->post('po_number'),
                'date' => $this->input->post('date'),
                'supp_id2' => $this->input->post('supp_id2'),
                'contact_person' => $this->input->post('contact_person'),
                'delivered_to' => $this->input->post('delivered_to'),
                'plu_number' => $this->input->post('plu_number'),
                'address' => $this->input->post('address'),
                'remarks' => $this->input->post('remarks'),
            );

            $insert = $this->Purchase_model->purchase_add($purchase);

            $resp['row_added'] = $this->Purchase_model->get_purchase($insert);
            $resp['title'] = 'Success!';
            $resp['stat'] = 'success';
            $resp['msg'] = 'Purchase Information successfully created.';

            echo json_encode($resp);
        break;

        case 'update':
            $data =
            array(
                'po_number' => $this->input->post('po_number'),
                'date' => $this->input->post('date'),
                'supp_id2' => $this->input->post('supp_id2'),
                'contact_person' => $this->input->post('contact_person'),
                'delivered_to' => $this->input->post('delivered_to'),
                'address' => $this->input->post('address'),
                'plu_number' => $this->input->post('plu_number'),
                'remarks' => $this->input->post('remarks'),
            );

this is the purchase model I created
 public function get_purchase($purch_id)
 {
    $db = "SELECT p.*, s.supp_name FROM purchase as p LEFT JOIN supplier as
 s ON p.'supp_id2` = s.`supp_id` WHERE p.purch_id = $purch_id ";
 return $this->db->query($db)->result();-
    $this->db->from($this->table);
    $this->db->where('purch_id',$id);
    $query = $this->db->get();

    return $query->row();
}

if you need to see the other details please ask so a I can send it to the comment section or edit this post, how to solve this?
UPDATE:
I changed the 'supp_id2tosupp_id2` and it shows a new but I think the same error:
 Error Number: 1064

 You have an error in your SQL syntax; check the manual that corresponds to
 your MySQL server version for the right syntax to use near '' at line 1

 SELECT p.*, s.supp_name FROM purchase as p LEFT JOIN supplier as s ON
 p.`supp_id2` = s.`supp_id` WHERE p.purch_id =

 Filename: C:/xampp/htdocs/codeigniter/system/database/DB_driver.php

 Line Number: 691

A: The syntax is wron:
 $db = "SELECT p.*, s.supp_name FROM purchase as p LEFT JOIN supplier as
    s ON p.'supp_id2` = s.`supp_id` WHERE p.purch_id = $purch_id ";

copy this select
  $db = "SELECT p.*, s.supp_name FROM purchase as p LEFT JOIN supplier as
 s ON p.`supp_id2` = s.`supp_id` WHERE p.purch_id = $purch_id ";

A: As you can see at the error
Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near ''supp_id2` =
s.`supp_id` WHERE p.purch_id =' at line 1

SELECT p.*, s.supp_name FROM purchase as p LEFT JOIN supplier as s ON
p.'supp_id2` = s.`supp_id` WHERE p.purch_id =

Filename: C:/xampp/htdocs/codeigniter/system/database/DB_driver.php

Line Number: 691

Purchase id is not passing to the query.


Q: Is it safe to read a weak pointer while it's being deallocated? Is it safe to read a nonatomic weak pointer from a different thread than the object is being deallocated from?
In general, I know properties should be made atomic whenever there may be simultaneous accesses, at least one of which is a write operation.  But I have to wonder if ARC's write operation (setting the pointer to nil) is somehow special.  Otherwise, I would've expected to see more warnings about this possible issue.  Perhaps weak pointers are implicitly atomic?

A: It is safe. Accessing weak pointer and Zeroing weak pointer is in between spinlock_lock and spinlock_unlock.
Take a look at the runtime source code
http://opensource.apple.com/source/objc4/objc4-646/runtime/NSObject.mm
Accessing weak pointer
id
objc_loadWeakRetained(id *location)
{
    id result;

    SideTable *table;
    spinlock_t *lock;

 retry:
    result = *location;
    if (!result) return nil;

    table = SideTable::tableForPointer(result);
    lock = &table->slock;

    spinlock_lock(lock);
    if (*location != result) {
        spinlock_unlock(lock);
        goto retry;
    }

    result = weak_read_no_lock(&table->weak_table, location);

    spinlock_unlock(lock);
    return result;
}

Zeroing weak pointer
void
objc_object::sidetable_clearDeallocating()
{
    SideTable *table = SideTable::tableForPointer(this);

    // clear any weak table items
    // clear extra retain count and deallocating bit
    // (fixme warn or abort if extra retain count == 0 ?)
    spinlock_lock(&table->slock);
    RefcountMap::iterator it = table->refcnts.find(this);
    if (it != table->refcnts.end()) {
        if (it->second & SIDE_TABLE_WEAKLY_REFERENCED) {
            weak_clear_no_lock(&table->weak_table, (id)this);
        }
        table->refcnts.erase(it);
    }
    spinlock_unlock(&table->slock);
}

And the Object deallocating flow
https://stackoverflow.com/a/14854977/629118