text:
Q: Invalid rule reference error when compiling Windows Speech Recognition Macros Lately I have gotten interested in trying out some XML and Javascript with Windows Speech Recognition Macros. This is my first experience with both languages, but since I do have a small programming history, I thought that I could just dive in. And so far it has gone pretty well. But now that I am trying to implement a deeper level of interactivity to my macros I start running into errors of which I can find no explaination online, so I came here to ask for your help.
This is the macro that is giving me problems:
<command>
    <listenFor>Whats the weather like in [CityName]</listenFor>

</command>

And this is the error message:
Error compiling grammar for speech Macros:
"AI-base.WSRMac"
==========
Line 40: 80045048 - Invalid rule reference to <RULEREF NAME="CityName" REFID=""/>
==========
00001:
00002: <GRAMMAR LANGID="0409">
...
...
...
00038: <RULE NAME="Rule_8">
00039:

00040:
Whats the weather like in
<ruleref name="CityName" propname="CityName" />
00041:

00042: </RULE>
00043: <RULE name="build:namedDictation"><dictation min="1" max="10"/></RULE>
00044: </GRAMMAR>

What I am trying to do with this macro is get a cityname from the user and get the weather for that location, out it in a couple of variables and then let it tell me the weather in a format I like.
Could someone please explain what I am doing wrong and how to fix it?
Thanks in advance :)
-Dirk

A: As far as I know, WSR Macros doesn't have a predefined 'CityName' property.  The examples I've seen that use 'CityName' define a list of named cities with the appropriate properties.  For example, the Weather.WSRMac sample has
<listenForList name="CityName" propname="zipCode">
    <item propval="45255">Cincinnati</item>
    <item propval="98075">Sammamish</item>
    <item propval="98052">Redmond</item>
    <item propval="98004">Bellevue</item>
    <item propval="98101">Seattle</item>
</listenForList>

You would need to do something similar.
If you need an uninterpreted string, you could try
 <rule name="CityName">
      <Dictation PROPID="Dictation" Min="1" Max="5"/>
 </rule>

To retrieve the content at runtime, you should be able to use
 xml_doc.load("http://api.openweathermap.org/data/2.5/weather?q={[CityName.Dictation]}&mode=xml");

Almost all of this is available on the WSR Macros Wiki, particularly the section on Rule Generators; the details on SAPI 5 XML grammars are also on MSDN.


text:
Q: The type arguments cannot be inferred from the usage I have an MVC View and controller and in order to be able to pull out the correct information to display on the view I have used a linq query and converted this to a list to be picked up by the view, but since I changed the type to List from IEnumerable I an unable to get the Display names of the properties using @Html.DisplayNameFor(model => model.Name).
View Code:
@model List<UKAIS.Common.Brands.Data.Opex>

@{
    ViewBag.Title = "Index";
}

Index

    @Html.ActionLink("Create New", "Create")

            @Html.DisplayNameForModel()

            @Html.DisplayNameFor(model => model.Name)

            @Html.DisplayNameFor(model => model.Description)

            @Html.DisplayNameFor(model => model.BulletPoints)

            @Html.DisplayNameFor(model => model.ImageUrl)

            @Html.DisplayNameFor(model => model.PolicyWordingLink)

            @Html.DisplayNameFor(model => model.Price)

            @Html.DisplayNameFor(model => model.OpexType)

            @Html.DisplayNameFor(model => model.SortOrder)

            @Html.DisplayNameFor(model => model.MustSelectOption)

            @Html.DisplayNameFor(model => model.Selected)

            @Html.DisplayNameFor(model => model.DateCreated)

            @Html.DisplayNameFor(model => model.DateModified)

            @Html.DisplayNameFor(model => model.ModifiedBy)

            @Html.DisplayNameFor(model => model.RowVers)

            @Html.DisplayNameFor(model => model.Active)

            @Html.DisplayNameFor(model => model.SubHeading)

            @Html.DisplayNameFor(model => model.VariantKeyText)

            @Html.DisplayNameFor(model => model.VariantOptionText)

            @Html.DisplayNameFor(model => model.OpexGroup.Name)

@foreach (var item in Model) {

            @Html.DisplayFor(modelItem => item.Code)

            @Html.DisplayFor(modelItem => item.Name)

            @Html.DisplayFor(modelItem => item.Description)

            @Html.DisplayFor(modelItem => item.BulletPoints)

            @Html.DisplayFor(modelItem => item.ImageUrl)

            @Html.DisplayFor(modelItem => item.PolicyWordingLink)

            @Html.DisplayFor(modelItem => item.Price)

            @Html.DisplayFor(modelItem => item.OpexType)

            @Html.DisplayFor(modelItem => item.SortOrder)

            @Html.DisplayFor(modelItem => item.MustSelectOption)

            @Html.DisplayFor(modelItem => item.Selected)

            @Html.DisplayFor(modelItem => item.DateCreated)

            @Html.DisplayFor(modelItem => item.DateModified)

            @Html.DisplayFor(modelItem => item.ModifiedBy)

            @Html.DisplayFor(modelItem => item.RowVers)

            @Html.DisplayFor(modelItem => item.Active)

            @Html.DisplayFor(modelItem => item.SubHeading)

            @Html.DisplayFor(modelItem => item.VariantKeyText)

            @Html.DisplayFor(modelItem => item.VariantOptionText)

            @Html.DisplayFor(modelItem => item.OpexGroup.Name)

            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })

}

Controller Code:
//Returns Opex list dependant on brand
public async Task<ActionResult> Index(Guid? id)
{
    if (id == null)
    {
        var opexes = db.Opexes.Include(o => o.OpexGroup).ToList();
        return View(opexes);
    }
    else
    {
        var opexes = (from o in db.Opexes
            join b in db.BrandOpexes on o.Id equals b.OpexId
            where b.BrandId == id
            select new Opex()
            {
                Active = o.Active,
                Code = o.Code,
                BulletPoints = o.BulletPoints,
                ImageUrl = o.ImageUrl,
                PolicyWordingLink = o.PolicyWordingLink,
                Description = o.Description,
                Price = o.Price,
                OpexType = o.OpexType,
                SortOrder = o.SortOrder,
                MustSelectOption = o.MustSelectOption,
                Selected = o.Selected,
                DateCreated = o.DateCreated,
                DateModified = o.DateModified,
                ModifiedBy = o.ModifiedBy,
                RowVers = o.RowVers,
                SubHeading = o.SubHeading,
                VariantKeyText = o.VariantKeyText,
                VariantOptionText = o.VariantOptionText,
            }).ToList();
        return View(opexes);

    }

}

A: You are using List<UKAIS.Common.Brands.Data.Opex> in model, but You use this model like type in DisplayNameFor (DisplayNameFor not know which element You want to display)
Change this:
@Html.DisplayNameFor(model => model.Name)

to this(something like this)
@Html.DisplayNameFor(model => model[0].Name)

Best way is to create variable with one item from model
var displayItem = model[2];

 @Html.DisplayNameFor(displayItem => displayItem.Name)

Help links:
DisplayNameFor() From List<Object> in Model

A: You have to Use
@Html.DisplayNameFor(model => model.First().Name)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fatal error when trying to clear APC cache using index.php i am facing this problem in magento site:
Magento website suddenly has 'No data received' Error code: ERR_EMPTY_RESPONSE
so i tried solution provided by @Larzen in that link
but i am getting following error at the end of the frontend and backend :
Fatal error: Call to undefined function apc_clear_cache() in /var/www/html/site/index.php on line 92

so is there any way to clear APC cache through index.php file or how we can do this from server side.


text:
Q: What is the difference between using `late` keyword before the variable type or using `?` mark after the variable type it in the Flutter? I think in new Dart rules the variables can not be declared/initialized as null. So we must put a late keyword before the variable type like below:
late String id;

Or a ? mark after the variable type like below:
String? id;

Are these two equal Or there are some differences?

A: A nullable variable does not need to be initialized before it can be used.
It is initialized as null by default:
void main() {
  String? word;

  print(word); // prints null
}

The keyword late can be used to mark variables that will be initialized later, i.e. not when they are declared but when they are accessed. This also means that we can have non-nullable instance fields that are initialized later:
class ExampleState extends State {
  late final String word; // non-nullable

  @override
  void initState() {
    super.initState();

    // print(word) here would throw a runtime error
    word = 'Hello';
  }
}

Accessing a word before it is initialized will throw a runtime error.

A: when you use late keyword you can't let variable uninitialized when you called it with ? allows to you let variable uninitialized when you create it and call it

A: Null safety rules doesn't mean you can't use null. You can, but you should indicate that a variable might have the value null, by add "?" to its type declaration.
By use keyword late you indicate that variable has a non-nullable type, is not initialized yet, but will be initialized later.
Exception is thrown if try to acсess value of late variable before initialization.


text:
Q: Is there a good way to run benchmark to logstash on GKE? Here is an official tool but seems old: https://github.com/elastic/logstash-benchmark-tools
Google provides a way but for security: https://cloud.google.com/blog/products/containers-kubernetes/gke-cis-benchmarks-deliver-security-best-practices
Elastic has a tool Rally but for elasticsearch: https://www.elastic.co/jp/blog/benchmarking-and-sizing-your-elasticsearch-cluster-for-logs-and-metrics

A: Since the solution provided by Elastic seems old, I would suggest you to contact the support of Elastic [1] so they can provide you with a more recent approach.
Have a nice day!

[1] - https://www.elastic.co/contact?storm=global-header-en


text:
Q: Make array of specific items within a pager and select specific class My question is: how do I make array of specific items within a pager and select specific class
This is my next/previous (pager) html code:

1

2

next ›

last »

A pager looks like this: <--- previous 1 2 3 next ---> where you can go to next page.
I want to loop thru all pages 1 - 100.
Select each page, get the content and make a array of all elements with
 but only only the ones that has a class included named

The page content:

Now is the element with the allowed class only be inserted into the array, and the other one ignored.

A: This is how you make an array with the items that have a child which contains an element which has the class allowed.  Is this what you were looking for?
var $items = $("div.items");
var yourArray;

$.each($items,function(){
   if($(this).children(".allowed").length){
       yourArray.push($(this));
   }
});

A: You can use jQuery.fn.has() to filter down a jQuery object based on the contents of it:
$('.items') // <-- all items
  .has('div.allowed') // <-- only the items with a

or put it in the initial selector like this:
$('.items:has(div.allowed)');


text:
Q: Is there a way to require a module in TypeScript without binding a new variable? The standard module import syntax in TypeScript,
import foo = require('foo');

requires you to bind a new identifier to the imported module. But in some cases I just want to express a dependency without binding anything. For example, if I'm depending on a jQuery plugin that doesn't actually export things, it just adds new fields to jQuery itself. Is there a way to do something like
require('foo');

without the import part?

A: You can use the undocumented amd-dependency flag :
/// <amd-dependency path="foo"/>

Additional information (slightly dated video) : http://www.youtube.com/watch?v=4AGQpv0MKsA&hd=1


