text:
Q: VB.net OleDbDataReader doesn't return wanted values OleDb in VB.net only returns the first column
I don't know where I've gone wrong, stared at it for 2 hours straight and tried 150 different variations. Don't know where the error is that makes it not return any other fields than the first one.
And yes, I know it looks really confusing, I was going to put the 5 readings as a function but I got overwhelmed by the problem
Private Sub StartBtn_Click(sender As Object, e As EventArgs) Handles StartBtn.Click
    Dim Numbers As New List(Of Integer)
    For X As Integer = 1 To 15
        Dim Num As Integer = RandomNum()
        Numbers.Add(Num)
    Next

    Dim temp_QuestionSet As New List(Of Question)

    provider = "Provider=Microsoft.ACE.OLEDB.12.0;"
    dataFile = "Data Source=C:\course work\dttmq.accdb"
    connString = provider & dataFile
    Try
        Connection.ConnectionString = connString
        Connection.Open()
    Catch ex As Exception
        System.Console.Beep()
        MsgBox("Error")
    End Try

    For Each Number In Numbers
        Dim _question As New Question

        _question.ID = Number

        Using Connection
            Dim command As New OleDbCommand("SELECT Question FROM final WHERE QuestionID = " & Number.ToString, Connection)
            Try
                Dim reader As OleDbDataReader = command.ExecuteReader()
                While reader.Read()
                    _question.Q = reader(0).ToString()
                End While
                reader.Close()
            Catch ex As Exception
            End Try
        End Using

        Using Connection
            Dim command As New OleDbCommand("SELECT (Answer1) FROM final WHERE QuestionID = " & Number.ToString, Connection)
            Try
                Dim reader As OleDbDataReader = command.ExecuteReader()
                While reader.Read()
                    _question.A = reader(0).ToString()
                End While
                reader.Close()
            Catch ex As Exception
            End Try
        End Using

        Using Connection
            Dim command As New OleDbCommand("SELECT Answer2 FROM final WHERE QuestionID = " & Number.ToString, Connection)
            Try
                Dim reader As OleDbDataReader = command.ExecuteReader()
                While reader.Read()
                    _question.B = reader(0).ToString()
                End While
                reader.Close()
            Catch ex As Exception
            End Try
        End Using

        Using Connection
            Dim command As New OleDbCommand("SELECT Answer3 FROM final WHERE QuestionID = " & Number.ToString, Connection)
            Try
                Dim reader As OleDbDataReader = command.ExecuteReader()
                While reader.Read()
                    _question.C = reader(0).ToString()
                End While
                reader.Close()
            Catch ex As Exception
            End Try
        End Using

        Using Connection
            Dim command As New OleDbCommand("SELECT Answer4 FROM final WHERE QuestionID = " & Number.ToString, Connection)
            Try
                Dim reader As OleDbDataReader = command.ExecuteReader()
                While reader.Read()
                    _question.D = reader(0).ToString()
                End While
                reader.Close()
            Catch ex As Exception
            End Try
        End Using

        Using Connection
            Dim command As New OleDbCommand("SELECT CorrectAnswer FROM final WHERE QuestionID = " & Number.ToString, Connection)
            Try
                Dim reader As OleDbDataReader = command.ExecuteReader()
                While reader.Read()
                    _question.Z = reader(0).ToString()
                End While
                reader.Close()
            Catch ex As Exception
            End Try
        End Using
        temp_QuestionSet.Add(_question)
    Next
End Sub

A: You have one connection outside of a loop, with several commands inside the loop. While this is leaning in the right direction, each of the commands is wrapped inside a Using block targeted on the connection object. This means you have disposed of your connection at the end of the very first command on the very first time through the loop, making the connection unusable.
While I'm here, you should also look at parameterized queries.
Put that all together, along with some other changes, and you end up with this:
Dim temp_QuestionSet As New List(Of Question)
Private Sub StartBtn_Click(sender As Object, e As EventArgs) Handles StartBtn.Click
    temp_QuestionSet.Clear()
    Dim QuestionSql As String = "SELECT Question, Answer1, Answer2, Answer3, Answer4, CorrectAnswer FROM final WHERE QuestionID = ?"

    provider = "Provider=Microsoft.ACE.OLEDB.12.0;"
    dataFile = "Data Source=C:\course work\dttmq.accdb"
    connString = provider & dataFile

    Using Connection As New OleDbConnection(connString), _
          command As New OleDbCommand(QuestionSql, Connection)

        command.Parameters.Add("ID", OleDbType.Integer)
        Connection.Open()

        For Each Number In Enumerable.Range(0,15).Select(Function(i) RandomNum())

            command.Parameters("ID").Value = Number
            Try
                Dim reader As OleDbDataReader = command.ExecuteReader()
                While reader.Read()
                    temp_QuestionSet.Add(New Question With {
                    .ID = Number,
                    .Q = reader("Question").ToString(),
                    .A = reader("Answer1").ToString(),
                    .B = reader("Answer2").ToString(),
                    .C = reader("Answer3").ToString(),
                    .D = reader("Answer4").ToString(),
                    .Z = reader("CorrectAnswer").ToString())
                End While
                reader.Close()
            Catch ex As Exception
               MsgBox("Error: " & ex.Message)
               Console.Beep()
            End Try
        Next

    End Using
End Sub

I'd also look at getting this down to ONE trip to your database to load all the questions in one go, and then shuffling the result. The code I provided should make it easy to go in that direction, where you can accomplish this just by changing the SQL command.


text:
Q: Convert milliseconds to date in moment.js nodejs i want to know how can i convert  milliseconds to date format in moment.js using nodejs.
I am using the following way:-
var schedule_time="1512986378692";  // Monday, 11 December 2017 15:29:38

schedule_time time is 11 dec, 2017 15:29:38.
But when i use the following method it give me the following result
moment.unix((schedule_time)/1000).format("YYYY-MM-DD HH:mm:ss"); // 2017-12-11 09:59:38

A: This is because of the timezone difference. The milliseconds are of IST, but moment is by default using UTC for this on your machine.
You can try a good library which integrates well with MomentJS, and have good features for working with timezones.
To answer the quest, moment-timezone offers an API to change the timezone of the provided moment object, like this:
moment(1512986378692).tz('Asia/Kolkata').format('YYYY-MM-DD HH:mm:ss')

Also, I didn't quite understand why are you converting the millis to seconds further.

redpajama_set_name: RedPajamaStackExchange


text:
Q: React JS Bundle Load Issue -- SyntaxError: Invalid regular expression I am getting this strange issue in the browser "SyntaxError: Invalid regular expression..."
Any pointers?
I have read other similar posts suggesting to include utf-8 in the header or src both of which I have done as shown in the code below.
I have a react project, and it's producing bundle.js with webpack and included as follows.
<!DOCTYPE html>

    <meta charset="utf-8" />

And this is the entire package.json I am using:
{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^17.0.2",
    "react-bootstrap": "^2.0.4",
    "react-dom": "^17.0.2",
    "react-router-dom": "^6.2.1",
    "react-syntax-highlighter": "^15.4.5"
  },
  "scripts": {
    "build": "webpack --mode production",
    "dev": "webpack serve --mode development",
    "start": "webpack serve"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/core": "^7.16.5",
    "@babel/preset-env": "^7.16.5",
    "@babel/preset-react": "^7.16.5",
    "babel-loader": "^8.2.3",
    "css-loader": "^5.2.7",
    "raw-loader": "^4.0.2",
    "style-loader": "^2.0.0",
    "url-loader": "^4.1.1",
    "webpack": "^5.65.0",
    "webpack-cli": "^4.9.1",
    "webpack-dev-server": "^4.7.1"
  }
}

