text:
Q: How to use OpenCV cornerSubPix() in Python? I'm trying to get and paint corner points in an image. Now, I have a list of tuples with the following format: (row,column,scale) (scale is because I'm using a Gaussian Pyramid), obtained from harrisCornerDetector and nonMaximumSupression process manually. This list is featuresy1.
My code is the following:
r,g,b=cv2.split(image)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
cv2.cornerSubPix( r, featuresy1, (5,5), (-1,1), criteria )

Where image is an image in grayscale with three identical shapes. As you can see, I'm giving to cornerSubPix as second parameter a structure like this: [(x1,y1,scale1),(x2,y2,scale2),...,(xn,yn,scalen)].
This is throwing the following error:
cv2.cornerSubPix( r, featuresy1, (5,5), (-1,1), criteria )
TypeError: corners is not a numpy array, neither a scalar

For this reason I wonder what type, format or structure should have featuresy1 to do cornerSubPix() working. Is this the only thing I'm doing wrong? There isn't much documentation about this.
Thanks!

A: You need to make sure corners is numpy array with 3 dimensions (n, 1, 2), where n is the number of corners. It also has to be a type float32.
Just type
corners.shape

to verify this.
Type in
corners.dtype

To check you are using float32.
To me is looks like your corners featuresy1 is list where it should be a numpy array. Convert it first to a numpy array:
featuresy1 = np.array(featuresy1)

Opencv has an easy to understand example that might help you


text:
Q: How to remove all Activities except root activity with launch mode and activity alias? I'm studying launch mode intent flag and activity alias in Android programming.
There are activities (A - B - A - B) in back stack, and I want to start activity A and I also want to reuse A at bottom of back stack. So final state of back stack I want is just (A).
To do so, I write code like this
A (MainActivity)
package com.example.intentflagexampele;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.button).setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, MainActivity2.class);
            startActivity(intent);
        });
    }
}

B (MainActivity2)
package com.example.intentflagexampele;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;

public class MainActivity2 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        findViewById(R.id.button).setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity2.this, MainActivity.class);
            startActivity(intent);
        });

        findViewById(R.id.button2).setOnClickListener(v -> {
            Intent intent = new Intent();
            ComponentName componentName = new ComponentName(MainActivity2.this,
                    "com.example.intentflagexampele.SplashActivity");
            intent.setComponent(componentName);
            intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        });
    }
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.intentflagexampele">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.IntentFlagExample2">
        <activity android:name=".MainActivity2"/>
        <activity android:name=".MainActivity">
        </activity>

        <activity-alias
            android:name=".SplashActivity"
            android:targetActivity=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity-alias>
    </application>

</manifest>

The problem is that whenever I start SplashActivity with button2, Back Stack become (A - B - A) not (A).
What should I do? Is there something wrong?

A: Try something like this:
Intent intent = new Intent(this, A.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

This will clear the back stack of activities.

A: This is not a clean application architecture. In general, if you have multiple instances of the same Activity in the stack, you cannot reliably tell Android to go back to a specific instance of an Activity.
You should create separate activities so that you can avoid having multiples instances of the same Activity in the stack (if you want to be able to return to a specific instance of that Activity).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why do I get undefned symbol for yylex and yyerror while compiling a basic yacc program? I am writing a basic program with yacc/lex, and I get an undefined symbol error in the yacc C generated source code for yyerror and yylex. How do I specify that those files are generated in the lex lexer?
Here is what I have tried:
readfile_grammar.y
    %{

    #include <time.h>
    #include <stdio.h>

    %}

    %union {

            struct tm       datetime;               /* DATE TIME VALUES */
            double          float_number;           /* 8 BYTES DOUBLE VALUE */
            long            integer_number;         /* 8 BYTES INTEGER VALUE */

    }

    %token  <datetime>              DATETIME
    %token  <float_number>          FLOAT_NUMBER
    %token  <integer_number>        INTEGER_NUMBER

    %%

    lastbid_lastask:        DATETIME ',' FLOAT_NUMBER ',' FLOAT_NUMBER ',' INTEGER_NUMBER   { printf("MATCH %lf %lf %ld\n", $3, $5, $7); }
                            ;

    %%

    int main(int argc, char *argv[]) {

            yyparse();

            return 0;

    }

readfile_lexer.l
%{

#include <time.h>
#include "readfile_grammar.h"

%}

%%

                                                                        /* SKIP BLANKS AND TABS */
[\t ]                                                                   { ; }

                                                                        /* YYYYMMDD HHMM DATE */
[12][09][0-9][0-9][0-1][0-9][0-3][0-9][ ][0-2][0-9][0-5][0-9]           { read_date_YYYYMMDD_HHMM(); return DATETIME; }

                                                                        /* FLOAT NUMBER */
[0-9]+\.[0-9]+                                                          { read_float_number(); return FLOAT_NUMBER; }

                                                                        /* INTEGER NUMBER */
[0-9]+                                                                  { read_integer_number(); return INTEGER_NUMBER; }

%%

/* READ FLOAT NUMBER */
void read_float_number(void) {
        sscanf(yytext, "%lf", &yylval.float_number);
}

/* READ INTEGER NUMBER */
void read_integer_number(void) {
        sscanf(yytext, "%ld", &yylval.integer_number);
}

/* READ YYYYMMDD HHMM DATE */
void read_date_YYYYMMDD_HHMM(void) {

        /*  DATETIME STRUCT TM */
        struct tm dt;
        char buffer[80];

        /* READ VALUES */
        sscanf(yytext, "%4d%2d%2d %2d%2d", &dt.tm_year, &dt.tm_mon, &dt.tm_day, &dt.tm_hour, &dt.tm_min);

        /* NORMALIZE VALUES */
        dt.tm_year = dt.tm_year - 1900;         /* NORMALIZE YEAR */
        dt.tm_mon = dt.tm_mon - 1;              /* NORMALIZE MONTH */
        dt.tm_isdst = -1;                       /* NO INFORMATION ABOUT DST */
        mktime(&dt);                            /* NORMALIZE STRUCT TM */

        /* PRINT DATETIME */
        strftime(buffer, 80, "%c %z %Z\n", &dt);a
        printf("%s\n", buffer);

        /* COPY STRUCT TM TO YACC RETURN VALUE */
        memcpy(&dt, &yylval.datetime, sizeof(dt));

}

makefile
CCFLAGS = -std=c89
YFLAGS = -d     # Forces generation of y.tab.h
OBJS = readfile_lexer.o readfile_grammar.o
TARGET = readfile

readfile:               $(OBJS)
                        cc $(OBJS) -std=c89 -lm -o $(TARGET)

readfile_grammar.h readfile_grammar.o:  readfile_grammar.y
                                yacc $(YFLAGS) -oreadfile_grammar.c readfile_grammar.y
                                cc $(CCFLAGS) readfile_grammar.c

readfile_lexer.o:               readfile_lexer.l readfile_grammar.h
                                lex -oreadfile_lexer.c readfile_lexer.l
                                cc $(CCFLAGS) readfile_lexer.c

clean:
                                rm -f $(OBJS) readfile_grammar.[ch] readfile_lexer.c

While trying to compile the source code I get the mentioned error:
% make
yacc -d -oreadfile_grammar.c readfile_grammar.y
cc -std=c89 readfile_grammar.c
ld: error: undefined symbol: yylex
>>> referenced by readfile_grammar.c
>>>               /tmp/readfile_grammar-2d51ee.o:(yyparse)

ld: error: undefined symbol: yyerror
>>> referenced by readfile_grammar.c
>>>               /tmp/readfile_grammar-2d51ee.o:(yyparse)

ld: error: undefined symbol: yylex
>>> referenced by readfile_grammar.c
>>>               /tmp/readfile_grammar-2d51ee.o:(yyparse)

ld: error: undefined symbol: yyerror
>>> referenced by readfile_grammar.c
>>>               /tmp/readfile_grammar-2d51ee.o:(yyparse)
cc: error: linker command failed with exit code 1 (use -v to see invocation)
*** Error code 1

Stop.

A: In your makefile, in the command cc $(CCFLAGS) readfile_grammar.c add the -c option to specify that this is just one module and should be compiled to a .o file:
readfile_grammar.h readfile_grammar.o:  readfile_grammar.y
        yacc $(YFLAGS) -oreadfile_grammar.c readfile_grammar.y
        cc -c $(CCFLAGS) readfile_grammar.c

Otherwise cc assumes it's the entire program and tries to link it into an executable binary, which of course fails because it calls functions that are in other files.


text:
Q: How to solve the conflict with the color of dark solarized and some output? I really like the solarized and use it as the color scheme of my iTerm and Vim.
But recentlly, I start using Node.js. The problem has been bothering me for weeks.
The color of the result of mocha and pm2 seems the same the background of dark cheme,
I do not want to change to other color scheme.
So what should I do?
Thanks!!

A: Finally the setting of Contrast of iTerms fixed it for me.

A: This patch from iTerm2 Color Schemes leaves the rest of the Solarized Dark theme unchanged while patching the unfortunate issue with the background being set to bright-black.

A: If someone have the same problem, please use this patch for solarized.


text:
Q: What "fromRouter" option means on MongoDB aggregations? Recently i notice that a parameter fromRouter" : true exists on mongoDB aggregations. I search the MongoDB documentation and google for it, but i didn't found anything about it. Can anyone explain what this parameter is, or share any useful resource for it?
"op" : "command",
"ns" : "database_name.$cmd",
"command" : {
    "aggregate" : "collection",
    "pipeline" : [...erase them to make the post smaller...],
    "fromRouter" : true,
    "$queryOptions" : {
        "$readPreference" : {
            "mode" : "primary"
        }
    }
},
"ntoreturn" : 1,
"keyUpdates" : 0,
"numYield" : 440,
"lockStats" : {
    "timeLockedMicros" : {
        "r" : NumberLong(3106252),
        "w" : NumberLong(0)
    },
    "timeAcquiringMicros" : {
        "r" : NumberLong(5302577),
        "w" : NumberLong(6145)
    }
},

A: It just means that this is a sharded cluster and the aggregation is happening via a mongos (also known as a query router).  This is important for aggregations internally because it means that the output from multiple shards may need to be merged but it's not really relevant for most end users (you usually already know you are running in a sharded environment).


text:
Q: LaTex enumitem - controlling alignment of items by level I am using the enumitem package for a document that will have 6 levels and have the following settings already:
\usepackage[shortlabels]{enumitem}
\setlistdepth{6}
\setlist[enumerate,1]{label=\Alph*.}
\setlist[enumerate,2]{label=\arabic*.}
\setlist[enumerate,3]{label=\alph*.}
\setlist[enumerate,4]{label=(\arabic*)}
\setlist[enumerate,5]{label=(\alph*)}
\setlist[enumerate,6]{label=(\roman*)}
\renewlist{enumerate}{enumerate}{6}
\setlist[enumerate]{align=left, itemsep=1pt, parsep=3pt, topsep=1pt}

This is actually working as intended - up until I get to the 5th level.  At that point, the item indentation isn't sufficient and so the item label pushes the first line of the item paragraph farther to the right than the paragraph indent, causing the paragraph to not wrap around sufficiently, as in this case:

Notice that the spacing is fine for 6. a. (1) but when it gets to (a), (b) and then  (i) and (ii) the item indentation for (a) is insufficient.  That causes the wrapping to be inadequate.  In (b) you can also see that this results in the (i) label being misaligned and then the same issue as with the item indent occurs for that item level as well.
What is the proper setting to ensure that the item indent has the proper length for the (a) and (i) levels (Levels 5 and 6 in this case)?
Note that I saw this in the documentation:

But when I tried adding itemindent=! to the \setlist where I also set the alignment, topsep, etc. it did not change anything.  I confirmed I had the latest version of enumitem since the docs say that this itemindent=! option is new in Version 3.0.
Here is a complete working example:
\documentclass[letterpaper]{article}
\usepackage[
      height=9in,      % height of the text block
      width=7in,       % width of the text block
      top=78pt,        % distance of the text block from the top of the page
      headheight=36pt, % height for the header block
      headsep=12pt,    % distance from the header block to the text block
      heightrounded   % ensure an integer number of lines
      %,showframe       % show the main blocks
      ]{geometry}
\usepackage{enumerate}
\usepackage[default,scale=.9]{opensans}

\usepackage[shortlabels]{enumitem}
\setlistdepth{6}
\setlist[enumerate,1]{label=\Alph*.}
\setlist[enumerate,2]{label=\arabic*.}
\setlist[enumerate,3]{label=\alph*.}
\setlist[enumerate,4]{label=(\arabic*)}
\setlist[enumerate,5]{label=(\alph*)}
\setlist[enumerate,6]{label=(\roman*)}
\renewlist{enumerate}{enumerate}{6}
\setlist[enumerate]{align=left, itemsep=1pt, parsep=3pt, topsep=1pt, itemindent=!}

\begin{document}

\begin{enumerate}
\item Terms and Conditions

    \begin{enumerate}
    \item Vacancy Condition

        \begin{enumerate}
        \item \textbf{Description of Terms}

              \begin{enumerate}
              \item As used in this Vacancy Condition, the term building and the
                term vacant have the meanings set forth in (1)(a) and (1)(b)
                below:

                    \begin{enumerate}
                    \item When this policy is issued to a tenant, and with respect to
                      that tenant's interest in Covered Property, building means the
                      unit or suite rented or leased to the tenant. Such building is
                      vacant when it does not contain enough business personal
                      property to conduct customary operations.

                    \item When this policy is issued to the owner or general lessee of a
                      building, building means the entire building. Such building is
                      vacant unless at least 31\% of its total square footage is:

                          \begin{enumerate}
                          \item Rented to a lessee or sub-lessee and used by the lessee or
                            sub-lessee to conduct its customary operations; and/or

                          \item Used by the building owner to conduct customary operations.
                          \end{enumerate}

                    \end{enumerate}

              \end{enumerate}

        \end{enumerate}

    \end{enumerate}

\end{enumerate}

\end{document}

A: I added the specification leftmargin=*. Is it more like you want?
\documentclass[letterpaper]{article}
\usepackage[
      height=9in, % height of the text block
      width=7in, % width of the text block
      top=78pt, % distance of the text block from the top of the page
      headheight=36pt, % height for the header block
      headsep=12pt, % distance from the header block to the text block
      heightrounded % ensure an integer number of lines
      %,showframe % show the main blocks
      ]{geometry}
\usepackage{enumerate}
%\usepackage[default,scale=.9]{opensans}

\usepackage[shortlabels]{enumitem}
\setlistdepth{6}
\setlist[enumerate,1]{label=\Alph*.}
\setlist[enumerate,2]{label=\arabic*.}
\setlist[enumerate,3]{label=\alph*.}
\setlist[enumerate,4]{label=(\arabic*)}
\setlist[enumerate,5]{label=(\alph*)}
\setlist[enumerate,6]{label=(\roman*)}
\renewlist{enumerate}{enumerate}{6}
\setlist[enumerate]{align=left, itemsep=1pt, parsep=3pt, topsep=1pt, itemindent=!, leftmargin=*}

\begin{document}
\sffamily
\begin{enumerate}
\item Terms and Conditions

    \begin{enumerate}
    \item Vacancy Condition

        \begin{enumerate}
        \item \textbf{Description of Terms}

              \begin{enumerate}
              \item As used in this Vacancy Condition, the term building and the
                term vacant have the meanings set forth in (1)(a) and (1)(b)
                below:

                    \begin{enumerate}
                    \item When this policy is issued to a tenant, and with respect to
                      that tenant's interest in Covered Property, building means the
                      unit or suite rented or leased to the tenant. Such building is
                      vacant when it does not contain enough business personal
                      property to conduct customary operations.

                    \item When this policy is issued to the owner or general lessee of a
                      building, building means the entire building. Such building is
                      vacant unless at least 31\% of its total square footage is:

                          \begin{enumerate}
                          \item Rented to a lessee or sub-lessee and used by the lessee or
                            sub-lessee to conduct its customary operations; and/or

                          \item Used by the building owner to conduct customary operations.
                          \end{enumerate}

                    \end{enumerate}

              \end{enumerate}

        \end{enumerate}

    \end{enumerate}

\end{enumerate}

\end{document}


text:
Q: DbContext disposed when running parallel requests to repository After updating to ABP v3.0.0, I started getting DbContext disposed exception when running parallel requests to repository that create new UnitOfWork like this:
using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))

