text:
Q: Inner delete query sqlite I have a database and tables of events and time table. I have linked events with time tables. Event has time table key column.  Now I want to delete a time table and when the time table gets deleted the events referenced to respective time table should get delete.  How to do this?
My current delete query is this which deletes only the table not events.
    public void deleteTable(TimeTable timeTable) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_TIME_TABLE, KEY_TIME_TABLE_ID + " = ?",
            new String[]{String.valueOf(timeTable.getId())});
    db.close();
}

Database helper
     public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String TABLE_TIME_TABLE = "timetables";
    private static final String KEY_TABLE_TITLE = "tabletitle";
    private static final String KEY_TIME_TABLE_ID = "timetableid";
    private static final String KEY_TABLE_COLOR = "tablecolor";
    private static final String KEY_STATUS = "status";

    private static final String TABLE_EVENTS = "event";
    private static final String KEY_ID = "id";
    private static final String KEY_TITLE = "title";
    private static final String KEY_START_HOURS = "starthours";
    private static final String KEY_START_MINS = "startmins";
    private static final String KEY_END_HOURS = "endhours";
    private static final String KEY_END_MINS = "endmins";

    private static final String KEY_FROM_DATE = "datefrom";
    private static final String KEY_TO_DATE = "dateto";
    private static final String KEY_LOCATION = "location";
    private static final String KEY_DAY_OF_WEEK = "dayofweek";
    private static final String KEY_NOTIFICATION_TIME = "notification";

    private static final String KEY_COLOR = "color";

    private Context context;

    public DatabaseHelper(Context context) {
        super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
        //3rd argument to be passed is CursorFactory instance
        this.context = context;
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {

        createTable(db);

    }

    public void createDatabase(){
        context.deleteDatabase(Constants.DATABASE_NAME + ".db");
        SQLiteDatabase db = this.getReadableDatabase();
    }

    public void createTable(SQLiteDatabase db){
        String CREATE_EVENTS_TABLE = "CREATE TABLE " + TABLE_EVENTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + KEY_TITLE + " TEXT,"
                + KEY_FROM_DATE + " DATE,"
                + KEY_TO_DATE + " DATE,"
                + KEY_DAY_OF_WEEK + " TEXT,"
                + KEY_LOCATION + " TEXT,"
                + KEY_NOTIFICATION_TIME + " DATE,"
                + KEY_TIME_TABLE_ID + " TEXT" + ")";

        db.execSQL(CREATE_EVENTS_TABLE);

        String CREATE_TIME_TABLE = "CREATE TABLE " + TABLE_TIME_TABLE + "("
                + KEY_TIME_TABLE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + KEY_TABLE_TITLE + " TEXT,"
                + KEY_STATUS + " TEXT,"
                + KEY_TABLE_COLOR + " TEXT" + ")";

        db.execSQL(CREATE_TIME_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_EVENTS);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_TIME_TABLE);
        context.deleteDatabase(Constants.DATABASE_NAME + ".db");

        createTable(db);

        // Create tables again
        //onCreate(db);
    }

}

I tried this inner delete query but it's not working:
  public void delete(TimeTable t,int id)
{
    SQLiteDatabase db = this.getWritableDatabase();

    db.execSQL(" DELETE FROM " + TABLE_TIME_TABLE + " WHERE " + KEY_TIME_TABLE_ID + " == " + id + " IN "

    + " ( " + " SELECT * FROM " + TABLE + " WHERE " + KEY_TIME_TABLE_ID + " == " + id + " ) ");

    db.close();

}

Can anyone help please?
Thank you..

A: there are two ways to go about this.
first option: modify your deleteTable(TimeTable timeTable) function to delete both the parent and the child records.
preferable first delete the child records (events) using the parent id then delete the parent record (time table) using the same id. here is a sample.
public void deleteTable(TimeTable timeTable) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_EVENTS, KEY_TIME_TABLE_ID + " = ?",//KEY_TIME_TABLE_ID is a foreign key
            new String[]{String.valueOf(timeTable.getId())});
    db.delete(TABLE_TIME_TABLE, KEY_TIME_TABLE_ID + " = ?",
            new String[]{String.valueOf(timeTable.getId())});
    db.close();
}

you may want to name KEY_TIME_TABLE_ID in events table as FK_TIME_TABLE_ID
make code more readable.
second option: define the foreign keys with delete cascade when creating the table (you may also alter existing table and add them).
String CREATE_EVENTS_TABLE = "CREATE TABLE " + TABLE_EVENTS + "("
        + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
        + KEY_TITLE + " TEXT,"
        + KEY_FROM_DATE + " DATE,"
        + KEY_TO_DATE + " DATE,"
        + KEY_DAY_OF_WEEK + " TEXT,"
        + KEY_LOCATION + " TEXT,"
        + KEY_NOTIFICATION_TIME + " DATE,"
        + KEY_TIME_TABLE_ID + " TEXT,"
        + " FOREIGN KEY (" + KEY_ID + ") references "
        + TABLE_TIME_TABLE + "(" + KEY_TIME_TABLE_ID + ") ON DELETE CASCADE)";

Note: sqlite does not support foreign keys by default, therefore run the following query every time you connect to the database.
PRAGMA foreign_keys = ON

this enables the foreign keys

A: Delete the events having a reference to the timetable entry you're going to delete. Something like that:
DELETE FROM EVENTS WHERE TIMETABLE_ID=...


text:
Q: how to show full showModalBottomSheet when open keyboard I used isScrollControlled: true and SingleChildScrollView widget..when open keyboard how to open full sheet?
  onPressed: () {
                              showModalBottomSheet(
                                  context: context,
                                  builder: (BuildContext context) {
                                    return BottomSheet(
                                        camera: camera,
                                      subPost: widget.subPost
                                    );
                                  },isScrollControlled: true);
                            },

BottomSheet class
class _BottomSheetState extends State<BottomSheet> {