And the error in chrome console is:
SyntaxError: Invalid regular expression: /([À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*(<[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*(\s*,\s*[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*)*>)?\s+)+[a-zA-Z_]\w*\s*\(/: Range out of order in character class
    at new RegExp (<anonymous>)
    at n (core.js:836)
    at t (core.js:1136)
    at core.js:1151
    at Array.forEach (<anonymous>)
    at t (core.js:1151)
    at H (core.js:1171)
    at m (core.js:1975)
    at Object.p [as highlight] (core.js:1626)
    at Object.o [as highlight] (react-dom.production.min.js:79)
ss @ react-dom.production.min.js:268
bootstrap:22 Uncaught SyntaxError: Invalid regular expression: /([À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*(<[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*(\s*,\s*[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*)*>)?\s+)+[a-zA-Z_]\w*\s*\(/: Range out of order in character class
    at new RegExp (<anonymous>)
    at n (core.js:836)
    at t (core.js:1136)
    at core.js:1151
    at Array.forEach (<anonymous>)
    at t (core.js:1151)
    at H (core.js:1171)
    at m (core.js:1975)
    at Object.p [as highlight] (core.js:1626)
    at Object.o [as highlight] (react-dom.production.min.js:79)


text:
Q: How do I get the value of my textbox in my actionlink? I want to pass the value of my @HtmlTextBox("UserName") to my get method in my controller from my view via my @html.ActionLink. Here is what I have tried:
@Html.TextBox("UserName")
@foreach (string s in ViewBag.RolesForThisUser)
{

            @s

            @Html.ActionLink("Remove Role", "DeleteRoleForUser",
            new{controller = "Role",
            UserName=@Html.TextBox("UserName").ToString(), RoleName=@s})

}

Where this is out of scope it seems a bit tricky. This works well with the RoleName variable because it is within scope. Is there no way to get the value using the given variables?
Resolution
Taking a que from Scartag I came up with this
$(function () {
    $("#lnk")
        .click(function () {
            console.log("my message");
            var userName = $("#UserName").val();
            this.href = this.href + '&UserName=' + userName;
        });
});

A: Your approach is wrong.
Each time you see the @Html.TextBox("UserName") markup, you are telling the runtime to create an input field with id and name "Username"... that's all.
It doesn't translate into a value.
You could however use javascript to add an onclick to the actionlink which would append the value of the textbox before navigating to whatever url you want it to get to.

A: One way to do it is checking on FormCollection which value you are posting
[HttpPost]
public ActionResult SubmitAction(FormCollection collection)
{
  // Get Post Params Here
  string var1 = collection["UserName"];
}

Check that you use the correct id name to retrieve the value


text:
Q: How do I create a TypeScript Definition file for a class whose properties change depending on instantiation I'm trying to implement a DefinitelyTyped TS definition file for a JS class that has different definitions depending on how it's instantiated. The definitions are well defined and won't change after instantiation.
Example:
var a = new MyClass("foo");
console.log(a.a);//"a"
console.log(a.b);//"b"
console.log(a.c);//"c"
console.log(a.d);//"undefined"
console.log(a.e);//"undefined"
console.log(a.f);//"undefined"

var b = new MyClass("bar");
console.log(b.a);//"undefined"
console.log(b.b);//"undefined"
console.log(b.c);//"c"
console.log(b.d);//"d"
console.log(b.e);//"e"
console.log(b.f);//"f"

I'd like a TS definition something like:
interface myInterface{
    c:string;
}
class MyClass("foo") implements myInterface{
    a:string;
    b:string;
    c:string;
}
class MyClass("bar") implements myInterface{
    c:string;
    d:string;
    e:string;
    f:string;
}

Any pointers would be greatly appreciated
EDIT: Clarification: I cannot modify MyClass
Also, There is a multitude of different ways of instantiating MyClass, however they are all well known and defined ahead of time. We can also assume that we don't have to worry about the case of a non existant variation of MyClass.
Additionally, MyClass is best described as a factory that allows access to a database; so new MyClass("foo") would create an object that allows access to the foo table in the database, where the field names are now properties of the created MyClass object

A: If you have control over the code...
You should consider fixing it. What you describe is two different types, it does not make much sense to have a class change it's type depending on the input parameters.
The MyClass in your example looks like some kind of odd factory that uses the constructor instead of a method to create objects.
A solution in code could look something like this using union types and type guards:
class Foo {
    public FooMember: string = "I'm foo";
}

class Bar {
    public BarMember:string = "I'm bar";
}

let myObj: Foo | Bar;

myObj = new Foo(); // or FooBarFactory.GetInstance("Foo") or whatever

if(myObj instanceof Foo){
    console.log(myObj.FooMember);
} else {
    console.log(myObj.BarMember);
}

If you don't have control over the code...
...you are basically out of luck, in regards of having it typed differently depending on the input to the constructor. You can not type the constructor of a class to return anything other than the type of the class.


text:
Q: I need a solution to setting up a sign-up button, check Line 7, the signupactivity shows red on Android studio class Main3Activity : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main3)
    auth = FirebaseAuth.getInstance()

    btn5_sign_up.setOnClickListener() {
        LoginActivity(Intent(this.SignUpActivity::class.java))
        finish()

    }
}

public override fun onStart() {
    super.onStart()
    // Check if user is signed in (non-null) and update UI accordingly.
    var currentUser = auth.currentUser
    updateUI(currentUser)
}
//assigning the function previously named above
fun updateUI (currentUser : FirebaseAuth?){

}

Basically, line 7 is not making the code go through with the red on SignUpActivity

A: Use this
startActivity(Intent(this,SignUpActivity::class.java))

Instead of
LoginActivity(Intent(this.SignUpActivity::class.java))


text:
Q: How can I ignore annoying users? There are some guys who seem to be flooding or spamming me. Is there a way to ignore or block a user, like what can be done in Facebook, for example?

A: Only moderators can suspend users.
No users can be banned until moderators decide to permently destroy the account into shreds if that person seems to be too annoying in our digital society. Flag the user's post and in the Other section, write your reason for wanting that user suspended if necessary. Also give a friendly warning. If the user ignores it, it might go against that user in the future... Other than that, just go on with life as we know it today.

A: No, you cannot ban a user. If you feel a user is trolling, flag one of their posts for moderator attention so they can look at it, and warn (or suspend) the user when necessary.


text:
Q: Is there any way to evaluate (expand-file-name) in .dir-locals.el? I'm trying to move all my compilation config (compilation-command and compilation-directory to be exact) to .dir-locals.el file at the top of my project. It is working fine except that I can't find the way to use expand-file-name there and without it I have to use absolute path, which is not really convenient.
So, is there a way (or a dirty hack) to make local directory variables to evaluate values before assigning?

A: You can use the eval "variable" to evaluate an arbitrary elisp expression.  You will probably want to customize enable-local-eval and/or safe-local-eval-forms so you don't get asked each time.


text:
Q: Script system in application I'm developing a game and now I want to make script system for it.
Now I have abstract class Object which is inherited by all game objects. I have to write a lot of technical code, add new object type into enum, register parser function for each object (that function parses object's params from file).
I don't want to make such work. So the idea is to get some script system (boost.python for example, because I'm using boost in my project). Each object will be a simple python-script, at c++ side I just load and run all that scripts.
Python isn't hard -typed so I can register functions, build types dynamically without storing enum, etc. The only bad part is writing a lot of binding-code but It makes only once.
Are my ideas right?

A: Can you give us a rough idea of how large the game is going to be?
If you're not careful, you could give yourself a lot of extra work without much benefit, but with some planning it sounds like it might help. The important questions are "What parts of the program do I want to simplify?", "Do I need a scripting language to simplify them? and "Can the scripting language simplify them?".
You mentioned that you don't want to have to manually parse files. Python's pickle module could handle serialization for you, but so could .NET. If you're using Visual Studio, then you may find it easier to write the code in C# than in Python.
You should also look for ways to simplify your code without adding a new language. For example, you might be able to create a simple binary file format and store your data structures without much parsing. There are probably other things you can do, but that would require more detailed knowledge of the program.


text:
Q: How should I structure my project to share classes between an Android client application and a JSP server application? I'm building an Android application (as an Eclipse project) that needs to access a web service. We will be sending the data from the service as JSON serialized classes, so we want to share some of the classes between the Android application and the server application. We are currently thinking that the way we need to do this is to structure our Git repository with 3 folders. One for the client, one for the server, and one for the shared library.
But at that point we couldn't figure out how to create the shared code. It looks like we can put all the .java files into a folder and then create a relative link to that folder from the other projects, but is that a good way to go about this?
The other possibility we found was to create another project in Eclipse and then include the library project in the client project. However we ran into a problem here. How can we make the library usable by both the server and Android? If I create a new Java project in Eclipse, I must select a JRE to build for, but Dalvik isn't an option, and even if it was how could I use the library with a desktop VM if the library was compiled for Dalvik?

A: I would use 3 projects:

*

*server

*shared

*client (android)

and include shared as a project dependency in both server and client. If you use ant you'd drop the shared.jar in both server/lib and client/lib every time it's changed, and if you use maven it's a dependency (possibly with Ant + Ivy it's also a dependency). Consider Nexus as a repository location in that case.

A: You don't actually need to create a separate Eclipse project for the shared classes. You can just create a 'common source folder' outside of the other two projects' disk hierarchy. For both the server and client projects :in the Properties/Java Build Path/Source add a 'Link source' to the new folder. (Perhaps this is what you meant by 'relative link'). It's easy to add this common source folder to an Ant build file.

A: You could add the path to the classes/JARs to the server's runtime classpath.
Since it's unclear which one you're using, here's just a generic answer based on Apache Tomcat.

*

*Open /conf/catalina.properties file.

*Edit shared.loader entry to include the path to the package root of those classes or JAR file(s).
E.g.
shared.loader = /path/to/classes

or
shared.loader = /path/to/specific.jar

or
shared.loader = /path/to/*.jar

You can even specify multiple paths separated by a comma.


text:
Q: Reasons for Task Manager crashes in windows 8 There could be a number of reasons for Task Manager crashing. I believe I am doing the right thing in making this a community wiki. Here is my original post before I found the cause.
My task manager crashes in Windows 8.1. I open it using the right click on the start menu or using the keyboard shortcut.
It will crash immediately or when I show more details and try to interact with the view menu for "always on top" and "minimize to tray". The program just disappears and only by looking into the event viewer do I see there are crash events.
This is a new install (1 week old) and do not know when it occurred. It seemed to occur when I
enabled UAC.
I have tried finding any drivers that need updating.
I have tried disabling any running programs.
I have tried the SFC scan now command to check integrity.
System restore date lists approximately when i first installed windows.

Here are the event viewer logs.
First, the information event telling me there is a crash log.
Fault bucket , type 0
Event Name: APPCRASH
Response: Not available
Cab Id: 0
Problem signature:
P1: Taskmgr.exe
P2: 6.3.9600.16384
P3: 5215d00b
P4: Taskmgr.exe
P5: 6.3.9600.16384
P6: 5215d00b
P7: c0000005
P8: 0000000000043882
P9:
P10:
Attached files:
These files may be available here:
C:\ProgramData\Microsoft\Windows\WER\ReportQueue\AppCrash_Taskmgr.exe_(someguid)
Analysis symbol:
Rechecking for solution: 0
Report Id: dd180f3e-4b86-11e3-8277-002522ea094d
Report Status: 4100
Hashed bucket:

The error event
Faulting application name: Taskmgr.exe, version: 6.3.9600.16384, time stamp: 0x5215d00b
Faulting module name: Taskmgr.exe, version: 6.3.9600.16384, time stamp: 0x5215d00b
Exception code: 0xc0000005
Fault offset: 0x0000000000043882
Faulting process id: 0x7a4
Faulting application start time: 0x01cedf93cc33dd88
Faulting application path: C:\Windows\System32\Taskmgr.exe
Faulting module path: C:\Windows\System32\Taskmgr.exe
Report Id: 09e2cbbc-4b87-11e3-8277-002522ea094d
Faulting package full name:
Faulting package-relative application ID:

A: RAMDisk
My crash was caused by SoftPerfect RAM Disk. Once I unmounted the RAM disk drive, the crashing of task manager ended. Here is a forum discusssion.
ProgramData folder
Another reason I looked at was junctioning the ProgramData folder. In having a solid state drive there are reasons for moving folders to other drives. Saving space and saving the life time of the capacity of the drive. One method is to junction a folder to another drive.
The process involves copying the folder to another drive, creating a junction pointing from the original location to the new location.
Problem sets in when copying (mostly via robocopy) and the permissions are not also transferred. Since some of the folders the people transfer are windows operated folders, you sometimes need to use safe mode command prompt to complete the process. Check with a robocopy first and compare permissions. Some reported robocopy still did not copy permissions even when instructed to.
Update drivers
Some believe up to date drivers are needed, namely, video drivers.


text:
Q: Minesweeper - Angular I'm making angular version of MineSweeper, but I've got the problem with event. I mean, I've got my field component like that:
import {Component, Input, OnInit} from '@angular/core';
import {style} from '@angular/animations';

@Component({
  selector: 'app-pool',
  templateUrl: './field.component.html',
  styleUrls: ['./field.component.sass']
})

export class FieldComponent implements OnInit {
  isBomb = false;
  isInfo = false;
  isClickable = true;
  touchesBombCount = 0;
  isMarkedAsBomb = false;
  isExpanded = false;
  poolID: number;
  isBombExpanded = false;

  @Input() display: string;

  constructor() {
  }

  ngOnInit() {
  }

  expandMe() {
    this.isExpanded = !this.isExpanded;
    if (this.isBomb && this.isExpanded) {
      this.isBombExpanded = !this.isBombExpanded;
    }
    console.log(this);
  }

  onFieldClick(event: any) {
    this.expandMe();
    this.isClickable = false;
    console.log(event);
  }

  onRightClick(event: any) {
    event.preventDefault();
    this.isMarkedAsBomb = !this.isMarkedAsBomb;
  }

}

Then I'm creating fields in board component:
import {Component, Input, OnInit} from '@angular/core';
import {FieldComponent} from '../field/field.component';

@Component({
  selector: 'app-board',
  templateUrl: './board.component.html',
  styleUrls: ['./board.component.sass']
})
export class BoardComponent implements OnInit {
  fieldList: FieldComponent[] = [];
  bombCount: number = 10;
  poolBombList: FieldComponent[] = [];
  private allBombsPlanted = false;
  isGameOver = false;

  @Input() poolCount: number;

  constructor() {
  }

  ngOnInit() {
    this.createBoardFromPools();
    while (!this.allBombsPlanted) {
      this.plantTheBombs();
    }
    console.log(this);
  }

  createBoardFromPools() {
    for (let i = 0; i < this.poolCount; i++) {
      const pool = new FieldComponent();
      pool.poolID = i;
      this.fieldList.push(pool);
    }
  }

  plantTheBombs() {
    const poolCount = this.fieldList.length - 1;
    const poolToPlant = Math.floor((Math.random() * poolCount));
    if (!this.checkIfHasBomb(poolToPlant)) {
      this.poolBombList.push(this.fieldList[poolToPlant]);
      this.fieldList[poolToPlant].isBomb = true;
    }
    if (this.poolBombList.length === this.bombCount) {
      this.allBombsPlanted = true;
    }
  }

  checkIfHasBomb(poolToPlant): boolean {

    for (let i = 0, iMax = this.poolBombList.length; i < iMax; i++) {
      if (this.poolBombList[i].poolID === poolToPlant.poolID) {
        return true;
      }
    }
    return false;
  }

}

My question is:
why when I console.log (this) of field component, then the bomb is marked as false, even, when on my general list of fields in board component (  fieldList: FieldComponent[] = []) shows it is a bomb actually?
I'm moving from vanilla to angular, maybe I've created fields in board component not correctly?

A: I think a better solution would be to create a model for your Field like:
export interface FieldModel{
  poolID: number;
  isBomb:boolean;
  isInfo:boolean;
  isClickable:boolean;
  touchesBombCount:boolean;
  isMarkedAsBomb:boolean;
  isExpanded:boolean;
  isBombExpanded:boolean;
}

Now in your BoardComponent you would simply create FieldModel objects and push them into the list of fields.
In the template of BoardComponent you would create the FieldComponent via the declarative approach in a *ngFor iterating over the FieldModels and passing them as input properties to your FieldComponent.
Other Solution
If you want to dynamically create components, like you want to with your FieldComponent inside the BoardComponent you should use a
ComponentFactory. You will also need a ViewContainerRef where your components can get rendered inside.
In the template of your BoardComponent you need some container for your fields:
<ng-template #boardContainer></ng-template>

In BoardComponent you need to get the container with the help of the ViewChild decorator and inject a ComponentFactoryResolver:
export class BoardComponent implements OnInit {
  ...
  @ViewChild('boardContainer',{read:ViewContainerRef,static:false}) boardContainer:ViewContainerRef;

  constructor(private componentFactoryResolver:ComponentFactoryResolver) {
  }
  ...
}

Now you can create FieldComponents like shown below:
createFieldComponent(){
 const componentFactory = this.componentFactoryResolver.resolveComponentFactory(FieldComponent);
 const componentRef:ComponentRef<FieldComponent> = this.boardContainer.createComponent(componentFactory);
}

The componentRef then offers you access to the component instance.

A: I've managed it by 'mapping' my fieldList to fieldComponent like this:
Field component:
@Input() isBomb: boolean;

And then in board component template:
<div [className]="'board'">
<app-pool *ngFor="let field of fieldList" [isBomb]="field.isBomb"></app-pool>
</div>

It's doing the job, but I don't think so it is the best way to do it in Angular.


text:
Q: Port 80 automatically becoming blocked - Apache and Ubuntu I have a strange issue. I have installed Ubuntu version 22.04 which is using Apache 2.4.52.
I have also installed LetsEncrypt SSL which is working.
If I restart Apache Post 80 is open but as soon as I make a request to the nonssl version of my website (e.g. http://www.example.com) then port 80 is blocked automatically.
https://www.example.com continues to work
I have confirmed that Apache is still listening and that port 80 is not being blocked via UFW.
Thanks in advance


text:
Q: PHP script can not write to file with email piping I have a simple script written to process received email.  Here are the tested scenarios:
A. Script function is to send an email indicating an email was received at piped address.
-tested by browser - Success
-tested by CLI - Success
-tested by piping - Success
B. Script function is to parse and write files to folder, AND send email indicating email was received at piped address
-tested by browser - Files written and email sent.
-tested by CLI - Files written and email sent.
-tested by piping - Files NOT written, BUT email is sent.
I have simplified the script to the basic function of reading and writing the piped message.  I suspect the issue is a permission problem, but I can not find any supporting evidence.
I am not fluent in CLI, but can perform some task. I am not sure where to look for log files for the piped scenario.
Piping works just fine in all tested scenarios.  Here is the simplified code that fails when invoked by piping:
#!/usr/bin/php -q
<?php
/* Read the message from STDIN */
$fd = fopen("php://stdin", "r");
$email = ""; // This will be the variable holding the data.
while (!feof($fd)) {
$email .= fread($fd, 1024);
}
fclose($fd);
/* Saves the data into a file */
$fdw = fopen("/my/folder/mail.txt", "w");
fwrite($fdw, $email);
fclose($fdw);
/* Script End */

Thanks for any help.
Modified code to:
#!/usr/bin/php -q
<?php
/* Read the message from STDIN */
$email = file_get_contents('php://stdin');

/* Saves the data into a file */
$fdw = fopen("/Volumes/Cobra/Sites/email/mail.txt", "w+");
if (! $fdw) {
    error_log("Unable to open mail.txt for output.", 1, "myemail@mydomain.com", "From: admin@mydomain.com");
} else {
    fwrite($fdw, $email);
}

fclose($fdw);

/* Script End */

Error message was emailed.  Now what? What user does the pipe-invoked script run as?

A: If it's a permissions problem, then either fopen will return FALSE on failure. You're not checking for that case, and assumes everything worked. Try
$fd = fopen('php://stdin', 'r');
if (!$fd) {
   die("Unable to open stdin for input");
}

$fdw = fopen(...);
if (!$fdw) {
   die("Unable to open mail.txt for output");
}

If neither die() triggers, then it's not a permissions issue.
As one stylistic thing, unless your real code is much more complicated and does want to process stdin in chunks, you could just do:
$email = file_get_contents('php://stdin');


text:
Q: Pushing data with Windows Azure I am currently using Windows Azure with Android and need to sync data between sets of users using PUSH notifications.
For example: User A uploads data to Azure which is stored in the SQL DB. That then needs to be pushed down to a specific set of devices and stored locally in SQLite.
What is the best design pattern for this? Should I be pushing the data with the PUSH notification or be using PUSH as a prompt for the app to then connect with azure and download the data.
Thanks for any help.

A: I'd think you would want to send a notification to the device that prompts the user to launch the app, and then the app fetches the data. I don't know how Android push services work, but I'd assume there is a fairly limited amount of data you can send in a single notification.

A: The best way to accomplish this is to use Windows Azure Mobile Services and the unoffical Android SDK.
The unofficial Android SDK can be found at: https://github.com/goldshtn/wams-android
The benefit of using Mobile Services in this case is that it's super easy to writer server-side scripts on INSERT. After you connect your project to a Mobile Service, you'd then head to the 'Data' tab, select the appropriate table, and then head to 'Script.'  Pick INSERT from the dropdown, then write a function that sends a push notification to the designated subset of users.  You'll need to write this in JavaScript.
There's some code you can work from included with the unofficial SDK, but if you check out https://www.windowsazure.com/en-us/develop/mobile/tutorials/get-started-with-push-dotnet/#update-scripts you can get a sense for the steps you'd follow for an app on any platform (though the tutorials will only walk through Windows Phone 8, Windows Store, and iOS at the moment).


text:
Q: Is a server or DC server required for a network printer? I'm in the process of building, more like designing a small network for home. We currently have approximately 6 computers that can operate in the house. Unfortunately, all of these computers share one printer and must be plugged in to print. Can it essentially be done to where I can plug the printer into a router, configure it with a static IP address and then allow all computers to wirelessly print from their laptops? If this cannot be done do I need a computer to act as a DC to put the printer on the network?
I'm fairly new at configuring new networks and thought that network printing would be a good start to understanding network configuration.

A: If by plugged in to print you mean the printer has a network cable, no, you don't require a separate server to do anything.
Plug in the printer, give it an IP address.
On your client machines add the printer (in Windows, add it as a local printer, using an IP port.) Yes, "local printer" added as an IP port. Counterintuitive.
From there Windows should detect it and get the proper driver, if not download the proper driver from Windows Update or the manufacturer.
But no server is technically necessary in the setup you describe.

A: A domain controller is not necessary to run a print server. This can be done with a member server, or even an end-user computer. DNS is also not necessary to make this happen as you can simply use the IP address.
If you printer allows it, I would recommend giving it a Static IP and making one computer serve the function of the print server. Install the drivers on that server / computer, share the printer and add it to the other machines. Just remember that this computer will need to remain on at all times you wish to use the printer.

A: No need for DNS. You can just use the IP address. Also, there is definitely no reason to create a Windows domain for 6 computers! That would be overkill. You might want to purchase a router that can handle dynamic DNS and will register the printer's DNS name, because it will make it easier to use, but it's not necessary.
You asked if you can just plug the printer into the router. Well, that depends on your printer. You'd need a printer with an Ethernet card in it. If so, it likely has its own print processor hardware as well (such as HP's jetdirect) and can handle queuing jobs, etc. If not, you need to plug it into one of your computers and enable printer sharing. Again, this will work with Workgroup configuration, and there's no need to create a Windows domain to share a single printer.

A: In the even that you do not have a network ready printer, you can purchase a print server. A print server typically has a simple Web server allowing you to quickly set up a permanent IP address. Check the range of addresses that your home router is using for DHCP and assign the print server an address that is NOT in that range. For example, my home router offers DHCP to computers in the house with numbers 192.168.1.100 through 192.168.1.150 as the default setting. Make the printer have a fixed IP like 192.168.1.10.
Good luck.

A: Basic Instructions for setting up a Network Printer:
-Give your Printer an IP address within your local subnet(refer to printer manual to do so. It needs to have a network card.)
-In windows 7 click Start > Printers and Devices > New Printer
-Select Add a local printer
-Select Create a new port > Standard TCP/IP port
-Put in IP address of printer
Hopefully at this point Windows will automatically detect the drivers needed for the printer. If not, you'll have to select them manually.

A: Yes, you need to connect your printer to a print server for all of the computers to print to it.
If it is a "network ready" printer, with a built-in ethernet interface, then the print server is already embedded in the printer, and you can plug it in to your switch/hub/router.
If it's not a network ready printer, you can purchase a dedicated print server appliance (Linksys,D-link.Netgear,etc.), or connect your printer to a pc and configure it as the print server.
You may also check the specs for your router, as some are capable of acting directly as a print server.

A: I see three easy options here:
-share the printer and put all your machines in the same workgroup. This has the advantage for you of needing to buy NOTHING ELSE but it has the disadvantage of requiring your pc which shares the printer to be booted and ready for jobs or all prints from your other machines will fail.
-usb to ethernet print server adapter can be used to take a usb printer and turn it into a network printer. You'll have to buy the adapter but by doing this method you do not need to keep the primary computer booted like you would if you had shared the printer.
-usb to wifi print server adapter can be used if you want to physically locate the printer central to the group of machines. Same basic principle as the lan style adapter except you'll need a working wifi network to attach your print server to. And it sounds like you already have one set up.
If I were doing this for my house I would use a print server adapter. You can't always guarantee that your main machine will be up when someone else needs to print.


text:
Q: PIL cropped images return a funny PIL.Image._ImageCrop datatype When cropped_image = image.crop( cords ) works properly, it returns an Image object that works with Scipy's assaray:
bitmap <PIL.Image.Image image mode=RGBA size=1600x1200 at 0xAC9CFEC>
#SCIPY'S ASARRAY WORKS PROPERLY!
pic!! [[[ 16  18  31 255]
  [ 16  18  31 255]
  [ 16  18  31 255]
  ...,

But now I get a PIL.Image._ImageCrop object which fails.
bitmap <PIL.Image._ImageCrop image mode=RGBA size=1600x80 at 0x99635AC>
#SCIPY'S ASARRAY FAILS WITHOUT WARNING
pic!! <PIL.Image._ImageCrop image mode=RGBA size=1600x80 at 0x99635AC>
Traceback (most recent call last):
  File "/root/dev/spectrum/final/image_handler.py", line 216, in on_left_down
    self._sample_callback()
  File "/root/dev/spectrum/final/image_handler.py", line 237, in _sample_callback
    self.__callback_function( sample )
  File "/root/dev/spectrum/final/plot_handler.py", line 117, in __init__
    self.InitUI()
  File "/root/dev/spectrum/final/plot_handler.py", line 163, in InitUI
    self.canvas_panel.draw(self.__crop_section)
  File "/root/dev/spectrum/final/plot_handler.py", line 78, in draw
    pic_avg     = pic.mean(axis=2)
ValueError: axis(=2) out of bounds

Why is such a problem happening?

A: It is a silent failure that came out of two circumstances:
First, the crop method was supplied non-integer numbers.
Second, the crop operation happens to be a lazy operation, cropping happens only when .load() method is called (Im unclear on this, please edit this if you know better!) .
Hence the crop operation did not happen and it gave no obvious signal. Giving it valid coordinates solved the problem.


text:
Q: Creating a custom post type with custom fields This is my first wordpress site.  I am creating a local community site and I want to have similar functionality to freecycle, that is users can offer things to other people for free. So they'd need to be a drop down box to say if the thing was a wanted or an offered item. A title field for the name of the item. Then details of the item. Upload an image of the item and a location field, where people have to pick it up from. Also possibly a contact number field.  Plus ideally, I'd like a checkbox system so that if the item was offered to someone the user could tick a box saying offered and then the post would maybe get assigned a category of awaiting collection and the text of it go grey and disappear out of the list of posts.  When it was collected, they  could click another box which would then give it a category of archive.  I don't even know if any of this is possible though...
If it is though, how is the best way to do this? Considering I want to be able to use these posts on other areas of the site e.g. in a sidebar showing most recent items offered. I also want to be able to add a minimised version of the form which will sit in the sidebar of certain pages, so the user can add an item whilst on a different page.

A: firstly, I'd recommend having a go at writing custom post types yourself, they're not that difficult if you follow the instructions in the WordPress Codex: http://codex.wordpress.org/Function_Reference/register_post_type (The Codex is your best friend when it comes to WordPress development!)
If you still have trouble, there are a number of plugins which can help with the creation of custom post types, for example: http://wordpress.org/extend/plugins/custom-post-type-ui/
Lastly, to add custom fields to your custom post types, I'd recommend using a great plugin that I use quite often: http://www.advancedcustomfields.com/ (I've found it very reliable and a great time saver as opposed to manually creating custom meta fields)
I definitely recommend investigating how to create custom post types and custom meta fields yourself - if you don't have time to do it on this build, then make time on your next one. It's good to know how to do everything manually rather than relying on plugins.
Hope that helps!

A: there is two ways:

*

*Easy Way - there is composer package for it - wp_stem
here is how to create custom post type and add field to it:
PostType::create('custom_post_name')-> meta_box(array(
  'id'        => 'your_id',
  'title'    => 'your_title'
 ))->field(array(
   'name'      => 'your_field_name',
   'label'     => 'your field label',
   'value'     => 'your_field_default_value',
   'type'      => 'your_field_type'
));

how to install and use it see -> github

*

*Wordpress Way (4 steps)-
1. create post type
function create_post_type() {
    register_post_type( 'acme',
      array(
        'labels' => array(
          'name' => __( 'acme' )
        ),
        'public' => true,
        'has_archive' => true,
      )
    );
  }
  add_action( 'init', 'create_post_type' );

2. add meta box
function add_custom_metabox(){
    add_meta_box(
        "your_id",
        "Your Title",
        "custom_metabox_content",
        "post"
    );
}
add_action("add_meta_boxes", "add_custom_metabox");

3. add field to meta box content
function custom_meta_box_content($post_id){
    $value = get_post_meta($post_id, "custom_meta_field", true);

    echo '<input type="text" name="custom_meta_field" value="'. $value                                             .'">';
 }

4. listen to save post hook and update value(when you click update post from admin     panel).
function on_save_post($post_id){
    $meta_value = isset($_POST["custom_meta_field"]) ?  $_POST["custom_meta_field"]  : false;

    if (current_user_can("edit_posts") && $meta_value){
        update_post_meta($post_id,"custom_meta_field", $meta_value);
    }
 }
 add_action("save_post", "on_save_post");

A: Use this code in functions.php
function foobar_func( $atts )
{
   global $post;
   $key=$atts['name'];
   if(empty($key)) return;
   return get_post_meta($post->ID, $key, true);
}

add_shortcode( 'foobar', 'foobar_func' );

And for display
[foobar name=custom_field_name]

in your post page.


text:
Q: integrating differential form using integration by parts I would like to integrate
$$-xdlog(y(x))$$
with respect to $x$, where $d$ is the exterior derivative.
I'm trying to use integration by parts, so
$$-\int xdlog(y(x)) \; dx $$
letting
\begin{align*}
u&=x , \ \ \ dv=dlog(y(x)) dx \\
du&=dx , \ \ v= ?
\end{align*}
I'm getting stuck on how to write $v$. Is there a better way to integrate this?

A: If you are working with differential forms, then $d(\log y)$ is already a differential one-form given by
$$ d(\log y) = \frac{y'(x)}{y(x)} \, dx $$
so there's no need for the extra $d$. Then, you have $u = x$, $v = \log(y)$ and
$$ -\int x \frac{y'(x)}{y(x)} \, dx = \int x d(\log y) = -\int u dv = \int v du - uv = \int \log(y(x)) \, dx - x \log(y(x)) + C. $$


text:
Q: how to cutomize default chrome preferences with python scripts? i am looking for a chrome kinda simple solution , not sure if its already exist or need to customize it however i am open to hear your thoughts , i am using google latest version , when i create new user there's a preferences setting that i want to remove some checkboxes from 4 of them , the manual way to do it is after chrome open , i press F12 go to the upper right gearbox and manual remove checkbox from

*

*detect indentation

*autocompletion

*autocomplete from history

*group similar messages in console

i most all of those checkbox to be unchecked
i find out after i remove it manual chrome add this to the file preferences that located on :
 C:\Users\Dell Mini\AppData\Local\Google\Chrome\User Data\Profile 1\preferences
"preferences": {
"Inspector.drawerSplitViewState": "{\"horizontal\":{\"size\":0,\"showMode\":\"OnlyMain\"}}",
"InspectorView.splitViewState": "{\"vertical\":{\"size\":0}}",
"closeableTabs": "{\"security\":true,\"chrome_recorder\":true}",
"consoleHistoryAutocomplete": "false",
"currentDockState": "\"right\"",
"elements.styles.sidebar.width": "{\"vertical\":{\"size\":0,\"showMode\":\"OnlyMain\"}}",
"inspectorVersion": "31",
"releaseNoteVersionSeen": "42",
"undefined-tabOrder": "{\"Styles\":10,\"Computed\":20}"
},
"synced_preferences_sync_disabled": {
"adornerSettings": "[{\"adorner\":\"grid\",\"isEnabled\":true},{\"adorner\":\"flex\",\"isEnabled\":true},{\"adorner\":\"ad\",\"isEnabled\":true},{\"adorner\":\"scroll-snap\",\"isEnabled\":true},{\"adorner\":\"container\",\"isEnabled\":true}]",
"consoleGroupSimilar": "false",
"textEditorAutoDetectIndent": "false",
"textEditorAutocompletion": "false"

this is create only after i manual remove the checkbox
i also find out there's a initial_preferences file
and master_preferences file on the chrome directory that should be deployed the preferences you put there to any new chrome open , i try it didn't work so well maybe i dont know how to do it or maybe it's not design to do it ,


text:
Q: Trouble Adding Box2D to Xcode (12.4) project I have a project that I can open up with Xcode 12.4 (using cmake -G Xcode ..) and I want to be able use Box2D with it. Like some other people, there seems to be a problem with just running brew install box2d (which installs 2.4.1) and then trying #include <Box2D/Box2D.h>. However, I haven't found much help for more recent versions of Xcode (a lot of the solutions are at least 5 years old) and trying to use Box2D has really been a struggle. Has anybody figured this out with Xcode 12.4 and if so, what are some easy steps to take? Box2D is working just find on my friend's Linux. Thanks
OSX: Big Sur 11.4.1
box2d: 2.4.1
Xcode 12.4
fatal error: 'Box2D/Box2D.h' file not
      found
#include <Box2D/Box2D.h>

I've tried looking for Header Search Paths but I have no idea how to find or adjust such settings in Xcode 12.4.

A: What works for me, in XCode 12.3 at least, is in XCode's Build Settings for the build target:

*

*Add -lBox2D to "Other Linker Flags".

*Add /usr/local/include (the path to where Box2D's include files got installed) to "Header Search Paths".

*Add /usr/local/lib (the path to where Box2D's library got installed) to "Library Search Paths".

If your installation of Box2D is in different locations then of course you'll need to use the locations for your install.


text:
Q: Under what conditions are trigonometric integrals over a period zero? Often times, while solving a physics problem, for example, an integral involving only sines and cosines (and constants), over a period, must be solved. In many cases this may prove difficult, so it's useful to know when we can just cross it out. Under what conditions can we assume such an integral to be zero, and most importantly, why? What theorems and properties can we make use of?

A: The first thing that should be considered is probably the symmetry of the integral. If the integral has lower and upper limits of equal magnitude (e.g. x = -5 to x = 5) and the function you are integrating is even then you can simply find the integral from x = 0 to x = 5 and double the answer. Even better, if the function is odd, you can indeed cross it out just like you hoped for, because the regions will have opposite signs on either side of the y-axis, yet be equal in size. These types of integrals are the best! So, maybe study up on how to determine if a function is odd or even if you are using a combination of odd and even functions, such as cosine and sine.


text:
Q: colorbox contact form not working in iOS I'm trying to create a colorbox contact form calling from iframe. Everything looks good except that every time I try to click on the text box, the entire window gets shifted and makes it very hard to use. I've read it on another forum that the code below could be the answer yet the problem didn't go away.
<meta name="viewport" content="height=1000% width=1000%" />

Is it a known issue with colorbox? Does anyone have any solution to this? Thanks!

A: Shouldn't it be?
 <meta name="viewport" content="height=1000% width=1000%" />

I really don't have any experience with this, but i think the " should be placed at the end of the 1000%


text:
Q: XML not validating against multiple XSD loads only one file in fGrammarDescription I am trying to validate an XML against multiple XSD, and I have come up with this code. But the issue is when I keep a debugger at the validateXML method to check the schema object, I see only one file in fGrammarDescription, which is always the first file in the schemaname.
So finally, tags from other xsd's are not recognized and hence failing the validation.
public class TestMain {
    public static void main(String[] args) {
        TestMain testMain = new TestMain();
        String schemaName1 = "1.xsd";
        String schemaName2 = "2.xsd";
        String schemaName3 = "3.xsd";
        String schemaName4 = "4.xsd";
        String schemaName5 = "5.xsd";
        String xmlName = "C:\\Users\\nagesingh\\IdeaProjects\\test.xml";

        Schema schema = testMain.loadSchema(schemaName1, schemaName2, schemaName3,schemaName4,schemaName5);
        Document document = parseXmlDom(xmlName);
        validateXml(schema, document);
    }

    public static void validateXml(Schema schema, Document document) {
        try {
            // 3. Get a validator from the schema.
            Validator validator = schema.newValidator();
            System.out.println("Validator Class: " + validator.getClass().getName());

            // validating the document against the schema
            validator.validate(new DOMSource(document));
            System.out.println("Validation passed.");

        } catch (Exception e) {
            // catching all validation exceptions
            System.out.println(e.toString());
        }
    }

    public Schema loadSchema(String... schemaFileName) {
        Schema schema = null;
        try {
            String language = XMLConstants.W3C_XML_SCHEMA_NS_URI;
            SchemaFactory factory = SchemaFactory.newInstance(language);
            List<Source> sourceList = new ArrayList<>();
            List<String> stringList = Arrays.asList(schemaFileName);
            for (String eachSchemaFile : stringList){
                sourceList.add(new StreamSource(getClass().getClassLoader().getResource("xml/"+eachSchemaFile).toExternalForm()));
            }

            schema = factory.newSchema(sourceList.stream().toArray(Source[]::new));
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return schema;
    }

    public static Document parseXmlDom(String xmlName) {
        Document document = null;
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            document = builder.parse(new File(xmlName));
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return document;
    }
}


text:
Q: Need help POST is crashing server Can anyone see why, this would crash my app server?
// note_routes.js
module.exports = function(app, db) {
    app.post('/notes', (req, res) =>
    {
    console.log(req.body)
    res.send('Hello')
  });
};

I am following the tutorial on how to build a simple node server api on medium, https://medium.freecodecamp.org/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2
Yet, I cant figure out how to get past this error?
Any tips would be appreciated.

A: To close off this question, I'll summarize in an answer.
app needs to be passed as a function reference, not as a string.
Change this:
 require('./app/routes')('app',{})

to this:
 require('./app/routes')(app,{})


text:
Q: Accessing Subdirectory in public_html using CakePhp 2.0 my question is very simple.
I have a /cms subdirectory on my /public_html directory.
when I try to do: mysite.com/cms cake tries to find cms controller instead of showing the index.php that /cms contains.
How can I make cake to search this folder in the public_html?
Thanks.

A: Is this a folder that belongs to your app or is it an external one? This problem is most likely because your public_html folder is your cake root folder (or at least you have the .htaccess for routing there)
You may want to have your cake app on a subfolder instead of having it on the root of youe webserver
If the content belongs to yout app, you can put The cms folder on the wwwroot folder of your application or follow this tip and move all from cms to Pages folder


text:
Q: Is there a way to create a dict object from user input() in python 3.7.1? The purpose of this question is I want to write some request through pymongo.
For one criterion per field, this is not a difficulty to use input.
find_mongo = {}
key = input("enter a field :")
value = input("enter a criterion :")
find_mongo[key] = value

db.collection.find(find_mongo)#it works without problem.

That's more problematic when I want more complicated criteria.
For instance if I want the value to be in a range:
{"field":{"$lte":1,"$gte":0.5,"$exists:true"}}
Because for the user, who's my own-self, it would be very easier to write this in the shell:
enter a field : size
enter a criterion or criteria : {"$lte":1,"$gte":0.5,"$exists":true"}

the current issue is value returns a string object : '{"$lte":1,"$gte":0.5,"$exists":true"}'
and as far as I know, mongo is not able to find with a str expression but with a dict.
I want this too if I need to write even more complicated requests with "$or" nested in a "$and" expression:
{"$and":[
         {"size":{"$lte":100}},
         { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] }
         ]
}

and just have to write in an input the following example:
enter your request: {"$and":[
             {"size":{"$lte":100}},
             { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] }
             ]}

in order to be able to execute:
find_mongo = input("enter your request: ")
db.collection.find(find_mongo)

Sure it's easier from the mongoshell, but if I don't request from mongoshell is because I want to make transformation of the files of the request in python.
Besides I am not searching for a solution to obtain {"$lte":1,"$gte":0.5,"$exists":true"}. Honestly with some reflections, conditions and iterations, I think I am able to find a way. I am really searching if it is possible to enter and return an object, here a dict and not an str one, through the input() user. Just because it's easier for me if such a solution does exist.
Notes: Ubuntu 18.04, Python 3.7.1


text:
Q: How to enable the "Always encrypt new EBS volumes" regionwide setting? AWS has this "automatic encryption" setting that I'd like to turn on for my account: https://aws.amazon.com/premiumsupport/knowledge-center/ebs-automatic-encryption/.
I've spent a while poking around, and I cannot figure out how to enable that setting with CDK. Is it possible?
Possibly relevant links from my research:

*

*It looks like terraform supports this: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ebs_encryption_by_default

*Here are the awscli docs on this: https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/enable-ebs-encryption-by-default.html

*It looks like CDK has an AWS Config rule for this: https://github.com/aws/aws-cdk/blob/v2.13.0/packages/@aws-cdk/aws-config/lib/rule.ts#L661-L665, but AFAIK, that's just to get warnings when you don't have this setting turned on, which is nice, but doesn't actually turn the setting on for me

A: Is it possible to share code?? I guess you need to do something like below  (btw this is python code)
host = ec2.BastionHostLinux(self, "BastionHost",
    vpc=vpc,
    block_devices=[ec2.BlockDevice(
        device_name="EBSBastionHost",
        volume=ec2.BlockDeviceVolume.ebs(10,
            encrypted=True
        )
    )]
)

look at 'encrypted=True' option, which will encrypt your EBS volumes.
Reference : https://docs.aws.amazon.com/cdk/api/v1/python/aws_cdk.aws_ec2/EbsDeviceOptions.html
(Not sure if this was your requirement)


text:
Q: Error: unexpected '}' in "}" in an if condition I am trying do a for loop with an if statement. It didn't work, so I took out the "if" condition. I made it work. That is, the following code
if (data$mis[3] = "mis") {
print ("George Bush")
   }

Outputs "Geoge Bush"
However, it also says:

Error: unexpected '}' in "}"

Any idea why that might be?

A: This was an issue of the logical operator.  It should be == and not = (which can also be used as assignment)
 if (data$mis[3] == "mis") {
    print ("George Bush")
 }

It is not clear about the class of 'mis'.  If it is factor class, convert to character before doing the logical operation
 if (as.character(data$mis[3]) == "mis") {
        print ("George Bush")
 }

EDIT: A Typo in the second for loop fixed


text:
Q: Is oversmart a correct word? I have heard several people using the word "oversmart" or "over smart" to indicate that person is trying to act extra smartly. Is this a correct word? Does it make any sense?

A: "Oversmart" is not a word that I have come across before (appreciating that language changes all the time/over time, and that I am not the Lord and Arbiter of All English).
It feels like a business buzzword—possibly a contraction of "overly smart"—for which I presume the intention is to convey one of two opinions, in a mildly disparaging manner:

*

*either that the person has devised a complex solution to a problem, where a simpler solution is apparent;

*or that the person thinks they are being cleverer than they actually are; for instance, they may be attempting to win an argument with a person by attempting to confuse them, but have underestimated their target's ability to understand (or recognise the attempt).

The first option can potentially be softened to overengineered (when describing the solution) or overthinking (when describing the process of coming up with the solution).  This is possibly where the over- prefix has come from.  For example:

*

*"You are overthinking the problem." (especially in cases of decision paralysis)

*"He is overthinking it."

*"You have overengineered the solution."

*"You are overengineering the solution."

*"She has overengineered the solution."

*"The solution is overengineered."

The second might simply be better inferred with too clever, e.g. :

*

*"You are too clever by half" (or sometimes "too clever by far")

*"She is too clever by half"

*"You are too clever for your own good" (note a possible veiled threat of escalation/retaliation here)

*"He is too clever for his own good"

However, if this is a business buzzword, and it is being used in your line of business, you may just be better off using that term amongst your peers, until it falls out of favour.
PS.  Ngram suggests that it isn't very widely used (I always compare to "the", which hits about 6%)...

Trends suggest only occasional spikes (at least in the in the US):

A bit more interest in India:


text:
Q: Цепочка вызовов не сохраняет предыдущий результат Как сделать так, чтобы предыдущий add(2, 'years) прибавил 2 года, сохранил, а потом add(1, 'years') прибавил к уже сохраненному результату еще 1 год?
var time = function (date) {
  var arr = date.split(/[\s-:]/);

  var objTime = {
    newDate: new Date (arr[0], arr[1] - 1, arr[2], arr[3], arr[4]),

    add: function (value, string) {

      if (value > 0) {
         if (string == 'years') {
          this.newDate.setFullYear(value + +arr[0]);
          return this;
         }
         else if (string == 'months') {
          myDate.setMonth(value + +arr[1]);
          this.newDate = myDate;
          return this;
         }
         else if (string == 'days') {
          myDate.setMonth(arr[1] - 1, value + +arr[2]);
          this.newDate = myDate;
          return this;
         }
         else if (string == 'hours') {
          myDate.setHours(value + +arr[3]);
          this.newDate = myDate;
          return this;
         }
         else if (string == 'minutes') {
          myDate.setMinutes(value + +arr[4]);
          this.newDate = myDate;
          return this;
         } else {
          return TypeError('Передано неверное значение');
         }
      } else {
        return TypeError('Передано неверное значение');
      }
  },

  substract: function (value, string) {
    if (value > 0) {
       if (string == 'years') {
        myDate.setFullYear(+arr[0] - value);
        this.newDate = myDate;
        return this;
       }
       else if (string == 'months') {
        myDate.setMonth(+arr[1] - value);
        this.newDate = myDate;
        return this;
       }
       else if (string == 'days') {
        myDate.setMonth(arr[1] - 1, +arr[2] - value);
        this.newDate = myDate;
        return this;
       }
       else if (string == 'hours') {
        myDate.setHours(+arr[3] - value);
        this.newDate = myDate;
        return this;
       }
       else if (string == 'minutes') {
        myDate.setMinutes(+arr[4] - value);
        this.newDate = myDate
        return this;
       } else {
        throw new TypeError('Передано неверное значение');
       }
    } else {
      throw new TypeError('Передано неверное значение');
    }
  }
};

  return objTime;

};

console.log(time('2017-05-16 13:45').add(2, 'years').add(1, 'years'));

A: Не используйте arr в add и subtract. Я исправил для add - years.
Что такое myDate?

var time = function(date) {
  var arr = date.split(/[\s-:]/);

  var objTime = {
    newDate: new Date(arr[0], arr[1] - 1, arr[2], arr[3], arr[4]),

    add: function(value, string) {

      if (value > 0) {
        if (string == 'years') {
          this.newDate.setFullYear(value + this.newDate.getFullYear());
          return this;
        } else if (string == 'months') {
          myDate.setMonth(value + +arr[1]);
          this.newDate = myDate;
          return this;
        } else if (string == 'days') {
          myDate.setMonth(arr[1] - 1, value + +arr[2]);
          this.newDate = myDate;
          return this;
        } else if (string == 'hours') {
          myDate.setHours(value + +arr[3]);
          this.newDate = myDate;
          return this;
        } else if (string == 'minutes') {
          myDate.setMinutes(value + +arr[4]);
          this.newDate = myDate;
          return this;
        } else {
          return TypeError('Передано неверное значение');
        }
      } else {
        return TypeError('Передано неверное значение');
      }
    },

    substract: function(value, string) {
      if (value > 0) {
        if (string == 'years') {
          myDate.setFullYear(+arr[0] - value);
          this.newDate = myDate;
          return this;
        } else if (string == 'months') {
          myDate.setMonth(+arr[1] - value);
          this.newDate = myDate;
          return this;
        } else if (string == 'days') {
          myDate.setMonth(arr[1] - 1, +arr[2] - value);
          this.newDate = myDate;
          return this;
        } else if (string == 'hours') {
          myDate.setHours(+arr[3] - value);
          this.newDate = myDate;
          return this;
        } else if (string == 'minutes') {
          myDate.setMinutes(+arr[4] - value);
          this.newDate = myDate
          return this;
        } else {
          throw new TypeError('Передано неверное значение');
        }
      } else {
        throw new TypeError('Передано неверное значение');
      }
    }
  };

  return objTime;

};

console.log(time('2017-05-16 13:45').add(2, 'years').add(1, 'years'));


text:
Q: Array detect method - return the value of a specific sub-array index? (ruby 1.86)
I have an array made up of arrays like:
>> myArray
=> [["apple", 1], ["bananna", 2], ["peach", 3], ["orange", 4]]

I know I can use the detect method to find the first instance of 'orange' in index[0] of the sub-arrays in MyArray:
myTest = (myArray.detect { |i| i[0] == 'orange' } || []).first
=> orange

If it's possible, how can I have the detect method return the value of the sup-array index position 1.  Like, i[0] is being returned, but when i[0] == 'orange' I need i[1] returned.
I need to search for 'orange' and have the return value be 2.
Thank You!

A: I suppose you want the return value to be 4. No need for #detect:
ar = [["apple", 1], ["bananna", 2], ["peach", 3], ["orange", 4]]
puts ar.assoc("orange").last

#=> 4

A: I'd recommend using a hash. It better suits the usage you describe, and will be faster for large amounts of data.
fruit = {'apple'=>1, 'banana'=>2, 'peach'=>3, 'orange'=>4, 'kiwi'=>42}

puts fruit['orange'] #=> 4

But if you really want to retrieve the value from your subarray, change your first to last:
myTest = (myArray.detect { |i| i[0] == 'orange' } || []).last
#=> 4

Update: or even simpler, as @steenslag points out:
myTest = myArray.assoc("orange").last
#=> 4


text:
Q: Adding local dependency in a Typescript project doesn't work when it works in JS I have been able to import a local package into a project by running yarn link ../path, which adds a resolution field to the package.json to tell the bundler where to find a package, basically giving it an alias.
Weird thing is that while this works when the file I'm doing the importing from is .jsx, not changing anything else, if I'm importing from .tsx, the module is not found.
So the culprit could be ts-loader, Typescript (how it treats imports), webpack, or yarn. I don't know if this is because I'm doing something wrong or this is a bug.
So the folder structure might be:
--ProjectMain
  ----/src
  ------index.jsx
  ----package.json

--ProjectToImport
  ----/src
  ------index.js
  ----package.json

I have the following in webpack.config.js in ProjectMain
module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /\.yarn/,
      },
      {
        test: /\.jsx?$/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-react']
          },
        },
        exclude: /\.yarn/
      }
    ],
  },

ProjectToImport's index.js looks like
export function SharedLibTest(a){
  console.log(a)
}

A: Seems like the whole thing was because in my ProjectToImport/package.json, I used "main": "/src/index.js", instead of "main": "src/index.js"
I don't know why this makes a difference just because I'm using TS, may the wise among you enlighten me.


text:
Q: Cannot read properties of undefined (reading 'showOpenDialog') I keep getting this error:
TypeError: Cannot read properties of undefined (reading 'showOpenDialog')

How can I call showOpenDialog() with the most minimal changes?
I am using the new Quasar/Electron with Webpack 5.
Here is the openFile() method in my vue file:
    openFile () {
      window.electronApi.dialog.showOpenDialog({
        title: 'Load File',
        properties: ['openFile']
      }).then(result => {
        const filename = result.filePaths[0]

        if (filename) {
          const extension = getExtensionName(filename)
          console.log(extension)
        } else {
          console.log('No file selected')
        }
      }).catch(err => {
        console.log(FILE + 'Error: ' + err)
      })
    },

And here is what is declared in electron-preload.js:

import { contextBridge} from 'electron'

contextBridge.exposeInMainWorld('electronApi', {
  dialog: require('electron').dialog,
  showOpenDialog: require('electron').showOpenDialog
})

A: Thank you for @creative learner's idea! This works!
import { contextBridge} from 'electron'
import { dialog } from '@electron/remote'

contextBridge.exposeInMainWorld('electronApi', {
  dialog: dialog
})


text:
Q: getting google map searched location review and information i am wondering if there is any way we can pull the reviews and information of a location/store/shop/building from google map info, check following url please.
http://maps.google.com/maps?cid=16753855001018446220
http://maps.google.com/places/us/california/san-francisco/24th-st/2884/-la-palma-mexicatessen

A: I think you want to use  Google Maps Local Search APIs.
Or to use Something like ax said in this post

if you are a business owner, you can
  interact with this information.
  maps.google.com/support/bin/… :
  However, the basic information that
  you submit through the Local Business
  Center is the information that we
  trust the most. This means that it
  will appear instead of any basic
  information that we get from anywhere
  else. and you can upload photos and
  videos: maps.google.com/support/bin/…

note that you can not Add Review check this for more info

A: You'll probably want to hit up the Google Maps Local Search APIs.
Upon completion of a google.search.LocalSearch() search it delivers a collection of GlocalResult objects. This contains Local business results, but you don't have any further control over them. There doesn't seem to be an explicit Local Business API.
I couldn't find any mention of reviews or Business reviews, have you considered emailing / otherwise contacting some google contacts asking about this?

A: You can get the URL of the info page pretty easily. Like TreeUK initially suggested, use the local search API, and upon its completion, you'll have access to yourSearcher.results. For each one, just grab result.url (or yourSearcher.results[i].url to be more precise) to get the info page.
If you want the direct link to the reviews page, modify the result.url a bit...
var baseUrl = 'http://www.google.com/maps/place?';
var cid = result.url.match(/cid=\d*/gi)[0];
var reviewsUrl = baseUrl + cid + '&view=feature&mcsrc=detailed_reviews';

...then do what you want with reviewsUrl.
If you want more reviews, add the num (and optionally the start) parameter to the query string:
var reviewsUrl = baseUrl + cid + '&view=feature&mcsrc=detailed_reviews&num=100&start=0';

So, really all you need is the cid. Once you have that, you can get at any of the other info.


text:
Q: How to enable IntelliSense and indexer at the same time in typescript? For example, I have an object:
const obj = {
  a: (valueA: string) => true;
  b: (valueB: string) => false;
  c: (valueC: string) => false;
};

You see all properties in this object have same type ((value: string) => boolean). Now I want it to have IntelliSense which makes follows possible:

*

*Display a, b, c after I typed obj.;

*Limit its type when I try to add a property into obj.

I tried indexer:
const obj: Record<string, ((value: string) => boolean)> = {
  a: (valueA: string) => true;
  b: (valueB: string) => false;
  c: (valueC: string) => false;
};

But now target 1 won't happen, if I don't use indexer, I cannot achieve target 2.

A: Variable inference is either all or nothing, you either let typescript infer the type or you specify the type yourself.
You can only do this with a helper function:
function makeFunctionsMap<T extends Record<string, ((value: string) => boolean)>>(o: T) { return o; }
const obj = makeFunctionsMap({
  a: (valueA: string) => true,
  b: (valueB: string) => false,
  c: (valueC: string) => false,
})
obj.a;
obj.d // Error

Playground Link
You can also inline the function if you want to make it shorter and more unreadable (Playground Link)


text:
Q: HTML window open in IE This works fine in Chrome. But in IE it opens a window, and the current window from where the hyperlink is clicked goes blank. How do I fix this?

    86C2EC58

A: put ;void(0) after your window.open
like this:
    86C2EC58

Or just use the A element without the javascript and with target="_blank":
86C2EC58


text:
Q: How do I sort using two fields? I have a sorting/grouping issue that I'm hoping somebody could add some insight on.
We have a table of stories that have a publish date and an updated date.  I'm using Django so it looks like this:
class Story(models.Model):
    pub_date = models.DateTimeField(db_index=True)
    update_date = models.DateTimeField(blank=True, null=True, db_index=True)
    headline = models.CharField(max_length=200)
    ...

We want to display the stories on a paginated page grouped by day.  So...
Jan 20
    Story 1
    Story 2

Jan 19
    Story 1
    Story 3

The challenge is that if a story has an update_date it should be displayed twice, once on the pub_date day, and once on the update_day date (e.g. Story 1).
There are 10s of thousands of stories so I can't do it all in python of course, but I don't know of a way to do this query in SQL.
What I have right now is sorting everything by -pub_date and then getting a range of the max and min dates on a given page.  I then query for any stories between those dates with an update_date and combine and group them in python.  The problem is that the number of items on a page is irregular then.
So I guess my question is this:  What is the best way to query a table for a list of items and sort them based on two fields, duplicating an item in the query if it has a value in the second field, and then sorting based on the two fields?
Hope that makes sense...

A: i can only think of "union" being able to do this.
here's an example of what that would look like. not sure how fast or good it is for the database to have this type of query sent to it often though D:
the query assumes your table name is stories, and uses the columns headline, pub_date and update_date. it also assumes that a story that hasn't been updated has the value null in the update_date column.
SELECT      headline,
            the_date,
            DAY(the_date) AS the_day
FROM (
    SELECT      headline,
                pub_date AS the_date
    FROM        stories
    UNION
    SELECT      headline,
                update_date AS the_date
    FROM        stories
    WHERE       update_date IS NOT NULL
) AS publishedandupdated
ORDER BY    the_date DESC;

if you want to add a limit to the query, it should be done last, after the "order by" clause.

A: your question is similar to what I had. I read some items from Facebook walls. I had two dates, one on item creation(user posts the item), one on item retrieval(I read the item from Facebook). I wanted to show items that are posted or retrieved today.
SELECT link,time FROM homeWallItems WHERE
DATE_SUB(CURDATE(),INTERVAL 1 DAY)<= created
OR
DATE_SUB(CURDATE(),INTERVAL 1 DAY)<= time
group by time LIMIT 0,30

Edit: I was over optimistic in this sentence: It is wrong.

in this code, instead of CURDATE(),
  if you use time, then it should work
  you.

A: Making some assumptions on the column names, you need UNION ALL to retain duplicates from both parts.
    select headline, actualdate=pub_date
    from story
    where pub_date between /mindate/ and /maxdate/
union all
    select headline, actualdate=update_date
    from story
    where update_date between /mindate/ and /maxdate/
order by actualdate

*

*The virtual field actualdate is used to match up the pub_date / update_date as a single column on which to ORDER BY.

*The ORDER BY in a union-ed statement is applied AFTER the union has been done, so it only needs to appear once.

*the filter on the date range is applied within each part of the union, to reduce the worktable size (it shouldn't have to pull in all data unnecessarily before applying the filter)


text:
Q: Beginner Haskell: Making a last function with reverse I'm attempting to make a function that generates the last item in a list. I want to use reverse and !!. This is what I have so far:
myLast :: [a] -> [a] -> Int -> a
myLast xs = (reverse xs) !! 1

I know the problem lies somewhere within the type, but I'm having trouble identifying how to fix it.

A: A function's type signature has nothing to do with what you use in the function, it only describes how other people can use this function you're defining. So by writing
myLast :: [a] -> [a] -> Int -> a

you're saying, users need to supply two lists and and integer. Just to get the last element of one of the lists?? That doesn't make sense.
You surely mean
myLast :: [a] -> a

You should generally write that down before even thinking about how you're going to implement that function.
With that signature, you can write various implementations:
myLast :: [a] -> a
myLast xs = head $ reverse xs

myLast' :: [a] -> a
myLast' [l] = l
myLast' (_:xs) = myLast' xs

myLast'' :: [a] -> a
myLast'' = fix $ \f (x:xs) -> maybe x id . teaspoon $ f xs

or whatever weird implementation you choose, it has nothing to do with the signature.
On an unrelated note: though last is actually a standard function from the prelude, it's a kind of function avoided in modern Haskell: last [] gives an error, because the is no a value to be found in the empty list! Errors are bad. Hence the "ideal" way to write it is actually
myLast :: [a] -> Maybe a
myLast [] = Nothing
myLast [x] = x
myLast (_:xs) = myLast xs

A: I would recommend not using !! at all, but to use head.
myLast xs = head (reverse xs)

Head returns the first element of the list it is given as argument.
If you insist on using !!, in Haskell arrays are indeed zero-based, which means that !! 0 gets the first element, !! 1 the second, etc.
As for the type: myLast takes an array of some type and returns one item of that same type. That is denoted as follows:
myLast :: [a] -> a

 @leftaroundabout covered this way better in his answer.

A: Based on @leftaroundabout 's answer, here's an implementation that should do what you want:
safeHead :: [a] -> Maybe a
safeHead [] = Nothing
safeHead (x:_) = Just x

myLast :: [a] -> Maybe a
myLast [] = Nothing
myLast xs = safeHead $ reverse xs

The Maybe type is constructed as follows (from Hackage):
data  Maybe a  =  Nothing | Just a
  deriving (Eq, Ord)

myLast [1, 2, 3, 4], for example, will return Just 4. If you want to use the value 4 you can use the function fromJust function from the Data.Maybe module (fromJust (Just 4) returns 4). fromJust is defined like this:
-- | The 'fromJust' function extracts the element out of a 'Just' and
-- throws an error if its argument is 'Nothing'.
--
-- ==== __Examples__
--
-- Basic usage:
--
-- >>> fromJust (Just 1)
-- 1
--
-- >>> 2 * (fromJust (Just 10))
-- 20
--
-- >>> 2 * (fromJust Nothing)
-- *** Exception: Maybe.fromJust: Nothing
--
fromJust          :: Maybe a -> a
fromJust Nothing  = error "Maybe.fromJust: Nothing" -- yuck
fromJust (Just x) = x


text:
Q: How to implement NestedScrolling on Android? With support-v4 library 22.1.0 android supports nested scrolling (pre android 5.0). Unfortunately, this feature is not really documented. There are two interfaces (NestedScrollingParent and NestedScrollingChild) as well as two helper delegate classes (NestedScrollingChildHelper and  NestedScrollingParentHelper).
Has anyone worked with NestedScrolling on Android?
I tried to setup a little example, where I use NestedScrollView which implements both NestedScrollingParent and NestedScrollingChild.
My layout looks like this:
<android.support.v4.widget.NestedScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/parent"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

  <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical">

    <View
        android:id="@+id/header"
        android:layout_width="match_parent" android:layout_height="100dp"
        android:background="#AF1233"/>

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/child"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >

      <FrameLayout
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#12AF33"
            android:text="@string/long_text"/>

      </FrameLayout>
    </android.support.v4.widget.NestedScrollView>

  </LinearLayout>

</android.support.v4.widget.NestedScrollView>

I want to display a header view and another NestedScrollView (id = child) in a NestedScrollView (id = parent).
The idea was, to adjust the height of the child scroll view at runtime by using a OnPredrawListener:
public class MainActivity extends Activity {

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

    final NestedScrollView parentScroll = (NestedScrollView) findViewById(R.id.parent);
    final NestedScrollView nestedScroll = (NestedScrollView) findViewById(R.id.child);
    parentScroll.setNestedScrollingEnabled(false);
    final View header = findViewById(R.id.header);

    parentScroll.getViewTreeObserver()
        .addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
          @Override public boolean onPreDraw() {
            if (parentScroll.getHeight() > 0) {
              parentScroll.getViewTreeObserver().removeOnPreDrawListener(this);
              nestedScroll.getLayoutParams().height = parentScroll.getHeight() - 40;
              nestedScroll.setLayoutParams(nestedScroll.getLayoutParams());
              nestedScroll.invalidate();
              return false;
            }
            return true;
          }
        });

  }
}

So the header view will be scrolled away partially, 40 pixels will remain visible since I set the height of the nested child scroll view to parentScroll.getHeight() - 40.
Alright, setting the height at runtime and scrolling the parent scroll view works like expected (header scrolls out, 40 pixels remain visible and then the child scrollview fills the rest of the screen below the header).
I would expect that "NestedScrolling" means that I can make a scroll gesture anywhere on the screen (touch event caught by parent scroll view) and if the parent scroll view has reached the end the nested child scroll view beginns to scroll.
However that seems not to be the case (neither for simple scroll gestures nor for fling gestures).
The touch event is always handled by nested child scrollview if the touch event begins in its boundaries, otherwise by the parent scrollview.
Is that the expected behaviour of "nested scrolling" or is there an option to change that behaviour?
I also tried to replace the nested child scroll view with a NestedRecyclerView. I subclassed RecyclerView and implemented NestedScrollingChild where I delegate all methods to NestedScrollingChildHelper:
public class NestedRecyclerView extends RecyclerView implements NestedScrollingChild {

  private final NestedScrollingChildHelper scrollingChildHelper =
      new NestedScrollingChildHelper(this);

  public void setNestedScrollingEnabled(boolean enabled) {
    scrollingChildHelper.setNestedScrollingEnabled(enabled);
  }

  public boolean isNestedScrollingEnabled() {
    return scrollingChildHelper.isNestedScrollingEnabled();
  }

  public boolean startNestedScroll(int axes) {
    return scrollingChildHelper.startNestedScroll(axes);
  }

  public void stopNestedScroll() {
    scrollingChildHelper.stopNestedScroll();
  }

  public boolean hasNestedScrollingParent() {
    return scrollingChildHelper.hasNestedScrollingParent();
  }

  public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed,
      int dyUnconsumed, int[] offsetInWindow) {

    return scrollingChildHelper.dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed,
        dyUnconsumed, offsetInWindow);
  }

  public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
    return scrollingChildHelper.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow);
  }

  public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
    return scrollingChildHelper.dispatchNestedFling(velocityX, velocityY, consumed);
  }

  public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
    return scrollingChildHelper.dispatchNestedPreFling(velocityX, velocityY);
  }
}

