text:
Q: How to pass Multiple parameters as CommandParameter in InvokeCommandAction In WPF App Using MVVM I am using System.Windows.interactivity.dll  to get mouse events in my ViewModel in the following manner.
 <ListBox x:Name="listBox" ItemsSource="{Binding HeaderList}" DisplayMemberPath="Text" Width="Auto"   Margin="0,0,0,300" Height="Auto"  >
    <i:Interaction.Triggers>
            <i:EventTrigger EventName="MouseLeftButtonUp">
                <i:InvokeCommandAction Command="{Binding MouseLeftButtonUpCommand}"
                         CommandParameter="{Binding SelectedItem, ElementName=listBox}"/>
        </i:EventTrigger>

        </i:Interaction.Triggers>
</ListBox>

and in ViewModel.
        public class Headers
    {
        public Headers()
        {
            IsSelected = false;
        }

        public string Text { get; set; }
        public ListBox Control { get; set; }
        public bool IsSelected { get; set; }
    }
   public ObservableCollection<Headers> HeaderList
    {
        get { return _headerList; }
        set
        {
            _headerList = value;
            base.OnPropertyChanged("HeaderList");
        }

    }
 public ICommand MouseLeftButtonUpCommand { get; set; }
 public DesignTemplateViewModel()
    {
        string file = SessionHelper.FilePath;
        List<string> columns = new List<string>();

        if (!string.IsNullOrEmpty(file))
        {
            ExcelHelper Excel = new ExcelHelper(file);
            columns = Excel.GetHeader();
        }
        else
        {
            columns.Add("Name");
            columns.Add("FatherName");
            columns.Add("MotherName");
            columns.Add("Class");
            columns.Add("RollNo");
            columns.Add("ModeOfTransport");
            columns.Add("Phone");
            columns.Add("Mobile");
        }
        HeaderList = new ObservableCollection<Headers>();

        foreach (string column in columns)
        {
            HeaderList.Add(new Headers
            {
                Text = column,
            });
        }

        MouseLeftButtonUpCommand = new RelayCommand((item) => OnMouseLeftButtonUp((Headers)item));
    }
  private void OnMouseLeftButtonUp(Headers sender)
    {
        ListBox control = sender.Control as ListBox;
        DragDrop.DoDragDrop(control, sender.Text, DragDropEffects.Copy);
    }

So here I need to pass multiple objects such as Control that generated this event, Mouse related properties etc. Now I  am Passing single parameter and this code is working fine.
So My Questions is that how can pass Multiple parameters from Xaml(View) and access them on this ViewModel.
Any code help??

A: You can try with custom Converter and MultiBinding
<CommandParameter>
      <MultiBinding Converter="{StaticResource CustomConverter}">
       <Binding ElementName=".." Path=".."/>
       <Binding ElementName=".." Path=".."/>
      </MultiBinding>
</CommandParameter>

Converter
class CustomConverter : IMultiValueConverter
{
    public object Convert (object[] Values, Type Target_Type, object Parameter, CultureInfo culture)
    {
        var findCommandParameters = new FindCommandParameters();
        findCommandParameters.Property1 = (string)values[0];
        findCommandParameters.Property1 = (string)values[1];
        return findCommandParameters;
    }
    public object[] ConvertBack(object value, Type[] targetTypes, object parameter,   System.Globalization.CultureInfo culture)
    {
       throw new NotImplementedException();
    }
}

Parameters
public class FindCommandParameters
{
  public string Property1 { get; set; }
  public string Property2 { get; set; }
}

A: I Agree with Aghilas. That's how it's done.
I improved upon Aghilas's code to clarify what was missing.
note that    "i:InvokeCommandAction.CommandParameter" must be put inside the invokeCommandAction declaration.
    <ListBox x:Name="listBox" ItemsSource="{Binding HeaderList}" DisplayMemberPath="Text" Width="Auto"   Margin="0,0,0,300" Height="Auto"  >
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="MouseLeftButtonUp">
                <i:InvokeCommandAction Command="{Binding MouseLeftButtonUpCommand}">
                    <i:InvokeCommandAction.CommandParameter>
                        <MultiBinding Converter="{StaticResource XAMLResourceAddConverter}">
                            <Binding ElementName="listBox" Path="SelectedItem"/>
                            <Binding ElementName="listBox" Path="SelectedItem"/>
                        </MultiBinding>
                    </i:InvokeCommandAction.CommandParameter>
                </i:InvokeCommandAction>
            </i:EventTrigger>

        </i:Interaction.Triggers>
    </ListBox>


text:
Q: How to set a key on a component with React.cloneElement or React.Children.map I have a table parent component where I a map through data and set rows. I have created a component that should be used for each row. I am sending that to the table component as a child prop. This is the code in the table component:
     <TableBody>
      {stableSort(data, getSorting(order, orderBy))
        .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
        .map(n => {
          const isSelected = this.isSelected(n.id);
          return React.cloneElement(children, { eksamensett: n, isSelected,  handleClick: (event, id) => this.handleClick(event, id)});
        })}
      {emptyRows > 0 && (
        <TableRow style={{ height: 49 * emptyRows }}>
          <TableCell colSpan={6} />
        </TableRow>
      )}
    </TableBody>

And this is the child component that I am cloning:
const EksamenssettRow = ({eksamensett, isSelected, handleClick, onEksamenssetClicked}) => (
  <TableRow
    hover
    onClick={() => onEksamenssetClicked(eksamensett)}
    role="checkbox"
    aria-checked={isSelected}
    tabIndex={-1}
    key={eksamensett.id}
    selected={isSelected}
  >
    <TableCell padding="checkbox" onClick={(event) => handleClick(event, eksamensett.id)}>
      <Checkbox checked={isSelected}/>
    </TableCell>
    <TableCell component="th" scope="row" padding="none">
      {eksamensett.id}
    </TableCell>
    <TableCell component="th" scope="row" padding="none">
      {eksamensett.klasse.klassekode}
    </TableCell>
    <TableCell align="left">{eksamensett.navn}</TableCell>
    <TableCell align="left">{eksamensett.fastRekkefolge ? 'Fast eksamensset' : 'Randomisert'}</TableCell>
    <TableCell align="left">{formatStringToLocalDate(eksamensett.opprettetDatoTid)}</TableCell>
    <TableCell align="left">{getElapsedTime(eksamensett.endretDatoTid)}</TableCell>
  </TableRow>
);

Then I get the warning:

Warning: Each child in a list should have a unique "key" prop.

Because this is what is being rendered in the react tree:
<EksamenssettRow>
  <TableRow key="1">
  <TableRow/>
<EksamenssettRow/>
<EksamenssettRow>
  <TableRow key="2">
  <TableRow/>
<EksamenssettRow/>
<EksamenssettRow>
  <TableRow key="3">
  <TableRow/>
<EksamenssettRow/>

How can I set the key to the component itself so that I can avoid this warning, which also causes my tests to fail?
I have also used React.Children.map instead of directly using a child:
return React.Children.map(this.props.children, child => {
                      return React.cloneElement(child, { eksamensett: n, isSelected,  handleClick: (event, id) => this.handleClick(event, id)})
                    })[0]

That has given a key to EksamenssettRow, but every EksamenssettRow has received the same key='.0' How can I fix this?

A: What you need to do is set a second parameter in map to index, then give the highest level JSX elment a prop key={index}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Failed to start Apache [root@localhost ~]# systemctl start httpd.service
Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details.
[root@localhost ~]#  systemctl status httpd.service
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
    Active: failed (Result: exit-code) since Wed 2017-02-01 14:41:03 EST; 8s ago
    Docs: man:httpd(8)
          man:apachectl(8)
  Process: 3099 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=1/FAILURE)
  Process: 3098 ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND (code=exited, status=1/FAILURE)
  Main PID: 3098 (code=exited, status=1/FAILURE)

Feb 01 14:41:03 localhost.localdomain systemd[1]: Starting The Apache HTTP Se...
Feb 01 14:41:03 localhost.localdomain httpd[3098]: AH00526: Syntax error on l...
Feb 01 14:41:03 localhost.localdomain httpd[3098]: Invalid command 'Comment',...
Feb 01 14:41:03 localhost.localdomain systemd[1]: httpd.service: main process...
Feb 01 14:41:03 localhost.localdomain kill[3099]: kill: cannot find process ""
Feb 01 14:41:03 localhost.localdomain systemd[1]: httpd.service: control proc...
Feb 01 14:41:03 localhost.localdomain systemd[1]: Failed to start The Apache ...
Feb 01 14:41:03 localhost.localdomain systemd[1]: Unit httpd.service entered ...
Feb 01 14:41:03 localhost.localdomain systemd[1]: httpd.service failed.
Hint: Some lines were ellipsized, use -l to show in full.