I looked in the source code and found some code in AsyncLocalCurrentUnitOfWorkProvider that I don't understand. When setting current uow, it sets property in wrapper:
private static readonly AsyncLocal<LocalUowWrapper> AsyncLocalUow = new AsyncLocal<LocalUowWrapper>();

private static void SetCurrentUow(IUnitOfWork value)
{
    lock (AsyncLocalUow)
    {
        if (value == null)
        {
            if (AsyncLocalUow.Value == null)
            {
                return;
            }

            if (AsyncLocalUow.Value.UnitOfWork?.Outer == null)
            {
                AsyncLocalUow.Value.UnitOfWork = null;
                AsyncLocalUow.Value = null;
                return;
            }

            AsyncLocalUow.Value.UnitOfWork = AsyncLocalUow.Value.UnitOfWork.Outer;
        }
        else
        {
            if (AsyncLocalUow.Value?.UnitOfWork == null)
            {
                if (AsyncLocalUow.Value != null)
                {
                    AsyncLocalUow.Value.UnitOfWork = value;
                }

                AsyncLocalUow.Value = new LocalUowWrapper(value);
                return;
            }

            value.Outer = AsyncLocalUow.Value.UnitOfWork;
            AsyncLocalUow.Value.UnitOfWork = value;
        }
    }
}

private class LocalUowWrapper
{
    public IUnitOfWork UnitOfWork { get; set; }

    public LocalUowWrapper(IUnitOfWork unitOfWork)
    {
        UnitOfWork = unitOfWork;
    }
}

That does not look thread-safe, as any thread can set new UnitOfWork and then dispose it.
Is it a bug? I can use my own implementation of ICurrentUnitOfWorkProvider, without wrapping, but I'm not sure if that is correct.
Update
I can't give an example with DbContext disposed exception, but here is one with null reference exception in repository.GetAll() method. I think it has the same reason.
namespace TestParallelEFRequest
{
    public class Ent1 : Entity<int> { public string Name { get; set; } }
    public class Ent2 : Entity<int> { public string Name { get; set; } }
    public class Ent3 : Entity<int> { public string Name { get; set; } }
    public class Ent4 : Entity<int> { public string Name { get; set; } }
    public class DomainStartEvent : EventData {}
    public class DBContext : AbpDbContext {
        public DBContext(): base("Default") {}
        public IDbSet<Ent1> Ent1 { get; set; }
        public IDbSet<Ent2> Ent2 { get; set; }
        public IDbSet<Ent3> Ent3 { get; set; }
        public IDbSet<Ent4> Ent4 { get; set; }
    }

    public class TestService : DomainService, IEventHandler<DomainStartEvent>
    {
        private readonly IRepository<Ent1> _rep1;
        private readonly IRepository<Ent2> _rep2;
        private readonly IRepository<Ent3> _rep3;
        private readonly IRepository<Ent4> _rep4;
        public TestService(IRepository<Ent1> rep1, IRepository<Ent2> rep2, IRepository<Ent3> rep3, IRepository<Ent4> rep4) {
                _rep1 = rep1;_rep2 = rep2;_rep3 = rep3;_rep4 = rep4;
        }

        Task HandleEntityes<T>(IRepository<T> rep, int i) where T : class, IEntity<int> {
            return Task.Run(() => {
                using (var uow = UnitOfWorkManager.Begin(TransactionScopeOption.RequiresNew)) {
                    Thread.Sleep(i); // Simulating work
                    rep.GetAll();    // <- Exception here
                }
            });
        }

        public void HandleEvent(DomainStartEvent eventData) {
            using (var uow = UnitOfWorkManager.Begin(TransactionScopeOption.RequiresNew)) {
                var t1 = HandleEntityes(_rep1, 10);
                var t2 = HandleEntityes(_rep2, 10);
                var t3 = HandleEntityes(_rep3, 10);
                var t4 = HandleEntityes(_rep4, 1000);
              Task.WaitAll(t1, t2, t3, t4);
            }
        }
    }

    [DependsOn(typeof(AbpEntityFrameworkModule))]
    public class ProgrammModule : AbpModule
    {
        public override void PreInitialize() { Configuration.DefaultNameOrConnectionString = "Default"; }
        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
            Database.SetInitializer<DBContext>(null);
        }
    }

    class Program {
        static void Main(string[] args) {
            using (var bootstrapper = AbpBootstrapper.Create<ProgrammModule>()) {
                bootstrapper.Initialize();
                bootstrapper.IocManager.Resolve<IEventBus>().Trigger(new DomainStartEvent());
                Console.ReadKey();
            }
        }
    }
}


text:
Q: How to insert data into the database file which is in the assets folder I have created a SQLite file and putted it on to assets folder. Now I am able to read the data from that file but I don't have any idea how to write to this database file. I need to take the user name and score and store that in to that database file. I searched on the web and on the SO also but there are examples for the normal database insertion.
Can any one tell me how to store the values into database file. I need to store the username and score. Just think this to as Strings and please give me a example for it.