  @override
  Widget build(BuildContext context) {
    return
      SingleChildScrollView(
      child:
      Container(
        child: Padding(
          padding:
          EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
          child: Column(

My output

I need like this

A:
your screen is not scrolling, because your bottom sheet is not
scrollable.

Try below code :
 showModalBottomSheet(
      context: context,
      isScrollControlled: true,
...

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to highlight a particular data point in MP android Line chart? I am having a list view with data points in it. Now, what I want is to highlight the data point on the graph when I clicked on a particular data point in the List view. I want to increase the size of the data point circle and change its color.
  mChart.removeAllViews();
    mChart.setOnChartGestureListener(this);
    mChart.setOnChartValueSelectedListener(this);
    mChart.setDrawGridBackground(false);
    setData();
    mChart.setTouchEnabled(true);
    mChart.getAxisLeft().setDrawGridLines(false);
    mChart.getXAxis().setDrawGridLines(false);
    mChart.setDragEnabled(false);
    mChart.setScaleEnabled(false);
    mChart.getAxisLeft().setDrawLimitLinesBehindData(true);

    final XAxis xAxis = mChart.getXAxis();
    xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
    xAxis.setLabelRotationAngle(270);
    xAxis.setAxisLineWidth(3);
    xAxis.setTextSize(12f);
    xAxis.setTextColor(Color.WHITE);
  //  xAxis.setGranularity(0f);
    xAxis.setLabelCount(xAxisStringValues.length,true);

    xAxis.setValueFormatter(new IAxisValueFormatter() {
        @Override
        public String getFormattedValue(float value, AxisBase axis) {
                if (value > 0 || value < readingDateGlucose.length)
                {
                        return xAxisStringValues[(int) value];
                }
            return "-";
        }

        @Override
        public int getDecimalDigits() {
            return 0;
        }
    });

    YAxis leftAxis = mChart.getAxisLeft();
    leftAxis.removeAllLimitLines();
    leftAxis.setAxisLineWidth(3);
    leftAxis.setDrawAxisLine(false);
    leftAxis.setDrawGridLines(true);
    leftAxis.setTextSize(12f);
    leftAxis.setValueFormatter(new IAxisValueFormatter() {
        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            return "" + ((int) value);
        }

        @Override
        public int getDecimalDigits() {
            return 0;
        }
    });
    leftAxis.setTextColor(Color.WHITE);
    leftAxis.setDrawZeroLine(false);
    leftAxis.setDrawLimitLinesBehindData(false);
    mChart.getAxisRight().setEnabled(false);
    mChart.setAutoScaleMinMaxEnabled(true);
    mChart.getLegend().setEnabled(false);
    mChart.getDescription().setEnabled(false);
    mChart.animateX(2500, Easing.EasingOption.EaseInOutQuart);

    mChart.invalidate();

This is how, I am drawing my chart.And, I have used MP Android v3.0.0 library. I have seen this link already, but not able to understand from it:circular highlighted data points
this is how I have implemented my on click listner final AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {
                listPosition = position;
            }
        };
And this is how I am creating my data set ` set1 = new LineDataSet(yVals, "");
    set1.setFillColor(Color.TRANSPARENT);
    set1.setColor(Color.RED);
    set1.setCircleColor(Color.BLUE);
    set1.setLineWidth(2f);
    set1.setValueTextColor(Color.WHITE);
    set1.setValueTextSize(10f);
    set1.setCircleRadius(2f);
    set1.setDrawCircleHole(false);
    set1.setHighlightEnabled(true);
    set1.setDrawValues(false);
    set1.setDrawFilled(true);
    ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
    dataSets.add(set1);
    LineData data = new LineData(dataSets);
    mChart.setData(data);`

A: Design an icon which you want to display instead of circle. Place that icon in drawable folder of you project. Get your specific value on which you want to display your icon as:
set1.getEntryForIndex(index).setIcon(getDrawable(R.drawable.icon));

After that replace index with your entry index for example for first entry use 0. Also replace icon with your icon name in drawables.


text:
Q: $(18B^2/(A^2-9B^2)) - (A/A+3B) + 2$ Simplify:
$$ \frac{18B²}{A²-9B²} - \frac{A}{A+3B} + 2$$
If the notation doesn't work like I wrote it above it's; Simplify: 18B^2/A^2-9B^2 - A/A+3B + 2.

*

*I made denominator common by expanding A²-9B²: (A+3B)(A-3B)
So the A after the minus should be still multiplied by (A-3B)
This gave me: A²-3AB.

*Then I put common factors together but left out the +2. This is where I probably go wrong. Without the 2 I expanded:(18B^2-a^2+3ab) to (6B-A)(3B+A). The denominator was (3B-A)(3B+A). I cancelled out (3B+A) on both sides. I was left with: 6b-a/3b-a +2

*I made it smaller to = 2+ 2b-a/b-a
None of this seems correct. I first added 2 to the end. I then tried to add 4/2 earlier. That made my final answer: 6B-A+4/3B-A+2 = 2B-A+4/B-A+2. I also tried times 4/2. That also did not give me the correct answer and didn't seem logical. Perhaps I shouldn't have cancelled out? But I wouldn't know why. What am I doing wrong?

A: $$\frac{18b^2}{a^2-9b^2}+2=\frac{2a^2}{a^2-9b^2}$$
As $a^2-9b^2=(a)^2-(3b)^2=(a+3b)(a-3b),$
$$\frac{18b^2}{a^2-9b^2}+2-\frac a{a+3b}=\frac{2a^2}{a^2-9b^2}-\frac a{a+3b}$$
$$=a\left(\frac{2a}{a^2-9b^2}-\frac1{a+3b}\right)$$
$$=a\cdot\frac{2a-(a-3b)}{(a+3b)(a-3b)}=a\cdot\frac1{a-3b}$$ assuming  $a+3b\ne0$

A: You made a small mistake in step 2 and a bigger mistake in step 3.  The small mistake is that the denominator is not $(3B-A)(3B+A)$, but $(A-3B)(A+3B)$ -- in other words, you're off by a minus sign.  So at the end of step 2 you should have
$${6b-a\over a-3b}+2$$
The bigger mistake is thinking you can cancel the $3$ with the $6$, turning this into ${2b-a\over a-b}+2$.  Instead you should change the $2$ into a fraction the denominator $a-3b$:
$${6b-a\over a-3b}+2={6b-a\over a-3b}+{2(a-3b)\over a-3b}={6b-a+2a-6b\over a-3b}={a\over a-3b}$$
BTW, in calling the mistakes "small" and "bigger," I just mean that the sign error in step 2 struck me as very likely an oversight -- it's easy to get things turned around when factoring expressions -- but the cancellation error in step 3 struck me as possibly a more serious conceptional misunderstanding.


text:
Q: Firebase FCM http v1 icon not showing in browser I'm following this tutorial, so far I have notifications working for web browsers (tested in chrome)
But I don't know how to send the icon via payload, so far what I've done is send the body of the request as follows (I'm using firebase cloud functions):
{
    'message': {
     token,
     'notification': {
         title,
         body,
         icon // <-- added the icon
         }
    }
}

if I try to add the icon in the message payload I get a bad request when I do the post to the google FCM URL.
it works without adding the icon property to the payload, obviously, that's the error, the question again is how to send the icon in the payload to work.
thanks
EDIT, I'm posting my post function:
async function notification(messageBody) {
    const api = 'https://fcm.googleapis.com/v1/projects/{projectID}/messages:send';
    const accessToken = await getAccessToken();
    const response = await fetch(api, {
        headers: {
            'Accept': 'application/json',
            'Content-type': 'application/json',
            'Authorization': `Bearer ${accessToken}`
        },
        method: 'POST',
        body: messageBody
    });
    return response;
}

A: Try:
{
  "message": {
    "token" : token,
    "notification": {
      "title": title,
      "body": body
    },
    "webpush": {
      "headers": {
        "Urgency": "high"
      },
      "notification": {
        "body": body,
        "requireInteraction": "true",
        "icon": icon
      }
    }
  }
}


text:
Q: Datatable Nested table I'm trying to do a master-detail with datatable, but the responsive detail table is not working. and the detail is as if it were another row, but what I want is to be a separate table, to be able to do things with it.
This is my code
HTML

            Puesto de observación
            Fecha
            Observador
            Boton floral
            Floracion
            Maduracion
            Fructificacion
            Valoración
            Rendimiento
            Enfermedades
            Plagas

JAVASCRIPT
var  ListaControlCacao = $('#ListaControlCacao').DataTable({
    "ajax": "/PuestoObservacionCacao/ListaPuestoObservacionCacaoxUsuario",
     //"lengthMenu": [[10, 20, 30, -1], [10, 20, 30, "All"]],
    dom: 'rtip',
    select: 'single',
    rowId: 'Id',
    deferRender: true,
    responsive: true,
    language: LenguajeDataTable,
    "columns": [
        {
            "Width": 2,
            "orderable": false,
            "data": null,
            "defaultContent": ''
        },
        { "data": "PuestoObservacionCacao" },
            { "data": "Fecha" },
            { "data": "Observador" },
            { "data": "BotonFloral" },
            { "data": "Floracion" },
            { "data": "Maduracion" },
            { "data": "Fructificacion" },
            { "data": "Valoracion" },
            { "data": "Rendimiento" },
            { "data": "Enfermedades" },
            { "data": "Plagas" }
    ]
});

$('#ListaControlCacao tbody').on('click', 'td', function () {

    if ($(this).index() == 0) {
        return;
    }

    var tr = $(this).closest('tr');
    var row = ListaControlCacao.row(tr);

    if (row.child.isShown()) {
        // This row is already open - close it
        row.child.hide();
        tr.removeClass('shown');
    }
    else {
        // Open this row

        row.child(format()).show();
        tr.addClass('shown');

        var xyz =  $('#ListaDetalleControlCacao').DataTable({

            "bServerSide": true,
            "sAjaxSource": "/Cacao/ListarControlCacao3?IdPuestoObservacion=" + row.data().Id,
            "bProcessing": true,
            "pageLength": 10,
            //"lengthMenu": [[10, 20, 30, -1], [10, 20, 30, "All"]],
            dom: 'rtip',
            select: 'single',
            rowId: 'Id',
            deferRender: true,
            "responsive": true,
            buttons: [
                {
                    extend: 'colvis',
                    columns: ':not(:first-child)'
                },
                'copy',
                'csv',
                'excel',
                'pdf',
                'print'
            ],

            language: LenguajeDataTable,
            "aoColumns": [
                {
                    "sName": "Id",
                    "bSearchable": true,
                    "bSortable": true
                },
                { "sName": "Fecha" },
                { "sName": "Observador" },
                {
                    "sName": "BotonFloral",
                    "sWidth": 2
                },
                {
                    "sName": "Floracion",
                    "sWidth": 2
                },
                {
                    "sName": "Maduracion",
                    "sWidth": 2
                },
                {
                    "sName": "Fructificacion",
                    "sWidth": 2
                },
                { "sName": "ValoracionCultivo" },
                { "sName": "RendimientoCultivo" },
                { "sName": "Enfermedades" },
                { "sName": "Plagas" }
            ]
        });
    }
});

function format() {
    return '

No.	Fecha	Observador	Boton Floral	Floracion	Maduracion	Fructificacion	Valoracion	Rendimiento	Enfermedades	Plagas

';
}

And that's how it looks:


text:
Q: How do I print the name of generic classes in c#? Is there a simple way to obtain the name of a class in c# including template parameters?
I.E
Print( new List<int>{ 100, 1001});

Produce one of the following outputs:
List<int>
List<Int32>
System.Collections.Generics.List<System.Int32>

one of the first 2 is preferrable, but Type.FullName is not a viable option. It is ways too verbose.
Too verbose result that is unwanted.
System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=235hosehoue5h]]

Note I'm asking just for a shortcut if it exists. I'm no asking for a full implementation of such feature.

A: Create a method to get the class Name.

*

*there is a property in Type class Type.IsGenericType, which mean this type whether is genericType.

*use Type.GenericTypeArguments to get all arguments of the generic type the use linq to combine them by ,.

*If the class is generic contain generic you can use function recursively to get the name. Thanks for @Eric Lippert point out.

look like this.
public static class ExtensionLib {
    public static string GetClassName(this Type objType)
    {

        string result = objType.Name;
        if (objType.IsGenericType)
        {
            var name = objType.Name.Substring(0, objType.Name.IndexOf('`'));
            var genericTypes = objType.GenericTypeArguments;
            result = $"{name}<{string.Join(",", genericTypes.Select(GetClassName))}>";
        }
        return result;
    }
}

c# online
Input
Console.WriteLine(typeof(List<int>).GetClassName());
Console.WriteLine(typeof(List<List<int>>).GetClassName());
Console.WriteLine(typeof(Dictionary<List<int>,string>).GetClassName());

Result
List<Int32>
List<List<Int32>>
Dictionary<List<Int32>,String>


text:
Q: pip: install package at version that don't bump versions of other packages I know that project uses django == 1.3. Stacktrace shown that I miss package django-photologue. Command
pip install django-photologue

download django == 1.7. How to dump requirement for all possible version of selected package or ever better - dump only that have additional constraint for it dependencies?
I get project that have no requirements.txt file so try recreate working environment.

A: Currently I end with:
pip install -v --no-deps --no-install django-photologue

which dump version as list:
Downloading/unpacking django-photologue
  Using version 3.1.1 (newest of versions: 3.1.1, 3.1, 3.0.2, 3.0.1, 3.0, 2.8.3, 2.8.2, 2.8.1, 2.8, 2.7, 2.6.1, 2.6, 2.5, 2.4, 2.3)

I can manually install each versions and check dependencies.
Another way investigate URLs in:
https://pypi.python.org/pypi/django-photologue/json


text:
Q: JQuery ToolTip: How to have 2 different styles? I have the jquery-tooltip from here:
http://flowplayer.org/tools/tooltip/index.html
Not I have this code:
.tooltip
{
display:none;
background:transparent url(/Images/Design/Tooltip/black_arrow.png);
font-size:12px;
height:70px;
width:160px;
padding:25px;
color:#fff;
}

<asp:Image runat="server" CssClass="Tooltip" Title="Tragen Sie bitte hier Ihre Branche ein - z.B. Friseur, Anwalt, KFZ Werkstatt..." ID="imgHelp1" ImageUrl="~/Images/Design/Icons/question1.gif"
                            Height="15" />

 <asp:Image runat="server" CssClass="Tooltip" Title="Tragen Sie hier bitte 'Suchworte' ein mit denen Sie gefunden werden möchten. Z.B.
                                    wenn Sie ein Friseur sind: Haare schneiden, Haare färben, Ihren Firmennamen..." ID="imgHelp2" ImageUrl="~/Images/Design/Icons/question1.gif"
                            Height="15" />

$('.Tooltip').tooltip();

For the first image, the tooltip-height or 70px is perfect.
For the second image, the tooltip-height must be at least 100px.
But how do that? How can I have 2 different styles of the tooltip itself or give the tooltip a classname within or such like these?

A: Answer is:
name: tipClass
Default: 'tooltip'
Since 1.2.0. CSS class name for the generated tooltip element.


text:
Q: Creating 20 million records in Core Data from CSV - macOS I am building a database from a large CSV (4GB) to work on locally for myself, this will not be a production app. I will only have one model / entity to begin with that contains 8-9 attributes that are mostly strings and a handful of Int's. I will have around 20 million records to store. I will only write the database from this CSV once and from then it will receive incremental updates to add or amend roughly 50,000 records per month. I will be querying the database fairly frequently but only as a single user.
Is Core Data the correct choice for this scenario? I understand that it is an object graph and not just a database, I have a 16GB ram iMac and a 8GB Macbook pro and I am unsure how much of a memory constraint this may be while using Core Data. I am trying to figure out if I would be better off using SQLite or if Core Data is the correct tool for the job.
If Core Data is a good choice for this use case then I could use some help on structuring the creation of records without constraining myself on ram. As far as I  understand I should write entities to a child context and when I am ready to copy to disk I will pass the data from the child context to its parent context (memory to memory) and then the parent can write/flush to disk.
This is how I would visualise the process, I will only use one attribute on an entity the example.
DispatchQueue.global(qos: .background).async { //Non blocking
    //iterate line by line over csv reader never exceeds 9.1MB takes 30 mins. I will look into chunking to better utilise multithreading later.
    for (index, row) in reader.enumerated()  {
        let person = Person(entity: personEntity, insertInto: backgroundContext)
        person.setValue(row[0], forKey: "name")

        //When I hit x iterations or x seconds since last save - save to disk and clear the ram for the context
        backgroundContext.perform {
            do {
                try backgroundContext.save() //I beleive pushes changes only to its parent context?
               //Clear background context ram (of stored records)

               // Main context should now write to disk and then it should also clear its ram
              //do {
                  //main context work
             //} catch {

             //}
            } catch {
                //error handling
            }
        }
    }
}

I have a couple of concerns which stem from me not clearly understanding the Core Data structure.
1)  After saving to persistent storage from the main context I want to make sure the main context can flush those records from ram. I don't want to clear all records in ram as the main context may have been written to from the background context while the main context was writing to disk (effectively data loss).
2) Similar to point 1, when the background context saves I want to make sure the background context only clears records from ram that were saved to its parent context.
If anyone can shed some light on the situation or provide some examples of correct structure it would be much appreciated.
Thanks,

A: I think that reset() function of NSManagedObjectContext class is what you are looking for.
But I really think that you are using CoreData in a wrong, I would propose you to init CoreData with prepared .sqlite file (created from CSV). It will work better and much faster than creating instances of NSManagedObject and saving them to the context manually.


text:
Q: Is there any recommended strategy to run gridsearchcv on a huge data set? I am trying to evaluate svm on a huge dataset of size ~.3 million records. This is a multiclass problem with 23 features. Currently gridsearchcv takes ages to iterate parameters. Is there any strategy to speed this up? I guess .3 million records is a reasonable number and I am perplexed that the CPU usage doesn't go beyond 30% and RAM usage is limited to 50 %.
I had the n_jobs set to -1 and pre_dispatch=1 as suggested in documentation. Nothing changes. With my inputs I am expecting a total of 24 iterations. Here is my sample code
from sklearn.multiclass import OneVsRestClassifier
from sklearn.grid_search import GridSearchCV
from sklearn import svm
model_to_set = OneVsRestClassifier(svm.SVC())

parameters = {
    "estimator__C": [1,2,4,8],
    "estimator__kernel": ["poly","rbf","linear"],
    "estimator__degree":[1, 2, 3, 4],
}

model_tunning = GridSearchCV(model_to_set, param_grid=parameters,n_jobs=-1,pre_dispatch=1,
                             scoring='f1')

model_tunning.fit(mat[1:23], mat[0])

Appreciate any help.


text:
Q: Adding a new property to all actions in NGRX Is it possible to add new properties to an action with an action creator function that is reusable?
Actions in NGRX have the type property. I want to extend Actions to add a new property (Called customType) to all of my actions throughout my project. Basically I want to be able to listen in an effect for all actions that then have that property (Let's say action.customType === 'HTTP') with the idea to be able to have a single feature module that can keep track of the loading & error state of HTTP calls that is tied back to the action.
With goal to essentially be able to do this in a component:
this.store.dispatch(action.loadObject());
this.isLoading$ = this.store(httpSelectors.isLoading).pipe(x => x(action.loadObject))

A: I think you should/can use ActionsSubject, with it you will be able to listen to all actions.
constructor(
    private actions$: ActionsSubject
) {}

ngOnInit() {
    this.actions$.pipe(
        filter(action => action.customType === 'errorOrSomethingElse')
    ).subscribe(action => console.log(action));
}


text:
Q: Interface Builder UIButton inside of UITextView I want to build an interface that has scrolling text inside a UITextView, and a basic round rect button at the end of the text. The placement of the button will be dynamic, depending on the length of the text in the textView My view hierarchy is like this:

*

*View Controller

*

*Text View (UITextView)

When I try to add a Round Rect Button to the textView in Interface Builder, it replaces it. Is it correct to add a UIButton as a subview of the UITextView, or should I be doing something else?

A: I would take a slightly different approach.

*

*View Controller

*

*UIView (The holder)

*

*Text View (subview index 0)

*UIButton (subview index 1)

then set the buttons position to whatever you need based on the text fields width still.


text:
Q: Line up two blocks and avoid they stand on one another I have been trying for a while now to make those two blocks stand aside one another on the same line in vain!
Can you help me enlight this out
here http://jsfiddle.net/9UxZ8/2/

Hello,how are you

John Jogn

Kings and Queens

I truly believe that you are a cleaver person, but please remain quiet.

div#gros
{
color:red;
width:350px;
font-size:30px;
display: inline-block;
vertical-align:top;
}

div.bookinfo {
vertical-align:top;
display: inline-block;
width: 300px;
vertical-align:top;

}

A: Updated fiddle
While you had the right idea in theory (except the duplicate vertical-align:top), you're missing the important fact that the elements to be put side-by-side are .bookinfo and .chapter, NOT .bookinfo and #gros.

A: In your markup there are two parent div which are .bookInfo and .chapter. So I am assuming you want to put them aside one another. So for that
Add display:inline-block to .chapter
.chapter
{
    display: inline-block;
}

Js Fiddle Demo


text:
Q: POST Ajax запрос не работает Вроде всё делаю верно, но при нажатии на кнопку ничего не происходит. Приём ПОСТА стоит, но его нет смысла писать.
<script type="text/javascript">
function send()
{
var be = $('#be').val();
var pe = $('#pe').val();
   $.ajax({
            type: "POST",
            url: "/?page=send",
            data: "be="+be+"&pe="+pe,
            }
    });

}
</script>

<form action="">
<input id="be" type="text" name="be">
<input id="pe" type="hidden" name="pe" value="1">
</form>

 <input type="button" onclick="send();" value="Отправить" />

A: <form action="/?page=send" method="post" id="myform">
    <input id="be" type="text" name="be" />
    <input id="pe" type="hidden" name="pe" value="1" />
    <input type="button" value="Отправить" />
</form>

<script type="text/javascript">//<[!CDATA[
$(document).ready(function(){
    $('#myform').on('submit', function(e){
        var _self = $(this);
       $.ajax({
            type: _self.attr('method'),
            url: _self.attr('action'),
            data: _self.serialize(),
            success: function(data){
                console.log(data);
            }
        });
        e.preventDefault();
    });
});
//]]></script>


text:
Q: removing text after last \ I've been trying to do some perl regex's and have hit the wall.
I'm trying to do some data analysis of a log file and I'm running into the following problem:
I have a file, test.csv, that is comprised of multiple single line entries from another program that produces the following layout format:

*

*d:\snow\dir.txt

*d:\snow\history\dir.tff

*d:\snow\history\help.jar

*d:\winter\show\help.txt

*d:\summer\beach\ocean\swimming.txt

What I want would like to do is delete the file names from the path listing, so the resulting file would contain:

*

*d:\snow\

*d:\snow\history\

*d:\snow\history\

*d:\winter\show\

*d:\summer\beach\ocean\

I've banged my head against the wall on this one and have tried various perl regex's in an attempt to drop the file names out without much luck.  Since the paths to the directories are of varying length, I'm hitting a wall, I'm not sure if this is something that I can do within perl or python.

A: You can do this with one line in Perl:
perl -pe 's/[^\\]+$/\n/' <infile.txt >outfile.txt

Taking this in pieces:
-p causes Perl to wrap the statement (supplied with -e) in a while loop, apply the statement to each line of the input file, and print the result.
-e gives Perl a statement to run against every line.
s/[^\\]+$/\n/ is a substitution statement that uses a regular expression to change any sequence of characters not including a backslash at the end of the line, to just a newline \n.
[^\\] is a regular expression that matches any single character that is not a backslash
[^\\]+ is a regular expression that matches one or more characters that are not a backslash
[^\\]+$ is a regular expression that matches one or more characters that are not a backslash followed by the end of the line

A: Using regexes might work, but using a module designed for this purpose is generally speaking a better idea. File::Basename or File::Spec are suitable core modules for this purpose:
Code:
use strict;
use warnings;
use v5.10;

use File::Basename;

say dirname($_) for <DATA>;

__DATA__
d:\snow\dir.txt
d:\snow\history\dir.tff
d:\snow\history\help.jar
d:\winter\show\help.txt
d:\summer\beach\ocean\swimming.txt

Output:
d:\snow
d:\snow\history
d:\snow\history
d:\winter\show
d:\summer\beach\ocean

Of course, if you want ending backslashes, you'll have to add them.
And for File::Spec:
my ($volume, $dir, $file) = File::Spec->splitpath($path);
my $wanted_path = $volume . $dir;  # what you want

These two modules have been part of the core distribution for a long time, which is a nice benefit.

A: You can do with this one liner also
perl -pe s /\\\\\w+\.\w+$// test.csv > Output.txt

\w+\.\w+$ matches for the filename with the extension which is at the end of the path

A: Here's one way to do it in Python:
python -c 'import sys,re;[sys.stdout.write(re.sub("[^\\\]+$","\n",l))for l in sys.stdin]' < in.txt > out.txt

I'll admit it's a bit more verbose than a Perl solution.


text:
Q: Подскажите пожалуйста как мне достать объекты из JSON(при помощи JSONObject или Array) на Java? и сохранить в базу Хочу достать объекты из Json weatherbit api , выдает ошибки о ненайденных элементах
String weatherappi = "weatherbit.io";
    RequestEntity<?> request = RequestEntity.get(url).accept(MediaType.APPLICATION_JSON).build();
    ResponseEntity<T> exchange = this.restTemplate.exchange(request, responseType);
    JSONObject obj = new JSONObject(exchange.getBody());
    //db save logic
    WeatherEntity weatherEntity = new WeatherEntity();
    JSONArray jsonArray = obj.getJSONArray("data");
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject obj1 = jsonArray.getJSONObject(i);

        String strdate = obj1.getString("ob_time");
        Date date = new SimpleDateFormat("yyyy-MM-dd hh:mm").parse(strdate);
        weatherEntity.setTimestamp(date.toInstant());
        weatherEntity.setCity(obj1.getString("city_name"));
        weatherEntity.setTemperature(obj1.optInt("temp"));
    }

Сам Json
{
"data": [
    {
        "rh": 45,
        "pod": "d",
        "lon": 37.61556,
        "pres": 978.78,
        "timezone": "Europe/Moscow",
        "ob_time": "2020-04-25 12:17",
        "country_code": "RU",
        "clouds": 97,
        "ts": 1587817073,
        "solar_rad": 160.383,
        "state_code": "48",
        "city_name": "Moscow",
        "wind_spd": 2.11647,
        "last_ob_time": "2020-04-25T11:30:00",
        "wind_cdir_full": "west",
        "wind_cdir": "W",
        "slp": 996.168,
        "vis": 24.135,
        "h_angle": 33.8,
        "sunset": "16:58",
        "dni": 783.56,
        "dewpt": -2.2,
        "snow": 0,
        "uv": 1.16599,
        "precip": 2.21053,
        "wind_dir": 274,
        "sunrise": "01:57",
        "ghi": 495.34,
        "dhi": 94.33,
        "aqi": 31,
        "lat": 55.75222,
        "weather": {
            "icon": "r01d",
            "code": "500",
            "description": "Light rain"
        },
        "datetime": "2020-04-25:12",
        "temp": 9.2,
        "station": "UUEE",
        "elev_angle": 38.44,
        "app_temp": 9.2
    }
],
"count": 1

}


text:
Q: jQuery if else statements and data() I've been struggling over this for almost 5 hours and finally I've got a clue.
Here's a code that I'm using on my website:
jQuery(document).ready(function(){
    jQuery(".thumbnail").bind("click",function(){
    var elem = jQuery(this);
        if((elem).data('test')) {
            alert('data is test');
            elem.data('test',false);
        }
        else {
            alert('data is not test');
            elem.data('test',true);
        }
    });
});

Here's jfiddle.
http://jsfiddle.net/Fe678/
When you click on "thumbnail" it should fire one alert (either "data is test" or "data is not test").
When I try the same exact code on my WordPress page (localhost) it shows TWO alerts one after another - "data is not set" and then "data is set" - what may cause this strange behavior?
Unfortunately I can't provide the source. I'm hoping this is something common and maybe some jQuery wizard will know the answer? Somehow...?

A: I don't think it's a jQuery bug, but one of the following:

*

*Your WordPress templates eventually cause the code to be included twice. To debug this, put an alert before the call to .bind() and verify you see it only once.

*For some reason in your WordPress version you actually have two overlapping '.thumbnail' class objects, and "click" triggers both of them. If you wrap one of your thumbnails on jsfiddle with extra <DIV class=thumbnail> you will see how this happens. To debug this, put in an alert box that shows the object on which the method is being called and verify that you don't have two separate objects there.


text:
Q: añadir contenido a un json anidado (sin que sea al final) en python tengo este json :
{
      "listaUsers": {
        "test": {
          "Nombre": "nombretest",
          "Apellidos": "apellidotest",
          "password": "test"
        },
        "test2": {
          "Nombre": "nombretest2",
          "Apellidos": "apellidotest2",
          "password": "test2"
        }
      },

      "otralista": {
        "clave": "valor"
      }
}

podria de algun modo añadir objetos json dentro de listaUsers ?

A: Inicialmente tal vez deberias replantear la estructura del JSON. Existen dos llaves en la jerarquía más alta de la estructura que son listaUsers y otralista, como su nombre específican, son listas y su representación más cercana en el formato JSON es un Array. Corrigiendo lo anterior la correcta representación sería:
{
      "listaUsers": [
        "test": {
          "Nombre": "nombretest",
          "Apellidos": "apellidotest",
          "password": "test"
        },
        "test2": {
          "Nombre": "nombretest2",
          "Apellidos": "apellidotest2",
          "password": "test2"
        }
      ],

      "otraLista": [
        "clave": "valor"
      ]
}

Siguiendo con esa lógica y pensando en que ya tienes esa estructura en forma de diccionario en python, la forma de agregar un nuevo usuario es a través de:
# Cards el JSON en el json_dict a través de json.loads, json.load o alguna otra alternativa
# ...
json_dict['listaUsers'].append(nuevoUsuario)


text:
Q: Android return value from processFinish in AsyncTask in this below code i want to pass data from processFinish method to use that in outside class but i can not fix problem and i can not return value from processFinish in call function.
public class WSDLHelper  implements AsyncResponse{
    public SoapObject request;