but the NestedRecyclerView doesn't scroll at all. All touch events are caught by the parent scroll view.

A: I spent quite a bit of time on this just going through android code trying to figure out what's going on in NestedScrollView.  The following should work.
public abstract class ParentOfNestedScrollView extends NestedScrollView{

    public ParentOfNestedScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /*
    Have this return the range you want to scroll to until the
    footer starts scrolling I have it as headerCard.getHeight()
    on most implementations
    */
    protected abstract int getScrollRange();

    /*
    This has the parent do all the scrolling that happens until
    you are ready for the child to scroll.
    */
    @Override
    public void onNestedPreScroll(View target, int dx, int dy, int[] consumed){
        if (dy > 0 && getScrollY() < getScrollRange()) {
            int oldScrollY = getScrollY();
            scrollBy(0, dy);
            consumed[1] = getScrollY() - oldScrollY;
        }
    }

    /*
    Sometimes the parent scroll intercepts the event when you don't
    want it to.  This prevents this from ever happening.
    */
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return false;
    }
}

Some of my code was borrowed from this question.  From this I just extend this class as needed.  My xml has the child as a NestedScrollView as a child and the parent as this.  This doesn't handle flings as well as I would like, that's a work in progress.


text:
Q: How do I use the "where" parameter to add the picture at the end of an array? This method is supposed to insert the picture at the position given by the where parameter value.
I am confuse on how to use the where parameter.
This is what I have so far:
public boolean addPicture( Picture thePicture, int where )
{
    int index = where;
    while( index < pictArray.length )
    {
        pictArray[pictArray.length - 1] = thePicture;
    }
    return true;
}

