text:
Q: How do you get % of records per specific count grouping I have the following data in a table called users
   userId   | orgId
    1       | 1
    2       | 1
    3       | 2
    4       | 2
    5       | 2

I have the following data in a table called activities
userId   | activityId | type
1        | 11         | a
1        | 12         | a
1        | 13         | a
1        | 14         | b
1        | 15         | b
1        | 16         | c
1        | 17         | c
1        | 18         | c
2        | 19         | a
2        | 20         | a
2        | 21         | c
2        | 22         | c

I need to be able to calculate the % of users within each orgId who:

*

*have only 1 record in the activities' table wheretype` = 'c'

*have 5 records in the activities table where type = 'c'

*have 10 records in the activities table where type = 'c'

*have 50% of their records in the activities table where type = 'c'

*have 80% of their records in the activities table where type = 'c'

So the result should be in this (hopefully possible) format:
orgId|% who have 1| % who have 5| % who have 10| % who have 50%| % who have 80%
1    | 20         | 54          | 12           | 23            | 32
2    | 22         | 44          | 32           | 44            | 2
3    | 28         | 34          | 24           | 11            | 43
4    | 10         | 14          | 27           | 25            | 45

Thank you for any help.

A: You can use "conditional aggregation" to get the count and percentage per user:
select userId,
  sum(type = 'c') as countC,
  sum(type = 'c') * 100 / count(*) as percentC
from activities
group by userId

The result for your sample data would be:
| userId | countC | percentC |
|--------|--------|----------|
|      1 |      3 |     37.5 |
|      2 |      2 |       50 |

This can be used as a subquery joined with the users table. Then you can again use "conditional aggregation" to get the expected result:
select u.orgId,
  sum(countC = 1) as `only 1`,
  sum(countC >= 5) as `at least 5`,
  sum(countC >= 10) as `at least 10`,
  sum(percentC >= 50) as `at least 50%`,
  sum(percentC >= 80) as `at least 80%`
from (
  select userId,
    sum(type = 'c') as countC,
    sum(type = 'c') * 100 / count(*) as percentC
  from activities
  group by userId
) a
join users u using(userId)
group by u.orgId

Your sample data is not the best for that query. However you would get:
| orgId | only 1 | at least 5 | at least 10 | at least 50% | at least 80% |
|-------|--------|------------|-------------|--------------|--------------|
|     1 |      0 |          0 |           0 |            1 |            0 |

Demo: http://sqlfiddle.com/#!9/b30dae/2


text:
Q: Angular child component reconstructed on async pipe resubscription I am using 'ngFor' directive to initialize a list of child components:
Parent component:
 <div *ngFor="let item of serviceGetter.items | async; let i = index">
     <child-component [item]="item" [currentIndex]="i"></child-component>
</div>

Service:
@Injectable()
export class TermsService {

   private dataStore: {
     data: any[];
   } = { data: [] };

   get items() {
     return this._data$.asObservable();
   }

   //data are populated inside this method
   someMethod() {
      this.dataStore.data= result;
      this._data$.next(Object.assign({}, this.dataStore).data);
   }

   updateSpecificItem() {
       ....

      this.dataStore.data[index] = {
         ...somedata,
      };
   }
}

'Child component' change detection is set to 'OnPush'.
The problem is when 'updateSpecificItem()' function is called child component at 'index' position is reinitialized(constructor call). Is there a solution to avoid this or is this the accepted behavior?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Selenium IDE 3.17, defining nested variable I need to visit list of links and download something from each of them. At the stage where i am at, i couldn't achieve to read links from out csv file. So i decide to store all links as a variable and i write loop to visit each of them at a time. I will name these variables with consecutive numbers like "1,2,3,4,...,6500", and then i will call each at a time. What i am asking is about that. My nested variables didn't work. Here is my code that not worked:

I also tried open|retuned ${${s}}| to get link but it returns "unexpected token '{'",error.
In an nutshell, i need to visit my stored links each at a time, but i couldn't call my links. how can i achive this?
p.s.I know its not useful to store thousands of links, If there is any advice about alternatives, if wish to listen.

A: You could create an array with the links, then add a "for each" loop to iterate through the array and open up each link.
Here's some example code:

Let me know if this solved your issue.


text:
Q: Is there a way to set a title for the div element's :before or :after? <img src="..." title="Some title here">

Is the a way to do the same for the div:before or div:after via css?

A: You can try this..
document.getElementById('divId').title = 'title';


text:
Q: Como converter texto em arquivo para número com casas decimais? Tenho estes dados escritos no ficheiro de texto "000001010" (só tem este dado), mas queria que quando fosse para a variável fosse assim 10,10.
Eu estou a ler os dados do ficheiro assim:
var linhas = System.IO.File.ReadAllLines(@"C:\teste\pedro.txt");

A: Pela regra descrita: é só converter o número pra inteiro e dividir por 100.
Aproveitei pra fazer com LINQ, assim cada linha do arquivo vai retornar um item para a lista valores.
var valores = File.ReadAllLines(@"C:\teste\pedro.txt")
                  .Select(l => (decimal)Convert.ToInt32(l) / 100)
                  .ToList();

foreach(var val in valores)
    Console.WriteLine(val);

Veja funcionando no .NET Fiddle.
Considerando que cada arquivo terá apenas uma linha, seria melhor fazer assim:
var strVal = File.ReadAllLines("C:\teste\pedro.txt")[0];
decimal valor = Convert.ToInt32(strVal) / 100m;

A: Partido do princípio que o formato é sempre este e estará sempre correto pode fazer:
using static System.Console;
using static System.Convert;

public class Program {
    public static void Main() {
        var campo = "000001010";
        decimal valor = ToInt32(campo) / 100M;
        WriteLine(valor);
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Se tem um elemento único no arquivo basta ler assim:
File.ReadAllLines("C:\teste\pedro.txt")[0];

Como o método ReadAllLines() retorna um array com todas as linhas de texto do arquivo e só tem uma linha basta pegar o primeiro elemento. Não precisa fazer outras manipulação porque a linha não contém outra informação.


text:
Q: Calling function using double dot notation yields syntax error I've recently started doing some studying for various MCSE: BI exams. In doing so, I'm coming across aspects of SQL Server I haven't used before. Double dot notation isn't something I've used much, so this scenario struck me as a little odd.
My user's default schema is dbo, and all objects below create under dbo.
Given the following example:
use laboratory

create table tbl_simple_test(SimpleTestID int identity(1,1), SomeVal varchar(255))
go

insert tbl_simple_test
select 'test value 1'
go

create procedure usp_simple_procedure
AS
BEGIN

    select 1

END
go

create function fn_simple_function()
Returns int
AS
BEGIN

    Declare @Result int

    select @Result = 1

    return @Result

END
go

select * from laboratory.dbo.tbl_simple_test
--returns record we inserted above

select * from laboratory..tbl_simple_test
--returns record we inserted above

exec laboratory.dbo.usp_simple_procedure
--returns 1

exec laboratory..usp_simple_procedure
--returns 1

select laboratory.dbo.fn_simple_function()
--returns 1

select laboratory..fn_simple_function()
--syntax error

I did some googling and searching on SO. I came across some discussion around how naming is resolved, but I didn't see anything mentioning this "limitation". Since I can call a procedure, or select from a table, using double dot notation, why can't I call a function in a similar manner?

A: Scalar UDFs in SQL Server must be prefixed by a schema identifier.  While I cannot find a specific rationale for this, I'll speculate that it is to reduce confusion and namespace conflict between intrinsic functions (ISNULL, etc.) and UDFs.
The consequence of this is that double-dot notation, where you are specifying a database but using your default schema for that database, won't work for UDFs.


text:
Q: PyInstaller and OpenEXR - exe crashes I am using PyInstaller 3.3.1 and OpenEXR 1.3.0 in my project.
I create single file executable with --onefile option.

This works as intended:
import sys
if getattr(sys, 'frozen', False):
    print("hello world")

"hello world" is simply output into console and program closes.

This on the other hand makes exe crash (no errors are displayed):
import sys
import OpenEXR

if getattr(sys, 'frozen', False):
    print("hello world")

I tried debugging the program, to see if OpenEXR module is being properly included in exe. It is.

*

*What can be the other reason of the crash?

*Is there any way to make the exe tell me why it crashes?

A: I found the workaround to the problem. Instead of working with OpenEXR directly, I used pyexr - the wrapper library over OpenEXR. Exe doesn't crash anymore.


text:
Q: Java.IO.FileNotFoundException while reading assets file from adapter Class - Xamarin I'm trying to add an image from Assets to imageView. I'm doing this from adapter class. I'm getting Java.IO.FileNotFoundException on an existing file.
Here is my adapter class:
using System;
using System.Collections.Generic;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Java.IO;
using Android.Graphics;

namespace test2
{
    public class MyListViewAdapter : BaseAdapter<Person>
    {
        private List<Person> mItems;
        private Context mContext;
        private Button mButton;
        private Activity activity;
    public MyListViewAdapter(Context context, List<Person> items)
    {
        mItems = items;
        mContext = context;
        this.activity = (Activity)context;
    }
    public override int Count
    {
        get
        {
            return mItems.Count;
        }
    }
    public override long GetItemId(int position)
    {
        return position;
    }
    public override Person this[int position]
    {
        get
        {
            return mItems[position];
        }
    }
    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        View row = convertView;
        if (row == null)
        {
            row = LayoutInflater.From(mContext).Inflate(Resource.Layout.listview_row, null, false);
        }

        /*
        some code
        */

        Android.Content.Res.AssetManager assets = mContext.Assets;
        ImageView imageViewStar1 = row.FindViewById<ImageView>(Resource.Id.imageViewStar1);
        var InStr = assets.Open("poi_star_empty.png"); //here is an exception
        Bitmap bitmap = BitmapFactory.DecodeStream(InStr);
        imageViewStar1.SetImageBitmap(bitmap);

        /*
        some code
        */

        return row;
    }

    private class ButtonClickListener : Java.Lang.Object, View.IOnClickListener
    {
        /*
        some code
        */
    }

}
}
How can I read this image from non activity class?
That's how I call MyListViewAdapter constructor:
mAdapter = new MyListViewAdapter(this, mItems);

Here is my assets list:

A: I made it! For my Asset I had to set build action to AndroidAsset and it works

A: copy file to assets folder in xamarin.droid and then in properties of your file select build action then AndroidAsset
 then access it like
var fd = global::Android.App.Application.Context.Assets.OpenFd(fileName);


text:
Q: How to use $model-> attribute inside 'value' of CGridView This is my index
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'tblvehicleimagegrid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
      'serial_no',
    array(

      'header'  =>'image',
        'type'=>'image',

       'value'=>'Yii::app()->baseUrl."/images/originals/".$model->serial_no."img/img". $model->line_no.".jpg"',

      ),

The $model is not recognized inside the value because of the single quotation mark maybe. ANd without the mark no image is shown. Can anyone give an idea , how can i overcome this?

A: try using this
$data->attribute

or $data->serial_no in your case
So your value becomes
'value'=>'Yii::app()->baseUrl."/images/originals/".$data->serial_no."img/img". $data->line_no.".jpg"',

Note:- $data is an object that stores the values related to your current record.
The single quotes are not the problem. You have to wrap it inside single quote only.

A: Use $data instead of model ...Try this
 In GridView you can access model by using $data->attribute.
'value'=>'Yii::app()->baseUrl."/images/originals/".$data->serial_no."img/img". $data->line_no.".jpg"',


text:
Q: How to correctly setup cron job notifications I'm trying to setup to receive notification everytime my cron job fails, but i'm not sure if I am doing it correctly. This is my current setup.
The second line, i'm trying to clean my csv file, while the third line, i want that clean file to be copied to google cloud storage. How do I receive a notification when any of the jobs fail?
MAILTO:myemail@gmail.com
*/1 * * * *  csvcut -x -e UTF-16 myfile.csv > newfile.csv
*/6 * * * *  gsutil mv -r newfile.csv gs://gcsbucket

A: One thing that I noticed is MAILTO:myemail@gmail.com
To set the MAILTO variable you should use:
      MAILTO=username@domain.com

Sending Email Alerts Through Cron
Also your system should be able to send mails. Please check this related question on SO which describes how to configure your system.
How do I set Cron to send emails
To get an email every time a cron job fails you should redirect all of your standard output to /dev/null or to some file and the STDERR messages will be emailed.
Get email when a cron job fails


text:
Q: Tesseract confuses two numbers I'm writing an application to scan numbers from an image.
The numbers are using the OCR-B font and may also contain + and > characters.
This is my source image:

The scans using Tesseract weren't very good, even when limiting the character set to the mentioned characters. As I didn't find any OCRB training files for Tesseract, I decided to train it myself.
I created this training image and made a box file from it. The box file is correct, all letters are matched correctly.
Then I did all steps described here to create the other necessary files.
Using this newly trained OCR-B tessdata-set, I get pretty good results on the source image, with one little bug: All 1s are mistaken for 8s and vice-versa. The command used to process the image was
$ tesseract esr2c.tif ocrb-esr2c -l ocrb

and the output for the source image was
0800000001456>8 00000195731208 8 01050008 023+ 08 0301226>20
If you swap all 1s and 8s and compare it to the source image, the output would be correct (except for the last two letters which I can ignore).
How could this happen? Did I do some mistake in the training process? How can I fix it?

A: It's likely that somewhere in your box file has incorrect values (characters) for 1 and 8. You can verify using jTessBoxEditor program. If so, correct, regenerate the language data file, and try again.

A: I have trained tesseract 2.04 after 1 month efforts for OCR A extended font. Its working very well and showing above 90 Accuracy with font size 14.
Training image should be high Contrast image.
Use "GIMP" image editor and do following
Menu Colors->Info->Histgram- Read Std Deviation value
colors-> Threshould -> Write "Std Deviation value" as Threshould value
Save image
Use it for training.
Check and edit your box file using "qt-box-editor-1.06.exe".It is very easy to use.
Check All boxes and characters in it.
It is very important. Somewhere in your box file has incorrect characters for 1 and 8.
Run other cmds.


text:
Q: move the variable ''x'' 12 cell down in ''for each x in y'' I am writing a code to automatically write information in a specific cell if there is matching information between a main list and a masterlist.
This is the main list which will be printed.

And this is the masterlist which is a bank of components.

in my test, the information i am trying to compare would be "test" cells C3 and C180 and "test2" cells C15 and C191 and the information to be written is a183:C189 to A6:C12 and A194:C200 to A18:C24 if there is a match.
Here is part of the code i have written :
Sub FR_3_08_Filerie_remplissage_automatique()

'sélection worksheet
Set filerie = ActiveWorkbook.Worksheets("FR-3-08_Filerie")

'tableau liste filerie colonne 1
Dim tableau_fi1 As range
Dim nbrligne_fi1 As Integer
Set tableau_fi1 = filerie.range("c3:c75")
nbrligne_fi1 = tableau_fi1.Rows.Count

'tableau liste filerie colonne 2
Dim tableau_fi2 As range
Dim nbrligne_fi2 As Integer
Set tableau_fi2 = filerie.range("n3:n75")
nbrligne_fi2 = tableau_fi2.Rows.Count

'tableau catalogue carte
Dim tableau_cc As range
Dim nbrligne_cc As Integer
Set tableau_cc = filerie.range("c180:c191")
nbrligne_cc = tableau_cc.Columns.Count

'recherche du duplicata
Dim masterlist As range

'code start

For k = 1 To nbrligne_fi1