    private String MainResult;

    public String call(SoapObject rq){

        new ProcessTask(rq, this).execute();
        return MainResult;
    }

    @Override
    public void processFinish(String output) {
        MainResult = output;
    }
}

class ProcessTask extends AsyncTask<Void, Void,  String> {
    public AsyncResponse delegate=null;

    SoapObject req1;

    public ProcessTask(SoapObject rq, AsyncResponse delegate) {
        req1 = rq;
        this.delegate = delegate;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(Void... params) {

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.setOutputSoapObject(this.req1);

        AndroidHttpTransport transport = new AndroidHttpTransport(Strings.URL_TSMS);
        transport.debug = true;

        String result = null;
        try {
            transport.call(Strings.URL_TSMS + this.req1.getName(), envelope);
            result = envelope.getResponse().toString();
        } catch (IOException ex) {
            Log.e("" , ex.getMessage());
        } catch (XmlPullParserException ex) {
            Log.e("" , ex.getMessage());
        }

        if (result.equals(String.valueOf(Integers.CODE_USER_PASS_FALSE))) {
            try {
                throw new TException(PublicErrorList.USERNAME_PASSWORD_ERROR);
            } catch (TException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    protected void onPostExecute(String result) {
        delegate.processFinish(result);
    }
}

please help me to develop call method to return output value to outside class. thanks

A: There you are implementing AsyncResponce.
so
Replace
new ProcessTask(rq, new AsyncResponse() {
            @Override
            public void processFinish(String output) {
                MainResult = output;
            }
        }).execute();

By
new ProcessTask(rq, this).execute();

Then your class overrided method processFinish(String output) will call.
And use your value at processFinish() rather than value retured by call( ) method.

A: ProcessTask is an async task, so when u invoke callmethod, u will get null when return MainResult, becz it has not been set by processFinishmethod yet.


text:
Q: How to load json into my angular page with ng-include? If I run app.html my json loads ok, but if I run projects.html who is in other directory I cannot run my json.
I hope be clear.
SITE STRUCTURE:
**SITE**
  app/
    app.html
    todos.json
    app.js
    content-projects.html
  projects.html

app.html
<!doctype html>

  <meta charset="utf-8">
  <title>Todos $http</title>
  <link rel="stylesheet" href="style.css">

      {{todo.text}} - {{todo.done}}

app.js
var App = angular.module('App', []);

App.controller('TodoCtrl', function($scope, $http) {
  $http.get('todos.json')
       .then(function(res){
          $scope.todos = res.data;
        });
});

todos.json
[{ "text":"learn angular", "done":true },
 { "text":"build an angular app", "done":false},
 { "text":"something", "done":false },
 { "text":"another todo", "done":true }]

this will run well and load the json if I run app.html
but if I run projects.html I cannot get the json, someone know what I am doing wrong?
projects.html
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="">
  <meta name="author" content="">
  <title></title>

  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-T8Gy5hrqNKT+hzMclPo118YTQO6cYprQmhrYwIiQ/3axmI1hQomh7Ud2hPOy8SP1" crossorigin="anonymous">

content-projects.html

      {{todo.text}} - {{todo.done}}

A: 1)You're not using function annotation so ng-strict-di fails. Try to delete this.
2)When you call app.js the file route change. Try to put a relative path.
var App = angular.module('App', []);

App.controller('TodoCtrl', function($scope, $http) {
  $http.get('[approot]/app/todos.json')
       .then(function(res){
          $scope.todos = res.data;
        });
});


text:
Q: Button interaction in a DataGrid column template In a C# WPF program I have a grid that I have successfully populated with my data. One column has a button that I want to link to an edit page. The code is below.
var col = new DataGridTemplateColumn();
col.Header = "Edit";
var template = new DataTemplate();
var textBlockFactory = new FrameworkElementFactory(typeof(Button));
textBlockFactory.SetBinding(Button.ContentProperty, new System.Windows.Data.Binding("rumId"));
textBlockFactory.SetBinding(Button.NameProperty, new System.Windows.Data.Binding("rumId"));
textBlockFactory.AddHandler( Button.ClickEvent, new RoutedEventHandler((o, e) => System.Windows.MessageBox.Show("TEST")));
template.VisualTree = textBlockFactory;
col.CellTemplate = template;
template = new System.Windows.DataTemplate();
var comboBoxFactory = new FrameworkElementFactory(typeof(Button));
template.VisualTree = comboBoxFactory;
col.CellEditingTemplate = template;
dgData.Columns.Add(col);

The code successfully runs and I get a message box every time I choose a button.
How can I get this to call another method and then retrieve from this the row number of the button that I chose?
The subsequent method would look something like, how can I call it?
void ButtonClick(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("hi Edit Click 1");
// get the data from the row
string s = myRumList.getRumById(rumid).getNotes();
// do something with s
}

A: Just bind the Id, or better yet the entire data object, as the CommandParameter
void ButtonClick(object sender, MouseButtonEventArgs e)
{
    MessageBox.Show("hi Edit Click 1");

    Button b = sender as Button;

    // Get either the ID of the record, or the actual record to edit
    // from b.CommandParameter and do something with it
}

This will also work if you decide to switch your application so it uses the MVVM design pattern. For example, the XAML would look like this:
<Button Command="{Binding EditCommand}"
        CommandParameter="{Binding }" />

A: What I understand is that you need to have the rumId of the clicked Text block in order to edit it.
While setting the Click event you can do the following.
textBlockFactory.AddHandler( Button.ClickEvent,
     new RoutedEventHandler((o, e) =>
      {
         var thisTextBlock = (TextBlock) o; // casting the sender as TextBlock
         var rumID = int.Parse(thisTextBlock.Name); // since you bind the name of the text block to rumID
         Edit(rumID); // this method where you can do the editting
      }));


text:
Q: Set Android Dialog location I would like my Android Dialogs and/or Alerts to be aligned at the very top of the screen sometimes and not simply in the center. Is this possible? How about giving exact x-y coordinates, is that possible?

A: Check this out:
Positioning a dialog on screen
Transparent Dialog Alignment
This one should give you an idea:
How to change the positioning of a progress dialog?


text:
Q: Python Return case insensitive string from a list, if it contains case insensitive substring How can I return case insensitive string from a list, if it contains case insensitive substring? The returned string should be case insensitive
I was able to return string from the list, but I'm using the lowercase method. I would like to return it to its original state without modifying
entriesList = ['CSS', 'Django', 'Git', 'HTML', 'Python']

substring = "g"

def substringSearch(substring, entriesList):
  return [string for string in (string.casefold() for string in entriesList) if substring in string]

print(substringSearch(substring, entriesList))

Result:
['django', 'git']

What I would like to get:
['Django', 'Git']

A: You can just use the lower() or casefold() in the test in comprehension.
[string for string in entriesList if substring in string.casefold()]

You don't need to make a new generator for this. That will give you:
entriesList = ['CSS', 'Django', 'Git', 'HTML', 'Python']

substring = "g"

def substringSearch(substring, entriesList):
      return [string for string in entriesList if substring in string.casefold()]

print(substringSearch(substring, entriesList))

# ['Django', 'Git']


text:
Q: Error in crate.io SQL nested select I am performing this query from the crate.io admin console, and it fails with the an UnsupportedOperationException error:
Cannot create plan for: io.crate.analyze.QueriedSelectRelation
Here is the query:
SELECT url
FROM (
  SELECT url
  FROM my_table
  LIMIT 100
  OFFSET 0
  ) AS chunk
WHERE chunk.url ~ '.*string.*';

If I remove the final line (i.e. the WHERE statement) it runs. Also this runs just fine:
SELECT url
FROM my_table
WHERE url ~ '.*string.*'
LIMIT 10;


text:
Q: How to animate drawing part of CGPath I want to approach the following scenario:

If I draw a rectangle using CGBezierPath and CAShapeLayer like the following:
    CAShapeLayer *layerX = [CAShapeLayer layer];
    layerX.path = path.CGPath;

    layerX.lineWidth   = 3;
    layerX.strokeColor = [[UIColor whiteColor] CGColor];
    layerX.fillColor   = [[UIColor clearColor] CGColor];

    [self.view.layer addSublayer: layerX];

And I want to add animation like the image I attached, this cleared area keeps moving around the rectangle path so it gives visual effect of the rectangle being drawn over and over. [Snake movement in old snake games]
I tried animating using CABasicAnimation but I literally couldn't achieve anything, thanks in advance.

A: Try this code may be helpful.
    UIBezierPath *drawablePath = [UIBezierPath bezierPathWithRect:CGRectMake(100.0, 100.0, 150.0, 100.0)];
    CAShapeLayer *squareLayer = [[CAShapeLayer alloc] init];
    squareLayer.path = drawablePath.CGPath;
    squareLayer.strokeColor = [UIColor redColor].CGColor;
    squareLayer.lineWidth = 5.f;
    squareLayer.fillColor = [UIColor clearColor].CGColor;
    squareLayer.strokeEnd = 1.f;
    //squareLayer.strokeEnd = 0.9; // this line use draw half line but some animation issue.
    [self.view.layer addSublayer:squareLayer];

    CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    drawAnimation.fromValue = (id)[NSNumber numberWithFloat:0.10];
    drawAnimation.toValue = (id)[NSNumber numberWithFloat:1.f];
    drawAnimation.duration = 5.f;
    drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    [squareLayer addAnimation:drawAnimation forKey:@"drawRectStroke"];

This code is use to draw rectangle with animation.

A: You have to animate both: strokeStart and strokeEnd and use a CAAnimationGroup to make them happen at the same time.
I found this link which does something similar but in swift. I think it might help.
I will try to implement it if you can't do it. But I can't right now.
Happy coding.

A:     let drawablePath = UIBezierPath(rect: CGRect(x: 100, y: 100, width: 150, height: 150))
    let squareLayer = CAShapeLayer()
    squareLayer.path = drawablePath.cgPath;
    squareLayer.strokeColor = UIColor.red.cgColor;
    squareLayer.lineWidth = 5;
    squareLayer.fillColor = UIColor.clear.cgColor;
    squareLayer.strokeEnd = 1;
    //squareLayer.strokeEnd = 0.9; // this line use draw half line but some animation issue.
    flowerView.layer.addSublayer(squareLayer)

    let drawAnimation = CABasicAnimation(keyPath: "strokeEnd")
    drawAnimation.fromValue = 0.1
    drawAnimation.toValue = 1.0
    drawAnimation.duration = 5
    drawAnimation.timingFunction = CAMediaTimingFunction(name:.linear)
    squareLayer.add(drawAnimation, forKey:"drawRectStroke")

Not really an answer to the original question but here's a Swift 5 version of Dixit Akabari's answer, which was useful in itself in that it demonstrates how to animate drawing a UIBezierPath by animating strokeEnd.


text:
Q: Add things to an std::map by time range but interrogate by time value I am setting up an std::map object that links a series of time ranges (the key) to objects.
It is my intention to ensure that no two overlapping time range values can be added into this map - I know I can do this by creating a comparer function that returns true if there's an overlap and passing this in as the third comparer template item to the std::map.
However, I would like to look up the values based on a single point in time, not a range.
I think I need to override an operator but I'm not sure which - any ideas?
I need to be a bit quick as I think the office is about to close so apologies for any lack of detail/code.

A: You have three possible outcomes when you compare two ranges:

*

*The first starts and ends before the second.

*The first starts and ends after the second.

*The two overlap.

You need to code your comparison function to reflect this relationship.
bool RangeLess(const range &r1, const range &r2)
{
    return r1.end < r2.start;
}

That was easy, wasn't it? If there's any overlap, both RangeLess(r1,r2) and RangeLess(r2,r1) will return false, and the two will be considered equivalent. An attempt to insert into a map will fail if there's already an equivalent item in the map.
To find a single time, use a range with the start and end values the same.

A: *

*Add constructor that accepts a single value (time), and generates a range consisting of single point - beginning and end are same.

*Override operator == for your range, so that it returns true if ranges overlap, false otherwise.
Now, you can lookup up key passing it a single value (time), whcih would default construct proper range, and return true if ranges overlap.

A: In cases like this, I'd suggest using a vector or deque ordered by end time (this optimizes for 'scheduling' a many intervals as possible), and simply iterate the list, skipping overlapping items:
#include <string>
#include <deque>
#include <algorithm>

using Timepoint = unsigned; // std::chrono::system_clock::time_point;
struct Entry {
    Timepoint start, end;
    std::string data;
};

#include <iostream>
int main()
{
    std::deque<Entry> schedule {
        {  77472, 77504, "A" },
        {  77301, 77371, "B" },
        {  77406, 77439, "C" },
        {  77270, 77303, "D" },
        {  77302, 77570, "E" },
    };

    // order by end time_point
    std::sort(begin(schedule), end(schedule), [](Entry const& a, Entry const& b) { return a.end < b.end; });

    // now, iterate the schedule entries, skipping overlapping items
    for(auto it = begin(schedule); it != end(schedule); )
    {
        auto const& entry = *it;
        std::cout << "entry: " << entry.data << " from " << entry.start << " to " << entry.end << "\n";

        // find next entry that doesn't overlap:
        while (++it != end(schedule))
                if (it->start > entry.end)
                    break;
    }
}

There's probably a name for this algorithm: It's basically a scheduling algorithm that optimizes the number of jobs (as opposed to, e.g. total 'occupied' intervals) by always scheduling the next entry that would finish soonest.
The above code prints: (Live on Coliru):
entry: D from 77270 to 77303
entry: C from 77406 to 77439
entry: A from 77472 to 77504


text:
Q: JSF (PrimeFaces) radio button behavior when space bar used to activate I am using PrimeFaces 5.2 to render a radio button group for gender.  This is for an internal network so will only run on IE11 browsers in compatibility mode.  When I select one of the radio buttons by pressing space the button is correctly activated but I don't know where the focus has gone.  If I press TAB I got to the first item that I set the tabindex for, but if I press SHIFT-TAB focus does not go to the previous element that I set the tabindex on but goes to a button that I did not set the tabindex on and is also not the first or last element in the default tab order (it is not the first or last element added to the page).
The element before the gender radio buttons is included, the calendar button is what is getting selected with SHIFT-TAB The JSF (with sensitive information removed) is as follows:

      <h:outputText value="#{enr['birth.date']}"/>*:

      <h:outputText value="#{enr['other.last.names']}"/> / <h:outputText value="#{enr['maiden.name']}"/>

         <f:ajax listener="#{II.addOtherName()}" immediate="true" render="otherNameFields"/>

      <h:dataTable id="otherNameFields" value="#{II.otherNames}" var="otherNameField">
         <h:column size="30" maxlength="50">
            <h:inputText value="#{otherNameField.otherName}" tabindex="6">
               <f:ajax event="change" listener="#{II.populateName()}" immediate="true" render="otherNameFields" />
            </h:inputText>
         </h:column>
         <h:column>

               <f:ajax listener="#{II.deleteOtherName(otherNameField)}" immediate="true" render="otherNameFields" />

         </h:column>
      </h:dataTable>

      <h:outputText value="#{enr['gender']}"/>*:

         <f:selectItem itemValue="2" itemLabel="#{enr['male']}"/>
     <f:selectItem itemValue="1" itemLabel="#{enr['female']}"/>

I also did a plain non-JSF version for comparison which works as expected so I am certain the problem is in the JSF.
Plain HTML below:

Non Index:<input type="text" />

Index #200:<input tabindex="200" type="text" />

<input name="gender" tabindex="201" id="gender_male" type="radio" value="2" />Male

<input name="gender" tabindex="201" id="gender_female" type="radio" value="1" />Female

Index #202:<input tabindex="202" type="text" />

I

A: This can be fixed by using plain JSF version of the selectOneRadio, ie:
<h:selectOneRadio value="#{II.gender}" tabindex="7" required="true" requiredMessage="#{enr['missing.required.field']}: #{enr['gender']}" style="border-style: none !important;">
     <f:selectItem itemValue="2" itemLabel="#{enr['male']}"/>
     <f:selectItem itemValue="1" itemLabel="#{enr['female']}"/>
</h:selectOneRadio>

where:
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"


text:
Q: Copy Specific values in a column I need some VBA help. I want to copy values in a column.
Referencing to the picture, I want to start to copy when the value is "Dept/Branch code: 144" because this is the only value is consistent and stop copying until the cell value is "Total". Please help!!!! I cant use range to copy because te range might not be consistent in other workbook.

Sub Copycolumn()
For i = 1 To 100
If Left(Cells(i, "A").Value, 21) = ("Dept/Branch code: 144") Then
Cells(i, "A").Copy Destination:=Range("C1")
End If
Next
End Sub

A: try this if you want to save the positions of the cells in the new list
Cells(i, "A").Copy Destination:=Range("C" & i)

and if you want to make the cells in a new list then your code should be like this:
Sub Copycolumn()
n = 0
For i = 1 To 100
If Left(Cells(i, "A").Value, 21) = ("Dept/Branch code: 144") Then
n = n + 1
Cells(i, "A").Copy Destination:=Range("C" & n)
End If
Next
End Sub

A: You can use a range! The following code will find the first row to start the copy, then use that to look for the first instance of "Total*", then copy that range to cell C1
Sub gogo()
    START_ROW = Application.WorksheetFunction.Match("Dept/Branch code: 144*", Range("A:A"), 0)
    END_ROW = Application.WorksheetFunction.Match("Total*", Range("A" & START_ROW & ":A5000"), 0) + START_ROW - 1
    Range("A" & START_ROW & ":A" & END_ROW).Copy
    Range("C1").PasteSpecial
End Sub

This code doesn't use any looping, it just utilises Excel's in-built super-fast function for finding a MATCH so it'd be much faster if you had a sheet that had a tonne of entries
Also please note it's using a wild card * at the end of "Total" and "Dept/Branch code: 144" to do the match so you don't have to strip the string.

A: You can use a Range object, you can use the Find function to find the first cell where "Dept/Branch code: 144" and the last cell to copy where you have "Total".
Code
Option Explicit

Sub Copycolumn()

Dim StartRng As Range, FinishRng As Range, CopyRng As Range

With Sheets("Sheet1") ' modify "Sheet1" to your sheet's name
    Set StartRng = .Columns(1).Find(what:="Dept/Branch code: 144", LookIn:=xlValues, LookAt:=xlPart)
    If StartRng Is Nothing Then ' check if Find failed
        MsgBox "Unable to Find `Dept/Branch code: 144`", vbCritical
        Exit Sub
    End If

    Set FinishRng = .Columns(1).Find(what:="Total", LookIn:=xlValues, LookAt:=xlPart)
    If FinishRng Is Nothing Then ' check if Find failed
        MsgBox "Unable to Find `Total`", vbCritical
        Exit Sub
    End If

    ' set the range to be copied
    Set CopyRng = .Range(.Cells(StartRng.Row, 1), .Cells(FinishRng.Row, 1))

    ' copy the Range
    CopyRng.Copy Destination:=.Range("C1")

End With

End Sub

A: If your "dept/branch code" does not have duplicates, you can accomplish what you want in one line
Columns(1).Find("*144*", , xlValues, xlWhole).Resize(10).Copy Range("C1")


text:
Q: Check XML file against DTD file using expat in C I need to build an application the should parse an XML file using EXPAT and also check it against a DTD file. The problem is how do I do this, I checked the documentation, and couldn't find my way around.
My code so far:
int main(int argc, char *argv[])
{
    XML_Parser p = XML_ParserCreate(NULL);
    if (!p)
    {
        fprintf(stderr, "Couldn't allocate memory for parser\n");
        exit(-1);
    }
    FILE* xmlFile;
    xmlFile = fopen("test.xml", "r");
    XML_SetElementHandler(p, start, end);
    XML_SetParamEntityParsing(p, XML_PARAM_ENTITY_PARSING_ALWAYS);

    for (;;)
    {
        int done;
        int len;

        len = (int) fread(Buff, 1, BUFFSIZE, xmlFile);
        if (ferror(xmlFile))
        {
            fprintf(stderr, "Read error\n");
            exit(-1);
        }
        done = feof(xmlFile);

        if (XML_Parse(p, Buff, len, done) == XML_STATUS_ERROR)
        {
            fprintf(stderr, "Parse error at line %" XML_FMT_INT_MOD "u:\n%s\n",
                    XML_GetCurrentLineNumber(p),
                    XML_ErrorString(XML_GetErrorCode(p)));
            exit(-1);
        }

        if (done)
            break;
    }
    XML_ParserFree(p);
    return 0;
}

I guess that the should be a call to the XML_SetExternalEntityRefHandler function, but I fail to understand how to use it.
Thank you in advance.


text:
Q: phpseclib unable to read CSR field containing guillemet brackets Here is a sample CSR I created with brackets in the organizationalUnit OU field value <this is a test> phpseclib appears to be unable to return this value. Is there any fix for this?
-----BEGIN CERTIFICATE REQUEST-----
MIICqzCCAZMCAQAwaDEVMBMGA1UEAwwMdGVzdGNzci50ZXN0MQ0wCwYDVQQKDAR0
ZXN0MRkwFwYDVQQLDBA8dGhpcyBpcyBhIHRlc3Q+MQswCQYDVQQIDAJOWTELMAkG
A1UEBwwCTlkxCzAJBgNVBAYMAlVTMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
CgKCAQEAgqK3dSpXidA5DaKuIG7cg3ioKcyWXWCRdms/pUz+7FvDO1qUtdZoogXy
e5Vty+lHqxYsHOuqjt/HjVYEkQW5jV/e5i8BUdZ/HyBCLrVxhrOBCKYt5pTl5zE3
8Zw6zS7tL8ZVjoo3HvoFRp/R+IGjpNBLyhB4M7oyUBiomyQhuLxc1e/dq9/f7S1k
El66XOrLf15ghjRImVT4N4APmvV1eSojGINFG+ILST0iBSTz2tKPsPPVwO9b59nh
Prrdhzz7tPmn9qooVzVqRvUtZan3dNmtG3ZGR1v0wU0Psox6go/LgECagSXeXBYN
cctuqOkcfXxL2n+dLlkFUDS3qhYoGQIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQAk
jzYjenq3IVUj5jKhC0MPRvSFnazun6H35pVLXqES8Zn3kN6bCqmZTAjDDtRP0ohx
jCk0FW1lkvQVn+/tYrX/kghclZhHVXFO47B0Li3KMm/Gg9DAHxud2xCHwJOcCWDQ
t/RXTLjq7n8A7A4/enfWiSlMGeSA6o5zynSCbzRzkjx+CzCfwunOKEdhARaouxqZ
Z3lXWhoH1QcBy2SS90mS8XiqFaXwDGYz8c8PK5JBP01mH/MuAgVsOONDSz/nEFzR
MC7l/ATdyqQf/lOegM+Rr/K5ox5+kdxAnBx0SrvvGB1iLTlVy/hyrjK4GIQaTZPC
fixw9o3Nje4+FsBnW6vP
-----END CERTIFICATE REQUEST-----

When parsing the field with phpseclib i get the following output:
[2] => Array
    (
        [0] => Array
            (
                [type] => id-at-organizationalUnitName
                [value] => Array
                    (
                        [utf8String] =>
                    )

            )

    )

Native openssl via commandline has no problems reading the OU field.
openssl req -text -noout -verify -in ouissue.txt
verify OK
Certificate Request:
    Data:
        Version: 0 (0x0)
        Subject: CN=testcsr.test, O=test, OU=<this is a test>, ST=NY, L=NY, C=US
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    00:82:a2:b7:75:2a:57:89:d0:39:0d:a2:ae:20:6e:
                    ....
                    1c:7d:7c:4b:da:7f:9d:2e:59:05:50:34:b7:aa:16:
                    28:19
                Exponent: 65537 (0x10001)
        Attributes:
    Signature Algorithm: sha256WithRSAEncryption
         24:8f:36:23:7a:7a:b7:21:55:23:e6:32:a1:0b:43:0f:46:f4:
         ....

A: solved by using htmlentities(); to display script tags otherwise the browser just to reads it as html.
e.g. echo htmlentities($x509->getDNProp('OU'));


text:
Q: Django class based view, define method and property I'm caching a view's html output.  (I'm caching a view response (html) myself without using django's caching framework.)
I need to invalidate this cache in various places.
eg) Suppose I develop StackOverflow (woohoo), and caches its main-page.
I definately want to invalidate the cache whenever a new question is posted.
or new featured article needs to be shown in the main page.
Among other things, I would like to store cache_key for the main page, and invalidate_page (a function) somewhere near main page 's view code.
I could define them separately near main_page view. but just thought it would be nicer for the main_page view to have those constants, methods attached to itself.
I'd like to encapsulate stuff in main_page view somehow as we do with object oriented programming if it's possible.
I only use FBV and thought maybe CBV can help here, but any other suggestion is welcome.


text:
Q: ¿Cómo agregar datos en un data frame utilizando condicionales? Lo que sucede es que tengo una base de datos amplia sobre transacciones que hicieron los clientes de una entidad financiera durante un mes, por lo que hay usuarios que aparecen repetidos en dicha base datos puesto que han realizado más de una transacción en el mes. Hay una columna que se llama <>" en la cual hay espacios que deseo llenar con datos. En total son tres segmentos: "Pensionado", "Independiente", "Empleado". Lo que quiero es llenar esos espacios con cada uno de los tres segmentos, pero teniendo en cuenta el documento de la persona. Es decir, colocar "Pensionado" en los espacios vacíos si el número de documento de la personas es xxxxxxxx, colocar pensionado "Independiente" en los espacios vacíos de la persona con número de documento xxxxx, y así sucesivamente hasta llenar todos los campos de la columna <>.
¿Esto se puede hacer? ¿Si es así, cómo se haría? Les agradecería mucho su ayuda.


text:
Q: How to handle Javascript depencencies after bundling? From what I understand, the common way to deploy a Javascript app is to take all your dependencies and put them all in one file (and then minify it). I don't understand how the code I wrote will then find the modules that are now all in this new file. I'm using node.js if that matters and use a gulp task like this to do the bundling:
gulp.task('bundle_deps', function() {
  return gulp.src('src/**/*.js')
    .pipe(concat('bundle.js'))
    .pipe(gulp.dest(deploy_dir));
});

A: If you're talking about deployment, then the way to do this in node.js is to put your dependencies in the package.json file. For example:
{
  "name": "yourAppName",
  "version": "0.0.1",
  "dependencies": {
    "restify": ">= 2.6.0",
    "node-restify-validation": "0.0.6",
    "node-restify-swagger": "0.1.6"
  }
}

See: https://docs.npmjs.com/files/package.json#dependencies
Then when you deploy the application, copy your code to the server and run the command
npm install

npm will read the dependencies in the package.json file and install them all for you.


text:
Q: MySQL syntax - adding a primary key. What does the following mean? I have the following syntax from an SQL tutorial. It updates a table to add a primary key constraint to a column.
ALTER TABLE Persons
ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)

What exactly is the pk_PersonID? Is this just an identifier? Must this unique right across the entire database?
Thanks indeed

A: Yes, it's an identifier for the constraint and must be unique. For example, if you want to delete the constraint later you can do
ALTER TABLE Persons
DROP CONSTRAINT pk_PersonID;


text:
Q: Problema Con un if en java Estaba intentando hacer que si eres mayor de 18 pues que te salga un mensaje si no eres mayor que te salga otro mensaje y hice el código(Creo que esta bien)

class Main{
    public static void main(String []args){
        Scanner myObj  = new Scanner(System.in);
        System.out.print("Introduce Tu Edad");

        String Edad = myObj.nextLine();
        System.out.print("Tu Edad es: " + Edad);
        if (Edad < 18){
            System.out.println("Eres Menor De Edad");
        }
        else{
            System.out.println("Eres Mayor De Edad");
        }
        }
}

pero me sale un error en el if donde esta la edad me pone un fallo y que yo sepa esta bien

A: Estás declarando la variable edad como una cadena de texto (String). Tienes que declararlo como un entero (int) para poder compararlo.
Esto no podrás hacerlo ya que estás recogiendo la edad por consola y al recoger un valor por consola lo que hace es recogerlo como cadena de texto. Por tanto, deberás hacer un casting para convertirlo a entero. Para ello deberás utilizar Integer.parseInt(edad)
Código funcional:
class Main{
    public static void main(String []args){
        Scanner myObj  = new Scanner(System.in);
        System.out.print("Introduce Tu Edad");

        String Edad = myObj.nextLine();
        System.out.print("Tu Edad es: " + Edad);
        if (Integer.parseInt(Edad) < 18){
            System.out.println("Eres Menor De Edad");
        }
        else{
            System.out.println("Eres Mayor De Edad");
        }
        }
}

O, si te parece más comprensible:
class Main{
    public static void main(String []args){
        Scanner myObj  = new Scanner(System.in);
        System.out.print("Introduce Tu Edad");

        String Edad = myObj.nextLine();
        int edadEntero = Integer.parseInt(Edad)
        System.out.print("Tu Edad es: " + Edad);
        if (edadEntero < 18){
            System.out.println("Eres Menor De Edad");
        }
        else{
            System.out.println("Eres Mayor De Edad");
        }
        }
}

A: También puedes declarar la variable Edad como int desde el principio
int Edad = myObj.nextInt();

A: Ya que tienes el modelo if-else puedes usar el operador ternario que hace que el código sea más compacto.
public static void main(String[] args) {
        Scanner myObj  = new Scanner(System.in);
        System.out.print("Introduce Tu Edad: ");
        int edad = myObj.nextInt();
        System.out.println(edad < 18 ? "Eres Menor De Edad": "Eres Mayor De Edad");
}

Observación
Las variables en java se declaran en minúscula y si es una palabra compuesta se usa la notación Camel Case


text:
Q: How do I estimate error when I know a survey is not representative? Let's say that I have a survey of $n = 1000$ respondents from a population of $N = 3000$.
Moreover, it is known that the ratio of male to female in the population is $50:50$. However, in the sample, $70\%$ were female.
Given that I know that the sample is not representative in terms of sex, how do I calculate the survey error rate?

A: I can give some general advice, but a lot of the answer is actually dependent on the design of the survey. I'm going to assume that you made a probability sample (that is, all units had a known probability of being selected). I'm also going to assume you are making estimates of population total - other population quantities are analogous.
Often when we know we need to calibrate to certain general subpopulations that are unidentified before units have responded, we use post-stratified estimation. Generally:
$$
\hat{Y}_{pos} = \sum_{k\text{ post-strata}}\frac{N_k}{\hat{N_k}}\hat{Y}_k
$$
Which means to estimate the total within a population, we estimate the total within each subpopulation, and multiply by an adjustment factor which accounts for the disparity between the known subpopulation representation and the estimated subpopulation representation. The estimates of subpopulation total and size are given by:
$$
\hat{Y}_k = \sum_{i\in s_k}\pi_i^{-1}y_i\\
\hat{N}_k = \sum_{i\in s_k}\pi_i^{-1}
$$
$\pi_i$ is the known probability of selecting unit $i$.
This estimate of population total is biased, but in many cases this is able to be ignored. Ignoring the bias gives us an approximate variance formula of:
$$
Var(\hat{Y}_{pos})\approx\sum_{k\text{ post-strata }}\left[\sum_{i\in s_k}\sum_{j\in s_k}\frac{y_i}{\pi_i}\frac{y_j}{\pi_j}(\pi_{ij}-\pi_i\pi_j)\right]
$$
$\pi_{ij}$ is the probability of both $i$ and $j$ being selected in the sample, and has to be non-zero for all pairs of units in the population. This formula further simplifies rather significantly if the sample is simple random (where all samples of the same size are equally as likely).


text:
Q: Popup/panel does not appear at the right position through javascript I have created a page where a list of members is shown. I created a Javascript function which shows the details of a user in a panel with id divpreview with position:absolute and z-index:100 the popup/panel does but I am not able to show it right above the the member.

I want the panel to appear near the stars. What should I do.

A: Use
position: relative;

to the parent div. Position absolute element will "stop" when finding the closest positioned relative or positioned absolute element.

A: use this style on divpreview

A: position: absolute;

parent div Position 'absolute'.


text:
Q: How to restrict user to be logged only one time per session? I'm working a Symfony 1.4 apps, and I need to prevent a user beeing able to login more than once into the application, I mean if S/He is already logged in, it should not be able to logged in just opening a new browser.

*

*user log in on Chrome.

*Open Firefox, try to login and then can't login because a session is already active on Chrome

I want to avoid same user begins another session with a different browser in the same computer, or in another.

A: You can check whether user is logged in by calling:
sfContext::getInstance()->getUser()->isAuthenticated()

or inside action just:
$this->getUser()->isAuthenticated()

So I guess you want to have something like:
public function executeLogin($request)
{
    if ($this->getUser()->isAuthenticated()) {
        // redirect or whatever
        // $this->redirect(...);
    } else {
        // login user properly
    }
}

A: The only solution I think about is to use session in MySQL (or your database) and then, check if a session is active for a given user so it can login or not.
It won't be an easy part. I did that one time but can't find the source code.. So I will describe what you will have to do.

*

*You need to activate sfPDOSessionStorage to store session in db (you can follow this blogpost)

*then create a custom storage that extend sfPDOSessionStorage to be able to add more field into the session table.
You will have a new field (for example sess_user_id) inside your factories.yml, something like this :
all:
  storage:
    class: myCustomPDOSessionStorage
    param:
      db_table:       session
      database:       propel