A: If you already know where to add the Picture, Just add it to that position on the Picture array Index-1 position. This is because Indexing in java Starts with a 0.But we as humans start it from 1.
Like if it is to be added on the 3rd position according to the user. He inputs 3 in the Where variable. Java will have to store it on the index 2 of the array.
PicArray[index-1]=picture;


text:
Q: Ads not showing up in AdView I am new to integrate AdMob with android. I got a issue that Ads not showing up in AdView. I already linked firebase to my AdMob account. Upto my findings this should display ads. But I don't know Why this occurs
My Activity,
MobileAds.initialize(MainActivity.this, "my-id");

AdView adView = (AdView) findViewById(R.id.adview);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);

Layout,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<android.support.v7.widget.RecyclerView
    android:id="@+id/main_recycler_view"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:background="@color/colorGrey"
    android:scrollbars="vertical" />

<com.google.android.gms.ads.AdView
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/adview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_alignParentBottom="true"
    ads:adSize="BANNER"
    ads:adUnitId="@string/banner_ad_unit_id">
</com.google.android.gms.ads.AdView>

My log,
04-16 19:38:26.146 10178-10268/com.example.my.app W/zygote64: Skipping duplicate class check due to unrecognized classloader
04-16 19:38:26.150 10178-10264/com.example.my.app W/VideoCapabilities: Unrecognized profile 2130706433 for video/avc
04-16 19:38:26.150 10178-10264/com.example.my.app W/VideoCapabilities: Unrecognized profile 2130706434 for video/avc
04-16 19:38:26.151 10178-10178/com.example.my.app I/Ads: Starting ad request.
04-16 19:38:26.154 10178-10178/com.example.my.app I/Ads: Use AdRequest.Builder.addTestDevice("FFD5F3261542E02E3D30EE7D21F08733") to get test ads on this device.
04-16 19:38:26.157 10178-10178/com.example.my.app W/Ads: Not retrying to fetch app settings
04-16 19:38:26.177 10178-10264/com.example.my.app W/VideoCapabilities: Unrecognized profile 2130706433 for video/avc
04-16 19:38:26.177 10178-10264/com.example.my.app W/VideoCapabilities: Unrecognized profile 2130706434 for video/avc
04-16 19:38:26.183 10178-10264/com.example.my.app W/VideoCapabilities: Unrecognized profile 2130706433 for video/avc
04-16 19:38:26.183 10178-10264/com.example.my.app W/VideoCapabilities: Unrecognized profile 2130706434 for video/avc
04-16 19:38:26.196 10178-10264/com.example.my.app W/VideoCapabilities: Unrecognized profile/level 0/3 for video/mpeg2
04-16 19:38:26.201 10178-10264/com.example.my.app W/VideoCapabilities: Unrecognized profile/level 0/3 for video/mpeg2
04-16 19:38:26.211 10178-10279/com.example.my.app W/Ads: Invoke Firebase method getInstance error.
04-16 19:38:26.211 10178-10279/com.example.my.app W/Ads: The Google Mobile Ads SDK will not integrate with Firebase. Admob/Firebase integration requires the latest Firebase SDK jar, but Firebase SDK is either missing or out of date
04-16 19:38:26.213 10178-10264/com.example.my.app W/VideoCapabilities: Unsupported mime video/x-ms-wmv
04-16 19:38:26.216 10178-10264/com.example.my.app W/VideoCapabilities: Unsupported mime video/x-ms-wmv
04-16 19:38:26.218 10178-10264/com.example.my.app W/VideoCapabilities: Unsupported mime video/divx
04-16 19:38:26.221 10178-10264/com.example.my.app W/VideoCapabilities: Unsupported mime video/divx311
04-16 19:38:26.226 10178-10264/com.example.my.app W/VideoCapabilities: Unsupported mime video/divx4
04-16 19:38:26.227 10178-10178/com.example.my.app D/AppTracker: App Event: start
04-16 19:38:26.236 10178-10183/com.example.my.app I/zygote64: Do partial code cache collection, code=61KB, data=43KB
04-16 19:38:26.247 10178-10183/com.example.my.app I/zygote64: After code cache collection, code=61KB, data=43KB
04-16 19:38:26.247 10178-10183/com.example.my.app I/zygote64: Increasing code cache capacity to 256KB
04-16 19:38:26.270 10178-10264/com.example.my.app W/VideoCapabilities: Unsupported mime video/mp4v-esdp
04-16 19:38:26.324 10178-10264/com.example.my.app I/VideoCapabilities: Unsupported profile 4 for video/mp4v-es
04-16 19:38:26.578 10178-10315/com.example.my.app W/cr_CrashFileManager: /data/user/0/com.example.my.app/cache/WebView/Crash Reports does not exist or is not a directory
04-16 19:38:26.579 10178-10178/com.example.my.app I/chromium: [INFO:CONSOLE(0)] "Document was loaded from Application Cache with manifest https://googleads.g.doubleclick.net/mads/static/mad/sdk/native/sdk-core-v40-loader.appcache", source: https://googleads.g.doubleclick.net/mads/static/mad/sdk/native/sdk-core-v40-loader.html (0)
04-16 19:38:26.580 10178-10178/com.example.my.app I/chromium: [INFO:CONSOLE(0)] "Application Cache Checking event", source: https://googleads.g.doubleclick.net/mads/static/mad/sdk/native/sdk-core-v40-loader.html (0)
04-16 19:38:26.746 10178-10288/com.example.my.app W/Ads: There was a problem getting an ad response. ErrorCode: 0
04-16 19:38:26.750 10178-10178/com.example.my.app W/Ads: Failed to load ad: 0
04-16 19:38:26.953 10178-10178/com.example.my.app I/chromium: [INFO:CONSOLE(0)] "Application Cache NoUpdate event", source: https://googleads.g.doubleclick.net/mads/static/mad/sdk/native/sdk-core-v40-loader.html (0)
04-16 19:38:48.880 10178-10178/com.example.my.app D/AppTracker: App Event: stop
04-16 19:41:11.526 10178-10178/com.example.my.app D/AppTracker: App Event: start
04-16 19:41:41.449 10178-10178/com.example.my.app D/AppTracker: App Event: stop

