text:
Q: Column in table not getting updated but not showing error Hello everyone I'm getting confused because when I'm running a code with some condition only 1 column getting updated and the others column stay null, I'm sure there is no typo with the column name in table nor in code here is my code :
public function solusi_line($id)
{
    $idasli  = base64_decode($id);
    $solusi = solusi::where('request_id', $idasli)->orderBy('created_at', 'asc')->get();
    $count = solusi::where('request_id', $idasli)->orderBy('created_at', 'desc')->count();
    $cekakun = Session::get('id');
    $adminkah = Admin::where('user_id', $cekakun)->count();
    // dd($solusi);
    //jika admin ke bagian sini
    if ($adminkah != 0) {
        # code...
        return view('admin.detail_feedback', compact('solusi', 'count'));
    } else {
        return view('user.detailfeedback_user', compact('solusi', 'count'));
    }

    //klo user kebagian user

}
public function FirstFeedback($id)
{
    $datas = Kirim::where('id', $id)->first();
    return view('admin.detailprogress', compact('datas'));
}
//solusi dari admin
public function solusiPost(Request $request)
{
    $itungsolusi = solusi::where('request_id', $request->idRequest)->count();
    $data = new solusi();
    $data->request_id = $request->idRequest;
    $data->pengirim_id = Session::get('id');
    $data->penerima_id = $request->idPenerima;
    $data->solusi = $request->solusi;
    $file = $request->file('lampiran_solusi');
    if (!empty($file)) {
        $ext = $file->getClientOriginalExtension();
        $name = time() . '.' . $ext;
        $file->move('upload/lampiran/', $name);
        $data->lampiran = $name;
        $data->url_lampiran = url('upload/lampiran') . "/" . $name;
    } else {
        $data->lampiran = null;
        $data->url_lampiran = null;
    }
    if ($data->save()) {
        //matiin sementara
        $check = DB::table('kirims')->where('id', $data->request_id)->first();
        $user = Kirim::find($check->id);
        // dd($user);
        if (!is_null($user)) {
            // $user->update(['status' => 'CheckByUser', 'status_feedback' => 'Ya']);
            $user->update(['remarks' => 'Ya', 'status' => 'CheckByUser', 'status_feedback' => 'Ya']);
        }
        //just status column is success to update but not the remarks and status_feedback column
        $id_solusi = $data->id;
        $thisUser = DB::table('kirims')
            ->join('simpan_users', 'kirims.pengirim_id', '=', 'simpan_users.user_id')
            ->join('solusis', 'kirims.id', '=', 'solusis.request_id')
            ->where('kirims.id', $data->request_id)
            ->where('solusis.id', $id_solusi)
            ->select('kirims.email', 'kirims.ticket_id', 'solusis.solusi', 'solusis.lampiran', 'solusis.url_lampiran')
            ->first();
        // dd($thisUser);

here the problem
$check = DB::table('kirims')->where('id', $data->request_id)->first();
        $user = Kirim::find($check->id);
        // dd($user);
        if (!is_null($user)) {
            // $user->update(['status' => 'CheckByUser', 'status_feedback' => 'Ya']);
            $user->update(['remarks' => 'Ya', 'status' => 'CheckByUser', 'status_feedback' => 'Ya']);
        }
        //just status column is success to update but not the remarks and status_feedback column

I really appreciate for any help, I getting stuck because laravel not showing error too, thank you.

A: use update statement like this.
 $user->remarks = 'Ya',
$user->status = 'CheckByUser',
$user->status_feedback = 'Ya'
$user->update();

few days ago i faced the same issue and fixed it as i told you .

A: You should check your Kirim model, where you need to define $fillable property. Something like below.
 class Kirim extends Model {

     protected $fillable = ['remarks', 'status', 'status_feedback',''];

     // All fields inside $fillable array can be mass-assigned

     }


text:
Q: Firing an Event on  end with JQuery selector I'm firing an event when a video is completed using:
video.addEventListener("ended", function() {
    //whatever
});

This works if I grab the selector via pure javascript: var video = document.getElementById('test');
This doesn't work if I grab the selector via jQuery: var video = $("#test");
Why is this the case? Here's the accompanying JSFiddle

A: Thats because $("#test") returns a jQuery object. Use $("#test").get(0) to get the first dom element.
var video = $("#test").get(0);

A: With jQuery, use the .on() method:
jqueryVideo.on("ended", function() {
    console.log('This Works 2');
});

http://jsfiddle.net/w4zahwk9/4/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript variable to html data attribute I am looking to be able to pass a javascript variable as data in an html table row element and have the data logged when that row element is click. The code that is appending/creating the table rows is inside an ajax call. Outside of the call in a click function I want to click on a table row that was created/appened and get the data variable. Here is the current code
$.ajax({
...
  var name = 'superman'
  $('#myTable tbody').append('

');
  });
...
$('#myTable tbody').on('click','table_class', function(){
    console.log($(this).dataset.name);
}

The expected result of the console log is to be: superman.

A: You have more errors:

*

*data-person= must be data-name

*$('#myTable tbody').on('click','table_class', function(){  should be:
$('#myTable tbody').on('click','.table_class', function(){

*$(this).dataset.  should be this.dataset or $(this).data

The snippet:

var name = 'superman';
$('#myTable tbody').append('
XXXX
');

$('#myTable tbody').on('click', '.table_class', function () {
    console.log(this.dataset.name);
})

A: If you are adding the class to the
, make sure you include at least one  child so that you can actually click on the row.

var table_id = 'table_id';
var table_class = 'table_class';

// AJAX logic start...
var name = 'superman';
$('#myTable tbody').append(
  $('
')
  .attr('id', table_id)
  .addClass(table_class)
  .data('person', name)
  .append(
    $('').text(name)
  )
);
// AJAX logic end...

$('#myTable tbody').on('click', `.${table_class}`, function() {
  console.log($(this).data('person'));
});
#myTable { border-collapse: collapse; }

#myTable, #myTable th, #myTable td { border: thin solid grey; }

#myTable th, #myTable td { padding: 0.5em; }

      Name


text:
Q: How to prevent the keras convolutional neural network model to over-fit? I want to build a convolutional neural network and train it to recognise whether the digit is 0 or 1.
Example of my training data is a 800 * 600 gray scale image containing a digit one:
I have 22 such images, 11 containing zeroes, 11 containing ones.
I now build a convolutional nerual network:
def addConvolutionalLayer(layer, newDepth = None):
    print(layer.get_shape().as_list())
    if newDepth is None:
        newDepth = layer.get_shape().as_list()[3] * 2
    newLayer = Conv2D(newDepth, kernel_size = (3, 3),
                activation = 'relu', padding='same') (layer)
    newLayer = Dropout(0.2) (newLayer)
    return Conv2D(newDepth, kernel_size = (3, 3),
        activation = 'relu', padding='same') (newLayer)

def buildModel():
    s = Input((600, 800, 1))
    d1 = addConvolutionalLayer(s, 32)
    d2 = addConvolutionalLayer(MaxPooling2D(4)(d1))
    d3 = addConvolutionalLayer(MaxPooling2D(4)(d2))
    d4 = addConvolutionalLayer(MaxPooling2D(4)(d3))
    f = Flatten()(d4)
    dense = Dense(64, activation='relu') (f)
    o = Dense(1, activation='sigmoid') (dense)
    model = Model(inputs = [s], outputs = [o])
    model.compile(optimizer='adam', loss='binary_crossentropy',
              metrics=['accuracy'])
    return model

model = buildModel()
model.compile(optimizer='adam',
        loss='binary_crossentropy',
        metrics=['accuracy'])

In short, a network consists of multiple convolutional layers (with MaxPooling included), ending with a dense layer.
I then split the data into training and test sets:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)

X_train, X_test are arrays of float values, each value corresponding
to the pixel in the image (1.0 for white, 0.0 for black).
y_train, y_test are lists containing 0 or 1 depending on the digit in the corresponding image.
Finally, I run the model to train:
model.fit(X_train, y_train, epochs = 50, validation_split=0.2)
model.save('prediction.h5')

The problem is that the model gets over-fitted: it reaches 100% accuracy on the training data, but does not perform well on the validation set:
Epoch 95/100
12/12 [==============================] - 0s 32ms/step - loss: 1.0640e-07 -
    acc: 1.0000 - val_loss: 10.7454 - val_acc: 0.3333

How to fix this issue?

A: First thing you could try is that remove Dropout in ConvBase and add before dense layers (need to experiment a bit on dropout percentage value), then experiment with different pre-processing techniques to augment the data. Most importantly check no.of parameters by getting summary of network and try to reduce the no.of parameters in case if no.of parameters are high.


text:
Q: How can I enable encryption for SQLite3 in PHP5.3? The php manual for SQLite3::open has this information:
public bool SQLite3::open (
    string $filename
    [, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE
    [, string $encryption_key ]]
)

Opens an SQLite 3 Database. If the build includes encryption, then it will attempt to use the key.

I would like to use encrypted SQLite databases for a project I'm working on, but I can't find any information anywhere on how to build the SQLite module including encryption.
Does anyone know how to do this?
Perhaps it's so obvious no one has published any information or perhaps only commercial modules are available.
I've noticed that the developers of SQLite offer a proprietary encryption extension. Is this the only way to go?

A: You can also use Berkeley DB, which has a SQLite-compatible SQL API and includes encryption as a part of the download.


text:
Q: Get Nearest Point with slick I have the following case class:
case class Block(

id: Option[Int] = None,

blockId: Int,

name: String,

location: Option[Point] = None,

geometry: Option[Geometry] = None,

)

In postgres i have a table SubBlock contient
id : int,
block_id: Int,
name: String,
geom_location: geography,
sub_block_geom: geography
And I define a function to return a subBlock nearest of a specified point
override def getNearestSubBlock(point: Point): Future[SubBlock] = {

val query = sql"""SELECT sub_block_id,block_id,name,ST_AsText(geom_location),sub_block_geom from now.sub_block order by ST_Distance(geom_location, ST_MakePoint(${point.getX()}, ${point.getY()})::geography) limit 1""".as[SubBlock].head

db.run(query)

}

implicit val getSubBlock = GetResult(r => SubBlock(r.nextIntOption(), r.nextInt(), r.nextString(), Option(Location.location2Point(Location.fromWKT(r.nextString()))), Option(new WKTReader().read(r.nextString())))

And my request return the right result, but after I got « Exception in thread "main" java.lang.NullPointerException « because the sub_block_geom is null in my database, so I think that the solution is to change implicit val getSubBlock or to write query with filter, sortedBy , … and I don't know how to do that

A: Well... I am not too sure about your problem, as a lot of required details are missing. But from what I can see, you just need to properly handle possibility of null in your getSubBlock.
implicit val getSubBlock = GetResult(r => {
  val id = r.nextIntOption()
  val blockId = r.nextInt()
  val location: Option[Point] = r.nextStringOption().map(s => Location.location2Point(Location.fromWKT(s)))
  val geometry: Option[Geometry] = r.nextStringOption().map(s => new WKTReader().read(s)))

  SubBlock(id, blockId, location, geometry)
}


text:
Q: MS Office Apps not working after Windows 10 upgrade After upgrading to Windows 10, MS Office Apps (e.g. Excel, Word, etc) crash.
The error message refers to excel.exe, which seems to be missing completely on my local setup.
I tried copying the excel.bak.exe file and renaming it, but get the same error. Suggestions?

A: Please try to repair your installation of Office.

*

*open your control panel by pressing Win+X and then clicking Control pannel

*click on Uninstall a program

*on the following window click again uninstall a program

*search for your Microsoft Office entry

*right-click that entry and select change

*now your choice depends on your office version... Office 365 gives me two options: quick repair and online repair. Choose what ever suits you - if Office isn't working at all I would go for the big repair (which would be the online repair)


text:
Q: Float div left and div centered without overlapping on resize I'm looking to have a div aligned left (Div 1) and a div aligned center (Div 2).
When the user resizes the window, the centered div (Div 2) should stay centered until it bumps into the edge of Div 1.
Div 2 (centered div) should not always be docked left unless the width of Div 1 (left div) plus half the width of Div 2 is greater than half the browser width.
Any thoughts on making this happen without javascript?

Here is a working example to work from: http://jsfiddle.net/pjg8D/9/

#fixedBar {
    height: 50px;
    width: 100%;
    background: #f99;

}

#div1 {
    width: 200px;
    height: 50px;
    background: green;
    float: left;
}

#div2 {
    width: 100px;
    height: 50px;
    margin: 0 auto;
    background: blue;
}

A: The solution to the question is to use min-width on the container div. The ratio for this width is calculated as follows: ( Div1 Width + half of Div2's Width ) x 2.
The solution is here: http://jsfiddle.net/pjg8D/16/

A: You need to give the left hand div a % width, then give the right hand div a left-margin of the same %. Try this:
#div1 {
    width: 25%;
    height: 50px;
    background: green;
    float: left;
}

#div2 {
    width: 250px;
    height: 50px;
    margin: 0 0 0 25%;
    background: blue;
}

Updated fiddle


text:
Q: Remove grid on reset I am trying to make the reset button in HTML clear the grid.
The grid does not show up until the width and height are filled with the dimensions which is great and the reset button resets the width and height.  I want it to also reset the grid to disappear again.
The grid also gets filled with color boxes when clicked on them.

// When size is submitted by the user, call makeGrid()
$('#sizePicker').submit(function(event) {
  event.preventDefault();
  height = $('#inputHeight').val();
  width = $('#inputWidth').val();
  makeGrid(height, width);
  console.log('Height: ' + height + ' and width: ' + width);
})

/* Adding height and width parameters */
function makeGrid(x, y) {
  /* If any table rows there then remove them */
  $('tr').remove();

  /* height = x then add to i */
  for (var i = 1; i <= x; i++) {
    /* This creates a table row */
    $('#pixelCanvas').append('

');
    /* This line finds table one by its id and adds the cell so it can be seen */
    for (var j = 1; j <= y; j++) {
      $('#table' + i).append('	');
    }
  }

  //add color to cell
  $('td').click(function addColor() {
    /* color placement */
    color = $('#colorPicker').val();
    /* Changes the colors of the boxes */
    if ($(this).attr('style')) {
      /* removes them or else places them */
      $(this).removeAttr('style')
    } else {
      $(this).attr('style', 'background-color:' + color);
    }
  })
}
body {
  text-align: center;
}

h1 {
  font-family: Monoton;
  font-size: 70px;
  margin: 0.2em;
}

h2 {
  margin: 1em 0 0.25em;
}

h2:first-of-type {
  margin-top: 0.5em;
}

table,
tr,
td {
  border: 1px solid black;
}

table {
  border-collapse: collapse;
  margin: 0 auto;
}

tr {
  height: 20px;
}

td {
  width: 20px;
}

input[type=number] {
  width: 6em;
}

Pixel Art Maker

Choose Grid Size

  <form id="sizePicker">
    Grid Height:
    <input type="number" id="inputHeight" name="height" min="1" value="1"> Grid Width:
    <input type="number" id="inputWidth" name="width" min="1" value="1">
    <input type="submit">
    <input type="reset">
  </form>

Pick A Color

  <input type="color" id="colorPicker">

Design Canvas

A: When reset is submitted by the user, call makeGrid() with zero values.

// When size is submitted by the user, call makeGrid()
$('#sizePicker').submit(function(event) {
  event.preventDefault();
  height = $('#inputHeight').val();
  width = $('#inputWidth').val();
  makeGrid(height, width);

})

// When reset is submitted by the user, call makeGrid()
$('#reset').click(function() {
  makeGrid(0, 0);
})

/* Adding height and width parameters */
function makeGrid(x, y) {
  /* If any table rows there then remove them */
  $('tr').remove();

  /* height = x then add to i */
  for (var i = 1; i <= x; i++) {
    /* This creates a table row */
    $('#pixelCanvas').append('

');
    /* This line finds table one by its id and adds the cell so it can be seen */
    for (var j = 1; j <= y; j++) {
      $('#table' + i).append('	');
    }
  }

  //add color to cell
  $('td').click(function addColor() {
    /* color placement */
    color = $('#colorPicker').val();
    /* Changes the colors of the boxes */
    if ($(this).attr('style')) {
      /* removes them or else places them */
      $(this).removeAttr('style')
    } else {
      $(this).attr('style', 'background-color:' + color);
    }
  })
}
body {
  text-align: center;
}

h1 {
  font-family: Monoton;
  font-size: 70px;
  margin: 0.2em;
}

h2 {
  margin: 1em 0 0.25em;
}

h2:first-of-type {
  margin-top: 0.5em;
}

table,
tr,
td {
  border: 1px solid black;
}

table {
  border-collapse: collapse;
  margin: 0 auto;
}

tr {
  height: 20px;
}

td {
  width: 20px;
}

input[type=number] {
  width: 6em;
}

Pixel Art Maker

Choose Grid Size

  <form id="sizePicker">
    Grid Height:
    <input type="number" id="inputHeight" name="height" min="1" value="1"> Grid Width:
    <input type="number" id="inputWidth" name="width" min="1" value="1">
    <input type="submit">
    <input id="reset" type="reset">
  </form>

Pick A Color

  <input type="color" id="colorPicker">

Design Canvas


text:
Q: FileVersionInfo and AssemblyInfo Given this snippet from Blah.dll's AssemblyInfo.cs:
[assembly: AssemblyVersion("3.3.3.3")]
[assembly: AssemblyFileVersion("2.2.2.2")]

And then in a separate .exe:
var fileInfo = FileVersionInfo.GetVersionInfo("/path/to/Blah.dll");
fileInfo.ProductVersion == fileInfo.FileVersion == true;

Other SO questions show ProductVersion being "correct", curious if there is something odd about how I'm using it.
Shouldn't ProductVersion be "3.3.3.3" and FileVersion be "2.2.2.2"?  What would cause it to report both properties as AssemblyFileVersion?

A: I found the answer originally here.  I'm repeating the details for ease of reference.
There are three 'versions' that can be included in the AssemblyInfo.cs file:
[assembly: AssemblyVersion("1.1.1.1")]
[assembly: AssemblyInformationalVersion("2.2.2.2")]
[assembly: AssemblyFileVersion("3.3.3.3")]

AssemblyInformationalVersion defaults to AssemblyFileVersion if it is not specified.  Likewise, AssemblyInformationalVersion and AssemblyFileVersion default to AssemblyVersion if both are not specified.
In your example, the AssemblyInfo.cs file did not include AssemblyInformationalVersion, so it defaults to the value of AssemblyFileVersion.  As you will see below, AssemblyInformationalVersion maps to the FileVersionInfo.ProductVersion property, which explains why the test returns true.
Obviously, there are a couple of frustrating aspects to this.  First, there is no way (that I know of) to set the AssemblyInformationalVersion from Visual Studio.  You have to modify the AssemblyInfo.cs file directly to include this attribute.  Second, AssemblyInformationalVersion maps to the FileVersionInfo.ProductVersion property, which is non-intuitive.  The attribute should more properly be named AssemblyProductVersion. And apparently, a title is also a description, etc.
That said, how do we retrieve these (and related) values in code?  Like this:

AssemblyFileVersion          => System.Diagnostics.FileVersionInfo.FileVersion
AssemblyInformationalVersion => System.Diagnostics.FileVersionInfo.ProductVersion
AssemblyVersion              => System.Reflection.Assembly.Version

/// others...
AssemblyTitle                => System.Diagnostics.FileVersionInfo.FileDescription
AssemblyDescription          => System.Diagnostics.FileVersionInfo.Comments
AssemblyProduct              => System.Diagnostics.FileVersionInfo.ProductName
AssemblyCompany              => System.Diagnostics.FileVersionInfo.CompanyName
AssemblyCopyright            => System.Diagnostics.FileVersionInfo.LegalCopyright
AssemblyTrademark            => System.Diagnostics.FileVersionInfo.LegalTrademarks

In the case of AssemblyVersion, use this:
string ver = Assembly.GetExecutingAssembly().GetName().Version.ToString();


text:
Q: External microphone, with windows 10, says "Not Connected" I have a Pioneer DM-DV20, It's my first microphone, I would like to record sounds with this mic connected to my Windows 10 laptop.
My laptop is a HP Pavilion 15 it has only a Realtek driver with one headphone jack like this.
Now, I have jack splitter wich looks like this, except that the rings on the jack are black.
When I connect the jack splitter to my computer, the Sound -> Recording menu shows that the mic is connected (the selected mic) (although I just connect the splitter and nothing else).
When I plug in the Pioneer DM-DV20 microphone to the jack splitters microphone part (rose red), it instantly shows "Not Connected", like here.
Therefore I cannot use the microphone, I have tried it in Audacity but it uses the inner mic of the laptop.
Also I have tried to plug the jack splitter + mic combo to my iPhone 7, but it didn't work at all. The only way I know that the mic is working is that I pluged it in one of my old laptops wich has a separate microphone port, It worked perfectly (both under Windows 10 and Windows 7).
Note that the microphone has an XLR connector with a 3.5 mm jack on it's end, thats what I used for these "tests".
What I've tried:

*

*Realtek driver update.

*Realtek driver removal.

*Getting Realtek HD Audio Manager on my laptop. (I still have none)

*Windows privacy settings. (Everything can use mic, I haven't changed that)

*Puting a headphone into the output part of the jack splitter while the mic part is connected to the mic. (No success, still using the inner mic of the laptop)

How can I make this microphone to work with my computer? Am I missing something?

A: The splitter you have isn't for those type of microphones. They are used with old desktop mics that separated (split) mics and speakers. Have you tried hooking up the mic to.the laptop straight up?


text:
Q: How to use WebView.Reload() within SizeChanged event in .NET MAUI? I need to refresh webView control when the ui size changed. I used SizeChanged event in some controls like Border, WebView, etc SizeChanged event. But I got this system.invalidoperationexception 'a method was called at an unexpected time error. I got this error at the beginning of running the application. The way I used:
<WebView x:Name="webView" SizeChanged="OnSizeChanged" HorizontalOptions="FillAndExpand"  VerticalOptions="FillAndExpand">
     <WebView.Source>
          ...
     </WebView.Source>
</WebView>

private void OnSizeChanged(object sender, EventArgs e)
{
      webView.Reload();
}

Probably I used it in wrong way, or could it be a bug?

A: I solved the problem when I used Reload method in try-catch:
private void OnSizeChanged(object sender, EventArgs e)
{
    try
    {
        webView.Reload();
    }
    catch(Exception ex)
    {

    }
}


text:
Q: mle for the binomial distributed data (number of boys in families) For example I have following dataset of number of boys in families that have 5 kids:

*

*0 boy - 34 (number of such families)

*1 boy - 128 families

*2 boys - 233 families

*3 boys - 267 families

*4 boys - 144 families

*5 boys - 55 families

I want to test if this distribution fits to the binomial.  For this procedure I will use chi-squared test.
But first of all I need to estimate the the parameter $p$ of binomial distribution.  Other parameter $n$ is given (which is 5, of course).  We know, that the mle of binomial distribution is $ \frac{x}{n}$ or $ \sum_{i=0}^n \frac{x_i}{n}$
But I can't understand how can we get the precise mle of binomial distribution (in number), in order to calculate the expected number of boys in $n$ families (by the binomial distribution)
P.S The probability of born the boy is equal to all families

A: You (null) model is $X \sim \mathcal{Binom}(5,p)$ and to estimate $p$ you just sum up the number of boys, the number of children and divide. In R:
xs <- 0:5
Ns <- c(34, 128, 233, 267, 144, 55)
boys <- sum(xs*Ns)
children <- 5*sum(Ns)
phat <- boys/children

Then you want to test if the distribution really is binomial, that is, that the assumption of a constant probability $p$ over families is reasonable. First, let us try simulation, and visualize the results. I simulate 19 times from the estimated binomial distribution, and plot the results together with the data:

Your given data is in red, and it does not look like a typical sample distribution, as judged by the simulations! So there is some reason for doubt ...
I will leave the chisquare test for you, here is another approach ...

A: To do a chi-square test, one can create a reference binomial population and compare with own test population. The code in R can be:
> pop = c(34,128,233,267,144,55)  # own test population
> N = sum(pop)
> ref = rbinom(N, 5, 0.5)         # reference binomial population
> tab = table(ref)                # tabulate
> tab
ref
  0   1   2   3   4   5
 25 131 291 268 121  25
> chisq.test(pop, tab)

Output:
    Pearson's Chi-squared test

data:  pop and tab
X-squared = 24, df = 20, p-value = 0.2424

Warning message:
In chisq.test(pop, tab) : Chi-squared approximation may be incorrect

So, your population is likely to have binomial distribution.


text:
Q: Cannot access 'NgbNavLink' before initialization I am trying to test a component containing a component from ng-bootstrap, in Angular 13  using Jest and get the following error: Cannot access 'NgbNavLink' before initialization.
I have a component MyComponent which is using a NgbModal. I just want to create the test for this component, so I need to import NgbModule in my test. However, the import doesn't seem to work as I get the following error:
 FAIL  src/app/pages/kafkaconnect/kafkaconnect.component.spec.ts
  ● Test suite failed to run

    ReferenceError: Cannot access 'NgbNavLink' before initialization

      2 |
      3 | import { MyComponent } from './mycomponent.component';
    > 4 | import { NgbModule } from "@ng-bootstrap/ng-bootstrap";
        | ^

      at Object.<anonymous> (node_modules/@ng-bootstrap/ng-bootstrap/fesm2015/ng-bootstrap.mjs:6651:991)
      at Object.<anonymous> (src/app/pages/kafkaconnect/kafkaconnect.component.spec.ts:4:1)

Here is my test class:
import { ComponentFixture, TestBed } from '@angular/core/testing';

import { MyComponent } from './mycomponent.component';
import { NgbModule } from "@ng-bootstrap/ng-bootstrap";

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ MyComponent ],
      imports: [ NgbModule ],
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

I am using Angular 13, ng-bootstrap 11.0.0-rc.0 and bootstrap 4.6.1. I know that these versions are very recent but I don't get any error serving or building my application, though.
Angular CLI: 13.0.3
Node: 16.13.0
Package Manager: npm 8.1.0
OS: win32 x64

Angular: 13.0.2
... animations, common, compiler, compiler-cli, core, forms
... localize, platform-browser, platform-browser-dynamic, router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1300.3
@angular-devkit/build-angular   13.0.3
@angular-devkit/core            13.0.3
@angular-devkit/schematics      13.0.3
@angular/cli                    13.0.3
@schematics/angular             13.0.3
rxjs                            6.6.7
typescript                      4.4.4

Finally, I am using jest 27.3.1. As I am using Angular, I have configured jest-preset-angular following this documentation.
Any lead on why I'd get this error?

A: The issue seemed to be with ng-bootstrap 11.0.0-rc.0. Upgrading to ng-bootstrap 12.0.0-beta.4 fixed the issue.


text:
Q: Eclipse calls sqlsever stored procedure prompt cannot find stored procedure I've created a new stored procedure on sqlserver that could run on the profiler, but when I call the stored procedure with eclipse, the prompt cannot find the stored procedure. I would appreciate it if you could give me a little help
public class TestID {
public static void main(String[] args) {
    // TODO Auto-generated method stub
    DBUtil db = new DBUtil();
    Connection conn = null;
    CallableStatement  cstmt =null;
    try{
        conn = db.getConnection();
        cstmt = conn.prepareCall("{call  dbo.GetSeqVal(?)}");
        cstmt.registerOutParameter(1, java.sql.Types.INTEGER);
        cstmt.execute();
        int count=cstmt.getInt(1);
        System.out.println(count);
    }catch (Exception e) {
            e.printStackTrace();
        } finally {
            db.closeAll();
        }
}

The following is the stored procedure I created in sqlserver,and the invoked statememt
USE [test]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[SP_GetSeqVal]
@result int output
as
begin
    declare @NewSeqValue int

    set NOCOUNT ON

    insert into SEQ_SERIAL_NO(seqval) values ('a')

    set @NewSeqValue = scope_identity()

    set @NewSeqValue = Convert(char(4),Getdate(),112) + right('000000'+CAST(scope_identity() AS varchar(5)),5)

    delete from SEQ_SERIAL_NO WITH (READPAST)

    set @result=@NewSeqValue
    return @NewSeqValue
end

Declare @NewSeqVal int,@myResult   int
Exec @NewSeqVal=GetSeqVal @myResult output
Print @myResult
print @NewSeqVal

the result will appear after the call,What if eclipse calls sqlsever stored procedure tips fail to find stored procedure


text:
Q: Doubts on LLDB debugging method In LLDB debugger, self.property works, but why doesn't self.property.property work.
example:
po self.modelData.arrayOfChatMessages
There is no member named arrayOfChatMessages.When a function from another class is stepped in and I try to do this:
po self.anotherClass's property(The class in which the function that the debugger is stepped in is present) it gives the following message:
po self.anotherClassProperty

There is no member named anotherClassProperty. Can anyone please help me out.
Thank you.

A: This is a limitation of the debugger.  To work around it, use regular message syntax:
po [[self modelData] arrayOfChatMessages]
po [self anotherClassProperty]


text:
Q: Node.js Exec not running on Visual Studio Code with MAC Visual Studio Code prompts this message when running the extension Node.js Exec:

Running the contributed command: 'extension.miramac.node.exec' failed.

It was running Ok until I changed my terminal shell to zsh. Changed to bash again but still not working.
Thanks in advance for any kind of help provided.

A: I had the same problem and I noticed that this happened after updating the VSCODE, the solution I found was to install the previous version. It sure will do.
I explain how to install the previous version in this video -> https://youtu.be/jAi3J3gNp6k.
Edit:
Following the recommendations of Logan Devine and Henry Twist, follow all the steps I did [in the video] 3 for the correct operation:
1 - uninstall the current vscode.
2 - I downloaded the previous version of vscode.
3 - Installed
4 - Disable automatic updating.
I emphasize that this is just a paleative for immediate operation.

A: an alternative if you don't want to downgrade your VSCode.
https://www.youtube.com/watch?v=0NvJhxhivyk
Credits to Mayk Brito


text:
Q: How does the &= assignment operator work? Can anyone explain me how &= assignment operator works in Python programming.

A: &= is a bitwise and operator. It works with the binary number. I'll explain this to you by an example
Example:
x = 5
In binary 5 is equal to 101
Now
x &= 3 which means x = x & 3
You also need to convert 3 to binary number which is 011
Now you need to apply and operator to both binary number
  101
  & 011
=001
So now convert this resulting binary number to decimal number which is equal to 1.
You can use online converter from decimal to binary and binary to decimal.

A: &= is a bitwise operator, it works with bits such as following,
a = 60            # 60 = 0011 1100
b = 13            # 13 = 0000 1101
c = 0

c = a & b;        # 12 = 0000 1100
print ("c: ", c)

output:
c: 12

It works on the basis of logic given below
0&0=    0
0&1=    0
1&0=    0
1&1=    1

look at the comments i have given in the code.


text:
Q: How much experience on average should a Sr. developer have to be competent with a framework or library? If you are a Senior developer with say 8+ years experience, how much time spent doing programming is reasonable for competency on average?  Specifically working with some library or framework associated with the core language they have worked with.  For example, 2 years of Spring or Hibernate for a java developer.
I understand that this is based on the complexity of the toolkit, framework or library, plus the competence of the individual developer, however, I'm sure there are reasonable ranges based on time with a language (hence the reference to Senior) that a Senior developer should be able to get competency and be productive.
The reason I ask the question is IT Managers should know this when writing requirements for a position and as a developer, I would like to have a better idea as to what criteria is involved for this type of experience = competency formula that has to exist.  Even if it's a rule of thumb only.
What prompted this question is that I've found recruiters, who generally don't have a technical background, are trying to place technical people and they just look at technology buzzwords on a resume and how much experience for each the dev has.  The hiring manager oftentimes doesn't have a technical background and does the same thing with the resume and uses his architect or other technical expert to screen the candidate to make sure the resume matches the person in the interview.
The problem here is the perception of "competency" in the mind of the hiring IT manager, whether or not the dev can really pick things up and run with it.  They rely on some formula in their mind as to how much experience the dev has with a technology will work for what they want.

A: Ideally you would never place a specific requirement on experience in a particular framework or library. A good developer should be able to pick up any new framework or library fairly rapidly, so my general suggestion is always try to recruit the best developer overall and don't pay too much attention to specific tick-boxes.
For example, lets say you found an absolutely excellent Java developer who'd been writing GUI apps for 6 years that connected to various back-end servlets that she also wrote. She is motivated, keen to learn, can clearly code pretty much anything in core Java as well as architect complex client/server systems. Would you turn her down just because she doesn't have Spring on her CV? It would in my view make much more sense to hire her and let her pick up Spring along the way. She can lean Spring from other colleagues which she teaches the others something about GUI development....
What's more, good developers are in my experience naturally curious and will generally appreciate the opportunity you give them to learn something new. It's depressing to be hired to do the same thing over and over again.
There are of course some situations where specific experience in a library or framework might be considered very important:

*

*In an emergency - if you are recruiting to solve an urgent problem with a tight deadline, then you haven't got time to bring somebody up the learning curve. You need someone who can start cranking solid work out right away. Clearly you want someone with solid experience in the specific library or framework, perhaps 6months+ recent experience.

*For a leadership / mentoring role - if you're hiring someone to lead, teach or mentor others, then they better know their stuff or they won't be respected and fail badly. Perhaps 2+ years direct experience in the area you want them to teach is necessary, in addition to general experience, talent and seniority.

*If the technology is fundamental to a field - for example, if someone claimed to be an "Enterprise Java Developer" with "Extensive SQL Experience" then I'd expect them to know something about JDBC. If they didn't then I'd be suspicious about their entire CV... did they really do significant work in this field? Note that you can only check this at interview, since people often leave basic technologies off their CV on the grounds that they are assumed to be there.

A: The way people know about the book Mythical Man Month - which talks about bogus myth of Man-month in project planning - i guess there is a clear need for another parallel book called "Mythical Man Years" to explain why number of years is a useless metrics to evaluate people.
There are many aspects to explain this:
1. Number of years alone don't count:
In a consulting/project-based IT company - there are often significant periods where staff are on the bench, or where staff are assigned on a project but don't do anything meaningful. Sometimes even if people do some constructive work, there are cases where they have 1 year experience multiplied 8 times rather than doing 8 different things over 8 years.

Choose candidate, based on depth - not length of career

2. What you learn is more important.
Following up, we are talking about how much she/he has learned from others so that now she can apply herself to other problems. There are many people who are so obedient and show successful results by following the boss's nod rather than
applying individual thinking. This means if the candidate does not get the support of good colleagues and bosses, they become a disaster (and many candidates themselves don't understand this)

Choose candidate, based on their original contribution than project
  results and complexity

3. Number of years sometimes is inversely proportional to how much you can learn.
This doesn't have to be true, but it is a possibility. Because someone has spent a lot of time on one subject - they may cease to learn; learning a new framework (details of it) might not be as much if someone has worked in similar level of challenge (and gained wisdom) otherwise. Given this, you can be better off with a relatively newer guy compared to a guy who has some experience.

Choose a candidate who has energy to learn rather than someone tired
  or who thinks she/he knows everything.

4. New area of work requires new thinking
this implies that often in more senior roles, specific details (how to solve problems with a specific tool) are less important but rather insight on how to approach problems in general becomes more important. It takes wisdom rather than years of experience to foresee upcoming problems.

Choose candidate who has developed insight rather than someone who
  knows all terms of the API!

A: Unless I need something done this week, I don't care if candidates have any experience with the technology I am hiring them to use.  If I already have one in-house expert, I care even less.  In two months a good developer with no experience in a platform will be outperforming the average developer with ten years experience in it.  The good developer will read a handful of books in the first month that the average developer has never thought to look at.  The good developer will search in the standard library, and then the internet for common functions, while the average developer is busy re-implementing date formatting.  The good developer will produce understandable DRY code while the average developer cuts and pastes his way through the day.
Certainly, if I can hire an great developer who knows the platform inside and out, I will, but general ability beats experience very quickly.

A: If you apply a rule blindly you will pass over candidates you should hire, and perhaps even hire someone who isn't entirely suitable, because although they have the relevant experience you're looking for, there are other problems.
Remember, that familiarity with the specific framework is not the greatest predictor of success in the actual job.   The best candidates will be smart people who get things done effectively and can apply the skills they already have in new ways to problems that haven't been solved yet.
Try not to rule people out entirely at the advertising stage.   Instead, find efficient ways to filter the stream of applicants to a level that it's feasible to do short phone interviews with.

A: Sometimes a useful proxy for competence in a specific framework is "shipped a product with it." However, shipping a product with "similar" frameworks may be just as good. Also consider how they tested their code in that framework.
Some frameworks are more involved than others and take deeper experience to grok. jQuery for an experienced JavaScript dev who is fluent with Dojo or ExtJS -- no prob. jQuery for a C programmer with no JavaScript -- riskier, since they haven't learned yet how to "think" like a JavaScript dev. Learning all of Spring for a non-Java dev -- risky too -- tools are different, concepts, terminology, even open source may be new.
I do not believe that you only should hire devs already up to speed in tech X, but sometimes the learning curve is too big to absorb right now.. and your question did ask specifically about already being competent.

A: 10,000 hours seems to be the magical number for mastery in anything. Those who get to this point typically spend at least 10 years getting there, although in programming, those 10 years are not typically all spent on a paid job - many programmers start their 'career' at a young age (between ages 12 and 16 seems to be quite common), so it is certainly possible to find a 25-year-old candidate who is already a master in his/her particular field, despite having "only" maybe six years of on-the-job experience.
That said, a lot depends on how much knowledge exactly is required in which area.
Knowing a particular framework inside-out isn't necessarily required for a senior developer role: technologies come and go, and a good programmer can pick up any halfway decent framework in a matter of weeks (days even, if the framework makes sense and is well documented). Skills that are much more important typically include communication, writing clean and robust code, analytic skills, prioritizing, etc.
Of course, if the particular role is that of a 'guru', then in-depth knowledge of that particular technology is the top requirement, but most of the time, you don't need gurus; in fact, they can be a risk. If their specialism goes out of fashion, or gets discontinued, you can only hope that they have acquired a similar level of expertise in a replacement technology by the time you start transitioning.

A: If you're asking about competency then I would say just a couple of months of dedicated effort. mastery, as many point out, is generally accepted to take 10,000 hours to achieve.
The times I've had to learn new technologies -- from complete languages like groovy or python, or frameworks like rails, or GUI toolkits like tk and wxPython -- usually take me just a few weeks to become competent. That means I am able to do my job, but that I still have to look things up. It means if my boss says "can you make product x using framework y in language z" I can confidently say "yes".
To me, that's the difference between senior and junior: senior developers can pick up new toolkits, frameworks and complete languages pretty quickly.

A: It depends, on too many factors for the question to even be relevant as some fresh college graduates could feasibly be competent with a given framework or library just on the basis of where they went to school and how the program was structured. Likewise, once you start working in industry you tend to find that there is a degree of specialization and companies are a various stages with regards to the current cutting edge (i.e. they are still working with Visual Basic 6).
If you are looking for someone to get something done in the short term where the knowledge is a mandatory item then you are better off hiring a contractor to get the work done. If you are looking for someone for the longer term you are better off looking for someone on the basis of what makes for a good developer and with enough industry experience and competency to justify paying them as a senior developer.


text:
Q: Macro to Replace Pronouns with Conditional Merge Field I need a macro that replaces his/her or he/she with a conditional merge field. Thanks to another website, I was able to replace these pronouns with a merge field, but not a conditional merge field without crashing MS Word. Below is the code that I used.
  Sub TestAddIf()

    Dim doc As Word.Document
    Dim mRng As Range
    Set doc = ActiveDocument
    Set mRng = ActiveDocument.Range
    With oRng.Find
      Do While .Execute(FindText:="he")
        doc.MailMerge.Fields.AddIf mRng, _
        MERGEFIELD:="""Client_Sex""", Comparison:=wdMergeIfEqual, CompareTo:="M", _
        truetext:="he", _
        falsetext:="she"
        mRng.Collapse wdCollapseEnd
        Loop
    End With
End Sub

A: Try the following macro, which deals with 'he', 'his', 'him', and 'male' throughout the document (delete the ',male' & ',female' terms if you don't want them).
Sub Demo()
Application.ScreenUpdating = False
Dim Rng As Range, RngFld As Range, StrFnd As String, StrRep As String, StrCode As String, i As Long, j As Long
StrM = "he,his,him,male": StrF = "she,her,her,female"
With ActiveDocument
  For i = 0 To UBound(Split(StrM, ","))
    StrCode = "IFX= ""M"" """ & Split(StrM, ",")(i) & """ """ & Split(StrF, ",")(i) & """"
    j = Len(StrCode) + 4
    Set Rng = .Range(0, 0)
    .Fields.Add Range:=Rng, Type:=wdFieldEmpty, Text:=StrCode, PreserveFormatting:=False
    Rng.End = Rng.End + j
    .Fields.Add Range:=Rng.Characters(5), Type:=wdFieldEmpty, Text:="MERGEFIELD Client_Sex", PreserveFormatting:=False
    Rng.Cut
    With .Range.Find
      .ClearFormatting
      .Replacement.ClearFormatting
      .Forward = True
      .Wrap = wdFindContinue
      .MatchCase = False
      .MatchWholeWord = True
      .MatchWildcards = False
      .Text = Split(StrM, ",")(i)
      .Replacement.Text = "^c"
      .Execute Replace:=wdReplaceAll
    End With
  Next
End With
Application.ScreenUpdating = True
End Sub


text:
Q: Not managed to get value for unchecked checkbox First, don't treat this as duplicate since I do a few try & error, as well research before asking. I intended to post value from jquery including unchecked checkbox. I've tried many ways but still didn't manage to get it works, either due to structure of my code or else. Here is one of the attempt I try currently:

function toggle_tip() {}
$('#l_sync_ul').click(function() {
  if ($('#l_sync_ul').prop("checked") == undefined) {
    $('#l_sync_ul').after('<input type="hidden" name="' + $('#l_sync_ul').attr("l_sync_ul") + '" value=off>')
  } else {
    $('#l_sync_ul').next().remove();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input name="l_sync_ul" id="l_sync_ul" onclick="toggle_tip('ul_dept')" type="checkbox">

Just ignore the 'onclicks' attribute since I'm using it for toggle the table.

A: You just .prop("checked") will return true or false. And as you are using jQuery I would recommend you to directly bind the change event handler using it.

$('#l_sync_ul').change(function() {
  if (!this.checked) {
    $(this).after('<input type="hidden" name="' + $(this).attr("name") + '" value=off>')
  } else {
    $(this).next().remove();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input name="l_sync_ul" id="l_sync_ul" type="checkbox">*Just ignore the 'onclicks' attribute since I'm using it for toggle the table.*

A: $('#l_sync_ul').prop("checked") itself a boolean, no need to check for undefined.
And you can track checkbox with .change event listener.

function toggle_tip() {}
$(document).ready(function() {
  $('#l_sync_ul').click(function() {
    if ($('#l_sync_ul').prop("checked")) {
      console.log("Checked");
      $('#l_sync_ul').after('<input type="hidden" name="' + $('#l_sync_ul').attr("l_sync_ul") + '" value=off>')
    } else {
      console.log("Un Checked");
      $('#l_sync_ul').next().remove();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input name="l_sync_ul" id="l_sync_ul" onclick="toggle_tip('ul_dept')" type="checkbox">

A: Not 100% sure what you want, but this will work better

$('#l_sync_ul').click(function() {
  if (!$(this).is(":checked")) {
    $(this).after('<input type="hidden" name="' + $(this).attr("name") + '" value=off>')
  } else {
    $(this).next().remove();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input name="l_sync_ul" id="l_sync_ul" type="checkbox">

but why not have the hidden field and disable/enable it on click? Or better: If it is not checked it will not send. Deal with that on the server or in the Ajax if you are using Ajax –

A: Based on latest edit, I replace $(this).next().remove(); with $('input[value=off]').remove();, so it will remove any element with value=off. It may works on certain circumstances and vice versa. See here:
Script
$(':checkbox').change(function() {
  if (!this.checked) {
    $(this).after('<input type="hidden" name="' + $(this).attr("name") + '" value=off>')
  } else {
    $('input[value=off]').remove();
  }
});

HTML
<input type="hidden" name="l_sync_ul" value=off>
<input type="checkbox" name="l_sync_ul" id="l_sync_ul" onclick="toggle_tip('ul_dept')">


text:
Q: Can I concatenate environment variables in apache config? I have two environment variables in apache config, I want to concatenate them into one new environment variable. Is this possible?
I realise this doesn't work, but it demonstrates the sort of thing I'm after:
SetEnv one foo
SetEnv two bar
SetEnv three one+two

...and then 'three' would have the value "foobar"

A: Use a mod_rewrite regular expression with two wildcard backreferences to access the environment variables and concatenate the strings:
#This will be true for any user agent
RewriteCond  %{HTTP_USER_AGENT}  ^.*

#Replace / with / and set the new environment variable
RewriteRule  /(%{ENV:one})*(%{ENV:two})* / [E=three:$1$2]


text:
Q: Crystal report add dollar symbol In the crystal report, there are many transactions. I have taken the transactions from the database excel. Only one transactions I need to display in dollar symbol in front of the amount. If I given the dollar symbol entire transactions shows a dollar symbol. I need to show only one transaction in dollar symbol. Please help me on this.

A: Does the single record has an attribute where you can recognize this one should has a dollar sign or not?
If there is an attribute you can use a formula and do something like this:

If {showDollar} Then "$" + ToText({amount}, 0, ',', '.') Else ToText({amount}, 0, ',', '.')


text:
Q: How to declare my iOS voip app as an option on contact info (like whatsApp)? I want to add my app in the contact info in the address book for messaging, video calls.

A: This functionality can be achieve using CallKit, in short CallKit provides native phone app UI to all the VoIP application, to let your app visible in the contact (after integrating the CallKit), you just need to smoothly long press the audio/video call buttons.

By default It shows the most frequent used app (say WhatsApp), once you'll long press the icons it'll show a list of the supporting apps (VoIP enable apps). From where you can choose the app to perform the action.
The screenshots will make you more sense to figure it out.

Image 1  - is the default situation I.e. default call and video option.

Image 2 - Long press the call option, It'll show all the apps which are capable to make audio call.

Image 3 - Same for the video option.

Image 4 - Once you'll use any app (suppose WhatsApp) the default icon will change to WhatsApp and in the list it'll start showing WhatsApp and other concern apps.
Source: #1 Ray Wenderlich Toutorial , #2 Sample Code of CallKit Objective-C & Swift both

Note: - In the list below it'll start showing the apps name once you use any app to make call. And it'll remain listed even if you uninstall that particular app.

A: I assume you are using CallKit. So adding  .phoneNumber to supportedHandleTypes gives this ability that you can call number via your application.
.generic also gives ability you can start call from history that made or received via your application.
  let config = CXProviderConfiguration(localizedName: "anyname you want")
  config.supportedHandleTypes = [.phoneNumber,.generic]


text:
Q: copy/paste event listener in C# I'm new to C# (I'm used to Java) and am trying to implement a listener that can run in the background of a Windows XP computer and be able to see when a user does a copy, cut, or paste operation.
I found this page
and have attempted to implement that listener, but I keep having problems.
My question is two fold: one, will the listener on this page solve my problem?  and if so, any tips on implementing it? I'm getting:

The type or namespace name 'DragDropOrCopyPasteEventArgs' could not be found (are you missing a using directive or an assembly reference?)

I've tried attaching the necessary assembly reference, but I don't seem to have the correct dll.
Thanks a ton in advance. (before anyone asks, I am not writing a virus, its a writing analyzer)

A: For copy listener please look into this question here and an article here.
As for the paste event as discussed in the above thread there seems to be some confusion as clipboard listener does not provides any feedback on pasting. You may have to install global hooks to capture CTRL + V and mouse context menu.
for using key hook please read this CodeProject article.
for listening to mouse events and movement please visit this another CodeProject article and this msdn page about WIN 32 hooks.


text:
Q: Angular How to Delete a component instances using its object reference CLI 6.2.1 Angular 6.1.7 - I dynamically create components as the user requests them.  The HTML displays each instance as built and they are correct and unique.
At some point, I need to delete one (or more) of them.  By that I mean, I not only don't need the DOM representation, I don't need that specific instance or object reference at all.
New Information:  Here is how the component is created:
    createComponent(componentType): any {

    const factory: ComponentFactory<any> = this.resolver.resolveComponentFactory(componentType);
    this.componentRef = this.container.createComponent(factory);
    return this.componentRef;  // return the REFERENCE containing the instance.
  }

I have tried:
Items.objRef.delete;
Items.objRef.delete();
Items.objRef.instance.delete;
Items.objRef.instance.delete();

After this, I would expect to:
Items.objRef = null;  // just to clean up

and create a new one later if needed.
Do I need to force Angular to "detectChanges()"?
Any other ideas?
Thanks in advance,
Chuck aka Yogi.


text:
Q: add to value of input instead of overwrite val This is my code
$('#enterTags').keydown(function(event) {
                var tag = $(this).val();
                // 188 is comma, 13 is enter
                if (event.which === 188 || event.which === 13) {
                    if (tag) {
                        $('#tags').append('<div>' + tag + '</div>');
                        **$('#falseInput').val(tag + ', ');**
                        $(this).val('');
                    }
                    event.preventDefault();
                }
                // 8 is backspace
                else if (event.which == 8) {
                    if (!tag) {
                        $('#tags div:last').remove();
                        event.preventDefault();
                    }
                }
            });

The section of code I bolded is what I am having problems with.  I need the value of #enterTags to be added to that of #falseInput, not overwrite it.  How can I do this?

A: Try:
$('#falseInput').val($('#falseInput').val() + tag + ', ');

or:
$('#falseInput').val(function(index, value) {
  return value + tag + ', ';
});

A: Try something like this:
$('#falseInput').val($('#falseInput').val() + ', ' + tag);


text:
Q: How to call function from watch? data: function ()  {
    return {
       questions: []
    }
},

watch: {
    questions : function(val, oldVal) {
        foo()
    }
},

methods: {
    foo() {
        console.log("foo called");
    }
}

Produce error: ReferenceError: foo is not defined
Also I am looking at examples: http://vuejs-ru.github.io/vuejs.org/api/options.html#watch
What this string do?
handler: function (val, oldVal) { /* ... */ },
handler it's keyword? Or it can be function?

A: Just to add to the answer from @nils
handler: 'foo'

also works if the function foo is within methods.
Bit shorter than
handler() {
    this.foo()
}

A: If you want to use watch to observe your property, you could call your method it with this.foo:
data: function ()  {
    return {
       questions: []
    }
},

watch: {
   questions: {
       handler: function(val, oldVal) {
           this.foo(); // call it in the context of your component object
       },
       deep: true
    }
},

methods: {
    foo() {
        console.log("foo called");
    }
}

To answer your question about handler: It is a keyword property that can take either a function expression (as in the example) or a reference to a function, such as:
function myHandler() { ... } // Defined somewhere outside of the vue component object

...

handler: myHandler,

...

Just out of curiosity: Do you need to watch a property in order to do something every time it changes or could computed properties solve your problem as well?


text:
Q: How to detect if the receiver exit suddenly a video call I'm using Agora RTC and Signaling SDK for building a video call function.
But I get a problem that if the receiver side exits app suddenly (like swiping app out from recent tray).
Then, the caller side is still on calling screen and can not get any event from receiver side to end the video call.
Please help

A: to solve this problem, you need to add leave channel logic at onDestroy method in receiver's activity. So that when the receiver exits the app, he will leave the channel and that will notify the caller.


text:
Q: Is the any way to use numbers on list to perform operations? For a newcomer to python from c++
In python for example, is there a way to get this to substitute in the element in list position f[n-1], perform mathematical operations, and add it to the next element on the list?
f = [1, 1-x]
for n in range (1,5):
    f[n+1] = simplify((x*f[n-1])/n)
    print(f[n])

A: Is this the effect you want?  It extends the list, f, one element on each iteration.  I removed the simplify call, because I expect that it doesn't really affect your Python mechanics question.
x = 0.4

f = [1, 1-x]
for n in range(1,5):
    f.append((x*f[n-1]) / n)

print(f)

The output from this is
[1, 0.6, 0.4, 0.12, 0.053333333333333344, 0.012]

Now that you've clarified a little, here's a starting point for your string processing.
def simplify(expr):
    return expr

f = ["1", "1-x"]
for n in range(1, 5):
    f.append(simplify("x*(" + f[n-1] + ")/n"))
    print(f[n])

The output from this is
1-x
x*(1)/n
x*(1-x)/n
x*(x*(1)/n)/n

This leaves you with a reduced programming problem to attack: how to reduce things such as "x*(x*" to "x**2".  You're tackling a bit of a parsing problem here: you'll likely have to specify a grammar and make a reasonable attack on your coding to get to the next point where we can help.


text:
Q: Как устроен синтаксис обработчика $(window).on('scroll')? 1) Есть такая функция c параметром:
function check_Smth () {
  ..
};

Хочу чтобы она вызывалась при скроллинге страницы. Пишу:
$window.on('scroll', check_Smth});

Всё работает.
2) Хочу добавить параметр для универсальности:
function check_Smth (param) {
  ..
};

Вызываю обработчик:
$window.on('scroll', check_Smth(param1)});

Не работает ((
Пришлось переделать в такой формат:
$window.on('scroll', function () {
        check_Smth(param1);
 });

Нет понимания почему не работает второй вариант. Кто-нибудь может объяснить доступным языком, подробно, почему он не работает ?

A: На самом деле, в документации все довольно неплохо описано. Однако, постараюсь объяснить простым языком.
Когда вы создаете такой код:
$window.on('scroll', function () {
    check_Smth(param1);
});

Вы делаете function declaration. Иными словами, вы определяете функцию, которая будет вызываться каждый раз, когда срабатывает событие, при этом не вызывая саму функцию.
То же самое происходит, когда Вы делаете так:
function check_Smth () {
  ..
};

$window.on('scroll', check_Smth});

Сначала вы декларируете функцию, затем Вы ее "аттачите", но не вызываете ее.
Когда же Вы делаете так:
$window.on('scroll', check_Smth(param1)});

Вы выполняете вызов функции при попытке аттача хэндлера для события scroll.
В данном случае Ваша функция выполнится и вернет undefined.
Далее, этот undefined и заатачится как хендлер к событию onScroll:

*

*-> попытка attach'a handler'a для onScroll события

*-> вызов переданной function

*-> function возвращает 'undefined'

*-> ничего не работает

Решить данную проблему можно было бы еще и так:
function check_Smth(param1) {
  return function() {
      //...
  }
};

$window.on('scroll', check_Smth(param1)});

В этом случае, у Вас вызовется функция, которая возвращает функцию, которая и станет обработчиком, а не undefined.
По большому счету, это вопрос разницы function call vs function reference
Кроме того, конструкция:
$window.on('scroll', check_Smth(param1)});

С точки зрения использования jQuery не является верной, так как param1 в данном случае будет содержать event, а не нужный Вам параметр.
P.S. подобные вопросы, кстати, часто ставят в тупик людей на собеседованиях =) Вроде и понятно, почему не работает, а объяснить не могут =)


text:
Q: Vertx: pass initial data to verticle on it deployment How can I pass copy of int[][] array to verticle on it deployment?
I have a ServerVerticle from which deploy 5-10 ServiceVerticles.
Each of ServiceVerticle must use the same shared data structure - Map<Integer, Short[]> which can be 100-2000 Mb.
Problem - I can't create Local map with array as a value.
The only in-memory solution I see - pass copy of int[][] to each ServiceVerticle on it deployment and keep 5-10 copies of data.
P.S. This data structure must have as fast as possible lookup, so I dislike cluster-wide solutions like Hazelcast IMap.

A: While there isn't much freedom in the types you can use in a LocalMap you can use Buffers. A buffer is an optimized byte array and you can quickly adapt it to your use case. Using a Buffer also means you will have a compact in memory representation so you can save memory and any operations will be fast.
You only need to write a transformation from a 2D plane to a 1D line. For example say that you have the following array (2 x 3):
int[][] data = new int[] {
  new int[] {1, 2, 3},
  new int[] {4, 5, 6},
};

If you transform it to a buffer:
Buffer.buffer()
  .appendInt(1).appendInt(2).appendInt(3)
  .appendInt(4).appendInt(5).appendInt(6);

(You can later just use the byte representation, this is just to illustrate how it works).
Now you can refer to any x, y by doing:
int getInt(int x, int y) {
  // transform from 2D to 1D
  int pos = y * LENGTH + x;
  // Where LENGTH is the the example: 3

  // For safety assert on length
  if (pos > buffer.length()) throw new ArrayIndexOutOfBoundsException();
  // TODO: assert on min, max (x, y)

  return buffer.getInt(pos);
}


text:
Q: Best OOP approach for this simple PHP app? Ok, I couldn't insert the overview image, but I'm required to create a PHP app for my studies, it must allow student to register, and the administrator to edit course and student info.
We are not required to code it in an OOP style, but since its the best programming practice to code in OOP, why not learn OOP from the beginning.
I'm a beginner but I know the basics about OOP, classes, inheritance, setters and getters and all that cool lingo, but I'm struggling to decide which parts of this app should be objects, should I make course and student classes or add, edit and delete classes? Any advice on how to approach and visualize such a problem would be appreciated.

A: Very roughly:  This is how I would do it:

*

*Store your data in SQL or XML. You will need two SQL tables, one for Students and one for Courses.  You can use one XML file containing all the data, or you can use two files (which I recommend).

*Create a class called, for example, dataItem with a property like '$arr_fields' corresponding to a single data record (a single row in a SQL table, or an XML record).

*The dataItem class should have the following methods (all public):

*

*loadFromSQL() (or loadFromXML())

*saveToSQL() (or saveToXML())

*add(), edit() and delete()

*a view() method using HTML

*These methods are obviously used to read and write data between the SQL/XML data and $arr_fields of the class, and to display the data in $arr_fields.  The keys of $arr_fields are the SQL column names (or XML tag or attribute names) for the specific SQL table.

*Try not to call loadFromSQL() or saveToSQL() in your constructor or in any of the other methods which are used to modify only the class data.  Keep these actions separate. EDIT: This is a personal preference which helps me to keep track of the state of my objects.

*Create Student and Course classes that extends the dataItem class.

*You can override methods, for instance the view() method, inside your extended classes if you need to.

*Then you can call the methods in Students and Courses from an Admin object (like rcdmk suggested) or maybe from StudentFolder and CourseFolder classes whose view() method contains buttons for the actions that need to be performed.  (Let StudentFolder and CourseFolder extend a Folder class that you create).
UPDATE:
For example:  If your primary key in a SQL table is id, then dataItem's loadFromSQL($id, $tablename) should set $arr_fields so that its keys are the column names and it's values are the values from the row whose primary value is equal to $id.
In Students, you can then override loadFromSQL() as follows:
class Students extends dataItem {

  // other attributes

   public function loadFromSQL($id) {
     parent::loadFromSQL($id, "Students");
   }

}

EDIT: On reconsideration, it might be better to set $arr_fields["id"] = $id and also set $tablename with the constructor for dataItem - then you never have to override loadFromSQL() or specify parameters for it.  loadFromSQL() should then load the record if it exists.  saveToSQL() should save $arr_fields in SQL if $arr_fields["id"] is set and create a new record if it is not set.  Anyway, you must find a consistent way of interacting with the data which works for you, these are just possibilities.
However, if you are not experienced with OOP and SQL or XML, you might be opening a can of worms for yourself and it might be better to just do your assignment using functions only and php arrays for your data.  Unless you have some time to learn...

A: From a simple perspective:
Abstract the main objects as classes and use methods for actions of this objects:
Student (object) are deleted (action) by the Admin (object), so
Admin class will have a deleteStudent method, because Admin deletes Students.
Another aprouch is to concentrate all Student related actions in the Student class:
Student class will have a public delete method that Admin can use.
Anyone that think this in better ways of explanation can edit this wiki.

A: Think about which aspects of your system are actually objects, you know, something you can do something with.  The methods are what you do to the objects.  So, you're on the right track with course and student classes, and add, edit, and delete would be methods of those classes.
But don't get too bogged down with it.  If it's not your core assignment objective, you could quickly get in over your head by trying to do everything exactly the right way.  If you can formulate a clear way to get to where you need to go, then go for it, if it seems confusing, back off it a little and learn some more.

A: You say that you know the basis of OOP, however you ask whether you should create Course, Student classes OR Add, Delete, Edit classes. Well maybe there are other practices, but I guess the most popular one and the only I am aware of is to use nouns as classes and verbs as their methods. Hence, intuitively there is something wrong with class "Add" or "Edit". What I would have done if I were were, is to think of all "entities" that might be considered an object - like Student, Course, Lecturer, Class (Room) and depending on how advanced your model should be you can add more like Building etc. Then try to implement basic things like creating new student, registering for a course, associating teacher with a course etc. Once you have it in place and IT IS WORKING you might want to add advanced things, like inheritance. For example you might want to say, that both Teacher and Student are a Person so you might want to create such abstract class and use inheritance.


text:
Q: Observing social web behavior: to log or populate databases? When considering social web app architecture, is it a better approach to document user social patterns in a database or in logs? I thought for sure that behavior, actions, events would be strictly database stored but I noticed that some of the larger social sites out there also track a lot by logging what happens.
Is it good practice to store prominent data about users in a database and since thousands of user actions can be spawned easily, should they be simply logged?

A: Remember that Facebook, for example, doesn't update users information per se, they just insert your new information and use the most recent one, keeping the old one. If you plan to take this approach is HIGHLY recommended, if not mandatory, to use a NoSQL DB like Cassandra, you'll need speed over integrity.
Information = money. Update = lose information = lose money.

A: Obviously, it depends on what you want to do with it (and what you mean be "logging").
I'd recommend a flexible database storage. That way you can query it reasonably easily, and also make it flexible to changes later on.
Also, from a privacy point of view, it's appropriate to be able to easily associate items with certain entities so they can be removed, if so requested.

A: You're making an artificial distinction between "logging" and "database".
Whenever practical, I log to a database, even though this data will effectively be static and never updated. This is because the data analysis is much easier if you can cross-reference the log table with other, non-static data.
Of course, if you have a high volume of things to track, logging to a SQL data table may not be practical, but in that case you should probably be considering some other kind of database for the application.


text:
Q: Connecting Two Windows Server via SSH - Ant Hope things going good.
I want to connect two windows server using ssh.But, My problem is, when I use the ANT task 'sshexec' to execute a .bat file from a remote WINDOWS server 2009 like this:
<sshexec host="10.46.220.108"
username="support"
password="India123"
 trust="true"
verbose="true"
command="D:\project\jboss-eap-6.1\bin\standalone.bat -b hostname41" />

My execution gets hanged and stops with the below lines.
 [sshexec] Connecting to hostname:22
[sshexec] cmd :D:\project\jboss-eap-6.1\bin\standalone.bat -b hostname41
[sshexec] Microsoft Windows [Version 6.1.7601]
[sshexec] Copyright (c) 2009 Microsoft Corporation. All rights reserved.
[sshexec] C:\users\administrator>

Guide me to resolve this.
NOTE: The remote server is running copssh in port number 22


text:
Q: How do I forcibly delete ALL xrandr/xinerama state and restore defaults? Background / Justification
In Ubuntu 18.04, I'm having a totally off-the-wall issue that's not addressed by any other questions about xinerama or xrandr. Suddenly, my 4K monitor is frequently being treated as a 1440p monitor, with no option to set the resolution back to 4K. This problem tends to be triggered by monitor restarts or resolution changes (e.g. due to games). Once the problem starts, running either
xrandr -s 3840x2160

or doing the equivalent using gnome-settings causes the screen to black out for several seconds before silently returning to the incorrect 2560x1440 resolution. In particular, neither xrandr nor dmesg seem to show any error messages relevant to the problem. Furthermore, once triggered, the problem persists through a restart: the resolution is still low, and xrandr 3840x2160 still silently fails. It seems the only way to solve the problem is to wait for a substantial amount of time for the problem to spontaneously resolve itself.
It's possible that the problem is a hardware issue, but I find this unlikely because:

*

*4K works fine when the resolution problem isn't triggered: still 60Hz, smooth, no distortion.

*The problem does not occur in other operating systems, or on the gdm login screen (text appears at native resolution as far as I can tell). The resolution only resets to 1440p once the X session is actually started.

*The problem can also be solved by plugging in a second 4K monitor, and using both -- but the problem reappears once the second 4K monitor is removed!
I suspect that something weird happened to xinerama's internal state -- I don't see why else I'm suddenly being plagued by these random resolution changes, barring hardware failures, which I find unlikely. So I want to delete / hard reset whatever files constitute xinerama's internal state.
Actual Question
I want to know the location of xinerama's config files (or more generally, its internal state) and forcibly reset them. You can try to xy-problem me but please look at the failed solutions first.
Failed Solutions
xrandr -s 0 -- this command is often the answer to "how do I reset?" questions. This had the same effect as xrandr -s 3840x2160, i.e. nothing. I want to reset ALL state to try to fix the problem.
Restarting, as mentioned.
Manually adding 3840x2160 as a new mode. The problem is not that the monitor fails to report that as an option, but that xrandr mysteriously does nothing when that resolution is selected.
Hardware/software details
Kernel: 4.15.0-70-generic
Distro: Ubuntu 18.04
CPU: AMD Ryzen 2700X
GPU: AMD Vega 64
DE: GNOME 3
Monitor: Dell U2718Q

A: Removing ~/.config/monitors.xml seems to have solved the problem for now. Said file was recreated later. I don't think that the file itself was the true problem -- rather it seemed to have triggered some underlying bug in xrandr (and it must be a bug -- no matter what, it makes no sense for xrandr to list 3840x2160 as an option and not support actually selecting that option). However, since the problem was solved for now, I don't feel like looking deeper into the true cause of the problem.


text:
Q: Python Coding - Using Spyder or Jupyter First of all, I am no programming expert. Zero experience, however, I am interested in learning it.
Summarize the problem.
My Master's topic requires me to use machine learning to predict if current hard engineering structures (concrete seawalls, gabions, etc...) are capable of withstanding future sea-level rise by the year 2071.
I managed to download the following:
-tide gauge data (1973-2021)
-gridded satellite altimetry data (1993-2022)
If I am to do future predictions, it will be as such:
-tide guage data from the years 1973-2021-2071
-gridded satellite altimetry from the years 1993-2021-2071
Essentially, my prediction involves 50 years into the future
Describe what you've tried.
Tried countless things - I don't even know where to start from haha. I tried searching youtube videos, stack overflow examples, and general sites on google, but nothing that can help me with my specific problem. I guess my problem is that I DO NOT know how to link one sentence code to another such that it becomes error-free. I managed to get hold of this website from a friend of mine.
In other words, I need help or guidance from someone who is well versed with python and machine learning - it would mean the whole world to me.


text:
Q: Is it possible to do indent only with css, image inside
Is it possible to do this only with CSS?
I thought about it a long time but nothing comes to my mind

A: Yes, but only if your background has a solid color:
div {
    width: 310px;
    height: 41px;
    background: gray;
    border-radius: 5px;
    position: relative;
}
div:after {
    content: '';
    display: block;
    width: 60px;
    height: 60px;
    background: white;
    border-radius: 50%;
    position: absolute;
    right: -30px;
    bottom: -30px;
}

Also check the DEMO.
EDIT: added the inner shadow: http://jsfiddle.net/LinkinTED/ThZrf/1/

A: Yes. You can create a relatively positioned div and give it a border-radius of a high number (you'll have to experiment to find at what point it becomes a circle) specify a width and height for it, set it's z-index to being higher than the thing it is sitting on top of and position it in the bottom corner. Something like
#circle{
    border-radius: 300px;
    z-index: 2;
    height: 40px;
    width:40px;
    left: 350px;
    top: 20px;
    background-colour:white;
}

These are only sample values. You'll need your own to do this correctly. If you wanted to get even more fancy I think you can specify which corners to apply the radius to. So you could (I think) create that exact shape in CSS rather than a circle which my method would do (but you position the circle to cut out just the corner).
EDIT: As pointed out, if you want a shadow, you can play about with the css box-shadow attribute(note this is not supported below IE9).

A: Without knowing your particular use case, you might consider this technique by Lea Verou:
http://lea.verou.me/2011/03/beveled-corners-negative-border-radius-with-css3-gradients/


text:
Q: best way to delete related entity in repository say you have a repository BusinessRepository and you want to have some method that deletes a given BusinessContact, in this scenario Business is the parent and BusinessContact is the child, one to many, each business can have many contacts, would we have two deletes method in same repository? or put it in the Update method. I am using C# and EF 4. Thankx

A: Sounds like Business is an aggregate root.
So, i would suggest Adding and deleting contacts through methods on your Business entity which you get using your repository.
Info on Repository Pattern and aggregate roots:
What's an Aggregate Root?


text:
Q: NSSet with CLRegion Objects I have two sets one obtained using
NSMutableSet *monitoredRegionSet = [[locationManager monitoredRegions]mutableCopy];

and the other is obtained using the
NSMutableSet *regionSet = [NSMutableSet setWithCapacity:regionChunks.count];
CLRegion *region = [[CLRegion alloc] initCircularRegionWithCenter:coordinate radius:radius
identifier:regionString];
[regionSet addObject:region];

When I try to set operations between them it does not works.Should I implement a category of CLRegion and implement the isEqual: and hash: methods.Is there a better approach of doing this.
[monitoredRegionSet intersectSet:regionSet];
[monitoredRegionSet minusSet:regionSet];

A: CLRegion *region =
    [[CLRegion alloc] initCircularRegionWithCenter:coordinate
        radius:radius
    identifier:regionString];

That is a totally new, different region object. In the absence of any built-in concept of region equality, you are guaranteed that there is no intersection between a set containing this region object and a previously existing set of region objects.
As you rightly imply, you could play with CLRegion isEqual: and hash. But is that something you really want to do? A better question might be: what are you actually trying to accomplish here? For example, it might be more appropriate and simpler just to draw the regions for the second set directly from the first set.
EDIT: Your simplest approach might be something like this:
https://stackoverflow.com/a/7197192/341994
Just stop monitoring all the regions and start over with a new set of regions (some of which, of course, might happen to be the same as a region you were already monitoring).


text:
Q: How to make literalinclude include precise C functions I would like to include part of a C header or a C file into my sphinx doc.
using literalinclude gets the whole file but I would like to get only some part but based on functions, struct names etc...
I don't want to use lines or start-with options as I would like to make it fail when the C idiom is not found.
I don't see any option or extension to do that.


text:
Q: How to use curl to retrieve data from a php file? i have a test.php file that will hold a facebook app (iframe based php).
I also have a dev environement where all my files go before they are commited to live.
What i want to do is create a curl page on the live server that will be seen by facebook and that curl page will pull the data from my test.php page that sits on the dev
i have been trying but i get Authorization Required:
/* gets the data from a URL */
function get_data($url)
{
  $ch = curl_init();
  $timeout = 5;
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
  $data = curl_exec($ch);
  curl_close($ch);
  return $data;
}

$returned_content = get_data('http://dev.xxx.com/test.php');

echo $returned_content ;

any ideas on how to accomplish that?
Thanks

A: Do you really need curl?
Live:
<?php readfile('http://your.dev.server.example.com/test.php');?>

A: Try using the file_get_contents function

A: Okay, that is specific error. If you need facebook authorization, you must look at Facebook API for authorization methods. If you are getting HTTP authorization error, you may use apropriate CURL options: http://www.php.net/manual/en/function.curl-setopt.php


text:
Q: Nodejs: Performance issues parsing CSV and Zip The files are submitted to my server and I'm trying to determine if the CSV is valid and if all the images referenced from the CSV are present in the zip. I have to populate a Mongo database with all that information but I want to do it in the background, and send a response to the client as fast as possible.
So I have two readable streams and I have three different approaches:

*

*Unzipping the file takes 24sec, so unzip + parsing the csv + fs.exists is not an option.

*Parsing the whole csv, save filenames in array and then reading the zip using node-unzip and pipe takes 5 seconds.

*Reading the csv and in parallel read the zip and use a shared array to determine simultaneusly if the files are present, which is the fastest option, takes 4 seconds.
Does anyone have an idea of how to do it faster?
EDIT: The code used for validation is:
// lib/validator.js

function validateParallel(csv, zip) {
  const shared = {};
  return new Promise((resolve, reject) => {
    const l = CSV_VALIDATORS.length - 1;
    csv
      .pipe(split())
      .pipe(through2(validateLine.bind({ zip, reject, n: 0, l, shared })))
      .on('finish', () => {
        zip
         .pipe(unzip.Parse())
         .on('entry', (entry) => {
           delete shared[entry.path];
         })
         .on('close', () => {
           resolve(Object.keys(shared).length === 0);
         });
      });
  });
}

// perfomance/validate.spec.js

const zip = fs.createReadStream('./performance/imports/import.zip');
const csv = fs.createReadStream('./performance/imports/stress-test.csv');

const hrstart = process.hrtime();
validator
  .validateParallel(csv, zip)
  .then(function(isValid) {
    console.log(`valid=${isValid}`);
    const hrend = process.hrtime(hrstart);
    console.info("Execution time (hr): %ds %dms", hrend[0], hrend[1]/1000000);
});

ValidateLine takes the image name and pushes it into the shared object. The output is:
valid=true
Execution time (hr): 4s 926.031869ms

I have simplified the code and removed error management to make it more readable.

A: Do you have to also validate the images themselves, or just make sure their paths exist in the CSV file? If the latter, you can run a shell process that executes unzip -l on the zip file, which will print only the file names, should be quick.


text:
Q: Detach element style from html I have bulk of html file like this

How to detach element style and make it become css (each div always have id to identify)
#wrap{
min-height: 32px;
padding: 5px;
width: 800px;
margin: 50px auto;
overflow: auto;
font-size: 12px;
}
#l1{...}
#l2{...}
...

I need to do it in client side, it mean I will work with javascript, jquery etc...

A: Why? There's no reason to do it at that point. If you need to apply the style to other elements that don't have it, do something like this:
var style = element.style;
var i;
for (i in style) {
    other_element[i] = style[i];
}

edit:
In light of your comment, you might be able to do something like this:
var elements = [...]; //collect together all the elements you need styles for
var i;
var j;
for (i = 0; i < elements.length; i++) {
    print('#' + elements[i].id + '{');
    for (j in elements[i].style) {
        print(j + ':'+elements[i].style[j] + ';');
    }
    print('}');
}

There's obviously no print statement in javascript, so substitute it with what you want. This still assumes that all elements have id's. I'm not sure that this is actually worthwhile - if you're going to have one style per element anyways, then that's a very big stylesheet.

A: If you have a bulk of files you want to do this to, what you're probably going to want to do is write a script in a HLL with a decent HTML parser ( I recommend Python with lxml or BeautifulSoup ), and then run it over your code.
In psuedo python:
css = {}
with(open(argv[1]) as htmlfile):
  for element in HTMLParser.parse(htmlfile):
    if element.hasAttributes(['style', 'id']):
        css[element.attribute('id')] = element.attribute('style')
out = ''
for id, style in css.iteritems():
    out += '#%s {' % id
    out += ";\n".join(style.split(';')
    out += "\n}\n"
open(argv[1] + "-new.css", 'w').write(out)

Then, assuming you have access to unix tools, something like find /path/to/html/root -name "*html" -exec /path/to/your/script {} \; will run it over all your files. You could probably do this whole task as a oneliner with sed if you really wanted to.
Oh, you need to do it client side? Well, you could do pretty much the same thing as the pseudocode above in jQuery, other than writing a file (you'd be writing a style element into the dom, and you'll need to use jQuery's methods for selecting elements and testing for attributes), although I'm confused as to why you'd want to do this client side.


text:
Q: Obtaining data from jqgrid on mouseover I'm trying to do a mouseover for the jquery and when the mouse is hovered over a certain row I can get the id from that row and populate information and display an image.  However, I have been having the hardest time trying to do so.
Here is what I want to happen
Just like in the onSelectRow where I obtain the data using the following code
var ret = $('#list').jqGrid('getRowData', Id);

I want to use when I do a mouseover.  However, I don't see a way of doing this.  I tried the following under gridComplete
gridComplete: function() {'.jqgrow').mouseover(function(e) {
 var rowId = $('.jqgrow').parent(tr:first).attr('id');
 alert("You rolled over " + rowId.Id);
});
}

but it only gave me the ide number of the row of that table inside the jqgrid and I need the data from that row instead.
For instance, in my data I have Id, FirstName, LastName, FullName, Title, SortID
I would like to present a picture on the right side of my HTML page when hovered over certain rows by passing the Id to the HTML page, and querying through an array.  If I can some how get the actual Id that's within my dataset I can do the rest.
Any help would be lovely.
I have given the entire code of my jqGrid at the bottom for reference.
jQuery("#list").jqGrid({
url: '/Providers/DynamicGridData/',
datatype: 'json',
mtype: 'GET',
colNames: ['Id', 'LastName', 'FirstName', 'FullName', 'Title', 'Url', 'SortId'],
colModel: [
{ name: 'Id', index: 'Id', width: 30, align: 'left', hidden: true },
{ name: 'LastName', index: 'LastName', width: 30, align: 'left', hidden: true },
{ name: 'FirstName', index: 'FirstName', width: 30, align: 'left', hidden: true },
{ name: 'FullName', index: 'FullName', width: 100, align: 'left' },
/*{ name: 'FirstName', index: 'FirstName', width: 100, align: 'left' },*/
{name: 'Title', index: 'Title', width: 200, align: 'left' },
{ name: 'Url', index: 'Url', width: 30, align: 'left', hidden: true },
{ name: 'SortId', index: 'SortId', width: 30, align: 'left', hidden: true}],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'Id',
scrollOffset: 0,
width: '425',
altRows: 'true',
altClass: 'ui-priority-secondary',
autowidth: 'true',
height: '300',
altRows: 'true',
altClass: 'ui-priority-secondary',
viewrecords: true,
caption: 'Clinical Providers',
onSelectRow: function() {
var Id = $("#list").jqGrid('getGridParam', 'selrow');
if (Id) {
var ret = $('#list').jqGrid('getRowData', Id);
var url = ret.Url;
url.split(' ').join('');
//alert("id=" + ret.Id + "FullName=" + ret.FullName + "...");
window.location = "/" + url;
}
else { alert("Please select a row"); }
},
gridComplete: function() {
$('.jqgrow').mouseover(function(e) {
var rowId = $('.jqgrow').
alert("You rolled over " + rowId.Id);
});
}
});

A: I'm trying this code and it works fine:
gridComplete: function() {
    $('.jqgrow').mouseover(function(e) {
        var rowId = $(this).attr('id');
        alert('You rolled over ' + rowId);
    });
}

A: I am confused - when you say:
var rowId = $('.jqgrow').parent(tr:first).attr('id');

That should be returning the ID of the row. You can then pass rowID to the getRowData method to retrieve additional data for the row.

A: try this code..this code work...
this code retrieve jqgrid row object ..
$('.jqgrow').mouseover(function(e) {
 var rowId = $(this).attr('id');
 var dataFromTheRow = jQuery("#list").jqGrid('getRowData',rowId);// this is your jqgrid row object;
 alert('your jqgrid row object id = ' + dataFromTheRow.id);
               });


text:
Q: Permissions used by other app in android I want to add a feature in my Android app that can check permissions used by other installed apps. For Example: - My app check other already installed apps permissions that  which they are used?
 StringBuffer appNameAndPermissions=new StringBuffer();
PackageManager pm = getPackageManager();
List <ApplicationInfo>packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
{
for (ApplicationInfo applicationInfo : packages) {
Log.d("test", "App: " + applicationInfo.name + " Package: " + applicationInfo.packageName);
try {
PackageInfo packageInfo = pm.getPackageInfo(applicationInfo.packageName, PackageManager.GET_PERMISSIONS);
              appNameAndPermissions.append(packageInfo.packageName+"*:\n");
    //  Get Permissions
String[] requestedPermissions = packageInfo.requestedPermissions;
 if(requestedPermissions != null) {
 for (int i = 0; i < requestedPermissions.length; i++) {
 Log.d("test", requestedPermissions[i]);
appNameAndPermissions.append(requestedPermissions[i]+"\n");
}
 appNameAndPermissions.append("\n");
}
} catch (NameNotFoundException e) {
 e.printStackTrace();
}}}

}
This is working code, it gives complete list of all permissions used by all apps.
But my question is how to know particularly which app using which permission ?
Please help me & give me some idea about this.

A: This is Working code:
PackageManager mPm = getPackageManager();
List <PackageInfo> appList=mPm.getInstalledPackages(PackageManager.GET_PERMISSIONS|PackageManager.GET_RECEIVERS|
          PackageManager.GET_SERVICES|PackageManager.GET_PROVIDERS);

for (PackageInfo pi : appList) {
    System.out.println("Process Name: "+pi);
    // Do not add System Packages
    if ((pi.requestedPermissions == null || pi.packageName.equals("android")) ||
            (pi.applicationInfo != null && (pi.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0))
        continue;

    for (String permission : pi.requestedPermissions) {
        //Map<String, String> curChildMap = new HashMap<String, String>();
        //System.out.println("############     "+permission);

        try {
            PermissionInfo pinfo = mPm.getPermissionInfo(permission, PackageManager.GET_META_DATA);
            CharSequence label = pinfo.loadLabel(mPm);
            CharSequence desc = pinfo.loadDescription(mPm);
            System.out.println("$$$$$ "+label+"!!!!!! "+desc);

        } catch (NameNotFoundException e) {
            Log.i(TAG, "Ignoring unknown permission " + permission);
            continue;
       }
    }


text:
Q: PHP arabic text compare using strpos I have a arabic keyword in a mysql table like
    *#1591; *#1610; *#1585;*#1575;*#1606

// Please consider & in the place of * , value with '&' automatically converts in to arabic.
Mysql table encoding:   utf8_general_ci
I am getting some string from the external resources example twitter.
I would like to match the keyword with the tweet i am getting .
 $tweet = 'وينج وأداسي الاماراتية توقعان اتفاقية تعاون لتوفير أنظمة الطائرات بدون طيا';

  $keyword = '*#1591; *#1610; *#1585;*#1575;*#1606'; //From db

  $status = strpos ($tweet, $keyword)

$status always returns false.
I have checked with utf8_encode(), utf_8_decode() , mb_strpos() without any luck.
I know need to convert both strings to one common format before compare but which format i need to convert ?
Please help me on this.

A: As arabic symbols are encoded using multibyte characters, you must use functions that support such a constraint: grapheme_strpos and mb_strpos (in that order).
Using them instead of plain old strpos will do the trick.
Also, keep in mind that you may have to check for its availability prior to its use, as not all hosted environments have them enabled:
if (function_exists('grapheme_strpos')) {
    $pos = grapheme_strpos($tweet, $keyword);
} elseif (function_exists('mb_strpos')) {
    $pos = mb_strpos($tweet, $keyword);
} else {
    $pos = strpos($tweet, $keyword);
}

And last but not least, check the docs for the different arguments that functions take, as the encoding used by the strings.


text:
Q: get text by class in jquery I want get test inside this example. Why it doesn't work?
HTML

 test

            <input class="addCart" type="button" value="click me" />

JAVASCRIPT
$(document).ready(function () {
    $('input.addCart').live('click', function () {
        var $partType = $(this).closest('div.partType');
        alert($partType.filter('span.name').text());
    });
});

A: Change:
alert($partType.filter('span.name').text());

to:
alert($partType.find('span.name').text());

Ideally you also want to stop using .live() and move to .on() (since live was deprecated awhile ago and removed in 1.9) so the whole block would be:
$('input.addCart').on('click', function () {
    var $partType = $(this).closest('div.partType');
    alert($partType.find('span.name').text());
});

jsFiddle example

A: Try this:
    $(document).ready(function () {
    $('input.addCart').click(function () {
        var $partType = $(this).closest('div.partType');
        alert($partType.find('span.name').text());
    });
});

A: .filter() will apply the filter to the passed set of elements, where as you want to look at the descendent elements for which you need to use find()
$(document).ready(function () {
    $('input.addCart').live('click', function () {
        var $partType = $(this).closest('div.partType');
        alert($partType.find('span.name').text());
    });
});

.filter(): Reduce the set of matched elements to those that match the selector or pass the function's test.
.find(): Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.