      db_id_col:      sess_id
      db_data_col:    sess_data
      db_time_col:    sess_time
      db_user_id_col: sess_user_id

*You will need to update method sessionRead & sessionWrite from your custom session storage to:

*

*insert/update with the new field (the user_id)

*check if a user_id already exist and session time is ok or not. If not, throw an exception. You will have to catch this exception when the user login, to display message about the problem.


text:
Q: Android error Log File : permission denied I am making an application in android. in first activity its displays list of videos and that are on youtube...
But, when i click that list and control transfer to the next activity and I am transferring URL of that video to the next activity. Every thing is working correct but video is not displaying... I am using video view control. But When I see LogCat File, Following errors displays to me...
I written permission of internet to my manifest file
 <uses-permission android:name="android.permission.INTERNET" />

But still got error.( Application doesn't display error)
LOGCAT:
12-09 21:13:10.905: V/VideoViewDemo(2559): path: http://www.youtube.com/watch?v=i5Fsnv6wHJo
12-09 21:13:12.865: E/VideoViewDemo(2559): error: Permission denied
12-09 21:13:12.865: E/VideoViewDemo(2559): java.io.IOException: Permission denied
12-09 21:13:12.865: E/VideoViewDemo(2559):  at java.io.File.createNewFileImpl(Native Method)
12-09 21:13:12.865: E/VideoViewDemo(2559):  at java.io.File.createNewFile(File.java:1257)
12-09 21:13:12.865: E/VideoViewDemo(2559):  at java.io.File.createTempFile(File.java:1322)
12-09 21:13:12.865: E/VideoViewDemo(2559):  at java.io.File.createTempFile(File.java:1278)
12-09 21:13:12.865: E/VideoViewDemo(2559):  at com.pxr.tutorial.xmltest.Watch_Video.getDataSource(Watch_Video.java:180)
12-09 21:13:12.865: E/VideoViewDemo(2559):  at com.pxr.tutorial.xmltest.Watch_Video.playVideo(Watch_Video.java:157)
12-09 21:13:12.865: E/VideoViewDemo(2559):  at com.pxr.tutorial.xmltest.Watch_Video.access$0(Watch_Video.java:141)
12-09 21:13:12.865: E/VideoViewDemo(2559):  at com.pxr.tutorial.xmltest.Watch_Video$5.run(Watch_Video.java:135)
12-09 21:13:12.865: E/VideoViewDemo(2559):  at android.app.Activity.runOnUiThread(Activity.java:3717)
12-09 21:13:12.865: E/VideoViewDemo(2559):  at com.pxr.tutorial.xmltest.Watch_Video.onCreate(Watch_Video.java:133)
12-09 21:13:12.865: E/VideoViewDemo(2559):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
12-09 21:13:12.865: E/VideoViewDemo(2559):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
12-09 21:13:12.865: E/VideoViewDemo(2559):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
12-09 21:13:12.865: E/VideoViewDemo(2559):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
12-09 21:13:12.865: E/VideoViewDemo(2559):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
12-09 21:13:12.865: E/VideoViewDemo(2559):  at android.os.Handler.dispatchMessage(Handler.java:99)
12-09 21:13:12.865: E/VideoViewDemo(2559):  at android.os.Looper.loop(Looper.java:123)
12-09 21:13:12.865: E/VideoViewDemo(2559):  at android.app.ActivityThread.main(ActivityThread.java:3683)
12-09 21:13:12.865: E/VideoViewDemo(2559):  at java.lang.reflect.Method.invokeNative(Native Method)
12-09 21:13:12.865: E/VideoViewDemo(2559):  at java.lang.reflect.Method.invoke(Method.java:507)
12-09 21:13:12.865: E/VideoViewDemo(2559):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-09 21:13:12.865: E/VideoViewDemo(2559):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-09 21:13:12.865: E/VideoViewDemo(2559):  at dalvik.system.NativeStart.main(Native Method)

Code for main file:
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listplaceholder);