text:
Q: Backendless CodeRunner not registering with backendless servers I'm using Backendless to handle data and push notifications for an iOS app. I am currently trying to write the server side code for a timer in Java.
I have followed the guide here to download the timer code, open it and build it in IntelliJ IDEA and then run CodeRunner through the terminal.
This is the only output I get from CodeRunner:
[INFO] JDK from "JAVA_HOME" - /Library/Java/Home
[INFO] CodeRunner(tm) Backendless Debugging Utility
[INFO] Copyright(C) 2018 Backendless Corp. All rights reserved.
[INFO] Version: 4.4.7 Build date: 2018-05-14T13:42:44Z
[INFO] CodeRunner session is running for 2 hours and will be terminated on 09:38:39.755[UTC]

It never seems to get to the registering step. There is a whole heap of output before the codeRunner version etc, stuff like
07:38:39,284 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - debug attribute not set
07:38:39,284 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.ConsoleAppender]

Not sure if that has anything to do with it.
Can anyone point me in the right direction to get CodeRunner up and running, no pun intended?

A: I had this problem since 2 hours. I tested it in a sample project 2 weeks ago and it worked fine. Now I'm using it in a real App, it can't register the CodeRunner.
The reason is the CodeRunner.jar build 2018-05-14 seems to have a bug. I replace the old CodeRunner.jar and weborb.jar from the sample project (build 2018-05-02) inside the bin directory and it works fine now. Here's the 2 JAR Files in my Google Drive. I replaced both cause I'm not sure where the bug is.

A: The blog post you linked is for the deprecated version 3 of Backendless (you should have noticed that the console now looks very different from the screenshots). Though the process is mostly the same as described in this blog post, this documentation for current version is much more relevant. There is a quick-start guide there for event handlers, the process for timers is analogous.


text:
Q: Fit-screen dosn't fill all the screen I'm new Mac user, on Yosemite.
Some apps, like Chrome Sublime Text,  when I double click on the title bar doesn't fit my screen, check the image
Also for some others apps, Like Xcode or Safari it works fine - double click on the title makes my app fit full screen.
How to fix?

A: Fit screen & full screen are not the same thing.
Fit screen makes a 'guess' based on window content & probable usage [per app, it would appear to not be consistent, some apps are better than others at 'guessing']
Full screen is under system control & will generate a new Space for the app, filling the entire screen.
Clicking the green dot, top left of a window, will set Full-screen.
Alt [opt] clicking the same dot will set to fit-screen.

A: In Chrome, use the keyboard cmd+shift+f to go in to full screen mode.
Use it again to exit full screen.
To fill in the Window (not the screen) I recommend the Chrome Extension called "iZoom", found here
https://chrome.google.com/webstore/detail/izoom/iheccogfcpjfjbnlohnlgdljaefpgaoi?hl=en-US

Automatically changes zoom level to fit window width. With three
  different zooming modes.


text:
Q: Proving $(0,1)$ and $[0,1]$ have the same cardinality Prove $(0,1)$ and $[0,1]$ have the same cardinality.
I've seen questions similar to this but I'm still having trouble.  I know that for $2$ sets to have the same cardinality there must exist a bijection function from one set to the other.  I think I can create a bijection function from $(0,1)$ to $[0,1]$, but I'm not sure how the opposite.  I'm having trouble creating a function that makes $[0,1]$ to $(0,1)$.  Best I can think of would be something like $x \over 2$.
Help would be great.

A: Use Hilbert's Hotel.
First identify a countable subset of $(0,1)$, say $H = \{ \frac1n : n \in \mathbb N\}$.
Then define $f:(0,1) \to [0,1]$ so that
$$ \frac12 \mapsto 0$$
$$ \frac13 \mapsto 1$$
$$ \frac{1}{n} \mapsto \frac{1}{n-2}, n \gt 3$$
$$ f(x) = x, \text{for } x \notin H $$

A: Use Cantor-Bernstein theorem:
You can trivially find a bijection between $(0,1)$ and $(1/4,3/4)\subset[0,1]$, hence $\mathrm{Card} (0,1) \leq \mathrm{Card} [0,1]$.
Likewise, there is a trivial bijection between $[1/4,3/4]\subset(0,1)$ and $[0,1]$, hence $\mathrm{Card} [0,1] \leq \mathrm{Card} (0,1)$.
By trivial, I mean a linear function $t\to at+b$ with some numbers $a,b$.
Thus $\mathrm{Card} [0,1] = \mathrm{Card} (0,1)$.


text:
Q: Problems Setting up custom logger in Python So I'm currently reworking our python based Automated Testing System (ATS) and I've come up against a real headache with logging. I've spent the last few hours going through youtube tutorials and articles on here, and I've yet to find a clear answer to my specific problem.
I want to replace all print statements with a logger that will output to both the console and .txt file. I've got the Test Log.txt creating (with datetime in the file name), but the file is blank and the printed text doesn't appear in the console either. This was using logger.debug. It's like the .txt file is being created before the text is ever passed to it.
I had originally been calling this via PrintLog.debug but that just led to visual studio telling me that the PrintLog.py had no attribute called debug. I'm really hoping I can just one bit of code that can be called by various scripts rather than having to bake it into every individual script. Additionally if you could also help me generate the logs in an 'OutputLogs' sub folder that would be much appreciated.
import os
import time
import datetime

def timeStamped(fname, fmt='%Y-%m-%d_%H.%M - {fname}'):
    return datetime.datetime.now().strftime(fmt).format(fname=fname)

#Records Current date & time and appends it to the file namme of the txt log created at the end of this script.

import logging

def PrintLog(self):
    PrintLog = logging.getLogger(__name__)
    PrintLog.setLevel(logging.DEBUG)

    formatter = logging.Formatter('%(levelname)s:%(name)s:%(message)s:%(asctime)s')

    file_handler = logging.FileHandler(timeStamped('Test Report.txt'))
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(formatter)

    stream_handler = logging.StreamHandler()
    stream_handler.setLevel(logging.DEBUG)
    stream_handler.setFormatter(formatter)

    PrintLog.addHandler(file_handler)
    PrintLog.addHandler(stream_handler)

Edit: So to clarify, that's the logger but I want to call it and pass it information to it from another Python Script.
import os
import time
import sys
import subprocess
import datetime
import logging
from PrintLog import PrintLog

def timeStamped(fname, fmt='%Y-%m-%d_%H.%M.%S - {fname}'):
    return datetime.datetime.now().strftime(fmt).format(fname=fname)

#Records Current date & time and appends it to the file namme of the txt log created at the end of this script.

from sys import platform
if platform == "darwin":
    PrintLog('Operating System = MAC')
elif platform == "win32":
    PrintLog('Operating System = Windows')

Information such as the OS statements isn't passed to the PrintLog script.

A: logging.getLogger(__name__) creates a new logger, not the same as the logger variable you created in your own log module, because __name__ is different in each module.
Either import logger from your own module and use that, or configure the root logger instead:
logger = logging.getLogger()  # Without arguments, it gets the root logger.
logger.setLevel(logging.DEBUG)

# ... add handlers etc. ...


text:
Q: Error using my own python data iterator in mxnet I am trying to create my own data iterator to use with mxnet. When I run it I get the error :
Traceback (most recent call last):
File "train.py", line 24, in <module>
batch_end_callback = mx.callback.Speedometer(batch_size, 1) # output progress for each 200 data batches
File "/usr/local/lib/python2.7/dist-packages/mxnet-0.7.0-py2.7.egg/mxnet/model.py", line 811, in fit
sym_gen=self.sym_gen)
File "/usr/local/lib/python2.7/dist-packages/mxnet-0.7.0-py2.7.egg/mxnet/model.py", line 236, in _train_multi_device
executor_manager.load_data_batch(data_batch)
File "/usr/local/lib/python2.7/dist-packages/mxnet-0.7.0-py2.7.egg/mxnet/executor_manager.py", line 410, in load_data_batch
self.curr_execgrp.load_data_batch(data_batch)
File "/usr/local/lib/python2.7/dist-packages/mxnet-0.7.0-py2.7.egg/mxnet/executor_manager.py", line 257, in load_data_batch
_load_data(data_batch, self.data_arrays)
File "/usr/local/lib/python2.7/dist-packages/mxnet-0.7.0-py2.7.egg/mxnet/executor_manager.py", line 93, in _load_data
_load_general(batch.data, targets)
File "/usr/local/lib/python2.7/dist-packages/mxnet-0.7.0-py2.7.egg/mxnet/executor_manager.py", line 89, in _load_general
d_src[slice_idx].copyto(d_dst)
AttributeError: 'numpy.ndarray' object has no attribute 'copy'

I assume this has something to do with the way I return the data. See my data iterator code below:
from mxnet.io import DataIter, DataDesc
import csv
from random import shuffle
import numpy as np
from cv2 import imread, resize

class MyData(DataIter):
    def __init__(self, root_dir, flist_name, batch_size, size=(256,256), shuffle=True):
        super(MyData, self).__init__()
        self.batch_size = batch_size
        self.root_dir = root_dir
        self.flist_name = flist_name
        self.size = size
        self.shuffle = shuffle

        self.data = []
        with open(flist_name, 'rb') as csvfile:
            csvreader = csv.reader(csvfile)
            for row in csvreader:
                self.data.append(row)
        self.num_data = len(self.data)
        self.provide_data = [DataDesc('data', (self.batch_size, 6, self.size[0], self.size[1]), np.float32)]
        self.provide_label = [DataDesc('Pa_label', (self.batch_size, 1), np.float32)]
        self.reset()

    def reset(self):
        """Reset the iterator. """
        self.cursor = 0
        if self.shuffle:
            shuffle(self.data)

    def iter_next(self):
        """Iterate to next batch.
        Returns
        -------
        has_next : boolean
            Whether the move is successful.
        """
        self.cursor += self.batch_size
        success = self.cursor < self.num_data
        return success

    def getdata(self):
        """Get data of current batch.
        Returns
        -------
        data : NDArray
            The data of current batch.
        """
        datalist = self.data[self.cursor:self.cursor+self.batch_size]
        ret = np.ndarray(shape=(0,6,self.size[0],self.size[1]), dtype=np.float32)
        for data_row in datalist:
            img1 = resize(imread(data_row[0]), self.size)
            img2 = resize(imread(data_row[1]), self.size)
            img1 = np.rollaxis(img1, 2)
            img2 = np.rollaxis(img2, 2)
            img = np.concatenate((img1, img2), 0)
            imge = np.expand_dims(img,0)
            ret = np.append(ret, imge, 0)

        print ret.shape
        pad = self.batch_size - ret.shape[0]
        if pad > 0:
            ret = np.append(ret, np.zeros((pad, 6, self.size[0], self.size[1])), 0)
        return ret

    def getlabel(self):
        """Get label of current batch.
        Returns
        -------
        label : NDArray
            The label of current batch.
        """
        datalist = self.data[self.cursor:self.cursor+self.batch_size]
        ret = np.ndarray(shape=(0,1,1,1), dtype=np.float32)
        for data_row in datalist:
            label = np.ndarray(shape=(1,1,1,1), dtype=np.float32)
            label[0,0,0,0] = float(data_row[2]) / float(data_row[5])
            np.append(ret, label, 0)

        pad = self.batch_size - ret.shape[0]
        np.append(ret, np.zeros((pad, 1,1,1)), 0)
        return ret

    def getindex(self):
        """Get index of the current batch.
        Returns
        -------
        index : numpy.array
            The index of current batch
        """
        return self.cursor

    def getpad(self):
        """Get the number of padding examples in current batch.
        Returns
        -------
        pad : int
            Number of padding examples in current batch
        """
        if self.cursor + self.batch_size > self.num_data:
            return self.cursor + self.batch_size - self.num_data
        else:
            return 0