A: The problem appears to be a syntactical error in your apache configuration files.  Take a look at your error log (typically /var/log/httpd/error_log or /var/log/apache2/error_log for more information.  Correct the error, and your apache server is likely to start.

A: You can verify your configuration file syntax using:
apachectl configtest

From https://httpd.apache.org/docs/2.4/programs/apachectl.html:
configtest
Run a configuration file syntax test. It parses the configuration files and either reports Syntax Ok or detailed information about the particular syntax error. This is equivalent to apachectl -t.

A: [Wed Feb 01 06:58:40.131743 2017] [core:notice] [pid 11281] SELinux policy enab$
[Wed Feb 01 06:58:40.133098 2017] [suexec:notice] [pid 11281] AH01232: suEXEC m$
AH00558: httpd: Could not reliably determine the server's fully qualified domai$
[Wed Feb 01 06:58:40.165629 2017] [auth_digest:notice] [pid 11281] AH01757: gen$
[Wed Feb 01 06:58:40.167758 2017] [lbmethod_heartbeat:notice] [pid 11281] AH022$
[Wed Feb 01 06:58:40.318077 2017] [mpm_prefork:notice] [pid 11281] AH00163: Apa$
[Wed Feb 01 06:58:40.318136 2017] [core:notice] [pid 11281] AH00094: Command li$
[Wed Feb 01 07:12:30.844891 2017] [mpm_prefork:notice] [pid 11281] AH00170: cau$


text:
Q: C# - Autozip files in a folder based on Year-Month IT has been tasked with reducing the file-server usage rate so I'd like to do my part my compressing old files(ie Excel/Access/Txt).
We have some folders that contain thousands of files so I don't want to just zip the whole directory into one large file - it would be preferrable to have a number of smaller files so that it would be easier for a user to find the data 'bucket' they are looking for.
Is there a way using C# to read through a directory and zip the files into year-month groups (all files from year-month placed together in one zip)?
Or would it be better to use a script like AutoIT?
Or are there programs already existing to do this so I don't have to code anything?

A: Im not sure if your question is about zipping, selecting files from particular year/month or both.
About zipping Peter already mentioned 7-zip and SharpZipLib. I have personally only experience with the latter but its all positive, easy to work with.
About grouping your files it could be done by iterating all the files in the folder and group them by either there created date or last modified date.
pseudo:
var files = new Dictionary<DateTime, IList<string>>();
foreach (var file in Directory.GetFiles(...)) {
   var fi = new FileInfo(file);
   var date = fi.CreatedDate();
   var groupDate = new DateTime(date.Year, date.Month);

   if (!files.ContainsKey(groupDate)) files.Add(groupDate, new Collection<string>());

   files[groupDate].Add(file);
}

now your should have a dictionary containing distinct year/month keys and foreach key a list of files belonging to that group. So for zipping
pseudo:
foreach (var entry in files) {
   var date = entry.Key;
   var list = entry.Value;

   // create zip-file named date.ToString();
   foreach (var file in list) {
      // add file to zip
   }
}

A: Surely you can do this with a bit of C# and libraries like 7-zip or SharpZipLib.

A: You could use System.IO.Directory.GetFiles() to loop through the files on each directory, parsing out by file name and adding them to a 7-zip or SharpZipLib object. If it's thousands of files it might be best to throw it in a service or some kind of scheduled task to run overnight so as not to tax the fileshare.
Good luck to you !
EDIT: As an addendum you could use a System.IO.FileInfo object for each file if you need to parse by created date or other file attirbutes.


text:
Q: Module build failed (from ./node_modules/@angular-devkit/build-angular/node_modules/postcss-loader/dist/cjs.js) ng serve error After update angular 11 to 12, with the following details :

    ./src/app/ngx-admin-lte/src/layouts/login/login.component.ts-1.css!=!./node_modules/@ngtools/webpack/src/loaders/inline-resource.js!./src/app/ngx-admin-lte/src/layouts/login/login.component.ts - Error: Module build failed (from ./node_modules/@angular-devkit/build-angular/node_modules/postcss-loader/dist/cjs.js):
    SyntaxError

    (1:1) /home/hp/Drive1/Project/Angular/iworklist/src/app/ngx-admin-lte/src/layouts/login/login.component.ts Unknown word

    > 1 | ./login.css
        | ^

login.component.ts:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-layout-login',
  styles: ['./login.css'],
  templateUrl: './login.component.html'
})
export class LayoutLoginComponent implements OnInit, OnDestroy {

  constructor( ) { }

  public ngOnInit() {
    window.dispatchEvent( new Event( 'resize' ) );
    document.body.className = 'hold-transition login-page';
  }

  public ngOnDestroy() {
    document.body.className = '';
  }
}

login.css (empty):
package.json:

    {
      "name": "iworklist",
      "version": "0.1.0",
      "scripts": {
        "ng": "ng",
        "start": "ng serve",
        "build": "ng build",
        "test": "ng test",
        "lint": "ng lint",
        "e2e": "ng e2e"
      },
      "private": true,
      "dependencies": {
        "@angular/animations": "~12.2.16",
        "@angular/cdk": "~12.2.13",
        "@angular/common": "~12.2.16",
        "@angular/compiler": "~12.2.16",
        "@angular/core": "^12.2.16",
        "@angular/forms": "~12.2.16",
        "@angular/localize": "^12.2.16",
        "@angular/material": "^12.2.13",
        "@angular/material-moment-adapter": "^12.2.13",
        "@angular/platform-browser": "~12.2.16",
        "@angular/platform-browser-dynamic": "~12.2.16",
        "@angular/router": "~12.2.16",
        "@ng-select/ng-select": "^7.4.0",
        "@types/crypto-js": "3.1.39",
        "admin-lte": "2.3.11",
        "ag-grid-angular": "^25.1.0",
        "ag-grid-community": "^25.1.0",
        "ag-grid-enterprise": "^25.1.0",
        "angular-highcharts": "^12.0.0",
        "big.js": "^6.0.3",
        "bn-ng-idle": "^1.0.1",
        "bootstrap": "^3.4.1",
        "core-js": "^3.9.1",
        "crypto-js": "3.1.8",
        "font-awesome": "^4.7.0",
        "highcharts": "^8.2.2",
        "ionicons": "^3.0.0",
        "jquery": "^3.6.0",
        "jquery-slimscroll": "^1.3.8",
        "moment": "^2.29.1",
        "rxjs": "^6.6.6",
        "tslib": "^2.0.0",
        "zone.js": "~0.11.5"
      },
      "devDependencies": {
        "@angular-devkit/build-angular": "~12.2.16",
        "@angular/cli": "^12.2.16",
        "@angular/compiler-cli": "~12.2.16",
        "@angular/language-service": "~12.2.16",
        "@types/jasmine": "~3.6.0",
        "@types/jasminewd2": "^2.0.8",
        "@types/node": "^12.20.6",
        "codelyzer": "^6.0.0",
        "jasmine-core": "~3.10.1",
        "jasmine-spec-reporter": "~5.0.0",
        "karma": "~6.3.17",
        "karma-chrome-launcher": "~3.1.0",
        "karma-coverage-istanbul-reporter": "~3.0.2",
        "karma-jasmine": "~4.0.0",
        "karma-jasmine-html-reporter": "^1.7.0",
        "postcss-loader": "~3.0.0",
        "protractor": "~7.0.0",
        "ts-node": "~7.0.0",
        "tslint": "~6.1.0",
        "typescript": "~4.3.5"
      }
    }

Could someone help me fix this error ?

A: Finally fix it.
Use the same name with component(ts) name. example:
Rename login.css to login.component.css
Example


text:
Q: Is there a scripting language with C-like syntax? I can neither code Bash nor Python (actually, I am only comfortable with C-like syntax), and, actually, am too busy and lazy to learn them now. But I would like to script some tasks. Is there a scripting language for GNU/Linux, having obvious and comfortable syntax for C/C++/C#/Java developers?

A: If you're comfortable with Java, then try groovy, a scripting language based on the Java platform. There is almost zero learning curve.

A: Ch is a C and C++ interpreter, it can be used for scripting.

A: CINT is another C & C++ interpreter. I don't know if you'd want to have to wrap commands in
system("foo");

though. Maybe a macro like the following (untested)
#define S(cmd) system(cmd);

might be useful in that approach, e.g., S("cp a b")
Maybe not :)

A: You should search for "learn python in 10 minutes".
It covers the most useful python features: lists, tuples, dictionnaries, classes, and of course its awesome indentation system.
Learn it, I personnaly considering python as important after C\C++, because it does so much by default, and as a scripting language, it serves a lot.
Advantages:

*

*Features everything you'll need as a programmer

*A VERY clean and easy syntax, its author says it can be 3 to 4 times more productive than c/c++

Disadvantages:

*

*Speed, but if you're not programming low level where performance matters, it's sufficient.