A: You should not create database in the assets folder as we can only read data from assets folder.
Infact you should create the database in the default internal folder i.e data/data/[package-name]/databases   OR  you also can create your database in the sdcard and can perform read-write operation but of course it will not run if there is no sdcard.
The following is the code for creating databse in sdcard:-
    private SQLiteDatabase db;
    private static Context cntxt;

    public static File filename = null;
    public static String DATABASE_FILE_PATH_EXTERNAL = null;

    public DBHelper(Context context) {
            super(context, DATABASE_NAME, null,1);
            cntxt = context;
            try{
                try{
                    filename = Environment.getExternalStorageDirectory();
                }catch(Exception e){
                    Toast.makeText(DbHelper.cntxt, "Please Insert SD card To create Database", Toast.LENGTH_LONG).show();
                    Log.e("Log",e.getMessage(),e.fillInStackTrace());
                }

                DATABASE_FILE_PATH_EXTERNAL = filename.getAbsolutePath()+File.separator+DATABASE_NAME;

                //  db = SQLiteDatabase.openDatabase(DATABASE_FILE_PATH_EXTERNAL, null, SQLiteDatabase.OPEN_READWRITE + SQLiteDatabase.CREATE_IF_NECESSARY);
            }catch(Exception e){

                Log.e("Log",e.getMessage(),e.fillInStackTrace());
            }
        }

        @Override
        public synchronized SQLiteDatabase getWritableDatabase() {
            // TODO Auto-generated method stub
            try{
                db = SQLiteDatabase.openDatabase(DATABASE_FILE_PATH_EXTERNAL, null, SQLiteDatabase.OPEN_READWRITE + SQLiteDatabase.CREATE_IF_NECESSARY);
                try{
                    onCreate(db);
                }catch(Exception e){
                    Log.e("Log",e.getMessage(),e.fillInStackTrace());
                }
                return db;
            }catch(Exception e){
                Log.e("Log",e.getMessage(),e.fillInStackTrace());
                if(db!=null)
                    db.close();
            }
            return db;
        }// End of getWritableDatabase()

**Inserting  and Retrieving data from database:-**

public void insertIntoTable(String[] userName,int[] score)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();

        try {
            db.beginTransaction();
            for (int i = 0; i < beatID.length; i++) {
                cv.put("UserName",userName[i]);
                cv.put("Score",score[i]);

                db.insert("TableName", "UserName",
                        cv);
            }
            db.setTransactionSuccessful();
        } catch (Exception ex) {

        } finally {
            db.endTransaction();
            db.close();
        }
    }

public void getUserNamePswd(){
        Cursor c = null;
        SQLiteDatabase db = null;
        try{
            db = this.getReadableDatabase();
            c = db.rawQuery("Select UserName,Score from TableName",null);
            c.moveToFirst();
            String[] username = new String[c.getCount()];
            int[] score = new int[c.getCount()];
            int counter = 0;
            c.moveToFirst();
            while(!c.isAfterLast()){
            username[counter] = c.getString(0);
            score[counter] = c.getInt(1);
            c.moveToNext();
            counter++;
            }

        }catch(Exception e){
            Log.e("Log", e.getMessage(), e.fillInStackTrace());
            return null;
        }finally{
            c.close();
            db.close();
        }
    }

A: As the /asset directory is read only (because android .apk file is read-only) so you can't write anything in asset folder file, you have to first copy that sqlite database file into your application's internal storage /data/data/<package_name>/databases directory then you can modify your database file..

*

*Copy your pre-populated sqlite database file into data/data/<package_name>/databases directory,

*Open that database file (from /databases/ directory) in your sqlite database helper class..

*Perform insert, update or select operation on that database..

A: You need to copy database file from asset and paste in /data/data/''/databases/ folder
private static String DB_NAME = "QuotesData.db";
private static String DB_PATH = "/data/data/[PACKAGE NAME]/databases/";
private void copyDataBase() throws IOException {

        InputStream myInput = context.getAssets().open(DB_NAME);

        String outFileName = DB_PATH + DB_NAME;

        OutputStream myOutput = new FileOutputStream(outFileName);

        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }

        myOutput.flush();
        myOutput.close();
        myInput.close();

    }

In Above code : Replace [PACKAGE NAME ] with your package name.


text:
Q: Expected an identifier and instead saw 'import' (a reserved word) jshint I am getting following warning in vscode:

Expected an identifier and instead saw 'import' (a reserved word). (W024)jshint(W024)

My code is as following:
import {
    createRouter,
    createWebHistory
} from "@ionic/vue-router";

const routes = [
    {
        path: "/",
        component: () => import("../views/Home.vue")
    },
    {
        path: "/manufacturers",
        name: "Manufacturers",
        component: () => import("../views/Manufacturers.vue") // getting error in this import
    },
];

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
});

export default router;

A: JSHint can be configured to enable ES2015 (ES6) language features, which include the import keyword for modules, by setting esversion:
// .jshintrc
{
  "esversion": 6
}

or
// package.json
{
  "jshintConfig": {
    "esversion": 6
  }
}


text:
Q: HttpServletRequest in schedulers - Java Spring I have to get my servlet path dynamically for some actions. Following is my code to get object:
HttpServletRequest request = ( (ServletRequestAttributes) RequestContextHolder.getRequestAttributes() ).getRequest();
request.getSession().getServletContext();

This is working fine in application, but when i run this through Scheduler, it fails to get the correct  request.getSession().getServletContext();
Please suggest solution following is my schedule class.
import org.springframework.scheduling.annotation.Scheduled;

public class CronServices
{

/**
 * Send Reminders.
 * Daily at  AM
 */
@Scheduled( cron = "* */10 * * * ?" )
public void initReminders()
{
    EmailComponent emailComponent;
    emailComponent = new EmailComponent();
    emailComponent.sendReminders();
}

}


text:
Q: Create a new password for user in laravel how create new password with str_random and save in users table password?
example :
$newPassword = str_random(8);
    $userFind = User::all()->where('numberPhone', $request->phone);
    $userFind->password = hash::make($newPassword);

A: You can user faker to generate fake or dummy-data, find the DatabaseSeeder class inside your project folder on /database/seeds.
Then add this line if you're using Laravel version 7 , you have already a factory to create fake users, you can check for that inside the /database/factories you should have UserFactory.php file.
factory(App\User::class, 50)->create();

Now execute this command using the terminal to run the DatabaseSeeder:
php artisan db:seed

A: $newPassword = str_random(8);
$userFind = User::where('numberPhone', $request->phone)->first(); // assuming phone number is unique - get only one with first()
$userFind->password = Hash::make($newPassword); // you may need to check whether user exists before updating.
$userFind->save();