A: numpy.ndarray doesn't have copyto method. Try to use mx.ndarray.


text:
Q: How can I keep from generating inappropriate words when autogenerating strings from an alphabet? Is there a downloadable dictionary (essentially just a textfile) that contains common swear or otherwise inappropriate words in different languages?
Background: I'm rewriting an URL Shortener (Just a Proof of Concept app - the world has enough shorteners already anyway) and for that I convert Numeric IDs into Strings by Base36 encoding them. Now the problem with that approach is that it's sequential, so the unlucky people who shorten the URL that comes after faf or fucj may not be happy with their results, unless they are precisely waiting for that moment and use it to shorten the URL of their favorite Politician.
So I want a blacklist. InsultMonger doesn't really help here.
How appropriate. You fight like a cow.

A: Just remove all the vowels (and Y) from your potential alphabet, then anyone who sees a swear word must have an overactive imagination.

A: Here's a large multilingual list: http://nerdcereal.com/blog/wp-content/uploads/2007/04/multilingualswearlist.txt


text:
Q: Concatenate two DataSet Column in dropdownlist DataTextField while Binding I have dropdownlist that i have to bind from back end. I am using DataSet to bind the Data but need concatenate two column data in datatextfield of Dropdownlist.
Here is my Code.
string sqlGetClass = "select * from tbl_studentClass";
SqlCommand cmdGetClass = new SqlCommand(sqlGetClass, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdGetClass);
DataSet ds = new DataSet();
da.Fill(ds);
ddlClass.DataSource = ds;
ddlClass.DataTextField = "brachName"+"-"+"classYear";
ddlClass.DataValueField = "pk_classID";
ddlClass.DataBind();
ddlClass.Items.Insert(0, new ListItem("--SELECT--", ""));
conn.Close();

if I use a single column the dropdownlist is binding fine but when concatenate them it is giving error
DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'brachName-classYear'.
whene binding the Data.
Code running fine is:
string sqlGetClass = "select * from tbl_studentClass";
SqlCommand cmdGetClass = new SqlCommand(sqlGetClass, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdGetClass);
DataSet ds = new DataSet();
da.Fill(ds);
ddlClass.DataSource = ds;
ddlClass.DataTextField = "brachName";
ddlClass.DataValueField = "pk_classID";
ddlClass.DataBind();
ddlClass.Items.Insert(0, new ListItem("--SELECT--", ""));
conn.Close();

But i need to concatenate branchName and class Like M.Sc-1st Year.
Please Help. Thanks in advance.

A: Your best option is to specify new column in your query, and then use it as a text field:
string sqlGetClass = "select [pk_classID], [brachName] + '-' + [classYear] as [classText] from tbl_studentClass";
...
ddlClass.DataTextField = "classText";


text:
Q: Como creo un Select en laravel que llene segun opcion seleccionada? Esta en mi vista con el selectview

         Chofer
            <select name="dni" class="form-control selectpicker" id="dni"
              data-live-search="true">
                <option value="">--Seleccione el *DNI--</option>
                 @foreach($chofers as $chofer)
                    <option value="{{$chofer['cuitdni']}}">{{$chofer['cuitdni']}}
                 @endforeach
              </select>

Luego de que se ejecute el select quiero llenar el campo nombre del DNI seleccionado (el que va en el select que es numero de cliente), cómo haría?, gracias por la ayuda que me puedan brindar

A: Usa un AJAX que se ejecute cuando detecte el cambio del select:

$('#presentation').on('change', function () {
        var value = $(this).val();
        $.ajax({
            type: 'GET',
            url: '/product-prices/' + value,
            success: function success(data) {
                $('element').text(data); // Si es un elemento como una

                $('element').value(data); // Si es algo como un input(type="text")
            },
            error: function error(data) {
                console.log("Error", data);
            }
        });
});

Y en tu método del controlador, regreses la info que necesitas.
O si, literalmente, solo necesitas el texto que aparece en la opción seleccionada. Puedes hacer lo siguiente, sin AJAX:

$('#presentation').on('change', function () {
    var text = $(this).text();
    $('element').text(text); // Esto para un elemento tal como un

    $('element').val(text); // Esto en caso de que algo como input(type="text")
});


text:
Q: How to programmatically save files (.csv) from local machine running c# application to virtual machine Hey guys so I have this one c# application which outputs these .csv's and I want it to send it to a virtual machine which has a python application that will pick up these files and do some data analysis on it. Is there any way to create a connection between the c# application and the virtual machine so that I can save the .csvs in the virtual machine directory for pickup by the python script.