A: Pike is a scripting language with a C-like syntax. You've never heard of it? Consider this a point against: it's rarely installed by default, it doesn't have many libraries, there's not much literature about it, there aren't many people who can help you with it…
Just pick Perl or Python, the two major scripting languages on unix systems (plus the shell, but it's a trickier language and has a less general scope.). The syntax is only 1% of learning a language anyway. I'd recommend Python as the simplest of the two.

A: If you really want to program in C but not have the long steps of compiling & linking, check out the TCC: the Tiny C Compiler. It even supports running via shebang.

A: Install and try tcsh. You can also make it your default shell, if you want.
Although I don't recommend it. ;-)

A: php-cli, can be quite useful.
php has a bad reputation, but since php version 5 the language is actually quite ok. And the syntax is similar to C/C++/Java.

A: There is cling Cern's project of C++ interpreter based on clang.
Here is Google Talk: Introducing cling, a C++ Interpreter Based on clang/LLVM

A: Nowadays, there's Jancy, a JIT scripting language built off LLVM whose grammar is so close to C that you can often copy/paste C segments directly in without modification.
jancy.org

A: There are some packages available for node that facilitate system scripting.
The node package manager is probably the easiest way to install such packages; node itself can be built from source (with the v8 engine it runs on) or installed via some system package managers.
You may need to learn to use evented I/O in order to get much done.

A: I haven't written it yet, but the best scripting language for C would be... C. Compilers are fast enough now that you could write a little script wrapper that would compile and run your program. Indistinguishable from a scripting language that loads in the source and parses it before executing.
When I get a script working, I'll post it.

A: Perl has essentially the same syntax as C (it's at least as close as C++), and is quite widely installed / available.


text:
Q: How to use Datatable in javascript  $('#dFinalReport').html(_todayOrderLstHtml);
 $('#dFinalReport').dataTable(
  { "sDom": 'l<"floatR pLeft10"T><"floatR"f>rtip',
    "aaSorting": [[3, "asc"]], "iDisplayLength": 20
  });

How to use datatable in javascript?
i declared div element in html and called datatable using div id(dFinalReport).i got a error message --------->
DataTables warning (table id = 'dFinalReport'): Attempted to initialise DataTables on a node which is not a table: DIV
which id i should use to call datatable and when i call?

A: If you are using jquery.datatable plugin then please refer to.
http://www.datatables.net/

A: I had a similar problem and changing the wrapper fixed it for me. I don't know C# but check if you don't have something similar to this. I had the following in my code:

{{=user_table}}

The "{{=user_table}}" basically calls the table - I am using python instead of C#. DataTable has a specific structure, the ID cannot be assigned to a DIV. Changing it to the following fixed my problem:

{{=user_table}}

Edit: Also check the manual on http://www.datatables.net for further instructions - you have to be using a structure that includes thead, and so on..


text:
Q: Anyways to automate finding Unused JavaScript And CSS? Right now, we can find Unused JavaScript And CSS With The Coverage Tab using the Chrome Dev tool, is there any way to integrate this into the Selenium test?
Any suggestion?
Thank you


text:
Q: Pass Arrays from PHP file to JS file I would like to pass an array I have in my PHP file to another file that is written in java script.
This is my array:
$pictures = array(
"1" => array("caption" => "1920x1200px", "tag" => "wallpaper", "link" => "#"),
);

And in my java script file this is the place where I want to call the array:
(At the place where they shall be in the code I wrote TAG, LINK and CAPTION.
Sry if this is a stupid question, but as you see, I have no idea about PHP and java script)
F.helpers.title = {
    beforeShow: function (opts) {
        var text = F.current.title,
            type = opts.type,
            title,
            target;

        if (!isString(text) || $.trim(text) === '') {
            return;
        }

        title = $('

' + text + '

CAPTION

TAG

');

        switch (type) {
            case 'inside':
                target = F.skin;
            break;

            case 'outside':
                target = F.wrap;
            break;

            case 'over':
                target = F.inner;
            break;

            default: // 'float'
                target = F.skin;

                title
                    .appendTo('body')
                    .width(title.width()) //This helps for some browsers
                    .wrapInner('');

                    //Increase bottom margin so this title will also fit into viewport
                    F.current.margin[2] += Math.abs(     getScalar(title.css('margin-bottom')) );
            break;
        }

        if (opts.position === 'top') {
            title.prependTo(target);

        } else {
            title.appendTo(target);
        }
    }
};

A: Try it using JSON. There are quite a few JSON parsers available

A: Encode it as JSON to convert it into a JavaScript literal, then access the resultant value as normal.
var data = <?php echo json_encode(array('foo' => 'bar')); ?>;
console.log(data['foo']);

A: The lifecycle of your PHP script (on the server side) is different from that of JS (on the client side). If you want to pass some information from PHP to client side, you can do one of the following:

*

*You should print this information into the HTML file on the server side itself using your template engine.

*You should return this information through another API by converting it into JSON format that is easy to browse through on the javascript side, and call your API using AJAX.

A: use an ajax call, something like $.post to get the array as a json array,
add an echo json_encode($picture) at the end of your PHP script.

A: PHP just generates files which then you send to the client. JavaScript is executed on the client side. So you should generate in php something like
var pictures = {'1': {caption: '1920x1200px', tag: 'wallpaper', link: '#'}};

and place it in html in script tag for example.
As a variant you may do it this way:
var pictures = <?= json_encode($pictures); ?>;


text:
Q: problem when writing an equation with latex: missing delimiter (. inserted) \end{equation} I tried this and that, but could not solve this problem. Here is the code that produces this error:
\begin{equation}
o=g(h)=\left\{\begin{array}{rcl}
    1 & if & h <   0 \\
    0 & if & h \le 0
\end{array}\right
\end{equation}

The error is given on the line \end{equation} resides.
Thanks.

A: \left\{ must be balanced by a \right\} in the same line. Since you don't want the right delimiter, and since the closing pair is needed, you have to put a null delimiter by \right.
\documentclass{article}
\begin{document}
  \begin{equation}
    o=g(h)=\left\{\begin{array}{rcl}
                     1 & if & h <   0 \\
                     0 & if & h \le 0
\end{array}\right.  %% <--here
\end{equation}
\end{document}

But for this amsmath provides cases environment. I suggest you to use this. A sample will be:
\documentclass{article}
\usepackage{amsmath}
\begin{document}
  \begin{equation}
    o=g(h)=\begin{cases}
              1 & \text{if $ h < 0 $}\\
              0 & \text{if $ h \le 0$}
\end{cases}
\end{equation}
\end{document}

Note the use of \text macro which is also provided by amsmath.

A: \begin{numcases}{|x|=}
x, & for $x \geq 0$ \label{eq:4}
\\ -x, & for$x < 0$ \label{eq:5}
\end{numcases}

You have to use
\usepackage{cases}


text:
Q: Can't set an application icon I've put a PNG image inside /res/drawable and specified it in the manifest, but Eclipse throws an error saying No resource found.
I've searched everywhere, and can't seem to find an answer to this.
The filename appears in autocomplete too, without the extension.
Edit:The icon's filename is ic_menu_umbrella.png
and here's how it appears in the manifest
<application android:label="@string/app_name" android:icon="@drawable/ic_menu_umbrella">

A: I can't comment, so I will answer, try cleaning the project (Right click on the project -> Android -> Fix Android Project and Project -> Clean) before you run it, sometimes I have problems like these.

A:
Go to the folder  make sure the picture exists.

Open Eclipse with administrative previliges.

Make sure your res folder is complete(contains values and layout folders)

Try using another picture. If it works, the problem is in your picture.

Make sure your picture's filename is ic_menu_umbrella.png


text:
Q: How to make a custom FrameLayout with a cover? Looking to make a small Android Compound View/Custom Component, where a FrameLayout is extended so that it has its own fully overlaying "Cover" view (that can intercept clicks and ripple) without repeating that cover in every XML instance.
I don't know whether it is best practice to re-layout the covering View in the Custom FrameLayout's onMeasure or onLayout methods, or if there's a simple XML trick that I'm missing (outside of just using a RelativeView since that would draw and re-draw the layout very often, but if I'm wrong here too correct me please)
CoveredFrameLayout.class
public class CoveredFrameLayout extends FrameLayout {

    private View coverView;

    public CoveredFrameLayout(@NonNull Context context) {
        this(context, null);
    }

    public CoveredFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CoveredFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        inflate(context, R.layout.widget_covered_framelayout, this);

        //

        setBackgroundColor(ContextCompat.getColor(context, R.color.light_red));

        coverView = findViewById(R.id.widget_cover);

        //

        coverView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                coverView.animate()
                        .alpha(0)
                        .setDuration(1000)
                        .withEndAction(new Runnable() {
                            @Override
                            public void run() {
                                coverView.setVisibility(GONE);
                            }
                        })
                        .start();
                view.setOnClickListener(null);
            }
        });
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }
}

widget_covered_framelayout.xml
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <View
        android:id="@+id/widget_cover"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:background="@color/transparent_yellow400"
        android:clickable="true"
        android:foreground="?attr/selectableItemBackground"
        android:visibility="visible" />

</merge>

The XML CoveredFrameLayout being used
    <com.example.oliver.content.ui.widgets.CoveredFrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="8dp"
            android:text="hello" />

    </com.example.oliver.content.ui.widgets.CoveredFrameLayout>

And here's a screenshot of what this is looking like currently.  Just trying to learn the best practice to get that yellow square to dynamically cover the whole FrameLayout!  Thanks y'all!

Here is the end goal result, however this result was only achieved by hardcoding the Cover View's height and width to the pre-calculated height and width in pixels of the view itself.  A dynamic version of this could work fine, but I don't know what is the best practice for where in the onMeasure/onLayout cycle to put this code.


text:
Q: SQLite separating two random numbers public void Isrinkzaidejapirma(){
    String sql = "SELECT rowid FROM Veiksmai WHERE Pirmas < 4 ORDER BY random() LIMIT 2";

    try (Connection conn = this.connect();
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql)){
        while (rs.next()) {
            int zaidejas1id = rs.getInt("rowid");
            //System.out.println(rs.getInt(zaidejas2id));
            System.out.println(zaidejas1id);
        }
    } catch (SQLException e) {
        System.out.println(e.getMessage());
    }
}

With this code I'm getting 2 random numbers. (For example 4 2, 1 2 and etc.).
How can I separate them into two variables?

A: Instead of a while (rs.next()) loop, how about just using
Integer value1 = null, value2 = null;
if (rs.next()) {
    value1 = rs.getInt("rowid");
    if (rs.next()) {
        value2 = rs.getInt("rowid");
    }
}

Then you could use one of those values in a subsequent query like so:
PreparedStatement ps = conn.prepareStatement("SELECT Pirmas FROM Veiksmai WHERE rowid=?");
ps.setInt(1, value1);
rs = ps.executeQuery();


text:
Q: How to get Apache Windows service daemons (procrun prunsrv) to use a java library path so Microsoft SQL Integrated Security Authentication can work I have a Java application that needs to run as a Windows service. The application needs to connect to Microsoft SQL server using Integrated Security. This means that Java needs to have the location of the driver dll in the java library path.
According to the prunsrv documentation, it is possible to pass in JVM options using the following parameter:
++JvmOptions="-Djava.library.path=drivers/MS SQL/x64"

where the path above is specific to my case.
When running the application using java.exe from a command line, and passing in the same library path as above (with the appropriate java syntax), it works exactly as expected. However, when running the application as a service (using jvm mode in prunsrv) it gives the following exception and does not connect:
com.microsoft.sqlserver.jdbc.SQLServerException:
This driver is not configured for integrated authentication. com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:1667)
...
Caused by: java.lang.UnsatisfiedLinkError: no sqljdbc_auth in java.library.path
        at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1865)
...

The exception is the same as when the "-Djava.library.path=drivers/MS SQL/x64" options is left out from the console application. It seems like the service is not setting the library path as expected.
Upon reviewing the documentation for prunsrv there is an option that looks promising:
--LibraryPath : Directory added to the search path used to locate the DLLs for the JVM. This directory is added both in front of the PATH environment variable and as a parameter to the SetDLLDirectory function.

This is exactly what I want.
Sadly, when setting this option along with the java.library.path jvm option, it still throws the exact same exception as before. It's as if it hasn't applied the setting.

A: I am posting this answer because I found it really difficult to find documentation on this particular use case. I hope This post will save someone some time.
It turns out that the solution for jvm mode is to use the --LibraryPath option BUT you must NOT include the same library path in the ++JvmOptions="..." because then it seems to break it and you get the exception.
In summary...

*

*Keep whatever jvm options you normally need in the ++JvmOptions parameter.

*REMOVE all java.library.path configurations from the ++JvmOptions parameter. NB!

*Add another --LibraryPath parameter with the paths removed in step 1.

As in:
++JvmOptions="-Dfile.encoding=UTF8;-Xmx6g" --LibraryPath="%solutionRootPath%\bin\drivers\MS SQL\x64"

where the path and environment variable above is specific to my use case.
After doing this, the solution works the same was as if it was run from the command line using java.exe.


text:
Q: 2d rotation falls spirally inwards? I recently started with 2d transformations in my class. I was just working with a program when I realized the formula I am using rotates the object spirally inwards. I have no idea whats over about this.
I expected my figures to be rotated about a point but rather they all deform with every degree of rotation. I used a single point & realized that the point was moving spirally inwards with every degree I moved.
Can someone help me & let me know why it falls in rather than following circle or if that is what is expected of 2d rotation. I somehow felt its something related to how we view in 2d plane (or the imaginary z index here) but simply can't get around it.
I am following wiki & talking about this :

x' = xcosθ − ysinθ
y' = xsinθ + ycosθ

A: My guess is that this is a very classic error in computer graphics implementation; you have to make sure that you don't accidentally use the new value of X when computing the new value of y!  For instance, this code:

x = x*cos(theta) - y*sin(theta);

y = x*sin(theta) + y*cos(theta);

will actually perform the following operation:
x'  =x cos θ - y sin θ

y' = x cos θ sin θ + y (cos θ - sin2θ)

and for small values of θ (i.e., incremental rotation) will generally cause the point <x,y> to spiral in towards <0,0>.


text:
Q: Mixitup jquery multiple filters css of controls I'm using the method to set up multiple filtering in mixitup described here:
Multiple filters in jQuery
Unfortunately I can't get the active filters highlighted with css. See here:
http://jsfiddle.net/LdVJv/
Help would be appreciated
html

 Filter

all

Lemon

Orange

Apple

 Filter

all

1

2

Lemon

2

Orange

1

Orange

2

Apple

1

JavaScript
// Wait until all images load
function imgLoaded(img) {
    var $img = $(img);
    $img.closest('.img_wrapper').addClass('loaded');
}

// Start mixitup
$('#grid').mixitup();

var $filters = $('.filter-list').find('li'),
    dimensions = {
        type: '',
        manufacturer: ''
    };

$filters.unbind('click');