    String str=getIntent().getExtras().getString("Category").toString();

    ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

    String xml = XMLfunctions.getXML(str);
    Document doc = XMLfunctions.XMLfromString(xml);

    int numResults = XMLfunctions.numResults(doc);

    if((numResults <= 0)){
        Toast.makeText(CategoryDetail.this, "Geen resultaten gevonden", Toast.LENGTH_LONG).show();
        finish();
    }

    NodeList nodes = doc.getElementsByTagName("video1");

    for (int i = 0; i < nodes.getLength(); i++) {
        HashMap<String, String> map = new HashMap<String, String>();

        Element e = (Element)nodes.item(i);
        map.put("iVid", XMLfunctions.getValue(e, "iVid"));
        map.put("vVName", XMLfunctions.getValue(e, "vVName"));
        map.put("vSource", XMLfunctions.getValue(e, "vSource"));

        mylist.add(map);
    }

    ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.category_detail,
                    new String[] { "vVName" },
                    new int[] { R.id.item_title });

    setListAdapter(adapter);

    final ListView lv = getListView();
    lv.setTextFilterEnabled(true);
    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            @SuppressWarnings("unchecked")
            HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
            //Toast.makeText(CategoryDetail.this, "Video '" + o.get("vVName") + "' is just clicked.", Toast.LENGTH_LONG).show();

            Intent intent=new Intent(CategoryDetail.this, Watch_Video.class);

            intent.putExtra("url", o.get("vSource"));
            startActivity(intent);
            //Toast.makeText(CategoryDetail.this,"This is Url" + o.get("vSource"), Toast.LENGTH_LONG).show();

            //Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=nLJYkat4HpE"));
            //startActivity(intent);

        }

    });
    }