A: As an option, you could create a Dropbox (or similar service) account, point your C# app to write the CSVs to this folder, and then access Dropbox from the VM for your Python app to pickup said CSVs.
You could also create a share on the VM, map it on the host (as long as you are on the same subnet, the VM has its own IP and is not bridged on the physical host's IP), have the C# app write the CSVs to this share, then point your Python app to parse the CSVs from the network share within the VM.
In Addition:
System.IO.File.Copy("sourcePath", "\\machinename\share folder path");

HTHs!


text:
Q: Sum the series $\sum_{n=0}^{\infty}a_n$ if $a_n =(-1)^{\lfloor{\frac{n}{m}\rfloor}} \cdot r^{n}$
Let $0<r<1$ and $m\in\mathbb{N}$. Sum the series $$\sum_{n=0}^{\infty}a_n$$ if $a_n =(-1)^{\lfloor{\frac{n}{m}\rfloor}} \cdot r^{n}$

I get stuck here because I don't know how to deal with the floor function here. Can someone give me hints on how to deal with that floor function?

A: Note that
$$\lfloor\frac{n}{m}\rfloor= k,\quad\forall km\leq n<(k+1)m.$$
Then compute
$$\sum_{n=km}^{(k+1)m-1}(-1)^{\lfloor \frac{n}{m}\rfloor}r^n=\sum_{n=km}^{(k+1)m-1}(-1)^kr^n=(-1)^kr^{km}\frac{1-r^m}{1-r}.$$
Thus
$$\sum_{n=0}^\infty a_n=\sum_{k=0}^\infty\sum_{n=km}^{(k+1)m-1}a_n=\sum_{k=0}^\infty(-1)^kr^{km}\frac{1-r^m}{1-r}=\frac{1-r^m}{1-r}\sum_{k=0}^\infty(-r^m)^k=\frac{1-r^m}{(1-r)(1+r^m)}.$$


text:
Q: "CL Typing Label " library error in swift I have added the file "CLTypingLabel.swift" from folder CLTypingLabel-master -> Pod -> Classes -> CLTypingLabel.swift to my xcode project taken from https://github.com/l800891/CLTypingLabel
 and when I build the project there shows 38 errors....
Some errors are

*

*Consecutive declarations on a line must be seperated by ';'

*Expected declarations

*Use of unresolved identifiers 'DispatchQueue'

How should I rectify it or Is there any easy label library to animate as message typing  while displaying the label?

A: Could it be, that you are trying to use a Swift 3.0 library in a Swift 2.x project?


text:
Q: WebApi : How to have multiple translation at the same time I read a lot of post about localization in .net WebApi.
However, I want to generate a pdf file in 2 differents languages.
The workflow can be defined like this :
WebApplication -> WebApi -> MyController -> PdfService -> Generate pdf in fr AND en.
How can I implement that ?
Thanks for your help.


text:
Q: PHPMyAdmin gives "Host "xxx.xxx.xxx.xxx" is not allowed to connect to this MySQL server" error I am working on Centos 7, trying to get everything to work in Docker.
I've set up Nginx and PHP-FPM successfully - both of them work and display everything like they are supposed to. I made so I can open them up with Docker-compose.
After that, I made this paragraph in Docker-compose:
  mysql:
    image: "mysql:latest"
    container_name: mysql
    ports:
      - "3306:3306"
    environment:
      TZ: Europe/Myregion
      MYSQL_ROOT_PASSWORD: 123123
    volumes:
      - ./data:/var/lib/mysql

I set up TZ to my region, no worries here.
As you see, I specifically requested for an example that MySQL's password is set to "123123". But when I try to log into it with "mysql -u root -p", it denies - says the password the incorrect. But when I leave it empty, I can log into it - for an unknown reason the password is empty.
I thought it might work and did set up PHPMyAdmin in Docker-compose:
phpmyadmin:
    image: "phpmyadmin:latest"
    container_name: phpmyadmin
    ports:
      - "8080:80"
    environment:
      - TZ=Europe/Myreqion
      - PMA_ARBITRARY=1
      - PMA_HOST=mysql
    depends_on:
      - mysql

And after that I get PHPMyAdmin window in browser and I can't log in! At all!
Sometimes it gives the "Host "xxx.xxx.xxx.xxx" is not allowed to connect to this MySQL server" error, sometimes it gives the error "Login without a password is forbidden by configuration (see AllowNoPassword)".
I can't add a new user, I can't grant myself privileges or edit tables (because MySQL suddenly says that I don't have access to do so, but I am in the wheel permissions group) and I can't do anything at all.
This has stopped me for a week. Any ideas?

Solution: grant yourself administrator privileges while installing this VM.

A: Can you make sure that the running mysql in Docker? My guess that the mysql is not in Docker. I remembered installing mysql from yum, and able to login without password with user root.
PS: I tried your docker-compose script exactly (except TZ of course), my ip is 192.168.0.3, and I was able to login to that IP from phpmyadmin.


text:
Q: Problem with running MKReverseGeocoder in background, iphone I am using MKReverseGeocoder (reversegeocoder) to retrieve  user's current location. I am calling reversegeocoder in locationDidUpdatedToLocation method of CLLocation Manager.
- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{

if(!reverseGeocoder )
    {
        NSLog(@"geocoder is nill");
        reverseGeocoder=[[MKReverseGeocoder alloc] initWithCoordinate:[newLocation coordinate]];
        reverseGeocoder.delegate=self;
        [reverseGeocoder start];
        NSLog(@"geocoder allocated");
    }

    else
    {
        NSLog(@"geocoder is not nill");

        if(reverseGeocoder.querying)
        {
        //do nothing ;
        }
        else
        [reverseGeocoder release];

    }

}

.querying property is used to ensure that reversegeocoder should be released only when It has completed its query. But when application crashes within 3-4 seconds of running with error message
-[MKReverseGeocoder isQuerying]: message sent to deallocated instance

What am I missing here?
Thanks for any help in advance.

A: Could it be because you haven't set the geocoder's delegate to nil before releasing it? Or that you haven't nilled the pointer?
Try this:
    if(reverseGeocoder.querying)
    {
            //do nothing ;
    }
    else
    {
            [reverseGeocoder setDelegate:nil];
            [reverseGeocoder release];
            reverseGeocoder = nil;
    }


text:
Q: Same component twice in page ngIf not working as expected

<loader *ngIf="!googleReady||plottingData"></loader>

I have a map component with an overlay that I have to show when the map is loading or when data is being fetched.I have the same map component on page and in a modal,the ngif works on page but not in modal.
window['onMapsLoaded'] = (ev) => {
  this.googleReady = true;
}
plotMarkers() {
this.plottingData = true;
....
//after plotting markers
 this.plottingData = false;
}


text:
Q: ConstraintLayout, Elevation of Child Views, and Backward Compatibility I have a ConstraintLayout and one Button and an ImageView as its child views. The ImageView is placed over the Button with the expectation that the ImageView would be drawn over the Button. (Definitely, I could have added the image as a drawabl with the Button. But, in my scenario I want to do some animation with the button width and I want the the ImageView to stay as it is). However, the ImageView is drawn below the Button as the Button has a 2dp elevation on its default state [Material Design Guidline]. This elevation rises to 8dp when the button is pressed. Generally, we'll need to set the elevation or translationZ property of the ImageView to more than 2dp to make the ImageView appear over the button. But, the elevation property nor the translationZ property is supported before the API level 21. I am require to support API level 19. Also, elevation is not achievable using design library yet. Maintaining the conditions, is there any way to draw the ImageView over the Button inside the ConstraintLayout?
            <android.support.constraint.ConstraintLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="@dimen/input_margin_bottom">

                <EditText
                    android:id="@+id/et_account"
                    style="@style/RocketTheme.EditText"
                    android:drawableStart="@drawable/ic_bill_pay"
                    android:hint="@string/prompt_biller_id"
                    android:inputType="number"
                    android:maxLength="12"
                    android:maxLines="1"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintTop_toTopOf="parent"
                    tools:layout_editor_absoluteX="0dp"
                    tools:layout_editor_absoluteY="0dp" />

                <Button
                    style="@style/RocketTheme.EditText.SideButton"
                    android:id="@+id/ib_get_contact"
                    android:layout_width="match_parent"
                    android:layout_height="48dp"
                    android:text="Select Biller"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_bill_pay"
                    android:layout_marginLeft="12dp"
                    android:elevation="2dp"
                    android:background="@drawable/bg_white_round"
                    app:layout_constraintTop_toTopOf="parent"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintLeft_toLeftOf="parent"/>

            </android.support.constraint.ConstraintLayout>

A: You should wrap your button with a FrameLayout. It will allow you to pile a view on top of the one below. See the following example:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

<FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!" />

    </FrameLayout>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    </android.support.constraint.ConstraintLayout>

A: In the xml cut imageview's code and paste it below button's code. elevation is not supported on older devices

A: This is the solution I am going with for now. According to android documentation, the later sibling is drawn later. So, in general if a View comes later as siblings in the layout file it will be drawn over the other siblings. However, the button has a elevation by default and so it will be drawn above the Views having lower elevation in API above 21.
We can set an elevation or translationZ in the sibling to make it appear above the Button. We also need to make sure the View we want on the top is placed later in the layout. In API below 21, the elevation won't work and the later View is drawn on top.


text:
Q: black as pre-commit hook always fails my commits I'm trying to use pre-commit to manage Black as a Git pre-commit hook, but I must be doing it wrong.
In my pre-commit config file I have:
-   repo: https://github.com/psf/black
    rev: 19.3b0
    hooks:
    -   id: black

What I'm expecting to happen is for Black to just modify the staged file, and for the commit to succeed. Because the whole point of Black is that it auto-enforces Python code style rules, no questions asked.
What actually happens when I stage a (non-black-compliant) file and try to commit: Black goes ahead and modifies the file to make it compliant, as intended... But the problem is that it returns a "fail". So the commit fails. And then I have to unstage the file, then restage it before committing again... and only then does the commit succeed.
This is a huge annoyance and can't possibly be the intended workflow?
What am I doing wrong?

A: Looking at black's README, you probably want to use the --check option, which simply exits successfully or unsuccessfully depending on whether the file meets standards.  That will cause the commit to fail without modifying the file.

A: (author of pre-commit here)
the framework intentionally does not provide a way to auto-commit modifications.  Here's a few issues which have asked for such:

*

*pre-commit/pre-commit#806

*pre-commit/pre-commit#747
A comment from one of those issues:

pre-commit itself will never touch the staging area. These are good ways to silently break commits. In my mind this is one of the worst things that [other frameworks do and suggest] -- hooks are very frequently not perfect and magically changing what's being committed should not be taken lightly.
That said, if you would like to foot gun, your hook can call git add -u and pre-commit won't know any better :) a sketch of that (untested, discouraged)
  - id: yapf
    entry: bash -c 'yapf "$@"; git add -u' --

(note: using bash will potentially reduce portability)

Another comment notes

Fortunately, git add -u && !! is pretty easy to run if you're ok firing from the hip :)

A: One of my developers came with a good tip, in case you have a fail by commit due to black (for example due to the single/double quotes) that's resolved with the pre-commit-hook (like with double-quote-string-fixer). You get in kind of 'nobodies land git situation'. There is a changed file in the staged files, but cannot be committed by the pre-commit-hook, git status won't see any changes, but commit fails (a really black hole in my opinion). You only get a fail on commit, but nothing can be done (excecpt a reset head on this file). Once you are in this situation and run: use commit -m 'Resolving pre-commit-hook changes' --no-verify ..... tada! It's resolved.

A: I'm the same boat as you. From what I've been researching, commits can't be amended by pre-commit hooks.
As far as I can figure out, the best next thing is what bk2204 outlined. We ask black to prevent any commits that include python files that haven't been formatted properly by black. It still makes sure that any commits are formatted, but it is indeed annoying that it won't just automatically format the files for us.
It makes sense. Any changes in a commit have to be staged. If we could do that from the git hook, then our problem would be solved. You got halfway there by modifying the file directly from the git hook. The next half would be staging all the changes of the modified files. But evidently... "You cannot amend a commit in a pre commit hook" which means no staging. https://stackoverflow.com/a/14641656/6032076
I would have commented on bk2204's answer, but I don't have 50 rep yet.
Scratch all that, this answer (https://stackoverflow.com/a/16832764/6032076) claims that commits can be changed in a pre commit hook. In that case files are being added, so I bet in our case files can be restaged/amended.

A: In my experience there is no need to unstage any files, either just git add the files that black, or other pre-commit hooks, as modified again which will overwrite them in the stage area and commit with the same message as before unless the error was with a commit message check.
If your commit includes all of your changed files then simply changing the commit command from git commit -m "Your commit message" to git commit -am "Your commit message" will do the job nicely.


text:
Q: Http Listener not running in oracle forms 11g I am using oracle forms 11g with oracle database 10g. While running forms it's been showing an error that http listener is not running on port 7001. How can I resolve this? Error no is FRM-10142

A: Run the Start Weblogic Admin Server from the start menu of your Oracle forms classic instance home menu, then you could be able to run your form.


text:
Q: ReactJS. Render component on click in another component (based on class toggle) I need to render the component on click in another component like this:
I have the DevStatus component which is just the two bootstrap radiobuttons. And I have IssuesList component that is the boostrap list.
codepen code, full page view
So, when a user clicks on one of the radiobuttons, I need the IssuesList component to be rendered with another data (closed_issues array for the Closed Issues radiobutton and open_issues array for the Open Issues radiobutton). I'm new to React, but I think I'll have just to change the component's state and it will trigger the rerender, is that correct?
However, I can't manage to link the state of the IssuesList with click event on the DevStatus. Could you help me with doing that?
Also, those closed_issues and open_issues arrays will actually be the jQuery ajax responses from $.getJSON method. How can I implement this data getting process so that it doesn't block the UI thread and actually does get rendered when the JSON response is received?
This is how I'm going to get the JSON:
function _getIssues() {
    let issues = $.getJSON('https://api.github.com/repos/org_name/project/issues?state=all&filter=all')
                  .done( (data) => { issues = data } );
    return issues;
}

So, I'll get just one array of all issues and after that I'll need to split it into two. But to do that, I'll first need to call _getIssues() method which at first will return the array of undefined and after some milliseconds that array will become the valid data. However, I think that would be enough to break the app and React will not render the array of undefined. If this assumption is correct, how do I avoid it?
Update
Now I have this:
class DevStatus extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      issues: [{title: '', html_url: '#', state: 'open'}]
    };
    this.CLOSED_ISSUE_ID = 'closed_issue_r';
    this.OPEN_ISSUE_ID = 'open_issue_r';
  }

  getIssues(p_url, p_data, cbSuccess) {
    console.log('getIssues');
    let request = $.ajax({
      url: p_url,
      method: "GET",
      data: p_data
    });
    request.done(cbSuccess);
    request.fail(console.log);
  }

  componentWillMount() {
    let url = 'https://api.github.com/repos/repo/project/issues?state=all&filter=all';
    this.getIssues(url, {issues: 'open'}, this.onBackendResponse.bind(this));
  }

  onBackendResponse(data) {
    console.log('onBackendResponse');
    this.issues = data;
    this.setState({ issues: data });
  }

  onChangeRadioButton(e) {
    console.log('onChangeRadioButton')
    console.log(e.target.id);
    switch(e.target.id) {
      case OPEN_ISSUE_ID:
        this.setState({ issues: this.getOpenedIssues(this.issues).bind(this) });
        break;
      case CLOSED_ISSUE_ID:
        this.setState({ issues: this.getClosedIssues(this.issues).bind(this) });
        break;
    }
  }

  getClosedIssues(issues) {
    console.log('filter closed');
    return issues.filter((issue) => { issue.state === 'open' });
  }

  getOpenedIssues(issues) {
    console.log('filter opened');
    return issues.filter((issue) => { issue.state === 'closed' });
  }

  render() {
    console.log(this.issues);
    return (

              <input type="radio" name="options" id={this.CLOSED_ISSUE_ID}
                     autoComplete="off" onChange={this.onChangeRadioButton.bind(this)}/> Closed Issues

              <input type="radio" name="options" id={this.OPEN_ISSUE_ID}
                     autoComplete="off" onChange={this.onChangeRadioButton.bind(this)} /> Open Issues

          <IssuesList issues={this.state.issues} />

    )
  }
}

class IssuesList extends React.Component {

  constructor(props) {
    super(props);
  }

  render () {
    let issues = this.props.issues.map( (item, index) => {
      return (

          {item.title}

      );
    });

    return (

        {issues}

    );
  }
}

IssuesList.propTypes = {
  issues: React.PropTypes.array
};