text:
Q: Codeigniter global variables in a core controller I am using $langs Variable in my Core Controller.
How to use Global Variables in Codeigniter? i'm very newbie on CI
My Controller Code is :
class MY_Controller extends CI_Controller{
  //global items
  var $langs;
  // construct
  public function __construct(){
    parent::__construct();
    global $title;
    $langs = array(
      'en' =>'English',
      'zh'  =>  '繁體中文',
      'zh_CN' =>  '簡體中文',
      'fr'  =>  'français',
      'de'  =>  'Deutsch',
      'ja'  =>  '日本語',
      'es'  =>  'Español',
      'pt'  =>  'Português',
      'ru'  =>  'Русский',
      'tr'  =>  'Türkçe',
      'kr'  =>  '한국어'
    );
  }

My View Code is :
<?
//display
var_dump($langs);
?>

A: class MY_Controller extends CI_Controller
{
    //global items
    public $langs;
    public $title;
    // construct
    public function __construct()
    {
        parent::__construct();

        $langs = array(
            'en' =>'English',
            'zh'  =>  '繁體中文',
            'zh_CN' =>  '簡體中文',
            'fr'  =>  'français',
            'de'  =>  'Deutsch',
            'ja'  =>  '日本語',
            'es'  =>  'Español',
            'pt'  =>  'Português',
            'ru'  =>  'Русский',
            'tr'  =>  'Türkçe',
            'kr'  =>  '한국어'
        );
        $this->langs = $langs;
    }
}

Use it in controllers that are extending MY_Controller as $this->title and $this->langs.
If you need it more widely available even if request controller doesn't extends MY_Controller, make own library with similar code and autoload it. Pay attention on making libraries. In docs it is well explained (check that Example_library).


text:
Q: Force fact-gathering on all hosts I'm sitting in front of a fairly complex Ansible project that we're using to set up our local development environments (multiple VMs) and there's one role that uses the facts gathered by Ansible to set up the /etc/hosts file on every VM. Unfortunately, when you want to run the playbook for one host only (using the -limit parameter) the facts from the other hosts are (obviously) missing.
Is there a way to force Ansible to gather facts on all hosts, even if you limit the playbook to one specific host?
We tried to add a play to the playbook to gather facts from all hosts, but of course that also gets limited to the one host given by the -limit parameter. If there'd be a way to force this play to run on all hosts before the other plays, that would be perfect.
I've googled a bit and found the solution with fact caching with redis, but since our playbook is used locally, I wanted to avoid the need for additional software. I know, it's not a big deal, but I was just looking for a "cleaner", Ansible-only solution and was wondering, if that would exist.

A: This still seems to be an issue without a clean solution here in 2016, but newer versions of Ansible offer a "jsonfile" fact caching backend, which seems to be a decent compromise to installing Redis locally just to address this need. Now I just fire off an ansible all -m setup before running a playbook with the --limit option. Good enough for jazz!
http://docs.ansible.com/ansible/playbooks_variables.html#fact-caching

A: Ansible version 2 introduced a clean, official way to do this using delegated facts (see: http://docs.ansible.com/ansible/latest/playbooks_delegation.html#delegated-facts).
when: hostvars[item]['ansible_default_ipv4'] is not defined is a check to ensure you don't check for facts in a host you already know the facts about
---
# This play will still work as intended if called with --limit "<host>" or --tags "some_tag"

- name: Hostfile generation
  hosts: all
  become: true

  pre_tasks:
    - name: Gather facts from ALL hosts (regardless of limit or tags)
      setup:
      delegate_to: "{{ item }}"
      delegate_facts: True
      when: hostvars[item]['ansible_default_ipv4'] is not defined
      with_items: "{{ groups['all'] }}"

  tasks:
    - template:
        src: "templates/hosts.j2"
        dest: "/etc/hosts"
      tags:
        - hostfile

     ...

A: In general the way to get facts for all hosts even when you don't want to run tasks on all hosts is to do something like this:
- hosts: all
  tasks: [ ]

But as you mentioned, the --limit parameter will limit what hosts this would be applied to.
I don't think there's a way to simply tell Ansible to ignore the --limit parameter on any plays.  However there may be another way to do what you want entirely within Ansible.
I haven't used it personally, but as of Ansible 1.8 fact caching is available. In a nutshell, with fact caching enabled Ansible will use a redis server to cache all the facts about hosts it encounters and you'll be able to reference them in subsequent playbooks:

With fact caching enabled, it is possible for machine in one group to reference variables about machines in the other group, despite the fact that they have not been communicated with in the current execution of /usr/bin/ansible-playbook.

A: You could modify your playbook to:
...
- hosts: "{{ limit_hosts|default('default_group') }}"
  tasks:
    ...
...

And when you run it, if some_var is not defined (normal state) then it will run on the default_group inventory group, BUT if you run it as:
ansible-playbook --extra-vars "limit_hosts=myHost" myplaybook.yml

Then it will only run on your myHost, but you could still have other sections with different hosts: .. declarations, for fact gathering, or anything else actually.


text: Q: Android auto response with pre-recorded voice? Is it possible to write an Android "application" that automatically (or manually on custom lock screen) responses the incoming phone call with the pre-recorded voice sound?


text:
Q: How to create xs:choice inside xs:all - (xsd:schema) I want to validate data as in below array:
input_array = array(
  "boy"=> array("boy_id"=>1),
   "first_name=>"First Name",
   "last_name"=>"Last Name"
);

Inside input_array first index can be replaced with girl array as
 "girl"=>array("girl_id"=>2)

I want to create xsd to validate information as below:
 <xs:element name="xml">
    <xs:complexType>
      <xs:all>
        <xs:element ref="boy" minOccurs="0"/>
        <xs:element ref="girl" minOccurs="0"/>
        <xs:element ref="first_name"/>
        <xs:element ref="last_name"/>
      </xs:all>
    </xs:complexType>
  </xs:element>

Problem - I want to make sure either boy or girl information is there, first_name and last_name will always be there, how can I put them (girl,boy) either as choice or option. I would prefer to use xs:all so that element order should not be a problem.
I refereed this link to use so as to try using choice inside xs:all but could not get it working. I would appreciate any response. Thank you.

A: In the article you referenced (http://www.w3.org/wiki/Needs_choice_inside_all)
they provide an example with substitution group. So, why not to use one?
Here's how it should look:
<xs:element name="xml">
  <xs:complexType>
    <xs:all>
      <xs:element ref="gender" minOccurs="1"/>
      <xs:element ref="first_name"/>
      <xs:element ref="last_name"/>
    </xs:all>
  </xs:complexType>
</xs:element>

<xs:element name="gender" abstract="true"/>
<xs:element name="boy" substitutionGroup="gender"> ... </xs:element>
<xs:element name="girl" substitutionGroup="gender"> ... </xs:element>

Specifically, I tried this full schema:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="xml">
    <xs:complexType>
      <xs:all>
        <xs:element ref="gender" minOccurs="1"/>
        <xs:element ref="first_name"/>
        <xs:element ref="last_name"/>
      </xs:all>
    </xs:complexType>
  </xs:element>

  <xs:element name="gender" abstract="true"/>
  <xs:element name="boy" substitutionGroup="gender"/>
  <xs:element name="girl" substitutionGroup="gender"/>

  <xs:element name="first_name" type="xs:string"/>
  <xs:element name="last_name" type="xs:string"/>
</xs:schema>

to validate this XML:
<?xml version="1.0" encoding="UTF-8"?>
<xml>
  <girl/>
  <first_name>Lara</first_name>
  <last_name>Croft</last_name>
</xml>

It worked! At that, if in place of <girl/> I specified <boy/>, it passed too,
but did not when there was neither <girl/> not <boy/> or any of them together.

A: Could you try this code?
<xsd:complexType name="column">
  <xsd:all>
    <xsd:element ref="gender" minOccurs="1"/>
    <xs:element name="firstname" type="xs:string"/>
    <xs:element name="lastname" type="xs:string"/>
  </xsd:all>
</xsd:complexType>

<xsd:element name="gender">
  <xsd:complexType>
   <xsd:choice>
     <xs:element name="boy" type="xs:integer" default="1"/>
     <xs:element name="girl" type="xs:integer" default="0"/>
   </xsd:choice>
  </xsd:complexType>
 </xsd:element>

A: The simplest approach is probably to rename boy_id and girl_id to gender (with an appropriate attribute value), as suggested by @herry.  If you don't want to do this (why not?) then your remaining options include:

*

*declare an abstract element gender_id, put it into the all-group, and declare boy_id and girl_id as being in its substitution group;

*rename the enclosing element from 'xml' to 'girl' or 'boy' to carry the information about whether you are dealing with a girl or a boy

There are doubtless others, some of which will feel idiomatic to Java programmers and some of which will feel idiomatic to XML users.


text:
Q: Error al pasar un valor al parámetro de una anotación: "Annotation attributes cannot have parameters" ¿Cómo puedo hacer para que una annotación (@interface) acepte como parámetros constantes estáticas?
En este caso tengo el siguiente código:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface prueba {
    String description() default "";
}

...y me gustaría poder aplicar un ResourceBundle aquí:
@prueba(description = com.prueba.constants.ConstantsStr.STR_PRUEBA_1)

...de la siguiente manera:
@prueba(description = resourceBundlePrueba.getString(com.prueba.constants.ConstantsStr.STR_PRUEBA_1)

Si al método le pongo parámetros, me sale el error:

Annotation attributes cannot have parameters

A: Primero que todo, los parámetros de una anotación pueden recibir como valores solo expresiones constantes. No puedes llamar a métodos para especificar el valor de un parámetro en una anotación, porque un método (en este caso resourceBundlePrueba.getString()) no es una expresión constante.
Entonces este llamado no es posible:
@prueba(description = resourceBundlePrueba.getString(com.prueba.constants.ConstantsStr.STR_PRUEBA_1))

Sí se pueden usar Nombres cualificados de la forma NombreTipo.Identificador que haga referencia a una variable constante, por ejemplo: ConstantsStr.STR_PRUEBA.
Asegúrate de que la constante estática ConstantsStr.STR_PRUEBA sea String, así puedes pasarle el valor directamente:
//Esto si es posible, mientras STR_PRUEBA_1 sea String
@prueba(description = ConstantsStr.STR_PRUEBA_1)


text:
Q: Vagrant/VirtualBox/Apache2 Strange Cache Behaviour I'm using Vagrant to run an Ubuntu powered VirtualBox with Apache2.
The webserver, among others, serves static files from my /vagrant directory.
This works well most of the time. But when I change an image on my shared folder and reload the website, the previous version of the image is served, but it's truncated.
It works if I delete the old picture first from my shared folder, refresh the website so the picture is NOT shown, then save the new file and reload the website again.
Does anyone knew about this problem? I don't have anything special installed, just Apache 2 with mod_rewrite and PHP with Mongo, APC Plugin, MongoDB as well as nodeJS with a bunch of scripts.

A: This has been driving me crazy! Thanks for posting this Philipp.
For those of you who have no idea how to do change the config file, here is what I did:
To find the file: $ sudo find -name "nginx.conf"
Mine was here: ./etc/nginx/nginx.conf
So I ran this to modify it: $ sudo nano ./etc/nginx/nginx.conf
Change the line that contains sendfile on; to sendfile off;
Don't forget to exit and vagrant reload!

A: This is old bug in VirtualBox (see: #819, #9069, #12597, #14920) where vboxvfs seems to have some problems with mmapped access to files which are synched.
This may happen when you edit the file outside of VM, and you expect to see the same change within the VM.
To workaround this problem, you need to disable the kernel sendfile support to deliver files to the client by disabling EnableSendfile option, either in httpd.conf or in vhosts file, e.g.
<Directory "/path-to-nfs-files">
  EnableSendfile Off
</Directory>

This is especially trouble for NFS or SMB mounted files. After the change reload the Apache.
Similar for Nginx (in nginx.conf), e.g.
sendfile off;

Other workaround is to remember to not edit the files on the host, or try to re-edit the same file, but within the VM.

Another workaround includes dropping the Linux pagecache, e.g.
echo 1 > /proc/sys/vm/drop_caches

Or to clear the caches every second (as per this post), try:
watch -n 1 $(sync; echo 1 > /proc/sys/vm/drop_caches)

Note: Number 1 stands for freeing pagecache, 2 for dentries and inodes, 3 for pagecache, dentries and inodes.

The above problem can be replicated by the following mmap-test program, see: mmap-problem.c.

A: I've got similar problem with VirtualBox/Docker/Nginx environment.
The decision with dropping Linux pagecache echo 1 > /proc/sys/vm/drop_caches works fine but looks awkward.
Also the directive sendfile off; in the nginx.conf didn't solve the problem and I tried to use it with expires off; directive together and it was successful.
So, my decision looks like
sendfile off;
expires off;

A: For anyone using Laravel 5, Barryvdh's Debugbar and browserSync via gulp.watch, you may get this error. I had exactly the same error because of how browser Sync was proxying my request.
If I viewed my dev server via:
http://127.0.0.1:3000/laravel/page I got the error
http://127.0.0.1/laravel/page error gone.
I've flagged it with our friends at browserSync, they do an awesome job. So, it's more of a reason than a solution, but rather than spend hours trying to fix it, test to see if this is your problem before wasting any more time.
This issue is also similar to the errors found in this article

A: Found the answer here:

JC,
What you're seeing is probably because the server serving the static files
  is using the "sendfile()" syscall, which is broken with the VirtualBox file
  system. You need to disable sendfile() usage in your server. For Apache:
EnableSendfile off
And for nginx:
  sendfile off;
Best,
  Mitchell

A: This was also responsible for strange behavior regarding CSS files in a CentOS/VirtualBox setup.
You could change the contents of a CSS file in the /vagrant folder, and the browser would show a Status of 200 (instead of a 304), meaning it knew the file was new.  But the contents wouldn't have changed.


text:
Q: Slideshow specific images Tictail frameweok I know how to implement a slideshow in the "Tictail-framework". That tag does fetch images from products and shows them in a slideshow. Is there any way of viewing only a few of these products? (like nr 3, 9 and 15) in Tictal? I'm asking here, because Tictail's support isn't the best I've seen.
I know how to achieve this by using an external js, but it seems like unneccesary if the native slideshow - tag can be used for this. Here is the documentation: https://tictail.com/docs/templates

A: You can get all images with
{{#all_images}}
    <img src="{{url-500}}" alt="{{title}}">
{{/all_images}}
with JS you could push all those images into an array and output your selection.


text:
Q: Для чего в OpenGL нужна функция glOrtho? Правильно ли я понимаю что glOrtho может пересчитывать координаты?
Я хочу разобрать эту часть кода:
glViewport(0,0,screenWidth, screenHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, screenWidth, 0, screenHeight, 0, 1);
glMatrixMode(GL_MODELVIEW);

После этого кода стало значения пикселей (X от 0 до windowWidth и Y от 0 до windowHeight). Но это не удобно для работы с 3D так? Наверное больше подходит для работы с 2D?

A: Когда вершины окажутся в пространстве вида, у них будет три пространственных координаты. Но экран у вас плоский, двумерный, и вы не можете взять и нарисовать трехмерную вершину на этом экране — вам нужно спроецировать эту трехмерную вершину на плоскость.
Мы можем сделать это самыми разными способами. Наиболее часто используют перспективную и ортографическую проекции.
Представьте себе рельсы. Они лежат параллельно друг другу. Но когда они находятся вдалеке, то нам кажется, что они пересекаются. Т. е. предметы, которые находятся далеко кажется нам меньше. Это перспективная проекция.
Ортографическая проекция работает иначе — она отображает каждую точку трехмерного пространства перпендикулярно плоскости. В частном случае, третья координата не учитывается и берутся просто координаты х и y вершин.

Перспективная проекция больше подходит для трехмерной графики, компьютерных игр и так далее, потому что так мы видим в реальной жизни. Ортографическая проекция чаще всего применяется в различных CAD системах, при черчении, в инженерной графике…
Так вот функция glOrtho как раз и задает матрицу ортографической проекции. Т. е. вы требуете от OpenGL, чтобы ваши вершины из пространства вида проецировались на плоскость с помощью ортографической проекции.

† К слову говоря, вы используете старую версию OpenGL. В новых версиях в core profile матрицы проекций нужно задавать самостоятельно.

A: Это легаси. https://www.khronos.org/opengl/wiki/Legacy_OpenGL
Нужна эта функция, чтобы старые программы продолжали работать.


text:
Q: python Non-block read file I want to read a file with non-block mode.
So i did like below
import fcntl
import os

fd = open("./filename", "r")
flag = fcntl.fcntl(fd.fileno(), fcntl.F_GETFD)
fcntl.fcntl(fd, fcntl.F_SETFD, flag | os.O_NONBLOCK)
flag = fcntl.fcntl(fd, fcntl.F_GETFD)
if flag & os.O_NONBLOCK:
    print "O_NONBLOCK!!"

But the value flag still represents 0.
Why..? i think i should be changed according to os.O_NONBLOCK
And of course, if i call fd.read(), it is blocked at read().

A: O_NONBLOCK is a status flag, not a descriptor flag. Therefore use F_SETFL to set File status flags, not F_SETFD, which is for setting File descriptor flags.
Also, be sure to pass an integer file descriptor as the first argument to fcntl.fcntl, not the Python file object. Thus use
f = open("/tmp/out", "r")
fd = f.fileno()
fcntl.fcntl(fd, fcntl.F_SETFL, flag | os.O_NONBLOCK)

rather than
fd = open("/tmp/out", "r")
...
fcntl.fcntl(fd, fcntl.F_SETFD, flag | os.O_NONBLOCK)
flag = fcntl.fcntl(fd, fcntl.F_GETFD)

import fcntl
import os

with open("/tmp/out", "r") as f:
    fd = f.fileno()
    flag = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, flag | os.O_NONBLOCK)
    flag = fcntl.fcntl(fd, fcntl.F_GETFL)
    if flag & os.O_NONBLOCK:
        print "O_NONBLOCK!!"

prints
O_NONBLOCK!!


text:
Q: PayPal - Full HTML payment form I've searched around the internet for at full paypal form. What i mean by this, is a form where you fill ind credit card information and stuff like thatk, and when you click the submit button, it goes to paypal and performs the payment.
I've found this form so far, but it dosn't have any credit card fields:
http://pastebin.com/1UbTanGk

A: Check out this basic credit card form I put together for PayPal years ago.  It's a basic shell, but it's fully functional and useful.
It does require Payments Pro in order to use it, though.


text:
Q: subset as for loop / if-statement I just started programming in R and I'm currently trying to do some exercises.
My task is it to write a subset for some csv dataset as a for-loop / if-statement.
The subset looks like this and is doing its job:
subset(data_sat_csv, Altitude <= 2000, Acronym)

And my try for a loop was like this:
for (i in 8:ncol(data_sat_csv)) {
  if(i > 2000){
    next
  }
    else(print(data_sat_csv$Acronym))

}

Instead of getting the same data as in the subset, it prints the whole column multiple times. So there should probably be a "break"-statement anywhere(?).
It should loop over the 8th column once and skip NA values.
Any suggestions on how to rewrite it so it works the same as the subset?
This is probably a minor issue but thanks in advance.

A: Absent a minimal reproducible example, we'll use the mtcars data to illustrate a solution for subsetting with a for() loop.
subset(mtcars,mpg > 30)

generates the following:
> subset(mtcars,mpg > 30)
                mpg cyl disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4 78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4 75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4 71.1  65 4.22 1.835 19.90  1  1    4    1
Lotus Europa   30.4   4 95.1 113 3.77 1.513 16.90  1  1    5    2

We set an output data frame to NULL so it doesn't disappear after the for() loop completes and its environment is recycled, and then write to it each time the condition in the if() statement is true, as we iterate from 1:nrow(mtcars).
The basic idea is that for each row in mtcars we check whether mpg > 30. If the comparison is TRUE, we write a row to the output data frame, resultData. We loop over the rows, not the columns in order to extract the rows that fulfill the same condition we used in subset().
resultData <- NULL
for(i in 1:nrow(mtcars)){
     if(mtcars[i,"mpg"] > 30) resultData <- rbind(resultData,data.frame(mtcars[i,]))
}
resultData

...and the result is:
> resultData
                mpg cyl disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4 78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4 75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4 71.1  65 4.22 1.835 19.90  1  1    4    1
Lotus Europa   30.4   4 95.1 113 3.77 1.513 16.90  1  1    5    2

If we want to include only certain columns in the output data frame, we can modify the rbind() function to write specific columns. For example, if we want to write only mpg and cyl, we'd use the following code:
resultData <- NULL
for(i in 1:nrow(mtcars)){
     if(mtcars[i,"mpg"] > 30) resultData <- rbind(resultData,data.frame(mtcars[i,c("mpg","cyl")]))
}
resultData

...and the output is:
> resultData
                mpg cyl
Fiat 128       32.4   4
Honda Civic    30.4   4
Toyota Corolla 33.9   4
Lotus Europa   30.4   4
>


text:
Q: A column with Check constraint that accepts only caps A to caps Z I have a column of varchar2(30) with not null and check constraint.
My problem is, I want that column to accept only caps A to caps Z only by using check constraint.  How do I do this?

A: CONSTRAINT check_column_name CHECK (REGEXP_LIKE(column-name, '^[A-Z]+$'));

Here's an sqlfiddle exemplifying it.


text:
Q: Filter by specific values in Pyspark DataFrame I have a crimes dataset and need to plot a monthly time series line chart of all crimes for the last 3 years (2019,2020,2021). My approach is to create a new dataframe where the count per month is the total count of incidents from 2019-202 and then plot that dataframe.
An example would be
enter image description here
The current table I've come up with is as below:

I know I would have to use an aggregated sum function but I'm new to this and unsure of an approach.
Please respond if you need more information!
I attempted to use multiple filters as in df.filter(...) along with .agg() but still am not able to get the syntax or approach correct.

A: Due to the distributed architecture of spark, the dataset rows are split across different worker nodes and partitions. Operations where computation of next row depends on output of previous row are trickier in spark.
First, partition the data by group. In your case, there is no such group, so introduce a dummy key with a constant value for all rows. Then partition by this key and order by required fields. In your case, first order by "year", then by "month". Now perform sum over this window to get running total:
import pyspark.sql.functions as F
from pyspark.sql import Window

df = spark.createDataFrame(data=[[2021, 12, 50],[2021, 11, 50],[2022, 2, 50],[2022, 1, 50],[2022, 10, 50]], schema=["year","month","count"])

df = df.withColumn("dummy_key", F.lit("0"))

w = Window.partitionBy("dummy_key").orderBy("year", "month")

df = df.withColumn("running_total", F.sum("count").over(w))

[Out]:
+----+-----+-----+---------+-------------+
|year|month|count|dummy_key|running_total|
+----+-----+-----+---------+-------------+
|2021|   11|   50|        0|           50|
|2021|   12|   50|        0|          100|
|2022|    1|   50|        0|          150|
|2022|    2|   50|        0|          200|
|2022|   10|   50|        0|          250|
+----+-----+-----+---------+-------------+


text:
Q: -eq and -ne give me the same results Why do the following two command, with the only difference the -eq and -ne operator give me my list of DCs?
Get-ADComputer -Filter {(operatingsystem -like "*server*") -AND
(PrimaryGroup -eq "CN=Domain Controllers,CN=Users,DC=domain,DC=com") }
-Property Name,PrimaryGroup

I'd expect this one to have everything, but domain controllers.
Get-ADComputer -Filter {(operatingsystem -like "*server*") -AND
(PrimaryGroup -ne "CN=Domain Controllers,CN=Users,DC=domain,DC=com") }
-Property Name,PrimaryGroup

If I run the equivalent against PrimaryGroupID instead of PrimaryGroup, it works as expected.

A: I actually get an error when trying both commands. Did a little digging and the filter was causing the problem. Had a quick look in ADSIEdit at a server object. It doesn't appear to have a attribute called "PrimaryGroup".
This was in a 2008 R2 AD running in 2008 R2 forest and domain functional levels.
As an aside, if you want a list of DC in a domain get-ADDomainController will do the job.
regards
Arcass

A: If you want to put one statement on separate lines, you need to put the backtick (`) at the end of the line to tell PowerShell that the statement continues on the next line. However, even then, you cannot split the filter on two different lines. So it should look something like this:
Get-ADComputer -Filter {(operatingsystem -like "*server*") -AND (PrimaryGroup -eq "CN=Domain Controllers,CN=Users,DC=example,DC=com") } `
    -Property Name,PrimaryGroup

As you've found, AD doesn't actually have an attribute called PrimaryGroup. That is a property that PowerShell exposes to you, which interprets the value in the primaryGroupId attribute for you.
The primaryGroupId attribute of any object has the Relative Identifier (RID) of the group. The RID is the last section of number in the SID, but the group also stores this value in its primaryGroupToken atrribute. So you can get this value like this:
$primaryGroupToken = (Get-ADGroup "Domain Controllers" -Properties primaryGroupToken).primaryGroupToken

PowerShell has to convert what you pass into the -Filter parameter into a proper LDAP query, so when you use PrimaryGroup in the filter, PowerShell is doing that for you.
However, doing that lookup is not really necessary in this case, because the Domain Controllers group is a built-in group and always has an RID of 516. So you can do what you're trying to do like this:
Get-ADComputer -Filter "operatingsystem -like '*server*' -AND PrimaryGroupId -eq 516" `
    -Property Name,PrimaryGroup


text:
Q: Can I put anything inside DL/DT/DDs? can I use definition lists just like unordered/ordered lists?
I mean insert DIVs any anything I want inside DT or DD?

    ...

    ...

Do any browsers, or search engines complain?

A: As of December 2017 according to HTML 5.2 Specification, you can now add a single nested
 tag inside a
 tag, I assume for styling purposes:
https://www.w3.org/TR/html52/grouping-content.html#the-dl-element

Content model:
Either: Zero or more groups each consisting of one or more dt elements followed by one or more dd elements, optionally intermixed with script-supporting elements.
Or: One or more div elements, optionally intermixed with script-supporting elements.

A: Updated answer based on comments:
This was originally answered in 2011 for HTML 4, but the answer is different for HTML5:

dt
Flow content, but with no header, footer, sectioning content, or heading content descendants.
dd
Flow content.

*

*dt element reference on W3C

*dd element reference on W3C

Original answer:
DT elements should contain inline content.
DD elements should contain block-level content.

Definition lists vary only slightly
from other types of lists in that list
items consist of two parts: a term and
a description. The term is given by
the DT element and is restricted to
inline content. The description is
given with a DD element that contains
block-level content.
Source: W3C

This question is also an interesting read: Why use definition lists (DL,DD,DT) tags for HTML forms instead of tables?

A: Inside a DL you can only put DT and DD tags. A DT tag is an inline tag, so you should not put block elements in it. A DD tag can contain basically anything you want, it's a flow content tag.


text:
Q: plabic graphs up to "homotopy" and how that relates to homeomorphisms that keep rotations around vertices intact. I am currently trying to understand the paper Total positivity, Grassmannians, and networks. In this paper a plabic graphs $G$ is defined as planar graph drawn inside a disk and considered "up to homotopy". On the boundary of that disk lie $n$ vertices labeled $b_1, ... , b_n$ in clockwise order. All other vertices are strictly inside the disk, and colerd black or white. Multiple edges as well as loops are allowed, and all $b_i$ are requiered to be incident with exactly one internal vertex.
This may already be wrong, but i interpret the boundary of the disk belonging to $G$. That means, viewed as a graph in the plane, the outer face of $G$ is bounded by the cycle $b_1b_2...b_nb_1$.
Now i have multiple Questions:

*

*What should a homotopy be in this context ? Is it a homotopy $f_t:G \to \mathbb{R}^2, t \in [0,1]$, such that all $f_t$ are homeomorphisms onto their image (the concept of homotopy is new to me, but i think this is usually called an isotopy) and $f_0$ is just the inclusion ?

*Suppose 1. is correct, can such an isotopy be covered by an isotopy $F_t: \mathbb{R}^2 \to \mathbb{R}^2$ in the sense that ${F_t}_{|G} = f_t$ for all $t$ and $F_0 = id$ ? Are there nessesary or sufficient conditions ?

To formulate my last Question i should first give some background:
We can order the edges around a vertex $v$ of $G$ clockwise (cf. Graphs on Surfaces chapter 3.2 [sadly i couldnt find a link to a pdf...]): Put a simple closed polygonal curve $C$ around $v$ that intersects all its edges. Every such edge has a first intersection with $C$ when we pass through it starting at $v$. It turns out that the clockwise order of those intersection points does not depend on $C$, so we can order the edges around $v$ acordingly. Such an ordering is usually called the rotation around $v$.
An isotopy as in 1. should preserve rotations. In fact after making some adjustments (we dont assume $G$ to be piecewise linear), the proof given in Simplest proof that cyclic ordering of edges is preserved under planar graph homotopy? should hold.
One can also look at what a homeomorphism $\psi:\mathbb{R}^2 \to \mathbb{R}^2$ can do to such an rotation. Here is what i came up with: Consider a plane $k$-star $S$ (a graph consisting of a central vertex, with $k$ leaves), and assume $k \geq 3$. Then the rotation around the center $z$ of $S$ can at worst be reversed by $\psi$ (here we identify $S$ with its image under $\psi$). Now if $\psi$ preserves the rotation of $z$, then it will also preserve the rotation around the center of any other plane $l$-star, where $l$ is arbitrary. We can thus speak of homeomorphisms of the plane that preserve rotations.

*If 2. is true, then $F_1$ should be a homeomorphism of the plane that preserves rotations (Note that $G$ does contain vertices of degree at least $3$ and we can view them as $k$-stars). Conversely, if we start with such an homeomorphism $F_1$, is there an isotopy $F_t:\mathbb{R}^2 \to \mathbb{R}^2, t \in [0,1]$, with $F_0 = id$ ?


text:
Q: 2 monitors, 1 TV mirroring either one. TV won't display signal when plugged into DVI port. I'm trying to get 3 monitors working on my GeForce GTX 560Ti graphics card on Vista 64-bit. I am aware that I can't run 3 displays on this card. That's fine because either monitor and my TV could be a mirror image. I have one primary monitor on a DVI port, and I have a splitter on the second DVI port. The splitter is connected to my second monitor and my TV with a HDMI adapter. The TV will not work when connected into the DVI port, even if I unplug my secondary monitor. The TV only will show an image if it's connected into the HDMI mini port on my graphics card. I can't split my primary and secondary monitor obviously.
Any ideas what I'm doing wrong, or how I can set this up?


text:
Q: Processor with 2 incoming edges - When returning false on one edge, keep re-processing from same edge and never process new items on other edge I'm asking for a confirmation to my assumption about the tryProcess() logic.
In detail how the return value (true/false) influence the DAG workflow on a processor with 2 incoming edges with no priority specified.
My assumption is that if the processor have incoming items for both edges, and one tryProcess() return false, the other edge will be processed (if more incoming items are available on such edge).
Alternating incoming items depending on which edge stop processing and which accept them.
Problem
Sometimes happens that one processor instance blocks on tryProcess(#0) that always returns false (because we expect to process a new item from other edge).
tryProcess(#0) is called repetedly and tryProcess(#1) is never called.
I'm sure that the completeEdge() is never called on the processor neither for #0 nor #1 edge, so I expect there are more items to process from edge #1.
This happens usually after running the same Job multiple times.
To better explain the question, this is my use case:
Use Case
My datamodel is composed by following object

*

*A: Object identified by "ida" attribute

*B: Object identified by "idb" attribute. It has a reference to A using "ida" value

*AB: Object that couples B object and its referenced A object

I need to match B objects with proper referenced A object and emit a couple of them.
I have a DAG with this setup:
Vertices

*

*S-A: Source items of type "A" (localParallelism(1), emits A objects sorted by "ida" attribute)

*S-B: Source items of type "B" (localParallelism(1), emits B objects sorted by referenced "ida" attribute)

*C-AB: Processor that matches B objects with referenced A object (emits AB objects)

Connections

*

*S-A -> C-AB : incoming edge #0 (no priority specified, partitioned by "ida" attribute)

*S-B -> C-AB : incoming edge #1 (no priority specified, partitioned by reference to "ida" attribute)

The environment is composed by an hazelcast jet cluster with 2 nodes.
Logics
The C-AB processor get the first "A" object (from edge #0) and keep it until all "B" objects related to that "A" object are processed.
If it receives another "A" object it return false in tryProcess(#0).
While it receives "B" objects (from edge #1) which match to current "A", it emits "AB".
When the processor receives a "B" object with a reference with a next "A" object, it discards current "A" and waits for the next one.
If it receives "B" objects before having the referenced "A" object, wait for the proper "A" to match returning false in tryProcess(#1) if a new "B" is received.
This should work because S-A and S-B emits properly sorted objects and edges are properly partitioned to send objects with same "ida" values to the same processor.

A:
My assumption is that if the processor have incoming items for both edges, and one tryProcess() return false, the other edge will be processed (if more incoming items are available on such edge).

This assumption is false. The processor's behavior is equivalent to
for (Object item : inbox) process(item);

but implemented with cooperative multithreading, which is why this loop must be able to "suspend" itself. We achieve suspension by letting tryProcess() return false.
The execution engine always resumes the processor where it left off and won't try to process any other items until the inbox is clear. The inbox itself contains a batch of items taken from an input queue, not all the items the edge will transfer during the entire job.
The only mechanism Jet offers to solve co-dependence between edges is edge priority. If you need something more fine-grained than that, your processor should accept all the items and buffer them internally until your progress condition is met.


text:
Q: Deriving median from grouped frequencies in R I have the following example table where I am required to find the median age of a herd of animals. Not only does it have a 0, it is also has a grouped frequency of animals for a given age.
library(tidyverse)
a<-data.frame(Age=c(0,1,2,3,4,5,6,7,8,9),
              Individuals=c(3655,2535,898,235,559,265,258,3659,7895,3655))
a%>%summarise(Age=as.numeric(Age),
          Median=sort(as.numeric(Age)*Persons/sum(Individuals)))

I understand that the standard median() option does not work. I tried to be clever and attempted something like: median(rep(a$Age, a$Individuals)), but the memory consumption was too much. Besides, I think it will fail with a larger dataset.

A: You could be abit clever and do:
a %>%
  arrange(Age) %>%
  summarise(median = Age[findInterval(sum(Individuals)/2, cumsum(Individuals)) + 1])

  median
1      7

A: You can uncount the original data frame and then use the standard median function.
a %>% uncount(Individuals) %>% summarise(Median=median(Age))
  Median
1      7

And to check:
> sum(a$Individuals)/2
[1] 11807
> sum(a$Individuals[1:7])
[1] 8405
> sum(a$Individuals[1:8])
[1] 12064

All good.


text:
Q: How do I show a Spinner while my React app is loading? Is it possible to show a Spinner while my Word add-in (react app) is loading?
Obviously to use a Spinner you need to compile a React app, so I guess another way of stating the question is: is there a standalone version of the fabric Spinner?

A: I think what you need is fabric core.
https://developer.microsoft.com/en-us/fabric#/get-started#core
https://github.com/OfficeDev/office-ui-fabric-core
If it's not there, then there is no standalone spinner and you need to open an issue according to them.

A: Since React is not loaded yet, I would personally within the
 Add the recommended CSS/HTML. Once React components gets loaded (Downloaded), it will automatically replace the "root" contents.
For example:

     You need to enable JavaScript to run this app.

Your index.tsx would just be:
ReactDOM.render(
  <App />,
  document.getElementById('root') as HTMLElement
);


text:
Q: How can I gensym when writing a compiler in Kanren? I'm writing a compiler from an esolang to WebAssembly, using CHICKEN Scheme's miniKanren. My compiler already works somewhat, but I'd like to extend it with support for named local registers and I'm not sure how to proceed.
CHICKEN has a gensym with the following non-relational behavior:
#;1> (gensym)
g18
#;2> (gensym "asdf")
asdf19
#;3> (gensym 'asdf)
asdf20

It would be nice if I could generate semi-readable registers in miniKanren. WebAssembly text tools usually want named registers to start with "$", as well. Given these constraints, I presumed that I could hack up a register-naming relation using gensym, symbolo, and project, but I'm not sure whether that is a practical solution. I also presume that I could write a custom walker against the underlying µKanren API, but that goes beyond portable miniKanren.
Is there a standard solution for this?
My compiler source is available, but likely the only relevant part is my current hack with project and little-endian->number for numbered registers:
; The successor function.
; Nat <-> Nat
(define (succ° n m) (+o n (build-num 1) m))

; A prelude which loads the given number of local params onto the stack.
; Nat <-> WAT Insts
(define (prelude° plen prelude)
  (conde
    ((zeroo plen) (== prelude '()))
    ((fresh (len lude) (succ° len plen) (prelude° len lude)
            (project (len) (appendo lude `((local.get ,(little-endian->number len))) prelude))))))


text:
Q: On newly published. Could not load file or assembly 'mvcappname' or one of its dependencies. Access is denied Starting a couple of days ago any MVC project that I publish returns the below error.
I'm publishing to IIS8 on Server 2012R2 on our LAN. All existed sites work fine. The projects build and run fine on my develop pc. If I publish a project that I haven't changed to a new site I get the same error. If I overwrite an existing site I get the error as well. The contents of a working site and a nonworking appear to be the same.
Server Error in '/mvcappname' Application.
Could not load file or assembly 'RSStatus' or one of its dependencies. Access is denied.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.FileLoadException: Could not load file or assembly 'mvcappname' or one of its dependencies. Access is denied.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Assembly Load Trace: The following information can be helpful to determine why the assembly 'mvcappname' could not be loaded.

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

Stack Trace:
[FileLoadException: Could not load file or assembly 'mvcappname' or one of its dependencies. Access is denied.]
   System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
   System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +232
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +113
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +23
   System.Reflection.Assembly.Load(String assemblyString) +35
# System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +49

[ConfigurationErrorsException: Could not load file or assembly 'mvcappname' or one of its dependencies. Access is denied.]
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +762
   System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +259
   System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +167
   System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +238
   System.Web.Compilation.BuildManager.GetPreStartInitMethodsFromReferencedAssemblies() +78
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +334
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +178
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +746

# [HttpException (0x80004005): Could not load file or assembly 'mvcappname' or one of its dependencies. Access is denied.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +552
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +122
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +737

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.8.4494.0

I've checked the user permissions of several existing and new sites and they all seem to match. I have restarted the server as well as my pc.
If I copy the 'site name dll' from a working site to a non working site then I can login to the site. I need help tracking this down. I'm told nothing has changed on the server. I am up to date with vs2022.
Thanks for any help.

A: ThreatLocker was installed on the server last week. It locks files if the hash value changes. I found out the hard way.


text:
Q: How to get exact control over the form of interactions using `lm`? df <- data.frame(y = rnorm(10), x = rnorm(10), z = sample(c("a","b"), size = 10, replace = TRUE))

Using the * operator gives me a regression of y on 1, 1[z = b], x, 1[z=b]x.
> lm(data = df, y ~ as.factor(z)*x)

Call:
lm(formula = y ~ as.factor(z) * x, data = df)

Coefficients:
    (Intercept)    as.factor(z)b                x  as.factor(z)b:x
        -0.2351           0.1524           0.2309          -0.2699

I would like to regress y on 1[z = a], 1[z=a]x, 1[z=b], 1[z=b]x (with no constant term).
This regression will produce the same fitted values as the one above, but the interpretation of the coefficients is different, and preferable for my use case.
How can I specify the formula to do this in a single regression? I realize that I could run two separate regressions among the subsamples with z = a and z = b, but I don't want to do this.
I have tried explicitly removing the intercept, which gets me part of the way to what I want, but the specification still has a base x term and an interaction x term, whereas I want two interaction x terms.
> lm(data = df, y ~ 0 + as.factor(z)*x)

Call:
lm(formula = y ~ 0 + as.factor(z) * x, data = df)

Coefficients:
  as.factor(z)a    as.factor(z)b                x  as.factor(z)b:x
       -0.23515         -0.08275          0.23088         -0.26992


text:
Q: Laravel Echo Server giving Error Unhandled error event: Error: connect ECONNREFUSED i am trying to install Laravel Echo Server on Laravel 5.5 with the help of thie Article
https://medium.com/@dennissmink/laravel-echo-server-how-to-24d5778ece8b
All things is going right but when i
laravel-echo-server start

Error comes with
[ioredis] Unhandled error event: Error: connect ECONNREFUSED 127.0.0.1:6379
at Object._errnoException (util.js:992:11)
at _exceptionWithHostPort (util.js:1014:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1186:14)

i install laravel 5.6 but still i face the same error
Thanks in advance who can guide me how can i handle this error

A: Seems like Redis is not installed or the Redis server is not running.

*

*Download and install the server from https://redis.io/

*And then run the service with "redis-server".

After that you can smoothly run "laravel-echo-server start"

A: make sure that redis listen on 127.0.0.1:6379.
look at /etc/redis/redis.conf, the line where is indicated "bind ....". make sure it's "bind 127.0.0.1" otherwise go to your laravel-echo-server.json and change databaseConfig: {redis: {port: "6379", host: "..."}}.
"..." indicating what is marked in redis.conf

A: Make sure you have install radis server

sudo apt install redis-server


text:
Q: Maven Spring MVC : Background image not recognising I am working on a spring mvc maven project, and here is my file structure :
[1]: https://i.stack.imgur.com/hSW66.png
 body  {
        background: url("/WEB-INF/Images/Image/tests.jpg") no-repeat center center fixed;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
    }

This is my css to display the background image. But for some reason, the image is not getting displayed. Please help.

A: you must tell spring what path to access static resources in the xml config
<mvc:resources location="/resources/" mapping="/res/**"></mvc:resources>
"resources" is the folder in the project, "res" is the request mapping


text:
Q: UICollectionView custom cell layout I have a UICollectionView and I'm trying customize it a little.
Here's what I want:

Here's what I have:

I thought implementing sizeForItemAtIndexPath from UICollectionViewDelegate would be enough.
Here's what I'm doing:
- I returning half of the screen's width for all the cell's widths
- For the first and third cells I'm returning a height of 50
- For the second cell I'm returning a height of 100.
What am I doing wrong?

A: There is no way to do that with simple UICollectionViewDelegateFlowLayout methods. You have subclass from UICollectionViewFlowLayout.
Here is very dirty example how you can do this
@interface CVFlowLayout1 : UICollectionViewFlowLayout

@property (nonatomic, strong) NSDictionary *layoutInfo;

@end

@implementation CVFlowLayout1

- (instancetype)init
{
    if (self = [super init])
    {
        self.minimumLineSpacing = 0;
        self.minimumInteritemSpacing = 0;
    }
    return self;
}

- (void)prepareLayout
{
    NSMutableDictionary *newLayoutInfo = [NSMutableDictionary dictionary];
    NSMutableDictionary *cellLayoutInfo = [NSMutableDictionary dictionary];

    NSInteger sectionCount = [self.collectionView numberOfSections];
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];