Please help me to sort out this issue.

A: Sometimes ads are not matched, and it's not displayed. you should add listener to AdView and check out the error code.
mAdView.setAdListener(new AdListener() {
    @Override
    public void onAdLoaded() {
        super.onAdLoaded();
         System.out.println("onAdLoaded() CALLBACK");
    }

    @Override
    public void onAdFailedToLoad(int errorCode) {
        super.onAdFailedToLoad(errorCode);
         System.out.println("onAdFailedToLoad() CALLBACK code: " + errorCode);
    }
});


text:
Q: Rails disable edit update delete routes I am trying to find a way to disable  resource routes like edit destroy and update. It can be done using this answer. Disable Route In this answer I can put code like this:
resources :books, except: [:edit, :destroy]

And it will work but I have a unique problem I have created many resource routes and my route file is like this:
         resources :expenditure_management2s do
                            collection { post :import }
                            collection { get :dropdown }
                            collection { get :test }
                            end
        resources :expenditure_management1s do
                            collection { post :import }
                            collection { get :dropdown }
                            collection { get :test }
                            end
        resources :expenditure_managements do
                            collection { post :import }
                            collection { get :dropdown }
                            collection { get :test }
                            end
                 ......

I have almost 100 routes like this If I have to change these methods one by one it would be a tough task. Is there any way where I can group these route into some method and reject edit update and destroy for all resource route.

A: I think you can you use a scope in your routes.rb file like this:
scope except: [:edit, :destroy] do
  resources :users
end

Will return the routes:
users     GET   /users(.:format)   users#index
          POST  /users(.:format)   users#create
new_user  GET   /users/new(.:format)   users#new
user      GET   /users/:id(.:format)   users#show
          PATCH /users/:id(.:format)   users#update
          PUT   /users/:id(.:format)   users#update

As you can see the users#destroy and users#edit routes are missing.
In your case, it would be:
 scope except: [:edit, :destroy] do
    resources :expenditure_management2s do
                        collection { post :import }
                        collection { get :dropdown }
                        collection { get :test }
                        end
    resources :expenditure_management1s do
                        collection { post :import }
                        collection { get :dropdown }
                        collection { get :test }
                        end
    resources :expenditure_managements do
                        collection { post :import }
                        collection { get :dropdown }
                        collection { get :test }
                        end
 end