$filters.on('click', function () {
    var $t = $(this),
        dimension = $t.attr('data-dimension'),
        filter = $t.attr('data-filter');
    console.info("dimension: " + dimension);
    console.info("filter " + filter);
    console.info("current filter for this cat: " + dimensions[dimension]);
    dimensions[dimension] = filter;
    console.info("selected filter for this cat: " + dimensions[dimension]);
    console.info("type: " + dimensions['type']);
    console.info("manufacturer: " + dimensions['manufacturer']);

    $('#grid').mixitup('filter', [dimensions['type'], dimensions['manufacturer']]);
});

css
    li {
    list-style: none;
}
#grid .mix {
    opacity: 0;
    display: none;
    padding: 10px;
    border: 1px solid #d0d0d0;
    width: 150px;
    margin: 0 0 10px 10px;
}
.filter-list li {
    margin-left: 20px;
    cursor: pointer;
    list-style-type: square;
}
.filter-list li.active {
    font-weight: 700;
}

A: $('#grid').mixitup({
  controls: {
    toggleFilterButtons: true,
    toggleLogic: 'or',
    activeClass: 'active'
  }
}

You need to pass the name of the class you want the active buttons to have when instantiating mixitup.


text:
Q: Hiding excel columns misreports widths I'm looking to get the widths of columns (hidden and visible) in Excel using VBA.
I want to total the widths of columns between two points and I have to take in to account the widths of hidden columns too which I can do using the previouswidth property.
The trouble is that when more than two are hidden, it looks like the previouswidth property of one of them is misreported as 0.
The test code I have is:
Sub LeftPositionFromCell()

    Dim rng As Range
    Dim i As Integer
    Dim l As Double

    Set rng = Range("J2")
    i = 0
    l = 0

    For i = 1 To rng.Column
        If (ActiveSheet.Columns(i).Hidden) Then
            l = l + ActiveSheet.Columns(i).Previous.Width
            Debug.Print "address: " & ActiveSheet.Columns(i).Address & " width: " & ActiveSheet.Columns(i).Previous.Width & " (hidden)"
        Else
            l = l + ActiveSheet.Columns(i).Width
            Debug.Print "address: " & ActiveSheet.Columns(i).Address & " width: " & ActiveSheet.Columns(i).Width
        End If
    Next

    Debug.Print " address: " & rng.Address & " left: " & l
    Debug.Print

End Sub

and sample output for when columns H & I are hidden is:
address: $A:$A width: 48
address: $B:$B width: 48
address: $C:$C width: 48
address: $D:$D width: 48
address: $E:$E width: 48
address: $F:$F width: 48
address: $G:$G width: 48
address: $H:$H width: 48 (hidden)
address: $I:$I width: 0 (hidden)
address: $J:$J width: 48
 address: $J$2 left: 432

Seems this only happens when the hidden columns are sequential as non-sequential hidden columns report the previouswidth correctly.
Does anyone know how to fix this?


text: Q: Morse-Sard lemma I would like to know what is the inductive hypothesis in the proof of the lemma below, which is quoted in the last line of the proof. I didn't understand this last line because I couldn't identify what is the inductive hypothesis in the beginning of the step $2$.


text:
Q: Is it possible to represent set of rational numbers as the countable union of disjoint dense subsets? Let, Q is set of rational numbers with relative topology of natural topology on R. Is it possible to represent Q as the countable union of disjoint dense subsets?
P.S. According the famous book, "Counterexamples in topology" by Steen and Seebach, it is possible, (page 143. Definition of Roys Lattice space). But, I dont know the proof of this.

A: Sure, there are various ways to do this.
In my opinion, the nicest is to consider restrictions on denominators - for example, let $B_k$ be the set of rational numbers whose lowest-terms representation has denominator a power of $k$ (with the convention that the lowest-terms representation of $0$ is $0\over 1$). Then:

*

*What can you say about each $B_k$ in terms of topology?

*How do the different $B_k$s relate? In particular, can you find an infinite set $X\subseteq\mathbb{N}$ such that for distinct $a,b\in X$ we have $B_a\cap B_b=\emptyset$ (which will then give you the partition you want)? HINT: think about divisibility ...


text: Q: Calculating second order partial derivative. Let $z=f (u,v),u=\frac {x}{x^2+y^2},v=\frac {y}{x^2+y^2} $ then prove that $z_{uu}+z_{vv}=(x^2+y^2)^2 (z_{xx}+z_{yy}) $ . I have never calculated the second order partial derivatives when the function is indirectly related with the variable. I can calculate $z_x,z_y $ but dont know how to differentiate them to get $z_{xx},z_{yy }$.Thanks!


text:
Q: how to include header correctly in the opencl kernel I am writing an opencl kernel with many helper function in the same .cl file. I want to package the helper function into a header file. I read the spec and see I should pass -I Dir in the clCreateProgram function call.
I am still confused here. When I crate a A.h file to be included in the .cl file. Should I create a corresponding A.c file or A.cl file?
If I create a corresponding A.c file, some routines in .c file and .cl file might be different and might make the function cannot be used directly by the kernel.

A: You can have a header file and #include that in the kernel file. So to include file1.h in kernel.cl you need to add #include "file1.h" and as build option pass -I. if header file is in the same folder as kernel file or i.e. -I./include if in the include folder.


text:
Q: ATX power supply doesn't turn off after PS_ON wire is disconnected from GND I'm using an old ATX power supply to power a PlayStation 3. I've built a small circuit to make the power supply only fully turn on when the PS3 is turned on, by using an optocoupler that connects the PS_ON wire to GND. The thing is that it works only to turn the power supply on, when I turn the PS3 off the power supply keeps working. Even if I disconnect the PS_ON wire from the circuit and hold it in the air, it won't turn off, only does so if I connect the PS_ON wire to 5V.
Now I must say that I desoldered all the wires coming from the power supply except for a 12V wire, a GND wire, the PS_ON wire and the 5VSB wire. I don't know if this could be the reason behind the problem. Here is a pic:

A: I found the problem, it was a grounding issue. The power supply PCB is supposed to touch the case in the bolting points, but only does so when it is bolted on, making the GND (0v DC) connected to the power plug ground. Since I had been soldering and testing, I had removed the PCB and it happens that I still hadn't put it back on.
Still, a big thank you to those who tried to help!


text:
Q: IE8 quirks mode issue: The website is made on Drupal 7. In that I'm using the doctype
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

While loading the website in ie8, the mode of IE changed to quirks mode and the website gets collapsed. To solve this issue, i added a meta tag
<meta content="IE=8" http-equiv="X-UA-Compatible" />

then some pages loaded correctly in the standard mode of ie8. But some pages are still collapsed. Thanks in advance.


text:
Q: How can I stream an XPS document to a browser and embed it in a webpage? I'm looking for some suggestions on how to go about this.  Any input is appreciated!
Currently, I have an ASP.NET MVC application.  On the client, I have a link with an ID of an XPS document.  When the user clicks the link, they are taken to a page with details about the document.  In addition to this information, I wish to display the document along side of this information, in the same page.
On the server side, once I have the ID, I can get the document, serialized as a byte array, from the database.  The question is, what's the best way to get that serialized document into the webpage?
I would SEVERELY prefer not having to drop that document into the file system and then munge together a file path.  I would like to be able to stream the document to the browser as a content type of "application/vnd.ms-xpsdocument".
I've tried using a web control to handle this (can't write binary out), thought about creating a HTTP handler to do this (no idea where to start), and have fuddled around with a couple other ways to get the document stream to the browser.
In addition, there is also the question of how to embed the document in the web page.  Do I use an EMBED tag?  Or an Object?  Or do I use an iframe and set the source to point to whatever delivers the document?
Again, I don't expect a solution wrapped up in a bow.  I'm looking for some advice on how to go about this.  And, while this question is about xps documents, it applies to any application that streams a binary file that is to be hosted in a browser (PDFs, etc).

Okay, as for displaying in the browser, one word:  Silverlight.  That's solved.  I still have the issue of figuring out the best way to send it from the server to the browser.

Strike that.  It appears Silverlight isn't advanced enough to display an XPS document just quite yet.  I'm thinking about an iframe pointing to a http handler now...  The iframe works.  Too bad it throws the entire thing down the pipe.  I suppose I could always strip off the first page and send that puppy...

Wow.  No need for a HTTP handler.  A custom ActionResult in MVC is all you need.  How friggen awesome is that?

A: I think the simplest way would be to provide the document as a link (target="_blank") from the details page.  This has several advantages:

*

*You don't need to retrieve and stream the entire doc unless the user asks for it.

*On my system at least IE is already registered as the default XPS viewer, so by giving the doc it's own window you avoid the whole question of how to embed it.

*It makes it simple to provide a streaming source for the document: just use an HTTP Handler with an ID for a query string parameter.

Even if you don't like that idea, definitely go with an HTTP Handler for transmitting document.  It's real simple to do:  when you create a new HTTP Handler in Visual Studio it should give you a nice page with all the busy-work done already.

A: There is a Silverlight control capable of displaying XPS documents. See http://firstfloorsoftware.com/blog/announcement-document-toolkit-for-silverlight/ for more


text:
Q: Create space between legend and chart in charts.js I am working with charts.js but I'm facing an issue. My legend and bar chart value overlaps a bit.
I am not able to resolve this issue, It would be appreciated if there is a solution to this issue
I have shared JS fiddle link below
https://jsfiddle.net/qh0yzmjf/1/
var ctx = document.getElementById("canvas").getContext("2d");
var nomi = [2017, 2018, 2019];

var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: nomi,
    datasets: [{
        label: 'PP PERVENUTI',
        data: [50, 30, 45],
        backgroundColor: "#8A0808",
        fill: false,
        borderColor: "#8A0808",
        borderWidth: 3
      },
      {
        label: 'PP EVASI',
        data: [60, 45, 12],
        backgroundColor: "#0B610B",
        fill: false,
        borderColor: "#0B610B",
        borderWidth: 3
      },
      {
        label: 'PI PERVENUTI',
        data: [20, 25, 35],
        backgroundColor: "#8A0886",
        fill: false,
        borderColor: "#8A0886",
        borderWidth: 3
      },
      {
        label: 'PI EVASI',
        data: [10, 20, 30],
        backgroundColor: "#0404B4",
        fill: false,
        borderColor: "#0404B4",
        borderWidth: 3
      }
    ]
  },
  options: {
    legend: {
      display: true,
      position: "top"
    },
    hover: {
      animationDuration: 0
    },
    animation: {
      onComplete: function() {

        var ctx = this.chart.ctx;
        const chart = this.chart;
        ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
        ctx.fillStyle = "black";
        ctx.textAlign = 'center';
        ctx.textBaseline = 'bottom';

        this.data.datasets.forEach(function(dataset, i) {

          if (chart.getDatasetMeta(i).hidden) {
            return;
          }

          for (var i = 0; i < dataset.data.length; i++) {
            for (var key in dataset._meta) {
              var model = dataset._meta[key].data[i]._model;
              ctx.fillText(dataset.data[i], model.x, model.y);
            }
          }
        });
      }
    }
  }
});