Second Activity File:
    mVideoView = (VideoView) findViewById(R.id.surface_view);

    mPath=getIntent().getExtras().getString("url");
    //mPath = (EditText) findViewById(R.id.path);
    //mPath.setText("http://daily3gp.com/vids/747.3gp");
    Toast.makeText(Watch_Video.this,"This is Url" + mPath.toString(), Toast.LENGTH_LONG).show();

    mPlay = (ImageButton) findViewById(R.id.play);
    mPause = (ImageButton) findViewById(R.id.pause);
    mReset = (ImageButton) findViewById(R.id.reset);
    mStop = (ImageButton) findViewById(R.id.stop);

    mPlay.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            playVideo();
        }
    });
    mPause.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            if (mVideoView != null) {
                mVideoView.pause();
            }
        }
    });
    mReset.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            if (mVideoView != null) {
                mVideoView.seekTo(0);
            }
        }
    });
    mStop.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            if (mVideoView != null) {
                current = null;
                mVideoView.stopPlayback();
            }
        }
    });
    runOnUiThread(new Runnable(){
        public void run() {
            playVideo();

        }});

}

private void playVideo() {
    try {
        final String path = mPath.toString();
        Log.v(TAG, "path: " + path);
        if (path == null || path.length() == 0) {
            Toast.makeText(Watch_Video.this, "File URL/path is empty",
                    Toast.LENGTH_LONG).show();

        } else {
            // If the path has not changed, just start the media player
            if (path.equals(current) && mVideoView != null) {
                mVideoView.start();
                mVideoView.requestFocus();
                return;
            }
            current = path;
            mVideoView.setVideoPath(getDataSource(path));
            mVideoView.start();
            mVideoView.requestFocus();

        }
    } catch (Exception e) {
        Log.e(TAG, "error: " + e.getMessage(), e);
        if (mVideoView != null) {
            mVideoView.stopPlayback();
        }
    }
}