    If IsEmpty(tableau_fi1(k, 1)) = False Then 'si cellule vide skip

        Set carte_actif = tableau_fi1(k, 1) 'mise en mémoire du composant de la cellule actif du tableau de filerie

        For Each masterlist In tableau_cc 'recherche de duplicata dans le catalogue de carte

            If carte_actif.Value = masterlist.Value Then 'si il y a duplicata, écriture de information

                'mise en mémoire des cellules utilisé dans les 2 tableaux
                Set couleur1 = carte_actif.Offset(3, 0)
                Set couleur2 = carte_actif.Offset(5, 0)
                Set couleur3 = carte_actif.Offset(7, 0)
                Set couleur4 = carte_actif.Offset(9, 0)
                Set mcouleur1 = tableau_cc.Offset(3, 0)
                Set mcouleur2 = tableau_cc.Offset(5, 0)
                Set mcouleur3 = tableau_cc.Offset(7, 0)
                Set mcouleur4 = tableau_cc.Offset(9, 0)

                Set deg1 = carte_actif.Offset(3, -1)
                Set deg2 = carte_actif.Offset(5, -1)
                Set deg3 = carte_actif.Offset(7, -1)
                Set deg4 = carte_actif.Offset(9, -1)
                Set mdeg1 = tableau_cc.Offset(3, -1)
                Set mdeg2 = tableau_cc.Offset(5, -1)
                Set mdeg3 = tableau_cc.Offset(7, -1)
                Set mdeg4 = tableau_cc.Offset(9, -1)

                Set qty1 = carte_actif.Offset(3, -2)
                Set qty2 = carte_actif.Offset(5, -2)
                Set qty3 = carte_actif.Offset(7, -2)
                Set qty4 = carte_actif.Offset(9, -2)
                Set mqty1 = tableau_cc.Offset(3, -2)
                Set mqty2 = tableau_cc.Offset(5, -2)
                Set mqty3 = tableau_cc.Offset(7, -2)
                Set mqty4 = tableau_cc.Offset(9, -2)

                'écriture de l'information dans le tableau couple de serrage
                couleur1.Value = mcouleur1.Value
                couleur2.Value = mcouleur2.Value
                couleur3.Value = mcouleur3.Value
                couleur4.Value = mcouleur4.Value

                deg1.Value = mdeg1.Value
                deg2.Value = mdeg2.Value
                deg3.Value = mdeg3.Value
                deg4.Value = mdeg4.Value

                qty1.Value = mqty1.Value
                qty2.Value = mqty2.Value
                qty3.Value = mqty3.Value
                qty4.Value = mqty4.Value

            End If

        Next masterlist

    End If

    k = k + 11

Next k

End Sub

The variable i am trying to move is ''masterlist'' in For Each masterlist In tableau_cc down 11 cells each loop which would move from test to test2 in the image bank of components. Else the code tries to verify each cell between the 2 which take more time for the code to finish.
I tried code like masterlist = masterlist.offset(11, 0) but it copies the information in C191 to c180.
I also played with .end(xdown) by moving C180 and C191 to ''E'' but i have the same problem and a new 1 by having for example Set deg1 = carte_actif.Offset(3, -1) broken. the -1 and any other number work but when i enter -3 i get an error which is what i need...
what would be the solution to move ''masterlist'' in the code 12 cells down each loop?
EDIT:
the range written is for test purpose as the range will grow as i add more component in my list. currently it is "C180:C279" but could go to C400 in the future. it is the reason i am trying to move the variable "masterlist" 11 row down each loop.
currently i am using Set tableau_cc = filerie.range("c180, c191, c202, c213, c224, c235, c246, c257, c268, c279") as a solution to force verification on specific cell insteal of the whole range. i will have to add manualy each cell as i expand the masterlist with more component. also added a exit for after the information has been transfered to make the loop faster

A: Untested but should be close:
Sub FR_3_08_Filerie_remplissage_automatique()

    Dim wb As Workbook, filerie As Worksheet, cModel As Range, i As Long
    Dim model, cMatch As Range, matched As Boolean, rw As Long, col As Long

    Set wb = ActiveWorkbook
    Set filerie = ActiveWorkbook.Worksheets("FR-3-08_Filerie")

    Set cModel = filerie.Range("C3") 'first model value to search for
    Do
        i = i + 1
        If Len(cModel.Value) > 0 Then            'anything to look for?
            Set cMatch = filerie.Range("C180")   'first cell to match on
            Do While cMatch.Row < 400            'adjust max row as needed
                If cMatch.Value = cModel.Value Then
                    For col = -2 To 0
                        For rw = 2 To 8 Step 2
                            cModel.Offset(rw, col).Value = cMatch.Offset(rw, col).Value
                        Next rw
                    Next col
                End If
                Set cMatch = cMatch.Offset(11)
            Loop
        End If

        If i Mod 2 = 1 Then
            Set cModel = cModel.Offset(0, 11)   'move over to the right
        Else
            Set cModel = cModel.Offset(12, -11) 'move down and back to the left
        End If

    Loop While cModel.Row < 80

End Sub

A: try below with check of last row with test name in column C starting at C180
    Option Explicit

Sub copy()
Dim lRow As Long, i, x, dn, rt, y

Do While Range("C" & Range("C180").Row + i) <> ""
i = i + 11
Loop

lRow = Range("C" & Range("C180").Row + i).Row - 11 ' the last row with test name