I have also shared my code above
I don't know how to create space between legend and chart, and help will be appreciated thanks

A: If I am not wrong, there isnt a configuration built by chart js to put padding between the labels and the chart,although, the padding to the labels are applied in wor format, this means that chart js applies padding between labels, on the other hand, you can apply padding between the title of the chart and the labels.
If you want padding between the tittle of the chart and the chart you can use the following code:
                 plugins: {
                    title: {
                        display: true,
                        text:'Historico Mensual',
                    },
                    legend: {
                        labels: {
                            padding: 100
                        }
                    }
                },

Another solution it could be to change the position of the labels to the bottom with the following code:
options: {
legend: {
  display: true,
  position: "bottom"
},

And adding a layput padding so the values dont get outside the canvas.
  options: {
     layout:{
        padding:20
     }
  },


text:
Q: Teradata, subquery in case can you help me please. I need insert in case subquery, but teradata doesn't allow me this query, how can i change it (to similar query as case, like if)?
select amount, status
case
when max(amount) then
(select sum(a1.amount)+a2.amount
from payments a1
join  payments a2 on a1.payment_id=a2.payment_id
where a2.status = 't'
and a1.status not like 'w'
group by  a1.amount,a2.amount)
else sum(amount)
end
from payments
Amount | Status
--------| ------
10      | t
20      | w
30      | t
40      | w
50      | t
60      | t
70      | k
expected results: if amount is max then calculate amount to new column like sum(a1.amount)+a2.amount, where status for table a1 is 't' and status for a2 is not 'w'. If amount is not max, then just calculate all amounts from table payments.
results:
--for amount = 70 insert into new column (for example result) sum(all amount where status is not 'w') + sum(all amount where status is 't').
--For other amount < 70 insert into new column result sum(all amount).
Thank you for your help.

A: This will help I guess
select  amt,status,(case when amt=max_amt then w_sum else total_sum end)results
from (
select  amt,
           status,
           sum(amt) over(partition by (case when status='w' and status<>'t' then 1 else 0 end   ))w_sum,
           sum(amt) over(partition by 1) total_sum,
           max(amt) over(partition by 1) max_amt
from    t st)x

Let me know if it works for you.


text:
Q: How to keep method names in Android Proguard R8? I'm developing an Android Library and I'd like to have this result for Proguard.

*

*I want to keep all package names, which I'm using "-keeppackagenames" to achieve.

*I want to keep all class names.

*I want to keep method names and method argument names for all public methods.

Other than that, I'd like to obfuscate and shrink everything else, including but not limited to all of non-public methods and even the body of the public methods.
How can I achieve that result?
Thank you very much beforehand for your help!

A: R8 itself is distributes as a library which has been run through R8. For that library we want to achieve exactly what you ask to ensure that developers using the library will not by accident use any APIs which are not supposed to be public (this has nothing to do with protecting IP as the project is open source).
The rules can be found here and I will explain the rationale for them below.
We try to be indirect and use annotations, so the main rules are:
-keep @com.android.tools.r8.Keep class * { public *; }
-keep @com.android.tools.r8.KeepForSubclassing class * { public *; protected *; }

All API classes are then annotated with @Keep or @KeepForSubclassing.
Then a number of attrubutes are kept
-keepattributes SourceFile, LineNumberTable, InnerClasses, EnclosingMethod, Exceptions, Signature

SourceFile and LineNumberTable are kept to get retracable stack traces. The rest for javac compilation and IDE integration for library users.
Then
-keepparameternames

is there for IDE integration getting the names of arguments in the API, and
-keeppackagenames com.android.tools.r8
-repackageclasses com.android.tools.r8.internal

to move as many classes as possible into the internal name space so the renamed classes does not show up in IDE's.
There are a few additional rules in the file to handle cases not covered by the annotation based approach.


text:
Q: Yet another 'module is not defined' in Karma I'm pretty new to angularjs, and I'm trying to test an app using Jasmine and Karma. The tests work fine if I just use the basic framework that Jasmine provides (with SpecRunner.html), but when I try to use Karma I keep getting the same 'module is not defined' message.
My file dependencies in karma.conf.js are as follows:
files: [
  '../../js/angular.min.js',
  '../../js/angular-sanitize.min.js',
  'lib/angular-mocks.js',
  '../../js/app.js',
  'lib/jasmine-2.4.1/jasmine.js',
  'lib/jasmine-2.4.1/jasmine-html.js',
  'lib/jasmine-2.4.1/boot.js',
  'lib/jquery-1.11.3.min.js',
  'spec/spec.js'
]

So far this looks exactly like all the previous karma undefined module questions I've seen on SO, except I'm quite sure that angular-mocks.js is included, file locations are correct, and I'm not using any other framework that might be overriding karma.conf.js. I apologize for asking the same question again, but am I missing something really obvious here?

A: I have had similar issues with Karma in the past.  It is picky about the order that you put the dependencies into.  For instance, if you are using JQuery and Angular, then Karma will want JQuery before Angular.  I see that you placed Angular before all of its submodules, which is great.
I would place the dependencies in this order:
files: [
  'lib/jquery-1.11.3.min.js',
  '../../js/angular.min.js',
  '../../js/angular-sanitize.min.js',
  'lib/angular-mocks.js',
  'lib/jasmine-2.4.1/jasmine.js',
  'lib/jasmine-2.4.1/jasmine-html.js',
  'lib/jasmine-2.4.1/boot.js',
  '../../js/app.js',
  'spec/spec.js'
]

I've also had problems using minified and unminified versions of Angular modules in the same application.  For instance, if you want to use minified versions of Angular, then make sure all of its submodules are minified too.  I would say the same for any JavaScript dependency.  Keep it consistent.


text:
Q: Intercept Onepage\SaveOrder I'm trying to add a certain process in the Magento\Checkout\Controller\Onepage\SaveOrder so I decided to implement a plugin for that. But after creating the di.xml and the classes needed when I try to purchase an item and fill out all the shipping details and selected the needed payment method. Upon submission of the order, I was expecting the function to be run. But somehow it's not being called. Can any help me with this or if anyone has any idea what I did wrong. Below are my codes

content of  di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
   <type name="Magento\Checkout\Controller\Onepage\SaveOrder">
        <plugin name="Custom_Module_Plugin" type="Custom\Module\Plugin\SaveOrderPlugin" sortOrder="10" />
    </type>
</config>

content of SaveOrderPlugin.php

<?php
namespace Custom\Module\Plugin;

class SaveOrderPlugin
{
    public function aroundExecute(\Magento\Checkout\Controller\Onepage\SaveOrder $subject, \Closure $proceed)
    {
        // logging to test override
        $logger = \Magento\Framework\App\ObjectManager::getInstance()->get('\Psr\Log\LoggerInterface');
        $logger->debug("********** " . __METHOD__ . ' - ' . __LINE__);

        // call the core observed function
        $returnValue = $proceed();

        // logging to test override
        $logger->debug("********** " . __METHOD__ . ' - ' . __LINE__);

        return $returnValue;
    }
}
?>

As you can see I was expecting an output in the console log as shown below but this does not show. Also, I tried intercepting other classes like Magento\Quote\Model\QuoteManagement and it worked as expected. But the reason I want to override the Magento\Checkout\Controller\Onepage\SaveOrder is primarily that I want to retrieve a certain parameter when the order of item is submitted.
Does anyone have an idea what I did wrong here?


text:
Q: %%f in a batch file with Windows 7 Professional 64 bit I have a line like the following in a several batch files:
FOR %%f IN (%*) DO something.exe %%f

I've used them for a long time with no problem. I recently had to replace my hard drive and had Windows 7 reinstalled just as it was before as far as I know. Now when I run any of the batch files with this kind of line in it, they aren't pre-processing the "%*". So for something like "XXX.bat *.txt" I get:
Unable to open input file "*.txt"
I'm running Windows 7 as a virtual machine in Parallels, upgraded from version 8 to 10, if that makes a difference. They also upgraded my Mac OS from Mountain Lion to Yosemite.
Even more strange, this little batch file works fine:
@ECHO off
FOR %%f IN (%*) DO start gvim %%f

But this one gives the message it can't find t? (where t? should parse out to t1, t2, and t3):
@ECHO off
FOR %%f IN (%*) DO af2.exe %%f

And I tried adding the "start" to it, same results.
Maybe a simpler way of saying it is:
This works:
af2 2014A 2014B 2014C
But this:
af2 2014?
gives an error about trying to access a file called "2014?"
And af2 calls, for each file, a program I wrote and have used for 20+ years that just gives a few statistics on a file.

A: Command Extensions are disabled for some reason. The command extensions involve serious changes to Command Line arguments (Parameters) as per CALL /?.
However, next excerpt from CMD /? shows some solution hints:

Command Extensions are enabled by default.  You may also disable
  extensions for a particular invocation by using the /E:OFF switch.
  You can enable or disable extensions for all invocations of CMD.EXE
  on a machine and/or user logon session by setting either or both of
  the following REG_DWORD values in the registry using REGEDIT.EXE:
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\EnableExtensions

and/or
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\EnableExtensions

to either 0x1 or 0x0.  The user specific setting takes precedence
  over the machine setting.  The command line switches take precedence
  over the registry settings.
In a batch file, the SETLOCAL ENABLEEXTENSIONS or
  DISABLEEXTENSIONS arguments takes precedence over the /E:ON or
  /E:OFF switch. See SETLOCAL /? for details.

Example
==>type D:\bat\cliParser.bat
@echo OFF >NUL
echo   all %%* = %*
set /A "ii=0"
:loopfor
  echo param %%%ii% = %0
  SHIFT
  set /A "ii+=1"
  if not [%0]==[] goto :loopfor
goto :eof

==>D:\bat\cliParser.bat aaa bbb
  all %* = aaa bbb
param %0 = D:\bat\cliParser.bat
param %1 = aaa
param %2 = bbb

==>cmd /E:OFF /C D:\bat\cliParser.bat aaa bbb
  all %* = *
The syntax of the command is incorrect.
param %3 = D:\bat\cliParser.bat
The syntax of the command is incorrect.
param %3 = aaa
The syntax of the command is incorrect.
param %3 = bbb
The syntax of the command is incorrect.
The system cannot find the batch label specified - eof

==>

A: I figured out the problem. I have a folder on my desktop with a bunch of .exe files in them from programs I've written. It also has a folder with some .bat files in it. In many cases, the .bat file calls one of the .exe files that has the same root name (af2.bat calls af2.exe). That works fine IF the folder with the .bat files in it precedes the other folder in the PATH variable, which it did on my previous install (and does now on this one).
Just gotta love those subtle little problems.
Thanks for all the input. :)


text:
Q: cannot find table from hive using spark-submi this is my simple code.
spark.sql("select * from default.some_table")