private String getDataSource(String path) throws IOException {
    if (!URLUtil.isNetworkUrl(path)) {
        return path;
    } else {
        URL url = new URL(path);
        URLConnection cn = url.openConnection();
        cn.connect();
        InputStream stream = cn.getInputStream();
        if (stream == null)
            throw new RuntimeException("stream is null");
        File temp = File.createTempFile("mediaplayertmp", "dat");
        temp.deleteOnExit();
        String tempPath = temp.getAbsolutePath();
        FileOutputStream out = new FileOutputStream(temp);
        byte buf[] = new byte[128];
        do {
            int numread = stream.read(buf);
            if (numread <= 0)
                break;
            out.write(buf, 0, numread);
        } while (true);
        try {
            stream.close();
        } catch (IOException ex) {
            Log.e(TAG, "error: " + ex.getMessage(), ex);
        }
        return tempPath;
    }

A: Try to add the following permission to your manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


text:
Q: Using base class methods to initialize derived class members Is it legal? If so, do you consider it as good coding practice?
I want to do something like this (nonessential details are not shown):
class ItemStorage {
    int size() const;
};

class SpecialStorage : public ItemStorage  {
public:
    SpecialStorage (...) : ItemStorage(...), items(ItemStorage::size()) {...}
private:
    int items;
};

I am pretty sure that it is OK if the method size is not virtual. What if it is virtual and the derived class doesn't overwrite it?

A: The general rule is that, during initialization, you must not access uninitialized parts of the object. As ItemStorage is already initialized when items gets initialized, calling size is indeed fine.
Even if size was virtual, and even if it was overwritten, it still would be fine: it would just call the base version (i.e. virtual methods only bind to the level which is under construction).


text:
Q: Integrating CAS and Symfony sfGuard? I'm trying to integrate CAS and sfDoctrineGuard. I want my login and logout to be controlled by CAS, which works perfectly with the sfCASPlugin.
However, I need to integrate this with the Users, Groups and Permissions from sfGuard. How can I do it?
I thought that I could "force" the login in sfGuard after logging with sfCas, but failed.
Any ideas?

A: There is no way doing this with the default implementations of the sfCasPlugin and sfGuardPlugin. The only way would be to change a lot of the sfCasPlugin implemntation. So for Symfony 1.4 you will not be able to use a standard-plugin to implement this. This will get a lot easier to do with Symfony2.


text:
Q: How to deal with backslashes (because of parenthesis) in json using laravel? I have text
This is Laravel's package. Following terms and conditions ("Terms")
Above text I want to return as json through laravel api, the problem is I am getting string with backslashes because of parenthesis.
I am trying following
$content = 'This is Laravel\'s package. Following terms and conditions ("Terms")';
$data =  str_replace(PHP_EOL, '', $content);
echo response()->json([ 'data' => $data ]);

Which output is following
{"data":"This is Laravel's package. Following terms and conditions (\"Terms\")"}


text:
Q: what is the difference between rel and href and src in HTML all of :
href
src
rel
attributes all seems to have same function so why each html element use these different attributes . So what is the function of each of these attributes and when to use each one of them

A: href
The href attribute specifies the location(URL) of any resource that anchor tag points to.

src
The src attribute specifies the location(URL) of any resource that needs to be embedded into the present HTML document. Resourse pointed by src attribute is linked to the current document such as img, video, audio, or script. The browser will allocate screen real estate depending upon the physical dimensions of the embedded object. href has no such provision.

The ***rel*** attribute defines the relationship that the linked resource has to the document from which it's referenced. In most cases, this resource will simply be "stylesheet", which means, not surprisingly, "the referenced document is a style sheet." Related to this value is alternate, which is used alongside the stylesheet value (rel="alternate stylesheet") to indicate that there's another style associated with the page. In fact, you can define several alternative styles, although the main issue with this approach lies in making it clear to the user that an alternative style sheet is available. In Firefox, you can chose View > Page Style and pick from the available style sheets on offer, but there's no obvious indication in any browser that these alternatives exist—it's usually left to the developer to provide some kind of JavaScript-based style switcher that renders as a control on the page. The following markup shows a page that has one main style sheet and two alternatives:


text:
Q: In swift, is there a way to log into a website with a token gotten with OAuth2 library? is there someone who can help me with the OAuth2 library in swift
I'm doing that to handle the end of OAuth
appDelegate.oauth2!.afterAuthorizeOrFail = { authParameters, error in
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let myString = formatter.string(from: appDelegate.oauth2!.accessTokenExpiry!)
        print("t \(appDelegate.oauth2!.accessToken)")
        print("td \(myString)")
        //login me here with oauth2.accessToken

}

In this block I want to log into my website with an url like that :
"http://my-website.com/authme.php?token=\(oauth2!.accessToken!)"
I've try webview.load and no success but if I do the request in another function evrything works like a charm
Thank in advance
EDIT More info
I think it is due to the fact that afterAuthorizeOrFail seems to be called in background
Here is how afterAuthorizeOrFail is called didFail and didAuthorize which only differences are the arguments of the function in those methods
public final func didFail(with error: OAuth2Error?) {
        var finalError = error
        if let error = finalError {
            logger?.debug("OAuth2", msg: "\(error)")
        }
        else {
            finalError = OAuth2Error.requestCancelled
        }
        callOnMainThread() {
            self.didAuthorizeOrFail?(nil, finalError)
            self.didAuthorizeOrFail = nil
            self.internalAfterAuthorizeOrFail?(true, finalError)
            self.afterAuthorizeOrFail?(nil, finalError)
        }
    }

Here is the source file with this method
https://github.com/p2/OAuth2/blob/master/Sources/Base/OAuth2Base.swift
and callOnMainThread is that:
public func callOnMainThread(_ callback: (() -> Void)) {
    if Thread.isMainThread {
        callback()
    }
    else {
        DispatchQueue.main.sync(execute: callback)
    }
}

Here is the source file with this method
https://github.com/p2/OAuth2/blob/master/Sources/Base/OAuth2Requestable.swift
And here is how I do the request
  let requrl=URL(string: "http://my-website.com/authme.php?token=\(oauth2!.accessToken!)")
     do{
        let request = try URLRequest(url: requrl!,method: .post)
        self.webView!.load(request)
     }catch let error {
       DispatchQueue.main.async {
       print("ERROR loading site \(error)")
     }
 }

A: The issue was that I used a wrong WKWebview (not the one on the storyboard)
Changing that fix my issue


text:
Q: Movesense: how to determine wbcmd port on Windows 10 I have a movesense device with the programming jig.
I can connect to the jig using j-link, I can program/firmware update the device, but I can-not connect to the device using "wbcmd". Keeps coming up with "No device connected"
The programming jig is listed in device manager as USB device "J-link driver" but does not have a corresponding COM port.
What is the connection I put in "port" settings in the following command:-
wbcmd --port xxxx --path /Info --op GET
Thanks in advance.

A: Connect the J-Link and run SEGGER J-Link Configuration tool, select your probe and enable Virtual COM-Port.
Unplug and reconnect the J-Link, the COM port should appear.

A: The COM port of Movesense jig is completely separate from the SEGGER (in fact you don't need to have SEGGER connected to use it). The easiest way to get the COM port number is to open the Windows "Device Manager" and open the "Ports" sub tree. The "Ports" is not visible if there are no COM/LPT ports in the system:

To access the sensor over COM-port the UART must be swithced on (it's off by default since it uses over 1 mA of current). That can be done using Android version of Movesense Showcase App (wrench icon in top-right corner). Sensor needs to be reset/power cycled for UART setting to take effect.
Full disclosure: I work for the Movesense


text:
Q: Checking file after creating. FS + timeout? After ajax request, I send options for Image Magick (child process) and create file.
If I send response to client immediately - I have error - img non exist. My solution, set Timeout and send response (hardcode).
I can set timeout and check file with fs module, but it is right way?
Or may be I can emit new event after file exist, but can you type sample for me?
Or this task have another solution?
fs.stat(currentImage, function(err, background) {

        if (background && background.isFile) {

            async.series([
                function(callback) {
                    var magickOpts = memOptions;
                    var im = spawn('convert', magickOpts);
                    callback(null, 'done');
                }
            ],
            function(err, result) {
                setTimeout(function() {
                    res.send({
                        status: '200',
                        src: '/images/mems/'+tempName+'.jpg',
                        tempName: tempName
                    });
                }, 500);
            });

        } else {
            res.send({
                status: '404',
                text: 'background image not found'
            });
        }

    });

A: You should wait for the child process to exit (by listening for the close event) before you send the response to the client.
Also, async.series doesn't seem to be really used in this case, so I left it out:
fs.stat(currentImage, function (err, background) {

  if (background && background.isFile) {
    var magickOpts = memOptions;
    var im = spawn('convert', magickOpts);
    im.on('close', function() {
      res.send({
        status: '200',
        src: '/images/mems/' + tempName + '.jpg',
        tempName: tempName
      });
    });
  } else {
    res.send({
      status: '404',
      text: 'background image not found'
    });
  }

});

By the way, there's also the im package which wraps ImageMagick for use in Node.


text:
Q: Throwing with the ternary operator This compiles:
struct A{};
struct B{};

int main(){
  if(true)
    throw A();
  else
    throw B();
}

, but
struct A{};
struct B{};

int main(){
  throw( true ?  A() : B() );
}

won't.
Can I throw with the ternary operator?

A: A and B are different, incompatible types, so the expression true ? A() : B() is ill-typed (it'd have to be either an A or a B).

A: Ternary operator needs to have the same type(or something convertible to the same type) on both paths otherwise the compiler can't reason about type safety.

A: If there is a result from the conditional operator, the types needs to be somehow compatible. If the types are not compatible, you can still throw from a ternary operator, though:
condition? throw A(): throw B();

Although all compilers I tried do compile the above statement, it seems to be illegal: according to 5.16 [expr.cond] paragraph 2, first bullet "The second or the third operand (but not both) is a (possibly parenthesized) throw-expression (15.1); ...". To counter that constraint it is possible to use something like
condition? (throw A()), true: throw B()


text: Q: emcee MCMC Sampling... Small set of walkers not converging? I'm running mcmc on a simulation where I know the true parameter values. Suppose I use 100 walkers and 10,000 steps in the chain. The bulk of the walkers converge to the correct parameter values, but ~3 walkers (out of the 100) just trail off into the distance, not converging. Not sure what could be at play here, other than a potential error on my end.