A: To answer your first question: yes changing the state is exactly what you should do. Changing the state with this.setState invokes the render method again.
You could do something like this:
var CLOSED_ISSUE_ID = 'closed_issue_r', OPEN_ISSUE_ID = 'open_issue_r';
var getAsyncDataFromBackend = function(p_url, p_data, cbSuccess){
  var request = $.ajax({
                   url: p_url,
                   method: "POST",
                   data: p_data
                });
      request.done(cbSuccess);
}
//..
getInitialState:function(){
  //empty state so App doesnt <quote>break</quote>
  return {issue_data:[]}
},
componentWillMount:function(){
  //init component with open issues
  //will be executed emediately before render.
  getAsyncDataFromBackend(url, {issues: 'open'}, this.onBackendResponse);
},
render:function(){
  return (
    <button id={OPEN_ISSUE_ID} onClick={this.onChangeRadioButton}>opened</button>
    <button id={CLOSED_ISSUE_ID} onClick={this.onChangeRadioButton}>closed</button>
    <IssueList list={this.state.issue_data} />
  )
},
onChangeRadioButton: function(e){
  switch(e.target.id){
    case OPEN_ISSUE_ID:
      getAsyncDataFromBackend(url, {issues: 'open'}, this.onBackendResponse);
      break;
    case CLOSED_ISSUE_ID:
      getAsyncDataFromBackend(url, {issues: 'closed'}, this.onBackendResponse);
      break;
  }
},
onBackendResponse(data){
  this.setState({issue_data: data});
}
//...

In your method getAsyncDataFromBackend you will most likely encapsulate some ajax code.
So all you do in your render function of your react component is calling the <IssueList list={this.state.issue_data} /> component.
I Hope this helped?
EDIT2: I've done some more code examples for AJAX and the rendering part to make it more obvious.
Hope that you catch me now.

A: The most sane solution, while staying within react and not doing flux or state containers, is to pass the data all the way up to the first common parent, and then down again to the consuming component
send in a callback in props to the component with the radio buttons, fire it from within the done-callback in the ajax call with the changes and then the parent can update its state and re render the child with the new data.
EDIT: with the update the question changed to another solution, this was about how you trigger re-renders in siblings/parents when state/data changes in one component.


text:
Q: How to predict multiple linear regression r I am trying to predict the next 24 months based on the following data from the electricity data set in the TSA package. I made a model using linear regression based on which the month and time.
library(TSA)
library(forecast)
data(electricity)
logdata = log(electricity)
month = season(electricity)
time = time(electricity)
model = lm(logdata~month +time(electricity))
summary(model)

However I am having difficulty trying to forecast 24 months into the future.
newelec= ts(rep(0,24), start=end(electricity), freq=frequency(electricity))
month = season(newelec)
mat = as.matrix(model.matrix(~month+time(newelec)+0)[,-1])
pred = forecast(model,mat)