when using this code in zeppelin or spark-shell then it works perfectly.
But, try on spark-submit command
following error occurred
diagnostics: User class threw exception: org.apache.spark.sql.AnalysisException: Table or view not found:: `default`.`some_table`; line 1 pos 14;

any help?
this is my spark submit command
spark-submit --class com.any.any.App  --master yarn --deploy-mode cluster app.jar

thanx

A:
Solved it!! need to set hive.metastore.warehouse.dir when create SparkSession!!
val spark = SparkSession
  .builder()
  .appName("mbp stream layer on nuri cluster")
  .config("hive.metastore.warehouse.dir", warehouseLocation)
  .enableHiveSupport()
  .getOrCreate()


text:
Q: SharePoint 2016 There is no file with URL '_catalogs/wp/DocumentSetProperties.dwp' in this Web I have a new installation of SharePoint server 2016, I have setup a new web application and now trying to create a new site collection and I am getting the error :

There is no file with URL '_catalogs/wp/DocumentSetProperties.dwp' in
  this Web.

I redid the web application a few times without any success.
thanks for any help
Edit: With poweershell I get the error
New-SPSite -Url $Site -OwnerAlias $Owner -Template STS#2

New-SPSite : There is no file with URL
  '_catalogs/masterpage/v4.master' in this Web

Here is the full powershell script:
Add-PSSnapin "Microsoft.SharePoint.PowerShell"
$siteURL = "http://somewebapp.com/sites/test2"
$sitePrimaryOwner = "domain\secretusername"
$siteSecondaryOwner = "domain\secretusername"
$siteName = "Test Site"
$siteTemplate = "STS#0"
$siteDescription = "This is a test site"

New-SPSite -Url $siteURL -OwnerAlias $sitePrimaryOwner -SecondaryOwnerAlias
$siteSecondaryOwner -Name $siteName -Template $siteTemplate -Description
$siteDescription

A: Install the security update KB4011244
You can download From https://support.microsoft.com/en-us/help/4011244/descriptionofthesecurityupdateforsharepointserver2016november14-2017


text:
Q: Shadow effect of TextView in Android Studio doesn't work I'm new to Android Studio and I need help with putting a shadow to my TextView. I read other topics on it and I think my code is correct. Which would mean that I might have some problem with the IDE, maybe a setting I missed or something. This is my code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.android.giphy.MainActivity">

    <pl.droidsonroids.gif.GifImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/lope3"
        android:background="#000102"
        android:id="@+id/gifImageView"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:text="@string/main"
        android:textColor="#ffffff"
        android:padding="20dp"
        android:fontFamily="monospace"
        android:textSize="32sp"
        android:shadowColor="#f4e402"
        android:shadowRadius="5.0"
        android:shadowDy="5.0"
        android:shadowDx="5.0" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/greeting"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:padding="20dp"
        android:textColor="#ffffff"
        android:fontFamily="monospace"
        android:textSize="32sp"    />
</RelativeLayout>

Unfortunately the text shadow doesn't appear. I tested it on a tablet and a phone both running Android 6.0. Any thoughts?
Thanks.

A: you can try this in run time
TextView text = (TextView) findViewById(R.id.textview);
text.setShadowLayer(1, 0, 0, Color.RED);

A: Well, thank you guys for your contributions. I played around with the code and put a larger value to radius added a black background to the TextView and voila...the shadow!


text:
Q: Are there Ubuntu User Experience Tests conducted. Are they open source and if so where can I find the data? any format accepted I've tried searching related topics but nothing has satisfied my question
Old Article is top google search
Older Blog referencing Scientific Method
There are plenty more examples of articles / links but nothing concrete.
I'd like to analyse the data myself and see if there is any stastically valid tests conducted at all.
I love Ubuntu, but find the Mac as it's a work machine is becoming my default OS
Thanks in advance to anyone who may point me in the right direction!


text:
Q: Struggling in getting value from array with variable as index/argument I'm struggling with an issue in getting value from array with variable as an index.
I'm trying to get value from array "ok"
ok = {"3"=>"on", "4"=>"on", "6"=>"on", "7"=>"on"}

In my code (in my model):
@i=0;
@veh = VehicleClass.order(id: :asc)
@veh.each do |veh|
@i = veh.id;

      checkbox = ok[@i];

end

Interesting is that, when I try to call the array by:
checkbox = ok['3'] => I got the value "on"

in case of
@i=3; checkbox = ok[@i] => result NULL.

I was trying many options like:
checkbox = ok[@i]
checkbox = ok['@i']
checkbox = ok['#{@i}']
checkbox = ok['#{i}']
checkbox = ok[i]
checkbox = ok[:i]