 For x = 180 To lRow Step 11
    If Range("C" & x) = Range("C" & Range("C3").Row + y) Then
        For dn = 3 To 9 Step 2
            For rt = 0 To -2 Step -1
                    Range("C" & Range("C3").Row + y).Offset(dn, rt) = Range("C" & x).Offset(dn, rt)
            Next rt
        Next dn
    End If
y = y + 12
 Next x

End Sub


text:
Q: Append text to Top of Textbox While populating a Textbox using a List.  The Display method is as follows.
 private void Display()
    {
        StringBuilder sb = new StringBuilder();
        foreach (Player dude in _FootballRoster)
        {
            if (btnUSA.Checked == true)
            {
                sb.AppendLine("\r\nName: " + dude.getName() + " \r\n Team: " + dude.getTeam() + "\r\n Birthday: " + dude.getBirthday() + "\r\n Height(in):" + dude.getHeight() + "\r\n Weight(lbs): " + dude.getWeight() + "\r\n Salary(USD): " + dude.getSalary());
            }
            if (btnUSA.Checked == false)
            {
                sb.AppendLine("\r\nName: " + dude.getName() + " \r\n Team: " + dude.getTeam() + "\r\n Birthday: " + dude.getBirthday() + "\r\n Height(meters):" + (dude.getHeight()) / 39.3701 + "\r\n Weight(kg): " + (dude.getWeight()) / 2.20462 + "\r\n Salary(CD): " + (dude.getSalary()) / 1.31);
            }
        }
        txtRosterLog.Text = sb.ToString();
    }

While trying to implement a Sort method when you click btnName, I want "SORT BY: NAME" to appear at the top of the textbox but my current code puts it at the bottom of all the players.
Current Name Sort Code:
private void btnName_Click(object sender, EventArgs e)
    {

        _FootballRoster = _FootballRoster.OrderBy(dude => dude.Name).ToList();
        Display();
        txtRosterLog.AppendText("SORT BY: NAME ");

    }

Any ideas?  I've tried using txtRosterLog.Text.Insert(0, "SORT BY NAME)" but that didn't work either.

A: txtRosterLog.Text = "SORT BY: NAME \r\n" + txtRosterLog.Text;

txtRosterLog.Text.Insert(0, "SORT BY NAME)" would also work if you assign it back:
txtRosterLog.Text = txtRosterLog.Text.Insert(0, "SORT BY NAME");

A: I would go with String.Format as it is quite flexible and easly readable if you would like to make your string more fancy in future.
String s = String.Format("SORT BY: NAME \r\n {0}", txtRosterLog.Text);


text:
Q: Skype event never goes away I seem to have an "immortal" event - when I start Skype I always get an event that one of my contacts has called me. Clicking on "Mark All Viewed" will remove it, until next time I start Skype, and it's back there. This has been driving me nuts!

A: I found the answer from here:

I had this problem too, but on the Linux version.  In the end, I found that instead of using the X or the "mark all viewed", I could right click on the entry and delete it from there.  Don't know if this works for Windows as well.


text:
Q: Customizing mat-tab with predefined themes in Angular I need to modify the styling of a mat-tab-group, specifically that it inherits the colors of the custom theme (color: primary) and changes the background color for each of the selected tabs as follows:

The styles assigned to the theme in the app-theme.scss file:
// Generate Fuse color classes for custom palettes
$custom_palettes: (
    fuse-white: $fuse-white,
    fuse-black: $fuse-black,
    // fuse-navy: $fuse-navy
);

@include fuse-color-classes($custom_palettes);

// --------------------------------------------------------------------
// @ Define the default theme
// --------------------------------------------------------------------

// Define the primary, accent and warn palettes
$default-primary-palette: mat-palette($dynamic-theme-primary);
$default-accent-palette: mat-palette($dynamic-theme-accent);
$default-warn-palette: mat-palette($mat-red);

// Create the Material theme object
$theme: mat-light-theme($default-primary-palette, $default-accent-palette, $default-warn-palette);

// Add ".theme-default" class to the body to activate this theme.
// Class name must start with "theme-" !!!
body.theme-default {

    // Create an Angular Material theme from the $theme map
    @include angular-material-theme($theme);

    // Apply the theme to the Fuse Core
    @include fuse-core-theme($theme);

    // Apply the theme to the user components
    @include components-theme($theme);

    // Generate Fuse color classes for primary, accent and warn colors
    $palettes: (
        primary: $default-primary-palette,
        accent: $default-accent-palette,
        warn: $default-warn-palette
    );

    @include fuse-color-classes($palettes);
}

SCSS file with styles to change the background of a selected tab that I taken from other answers:
.customTab {

    .mat-tab-list, .mat-tab-labels, .mat-tab-labels-active {
        background-color: rgb(255, 131, 62) !important;
        color: #fff !important;
    }

    .mat-tab-labels, mat-tab-link {
        color: rgb(3, 3, 75) !important;
        background-color: rgb(231, 229, 229) !important;
    }
}

HTML file:
<mat-tab-group>
    <mat-tab label="First"> Content 1 </mat-tab>
    <mat-tab label="Second"> Content 2 </mat-tab>
    <mat-tab label="Third"> Content 3 </mat-tab>
</mat-tab-group>

I want to change the style of a mat-tab-group or mat-tab using the styles assigned to the theme through a separate scss file that receives those variables?


text:
Q: Character encoding failing I'm trying to set the encoding of some files in PHP to ISO-8859-1. I tried using this:
<META HTTP-EQUIV="content-type" CONTENT="text/html; charset=ISO-8859-1">`

but it still isn't working. What can I do? Thank you.

A: You should be outputting this as a real HTTP header.  <meta> elements are not a good substitute.
header('Content-Type: text/html;charset=iso8859-1');

You should ensure that the encoding of the files is actually ISO 8859-1 - all this does is tell the browser that the resource is in that encoding, it doesn't actually transcode or anything.


text:
Q: What is the term for a graph with alternating vertex types? I would like to model a graph where each vertex connects to a different type. Below is an example of the kind of thing I'm after. In effect, the red nodes are acting as kind of "super edges" that connect multiple vertexes together.

If additional context is required, this is modelling various parts of various production chains. The blue vertexes represent some ingredient or product and the red vertexes represent various processes that can transform some amount of inputs into some amount of outputs. The edge weights describe the ratios of these processes.

A: The term you are looking for [if there are two types of vertices as you defined] is bipartite graph: every edge is between a red vertex and a blue vertex.


text:
Q: Cannot refer to non-final variable inside an inner class I'm trying to have a CountDownTimer inside each row in a ListView. The only place I can have my onClick methods for the button in each row, is in the CustomListAdapter. But I can't refer to the TextView where the time left should be displayed. I get this error:

Cannot refer to a non-final variable holder inside an inner class
  defined in a different method

I have tried setting the holder to final, but then i get this error:

The final local variable holder cannot be assigned. It must be blank
  and not using a compound assignment

This is my code:
    public class CustomTimerRowAdapter extends ArrayAdapter < TimerRow > {

      Context context;
      int height;

      public CustomTimerRowAdapter(Context context, int resourceId,
        List < TimerRow > items) {
        super(context, resourceId, items);
        this.context = context;
        // Height of screen from not Activity subclass
        height = context.getResources().getDisplayMetrics().heightPixels;
      }

      /* private view holder class */
      private class ViewHolder {
        TextView txtTimer;
        TextView txtName;
        Button bStartStop;
      }

      public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        final TimerRow rowItem = getItem(position);

        LayoutInflater mInflater = (LayoutInflater) context
          .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        if (convertView == null) {
          convertView = mInflater.inflate(R.layout.timer_row, null);
          holder = new ViewHolder();
          // make layout params
          holder.txtTimer = (TextView) convertView.findViewById(R.id.tvTimes);
          holder.txtTimer.getLayoutParams().height = height / 10;
          holder.txtName = (TextView) convertView.findViewById(R.id.tvName);
          holder.txtName.getLayoutParams().height = height / 10;
          holder.bStartStop = (Button) convertView
            .findViewById(R.id.bStartStopTimer);
          holder.bStartStop.getLayoutParams().height = height / 10;

          convertView.setTag(holder);

        } else
          holder = (ViewHolder) convertView.getTag();

        holder.txtName.setText(rowItem.getName());

        holder.bStartStop.setOnClickListener(new OnClickListener() {
          final ViewHolder temp = new ViewHolder();@
          Override
          public void onClick(View v) {
            new CountDownTimer(30000, 1000) {

              public void onTick(long millisUntilFinished) {
                // THIS IS WHERE I CANNOT REFER TO THE NON-FINAL VARIABLE
                holder.txtTimer.setText("seconds remaining: " + millisUntilFinished / 1000);
              }

              public void onFinish() {
                holder.txtTimer.setText("done!");
              }
            }.start();

          }
        });
        return convertView;
      }
    }

Any suggestions on how to fix this?

A: This should work:
final ViewHolder holder;
ie don't assign it to null initially.

A: Instead of making holder final use v.getParent() for accessing TextView on Button click like:
holder.bStartStop.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
             View parent = (View)v.getParent();
             final TextView txtTimer = parent.findViewById(R.id.tvTimes);
             //... your code here...
        }
    });

Use txtTimer in onTick and onFinish for updating TextView text.

A: Declare ViewHolder holder as class variable. Got it? No! look  below.
your getView will look like below
    private ViewHolder holder;

    public View getView(int position, View convertView, ViewGroup parent) {
         holder = null;


text:
Q: storing the contents or a for loop into an array and then retrieving it for if statements I'm having a bit of trouble, id like to store the contents of the values from my for loop into an array or something and then recall these values to be tested against the if statements and then printed accordingly. My current code gives me a good output however if I use large numbers like 1 and 50 as input values it gives me multiple rows of "Divisible by xValue" instead of just one of each value. Thanks in advance

if (( $# > 2 )); then
        echo "Only your first two values will be used"
        for((i=($1+($1%2));i<($2-3);i+=2));do  #for loop lists all even numbers between two input values

        if (( i %  7 == 0 )); then #checks if even number divisible by 7
                echo " $i : Divisible by 7 " # prints number and labels
                elif (( $i % 11 == 0 )); then #else if checks if divisible by 7
                        echo " $i : Divisible by 11 " #prints number and labels
                        elif (( $i % 13 == 0 )); then  #if divisible by 13
                                echo " $i : Divisible by 13 "
                        fi   #closes the if statement
                        printf "%d%s, " "$i"
                        done
        echo "$i"

A: Use +=() in bash to add a new element into an array.
#! /bin/bash
set -eu

if (( $# > 2 )); then
    echo "Only your first two values will be used"
fi

even=()
for ((i=$1; i<=$2; ++i)) ; do
    if (( i % 2 == 0 )) ; then
        even+=($i)
    fi
done

for e in "${even[@]}" ; do
    for d in 7 11 13 ; do
        if (( e %  d == 0 )); then
            echo "$e: Divisible by $d"
            break
        fi
    done
    printf "%d%s, " "$e"
done


text:
Q: On changing font-size all other divs positions are getting disturbed I am in big trouble and looking for the workaround for the same.I have a web page in which i have a header and a body section . I have many divs in both sections .
My question is when i change the font-size of any text in the div , the positions of all the other divs gets changed . Kindly help me out .
HTML

Event Name

Club Name

Report Title

Hdcp Index

Player Name

Club Name

CSS
.defaultBgColor{
       min-height: 20px !important;
       border: 1px solid lightgray;
       border-radius: 5px;
       background-color: white;
       text-overflow: clip;
       white-space: nowrap;
       overflow: hidden;
    }

A: Have you tried
box-sizing:border-box;

property value? Add this value for all DIV in CSS...
If it is not work fine, please paste your code in to jsfiddle or any other....


text:
Q: How to avoid repeating drop-down options? In my form made from PHP and HTML, in the drop-down list there are 4 options. If I select any option and submit it, it works fine, but after I do that, if I open the same drop-down again to update it then there is 5 options. That means there are 4 options and the previously selected option. How can I stop this happening?
thank you
code below
<select name ="curstatus"  required="">
    <option value="<?php echo $curstatus; ?>"><?php echo $curstatus; ?> </option>
    <option value="2">Received</option>
    <option value="3">Under Processing</option>
    <option value="4">Completed</option>
    <option value="5">Out Of Office</option>
</select>

A: <select name ="curstatus" required="">
    <option value="2" <?php if ($currstatus == 2) { ?>selected="selected"<?php } ?>>Received</option>
    <option value="3" <?php if ($currstatus == 3) { ?>selected="selected"<?php } ?>>Under Processing</option>

    <!-- and all other options in the same way -->
</select>

You can also make a PHP array with options and values and just loop over that.


text:
Q: cookie delete problem I have two simple functions to set and clear cookie.
 private function _setCookie($value = null) {
    $value = $value === null ? $this->getRandomId() : $value;
    setcookie($this->getName(), $value, time()+10800, '/');
}

private function _clearCookie() {
    setcookie($this->getName(), '', time()-10800, '/');
}

There is a page when accessed starts session and create a cookie as desired. When redirect call happens from different server to my page , delete cookie function calls internally above _clearCookie funtion.I checked setcookie returns true and I also tried to unset cookie in same method but cookie is still available when I reload page. I still can find that cookie in browser as well as firebug and print_r($_COOKIE)
Also I changed expire time to time()-(3600*24) as mentioned is some others threads but no change in my case. What am I missing here?

A: so when I mentioned 'redirect call happens from different server to my page' I was trying to mention it as back channel call. And being a back channel call, browser cookies were not getting identified I suppose and that is the main reason even if setcookie returns me true, actual cookie deletion from browser would never happen in such cases.


text:
Q: How to connect to Visual FoxPro database using ngrok We are working on a project where we use ngrok for opening a tunnel to our network to perform operations on the user's machine.As part of this, we have to do open ports of different types of databases.
SQL SERVER default port (1433) is opened correctly using Ngrok. However, we are having issues while opening the port of a file-based database like Visual Foxpro database as we don't know port number.
Can anybody help me, how to find the Visual Foxpro database port number or how to connect  Visual Foxpro database using ngrok?

A: There are many ways to do this, including the following:

*

*Create a VFP web service using the old MS SOAP Toolkit

*Create a VFP DLL and wrap it with a .Net web service

*Use a VFP web framework like ActiveVFP or West-Wind Web Connection to write a web service

Look up some of Rick Strahl's articles for all things pertaining to VFP and the web, including this one:
http://www.codemag.com/Article/0703062/Visual-FoxPro-Web-Services-Revisited

A: Visual Foxpro's database is purely file-based (unless you're using remote views against SQL Server or something).
As a result there is no port number involved. If the data is in a network location then that location needs to be shared and then you access it via the share.
For example if you need to access it from a Windows application then most people use the Visual FoxPro OLEDB driver.
See also Is there any way we can connect to document databases like Visual Fox pro using TCP tunneling

A: I have used ColdFusion to create a SOAP endpoint that can query and update a VFP database. It was capable of servicing hundreds of calls per second and was stable. You do it by creating classes in CF that relate to the logical entities (tables) in VFP, and you write methods that perform the SQL query or update against the VFP tables, and return the values.


text:
Q: Are there superset/subset relations between the sets of permissions of user owner, work group and other for a file?
Unix files have two kinds of ownership: user and group, each with its
  own permissions.  Normally, the owner of a file should have full
  access to it, whereas members of a work group to which the owner
  belongs might have limited access, and everyone else, even less
  access. This last category is called other in Unix documentation.

For a file,

*

*are the permissions for its work group necessarily permissions of its user owner?
Since its user owner is a member of its work group, I guess the answer is yes, unless its work group excludes its user owner in the case of permissions. The permissions of its user owner may be more than those of its work group.

*are the permissions for its user owner necessarily permissions of other?
Some said 'other'  means the entire world. In that sense its work group should be a subset of 'other', so I guess the answer is yes, unless 'other' excludes its work group. The permissions of its work group may be more than those of 'other'.
If it matters, I am focusing on Linux.

A: Permissions under Unix-like systems use an octal representation.
It begins with an optional special permission, followed by user, group, others.  u, g, and o permissions are a combination of the following ORed together:

*

*read: 4

*write: 2

*execute: 1

Therefore, the permission 0774 would allow its owner and group full access but read-only access to others.
Those permissions, including the special permission, are independent from one another.
Files also have a single owner and group, which are also independent, in their attributes.
It is therefore possible for the owner to have read-only access while members of groupX have read-write access, and people not matching either owner or group criteria having full access.
Lets consider user john that changes permissions of text.txt to 0467, ownership to john, and group to operator:
$ chown john:operator text.txt
$ chmod 0467 text.txt
$ ls -l text.txt
-r--rw-rwx 1 john operator 0 Dec 29 00:57 text.txt

If john is not part of the operator group, he will not be able to update the file contents:
$ echo hi > text.txt
text.txt: Permission denied

But he can still change the permissions on the file, and update the file:
$ chmod u+w text.txt
$ echo hi > text.txt
$ ls -l text.txt
-rw-rw-rwx 1 john operator 3 Dec 29 00:57 text.txt

Note that accessing a file also involves folder permissions throughout the directory tree.


text:
Q: I need help figuring out what type of programmer can do what I have in mind Id like to make a program based off data taken from a video stream. Sort of how the Chinese company SenseTime can track cars and people. I know I need a back and front end programmer for the main program but I do not know much about extracting and tracking data from the video feed. Im guessing id need a programmer that knows about machine learning, neural networks, & computer vision?
Thanks for the help

A: That is correct.  A "Data Scientist" is someone who will have experience in this field.  Someone with a specialty in computer vision and convolutional neural networks.


text:
Q: Как разделить список на 2 равных списка? Я создал односвязный линейный список:
#define _CRT_SECURE_NO_WARNINGS
#include<Windows.h>
#include <stdio.h>
#include <stdlib.h>
#define N 2
#define top_range 100
#define M 100

typedef struct node
{
    char firm[M];
    char type[M];
    char color[M];
    int price;
    struct node *next;
}node;

void new_node( node **head,  node **last)
{
     node *current;
    if ((current = (struct node *)malloc(sizeof(struct node))) == NULL)
    {
        fprintf(stderr,"No free memory");
        exit(EXIT_FAILURE);
    }
    else
    {
        current->next = NULL;
        current->price = rand() % top_range;
        printf("Firm:");
        scanf("%s",current->firm);
        printf("Color:");
        scanf("%s", current->color);
        printf("Type:");
        scanf("%s", current->type);
        printf("\n");
            if (!(*head))
                *head = current;
            else
                (*last)->next = current;

            *last = current;
    }
}

void print_out( node *lst)
{
     {
        while (lst)
        {
            printf("Price:%5d\nFirm:%5s\nColor:%5s\nType:%5s\n", lst->price, lst->firm, lst->color, lst->type);
            printf("\n");
            lst = lst->next;
        }
    }

    printf("\n");

}
int main()

{

    struct node *head = NULL;
    struct node *last = NULL;
    struct node *new_head = NULL;
    int i, pos;

    for (i = 0; i < N;i++)
        new_node(&head, &last);

    printf("List - \n");
        print_out(head);

    getchar();
    getchar();
    return 0;
}

Как разделить этот список на 2 равных списка и вывести их?

A: Я разделил списки на равные по длине. Если не то, то скажите.
node * half_list ( node * const head ) {
  node * j = head ;
  // элемент перед половиной списка
  node * prev = NULL ;
  // половина списка
  node * half = j ;
  // цикл списка по два элемента
  // а половину по одному
  while ( j ) {
    if ( j -> next )
      j = j -> next ;
    else
      break ;
    prev = half ;
    half = half -> next ;
    j = j -> next ; }
  // отрезаем у первого списка конец
  if ( prev )
    prev -> next = NULL ;
  // возвращаем остаток
  return half ; }
...

printf("1.List - \n");
    print_out(head);

new_head = half_list ( head ) ;

printf("2.List - \n");
    print_out(head);
printf("3.List - \n");
    print_out(new_head);


text:
Q: Init scripts do not run on mongo container start I want to create a MongoDB replica set with a standalone instance running in docker to be able to work with multi-document transactions.
The problem is that the replica set is not initiated automatically, I always have to start it manually, so I can't run it in gitlab runner.
My Dockerfile is as follows:
FROM mongo:4.2

RUN echo "rs.initiate({'_id':'rs0','members':[{'_id':0,'host':'127.0.0.1:27017'}]});" > /docker-entrypoint-initdb.d/replica-init.js

RUN chmod u+x /docker-entrypoint-initdb.d/replica-init.js

RUN cat /docker-entrypoint-initdb.d/replica-init.js

CMD [ "--bind_ip_all", "--replSet", "rs0" ]

And here the docker-compose snippet:
  mongo:
    build:
      context: .
      dockerfile: docker/mongo/Dockerfile
    command: --replSet rs0
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: root
    ports:
      - 27017:27017

I put this script into docker-entrypoint-initdb.d so it should run automatically on first container start but it does not happen.
If I run the same initiate() command manually using mongo shell - it then works fine.
Any ideas on what I do wrong?


text:
Q: Camtasia video with machine narrator I am new to Camtasia. Now I need to use machine narrator as the audio input instead of  microphone when I record on-screen activities, I didn't find out any solution for this case. Does any of you have any idea to integrate machine narrator into camtasia video? Thanks!

A: Stack Overflow is a Q/A site for programmers. If you'd like, you can ask at http://feedback.techsmith.com/techsmith.
It is TechSmith's general support forum. TechSmith is the creator of Camtasia. If you choose to ask there, elaborate on "Machine Narrator," because I genuinely don't understand. Good luck!


text:
Q: Prove that $U_{a+b}=U_aU_b+U_{a-1}U_{b-1}$ for $a\ge1$ and $b\ge1$ I am trying to prove that $U_{a+b}=U_aU_b+U_{a-1}U_{b-1}$ for $a\ge1$ and $b\ge1$, where $U_a$=$\sum_k {a-k\choose k}$.
Therefore $\sum_k {a+b-k\choose k}$=$\sum_k {a-k\choose k}$$\sum_k {b-k\choose k}$ + $\sum_k {a-k-1\choose k}$$\sum_k {b-k-1\choose k}$.
How can I modify the right hand side of the equation to get the left hand side?

A: We derive a closed formula for a generalisation of $U_m$ which will then be used to prove the identity.

The following is valid for $m\geq 0$
  \begin{align*}
\sum_{k=0}^{\lfloor m/2\rfloor}\binom{m-k}{k}z^k
=\frac{1}{\sqrt{1+4z}}\left(\left(\frac{1+\sqrt{1+4z}}{2}\right)^{m+1}
-\left(\frac{1-\sqrt{1+4z}}{2}\right)^{m+1}\right)\tag{1}
\end{align*}

It is convenient to use the coefficient of operator $[t^m]$ to denote the coefficient of $t^m$ of a series. We start with the generating function
\begin{align*}
\frac{1}{1-t-zt^2}
\end{align*}

On the one hand it can be shown by partial fraction decomposition
  \begin{align*}
[t^m]\frac{1}{1-t-zt^2}
&=[t^m]\frac{1}{\left(1-\frac{1+\sqrt{1+4z}}{2}t\right)\left(1-\frac{1-\sqrt{1+4z}}{2}t\right)}\\
&=\frac{1}{\sqrt{1+4z}}\left(\left(\frac{1+\sqrt{1+4z}}{2}\right)^{m+1}-\left(\frac{1-\sqrt{1+4z}}{2}\right)^{m+1}\right)
\end{align*}
  On the other hand we derive
  \begin{align*}
[t^m]\frac{1}{1-t-zt^2}&=[t^m]\frac{1}{1-t}\cdot\frac{1}{1-\frac{zt^2}{1-t}}\\
&=\frac{1}{1-t}\sum_{j=0}^\infty \frac{z^j t^{2j}}{(1-t)^j}\tag{2}\\
&=\sum_{j=0}^\infty \frac{z^j t^{2j}}{(1-t)^{j+1}}\\
&=\sum_{j=0}^\infty t^{2j}\sum_{l=0}^\infty \binom{-j-1}{l}(-t)^lz^j\tag{3}\\
&=\sum_{j=0}^\infty t^{2j}\sum_{l=0}^\infty \binom{l+j}{l}t^lz^j\tag{4}\\
&=\sum_{j=0}^{\lfloor n/2\rfloor} [t^{n-2j}]\sum_{l=0}^\infty \binom{l+j}{l}t^lz^j\tag{5}\\
&=\sum_{j=0}^{\lfloor n/2\rfloor} \binom{n-j}{n-2j}z^j\tag{6}\\
&=\sum_{j=0}^{\lfloor n/2\rfloor} \binom{n-j}{j}z^j
\end{align*}
  and the claim (1) follows.

Comment:

*

*In (2) we apply the geometric series expansion.

*In (3) we apply the binomial series expansion.

*In (4) we use the binomial identity  $\binom{-p}{q}=\binom{p+q-1}{q}(-1)^q$.

*In (5) we use the linearity of the coefficient of operator and use the rule $$[t^{p+q}]A(t)=[t^p]t^{-q}A(t)$$ We also restrict the upper limit of the sum since the exponent of $t^{n-2j}$ has to be non-negative.

*In (6) we select the coefficient of $t^{n-2j}$.

We obtain from (1) the following identity by setting $z=1$
  \begin{align*}
U_m=\sum_{k=0}^{\lfloor m/2\rfloor}\binom{m-k}{k}
=\frac{1}{\sqrt{5}\cdot2^{m+1}}\left(\left(1+\sqrt{5}\right)^{m+1}-\left(1-\sqrt{5}\right)^{m+1}\right)
\end{align*}

Next we calculate $U_aU_b$ and $U_{a-1}U_{b-1}$.

\begin{align*}
U_aU_b&=\frac{1}{5\cdot2^{a+b+2}}\left(\left(1-\sqrt{5}\right)^{a+b+2}
-\left(1-\sqrt{5}\right)^{a+1}\left(1+\sqrt{5}\right)^{b+1}\right.\\
&\qquad\qquad\qquad\qquad\left.-\left(1+\sqrt{5}\right)^{a+1}\left(1-\sqrt{5}\right)^{b+1}
+\left(1+\sqrt{5}\right)^{a+b+2}\right)\\
&=\frac{1}{5\cdot2^{a+b}}\left(
\frac{3-\sqrt{5}}{2}\left(1-\sqrt{5}\right)^{a+b}
+\left(1-\sqrt{5}\right)^{a}\left(1+\sqrt{5}\right)^{b}\right.\\
&\qquad\qquad\qquad\qquad\left.+\left(1+\sqrt{5}\right)^{a}\left(1-\sqrt{5}\right)^{b}
+\frac{3+\sqrt{5}}{2}\left(1+\sqrt{5}\right)^{a+b}\right)\\
\\
U_{a-1}U_{b-1}&=\frac{1}{5\cdot2^{a+b}}\left(\left(1-\sqrt{5}\right)^{a+b}
-\left(1-\sqrt{5}\right)^{a}\left(1+\sqrt{5}\right)^{b}\right.\\
&\qquad\qquad\qquad\qquad\left.-\left(1+\sqrt{5}\right)^{a}\left(1-\sqrt{5}\right)^{b}
+\left(1+\sqrt{5}\right)^{a+b}\right)\\
\end{align*}

It follows by collecting equal terms

\begin{align*}
U_aU_b+U_{a-1}U_{b-1}
&=\frac{1}{5\cdot2^{a+b}}\left(
\left(\frac{3-\sqrt{5}}{2}+1\right)\left(1-\sqrt{5}\right)^{a+b}+0\right.\\
&\qquad\qquad\qquad\qquad\left.+0+\left(\frac{3+\sqrt{5}}{2}+1\right)\left(1+\sqrt{5}\right)^{a+b}\right)\\
&=\frac{1}{5\cdot2^{a+b+1}}
\left(\left(1+\sqrt{5}\right)^{a+b+1}+\left(1-\sqrt{5}\right)^{a+b+1}\right)\\
&=U_{a+b}
\end{align*}
  and  the claim follows.


text:
Q: LTC1775 Buck converter component question I am trying to design a 12v,10A buck converter using a with LTC1775 and have gone through the calculations assuming a 40% inductor ripple current and a switching frequency of 150kHz. This gave an inductor value of 10uH and a mosfet with Rds(on) of 0.014ohm. So based on these i have selected IRLR3915 NMOS and 7443558100 inductor.
My main concerns are the following:

*

*Are these two good choices with regards to the output current or they are overkill?

*Should i attach a flyback diode across the output incase I have an inductive load like a motor?

*Are the Cin and Cout capacitors adequate? Based on datasheet formulas our output voltage ripple is supposedly ~60mv but the simulation only shows ~10mv

here is the circuit schematic:

and here is a inductor current on LTspice, as you can see the current does reach ~15A:

I can attach the calculations if its needed.
Thank you, I really appreciate your guys help.

A:
Are these two good choices with regards to the output current or they are overkill?

Use LT powercad (almost all linears DC DC conveters are there) to find optimal components, it is much easier to use and quicker (I'd run this design through myself but haven't the time).

Should i attach a flyback diode across the output incase I have an
  inductive load like a motor?

Yes, you may also want to consider a filter, the DC DC compensation loop may also present problems from the inductance of the motor. Extra capacitance\filtering may be advantageous with a motor. Because the motor impdeance is hard to determine (and for most motors non-linear) it may require experimentation to get the right compensation\filtering and to avoid voltage dropouts.

Are the Cin and Cout capacitors adequate? Based on datasheet formulas our output voltage ripple is supposedly ~60mv but the
  simulation only shows ~10mv

You have a fixed load, switch the load in the simulation to determine if it really is adaquate (unless your load really is fixed).


text:
Q: Check if element is visible after scrolling - jquery I have a ul element. my page has a scroll bar.I want to know when this element no longer visible I do stuff and when that element is visible I do something.

test 31

test 31

test 31

test 31

on stackoverflow, there are some functions like  :
if ($('body').hasClass('sticky-header')) {
    var theLoc = $('#categories').position().top;
    $(window).scroll(function() {

        if(isScrolledIntoView('#categories')){

            console.log('if');

        }else{
            console.log('else');
        }

    });
}

function isScrolledIntoView(elem)
{
    var $elem = $(elem);
    var $window = $(window);

    var docViewTop = $window.scrollTop();
    var docViewBottom = docViewTop + $window.height();

    var elemTop = $elem.offset().top;
    var elemBottom = elemTop + $elem.height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

but it doesn't work fine.


text:
Q: Вызов асинхронной функции внутри map Пытаюсь вызвать асинхронную функцию внутри map, но не получается. Что я делаю не так, подскажите, не могу понять.
АФ:
const GetAdditionalData = async (url) => {
  try {
    const response = await fetch(`url`)
    const json = await response.json()

    return json.data.result
  } catch (error) {
    console.error(error)
  }
}

Пример:
try {
  const promises = [1, 2].map(async market => {
    try {

      const data = await GetMarketData(market)
      const onlyOpen = data.filter(x => x[1] === 'open')

      return onlyOpen.map(async item => {
        const url = "..."
        const addData = await GetAdditionalData(url)

        return {
          main: item[0],
          sec: item[1],
          adInfo: GetAdditionalData(url)
        }

      })

    } catch (error) {
      return Promise.reject(error)
    }
  })

  Promise.all(promises).then(
    results => {
      res.status(200).send([...results[0], ...results[1]])
    },
    reason => {
      res.status(404).send(reason)
    }
  )
} catch (error) {
  res.status(404).send(error)
}

Все идет нормально до момента как я пытаюсь получить доп. инфу(adInfo) из await GetAdditionalData(url).


text:
Q: Ошибка при форматирование формы из Qt в PyQt Установил python версии 3.5(галочку поставил add path, путь дефолтный) и pyqt4
Сам питон стоит тут:

C:\Users\admin\AppData\Local\Programs\Python\Python35-32

PyQt стоит тут:

C:\Python34\Lib\site-packages\PyQt4

В path пути имеются
При форматировании простенькой формы из qt designer в формат pyqt получаю такую ошибку:

C:\Python34\Lib\site-packages\PyQt4>pyuic4.bat form.ui -o project.py
  ""C:\Python34\python"" не является внутренней или внешней командой,
  исполняемой программой или пакетным файлом.

Подскажите что я не так делаю?

A: Как вы могли бы догадаться, PyQt4, который вы установили, предназначен для работы с python 3.4. Поэтому у вас есть 2 варианта:
1) Если вам нужен именно python 3.5, то вам придется установить PyQt5, т.к. официального установщика PyQt4 для данной версии питона не существует.
2) Если вам нужен именно PyQt4, то советую сначала удалить уже установленный PyQt4, установить python 3.4 или python 2.7 последней ревизии, затем снова установить PyQt4 для соответствующей версии python.

A: Установка библиотеки для одной версии Питона, в общем случае, не делает её доступной для другой версии Питона.
Если вы хотите использовать библиотеку на Питоне 3.5, то и ставьте её на Питон 3.5, а не 3.4.


text:
Q: How to get RequestBody whose attribute are in camelCase but I have application level property-naming-strategy: SNAKE_CASE in springboot I have a nested object e.g
{
"driverNumber": 1,
"expressCustomerNumber": 34637593,
"salutationCode": "1",
"firstName": "firstName",
"lastName": "lastName",
"birthday": "1971-04-09T00:00Z",
"placeOfBirth": "",
"birthCountryCode": "",
"address": {
    "isoCountryCode": "US",
    "state": "TX",
    "postCode": "77363",
    "city": "city",
    "street": "street"
    }
}

and since my application level property-naming-strategy: SNAKE_CASE so it accepts driver_number(not driverNumber), I can add JsonProperty annotation at each attribute but I don't want to do that. Any other way to read the object.


text:
Q: So what *did* Alan Kay really mean by the term "object-oriented"? Reportedly, Alan Kay is the inventor of the term "object oriented". And he is often quoted as having said that what we call OO today is not what he meant.
For example, I just found this on Google:

I made up the term 'object-oriented', and I can tell you I didn't have C++ in mind
-- Alan Kay, OOPSLA '97

I vaguely remember hearing something pretty insightful about what he did mean. Something along the lines of "message passing".
Do you know what he meant? Can you fill in more details of what he meant and how it differs from today's common OO? Please share some references if you have any.

A: One of the major points that I've picked up from following the works of Alan Kay and others such as Jim Coplien is that true "object" oriented programming is about modeling computers and software in terms of HUMAN/USER mental models, rather than being just a tool for PROGRAMMERS.
As I understand it, Alan's vision of OOP was making the computer a tool that allows a human user to make whatever they want: the full capabilities of the computer are directly exposed to the end user through an intuitive interactive model. I should be able view and sculpt runtime objects and interactions DIRECTLY, not just through code.
Here is a post about my plans to attempt a some version of this in JavaScript as a proof of concept:http://www.cemetech.net/forum/viewtopic.php?p=234494#234494
From a perspective of software development / programming, Jim Coplien talks about how code can and SHOULD resemble the users mental model of it. That is, the code reads much the same way as it would sound by a person describing it's behavior. This is largely accomplished by thinking in terms of OBJECTS, rather than in terms of CLASSES and TYPES. Behavior is described on terms of the ROLES played by objects, not as part of the definition of an object's IDENTITY.  You should be able to model interactions on terms of objects, which are identified by the ROLE they play in an interaction. This is how human mental models work: Waiter, Customer, Cashier, Source Account, Destination Account,... These are ROLES, not TYPES, and you want to the able to define methods for "whatever object is playing this role at the time", because  that behavior is part of a system interaction between many changing objects, rather than part of the definition of some TYPE.

A:
Most if not all of what Alan Kay meant by object-orientation is embodied in the Smalltalk language.

"We didn't even do all of the idea at PARC. Many of Carl Hewitt's Actors ideas which got sparked by the original Smalltalk were more in the spirit of OOP than the subsequent Smalltalks. Significant parts of Erlang are more like a real OOP language the the current Smalltalk, and certainly the C based languages that have been painted with "OOP paint"."
Taken from Alan Kay's comment at:
http://computinged.wordpress.com/2010/09/11/moti-asks-objects-never-well-hardly-ever/

A: Most if not all of what Alan Kay meant by object-orientation is embodied in the Smalltalk language.
Also, from http://en.wikipedia.org/wiki/Message_passing#Influences_on_other_programming_models:
Alan Kay has argued that message passing is more important than objects in OOP, and that objects themselves are often over-emphasized. The live distributed objects programming model builds upon this observation; it uses the concept of a distributed data flow to characterize the behavior of a complex distributed system in terms of message patterns, using high-level, functional-style specifications.

A: TL;DR - Alan Kay wrote in 2003 that:

OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things.
It can be done in Smalltalk and in LISP. There are possibly other systems in which this is possible, but I'm not aware of them.

http://www.purl.org/stefan_ram/pub/doc_kay_oop_en
------- Full source, for context:

Date: Wed, 23 Jul 2003 09:33:31 -0800   To: Stefan Ram [removed for
privacy]   From: Alan Kay [removed for privacy]   Subject: Re:
Clarification of "object-oriented"
Hi Stefan --
Sorry for the delay but I was on vacation.
At 6:27 PM +0200 7/17/03, Stefan Ram wrote:

Dear Dr. Kay,
I would like to have some authoritative word on the term
"object-oriented programming" for my tutorial page on the
subject. The only two sources I consider to be "authoritative"
are the International Standards Organization, which defines
"object-oriented" in "ISO/IEC 2382-15", and you, because,
as they say, you have coined that term.

I'm pretty sure I did.

Unfortunately, it is difficult to find a web page or source
with your definition or description of that term. There are
several reports about what you might have said in this regard
(like "inheritance, polymorphism and encapsulation"), but
these are not first-hand sources. I am also aware that later
you put more emphasis on "messaging" - but I still would like
to know about "object oriented".

For the records, my tutorial page, and further distribution
and publication could you please explain:
When and where was the term "object-oriented" used first?

At Utah sometime after Nov 66 when, influenced by Sketchpad, Simula,
the design for the ARPAnet, the Burroughs B5000, and my background in
Biology and Mathematics, I thought of an architecture for programming.
It was probably in 1967 when someone asked me what I was doing, and I
said: "It's object-oriented programming".
The original conception of it had the following parts.

*

*I thought of objects being like biological cells and/or individual computers on a network, only able to communicate with messages (so
messaging came at the very beginning -- it took a while to see how to
do messaging in a programming language efficiently enough to be
useful).

*I wanted to get rid of data. The B5000 almost did this via its almost unbelievable HW architecture. I realized that the
cell/whole-computer metaphor would get rid of data, and that "<-"
would be just another message token (it took me quite a while to think
this out because I really thought of all these symbols as names for
functions and procedures.

*My math background made me realize that each object could have several algebras associated with it, and there could be families of
these, and that these would be very very useful. The term
"polymorphism" was imposed much later (I think by Peter Wegner) and it
isn't quite valid, since it really comes from the nomenclature of
functions, and I wanted quite a bit more than functions. I made up a
term "genericity" for dealing with generic behaviors in a
quasi-algebraic form.

*I didn't like the way Simula I or Simula 67 did inheritance (though I thought Nygaard and Dahl were just tremendous thinkers and
designers). So I decided to leave out inheritance as a built-in
feature until I understood it better.
My original experiments with this architecture were done using a model
I adapted from van Wijngaarten's and Wirth's "Generalization of Algol"
and Wirth's Euler. Both of these were rather LISP-like but with a more
conventional readable syntax. I didn't understand the monster LISP
idea of tangible metalanguage then, but got kind of close with ideas
about extensible languages draw from various sources, including Irons'
IMP.
The second phase of this was to finally understand LISP and then using
this understanding to make much nicer and smaller and more powerful
and more late bound understructures. Dave Fisher's thesis was done in
"McCarthy" style and his ideas about extensible control structures
were very helpful. Another big influence at this time was Carl
Hewitt's PLANNER (which has never gotten the recognition it deserves,
given how well and how earlier it was able to anticipate Prolog).
The original Smalltalk at Xerox PARC came out of the above. The
subsequent Smalltalk's are complained about in the end of the History
chapter: they backslid towards Simula and did not replace the
extension mechanisms with safer ones that were anywhere near as
useful.

What does "object-oriented [programming]" mean to you?
(No tutorial-like introduction is needed, just a short
explanation [like "programming with inheritance,
polymorphism and encapsulation"] in terms of other concepts
for a reader familiar with them, if possible. Also, it is
not neccessary to explain "object", because I already have
sources with your explanation of "object" from
"Early History of Smalltalk".)

(I'm not against types, but I don't know of any type systems that
aren't a complete pain, so I still like dynamic typing.)
OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things.
It can be done in Smalltalk and in LISP. There are possibly other systems in which this is possible, but I'm not aware of them.
[Also,] One of the things I should have mentioned is that there were
two main paths that were catalysed by Simula. The early one (just by
accident) was the bio/net non-data-procedure route that I took. The
other one, which came a little later as an object of study was
abstract data types, and this got much more play.
If we look at the whole history, we see that the proto-OOP stuff
started with ADT, had a little fork towards what I called "objects"
-- that led to Smalltalk, etc.,-- but after the little fork, the CS establishment pretty much did ADT and wanted to stick with the
data-procedure paradigm. Historically, it's worth looking at the USAF
Burroughs 220 file system (that I described in the Smalltalk history),
the early work of Doug Ross at MIT (AED and earlier) in which he
advocated embedding procedure pointers in data structures, Sketchpad
(which had full polymorphism -- where e.g. the same offset in its data
structure meant "display" and there would be a pointer to the
appropriate routine for the type of object that structure represented,
etc., and the Burroughs B5000, whose program reference tables were
true "big objects" and contained pointers to both "data" and
"procedures" but could often do the right thing if it was trying to go
after data and found a procedure pointer. And the very first problems
I solved with my early Utah stuff was the "disappearing of data" using
only methods and objects. At the end of the 60s (I think) Bob Balzer
wrote a pretty nifty paper called "Dataless Programming", and shortly
thereafter John Reynolds wrote an equally nifty paper "Gedanken" (in
1970 I think) in which he showed that using the lamda expressions the
right way would allow data to be abstracted by procedures.
The people who liked objects as non-data were smaller in number, and
included myself, Carl Hewitt, Dave Reed and a few others -- pretty
much all of this group were from the ARPA community and were involved
in one way or another with the design of ARPAnet → Internet in
which the basic unit of computation was a whole computer. But just to
show how stubbornly an idea can hang on, all through the seventies and
eighties, there were many people who tried to get by with "Remote
Procedure Call" instead of thinking about objects and messages. Sic
transit gloria mundi.
Cheers,
Alan Kay


text:
Q: How to share an instance variable among different classes in Python Suppose I have a class Game with attributes player1, player2, and Q. player1 and player2 are themselves instances of the class Player which also has an attribute called Q. I would like to make it such that when I instantiate a Game, it shares its Q with the instances of Player it was instantiated with.
To illustrate what I mean, consider this code:
class Game:
    def __init__(self, player1, player2):
        self.player1 = player1
        self.player2 = player2
        self.Q = {}

class Player:
    def __init__(self, mark):
        self.mark = mark
        self.Q = {}

player1 = Player(mark="X")
player2 = Player(mark="O")

game = Game(player1, player2)           # Instantiate a game with player 1 and player 2

game.Q["some key"] = "some value"

# I would like this to happen automatically
player1.Q = game.Q
player2.Q = game.Q

I'd like player1 and player2's Q variable to get updated automatically to game.Q whenever it changes. How can I achieve this?

A: You can introduce base class with Q as a class attribute:
class Base(object):
    Q = {}

class Player(Base):
    def __init__(self, mark):
        self.mark = mark

class Game(Base):
    def __init__(self, player1, player2):
        self.player1 = player1
        self.player2 = player2

player1 = Player(mark="X")
player2 = Player(mark="O")

game = Game(player1, player2)           # Instantiate a game with player 1 and player 2

game.Q["some key"] = "some value"

But this works only if you want to have one instance of game with players because if you create next Game it will have same Q as the previous one.

A: Following Rawing's comment, I used self.Q = self.player1.Q = self.player2.Q = {} in the __init__ of Game:
class Game:
    def __init__(self, player1, player2):
        self.player1 = player1
        self.player2 = player2
        self.Q = self.player1.Q = self.player2.Q = {}

class Player:
    def __init__(self, mark):
        self.mark = mark
        self.Q = {}

player1 = Player(mark="X")
player2 = Player(mark="O")

game = Game(player1, player2)           # Instantiate a game with player 1 and player 2

game.Q["some key"] = "some value"

As a result, player1.Q now yields {'some key': 'some value'} without having to 'update' it manually.


text:
Q: Como dar select entre uma hora_minuto e outra no SQL Preciso resolver um exercício simples pedindo para informar a quantidade de livros vendidos entre as 13h e 17h30 de todas as datas.
Consegui puxar entre as 13h e 17h mas não com os minutos "17h30".
Fiz assim:
SELECT SUM(quantidade)
FROM notafiscal WHERE extract(hour FROM data_compra) BETWEEN 13 AND 17;

Tentei usar hour_minute ao invez de hour e por '17:30' mas volta como null qualquer resultado.

A: Tente converter em texto:
SELECT SUM(quantidade)
FROM notafiscal
WHERE DATE_FORMAT(Data_compra, '%T') BETWEEN '13:00:00' AND '17:30:00'


text:
Q: AjaxUploadControl does not fire onuploadcomplete method I am trying to implement the AjaxUploadControl functionality on my site but it does not fire the OnUploadComplete method. Instead, it simply says file uploaded 100%, but the file is not in the specified folders. I have set breakpoints in the OnUploadComplete method and have been able to determine that this method is never being reached. It almost seems to be jumping into an infinite loop as the Cancel button displays, but none of the buttons on the screen are clickable once an attempt has been made to upload a file.
The .aspx page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AjaxTest.aspx.cs" Inherits="AjaxTest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

    <form id="form1" runat="server">
        <ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        </ajaxToolkit:ToolkitScriptManager>

            <ajaxToolkit:AjaxFileUpload ID="ajaxUpload1" runat="server" OnUploadComplete="ajaxUpload1_OnUploadComplete" />

    </form>

The codebehind file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class AjaxTest : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void ajaxUpload1_OnUploadComplete(object sender,   AjaxControlToolkit.AjaxFileUploadEventArgs e)
    {
        string filePath = "~/SiteImages/" + e.FileName;
        ajaxUpload1.SaveAs(MapPath(filePath));
    }
}

Help is greatly appreciated!

A: The property is OnClientUploadComplete, not OnUploadComplete.
Refer to this.

Events
UploadedComplete - Raised on the server when a file is uploaded
  successfully. In this event an instance of AjaxFileUploadEventArgs is
  passed in the argument that contains file name, size and content type.

A: If you don't set the right enctype and method UploadedComplete will never fire.
try adding enctype="multipart/form-data" into your form tag.

e.g.
 <form id="form1" runat="server" enctype="multipart/form-data" method="post">
Code behind:
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
    string filePath = "~/SiteImages/";
    AjaxFileUpload1.SaveAs(MapPath(filePath + System.IO.Path.GetFileName(e.FileName)));
}

Code inline:
<form id="form1" runat="server" enctype="multipart/form-data" method="post">
      <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>

        <asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
            onuploadcomplete="AjaxFileUpload1_UploadComplete" />

    </form>

Hope it helps.

A: The actual problem you were having is that you needed a HTTP handler in your web.config
<httpHandlers>
    <add verb="*" path="AjaxFileUploadHandler.axd"
      type="AjaxControlToolkit.AjaxFileUploadHandler,
      AjaxControlToolkit"/>
</httpHandlers>

I had the very same issue (red error on upload, event in .cs file not firing at all ), now resolved by adding that to my web.config

A: I discovered the problem that I am having. I was trying to implement the functionality in a website versus a web app. I created a test web app platform and it worked flawlessly. I am a beginner to AJAX and did not realize that this would cause issues, however, does anyone know a solution to get this functionality to work in a website. I'm afraid that there is too much to easily port over to web app at this time.

A: KINDLY FOLLOW THE FOLLOWING RULES (.NET 4.0)   OR (.NET 4.5 FRAMEWORKS)
MAKE SURE FOLLOWING STEPS WERE USED IN YOUR PROJECT

*

*HTML PAGE (MUST BE LIKE THIS)

<form id="form1" runat="server" enctype="multipart/form-data" method="post">

    <ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></ajaxToolkit:ToolkitScriptManager>
    <ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server" OnUploadComplete="AjaxFileUpload1_UploadComplete" ClientIDMode="Static" ContextKeys="dd" MaximumNumberOfFiles="4" />

</form>

*IMPORTENT WEB.Config SHOULD BE (HAVING FOLLOWING TAGS for .net 4.5)
<system.webServer>
    <handlers>
     <add name="aa" verb="*" path="AjaxFileUploadHandler.axd" type="AjaxControlToolkit.AjaxFileUploadHandler, AjaxControlToolkit" />
    </handlers>
  </system.webServer>

*IMPORTENT WEB.Config SHOULD BE (HAVING FOLLOWING TAGS for less than 4 or 4.5)
<httpHandlers>
    <add verb="*" path="AjaxFileUploadHandler.axd"
      type="AjaxControlToolkit.AjaxFileUploadHandler,
      AjaxControlToolkit"/>
</httpHandlers>


text:
Q: Linking boost libraries I have downloaded the boost library (version 1.46.1), but I don't know how to link it through xcode.I found an old question says to put the -lfftw3 flag, so I've put it.
I also added the path: /home/Documents/C++/boost_1_46_1 (it's the directory where I have put the library), but I am getting an error from the linker:
ld: warning: directory not found for option '-L/home/ramy/Documents/C++/boost_1_46_1'
ld: library not found for -lfftw3
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Command /Developer/usr/bin/clang++ failed with exit code 1

So the question are two:
1)How to manage xcode to link boost?
2)Where to put the library in file system? In linux there was /usr/lib, here there isn't this path, should I put it in /Developer/usr/lib?

A: Or for those who are looking for a quick answer (and are on linux), the magic is simply to add the following flags:
-l boost_system


text:
Q: Allow Dynamic Media URL in Products and Categories setting gone? I am running Magento 2.4.2 and I am not seeing to option to enable "Allow Dynamic Media URL in Products and Categories" under Store -> Configuration -> Catalog -> Storefront. How can I get media urls to work for category pages?

A: Issue solved. This was caused by the IceCat Live plugin.


text:
Q: How do I get data from the wunderground API and display it on the screen in Android? Currently I have a picture of a map in Android Studio, and I was wondering how I'd be able to pull information from wunderground and display it on top of the map in each location.
This is the website with some sample code.

A: That would depend on the type of data. Concider an example that pulls eathquake data location from a JSON feed.
try {
        JSONObject object = (JSONObject) new JSONTokener(JSONResponse)
                .nextValue();
        JSONArray earthquakes = object.getJSONArray("features");

        for (int i = 0; i < earthquakes.length(); i++) {
            JSONObject tmp = (JSONObject) earthquakes.get(i);
            //Log.i("JSON: ",tmp.toString());

            JSONObject geometry = tmp.getJSONObject("geometry");
            JSONArray coords = geometry.getJSONArray("coordinates");
            JSONObject properties = tmp.getJSONObject("properties");

            //Log.i("Data", "Coords:"+coords.getString(0) + " "+ coords.getString(1)+"\n Place:"+properties.getString("place")+ " Mag:"+properties.getString("mag"));

            if(coords.getString(0) != "" && coords.getString(1) != ""){
                result.add(new EarthQuakeRec(
                        Float.parseFloat(coords.getString(1)),//Lat
                        Float.parseFloat(coords.getString(0)),//Long
                        Float.parseFloat(properties.getString("mag")),//Magnitude
                        properties.getString("place")
                    )
                );
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

And the JSON structure looks something like this:
{
"id": "nc72241526",
"type": "Feature",
"geometry": {
    "type": "Point",
    "coordinates": [
        -122.0102,
        37.6053,
        6
    ]
},
"properties": {
    "detail": "http://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/nc72241526.geojson",
    "type": "earthquake",
    "net": "nc",
    "tsunami": null,
    "sources": ",nc,",
    "title": "M 3.0 - 1km NE of Union City, California",
    "time": 1403371328500,
    "updated": 1403374699020,
    "mag": 3,
    "types": ",dyfi,focal-mechanism,general-link,geoserve,nearby-cities,origin,phase-data,scitech-link,tectonic-summary,",
    "place": "1km NE of Union City, California",
    "status": "AUTOMATIC",
    "ids": ",nc72241526,",
    "alert": null,
    "rms": 0.17,
    "code": "72241526",
    "url": "http://earthquake.usgs.gov/earthquakes/eventpage/nc72241526",
    "magType": "Md",
    "mmi": null,
    "cdi": 3.8,
    "tz": -420,
    "felt": 319,
    "nst": 75,
    "dmin": 0.03593261,
    "gap": 25.2,
    "sig": 260
}

}
Then you would start with the JSONObject class and drill down to the data points of interest. Use the Log class to help you trouble shoot and gauge your progress in traversing your data structure. In my example, it is commented out.
For XML, you can try something to the tune of this:
        try {

        // Create the Pull Parser
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        XmlPullParser xpp = factory.newPullParser();

        // Set the Parser's input to be the XML document in the HTTP Response
        xpp.setInput(new InputStreamReader(response.getEntity()
                .getContent()));

        // Get the first Parser event and start iterating over the XML document
        int eventType = xpp.getEventType();

        while (eventType != XmlPullParser.END_DOCUMENT) {

            if (eventType == XmlPullParser.START_TAG) {
                startTag(xpp.getName());
            } else if (eventType == XmlPullParser.END_TAG) {
                endTag(xpp.getName());
            } else if (eventType == XmlPullParser.TEXT) {
                text(xpp.getText());
            }
            eventType = xpp.next();
        }
        return mResults;
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    }

It is a lot to throw at you, but you did not give much specificity. Hope that helps. ;)


text:
Q: 401 UNAUTHORIZED after replacing master page file I am getting 401 UNAUTHORIZED when I replace the mysite15.master file with custom one.
I am logged in with administrator but still having unauthorized access when I open then SharePoint site

A: please make sure, that every file which is linked in the masterpage (css, pictures...) is minimum in version 1.0. (Checkin as Major Version).
I've struggled a lot with 401 unauthorized exception in masterpages. You have to find out, which file is not published.


text:
Q: Multilevel modelling I am a newbie here and looking to answer my RQ: How does human comfort level with the robot changes given 4 different ways of expressing emotions? using multilevel modelling.
Independent Variable: 4 different ways of expressing emotions
Dependent Variable: Human comfort level responses from 0 - 100 on a Likert scale.

*

*This experiment is a between group design i.e, 4 different groups of
participants interacted with 4 different ways of expressing emotions.

*Each participant interacted with the robot for 15 minutes with giving
human comfort level rating after each minute.

*Robot displays negative emotions always at the start of 5th, 8th, 12th and 13th minute.
With a multilevel model that models the 15 responses (random intercepts for participants), and with a lag factor in the model, I wish to see how much time it take for human comfort to build up again after negative emotions and if that differs across 4 ways of expressing emotions.
The mean responses of human comfort looks like this:

Can I use GLMER in some way to achieve this?
Thanks!


text:
Q: navigation controller push another controller trigger tableview call scrollViewDidScroll: I have a tableview in the root view controller of a navigation controller.
And I use the JBParallaxCell for main view and segue into detailView, then return form detailview to JBParallaxCell and it will reset the imageView position.
JBParallaxCell is used to create a parallax image view in the tableview. However the image blinks when navigation controller push back to the tableview because it resets the position of the image view.
How could I fix this bug?
Thanks for any help!
Here are some code snippet:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // Get visible cells on table view.
    NSArray *visibleCells = [self.tableView visibleCells];

    for (JBParallaxCell *cell in visibleCells)
    {
        [cell cellOnTableView:self.tableView didScrollOnView:self.view];
    }

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    JBViewController *controller = [[JBViewController alloc] init];
    [self.navigationController pushViewController:controller animated:YES];
}

JBParallaxCell.h:
@interface JBParallaxCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UIImageView *parallaxImage;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *subtitleLabel;

- (void)cellOnTableView:(UITableView *)tableView didScrollOnView:(UIView *)view;

@end

JBParallaxCell.m:
@implementation JBParallaxCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];
    // Configure the view for the selected state
}

- (void)cellOnTableView:(UITableView *)tableView didScrollOnView:(UIView *)view
{
    NSLog(@"cell scrolling...");
    CGRect rectInSuperview = [tableView convertRect:self.frame toView:view];

    float distanceFromCenter = CGRectGetHeight(view.frame)/2 - CGRectGetMinY(rectInSuperview);
    float difference = CGRectGetHeight(self.parallaxImage.frame) - CGRectGetHeight(self.frame);
    float move = (distanceFromCenter / CGRectGetHeight(view.frame)) * difference;

    CGRect imageRect = self.parallaxImage.frame;
    imageRect.origin.y = -(difference/2)+move;
    self.parallaxImage.frame = imageRect;
}

A: I have the similar problem, after I call popViewControllerAnimated:YES from view controller, my table view is scrolled to the top position automatically.
And I think this is a bug of IOS7/8.
In IOS9+ it is alright.
The more the estimatedRowHeight differs from the actual height, the more the table will jump when the push segue happens.
After comment this line:
self.tableView.estimatedRowHeight = 64.0;

UITableView didn't jump any more.


text:
Q: Building Caught on Fire Which one of the following sentences is correct and why? Are there any other options? I'm not sure about the usage of "was", "has" and "on" in this situation.

*

*This building caught fire

*This building was caught on fire

*This building caught on fire

*This building has caught fire

I would like to use this to say that an abandoned building caught fire many years ago.
Related: catch fire; catch on fire , but it does not address the "was" part.

A: 1, 3 and 4 are all acceptable.
1 and 3 use the past tense, 4 uses the perfect tense. The difference between 1 and 4 is the usual difference between past and perfect tense. Other questions deal with that. The "on" is optional, and is best omitted.
2 is not acceptable as it is using a passive form. The expression "catch fire" is idiomatic and "fire" is not acting like a regular object of the verb to catch. It is better to think of the expression "catch fire" as being an intransitive verbal expression. As it is intransitive you cannot use it in the passive voice. [Example: "Jack died" is correct, "Jack was died" is not correct]. It would also be unreasonable to say "Fire was caught by the building".
The expression "The building was on fire" is correct. An incorrect merging of that expression with your number 3 could form number 2. Note as the comment below mentions, the structure "X was caught on Y" is grammatically well formed.

A: If you are specifically talking about something in the past, your best bet is option one or three. They're both correct for your usage and they both mean the same thing. The preposition "on" is discretionary - you can use it or not.
In your exact sentence, I recommend omitting "on".

The abandoned building caught fire many years ago.

You do not want to use version two. It sounds a bit odd to me as a native speaker. There are probably cases where it would be acceptable but it doesn't feel natural.
Version four is perfectly fine but not in your example case. The "has" implies that the building is currently in flames and it happened recently... which, since you're talking about something that occurred many years ago, would be incorrect.

Note that it may be helpful to continue your sentence to explain what the end result was.

The abandoned building caught fire many years ago but was rescued by the local fire department.
  The abandoned building caught fire many years ago and burned to the ground.


text:
Q: Angular2 testing - Get element by Id I'm writing an Angular2 test component and i've noticed this line in the tutorials:
de = fixture.debugElement.query(By.css('h1'));

de is defined as DebugElement type.
How can I get DebugElement by id?
That may seem extremely simple but I can't find any direction in the docs.

A: You can also use by.css
de = fixture.debugElement.query(By.css('#theid'));

A:   const fixture = TestBed.createComponent(DashboardComponent);
  const compiled = fixture.debugElement.nativeElement;

*

*using id
expect(compiled.querySelector('#from').textContent).toContain('From Date');

*using css
expect(compiled.querySelector('.from').textContent).toContain('From Date');

A: You can use following syntax to get an attribute value from an HTML element:
To retrieve an HTML element:
const element = fixture.debugElement.nativeElement.querySelector('name of element'); // example a, h1, p

To get an attribute value from that element:
const attributeValue = element.attributeName // like textContent/href


text:
Q: mono obfuscator for non-window os Are there any mono obfuscation programs out there that can run on mac os x?

A: There are a couple of command line tools:

*

*NCloak

*Obfuscar (seems a bit dead)

*A derivative from Obfuscar maintained by RemObjects.

A: Eziriz .NET Obfuscator (part of their .NET Reactor tool suite) seems to work for Mono on Mac OS X.

A: Just find one that is written for the .NET platform and use that under mono.
There are many of them around (top 2 hits from Google):
http://rustemsoft.com/downloadSkater.htm
http://www.9rays.net/Category/53-spices_net_suite.aspx

A: Babel Obfuscator can run on MAC OSX and support all major platforms included Mono.
DISCLAIMER: I am the developer of Babel Obfuscator.

A: Crypto Obfuscator supports this - as long as your original assemblies can run on Mac OS X using Mono, the obfuscated assemblies till run too.
DISCLAIMER: I work for LogicNP Software, the developer of Crypto Obfuscator.


text:
Q: How to find if a 2D vector contains a duplicate row? I want an elegant way to check if
(myvector[0][1] != myvector[1][1] != myvector[2][1]) && (myvector[0][0] != myvector[1][0] != myvector[2][0])

etc..I know this isn't how you compare values with an if statement... I figured storing variables into a vector would be the fastest way to properly compare the values as there is a lot of variables that must not equal each other
Edit: Maybe I'm not being that clear, basically I want [x][0],[x][1] to never match [y][0],[y][1]...if either [0] or [1] is different, then it's fine but if ANY of the two pairings match up, then return false.
{0,0},
{1,1},
{0,1}

is ok, thus passes the duplicate test
{0,0},
{1,1},
{0,0}

failed because there is two pairs of 0,0
The reason so, is because the first row will have values between 2-14 and the second will have values between 0-3. These values represent a 52 card deck and I do not want cards to repeat

A: Use map. It will take O(N) space and O(LogN) to search an element if it is present in the map or not. map.find() helps to find element if present in the map in LogN time. In your case, the element can be a pair.
Here's a sample code:
#include <iostream>
#include <map>
using namespace std;
int main() {
    int i,j,n=3,m=2;
    for(i=0;i<n;i++)
    {
       for(j=0;j<m;j++)
            cin>>a[i][j];
    }
    map< pair<int,int>,bool>m;        // Map key can be a pair and value can be boolean
    bool unique = true;
    for(i=0;i<n;i++)
    {
        if(m.find(make_pair(a[i][0],a[i][1]))==m.end())    // if pair is not already present in array insert the element in map
            m[make_pair(a[i][0],a[i][1])]=true;
        else
        {
            unique=false;    // else pair was already present in array
            break;           // break the loop
        }
    }
    if(unique)
        cout<<"true";
    else cout<<"false";
    return 0;
}

Input:
0 0
1 1
0 1
Output:
true

Input:
0 0
1 1
0 0
Output:
false

A: Since you are representing a deck of cards, have you considered using enums with bit sets? With that, you can store a combination of cards into a single number and easily compare them. In case of large sets that exceed the precision of int (int has 32 bits), use a std::bitset<N>, where N is the number of items in the set.
#include <iostream>

enum Deck
{
    Jack =  2 << 0,
    Queen = 2 << 1,
    King  = 2 << 2,
    Ace   = 2 << 3
};

void compare_hands(const int hand1, const int hand2)
{
    if (hand1 == hand2)
        std::cout << "Same hand" << std::endl;
    else
        std::cout << "Different hand" << std::endl;
}

int main()
{
    int hand1 = Jack  | Queen;
    int hand2 = King  | Ace;
    int hand3 = Queen | Jack;

    compare_hands(hand1, hand2);
    compare_hands(hand1, hand3);
    compare_hands(hand2, hand3);

    return 0;
}

A: Here's a benchmark of a simple solution using a std::vector vs std::map (in another answer here).  You can see here that the vector solution is 6x faster(for a small data set):
http://quick-bench.com/-fOG_uDO6HRPKqOMgxqchqUXHbo
#include <iostream>
#include <algorithm>
#include <benchmark/benchmark.h>
#include <memory>
#include <vector>

constexpr int width=2;
constexpr int height=16;

static void vector(benchmark::State& state) {
    std::vector<std::vector<int>> data;

    int count = 0;
    for(int i = 0; i < height; i++) {
    data.emplace_back(std::vector<int>());
    for (int j = 0; j < width; j++) {
        data[i].push_back(count++);
    }
    }
    while (state.KeepRunning()) {

    std::vector< std::pair<int,int>>m;        // Map key can be a pair and value can be boolean
    m.reserve(height);
    bool unique = true;
    for(int i=0;i<height;i++)
        {
        if(std::find(m.begin(), m.end(), std::make_pair(data[i][0],data[i][1]))==m.end())    // if pair is not already present in array insert the element in map
            m.emplace_back(std::make_pair(data[i][0],data[i][1])); // nothing to do here
        else
            {
            unique=false;    // else pair was already present in array
            break;           // break the loop
            }
        }
    if(!unique) {
        std::cout<<"unexpected match found";
    }

    }

}
BENCHMARK(vector);

static void set(benchmark::State& state) {
    std::vector<std::vector<int>> data;

    int count = 0;
    for(int i = 0; i < height; i++) {
    data.emplace_back(std::vector<int>());
    for (int j = 0; j < width; j++) {
        data[i].push_back(count++);
    }
    }

    while (state.KeepRunning()) {

    std::map< std::pair<int,int>,bool>m;        // Map key can be a pair and value can be boolean
    bool unique = true;
    for(int i=0;i<height;i++)
        {
        if(m.find(std::make_pair(data[i][0],data[i][1]))==m.end()) {    // if pair is not already present in array insert the element in map
            m[std::make_pair(data[i][0],data[i][1])]=true;
        } else {
            unique=false;    // else pair was already present in array
            break;           // break the loop
        }
        }
    if(!unique) {
        std::cout<<"unexpected duplicate found";
    }
    }
}
BENCHMARK(set);

Changing the code to use std::unordered_map makes it even worse -- a 10x slowdown over std::vector:  http://quick-bench.com/aSKrpaW4cZoL2mYJFjy6x1dEvDo
(though I may be hashing poorly)
There may be some optimizing that could be done on the map solution, but it still won't make the map solution faster with this size data set.
The two algorithms seem to even out at around 250 pairs, but there are also further optimizations that can be done on the vector solution to make it scale better.


text:
Q: how to plot a matlab style graph with opencv in visual studio? I am trying to plot a matlab style line graph using opencv and C++.
and I also found this link https://code.google.com/p/cvplot/ about cvplot.
but still the problem remains because cvplot needs "cv.h" and "highgui.h" to work, and I dont know where to find them.
Does anyone have experience with this cvplot or other ways to plot a graph with opencv and C++?
Thanks for your help.

A: My bad I found where the problem is
I forget to include
opencv2\opencv.hpp AND
opencv2/core/core_c.h
Besides, if anyone want to use cvplot in visual studio, better add
"#define snprintf _sprintf"
or cvplot wont work