When I do this I get the following error:
Error in `[[<-.data.frame`(`*tmp*`, length(tmpdata) + 1, value = c(1973, : replacement has 396 rows, data has 24

Any help pointing me in the right direction would be great!


text:
Q: Date validation is not working for some condition I want to validate date in such a way so that it should take only 3 month back date from yesterday
i.e. DATE should be >= 3 months and < Current date.
I am getting output as wanted but after alert message its setting that day what ever the user selected. Even-though i have mention return false; and added " UserDate = new Date();"  its not setting "UserDate" to current date. Why its not working. Please help me. Any one can help me in that
Thanks in Advance
CODE:
<asp:TextBox ID="txtdate" AutoComplete="off" placeholder="Enter Sales Date" runat="server"></asp:TextBox>
<ajaxToolkit:CalendarExtender ID="CalendarExtender" OnClientDateSelectionChanged="TDate"
runat="server" TargetControlID="txtdate" Format="dd-MMM-yyyy"></ajaxToolkit:CalendarExtender>
      <script type="text/javascript">
        function TDate() {
        var UserDate = document.getElementById("txtdate").value;
        var ToDate = new Date();
        var minDate = new Date().setMonth(new Date().getMonth() - 3);
        if (new Date(UserDate) > ToDate || new Date(UserDate) < new Date(minDate)) {
             alert('Selection date should be within 3 month from yesturday');
                 return false;
                    }
              return true;
                }
       </script>

After clicking "OK" its again selected 29th date which i don't want i want to select select Yesterday date by default

A: This Enable only 3 months from current date in bootstrap datepicker.
var lastDate = new Date(today.getFullYear(), today.getMonth()+3, today.getDate());

$("#startdate").datepicker({
  isDisabled: function(date) {
    return date.valueOf() < Date.now() ? false : true;
  },
  startDate: "dateToday", // If you need to disable past dates
  autoClose: true,
  viewStart: 0,
  weekStart: 1,
  endDate: lastDate,
  dateFormat: "dd/mm/yyyy"
});


text:
Q: c# cassandra DataStax driver version compatibility Is it possible to use Cassandra version 3.6.0 using DataStax c# driver version 3.0.8 ? If so, why do I get the error unconfigured table "table name" error. What other alternatives do I have?
Edit:
I think the issue is I created the table as TableName , however the driver searches for the table tablename (LOWER CASE FOR T and N) and my query is INSERT INTO TableName(Column1) Values(value1)

A: Yes, you can use that version of the C# driver against Cassandra 3.6 (or really, any 3.x version). I suspect you're getting the "unconfigured table" error because either:

*

*You're not connecting the driver to the keyspace where "table name" has been created.

*You haven't created the table yet in the keyspace the driver is connecting to.

Update: Casing
Sounds like from the comments above you used double quotes when creating tables and the keyspace. My recommendation (if it's feasible) is to just drop and recreate them without the quotes so you don't have to remember to quote everything and use proper case when doing queries. It just tends to be a lot simpler that way. If you want more information on how casing works in CQL, check out the Uppercase and lowercase section of the CQL docs.


text:
Q: Milestone View with animation like candy crush in React-native Want to create an animation like Candy crush of level Update
I want the animation of level change like Candy crush
how the level changes and your user change the position


text:
Q: YouTube iFrame API hangs in buffering state after the playVideo() command on iPad I have a problem with the iFrame API on the iPad (iOS 7, Safari browser). When I try to start the video with the 'player.playVideo()' command, the player goes to black and returns a '3'-state when I call 'player.getPlayerState()' command (says it's buffering).
Hitting the big red YouTube button works, but using the 'playVideo()' command does not. This can be reproduced on Google's own YouTube API demo page: https://developers.google.com/youtube/youtube_player_demo
Make sure you display an iFrame, and hit the blue 'Play' button below the player. On desktop browsers, this works fine, but fails on an iOS7 iPad.
I need the 'playVideo()' command to control a chromeless player (no controls). Any ideas?

A: Try the autoplay feature if hitting the big red button is not a compulsion, i have done so by adding "event.target.playVideo();" to the onReady function in the embeded HTML body. My player shows the big red button and starts itself immediately. I have used the latest ios helper availble on GitHub youtube-ios-player-helper. It is also mentioned on the google developers site Using the YouTube Helper Library to embed YouTube videos in your iOS application


text:
Q: Ugly/Non Anti-Aliased fonts in Java-Swing Applications I've recently switched to Ubuntu and I've installed Oracle's Java JDK 8u45 (32 bit) using the webupd8team/java repository.
Everything seems to be working fine except that the Java-Swing applications are having broken and ugly fonts with no anti-aliasing. Changing the font doesn't work. Native applications like Gedit though having the same font are not affected (nor are non-Swing Java-applications like Eclipse); its only affecting Swing-based applications.
Screenshots:
(jEdit v5.1)

I'm running Ubuntu 15.04 (which is the latest version as of 2015-06-15). My Java version is 1.8.0_45 and 'java -version' gives the following output:
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) Server VM (build 25.45-b02, mixed mode)

I've tried the fixes given in similar questions (here and on other stackexchange sites) but they do not work. I've also added the following lines in the /etc/environment (as given here: https://wiki.archlinux.org/index.php/Java_Runtime_Environment_Fonts) but they are not giving me any apparent results.
JAVA_FONTS=/usr/share/fonts/truetype
_JAVA_OPTIONS='-Dawt.useSystemAAFontSettings=on'

I'm sure there must be a fix for this. The same Java-Applications are working as they should on Windows-7.

A: This problem has long been fixed so I decided I should post the solution. Note that the problem is still there by default but it can be fixed by a parameter.
Adding this line:
_JAVA_OPTIONS='-Dawt.useSystemAAFontSettings=on -Dswing.aatext=true'

to /etc/environment fixes the issue.
This fix works as of Ubuntu 16.04 and OpenJDK 8u151 (haven't checked with Oracle JDK or Java 9).
Working example:

Note: Some fonts and AA settings complicate the problem. In jEdit, I use the default Java fonts ("Dialog" as it's called) for everything. You can probably use a different font for the Text-Area but Dialog is the best for buttons, etc. The best Text-Area AA setting I've found is standard but your mileage may vary.


text:
Q: white page in php can't find the error Hey guys built an basic php script but  when i run it i have a white page can't find the error can someone else see it? The Table from where i collect Datas in mysql has the name zurodnung and i just want to read the datas out and output them as text.

  <title>PHP Test</title>

 <?php
echo(
test1
);
include ("db_login.php");

    $link = mysql_connect($host, $user, $pass) or die ("Keine Verbindung zu der Datenbank moeglich.");
    mysql_select_db($db, $link);

    $sql = "SELECT ID_Zuordnung, HW_Typ, Hostname_alt, zuordnung.Username, Emailadresse, Datum_Ausgabe, Abteilung
        FROM zuordnung
        WHERE Status_Tausch = 'OK' AND Status_Altgeraet = 'NOK'
        ORDER BY Hostname_alt;";

    $result = mysql_query($sql);

    if (mysql_num_rows ($result) > 0)
    {
    $Farbe = "#fffffff";

            echo(''.$resultarray['HW_Typ']."	");
            echo(''.$resultarray['Hostname_alt']."	");
            echo(''.$resultarray['Username']."	");
            echo(''.$resultarray['Emailadresse']."	");
            echo(''.$resultarray['Abteilung']."	");
            echo(''.$resultarray['Datum_Ausgabe']."	");
    }
    else {
    echo(
fail
);
    }
    ?>

A: Your echos are failing;
echo(
test1
); should be echo('
test1
');
and echo(
fail
); should be echo('
fail
');
FYI: echo doesn't require brackets, you could do echo '
fail
';

A: The error is probably here: echo(
fail
); - you need to encapsulate that text in a string.
Now - before you do anything else - set up your development environment to give you the information you need:

*

*Set error_reporting to E_ALL

*Set display_errors to true

*Find out where your error logs are (although, display_errors being on means that the browser will show messages, so you shouldn't have to monitor logs in a development environment - but this is useful for diagnosing production errors).

A: Spaghetti code. Awful thing - try to avoid it.
Wrong lines in your code are:
echo(
test1
);
echo(
fail
);

should be
echo('
test1
');
echo('
fail
');

Also this code:
echo(''.$resultarray['HW_Typ']."	");

can be easily made more human readable this way:
printf('%s	', $Farbe, $resultarray['HW_Typ'] );


text:
Q: Why do Ubuntu notifications fade when I'm hovering them? I don't understand the logic behind this. If a notification pops up and I want it to stay a little longer, I can hover it, but the notification fades, which makes it illegible. On the other hand, when I want to close it immediately, I expect it to close when I click on it, but instead it sticks even harder.
It seems like the logic is reversed here. Can it be changed ?

A: This is the design specification.
I can't find the original text to this, but as far as I can remember, the idea with the translucence on mouseover was designed so when a user needs to read what is below the bubble he/she can uncover it with the mouse pointer.
The Notify-OSD has changed a bit since this document appeared. Notably there are no more buttons on it. But the rational behind it is still the same.
However, I haven't seen a way to configure it as per your description. You would probably have to go to the source and create your own version.
EDIT
Webupd8 has an article how to patch the Notify-OSD to be click-closeable under Ubuntu 12.04.


text:
Q: PHP Query, get the value of a default serial value of newly created record For a Quiz website, I am creating a record for a question, and want to get it's questionid straight after so I can use it in creating answer records. The questionid created at INSERT is a serial value automatically generated.
I am new to PHP and cannot figure out how I may get this value, as this id is the only unique way to id this newly created record. Is there anyway to do so?
This is my code for creating the new record.
$questioncreatequery = pg_query("INSERT INTO question (questionid, quizid, questiontype, qdescription, qfilelocation, noofanswers, answertype) VALUES( default, '".$thisquizid."', '".$questiontype."', '".$qdescription."', '".$qfilelocation."', '".$noofanswers."', '".$answertype."')");

Thanks for your time.

A: The easiest way to get what you need is to use the RETURNING clause, to return a value from your INSERT statement like that:
$questioncreatequery = pg_query("INSERT INTO question (questionid, quizid, questiontype, qdescription, qfilelocation, noofanswers, answertype) VALUES( default, '".$thisquizid."', '".$questiontype."', '".$qdescription."', '".$qfilelocation."', '".$noofanswers."', '".$answertype."') RETURNING questionid");

Then you can use $questioncreatequery just like any query result and get your value:
  $row = pg_fetch_assoc($questioncreatequery);
  echo $row['questionid']; // <= this is the value you want


text:
Q: android webview previous content in background Not sure if this is a problem due to using transparent backgrounds, but I am using a webview to show a webpage to the user, however if the user loads another url from a link or javascript is used to dynamically insert new content into the page the rendering seems to glitch.
By glitch I mean that the page remains in the background whilst the new content / page is loaded in the foreground. They end up overlapping and making everything very unreadable.
I have hardwareacceleration turned off on my webview to enable transparent background, could that be causing the problem?
It's similar to this question Android Webview Content Overlapping While Using Transparent Background.
Many thanks.

A: This was due to the fact I had transparent background on, I removed this and it was okay. Not the best solution but one that is preferred over having glitchy graphics. I mimiced the transparent background by matching the CSS background properties to that of where my WebView was positioned.

A: Had the same problem on Google TV boxes and managed to fix this by forcing WebKit to redraw the DOM from jQuery as in:
$('<style></style>').appendTo($(document.body)).remove();

or (if you don't like jQuery):
document.body.style.display='none';
document.body.offsetHeight;
document.body.style.display='block';

You can inject either of the code fragments dynamically from Android as in webView.loadUrl("javascript:(function(){ /* put the force-redraw-code here */ })()") or do it directly from JavaScript after you altered the DOM.
More related fixes at How can I force WebKit to redraw/repaint to propagate style changes?


text:
Q: Как дождаться завершения нескольких последовательных промисов? Передо мной стоит задача выполнить несколько асинхронных процессов в angularjs ПОСЛЕДОВАТЕЛЬНО. Их количество заранее не известно.
Как пример: в процедуру передается путь и нужно создать все папки последовательно, т.к. следующую папку можно создать только в предыдущей. При этом нужно дождаться завершения.
Я сделал это через рекурсивный вызов _manager, процедура отрабатывает, но о завершении в start не сообщает.
.factory('TEST_F', function ($timeout, $q) {

    var isStop = false;
    var stop = function () {
      isStop = true;
      console.log('stop loop');
    };

    var start = function () {
      console.log('start loop');
      isStop = false;
      var i = 0;
      _manager(i)
        .then(function (data) {
          console.log('---> resolve, i = ' + data.i);
        }, function (data) {
          console.log('---> reject, i = ' + data.i);
        });
    };

    var _manager = function (i) {
      var deferred = $q.defer();
      _doer()
        .then(function (data) {
          i++;
          console.log('isStop = ' + isStop, 'i = ' + i);
          if (data.state === 'ok' && !isStop) {
            //deferred.resolve({state: 'ok', i: i});
            return _manager(i);
          } else {
            deferred.reject({state: 'error', i: i});
            return {state: 'error', i: i};
          }
        }, function (data) {
          deferred.reject({state: 'error', i: i});
          return {state: 'error', i: i};
        });
      return deferred.promise;
    };

    var _doer = function () {
      var deferred = $q.defer();
      $timeout(function () {
        console.log('loop');
      }, 2000)
        .then(function (data) {
          console.log('+2 sec');
          deferred.resolve({state: 'ok'});
        })
      ;
      return deferred.promise;
    };

    return {
      stop: stop,
      start: start
    }
  })

Подскажите пожалуйста, как можно реализовать последовательное выполнение асинхронных процедур?

A: @Regent, учел Ваши подсказки и переписал _manager.

var _manager = function (i) {
      var deferred = $q.defer();

  _doer(i)
    .then(function (data) {
      i++;
      console.log('isStop = ' + isStop, 'i = ' + i);
      if (data.state === 'ok' && !isStop && i < 7) { // доп. условие остановки
        //deferred.resolve({state: 'ok', i: i});
        return _manager(i);
      } else {
        //deferred.resolve({state: 'end', i: data.i});
        return {state: 'end', i: data.i};
      }
    }, function (data) {
      //deferred.reject({state: 'error', i: data.i});
      return {state: 'error', i: data.i};
    })
    .then(function (data) {
      if(data.state === 'ok') {
        deferred.resolve({state: 'ok', i: data.i});
      } else if (data.state === 'end') {
        deferred.resolve({state: 'end', i: data.i});
      } else {
        deferred.resolve({state: 'error', i: data.i});
      }
    })
  ;

  return deferred.promise;
};

Теперь все работает так, как мне нужно. Но мне кажется, что это можно написать как-то короче.

A: У вас нет условия остановки. Поскольку i может расти сколь угодно долго - ничего и не получается.


text:
Q: how ignore part of the target string Suppose I have some targets in a Makefile as below:
A-foobar-int:
    mvn test -Dtest.env=(@:X-foobar-%=%)

B-foobar-qa:
    mvn test -Dtest.env=(@:X-foobar-%=%)

C-foobar-int:
    mvn test -Dtest.env=(@:X-foobar-%=%)

Currently, the X as in X-foobar-% is something I am trying to figure out. Basically, what I want to achieve is have a general pattern in all the target actions, instead of A-foobar-%, B-foobar-%, or C-foobar-%. So, what should I do?

A: If I understood your question correctly, this does what you want:
%-foobar-int:
    @echo mvn test -Dtest.env=$(@:$*-foobar-%=%)

%-foobar-qa:
    @echo mvn test -Dtest.env=$(@:$*-foobar-%=%)

There's only 2 rules because A-foobar-int and C-foobar-int are both handled by the first rule. The rules use $* to get the value of the stem matched by the target patterns. (And I'm using echo to check the results because I not set to run the command.)

A: So, you want to drop the first two tokens of $@ (when - is used as a tokenizer).
Here we go:
drop-two-tokens-helper = $(subst $(word 1,$3)$2$(word 2,$3)$2,,$1)

drop-two-tokens = $(call drop-two-tokens-helper,$2$2$2$1,$2,$2$2$2$(subst $2, ,$1))

A-foobar-int:
    mvn test -Dtest.env=$(call drop-two-tokens,$@,-)


text:
Q: How can I remove rows that contain more than two 0 values? Suppose I have the following dataset:

ID
Col_A
Col_B
Col_C
Col_D

1
30
0
20
5

2
20
0
10
0

3
0
0
0
10

4
15
10
15
5

Which function in R can I use to get rid of rows that have more than two "0"-values, so that the output results in:

ID
Col_A
Col_B
Col_C
Col_D

1
30
0
20
5

2
20
0
10
0

4
15
10
15
5

A: We can create a logical vector with rowSums to subset the data
subset(df1, rowSums(df1[-1] == 0) < 3)
  ID Col_A Col_B Col_C Col_D
1  1    30     0    20     5
2  2    20     0    10     0
4  4    15    10    15     5

data
df1 <- structure(list(ID = 1:4, Col_A = c(30L, 20L, 0L, 15L), Col_B = c(0L,
0L, 0L, 10L), Col_C = c(20L, 10L, 0L, 15L), Col_D = c(5L, 0L,
10L, 5L)), class = "data.frame", row.names = c(NA, -4L))


text:
Q: Salesforce subscribe topic I've got 2 SalesForce connectors subscribing on /ContactTopic & /AccountTopic.
Now when I check my log files I notice that, after 19 hours of runtime (application is running on mule enterprise), I've got 5 subscribes on each topic.
INFO  2015-01-14 08:05:16,403 [HttpClient-517] org.mule.modules.salesforce.SalesforceBayeuxClient: Re-Subscribing to channel: /topic/AccountTopic
INFO  2015-01-14 08:05:16,485 [HttpClient-517] org.mule.modules.salesforce.SalesforceBayeuxClient: Re-Subscribing to channel: /topic/ContactTopic
INFO  2015-01-14 08:05:17,067 [HttpClient-1363] org.mule.modules.salesforce.SalesforceBayeuxClient: Re-Subscribing to channel: /topic/AccountTopic
INFO  2015-01-14 08:05:17,149 [HttpClient-1363] org.mule.modules.salesforce.SalesforceBayeuxClient: Re-Subscribing to channel: /topic/ContactTopic
INFO  2015-01-14 08:06:11,247 [HttpClient-601] org.mule.modules.salesforce.SalesforceBayeuxClient: Re-Subscribing to channel: /topic/AccountTopic
INFO  2015-01-14 08:06:11,329 [HttpClient-601] org.mule.modules.salesforce.SalesforceBayeuxClient: Re-Subscribing to channel: /topic/ContactTopic
INFO  2015-01-14 08:06:17,231 [HttpClient-1576] org.mule.modules.salesforce.SalesforceBayeuxClient: Re-Subscribing to channel: /topic/AccountTopic
INFO  2015-01-14 08:06:17,313 [HttpClient-1576] org.mule.modules.salesforce.SalesforceBayeuxClient: Re-Subscribing to channel: /topic/ContactTopic
INFO  2015-01-14 08:06:19,451 [HttpClient-1603] org.mule.modules.salesforce.SalesforceBayeuxClient: Re-Subscribing to channel: /topic/AccountTopic
INFO  2015-01-14 08:06:19,533 [HttpClient-1603] org.mule.modules.salesforce.SalesforceBayeuxClient: Re-Subscribing to channel: /topic/ContactTopic

After the subscribe I simply use a datamapper to insert everything into a MYSQL database.
Is this a bug in Mule or am I doing something wrong here?
Thanks.

A: That log file doesn't necessarily means you have 5 subscribers. If there is any problem with the connection the suscription will be reconnected, and that could explain your re-subscriptions.

A: I've finally solved it. Something very stupid, I was subscribing on API 29, while my application was using 31.. I think this way it couldn't re-subscribe properly on a 'expire' notification. In any case, it is working right now. Thanks!


text:
Q: How to have multiple selection of items on combobox Hey I wanted to know how can I select multiple items from the combobox in XAML?
Note: I'm using Data Binding.
Like this image:

A: You can use CheckBox as the Items of ComboBox.
And when the CheckBox is checked, it is important to modify the PlaceholderText of ComboBox, by default it will show the selected Item, but we can modify it to show all the items which is checked.
For example here: How to make a List of CheckBoxes like in the Alarm & Clock App.


text:
Q: Simple Irreducibility Question in $\mathbb{Z}[\sqrt{13}]$ I'm trying to show that $x^2+3x-1$ is irreducible in $\mathbb{Z}[\sqrt{13}]$.  I have that the roots are $\frac{-3+\sqrt{13}}{2}$ and $\frac{-3-\sqrt{13}}{2}$, but I don't believe this is enough to show irreducibility.  What else would I need?

A: In fact, since $x^2+3x-1$ is a (monic) quadratic polynomial, it is enough; the only way it could factor is into linear factors, which would require that its roots lie in the given ring.
Note that this is not true for quartics and higher: for example, $x^4+4=(x^2+2x+2)(x^2–2x+2)$ factors over $\mathbb{Z}$ even though its roots certainly are not integers.


text:
Q: MongoDB - Delete item in nested array I saw a lot of similar questions about this but couldn't make it work in my collection.
How can I delete a specific comment (you can assume that I know the userId).
For example, I want to remove comment with commentId=3 and I know that it's under userId=1.
[
{
    userId: "1",
    posts: [
        {
            postId: "2",
            comments: [
                {
                    commentId: "3",
                    ...
                },
                ...
            ]
        },
        ...
    ]
},
...
]

Thanks!

A: This works with Mongodb 4.2 and will remove first array entry from "comments" if it matches the "commentId" 3
db.posts.update(
    {"userId" : "1"},
    {$pull : {"posts.$[].comments" : {"commentId":"3"}}}
)

If you would like to remove all array entries use:
db.posts.update(
    {"userId" : "1"},
    {$pull : {"posts.$[].comments" : {"commentId":"3"}}},
    {"multi": true}
)

A: Have you tried using the deleteOne()function ?  try and have a look on MongoDb documentation. MongoDbDocumentation


text:
Q: python 3.6 'TypeError: invalid destination position for blit' I have another Python Error, now a TypeError..... Here's the error,
Traceback (most recent call last):
  File "C:/Users/dongjune/Desktop/PyCharm/PyFlying/PyFlying7.py", line 194, in
<module>
initGame()
  File "C:/Users/dongjune/Desktop/PyCharm/PyFlying/PyFlying7.py", line 190,
in initGame
    runGame()
  File "C:/Users/dongjune/Desktop/PyCharm/PyFlying/PyFlying7.py", line 146, in
runGame
    drawObject(bat, bat_x, bat_y)
  File "C:/Users/dongjune/Desktop/PyCharm/PyFlying/PyFlying7.py", line 21, in
drawObject
    gamepad.blit(obj, (x,y))
TypeError: invalid destination position for blit

Here's the drawObject,
    def drawObject(obj, x, y):
        global gamepad
        gamepad.blit(obj, (x,y))

Line 145 to 154:
        if not isShotBat:
               drawObject(bat, bat_x, bat_y)
          else:
               drawObject(boom, bat_x, bat_y)
               boom_count += 1
               if boom_count > 5:
                    boom_count = 0
                    bat_x = pad_width
                    bat_y = random.randrange
                    isShotBat = False

Now top of runGame...
    def runGame():
        global gamepad, aircraft, clock, background1, background2
        global bat, fires, bullet, boom

        isShotBat = False
        boom_count = 0

Please fix this error!!!


text:
Q: SQL - Get all rows of table one and count of rows How do I create an SQL query which gets all the rows of the table and count of rows inserted under e-mail?
I tried something like this, but this groups the rows and so I don't get all the rows.
SELECT *, COUNT(email) AS 'count' FROM adverts GROUP BY email

A: select a1.*, a2.count
from adverts a1
join
(
  SELECT email, COUNT(*) AS 'count'
  FROM adverts
  GROUP BY email
) a2 on a1.email = a2.email

A: try this,
select *,
    (select count(Email)
    from adverts  where adverts.Email =a.Email) as EmailCount
    from adverts as a

or this
SELECT *, COUNT(email) OVER (PARTITION BY  email) as EmailCount FROM adverts


text:
Q: NGRX - Using hashes instead of arrays for state actually I'm using NGRX (Redux for Angular). At the beginning I have started to store my entities as arrays inside my state. After reading some articles I want to store my entities as hashes while I think it is more performant accessing an entity of entities using the id instead of filtering an array.
But I'm actually unsure doing that the right ngrx way.
Feel free to check my (working - but best practice?) sample here:
Ngrx Articles Sample
Inside the articles.component you will find an articleReducer and an ArticlesComponent, that will use the store to get all articles and to get one concrete article.
For each unsure part I have comment that with QUESTION x - ...
If you don't want to check the complete sample, here are the Question Snippets:
Question 0:
export const initialState: ArticleState = {
  foo: 'bar',
  articlesById: [], // QUESTION 0: What is a good usecase to hold an array with the id's when Object.keys(hash) will give the same?
  articleEntities: {}
}

Question 1 + 2:
case GET_ALL_ARTICLES: {

// QUESTION 1: is this a good choice? Or is there a better alternative to create the hash?
   const articleHash: { [id: number]: Article} = {};
   action.payload.forEach(article => articleHash[article.id] = article);

  return {
    ...state,

    // QUESTION 2: is this a good choice? Or is there a better alternative?
    articlesById: action.payload.map(article => article.id),
    articleEntities: articleHash
  }
}

Question 3:
// QUESTION 3 - Getting all articleEntities as Array for ngFor : is this a      good choice? Or is there a better alternative?
  this.articles$ = this.store.pipe(
    select('articles', 'articleEntities'),
    map(entities => Object.keys(entities).map(id => entities[id]))
  );

Question 4:
const givenIdByRouterMock = 2;
// QUESTION 4 - Getting one concrete Article for given id : is this a good choice? Or is there a better alternative?
this.article$ = this.store.pipe(
  select('articles', 'articleEntities'),
  map(entities => entities[givenIdByRouterMock])
);

If I will update some article (for instance with id 2) using a new action, I want, that the component including the article will be updated.
Are this valid variants or are there better options, solutions? Feel free to fork the stackblitz sample with other variants/code snippets.
Thanks!

A: Q0: the ids property can be used to indicate ordering. Another point is if you delete an entity, it's sufficient to only remove it from the this array, which is a simpler task in comparing to remove it from your dictionary.
Q1: your solution works, I prefer using a reduce
Q2: that's fine
return {
  products: action.payload.products.reduce((dict, product) => {
    dict[product.sku] = product;
    return dict;
  }, {}),
  productSkus: action.payload.products.map(product => product.sku),
};

Q3: in your selectors you should indeed transform it to an array. If you're using a ids property (see answer1) you should use ids.map(id => entities[id]).
Q4: indeed to select a specific entity use entities[id]
Extra:

*

*NgRx has a package @ngrx/entity which handles state in this manner - unsorted_state_adapter.ts - state_selectors.ts

*Instead of selecting data with this.store.pipe(select('articles', 'articleEntities')), I think you should take a look at NgRx selectors which is cleaner imho.

*Since Angular 6.1 you can also use ngFor over a dictionary with the keyvalue pipe.
.
<mat-nav-list>
      <a *ngFor="let member of familyMembers | async | keyvalue"
        mat-list-item [routerLink]="['/groceries', member.key]">
          {{ member.value.avatar }} {{member.value.name}}
      </a>
</mat-nav-list>

A: If order matter - use Array as properties order in objects is not guaranteed.
To optimize look up in Array we can create selector that transform Array to Object.
It's better to keep state normalized (no need to keep the value that we can compute from others).
export interface ArticleState {
  foo: string;
  articles: Article[];
}

export const selectFeature = (state) => state.articleState;
export const selectFeatureArticles = createSelector(selectFeature, state => state.articles);
export const selectFeatureArticlesMap = createSelector(
  selectFeatureArticles,
  articles => _.keyBy(articles, 'id' )
);

QUESTION 0: What is a good usecase to hold an array with the id's when
  Object.keys(hash) will give the same?

use Array and selector that transform Array to Object

QUESTION 1: is this a good choice? Or is there a better alternative to
  create the hash?

action.payload.reduce((hash, article) =>({...hash, [article.id]: article}), {});

or Lodash keyBy
_.keyBy(action.payload, 'id' );

QUESTION 2: is this a good choice? Or is there a better alternative?

It's ok.

QUESTION 3 - Getting all articleEntities as Array for ngFor : is this
  a good choice? Or is there a better alternative?

Store articles in Array.

QUESTION 4 - Getting one concrete Article for given id : is this a
  good choice? Or is there a better alternative?

I't ok.


text:
Q: why does captcha fail on ie 9 On a browser by browser comparison.  Captcha in the yabe example worked great on Firefox 5.0 but was randomly generated junk on Internet Explorer 9
�PNG  IHDR�2��" IDATx��\}lE�*P+-RK��4DkD�j"*�F$�j$(�b� *��>BAĈ�"}�&5"��1�b�? ��ZE�h@c@-    X�G_�3ys�r���}���/���w�s���ٙ�}O ���s�ӀM���o7�^��<`-p0Ev'K�wo���" �5�z�E����PU��o�Y3
�-4�g`�r���{� `1p#����+�2��l�V��¸�n�?� l��(/IBʆ�7\� N����i���\�/�i ;��)lx�m�ܛ        \

etc etc etc
Is there a way to make captcha work as expected on IE9?

A: I found this snippet:
Images.Captcha captcha = Images.captcha();
String code = captcha.getText("#E4EAFD");
Cache.set(id, code, "30mn");
renderBinary(captcha);

I think you should set the content type before rendering:
response.setContentTypeIfNotSet("image/jpeg");

A: On a similar topic, you may want to give the recaptcha module a try link.
The module integrates Google's captcha engine into you app. 2 minute integration garantied.
Captcha should have never made it to the core of Play - it doesn't go along the philosophy of the framework.


text:
Q: select all results from only certain tables Using SQL in C# from a stored procedure that returns multiple tables I have a stored procedure that returns about 20 tables.
i.e.:
TABLE 1
    id|a
    01|whatever
TABLE2
    id|b
    01|whatever
TABLE3
    id|c
    01|whatever
    02|whatever2
    03|whatever3
    04|whatever4

I use the following code to only grab the result from the tables with only 1 column and 1 row:
            sqlReader.Read();
            rows = Convert.ToString(sqlReader.GetValue(0));
            sqlReader.NextResult();

When I move to the next result, what can I use to get the results of the tables (would be helpful to grab only columns with no NULL values as well)?
EDIT:
How do I get from the TABLE with COLUMN 'c'


text:
Q: Bash Redirects That I Don't Understand I have a variable called payload that points to a file and I have this line that is completely baffling me.  Can anyone interpret this for me?
cat > $payload <&0

Above this line I also have other cryptic messages that I don't understand either.  Perhaps you could help me with this at the same time.
exec 3>&1
exec 1>&2

A: exec when given only redirections will set them for the remainder of the script.
If you do exec 1>/tmp/myfile, then any text that gets printed to stdout (or rather, file descriptor 1) will be sent to that file instead of your terminal. This is pretty handy for logging, particularly when you do something tricky like
exec 1> >(ts | tee -a /var/log/myscript.log)

You can also redirect a file descriptor to another file descriptor's destination. exec 3>&1 redirects fd 3 to whatever fd 1 is currently pointing to.
The 2 exec calls set fd 3 to print to the current destination for fd 1 (probably /dev/stdout) and then stdout is redirected to stderr.
If you invoke that script like
bash myscript 2>/dev/null

Then you'll only see stuff printed like echo hello >&3

The cat <&0 is odd: by default cat reads from stdin if no filenames are given. We'd have to see more context to figure out that apparent redundancy.


text:
Q: encapsulate custom service from app I was reading stuff about defining my own services for angularjs. But in all examples the service is directly defined on my app via myApp.factory(...) call. See the offical docs for an example. I'm asking how I would define my service totally encapsualted from my app. So that I can share the service easily over different apps. I would like to simply include the .js file in which the service is defined and inject in into my app. Am I thinking wrong or is there a proper solution for this?
Felix

A: Yes either you can Define the global services or use factory pattern.
1) Defining the global service helps you in retrieving that global services into you multiple app.
function SimpleService($scope){
//define your service here
};

2) You can use factory design pattern and can define multiple services inside your factory and let say you wants to use your services in many apps(e.g. app1, app2, app3 etc.)
function SimpleFactory($scope){
//define your service here
};
app1.factory(SimpleFactory)
app2.factory(SimpleFactory)
app3.factory(SimpleFactory)


text:
Q: Bash scripting arguments I am currently taking a linux class.  I pretty much have to learn stuff on my own.  I have writtent this script to produce a date format based on the argument.  Ie (./script.sh one).  I am having an issue getting this script to do just that.  I think that i have something wrong.  Any help would be greatly appreciated. here is the script:
#!/bin/bash

if [ $1="one" ]
    then
        date +%m-%d-%y

elif [ $2="two" ]
    then
        date +%d-%m-%y

elif [ $3="three" ]
    then
        date +%A,%B-%d,%Y

elif [ $4="four" ]
    then
        date +%s
elif [ $5="five" ]
    then

fi

A: Shell scripts are counter-intuitively whitespace-sensitive. There must be spaces before and after the equal signs. You also can't have a completely empty if statement. There must be at least one statement in there. If you don't have anything, writing : is the common idiom for a null statement.
if [ $1 = "one" ]; then
    date +%m-%d-%y
elif [ $2 = "two" ]; then
    date +%d-%m-%y
elif [ $3 = "three" ]; then
    date +%A,%B-%d,%Y
elif [ $4 = "four" ]; then
    date +%s
elif [ $5 = "five" ]; then
    :
fi

I am guessing you might also want to use $1 in all of the checks, not $1 through $5—i.e., check what the first argument is. If that's true then you could swap the ifs for a case.
case $1 in
    one)   date +%m-%d-%y;;
    two)   date +%d-%m-%y;;
    three) date +%A,%B-%d,%Y;;
    four)  date +%s;;
    five)  ;;
esac


text:
Q: Django passing from DropDownlist to View I am trying to get the value of the Drop-down Menu Selected. I have done the following and it is returning a 'null' value.
I think the problem is here: newupload = request.POST('nameProjects') but I'm not sure which on how to get it working.
upload.html
<form class="form" method="POST" action="upload">
<select id="ddProjects" name="nameProjects">
    {% for project in projects %}
      <option value="{{ project.id }}">{{ project.name }}</option>
    {% endfor %}
</select>
</form>

views.py
def upload_new(request):
    newupload = Upload()
    projects = Project.objects.all()
    newupload.project = request.POST['nameProjects']
    newupload.save()
return render(request, 'upload.html', {'projects':projects})

A: In the views.py, you should use request.POST['nameProjects'] because request.POST will give a dictionary.  If you want to store the project object in upload model, we need to give the project model instance variable or can give the id.

def upload_new(request):

    newupload = Upload()

    projects = Project.objects.all()

    newupload.project_id = request.POST['nameProjects']

    newupload.save()

return render(request, 'upload.html', {'projects':projects})


text:
Q: Why is $E_A(Pr(\Theta \leq 0 | A= \alpha, X=x) | X=x)) = Pr_{\pi}(\Theta \leq 0 | X = x)$? I'm reading Casella & Berger (1987) [1]. On page 107, the following can be found:

We use the notation $Pr_{\pi}(H_0|x)$ to indicate that $\pi$ is the prior used in calculating a posterior probability. Consider the random triple $(A, \theta,x)$ with joint distribution defined by the following. The distribution of $X|\Theta=\theta$ has density $f(x-\theta)$, the distribution of $\Theta|A=\alpha$ is $\pi_{\alpha}$, and the distribution of $A$ is $P$. Then for any $\pi \in \Gamma_M$,
  $$\begin{align} Pr_{\pi}(H_0|x) & = Pr_{\pi}(\Theta \leq 0 | X = x) \\ &= E_A(Pr(\Theta \leq 0 | A= \alpha, X=x) | X=x))\end{align}$$

Here, $\Gamma_M$ is the mixture of all elements of the set $\Gamma = \{\pi_{\alpha}: \alpha \in \mathcal{A}\}$, which is a class of prior distributions on the real line indexed by the set $\mathcal{A}$. $P$ is some probability measure on $\mathcal{A}$ and $f(x-\theta)$ is symmetric about zero and has monotone likelihood ratio.
I've got a hard time to understand the last equality in the equation stated above, namely:
$$E_A(Pr(\Theta \leq 0 | A= \alpha, X=x) | X=x)) = Pr_{\pi}(\Theta \leq 0 | X = x)$$
Any hints and help would be greatly appreciated.
[1] Casella, G., & Berger, R. L. (1987). Reconciling Bayesian and frequentist evidence in the one-sided testing problem. Journal of the American Statistical Association, 82(397), 106-111.

A: to show
$$ Pr_{\pi}(\Theta \leq 0 | X = x) = E(Pr(\Theta \leq 0 | A= \alpha, X=x) | X=x))$$
it is better to prove
$$ Pr_{\pi}(\Theta \leq 0 | X ) = E(Pr(\Theta \leq 0 | A, X) | X))$$
start with
$E(P(\Theta \leq 0 | A, X) | X))=E(E(I_{\Theta \leq 0} | A, X) | X))$
$=E(E(I_{\Theta \leq 0} | \sigma(A, X)) | \sigma(X)))$
since $\sigma(X) \subset \sigma(A, X)$ by tower property
$=E(I_{\Theta \leq 0} |\sigma(X))$
$=E(I_{\Theta \leq 0} |X)$
$=P(\Theta \leq 0 |X)$ so
$$ Pr_{\pi}(\Theta \leq 0 | X ) = E(Pr(\Theta \leq 0 | A, X) | X))$$
and in hence
$$ Pr_{\pi}(\Theta \leq 0 | X = x) = E(Pr(\Theta \leq 0 | A= \alpha, X=x) | X=x))$$


text:
Q: Deleting all commits in a branch after certain commit I'm having a difficult time grasping how I can use rebase/revert to accomplish this.
I was working on my master branch and after a certain commit my software stopped working. I did not want to loose the changes made at the time and I was pressured on time to reach a milestone so I went back a few commits with git checkout and created a new branch called working and started pushing all my changes there. Later on I realized that these changes (made on the master branch) were not needed. Now I want to go back to my master branch and delete all the commits after the commit I used to create my working branch and then merge my working branch to master branch.
I've created an image with an online photo editor to try and explain what I'm trying to do. I hope it helps:

I want to keep everything after 5cb967f. get rid of everything between 5cb967f and a0c1de2 (not including those)

A: You have two options:
Rewrite history (destructive)
You can use git-rebase to rewrite history, ommiting these commits. You can run an interactive rebase. From your description, I'm not certain exactly what you have in master and working, but I am assuming all the history (wanted and unwanted) is present there.
  git checkout master
  git rebase -i a0c1de2

At this point, your $EDITOR will pop up with a list of commits from a0c1de2 to the HEAD of master. You can remove the lines corresponding to c460070..a3cb10e to delete them from history.
Your history will be rewritten locally. If you attempt to push this change, it will be a non fast-forward update.
Revert, preserving history (non-destructive)
IF you prefer to keep the history, you can revert a sequence of commits:
git checkout master
git revert c460070..a3cb10e

This will create 7 new commits, each reverting the changes in these unwanted commits, in order.

A: Something about the history graphic is screwy.  Going by the text markup in it, what you want is simply
$ git branch -f master working

because there weren't any post-working-base commits on master that you want to keep.


text:
Q: What tool was used to generate these technical diagrams? I was reading a paper or Computed Tomography, and I found these two nice diagrams:

And I was wondering, what tool was used to make them. I've worked with Tikz for example, but I believe it would be time consuming to write all that code for these graphs. In addition, I've looked at Inkscape and Gimp, but I don't see how they can be used for these type of diagrams. Finally, I looked at Metapost and that seems like the best candidate. What do you guys think? Is there a nice GUI for drawing these kind of technical plots (2D,3D) with labels and latex fonts? Or should I just stick with coding it up in Metapost or Tikz?
Thanks!

A: That doesn't look like it was created with a 3D-aware drawing tool - the sheets look like they were meant to be sections from a cylinder that didn't quite come out right, and it has that freehand look about it.  I guess it wasn't created using Word's Drawing Tool: building up pictures by joining together curves is brutal in that environment, but Visio would be a good bet.
If you want a Tex-aware GUI drawing tool, people speak highly of Inkscape, which is a serious 2D drafting tool with support for ensuring lines are in proportion, to help avoid the freehand look.  Inkscape supports export to embedded PS/ PDF, as well as to Xfig, allowing you to use the Xfig export function.  Additionally, it supports export to SVG, which is used by the inkscape2tikz program. I can't say more, since I haven't seriously used Inkscape.
Xfig gives you less sophisticated drawing support, but better integration with Tex: it allows limited export to both the Latex picture environment and full export to Metapost.  It is pleasant enough to use, but the results do look hand drawn.
Or finally, the figures do not look so difficult to draw algorithmically either using Metapost or Tikz.  Metapost is very nice for computing complex figures using line intersections, which would be useful for the example diagrams.

A: For years, under linux, the answer to that question has been Xfig. However, the interface of Xfig is a bit cumbersome (especially the use of the three buttons is necessary most of the time) if you want a GUI. On other platforms, use of any vector drawing program should be enough.
There are many defects in the original image. See for example the voxel box in pseudo 3d, the "rows" arrow and the \phi and \theta angles.
As Joseph wrote, Tikz or PSTricks seems a good candidate for this; this is not a GUI (Xfig can export to either of these if I recall correctly).