    for (NSInteger section = 0; section < sectionCount; section++) {
        NSInteger itemCount = [self.collectionView numberOfItemsInSection:section];

        for (NSInteger item = 0; item < itemCount; item++) {
            indexPath = [NSIndexPath indexPathForItem:item inSection:section];

            UICollectionViewLayoutAttributes *itemAttributes =
            [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
            itemAttributes.frame = CGRectMake(item == 1 ? [UIScreen mainScreen].bounds.size.width/2.0 : 0, section == 0 ? 0 : 50, [UIScreen mainScreen].bounds.size.width/2.0, item == 1 ? 100 : 50);

            cellLayoutInfo[indexPath] = itemAttributes;
        }
    }

    newLayoutInfo[@"Cell"] = cellLayoutInfo;

    self.layoutInfo = newLayoutInfo;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return self.layoutInfo[@"Cell"][indexPath];
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSMutableArray *allAttributes = [NSMutableArray arrayWithCapacity:self.layoutInfo.count];

    [self.layoutInfo enumerateKeysAndObjectsUsingBlock:^(NSString *elementIdentifier,
                                                         NSDictionary *elementsInfo,
                                                         BOOL *stop) {
        [elementsInfo enumerateKeysAndObjectsUsingBlock:^(NSIndexPath *indexPath,
                                                          UICollectionViewLayoutAttributes *attributes,
                                                          BOOL *innerStop) {
            if (CGRectIntersectsRect(rect, attributes.frame)) {
                [allAttributes addObject:attributes];
            }
        }];
    }];

    return allAttributes;
}

@end

just set instance of that class to your collectionView.flowLayout property
CVFlowLayout1 *layout = [[CVFlowLayout1 alloc] init];
[_collectionView setCollectionViewLayout:layout];


text:
Q: UITextView delegate class crashes on clicking the textview?! What's going on? So I saw this question: How do you connect the "delegate" outlet of a UITextView to a class that implements UITextViewDelegate protocol?
My problem is similar to what booboo is describing in the second response (not the one marked as the answer.)
I have a MyViewController which implements UITextViewDelegate. In interface builder for the nib, inside the view I have selected the TextView and assigned it's delegate to the File Owner (which is MyViewController.)
MyViewController has implemented
- (void)textViewDidBeginEditing:(UITextView *)textView
{
NSLog(@"TextView EDIT %@",textView);
}

Every single time I test my app though, as soon as I click on the TextView I get an EXC_BAD_ACCESS crash. If I remove the delegate link in IB then the keyboard pops up fine.
I have also tried creating an IBOutlet UITextView to the textview inside MyViewController and linking the TextView to this IBOutlet in the File Owner. In the viewDidLoad then I assign:
myDescriptionTextField.delegate = self;

But this also results in the same issue of an EXC_BAD_ACCESS as soon as I click the TextView.
Inside XCODE at the top when it crashes the stack trace(i think this is what it is ?) of where it crashes says:
objc_msgSend
??
-[UIResponder becomeFirstResponder]
-[UITextView becomeFirstResponder]
-[UITextInteractionAssistant setFirstResponderIfNecessary]

... etc?
Does this help? I'm so lost on what this issue is? Everything seems linked correctly.

A: I would check how the MyViewController object is created and managed (how you keep the object in your application). It is possible that while your UITextView exists as it becomes a subview of one of your UIView object (addSubview retains the subview), the MyViewController object itself is released from the memory after you build up your view hierarchy.
myDescriptionTextField.delegate = self;

does not retain self, as retaining a delegate may cause a problem of reference cycles.
Check this, and if it doesn't solve the problem try debugging with NSZombieEnabled because it will tell you where exactly you make a reference to an invalid object.

A: Also I got your problem!
I solve by passing weak delegate instead of self
__weak typeof(self) weakSelf = self;

than use weakSelf !!


text:
Q: Map loads incorrectly Leaflet with React I've tried to use "leaflet" && "react-leaflet", but in both cases map displays like this. I can interact with this map, but map pieces showing incorrectly, with distance.
Looks like not all map pieces loads, or maybe incorrect css styles.
PLease check this code:
import React, { useState, useEffect }  from "react";
import styled from "styled-components";
import ScrollHandler from "../../components/ScrollHandler";
import SectionWipes from "../../components/SectionWipesComponent/SectionWipes";
import "./BodyHomePage.css";
import L, { LatLngExpression } from 'leaflet';

function BodyHomePage()
{
    const _isScrolled = ScrollHandler();
    const position: LatLngExpression = [51.505, -0.09];
    const [isMapCreated, setCount] = useState(false);

    useEffect(() => {
            if(!isMapCreated)
            {
                const map = L.map('map').setView(position, 13);

                L.tileLayer('https://api.maptiler.com/maps/basic/{z}/{x}/{y}.png?key=L7jWH8UlPu3enKseP3Nw', {
                attribution: '© OpenStreetMap contributors',
                }).addTo(map);

                L.marker(position)
                .addTo(map)
                .bindPopup('A pretty CSS3 popup.
 Easily customizable.');
                setCount(true);
        }
      });

    return(

            </StyledDiv>
            <SectionWipes/>


text:
Q: bash update huge csv file with values from another large csv file I need to update selected rows of huge csv file (20M rows) with data from another big csv file (30K rows),
File to be updated is 1.csv

1120120031,55121
1120127295,55115
6135062894,55121
6135063011,55215
4136723818,55215
6134857289,55215
4430258714,55121

Updating file is 2.csv

112012 ,55615
6135062,55414
6135063,55514
995707 ,55721

Such as 1_MOD.csv

1120120031,55621
1120127295,55615
6135062894,55421
6135063011,55515
4136723818,55215
6134857289,55215
4430258714,55121

Modifications:

*

*if $1 in 2.csv matches  substring of $1 in 1.csv (rows 1 & 2) then
update $2 in 1.csv as per 3rd char in $2 of matched row 2.csv;

*Match the Maximum size of strings (rows 3 & 4);

*Unmatched rows remain unchanged (rows 5 to 7).

So far I managed to test sed in while loop, but script will take about 31 days to complete. I believe there is a better way, such as awk file 2.csv in Array and update 1.csv with that array, something that I could not do as my Awk knowledge is limited
Thanks

A: Using awk, reading in 2.csv, and using the first field as a pattern.
BEGIN {
    FS = " *, *";
    OFS = ",";
}
NR==FNR {
    # Ensure there are no special characters in $1
    if ($1 ~ /^[[:digit:]]+$/)
        a[$1] = substr($2, 3, 1);
    next;
} {
    for (n in a)
        if ($1 ~ "^"n) {
            $2 = substr($2, 1, 2) a[n] substr($2, 4, length($2) - 3);
            break;
        }
} 1


text:
Q: Speed at the perihelion Hale Bopp has a period of 2400 days, with a mean distance from the sun at 174 AU and 1AU away in perihelion and 357 AU away in aphelion, what is its speed at the perihelion?
what formulas do you need in order to get this? We have not even tackled kinetic and potential energy in class but that was the topic i found when i searched it up

A: Given the numbers you quoted, you can easily calculate(*) the semimajor axis $a$ and the semiminor axis $b$.  From these, you should know that the total area of the ellipse that the comet follows is $A = \pi\, a\, b$.  Now, Kepler's second law says that the rate at which area is swept out by the line between the Sun and the comet is constant.  We can calculate the rate over an entire period $P$ of the comet:
\begin{equation}
  \frac{dA}{dt} = \frac{\pi\, a\, b} {P}.
\end{equation}
Again, this quantity is constant, no matter whether it's over some infinitesimal amount of time, or the whole orbit.  Now, at perihelion (or aphelion), there's no radial motion — it's all angular.  So if the comet moves some angle $d\theta$ while it's at radius $r$, the area it sweeps out is $dA = \frac{1}{2} r^2\, d\theta$.  But we also know that the velocity is just $r\, d\theta/dt$, so we have
\begin{equation}
  \frac{dA}{dt} = \frac{1}{2} r^2 \frac{d\theta}{dt} = \frac{1}{2}r\, v.
\end{equation}
You know what $r$ is, so just solve for $v$, and you've got your answer.
The Wikipedia link I gave has some more details about these steps, if you're wondering.

(*) The semimajor axis is the (arithmetic) mean of the distance at perihelion $r_\mathrm{per}$ and the distance at aphelion $r_\mathrm{ap}$:
\begin{equation}
  a = \frac{r_\mathrm{per} + r_\mathrm{ap}} {2}.
\end{equation}
Meanwhile, the semiminor axis is the geometric mean of those distances:
\begin{equation}
  b = \sqrt{r_\mathrm{per}\, r_\mathrm{ap}}.
\end{equation}


text:
Q: Is a mailto URL with slashes still valid? I am using a subclassed Django URLField to perform some validation on clicked URLs. I added mailto as one of the supported URLValidator default_validators:
class MyURLField(forms.URLField):
    default_validators = [
        validators.URLValidator(
            schemes=['http', 'https', 'ftp', 'ftps', 'mailto']
        )
    ]

class MyForm(forms.Form):
    url = MyURLField(required=True)

form = MyForm({'url': 'mailto:test@example.com'})
if not form.is_valid():
    raise Exception()

clean_url = form.cleaned_data['url']
print(clean_url)  # this prints 'mailto://test@example.com'

Is a mailto URL still valid with the two extra protocol slashes?
mailto:test@example.com versus mailto://test@example.com (what Django produces)

A: Django has an EmailField so if you want to store email addresses, or even use them in forms, use these fields because you get the built-in validation and don't have to hack anything like you're going to have to with your approach.
In your models you'd do;
class MyModel(models.Model):

    email = models.EmailField(
        verbose_name=_('Email'),
        max_length=255,
        unique=True,
        db_index=True
    )

In your forms it's very similar;
class MyForm(forms.ModelForm):

    email = forms.EmailField(
        label=_("Email")
    )

And then this becomes a mailto URL when you output it in a template etc;
<a href="mailto:{{ object.email }}">
    {{ object.email }}
</a>


text:
Q: golang - library/package that returns json string from http request Is there any library/package that returns the json string received in response to an http request. It's pretty straightforward, so I can write my own, but would prefer existing/tested code over reinventing the wheel.
Currently, I have:
func getJsonStr(url string) ([]byte, error) {
    resp, err := http.Get(url)
    if err != nil {
        return []byte{0}, err
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return []byte{0}, err
    }
    return body, nil
}

EDIT: I'm looking for something like Node's 'request' module, which lets me do it in one line, like so: jsonStr, err := getJsonStr(url).

A: There is nothing wrong it using existing system package and it fairly simple to retrieve json data over http in go
package main

import (
    "encoding/json"
    "fmt"
    "net/http"
)

func main() {
    var data struct {
        Items []struct {
            Name              string
            Count             int
            Is_required       bool
            Is_moderator_only bool
            Has_synonyms      bool
        }
    }

    r, _ := http.Get("https://api.stackexchange.com/2.2/tags?page=1&pagesize=100&order=desc&sort=popular&site=stackoverflow")
    defer r.Body.Close()

    dec := json.NewDecoder(r.Body)
    dec.Decode(&data)

    for _, item := range data.Items {
        fmt.Printf("%s = %d\n", item.Name, item.Count)
    }

}

Output go run main.go
java = 781454
javascript = 769128
c# = 744294
php = 692360
android = 617892
jquery = 570461
python = 379608
html = 374617
c++ = 341533
ios = 300992
mysql = 296223
css = 276063
sql = 258178
asp.net = 244833
objective-c = 215095
.net = 202087
iphone = 199749
ruby-on-rails = 190497
c = 166226
ruby = 123840
sql-server = 119341
arrays = 116975
ajax = 109786
regex = 107215
xml = 106705
asp.net-mvc = 101921
json = 101545
wpf = 96016
linux = 92266
django = 88008
database = 86638
eclipse = 79952
vb.net = 78888
r = 78401
xcode = 76326
windows = 74359
angularjs = 73266
string = 71149
html5 = 68094
node.js = 66731
wordpress = 65125
multithreading = 64168
facebook = 62460
excel = 58402
spring = 57380
image = 56798
winforms = 55268
forms = 54263
ruby-on-rails-3 = 52611
osx = 51292
oracle = 50876
git = 50019
performance = 48867
swing = 48768
algorithm = 48258
apache = 47355
bash = 46347
linq = 45169
visual-studio-2010 = 43907
entity-framework = 43776
perl = 42740
web-services = 42609
matlab = 42112
hibernate = 41410
visual-studio = 40307
wcf = 39948
sql-server-2008 = 39394
mongodb = 38632
asp.net-mvc-3 = 38018
list = 37914
qt = 37505
.htaccess = 37305
css3 = 36505
vba = 36368
sqlite = 36274
actionscript-3 = 35594
file = 35171
twitter-bootstrap = 34911
postgresql = 34757
function = 34747
codeigniter = 33439
api = 32964
class = 32888
scala = 32763
shell = 32407
google-maps = 31961
cocoa = 31744
ipad = 31600
jsp = 31510
cocoa-touch = 30994
tsql = 30976
sockets = 30635
flash = 30555
jquery-ui = 30506
asp.net-mvc-4 = 30278
validation = 30166
security = 30035
delphi = 29758
unit-testing = 29717
rest = 29475

A: Since you didn't want to define a struct, it's also possible (but a bit ugly) to unmarshal into a map of type map[string]interface{}{}
package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {

    data := map[string]interface{}{}

    r, _ := http.Get("http://api.stackoverflow.com/1.1/tags?pagesize=100&page=1")
    defer r.Body.Close()

    body, _ := ioutil.ReadAll(r.Body)
    json.Unmarshal(body, &data)

    fmt.Println("Total:", data["total"], "page:", data["page"], "pagesize:", data["pagesize"])
    // Total: 34055 page: 1 pagesize: 100
}


text:
Q: Is "throughout" used in this sentence as a verb?
There's a lengthy bug thread on OS X Yosemite that has been added to throughout the beta testing period.

Source: http://www.macrumors.com/2014/07/24/os-x-yosemite-first-impressions/

A: No, that's not a verb.  The sentence has been structured to place the emphasis on "bug thread" (by having it at the front), but "bug thread" is the object of "to", and "throughout" has its usual duration-based meaning; to throughout is not an attempted to-infinitive, but a simple collocation of words in unrelated functions.
We could rewrite and simplify the sentence a bit to make it more apparent:

Items have been added to the bug thread throughout the beta testing period.