Nothing works..:(
Any thoughts / suggestions?
Thanks!

A: Use double quotes for interpolation
checkbox = ok["#{@i}"]

You are using single quotes that's why it's not working
or you can also use to_s
checkbox = ok[@i.to_s]


text:
Q: Voltage/current conversion I have a device which uses 4.5 watts @ 18V (0.245A). The device can be powered by 12 volts, which I plan to do so.
I can I work out the current draw at 12 volts based off the above info?

A: Not without knowing something about the circuit. For example if it's a simple resistive load then it would be:
\$(12V \ \div 18V)^{2} \times 4.5W = 2W\$
\$2W \div 12V = 0.1666A\$
Or
\$ 4.5W \div 18V = 0.25A \$
\$ 18V \div 0.25A = 72\Omega\$
\$ 12V \div 72\Omega = 0.1666A\$
\$ 12V \times 0.1666A = 2W \$
However, it's probably going to be more complex than the above. Depending on the circuit, it may be non-linear, draw the same or even more current at the lower voltage.
For another example take a switching regulator, in your example say you have a 100 percent efficient switcher (don't exist, but for easy calculations) delivering 5V (from the 18V input) to the rest of the circuit. 4.5W at 5V is 900mA. So the 18V at 250mA is turning into 5V at 900mA.
If we drop the input voltage to 12V, then to supply the required 4.5W the switcher will automatically draw more current at it's input in order to deliver the 4.5W at it's output. So 4.5W / 12V = 0.375A. The input voltage has dropped, but the current has actually  increased. This can be seen as a negative impedance at the switcher input.
With more details about the circuit a reasonable estimation could be arrived at, but I think the easiest way would be simply to run it from 12V and measure the current with a multimeter.


text:
Q: How to limit number of threads all concurrent methods at once I am working on a legacy project which uses Java 8, Spring, HikariCP, and MySQL. Microservices' methods are triggered with a Kafka topic and start a reporting operation. Almost all triggered methods have this and some of them have the same usage inside their blocks.
new ForkJoinPool().submit(() -> { users.parallelStream().forEach(user ->

The application creates 8-9k threads and all of them try to get or create a record. However, the database couldn't handle these requests and started to throw exceptions and Zabbix sends mails about heap memory usage above %90:

Caused by: java.sql.SQLTransientConnectionException: HikariPool-2 -
Connection is not available, request timed out after 30000ms.

When I check the database and see the variable for max_connections = 600, but this is not enough.
I want to set a limit for thread count for the application level.
I tried setting these parameters but the thread size doesn't decrease.
SPRING_TASK_EXECUTION_POOL_QUEUE-CAPACITY , SPRING_TASK_EXECUTION_POOL_MAX-SIZE, -Djava.util.concurrent.ForkJoinPool.common.parallelism
Is there any property to solve this problem?

A: I have changed all new ForkJoinPool() to ForkJoinPool.commonPool() and use this parameter to control thread creation -Djava.util.concurrent.ForkJoinPool.common.parallelism after that I have fixed my problem.


text:
Q: `keyof` reported compile error when using generic type First I have a type definition map all properties into number by using keyof
type Numeric<T> = {
    [K in keyof T]: number
}

Below is a class I will use.
class Entity {
    aNumber: number;
}

Below is a function which accept a generic type argument and a local variable with type Numberic<T>. But when I assigned { aNumber: 1 } it gave a compile error.
const fn = <T extends Entity>() => {
    const n: Numeric<T> = {
//        ^
//        Type '{ aNumber: number; }' is not
//        assignable to type 'Numeric<T>'
        aNumber: 1
    };
};

I don't know why { aNumber: number; } cannot be assigned to Numeric<T> since the type argument T must be extended from Entity and it must contains a key named aNumber. This means aNumber must be the key of type T and should be able to assigned to Numeric<T>.

A: The error message is misleading. However there is an error and that is what TypeScript is catching. Indeed there is nothing wrong with Entity:
type Numeric<T> = {
    [K in keyof T]: number
}
interface Entity {
    aNumber: number
}

// No error
const n: Numeric<Entity> = {
    aNumber: 1
};

However when you say T extends Entity it opens it up for non number values e.g.
type Numeric<T> = {
    [K in keyof T]: number
}
interface Entity {
    aNumber: number
}

// No error
const n: Numeric<Entity> = {
    aNumber: 1
};

interface X extends Entity {
    notANumber: string
}
// Error. Thank you TypeScript
const o: Numeric<X> = {
    aNumber: 1
};

Hence the error when you use a T extends Entity in Numeric.

A: The constraint imposed by <T extends Entity> should be considered just the minimum requirement that T should meet. It means "T should at least contain aNumber: number pair".
Let's see const n: T. It means "n should at least contains whatever key-value pairs that are in T".
Now we do know, T has a aNumber: number pair, but remember that's just the minimum requirement. T might as well be { aNumber: number; aString: string }. That's why this will also give you error.
// if you understand this:
const n: { aNumber: number; aString: string } = { aNumber: 42 }  // error, of course
// you see why this is an error:
const n: T = { aNumber: 42 }  // also error

You can never tell what exactly is T. keyof T is fine though, cus we know about at least one of T's key for sure.
const k: keyof T = "aNumber"

To prove my point, let's review a non-generic case. Take @basarat's code for example, here X is not genreic.
type Numeric<T> = {
    [K in keyof T]: number
}

type OptionalNumeric<T> = {
    [K in keyof T]?: number
}

interface Entity {
    aNumber: number
}

interface X extends Entity {
    notANumber: string
}

// Error, because `notANumber` is missing
const o: Numeric<X> = { aNumber: 1 };
// Correct
const o1: Numeric<X> = { aNumber: 1, notANumber: 2 };
// Also correct, because all keys are optional.
const o2: OptionalNumeric<X> = { aNumber: 1 };

Side note. Above should explain your case. However, I do believe there's a bug in TS.
I think if you use OptionalNumeric in your original case, what you want should work. But turns out it doesn't. Should be a defect when generic type parameters involve.


text:
Q: NIC down after wakeonlan I've setup wakeonlan on an Ubuntu 22.04 machine using iw, following this tutorial:
$ sudo iw phy0 wowlan enable magic-packet disconnect

I then control the machine over ssh with wakeonlan <MAC> and systemctl suspend, this most often works. But sometimes, after wakeonlan, the network interface is down and does not appear in ifconfig output anymore (unless -a is provided). Trying to re-enable it causes an error:
$ sudo ifconfig wlp4s0 up
SIOCSIFFLAGS Input/output error

The network manager service provides the following logs:
Feb 27 21:45:26 Z390-GAMING-X NetworkManager[33337]: <warn>  [1677530726.0879] device (wlp4s0): re-acquiring supplicant interface (#1).
Feb 27 21:45:26 Z390-GAMING-X NetworkManager[33337]: <error> [1677530726.5096] device (wlp4s0): Couldn't initialize supplicant interface: GDBus.Error:fi.w1.wpa_supplicant1.UnknownError: wpa_supplicant couldn't grab this interface.

with the following logs for wpa_supplicant:
Feb 27 21:45:26 Z390-GAMING-X wpa_supplicant[835]: Could not set interface wlp4s0 flags (UP): Input/output error
Feb 27 21:45:26 Z390-GAMING-X wpa_supplicant[835]: nl80211: Could not set interface 'wlp4s0' UP
Feb 27 21:45:26 Z390-GAMING-X wpa_supplicant[835]: nl80211: deinit ifname=wlp4s0 disabled_11b_rates=0

I've tried to follow this (unmask wpa_supplicant.service) and disabling WiFi Powersave, without success. Any ideas on how to solve this are welcome. My network card is an Intel Wireless-AC 9260.

A perhaps important note: I could not setup wakeonlan with ethtool as described in Ubuntu's documentation, since I got the following output:
$ sudo ethtool wlp4s0
Settings for wlp4s0:
    Link detected: yes

That is, there is no Wake-on: field as I would expect. Trying to enable it with ethtool returns an error:
$ sudo ethtool -s wlp4s0 wol g
netlink error: Operation not supported


text:
Q: Is the number of types in a C++ template variant limited? I'm trying to understand how variants are implemented, and reading:
http://www.codeproject.com/KB/cpp/TTLTyplist.aspx
And I'm getting the impression that I can't write a variant that takes X types; but that the template writer picks some N, and I can only have less than-N types in a variant.
Is this correct?
Thanks!

A: In C++03, there are no variadic templates. This means yes; you simply have to pick some N to go up to, and live with that.
In C++0x, there will be variadic templates, so you could use one definition for all X.
If you're looking to make changing the number easy, you can use Boost.Preprocessor and have it do the work for you:
#define MAXIMUM_TYPELIST_SIZE 20 // or something

struct empty{};

template <BOOST_PP_ENUM_BINARY_PARAMS(MAXIMUM_TYPELIST_SIZE, typename T, =empty)>
struct typelist;

template <BOOST_PP_ENUM_PARAMS(MAXIMUM_TYPELIST_SIZE, typename T)>
struct typelist
{
    typedef T1 head;
    typedef typelist<
            BOOST_PP_ENUM_PARAMS(BOOST_PP_DEC(MAXIMUM_TYPELIST_SIZE), T)> tail;
    enum
    {
        length = tail::length+1
    };
};

If MAXIMUM_TYPELIST_SIZE were 5, those macro's would expand to what the article has.
(Of course, if you're using Boost just use their meta-programming library.)

A: Yes -- there's some limit set by the implementation of the library. IIRC, in Loki the maximum is 99 by default. Glancing at that article he's set the limit at 5, which is probably enough for a lot of work, but I can see the possibility of exceeding it; I can't quite imagine exceeding the 99 Loki allows (though in either case it's a trivial editing job to extend the limit if you want).

A: Without variadic template support, template authors can only provide workarounds that look like variadic templates:
template<class Arg1=nil, class Arg2=nil /* , ... */>
struct foo {};

Here the number of template arguments the author provides is the limit.
If they wouldn't provide such work-arounds, you'd be forced to resort to explicit typelists, which are quite clumsy in comparison:
typedef list<T1, list<T2, list<T3, nil> > > myTypeList;
foo<myTypeList>::bar;

These are not limited to a fixed number of types, but not something i'd like to use explicitly.
With the next C++ standard this will be solved with true variadic templates:
template<class... Args> // can take 0..n arguments
struct foo {};

A: That is correct under the current standard; templates can only have a fixed number of arguments, and libraries use techniques like preprocessor meta-programming to simulate variadic template parameters up to a certain set maximum. Normally this isn't much of a problem in practice because the maximums are set such to be well above what most people use.
In the new 0x standard, there is support for true variadic template parameters.


text:
Q: SQL FOREIGN KEY ERROR (errno: 150 "Foreign key constraint is incorrectly formed") Hi I have this three very simple tables but I can't fix it to get the right format of foreign key.
CREATE TABLE company(
company_name varchar(30) UNIQUE NOT NULL,
bid INT(15) NOT NULL UNIQUE,
cid INT(15) NOT NULL UNIQUE,
FOREIGN KEY (bid) REFERENCES branch(branch_id),
FOREIGN KEY (cid) REFERENCES contact(contact_id)
);
CREATE TABLE  branch(
branch_id INT(15) NOT NULL AUTO_INCREMENT UNIQUE,
branch_type varchar(30),
cid INT(15) NOT NULL UNIQUE,
PRIMARY KEY (branch_id),
FOREIGN KEY (cid) REFERENCES contact(contact_id)
);
CREATE TABLE contact(
contact_id INT(15) NOT NULL AUTO_INCREMENT UNIQUE,
fst_name varchar(20),
mdl_name varchar(20),
lst_name varchar(20),
sex varchar(20),
dob DATE,
phone_number INT(15),
address varchar(255),
email varchar(255),
bid INT(15) NOT NULL UNIQUE,
PRIMARY KEY (contact_id),
FOREIGN KEY (bid) REFERENCES branch (branch_id)
)ENGINE=InnoDB;
All three of them have the same error150.
Thank you so much for helping.table

A: The problem is that you have the company table reference the branch and contact table before they are created.
Also, the branch table references the contact table and vice versa so the database goes like that:
Creating the contact table ... there is a bid field connected to a table named branch ... table branch does not exist -> error
You have to create the contact table first but without the foreign id reference to bid, then create branch table and then company table.
After you have your tables all set you can execute another query to add a foreign id reference to bid.
So Like this:
CREATE TABLE contact( contact_id INT(15) NOT NULL AUTO_INCREMENT UNIQUE, fst_name varchar(20), mdl_name varchar(20), lst_name varchar(20), sex varchar(20), dob DATE, phone_number INT(15), address varchar(255), email varchar(255), bid INT(15) NOT NULL UNIQUE, PRIMARY KEY (contact_id) )ENGINE=InnoDB;

CREATE TABLE branch( branch_id INT(15) NOT NULL AUTO_INCREMENT UNIQUE, branch_type varchar(30), cid INT(15) NOT NULL UNIQUE, PRIMARY KEY (branch_id), FOREIGN KEY (cid) REFERENCES contact(contact_id) );

CREATE TABLE company( company_name varchar(30) UNIQUE NOT NULL, bid INT(15) NOT NULL UNIQUE, cid INT(15) NOT NULL UNIQUE, FOREIGN KEY (bid) REFERENCES branch(branch_id), FOREIGN KEY (cid) REFERENCES contact(contact_id) );

Notice I removed FOREIGN KEY (bid) REFERENCES branch (branch_id)
And then:
ALTER TABLE contact ADD FOREIGN KEY (bid) REFERENCES branch(branch_id);

P.S Run the commands in the same order


text:
Q: Add block on MatLab Simulink does strange things I did a simulation of the following circuit on MatLab Simulink (I will only show the section of interest):

and obtained the following results from the scope:

As you can see the add block, didn't "add" the two input signals. Instead, it subtracted the first from the second, where the first was null. So, why this happened? How could I correct this?


text:
Q: How to get attributes of subclasses with base class pointer I have a problem which I encounter again and again in a similar way.
For example:
I have an abstract base class which acts as interface for a series of concrete classes which act as, let's say, data containers.
class DataInterface
{
public:
    DataInterface();
    ~DataInterface();

    virtual void FetchData(void) = 0;
    virtual void ProcessData(void) = 0;
    virtual void ClearData(void) = 0;
}

The concrete classes would look like this:
class BinaryData: public DataInterface
{
public:
    BinaryData();
    ~ BinaryData();

    virtual void FetchData(void);
    virtual void ProcessData(void);
    virtual void ClearData(void);

private:
    bool m_boolData;
}

class IntegerData: public DataInterface
{
public:
    IntegerData();
    ~ IntegerData();

    virtual void FetchData(void);
    virtual void ProcessData(void);
    virtual void ClearData(void);

private:
    int m_intData;
}

The subclasses implement the interface which they inherited from DataInterface. But they have different attributes to hold their data. So far so good.
I can use the classes in the main function like that:
int main()
{
    int IntegerData;
    bool BoolData;
    DataInterface *pData1 = new BinaryData();
    DataInterface *pData2 = new IntegerData();

    pData1->FetchData();
    pData2->FetchData();

    pData1->ProcessData();
    pData2->ProcessData();

    // now I want to get the data of pData1 and pData2, for example to write it into a file, show in visualization, ...
    IntegerData = pData2->GetData() ????
    BoolData = pData1->GetData() ????
}

Now comes the problem:
How do I get the data from the concrete classes? I have only base class pointers, so I would need to define an abstract getter method in DataInterface. But the signature of the getter method wouold vary from subclass to subclass. For example one time I need to return an integer, one time I need to return a bool type.
Please give me a hint, this problem drives me nuts :/

A: Make a non-virtual GetData() member on each derived class. Then, if you know for certain the actual class of your objects, you can simply perform a static cast and call GetData():
int intData = static_cast<IntegerData*>(pData2)->GetData();

If you don't know the class, then you need to perform a dynamic cast and check its result:
if (IntegerData* _pData2 = dynamic_cast<IntegerData*>(pData2))
{
  int intData = _pData2->GetData();
  // Do stuff with the int
}
else if (BinaryData* _pData2 = dynamic_cast<BinaryData*>(pData2))
{
  bool binaryData = _pData2->GetData();
  // Do stuff with the bool
}

A: I am not really sure this is a "good" practice but here is one way to solve this.
One advantage with this is that if you try to get the wrong type of data you can get custom error messages. And you can avoid casts (I am not a fan of them).
class DataInterface
{
public:
  DataInterface();
  ~DataInterface();

  virtual void FetchData(void) = 0;
  virtual void ProcessData(void) = 0;
  virtual void ClearData(void) = 0;
  virtual int getIntData() { // Error message }
  virtual bool getBoolData() { // Error message }
};

class BinaryData: public DataInterface
{
public:
    BinaryData();
    ~ BinaryData();

    virtual void FetchData(void);
    virtual void ProcessData(void);
    virtual void ClearData(void);
    virtual int getIntData() { // Error message }
    virtual bool getBoolData() { return m_boolData; }

private:
    bool m_boolData;
}

class IntegerData: public DataInterface
{
public:
    IntegerData();
    ~ IntegerData();

    virtual void FetchData(void);
    virtual void ProcessData(void);
    virtual void ClearData(void);
    virtual int getIntData() { return m_intData; }
    virtual bool getBoolData() { // Error message }

private:
    int m_intData;
}

int main()
{
    int IntegerData;
    bool BoolData;
    DataInterface *pData1 = new BinaryData();
    DataInterface *pData2 = new IntegerData();

    pData1->FetchData();
    pData2->FetchData();

    pData1->ProcessData();
    pData2->ProcessData();

    // now I want to get the data of pData1 and pData2, for example to write it into a file, show in visualization, ...
    IntegerData = pData2->GetIntData();
    BoolData = pData1->GetBoolData();
    BoolData = pData2->GetBoolData() // This will tell you that you are trying to get bool from int class.
}

Here is one way of handling it with templates.
using namespace std;

template<typename T>
class DataInterface
{
public:
    DataInterface(T d) : data(d) {}

    virtual T GetData() = 0;
protected:
    T data;
};

class BinaryData : public DataInterface<bool>
{
public:
    BinaryData(bool b) : DataInterface<bool>(b) {}

    virtual bool GetData() {return data;}

};

class IntegerData: public DataInterface<int>
{
public:
    IntegerData(int i) : DataInterface<int>(i) {}

    virtual int GetData() {return data;}

};

int main()
{
    int myint;
    bool mybool;
    DataInterface<bool> *pData1 = new BinaryData(true);
    DataInterface<int> *pData2 = new IntegerData(1);

    // now I want to get the data of pData1 and pData2, for example to write it into a file, show in visualization, ...
    myint = pData2->GetData();
    mybool = pData1->GetData();

    cout<<myint<<" "<<mybool<<endl;
}

A: If you want to pass your data to another entity, you need an abstraction of it.
There are 2 common ways to achieve this:
1:
Use void*.
class DataInterface
{
public:
   ...
   virtual void* GetData() = 0;
};

class BinaryData: public DataInterface
{
public:
   virtual void* GetData() { return &m_boolData; }

private:
    bool m_boolData;
};

In main use it like this:
int main()
{
    bool BoolData;
    DataInterface *pData1 = new BinaryData();

    pData1->FetchData();
    pData1->ProcessData();
    BoolData = *(bool*))pData1->GetData());
}

Advantage of this approach is in its simplicity.
Disadvantages are direct access to internal of an object (breaking encapsulation) and also misuse of polymorphism (why do you need an interface if you eventually cast to a type related to a concrete derivative?)
2:
A more robust way is to not send the raw data to a client from out of your concrete object but to make a communication with clients an additional role of the object.
class DataInterface
{
public:
   ...
   virtual void SendData() = 0;
};

class BinaryData: public DataInterface
{
public:
   ...
   virtual void SendData()
   {
        //do your stuff here, you know the exact type of your data
   }
};

int main()
{
    bool BoolData;
    DataInterface *pData1 = new BinaryData();

    pData1->FetchData();
    pData1->ProcessData();
    pData1->SendData();
}

Note, this is a very stripped example but it demonstrates the idea. Normally, in a real use case you would register clients with you class and send the data to them via a defined interface.

A: A very simple way of achieving this is to design your base class so that it returns a variant type. A variant is a discriminated union container, which holds an object from an heterogeneous set of types (see http://www.boost.org/doc/libs/1_59_0/doc/html/variant.html). Here is a complete example:
#include <iostream>
#include <algorithm>
#include <boost/variant.hpp>

#include <memory>

using namespace std;

class DataInterface
{
public:
    DataInterface(){};
    virtual ~DataInterface(){};

    virtual void FetchData(void) = 0;
    virtual void ProcessData(void) = 0;
    virtual void ClearData(void) = 0;
    virtual boost::variant<bool,int,double,std::string> GetData()=0;
};

class IntResult : public DataInterface{
public:
    IntResult() : resultInt(0){};
    ~IntResult(){};

    virtual void FetchData() override {resultInt = 10;};
    virtual void ProcessData() override {resultInt *= 10;}
    virtual void ClearData() override {resultInt = 0;};

    virtual boost::variant<bool,int,double,std::string> GetData()override{
        return resultInt;
    };

private:
    int resultInt;
};

class StringResult : public DataInterface{
public:
    StringResult() : resultString(""){};
    ~StringResult(){};

    virtual void FetchData() {
        resultString= "Hello World";
    }

    virtual void ProcessData() override {
        std::transform(resultString.begin(), resultString.end(),resultString.begin(), ::toupper);
    }

    virtual void ClearData() override {resultString = "";}

    virtual boost::variant<bool,int,double,std::string> GetData() override {
        return resultString;
    };

private:
    std::string resultString;
};

int main() {

    DataInterface* data;

    IntResult* intResult = new IntResult;
    StringResult* stringResult = new StringResult;

    data = intResult;

    data->FetchData();
    data->ProcessData();

    switch(data->GetData().which()){
        case 0:
            std::cout << "found bool: " << boost::get<bool>(data->GetData()) << std::endl;
            break;
        case 1:
            std::cout << "found int: " << boost::get<int>(data->GetData()) << std::endl;
            break;
        case 2:
            std::cout << "found double: " << boost::get<double>(data->GetData()) << std::endl;
            break;
        case 3:
            std::cout << "found string: " << boost::get<std::string>(data->GetData()) << std::endl;
            break;
        default:
            break;
    }

    data = stringResult;

    data->FetchData();
    data->ProcessData();

    switch(data->GetData().which()){
        case 0:
            std::cout << "found bool: " << boost::get<bool>(data->GetData()) << std::endl;
            break;
        case 1:
            std::cout << "found int: " << boost::get<int>(data->GetData()) << std::endl;
            break;
        case 2:
            std::cout << "found double: " << boost::get<double>(data->GetData()) <<  std::endl;
            break;
        case 3:
            std::cout << "found string: " << boost::get<std::string>(data->GetData()) << std::endl;
            break;
        default:
            break;
    }

    delete intResult;
    delete stringResult;

    return 0;
}

Note that in your case a bool is implicitly convertible to an int so you could simply return ints all the time. The variant approach would work if you need to return truly heterogeneous types. Equivalently you could return a boost any, which can also lets you manipulate a heterogeneous union of types uniformly (see http://www.boost.org/doc/libs/1_59_0/doc/html/any.html). Finally if you don't want any dependencies on boost, it is not terribly difficult to roll out your own variant type, which can hold discriminate set of types.


text:
Q: SQLite Encoding Issue I am trying to read UTF8 encoded text from a SQLite database using the following code. However, the code will occasionally throw an EXC_BAD_ACCESS exception. This appears to be due to the sqlite3_column_bytes16 method call. If I replace the method call with a small number, such as 20, the exception is not thrown at all. What should I do to prevent this exception?
const unichar *text = sqlite3_column_text16(compiledStatement, 0);

if (text) {

   article = [NSString stringWithCharacters:text length:sqlite3_column_bytes16(compiledStatement, 0)];

}

A: sqlite3_column_text16() return the number of bytes in the string, but
 stringWithCharacters:length: expects the number of characters as the second
argument:
const unichar *text = sqlite3_column_text16(compiledStatement, 0);
if (text) {
   NSUInteger length = sqlite3_column_bytes16(compiledStatement, 0)/sizeof(unichar);
   article = [NSString stringWithCharacters:text length:length];
}

This error could go unnoticed in some cases because the string returned by
sqlite3_column_bytes16() is always zero-terminated, but your code would read beyond the
allocated buffer size and cause undefined behaviour.


text:
Q: Can we get any performance gain from creating index from date column? I have seen lot of indexes created on the date columns in my project. Normally the index is a combination of a date column and another column (like state) which are used to create an index.
Since the date column is the only value that gets increased, is there any performance gain from creating an index on the column?
My understanding is that the database engine creates a binary search tree as the index. I can't understand that an ever increasing value will benefit anything from a btree.

A: Phone book contains a list of persons and their phone numbers.
If this list is unordered and you looking for person that isn't listed in the book, then you have to proceed each and every record in the list until the list will be exhausted.
Ordering allows us the bigger/lesser comparison. If the list is ordered and we proceed it row by row we'll find the requested row OR we'll find the row with key bigger than requested. And we can do the reasonable assumption that all the following rows have the key bigger too.
We can use the tree search on the ordered lists. Say we split the phonebook in two equal parts and look at arbitrary row in the middle. If the key is bigger than given one, we take the first half of the book and repeat the procedure recursively. If the list is unordered the tree search is impossible.
BTree splits the list in more than two parts but the idea is the same. Ordering, splitting and comparisons. That's how it goes.


text:
Q: Calling non-transactional method after transaction is rolled back I've just found some EJB behaviour which looks rather surprizing to me.
Here is the code sample (for sure MyBean, beanA, beanB are EJBs using CMT):
@Stateless
public class MyBean {
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public void myMethod(){
         try {
             beanA.methodA(); /* annotated as REQUIRED */
         } catch (Exception e) {
             beanB.methodB(); /* annotated as NOT_SUPPORTED */
         }
    }
}

Lets's say methodA takes more than transaction timeout to execute, so once it returns myMethod receives TransactionRolledbackException, which is successfully caught then in "myMethod".
I would expect "methodB" be called so far, as accordingly with EJB spec it must be called without any transaction context.
But actually, the "beanB" proxy simply returns another TransactionRolledbackException, the "methodB" is not executed.
Looking through EJB spec I do not see anything to prove that container should or even might behave that way.
Do I miss something? Any hint would be appreciated.
UPDATE
At least for Websphere, this behaviour appears to be timeout-specific. The "rollbackOnly" flag which for example is set when "methodA" throws a RuntimeException, does not prevent "methodB" from execution. Only timeout flag does.

A: The EJB specification does not specifically address this scenario, other than to indicate that once a transaction has been marked for rollback, then "Continuing transaction is fruitless", and for the handling of NOT_SUPPORTED, the specification indicates it "does not prescribe how the container should manage the execution of a method with an unspecified transaction context".
All versions of WebSphere Application Server have taken the approach that the best way to handle the scenario where an EJB method has been marked for rollback only is to prevent all further actions the container has control over, so that the transaction may be rolled back as quickly as possible, ensuring the timely release of resources (such as database locks).  Allowing a call to a NOT_SUPPORTED EJB method would result in the marked for rollback transaction being suspended; and thus continue to hold onto resources that could block or already be blocking other transactions. For this reason, WebSphere prevents such activity.

A: Faced the similar issue a while back . When the container mark the transaction for rollback you will not be able to do any other EJB calls after that. You can think about a solution of  annotating @RequiresNew for beanA.methodA() , so that it will not share the global transaction of myMethod() and will always use new transaction. Therefore anything happens to this new transaction will not affect the global transaction so that you can proceed with your further EJB calls.