text:
Q: AtTask API Login Error I'm trying to access the AtTask API using AtTask StreamClient.php library.  I am able to login and extract information using the Chrome Advanced Rest Client, however, I am not able to login to the API from a .php script using StreamClient.  The message I keep getting is:
"Logging in...Error: Unknown SSL protocol error in connection to XXXXXXXXXX.attask-ondemand.com:443"
Does anyone have an idea what this means, and how to get around it.  My gut feeling is that it has something to do with the configuration of my server.
Thanks in advance.

A: Problem solved.  Very strange, very strange. Apparently, you have to force CURL to use SSL Version 1.  I added the line:
curl_setopt($this->handle, CURLOPT_SSLVERSION, 1);

to the CURL initiation part of the script and it started working.


text:
Q: Counting number of occurrences in a range within an unordered_map I have my unordered_map set up as:
unordered_map<int, deque<my_struct>> table;

When I read values to my program, I usually do:
 table[int].push_back(obj);

What I want to be able to do is if I'm given 2 integer variables, I want to be able to find the number of keys that occur between the two.
So if in my table I have code like
  table[49].push_back(obj);
  table[59].push_back(obj);
  table[60].push_back(obj);

If I execute my search function(which I'm currently trying to write) to look between the key values of 45 and 65, I should have 3 results.
I'm not exactly sure how to go about it in an efficient manner. Any ideas would be helpful. Than you.

A: If you are using a std::unordered_map I don't think you have a choice but to loop over all integers 45 to 65 and use find to check if the key exists in the unordered_map:
using my_table = std::unordered_map<int, std::deque<my_struct>>;

int count(const my_table& table, int begin, int end) {
  int sum = 0;
  for (int i = begin; i != end; ++i) {
    auto find_result = table.find(i);
    if (find_result != table.end())
        sum++;
  }
  return sum;
}

But this may not be very efficient. If you use a std::map instead the elements are ordered so this can be achieved more efficiently:
using my_table = std::map<int, std::deque<my_struct>>;

int count(const my_table& table, int begin, int end) {
  auto begin_itr = table.lower_bound(begin);
  if (begin_itr == table.end())
      return 0;
  auto end_itr = table.lower_bound(end);
  return std::distance(begin_itr, end_itr);
}

I've used the std::map::lower_bound function.
Depending on how sparse your map is you might even consider using something like std::vector<std::deque<my_struct>> as a flat map.
Live demo.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How Could I Write a helper function which is query from mongodb , and then can call this func for any ejs template I want to write a function with one param id for this mongo to pass to my home.ejs.
Example with this query:
db.getCollection('users').find('5da85558886aee13e4e7f044', {image: 1})
Example I have a route.
routes/users.js
var User = require("../models/user");
var db = require("../secure/db");
var middleware = require("../middlewares/middleware");
 //...
router.get("/home", middleware.isAllowed, function(req, res, next) {
 res.render('home',{
  title: "Project",
  userList: userList,
  getUserimage: getUserimage(??)//trying here
 })

});

so in home.ejs or any file.ejs
I can call like getUserimage('5da85558886aee13e4e7f044') inside loop of list of ids
views/home.ejs
 <% layout('layout/layout') %>
 //more code
 <% for(var i=0; i < userList.length; i++){ %>

    <img src ="<%=getUserimage(userList[i].id)%>" > <%=userList[i].name%>

 <% } %>
 //more code

Here is my updated helper
var User = require("../models/user");
var ObjectId = require('mongodb').ObjectID;

module.exports.getUserImage = async function getUserImage(id) {
  let result = await  User.find(ObjectId(id), {image: 1, _id: 0}).lean();
   console.log(result[0].image);
    return result[0].image; //or whatever you wanna return
  };

When I console.log it is gave me the correct result. but when I call in view.ejs like this <%=getUserImage("5d999578aeb073247de4bd6e")%>   file it give me [object Promise]

A: Create a file , we name it helper.js.
module.exports.getUserimage = async function(id){

    //do something
    //replace this with your own code but use the await
    let result = await collection.findOne(query);
    return result; //or whatever you wanna return

}

Then inside app.js you can do this
const helper = require("helper");

app.locals.getUserimage = helper.getUserimage

Then you can call it inside your .ejs template like the way you are doing.
 <% layout('layout/layout') %>
 //more code
 <% for(var i=0; i < userList.length; i++){ %>

    <img src ="<%= getUserimage(userList[i].id)%>" > <%=userList[i].name%>

 <% } %>
 //more code

app.locals properties persist throughout the life of the application. Provide the complete path to the helper.js file. I have assumed that is in the same directory as the app.js file.


text:
Q: TypeError: run() missing 1 required positional argument: 'fetches' on Session.run() I'm new at tensorflow and I'm trying to follow this getting started tutorial. But executing this very simple code within "ex001.py" script:
import tensorflow as tf

sess = tf.Session
hello = tf.constant('Hello, TensorFlow!')
print(hello)
print(sess.run(hello))

I get the following output

Tensor("Const:0", shape=(), dtype=string)
      Traceback (most recent call last):
        File "C:\Users\Giuseppe\Desktop\ex001.py", line 6, in
          print(sess.run(hello))
      TypeError: run() missing 1 required positional argument: 'fetches'

I've checked the tf.Session.run() syntax but looks right and I didn't find anyone with the same issue.
I'm running with this configuration:

*

*Windows 7 Professional sp1 64 bit

*Python 3.5.3 64 bit

*Tensorflow 1.0.1 cpu version

Thanks in advance

A: Not sess = tf.Session, it should be tf.Session(), you are missing ()

A: sess = tf.Session line has incorrect syntax of Session.
It should be
sess = tf.Session()
() is missing.


text:
Q: How can I efficiently use R to add summary rows with 0 cases? I have a data set that includes cases by year and month.  Some months are missing, and I'd like to create rows with a case count of zero for those months.
Here is an example, and my current brute force approach.  Thanks for any pointers.  Obviously, I'm new at this.
# fake data
library(plyr)
rm(FakeData)
FakeData <- data.frame(DischargeYear=c(rep(2010, 7), rep(2011,7)),
                       DischargeMonth=c(1:7, 3:9),
                       Cases=trunc(rnorm(14, mean=100, sd=20)))

# FakeData is missing data for some year/months
FakeData

# Brute force attempt to add rows with 0 and then total
for(i in 1:12){
  for(j in 1:length(unique(FakeData$DischargeYear))){
    FakeData <- rbind(FakeData, data.frame(
                DischargeYear=unique(FakeData$DischargeYear)[j],
                DischargeMonth=i,
                Cases=0))
      }
     }

FakeData <- ddply(FakeData, c("DischargeYear","DischargeMonth"), summarise, Cases=sum(Cases))

# FakeData now has every year/month represented
FakeData

A: Using your FakeData data frame, try this:
# Create all combinations of months and years
allMonths <- expand.grid(DischargeMonth=1:12, DischargeYear=2010:2011)
# Keep all month-year combinations (all.x=TRUE) and add in 'Cases' from FakeData
allData <- merge(allMonths, FakeData, all.x=TRUE)
# 'allData' contains 'NA' for missing values. Set them to 0.
allData[is.na(allData)] <- 0
# Print results
allData

A: Another solution would be to use cast from the reshape package.
require(reshape)
cast(Fakedata, DischargeYear + DischargeMonth ~ ., add.missing = TRUE, fill = 0)

Note that it only adds 0 for the missing combinations in the data, months 8, 9 for year 2010 and months 1 and 2 for year 2011. To ensure that you have all months 1:12, you can change the definition of DischargeMonth to be a factor with levels 1:12 using
FakeData = transform(FakeData,
   DischargeMonth = factor(DischargeMonth, levels = 1:12))

A: Here is a zoo solution.  Note that zoo FAQ #13 discusses forming the grid, g.  Also we convert the year and month to a "yearmon" class variable which is represented as a year plus fractional month (0 = Jan, 1/12 = Feb, 2/12 = Mar, etc.)
library(zoo)

# create zoo object with yearmon index
DF <- FakeData
z <- zoo(DF[,3], yearmon(DF[,1] + (DF[,2]-1)/12))

# create grid g. Merge zero width zoo object based on it.  Fill NAs with 0s.
g <- seq(start(z), end(z), 1/12)
z0 <- na.fill(merge(z, zoo(, g)), fill = 0)

which gives
> z0
Jan 2010 Feb 2010 Mar 2010 Apr 2010 May 2010 Jun 2010
     149      113      110       99      110       96
Jul 2010 Aug 2010 Sep 2010 Oct 2010 Nov 2010 Dec 2010
     108        0        0        0        0        0
Jan 2011 Feb 2011 Mar 2011 Apr 2011 May 2011 Jun 2011
       0        0       91       72      119      130
Jul 2011 Aug 2011 Sep 2011
      93       74      112

or converting to "ts" class:
> as.ts(z0)
     Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
2010 149 113 110  99 110  96 108   0   0   0   0   0
2011   0   0  91  72 119 130  93  74 112

Note that if z is a zoo object then coredata(z) is its data and time(z) are its index values.


text:
Q: What is wrong with my solution?(hackerrank exercise - bitwise operation) the link for the excersize
In short, 'n' is series of number from 1 to n, and 'k' is a number.
I need to return the largest result of a&b (a<b) as long as it's smaller than k, for example 1&2, 1&3 …2&3,2&4…
I get 0 whenever I run this function:
function getMaxLessThanK(n, k) {
  let maxPV = 0;
  for (let a = 1; a < n; a++) {
    for (let b = a + 1; b <= n; b++) {
      if (a & b < k && a & b > maxPV) {
        maxPV = (a & b)
      }
    }
  }
  return maxPV
}

A: It's an operator precedence problem.
Comparison operators (<, >, ...) have higher precedence than bitwise AND (&), so you need to use parentheses to group:
if ((a & b) < k && (a & b) > maxPV) {
    // ...
}

Complete snippet:

function getMaxLessThanK(n, k) {
  let maxPV = 0;
  for (let a = 1; a < n; a++) {
    for (let b = a + 1; b <= n; b++) {
      if ((a & b) < k && (a & b) > maxPV) {
        maxPV = (a & b);
      }
    }
  }
  return maxPV;
}

console.log(getMaxLessThanK(8, 5));


text:
Q: problemas con el uso del json y ajax tengo el siguiente codigo ajax donde envio valores por medio de json a un php ya que estoy obteniendo valores desde un select, el problema es que creo que el php que debe recibir los datos no recibe ya que mando imprimir y me sale en la pantalla como valores null. la verdad soy muy nuevo en esto del json y ajax.
jQuery("#form_filtroscajas").submit(function( e ) {
var _servicio = $("#servicio").val();
var _producto = $("#producto").val();
var _estado = $("#estado").val();
var  datos = {servicio: _servicio, producto: _producto, estado: _estado}
jQuery.ajax({
        url: "ubicacion de mi php",
        data: datos,
        type: 'POST',
        success:function(data){
            if(data == "success"){
                 alert("correcto");
            }else{
                // alert(data);
                alert("error");
            }
            return false;
        },
        error: function( XMLHttpRequest, textStatus, errorThrown ) {
            console.log(textStatus);
            console.log(errorThrown);
            return;
        }
      });
      e.preventDefault();
        });

en donde yo debo recibir los datos los tengo asi
$servicio=$_POST['servicio'];
$producto=$_POST['producto'];
$estado=$_POST['estado'];
$data = array('servicio' => $servicio,
              'producto' => $producto,
              'estado' => $estado );
//en el mismo php tengo este pedazo de codigo cosa que segun he leido debe de debolver los datos al ajax
// aqui es donde mando a imprimir igual el array que tengo para ver los valores pero este manda null
  echo json_encode($data);

A: En principio veo dos problemas en tu código:

*

*Si esperas un JSON, conviene indicarlo en la parte del Ajax, poniendo esto: dataType: 'json'

*En la comprobación del success estás verificando esto: if(data == "success"){, lo cual, según la respuesta que estás enviando, nunca se cumplirá. Generalmente se pone una clave dentro de la respuesta para verificarla. O sea, para hacer ese estilo de verificación tendrías que poner en $data un par del tipo 'success'=>'Todo OK' (por ejemplo) y comprobar así: if(data.success){
Sea como sea, en fase de desarrollodo conviene siempre depurar la respuesta con un console.log(data); sin if ni nada.
También, es conveniente en PHP poner un header con el tipo de respuesta y la codificación. Eso ayuda, sobre todo cuando hay caracteres con acentos, que suelen dañar el JSON si no controlas la codificación.
Vamos a aplicar lo dicho en el código:
JS
Muestro sólo la parte de Ajax a modificar
jQuery.ajax({
        url: "ubicacion de mi php",
        data: datos,
        method: 'POST',
        dataType: 'json'
        success:function(data){
            console.log(data); /*Usa esto siempre en fase de desarrollo*/
            if(data.success){
                 alert("correcto");
            }else{
                // alert(data);
                alert("error");
            }
            return false;
        },

Todo lo demás igual ...
PHP
/*
   Puedes usar un ternario para guardar los datos
   aquí se verifica con empty si los datos existen
   de ese modo evitas los undefined index y puedes usar luego
   las variables si hace falta verificar la existencia de datos requeridos
   sin los cuales el código no debe seguir adelante
*/
$servicio=!empty($_POST['servicio']) ? $_POST['servicio'] : NULL;
$producto=!empty($_POST['producto']) ? $_POST['producto'] : NULL;
$estado=  !empty($_POST['estado'])   ? $_POST['estado']   : NULL;
/* Nótese la creación de una clave success en el array */
$data = array(
                'success' =>'Todo Okey Manuel',
                'servicio' => $servicio,
                'producto' => $producto,
                'estado' => $estado
              );

header('Content-type: application/json; charset=utf-8');
echo json_encode($data);


text:
Q: What algorithm will sort nodes to create the least number of crossing connection lines? I have a graph which has parent nodes up top, and layers of child nodes. Each child node can connect to one to many parent nodes.
I'm building a visual representation, and I want to sort all the nodes so that there is the least number of connecting lines that are crossing.
Child nodes should be grouped together as closely as possible. The parents can be re-arranged.
Unoptimized:

Optimized:

Another Unoptimized:

Optimized:


text:
Q: How to download a photo from url and save in Xamarin I need Xamarin to call a GET API that downloads a photo from a url and save it in the phone.
When xamarin calls the API, it will download a image from a url and then return it as response to xamarin, after this I will save the photo in the phone.
The API is a C# 4.0 MVC. I created a Get API that downloads the image successfully and returns it as FileStreamResult.
The API downloads the image from a url and return it
public FileStreamResult DownloadFoto()
        {

            Stream rtn = null;
            string aURL = "https://image.shutterstock.com/image-vector/sample-stamp-grunge-texture-vector-260nw-1389188336.jpg";
            HttpWebRequest aRequest = (HttpWebRequest)WebRequest.Create(aURL);
            HttpWebResponse aResponse = (HttpWebResponse)aRequest.GetResponse();
            rtn = aResponse.GetResponseStream();
            return File(rtn, "image/jpeg", foto);
        }

Xamarin Forms
HttpConnectionis an instance of HttpClient.
var Response = await Application.HttpConnection.GetAsync("DownloadFoto");
                        DependencyService.Get<IFileService>().SavePicture("ImageName.jpg", Response.Content.ReadAsStreamAsync().Result, "imagesFolder");

Xamarin Android
[assembly: Dependency(typeof(FileService))]
namespace Diario.Droid
{
    public class FileService : IFileService
    {
        public void SavePicture(string name, Stream data, string location = "temp")
        {
            var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            string filePath = Path.Combine(documentsPath, name);
            byte[] bArray = new byte[data.Length];
            using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
            {
                using (data)
                {
                    data.Read(bArray, 0, (int)data.Length);
                }
                int length = bArray.Length;
                fs.Write(bArray, 0, length);
            }
        }
    }
}

I don't get any error, it looks to be saving the image, but when I look for it in File Management I don't find the image there.

A: Yeah the directory path your are getting with:
var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);

It is pointing at somewhere in /data/user/ which will be private to the App. If you want to make it browse-able using a File Explorer App, you will probably need to save it somewhere in External Storage (public storage).
You can get a path for that with:
var externalDir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments);

If you are targeting Android API 18 and lower, remember to add permissions for that in your AndroidManifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="18" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18" />

Since some devices on Android can have their External Storage on microSD cards, you will need to check whether you can write to it first:
var stateOk = Android.OS.Environment.ExternalStorageState == Android.OS.Environment.MediaMounted;
if (stateOk)
{
    // I can write!
}

From Android API 23 and up, you will need to request permission before being able to read and write to external storage. You could use this plugin to easily ask for permissions: https://github.com/jamesmontemagno/PermissionsPlugin
Another couple of things to notice. You are using .Result on your ReadAsStreamAsync() call. Just keep in mind that you will be blocking the thread you are on. I highly suggest you design your methods to be async all the way.


text:
Q: Commutation preserving operators Let $A$ and $B$ be unital $C$*-algebras and let $T\colon A\to B$ be a bounded linear bijection that preserves commuting elements, i.e., $ab=ba$ implies $TaTb=TbTa$. Does $T^{**}$ then also preserve commuting elements?
An approach to answer this question would be to weak*-approximate commuting elements in $A^{**}$ by commuting elements of $A$, but by Commuting nets for commuting projections this already seems to fail for projections.


text:
Q: Why would AutoLayout not respect constraints if an initial frame is specified for the target view? We have a weird case where our view is not appearing as expected and we've traced it to AutoLayout and some sequence of events that we can't see why it would change things.
To simplify the example, here's some test code you can run directly in an Xcode playground. (We're using Xcode 11.3.1 if it matters.)
First, we define an InlineConfigure operator, like so...
// 'InlineConfigure' operator
infix operator ~> : AssignmentPrecedence

@discardableResult
public func ~> <T>(item:T, _ configure:(T)->Void) -> T {
    configure(item)
    return item
}

Next, to illustrate it's not a case of something being deallocated when not expected, we create a UIView subclass specifically to log that...
class SomeView : UIView {

    override init(frame: CGRect) {
        super.init(frame:frame)
        print("SomeView created")
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    deinit {
        print("SomeView deinitialized")
    }
}

With both of the above in place, take a look at this code.  It works as expected.
class TestViewController : UIViewController {

    let margin:CGFloat = 24

    override func loadView() {

        view = UIView()
        view.backgroundColor = .yellow

        SomeView()~>{

            $0.backgroundColor = .blue
            $0.translatesAutoresizingMaskIntoConstraints = false
            view.addSubview($0)

            NSLayoutConstraint.activate([
                $0.leftAnchor.constraint(equalTo: view.leftAnchor, constant: margin),
                $0.topAnchor.constraint(equalTo: view.topAnchor, constant: margin),
                $0.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -margin),
                $0.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -margin)
            ])
        }
    }
}

PlaygroundPage.current.liveView = TestViewController()

If we however change the line that creates SomeView to take in a frame that has a non-zero area (e.g. both a width and a height) then that same code no longer works and you don't see the blue view at all.
override func loadView() {

    view = UIView()
    view.backgroundColor = .yellow

    SomeView(frame:CGRect(x: 0, y: 0, width: 20, height: 20))~>{

        $0.backgroundColor = .blue
        $0.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview($0)

        NSLayoutConstraint.activate([
            $0.leftAnchor.constraint(equalTo: view.leftAnchor, constant: margin),
            $0.topAnchor.constraint(equalTo: view.topAnchor, constant: margin),
            $0.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -margin),
            $0.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -margin)
        ])
    }
}

Setting the frame to have a zero area and it works again...
SomeView(frame:CGRect(x: 0, y: 0, width: 0, height: 20))~>{

    [...]

}

But back to the non-zero frame, if you move the constraint-setting code to outside of the configuration closure, then it always works regardless of the frame having an area or not!
override func loadView() {

    view = UIView()
    view.backgroundColor = .yellow

    let someView = SomeView(frame:CGRect(x: 0, y: 0, width: 20, height: 20))~>{

        $0.backgroundColor = .blue
        $0.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview($0)
    }

    NSLayoutConstraint.activate([
        someView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: margin),
        someView.topAnchor.constraint(equalTo: view.topAnchor, constant: margin),
        someView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -margin),
        someView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -margin)
    ])
}

What's confusing us is in the earlier code, $0 inside the closure is a strong reference to the newly-created view (and the parent also holds a reference to it when it was added as a subview so it's not unloading), and that exact same reference is assigned to someView on the outside where it then executes the exact same code that used to be in the closure.  There is nothing in between the closure and the code on the outside except that assignment, yet it's giving different results!  But why?
Can anyone explain why we're seeing this behavior?  What are we missing?

A: I'd say it's because playgrounds are the work of the devil. I ran your code in a real iOS app project and it worked as expected even with
SomeView(frame:CGRect(x: 0, y: 0, width: 20, height: 20))

Basically I wouldn't expect a playground to go through all the lifetime stages of a view controller correctly.


text:
Q: Can not import from 'sockjs-client' (typescript) I am very new to angular and typescript.
First I install via npm:
npm install --save sockjs-client

I am trying to import like this in chat.component.ts:
import * as SockJS from 'sockjs-client';

But I am getting this error:

TS7016: Could not find a declaration file for module 'sockjs-client'.
'/home/simon/javaprojs/tour-creator/client/node_modules/sockjs-client/lib/entry.js'
implicitly has an 'any' type.   Try npm i --save-dev @types/sockjs-client if it exists or add a new declaration (.d.ts)
file containing declare module 'sockjs-client';

So after that I tried the following as suggested by the error:
npm i --save-dev @types/sockjs-client

But that only resulted in a new warning:

Warning:
/home/simon/javaprojs/tour-creator/client/src/app/components/chat/chat.component.ts
depends on 'sockjs-client'. CommonJS or AMD dependencies can cause
optimization bailouts. For more info see:
https://angular.io/guide/build#configuring-commonjs-dependencies

Here is the full code of my component
import {Component, OnInit} from '@angular/core';

import * as Stomp from 'stompjs';
import * as SockJS from 'sockjs-client';

@Component({
  selector: 'app-chat',
  templateUrl: './chat.component.html',
  styleUrls: ['./chat.component.css'],
})
export class ChatComponent implements OnInit {

  constructor() { }

  connect(): void {
    const socket = new SockJS('gs-guide-websocket');
  }

  ngOnInit(): void {
    this.connect();
  }
}

What to do? When I start the application, all I get is a white page, and a console error saying that global is not defined.

A: Please execute below commands and try again.
npm install --save sockjs-client
npm install --save @types/sockjs-client

npm audit fix

Please add this declaration
declare module 'sockjs-client';

You can also visit this link:
How to add SockJS into Angular 2 project?

A: I don't know if this is 'best practice' but it works for me.
In the index.html file I simply load SockJS via  tag.
And then in top of my chat.component.ts I add the following:
declare var SockJS: any;

A: actually, in order to benefit of typings you need to import the default value:
import SockJS from 'sockjs-client';


text:
Q: Eagle routing (manual routing) I am new to eagle and I need to practice routing. I've read many general tips (about using jumpers for example) to use while routing, however I want a precise step by step procedure I can follow to manually do the routing for any circuit. Should i for example start by one part of the schematic and look at his corresponding part in the board? Any ideas?

A: This is usually the procedure I use:

*

*Create your desired board outline. If not defined by an enclosure, you may need to tweak it later on, but start with what you think you'll need. This would also be the time to determine how many layers you need and configure accordingly.

*In the PCB layout editor, begin by placing your connectors and other human-interface items (buttons, switches, LEDs, etc). Usually you want to place these in a specific location on the board, to make it neat and clean (in a logical manner for human interface).

*Mentally group together different parts of the schematic - Power, Microcontroller, Communication, Logic, etc. Pick which one you want to start with.

*In the PCB layout editor, drag the components which are a part of the section you chose to start with and group them together (outside the board but separate from the other parts). You may have to break the larger section up into smaller groups, depending on the size. For example, the Power section of the schematic may have several voltage regulators, so do one regulator with its requisite circuitry as one group.

*Within the single small group you just moved, start positioning the components in a logical manner that promotes the easiest routing (shortest, straightest airwires).

*Within that single group, you may start routing the connections. Don't worry about the connections that go to different sections yet, just route what will be self-contained within that group.

*Move the group onto the board and find a logical place for it.

*Repeat steps 4-7 with the next group of components in the section, and then with the remaining sections.

*Once all groups have been moved to the board and positioned where you want them (make sure to group parts within the Power section together, and parts within the microcontroller section together, and so on), you can start routing between the sections and do the human interface parts.

*During the routing process you may find it much easier to place copper pours instead of individual traces, usually for power and ground connections. I normally do this right after I place all component sections on the board. This will minimize the airwires for ground or power that are visible and make it easier to identify which connections go group-to-group.

Sometimes you may need to do some of these steps out of order, but you'll get a better feel for it the more you practice. However, the process mentioned above should help you get started with routing just about any board.

A: Add a Polygon to both layers and Name then GND. Place them  outside of the board Dimension lines.  Do to not run Gnd traces all over the board.  Add a few Vias and Name them GND also, that connect the top & bottom if you don't have thru hole parts connecting them.
Go into View:Grid and change the Grid 1 mil, that will let you place traces and parts pretty finely.
10 mil wide signal traces. 12 mil vias for signals.
20, 24mil wide for power, 24 or 32mil vias.


text:
Q: Want to know how FCM works in below scenarios I want to know how FCM Notifications works in below scenarios:

*

*Same user logging into multiple devices. Will all the devices gets the notification?

*What if user uninstalls the app? Does FCM sends the notification even if user uninstalls the device, and later checks for sending failed event?

*If login changes on the device - Suppose if I login to a device as user A, and then logged out of the device and logged in as user B. I  must not get the notifications for user A. How this situation is handled in FCM?

A:
Same user logging into multiple devices - Will all the devices gets the notification?

Firebase Cloud Messaging sends messages to devices, it doesn't know anything about users. If you're sending messages to FCM Instance IDs, the message will only be delivered to the device with that ID. If you're sending messages to topics, the message will only be delivered to devices that subscribed to that topic.

Does FCM sends the notification even if user uninstalls the [app from the device]?

When the app is uninstalled, the Instance ID for that app installation is deleted to. So no message will be delivered to the app on that device anymore.
If the user later reinstalls the app on the device, it generates a new Instance ID. So it won't receive any messages from when the app was uninstalled.

If login changes on the device - Suppose if I login to a device as user A, and then logged out of the device and logged in as user B. I must not get the notifications for user A. How this situation is handled in fCm?

Since Firebase Cloud Messaging doesn't know anything about the users of your app, it is up to your application code to make this connection. Many apps clear the Instance ID from the device when a user explicitly signs out.
Also see:

*

*How to refresh FCM Token on user Logout?

*Firebase Cloud Messaging - Handling logout

*How to unsubscribe from FCM notifications after logout from app?

*How to release Firebase Cloud Messaging token when Android user logs out?


text:
Q: Logstash custom input plugin to call java class I have written a custom filter plugin for logstash to call a java class.
Requirement:
Input plugin: read from queue
Custom plugin: For each message in queue call the java class
**Code:**

# encoding: utf-8
require "logstash/filters/base"
require "logstash/namespace"
require "java"
require "test.jar"

class LogStash::Filters::Example < LogStash::Filters::Base

  config_name "example"

  public
  def register
  end # def register

  public
  def filter(event)
      object = Java::Com.test.Test.new
      a = object.readMessage(event.get("message"))
      event.set("message",a)

    filter_matched(event)
  end # def filter

end # class LogStash::Filters::Example

Problem:
Is there a way that I can instantiate the java class just once? For every message that i read from the queue i do not want to create a new instance of the java class, but rather instantiate it during logstash startup and use the same object for all incoming messages.

A: Yes. It is pretty easy to do that. You can create an instance variable in your ruby class to hold the Java object and instantiate that in the register method of your ruby class. In the filter method, use the instance variable to access the java object.
Below code should work for you.
# encoding: utf-8
require "logstash/filters/base"
require "logstash/namespace"
require "java"
require "test.jar"

class LogStash::Filters::Example < LogStash::Filters::Base

  config_name "example"

  public
  def register
    @object = Java::Com.test.Test.new
  end # def register

  public
  def filter(event)
      a = @object.readMessage(event.get("message"))
      event.set("message",a)
    filter_matched(event)
  end # def filter
end # class LogStash::Filters::Example

Remember to use @ before the variable name to make it an instance variable in Ruby.

A: An alternative would be to use the Ruby Singleton class;
require 'singleton'

class Logger
  include Singleton

  def initialize
    @log = File.open("log.txt", "a")
  end

  def log(msg)
    @log.puts(msg)
  end
end

Logger.instance.log('message 2')

You can do what you need in the initialize method, and then just all the instance of your class to call it repeatedly without initializing it every time.
More available at:
1) Singleton Pattern
2) Ruby Singleton class documentation


text:
Q: how to key-bind ESC My problem is that ESC does not do anything, even though it is the same code as for w, a and s which work, and when I push the button, w, a and s no longer work. What this code should do is display the JFrame with a JLabel that should move up, down, left and right when I press w, s, a and ESC respectively. this is the video I was using as a guide (I am not implying it is a bad video) https://www.youtube.com/watch?v=IyfB0u9g2x0&t=118s
Game(){

        frame = new JFrame("KeyBinding Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(420,420);
        frame.setLayout(null);

        label = new JLabel();
        label.setBackground(Color.red);
        label.setBounds(100, 100, 100, 100);
        label.setOpaque(true);
        b = new JButton();
        b.setBackground(Color.red);
        b.setBounds(400, 400, 400, 400);
        b.setOpaque(true);
        upAction = new UpAction();
        downAction = new DownAction();
        leftAction = new LeftAction();
        rightAction = new RightAction();

        label.getInputMap().put(KeyStroke.getKeyStroke('w'), "upAction");
        label.getActionMap().put("upAction", upAction);
        label.getInputMap().put(KeyStroke.getKeyStroke('s'), "downAction");
        label.getActionMap().put("downAction", downAction);
        label.getInputMap().put(KeyStroke.getKeyStroke('a'), "leftAction");
        label.getActionMap().put("leftAction", leftAction);
        label.getInputMap().put(KeyStroke.getKeyStroke("ESC"), "rightAction");
        label.getActionMap().put("rightAction", rightAction);
        frame.add(b);
        frame.add(label);
        frame.setVisible(true);
    }

    public class UpAction extends AbstractAction{

        @Override
        public void actionPerformed(ActionEvent e) {
            label.setLocation(label.getX(), label.getY()-10);
        }
    }
    public class DownAction extends AbstractAction{

        @Override
        public void actionPerformed(ActionEvent e) {
            label.setLocation(label.getX(), label.getY()+10);
        }
    }
    public class LeftAction extends AbstractAction{

        @Override
        public void actionPerformed(ActionEvent e) {
            label.setLocation(label.getX()-10, label.getY());
        }
    }
    public class RightAction extends AbstractAction{

        @Override
        public void actionPerformed(ActionEvent e) {
            label.setLocation(label.getX()+10, label.getY());
        }
    }
}

This is where I run it
public class Main{
    public static void main(String[] args ){
        Game game = new Game();
    }
}

A: label.getInputMap().put(KeyStroke.getKeyStroke("ESC"), "rightAction");

The label on your keyboard means nothing to Java.
What is important are the variables defined in the KeyEvent class:
VK_ESCAPE

Therefore to create the KeyStroke you use:
label.getInputMap().put(KeyStroke.getKeyStroke("ESCAPE"), "rightAction");

but still when i click on the button, the keys stop working

You are using the default InputMap, which will only work when the component has focus. There are 3 InputMaps. Read the Swing tutorial on How to Use Key Bindings.
You should use the WHEN_ANCESTOR_OF_COMPONENT input map. And the key bindings should be added to the content pane of the frame, not the label.

A: The code you posted had more than 50 errors, please provide a complete and compileable example. After fixing the errors, I arrived at the following code:
import java.awt.Color;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.KeyStroke;

class Game
{

final JLabel label;

Game()
{
        var frame = new JFrame("KeyBinding Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(420,420);
        frame.setLayout(null);

        label = new JLabel();
        label.setBackground(Color.red);
        label.setBounds(100, 100, 100, 100);
        label.setOpaque(true);

        var b = new JButton();
        b.setBackground(Color.red);
        b.setBounds(400, 400, 400, 400);
        b.setOpaque(true);
        var upAction = new UpAction();
        var downAction = new DownAction();
        var leftAction = new LeftAction();
        var rightAction = new RightAction();

        label.getInputMap().put(KeyStroke.getKeyStroke('w'), "upAction");
        label.getActionMap().put("upAction", upAction);
        label.getInputMap().put(KeyStroke.getKeyStroke('s'), "downAction");
        label.getActionMap().put("downAction", downAction);
        label.getInputMap().put(KeyStroke.getKeyStroke('a'), "leftAction");
        label.getActionMap().put("leftAction", leftAction);
        label.getInputMap().put(KeyStroke.getKeyStroke("ESC"), "rightAction");
        label.getActionMap().put("rightAction", rightAction);
        frame.add(b);
        frame.add(label);
        frame.setVisible(true);
    }

    public class UpAction extends AbstractAction{

        @Override
        public void actionPerformed(ActionEvent e) {
            label.setLocation(label.getX(), label.getY()-10);
        }
    }
    public class DownAction extends AbstractAction{

        @Override
        public void actionPerformed(ActionEvent e) {
            label.setLocation(label.getX(), label.getY()+10);
        }
    }
    public class LeftAction extends AbstractAction{

        @Override
        public void actionPerformed(ActionEvent e) {
            label.setLocation(label.getX()-10, label.getY());
        }
    }
    public class RightAction extends AbstractAction{

        @Override
        public void actionPerformed(ActionEvent e) {
            label.setLocation(label.getX()+10, label.getY());
        }
    }

    public static void main(String[] args ){
        Game game = new Game();
    }
}

Then, the problem with "ESC" is that it seems to not recognize that string, however it works when you supply the key code of escape, for example like this:
import java.awt.event.KeyEvent;
[...]
label.getInputMap().put(KeyStroke.getKeyStroke((char) KeyEvent.VK_ESCAPE), "rightAction");


text:
Q: Create repeated service with alarm Im try to create a service in my app to update data everyday at 2pm. I want to set a repeating alarm which triggers a service to fetch the data for me. This has nothing to do with UI thread and should work even when the app is closed.
I can't seem to get my service to start.
Here is my code in my activity where I create the alarm
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, 20); // HOUR
    cal.set(Calendar.MINUTE, 0); // MIN
    cal.set(Calendar.SECOND, 0); // SEC
    Intent intent = new Intent(Main.this, VenueUpdater.class);
    PendingIntent pintent = PendingIntent.getService(Main.this, 0, intent, 0);
    AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);

Then my service class
public class VenueUpdater extends Service{

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

@Override
public void onCreate() {
    Toast.makeText(this, "Create", Toast.LENGTH_SHORT).show();
    Log.i("SERVICE", "onCreate");
}

@Override
public void onDestroy() {
    Toast.makeText(this, "Destroy", Toast.LENGTH_SHORT).show();
    Log.i("SERVICE", "onDestroy");
}

@SuppressWarnings("deprecation")
@Override
public void onStart(Intent intent, int startid) {
    super.onStart(intent, startid);
    Toast.makeText(this, "Start", Toast.LENGTH_SHORT).show();
    Log.i("SERVICE", "onStart");
}

}

and in my Manifest just before I close my application tag
 <service android:enabled="true" android:name="services.VenueUpdater" />

</application>

I've checked some other examples and code where I've used services and the code seems to be fine but still doesn't work. Also I'm wondering if there is a better way to achieve this as the same alarm may end up being created multiple times but there may be a Pending intent Flag I can use to check that it doesn't.

A: You've set your alarm to go off at 8PM, not 2PM with this:
cal.set(Calendar.HOUR_OF_DAY, 20); // HOUR

If you want to make sure that your alarm isn't scheduled multiple times, you can cancel any previously scheduled alarms before setting the alarm, like this:
alarm.cancel(pintent);

Also, this call to the AlarmManager:
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);

Will set your alarm to go off at 8PM and then every 30 seconds after that. Is that what you want?
EDIT Show how to set the alarm to repeat once per day at 2PM
To schedule the alarm to repeat once per day at 2PM, use this:
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pintent);

A: 1) In Service subclass use onStartCommad method to start all service routine. Not onStart/onCreate.
2) Here is example of my AndroidManife:
<service android:name=".service.AlertService" />

3) PendingIntent will everlap previous one (i.e. overlap alam) if it uses the same requestCode (the second param of getService method) and flag PendingIntent.FLAG_UPDATE_CURRENT is used as last param.
Try it.


text:
Q: PowerShell Path Parameter Invoke-Command (UnauthorizedAccessException) When running this simple script I am receiving the error message:
+ CategoryInfo          : OpenError: (:) [Import-Csv], UnauthorizedAccessException
+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.ImportCsvCommand

Param(
[string]$Path,
[string]$Credential
)

Invoke-Command –cn DC –Credential $Credential -ArgumentList $Path –ScriptBlock `
{import-csv -Path $args[0] | select-object –property `
@{name='Identity';expression={$_.username}},@{name='Fax';expression={$_.'fax number'}} `
| foreach{Set-ADUser -Identity $_.identity -Fax $_.fax -Confirm:$false}}

Any idea why this may be happening? I have correct permissions the the path that I am using.

A: I found the issue and it was because I was not including the CSV file in my path. I was pointing to C:\Files\CSV instead of C:\Files\CSV\fax-users.csv.


text:
Q: Reg: procedure is giving erro Below is my procedure giving error below, kindly check and confirm.
create or replace PROCEDURE CLEANUP_rec

IS

BEGIN

EXECUTE IMMEDIATE 'create table TEMP_JOB_ID_FROM_JOB_DOC_1119 as select JOB_ID, last_update_time_utc, status from J_DOC where
LAST_UPDATE_TIME_UTC <= TRUNC(SYSDATE) - 90 and status=''Sent''';

delete from HUB_SIG where JOB_id IN ( SELECT JOB_ID
  FROM TEMP_JOB_ID_FROM_JOB_DOC_1119);

  delete from J_DOC
 where JOB_id IN ( SELECT JOB_ID
  FROM TEMP_JOB_ID_FROM_JOB_DOC_1119);

EXECUTE IMMEDIATE 'RENAME TABLE TEMP_JOB_ID_FROM_JOB_DOC_1119 TO TEMP_ID_STAT_TIME_FRM_JOB_DOC';

END;

Giving below error
Project: C:\Users\bc8807\AppData\Roaming\SQL Developer\system4.0.1.14.48\o.sqldeveloper.12.2.0.14.48\projects\IdeConnections#database_zltv9883.jpr
t1c3d231_db_connection
Error(10,1): PL/SQL: SQL Statement ignored
Error(11,8): PL/SQL: ORA-00942: table or view does not exist
Error(13,3): PL/SQL: SQL Statement ignored
Error(15,8): PL/SQL: ORA-00942: table or view does not exist

Kindly suggest how can we resolve this issue.
so kindly confirm is below is correct:
create or replace PROCEDURE CLEANUP_AUTOMATION

IS

BEGIN

EXECUTE IMMEDIATE 'create table TEMP_JOB_ID_FROM_JOB_DOC_1119 as select JOB_ID, last_update_time_utc, status from J_DOC where
LAST_UPDATE_TIME_UTC <= TRUNC(SYSDATE) - 90 and status=''Sent''';

  execute immediate 'delete from HUB_SIG where JOB_id IN ( SELECT JOB_ID
  FROM TEMP_JOB_ID_FROM_JOB_DOC_1119)';

 execute immediate 'delete from J_DOC
 where JOB_id IN ( SELECT JOB_ID
  FROM TEMP_JOB_ID_FROM_JOB_DOC_1119)';

EXECUTE IMMEDIATE 'RENAME TABLE TEMP_JOB_ID_FROM_JOB_DOC_1119 TO TEMP_ID_STAT_TIME_FRM_JOB_DOC';

END;

Also Next step would be to automate them inside procedure. we  must get the date as input and pass that
when  rename the table (RENAME TEMP_JOB_ID_FROM_JOB_DOC_1119 TO TEMP_ID_STAT_TIME_FRM_JOB_DOC)
and schedule this procedure in DBMS_SCHEDULER to run every night at 10 PM PST.
Kindly suggest

A: The issue here is that you are trying to compile a procedure, thus checking that all the code is correct, which uses a table that, at compile time, does not exist.
No matter what you have in the execute immediate string, you can't write a statement that uses something that does not exist.
If you strictly need to create this table at runtine, use it and then rename it, you need to use dynamic SQL for all the statements that use your table:
execute immediate 'delete from HUB_SIG where JOB_id IN ( SELECT JOB_ID
  FROM TEMP_JOB_ID_FROM_JOB_DOC_1119)';

 execute immediate 'delete from J_DOC
 where JOB_id IN ( SELECT JOB_ID
  FROM TEMP_JOB_ID_FROM_JOB_DOC_1119)';


text:
Q: Mysql create trigger throws error I've tried to create trigger for each new post
here is my code
CREATE TRIGGER insertprod AFTER INSERT ON post
FOR EACH ROW
BEGIN
  INSERT INTO attributes SET attrtext = 'sometext', post_id = NEW.id;
END;

I'm getting this error

A: You probably just need a delimiter:
DELIMITER $$
CREATE TRIGGER insertprod AFTER INSERT ON post
FOR EACH ROW
BEGIN
  INSERT INTO attributes SET attrtext = 'sometext', post_id = NEW.id;
END;
$$
DELIMITER ;

However, you are also using a non-standard form of INSERT.  I would suggest:
DELIMITER $$
CREATE TRIGGER insertprod AFTER INSERT ON post
FOR EACH ROW
BEGIN
  INSERT INTO attributes(attrtext, post_id)
     VALUES('sometext', NEW.id);
END;
$$
DELIMITER ;

A: Your INSERT command is wrong. It should have been
 INSERT INTO attributes (attrtext, post_id) VALUES ('sometext', NEW.id);

A: The parser is confused by the ; that terminates the statement inside the trigger's BEGIN...END block. You need to use a DELIMITER statement to define a new delimiter, which you can then use to end the CREATE TRIGGER statement.


text:
Q: Setting up networking on a virtual server with virtual PC 2007 I've created a virtual PC and installed Server 2003 R2 on it. I have added the application server role. I can get to the default site using http://localhost on the VPC.
The VPC can access the internet.
I can't however ping the VPC from my physical desktop (host machine).
I've tried adding a second network adaptor in the VPC console and giving this a static IP but to no avail.

A: It depends on how you have networking setup.  I you have it setup with NAT, then Virtual PC is assigning a private IP to the VPC (likely on a different subnet than your host PC).  If you have it setup to use the same network adapter as your host OS is using, then (if I recall correctly) it should get another IP from your router, and you can try pinging it via that IP, although (if I recall) that is tricky in that it has two IP addresses using the same MAC address, and your NIC would not know where to route packets.  If you have a second network card in the host, you could assign it to the Virtual machine and try connecting to it that way.
Could you perhaps post information on what the TCP/IP settings are for the host and guest, as well as information on the type of networking you have setup in Virtual PC?

A: It looks like you've set it up NAT'd behind the host.  So nothing can access it.  You need to bridge it to the network adapter.  Then you'll be able to access it from any machine on the network.


text:
Q: How to catch exception from thread? I am using a free .net telnet component (De.Mud.Telnet), which has several asynchronous methods you can call, and the component fires events when things happen.  My problem is that the component is throwing an exception and I don't know how to catch it.  There's no exception event, and the exception doesn't get thrown by my method call.  I'm using this component from a service, and I don't know how to trap the exception.

A: Check the latter part of this page, it is part of a good .NET threading guide that I refer to often for threading help.

A: Source code appears to be available here.  Not sure of course, but it certainly matches your problem description.  Whomever wrote this code was quite clueless about how exceptions work.  The callbacks are the problem, when something goes wrong they throw an ApplicationException.  Those exceptions are uncatchable, the callbacks are made on a threadpool thread.
This might have worked somewhat back in the .NET 1.x days, it would simply stop working properly instead of aborting your program.  At least you're ahead, you now know it isn't working properly.  Given that the code does very little and that the way it works is basically unfixable, I'd have to strongly recommend you just forget about using this.
Check out nsoftware.com for a company that sells a real library.


text:
Q: Navigation Ionic 4 Vanilla Javascript I'am using Vanilla Javascript in Ionic4.
I want to route from one page to other but I don't know how to add second page "such as Login Page for example".
I Tried to add two ion-contents in same ion-app but it doesn't work.
This is my HTML code:
<!DOCTYPE html>

<html>

<head>
<link rel="stylesheet" type="text/css" href="css/index.css">
<script src="https://unpkg.com/@ionic/core@latest/dist/ionic.js"></script>
<link href="https://unpkg.com/@ionic/core@latest/css/ionic.bundle.css" rel="stylesheet">
<title>Hello World</title>
</head>

<body>
<ion-app>
    <ion-menu side="start" menu-id="first">
        <ion-header>
            <ion-toolbar color="primary">
                <ion-title>Start Menu</ion-title>
            </ion-toolbar>
        </ion-header>
        <ion-content>
            <ion-list>
                <ion-route url="/login" component="page-login">
                    <ion-item>Login Page</ion-item>
                </ion-route>
            </ion-list>
        </ion-content>
    </ion-menu>

    <ion-header>
        <ion-toolbar>
            <ion-title>Menu - Basic</ion-title>
        </ion-toolbar>
    </ion-header>
    <ion-content padding>
        <ion-button expand="block" onclick="openFirst()">Open Start Menu</ion-button>
    </ion-content>
    <ion-content padding component="page-login">
        Welcome To Login Page
    </ion-content>
</ion-app>

<ion-menu-controller></ion-menu-controller>

<ion-router>
    <ion-route url="/login" component="page-login"></ion-route>
</ion-router>

<!-- <script type="text/javascript" src="cordova.js"></script> -->
<script type="text/javascript" src="js/index.js"></script>

This is my JS code:
const menuCtrl = document.querySelector('ion-menu-controller');
const navCtrl = document.querySelector('ion-router');

function openFirst() {
   menuCtrl.enable(true, 'first');
   menuCtrl.open('first');
}

function login() {
   navCtrl.push("/login");
}

So how I can add two pages and navigate between them?
Thanks a lot.


text:
Q: Keyboard shortcut to display music library in iTunes So assuming that I'm in a playlist I'd like to be able to type a keyboard shortcut and then have my music library display on the main panel and then tab to the search bar and look for a song.

A: Just use Tab.
If you start with the focus on the playlist and hit Tab, the focus will go to the sidebar. You can start typing Mus and the Music library will display in the main panel. Hit Tab again. The focus will jump to the search bar. Start typing the song you're looking for. Hit tab again and you're back in the main window where you started.
You can use OptionCommand + f to jump to the search box at any time regardless of where the focus is.
It sounds like you'd benefit from an app launcher with built-in iTunes launch/search navigation. Quicksilver and LaunchBar are both good choices.

A: The script works perfectly when I run it from the AppleScript editor, but when I run it from the iTunes scripts menu it

*

*takes about 7 seconds to run

*changes my view to music, but doesn't leave the cursor in the search field

I ensured enable access for assistive devices is checked.  It's frustrating as it does exactly what I want when running from the editor.
Any idea what could be wrong?

A: A little Applescript along these lines will work:
try
tell application "iTunes"
    activate
    set winname to name of browser window 1
    set view of window winname to playlist "Music"
end tell

tell application "System Events"
    tell application process "iTunes"
        set (value of text field 1 of window winname) to ""
        set focused of text field 1 of window winname to true
    end tell
end tell
on error

beep 1
end try
Put the script in /Users/.../Library/iTunes/Scripts to see it in your iTunes script Menu. You'll have to turn on "Enable Access for assistive devices" in the 'Universal Access' Preferences pane to let the script work. You can also add a keyboard shortcut to run the script when you're in iTunes thru the 'Keyboard Shortcuts' pane of the Keyboard preferences pane.


text:
Q: JavaScript set all column checkboxes in table with +200 rows, but only visible rows on screen are available I need to add toggle buttons for un- and checking checkboxes to a page with a table which is delivered by another system. The table can have more then 200+ rows.
The problem I'm currently facing is, that I can only set the checked properties of the checkbox that are currently visible on the screen. So when I try to use document.getElementById for a checkbox which is not on my screen, I got as return value undefined.
Is there a way to load the full content of the table to DOM and not if you scroll to that section in the table?
Update: Sorry for the missing information.
I need to customize a wizard which is rendering a JCA table on the page. I don't have any chance to modify the table itself before generation. Therefore, I need to a script to toggle the checkboxes within the table with a button. The table contains of a few columns with checkboxes. This is the script I'm currently using:
var checkbox = document.getElementById(checkboxId);
  if (checkbox != undefined) {
    if (!checkbox.disabled) {
        checkbox.checked = true;
        checkbox.dispatchEvent(new Event("change" {bubbles: true}));
    }
 }

I know the syntax of the checkboxIds, but when I try to get with document.getElementById(checkboxId) the checkbox, then I only get the ones which are visible on the screen. So I can't do the toggle for all checkbox elements in the table.
I'm pretty new in JavaScript, so I don't know what information to provide :)
Update: This is how it looks like in the debugger

<input id="SomeID_checkbox_column1" type="checkbox" name="someName" disabled="" ext:qtip="demo">

A: Have you tried to getElementsByTagName('input') if all the input html tags are checkbox you could try to get them by Tag insead of ID or Class, I don't know if it will work but you could try...
Also you could try to do the same with JQuery var checkBoxs = $('input') then disable the checkboxs iterating over the array.


text:
Q: T-SQL update with restrictions in WHERE clause SOLVED IT
This will do it:
UPDATE myTable
  SET
    URL =
       ( CASE
            WHEN (URL <> 'new domain' THEN 'new domain'
            ELSE URL
         END
       )
  WHERE
    NAME = 'any name'

Good Morning,
I have an UPDATE query with a little problem.
The query shall update the existing URL column.
BUT ... the WHERE clause has two restrictions build up on each other.
First and main restriction is the NAME column. This column is unique.
Now I want to check if that URL in the database is equal to the new one.
And only if there is a difference I want to replace it.
UPDATE myTable
  SET
    URL = 'new domain'
  WHERE
    NAME = 'any name' AND
    URL <> 'new domain'

This UPDATE query will look for the name but also for every domain that doesn't match this pattern.
Not what I want.

A: If you want to update only if there is really a change, the value for URL in the SET-clause should be the same as in the WHERE-clause. In your example they are different.


text:
Q: set javascript div id to increasing var I have a looping form in PHP that I want to submit through javascript.  The problem is that each of the ids seem to need their own separate javascript submit code.
PHP CODE:
$i = 0;
while ($i < $num) {
    $j = $i + 1;
    echo "<form id='form".$j."' name='form3' method='post' action='post.php'>
    <input type ='checkbox' name='box1' value = 'useless' > Useless</input>
    <input type='submit' name= 'submit' id='submit' value='Submit' />
    </form>";
    $i++;
}

Javascript which doesn't work:
var x = 2;
var y = '<?php echo $num; ?>';
while (x <= y) {
    $(document).ready(function () {
        $("#form" + x).on("change", "input:checkbox", function () {
            $("#form" + x).submit();
        });
    });
    x++;

A: Since you are creating a submit button for each form but you seem to want to trigger the submit when the checkbox is changed, a simpler solution might be:

$('[name="box1"]').change(function() {
      $(this).next().click();
});

// this is just here to demonstrate that all of the forms will not be submitted at once in response to your comment
$('form').submit(function(e){
      e.preventDefault();
      $('#result').append('submitted form with id '+ $(this).attr('id')+'
');
});

<form id="form1" name="form1" method="post" action="post.php">
  <input type="checkbox" name="box1" value="useless"/>Useless
  <input type="submit" name="submit" id="submit" value="Submit" />
</form>

<form id="form2" name="form2" method="post" action="post.php">
  <input type="checkbox" name="box1" value="useless"/>Useless
  <input type="submit" name="submit" id="submit" value="Submit" />
</form>

<form id="form3" name="form3" method="post" action="post.php">
  <input type="checkbox" name="box1" value="useless"/>Useless
  <input type="submit" name="submit" id="submit" value="Submit" />
</form>

BTW, <input type ='checkbox' name='box1' value = 'useless' > Useless</input>  should be <input type ='checkbox' name='box1' value = 'useless' /> Useless.
Input is a void element and does not have a closing tag


text: Q: Prime ideals in the same connected component of Spec Let $R$ be a commutative Noetherian ring with unit. Is it true that two prime ideals $p$ and $q$ are in the same connected component of $\text{Spec} R$ iff there exists a series of minimal primes ideals $p_1,\dots,p_n$ with $p\in \overline{p}_1$, $q\in\overline{p}_n$, $\overline{p}_i\cap\overline{p}_{i+1}\neq \emptyset$ for $1\leq i\leq n-1$. (Here $\overline{p}$ denotes the closure of $p$ in $\text{Spec} R$, that is, the set of primes $q$ with $p\subseteq q$.)


text:
Q: How can i send SMS when only customer register success Magento ver. 1.9.2.2? I want to send SMS when  customer register success, I use customer_register_success magento event not working.
But when i use customer_address_save_after magento sms sending but problem here every time change address customer get sms alert.
How can i use customer_register_success event only for customer register success
\app\etc\modules\Sslw_Ismsregister.xml
<?xml version="1.0" encoding="UTF-8"?>
        <config>
            <modules>
                <Sslw_Ismsregister>
                    <codePool>local</codePool>
                    <active>true</active>
                </Sslw_Ismsregister>
            </modules>
        </config>

app\code\local\Sslw\Ismsregister\etc\config.xml
<?xml version="1.0" encoding="UTF-8"?>
        <config>
            <modules>
                <Sslw_Ismsregister>
                    <version>0.0.1</version>
                </Sslw_Ismsregister>
            </modules>
            <global>
                <models>
                    <sslwismsregister>
                        <class>Ismsregister_Model</class>
                    </sslwismsregister>
                </models>
                <events>
                    <customer_register_success>
                        <observers>
                            <Sslw_Ismsregister_model_observer>
                                <type>singleton</type>
                                <class>Sslw_Ismsregister_Model_Observer</class>
                                <method>SendSmsRegister</method>
                            </Sslw_Ismsregister_model_observer>
                        </observers>
                    </customer_register_success>
                </events>
            </global>
        </config>

app\code\local\Sslw\Ismsregister\Model\Observer.php
 class Sslw_Ismsregister_Model_Observer {
            public function SendSmsRegister(Varien_Event_Observer $observer) {
              Mage::log('customer_register_success '.'Mobile==',null,'SendSmsRegister001.log' );  //No log created
              $msisdn = $observer->getCustomerAddress()->getTelephone();
               Mage::log('customer_register_success '.'Mobile=='.$msisdn,null,'SendSmsRegister00.log' );
//NOT Create Log here for this event

            //START SMS API Code here your code here

          //ENd SMS API Code here your code
            }

        }

customer_address_save_after magento sms sending (SMS API Working Properly) but problem here every time change address customer get sms alert Module Code below:
Just change customer_address_save_after==>customer_register_success
https://github.com/SSLWireless/MagentoSMS/tree/master/Magento_SendIsmsRegister/app
Magento Events Cheat Sheet (1.9) List:
https://www.nicksays.co.uk/magento-events-cheat-sheet-1-9/

A: I got my solution describe flowing:
magento customer registration 2 way
 1. Create Account directly from sinup form
 2. Create account order checkout time
The Above module work only for customer_register_success observers events work when customer Create Account directly from sinup form.

When customer create account order checkout time we need to  add
  flowing

Add following Line  Top of success.phtml
    // Retrieve order
    //$_order = new Mage_Sales_Model_Order();
    //$orderId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
    //$_order->loadByIncrementId($orderId);

    // Start Send Emai Here......
    $order = new Mage_Sales_Model_Order();
    $incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
    $order->loadByIncrementId($incrementId);

   //Start New Customer Registration SMS Here
    $customerAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultBilling();
    $address = Mage::getModel('customer/address')->load($customerAddressId);
    $msisdn = $address->getTelephone();
    $quoteId = $order->getQuoteId();
    $quote = Mage::getModel('sales/quote')->load($quoteId);
    $method = $quote->getCheckoutMethod(true);
    $customer_email = $order->getCustomerEmail();
    if ($method == 'register'){
    //code to handle if customer just registered to your site
    //START SMS API Code here your code

    //ENd SMS API Code here your code

     } elseif($method == 'guest') {
    //code to handle if customer is guest
     } else {
    //code to handle for logged in customer
     }
   //END New Customer Registration SMS Here


text:
Q: insert row into database when checking corresponding checkbox to that row in apex oracle report I have apex oracle table report with checkbox column, i want the row corresponding to checkbox to be inserted immediately when the user checks the checkbox without using submit button, just when the user checks the checkbox the row be inserted immediately to the database, any row checked to be inserted immediately in database,
how can i do this , please advise me with examples i have no idea how to do this.
 i did it with submit button but that's not what i need.
i used this code but it updates and uses submit button.
DECLARE
    nvalue NUMBER;
BEGIN
    IF apex_application.g_f01.count <> 0 THEN
        FOR i IN 1..apex_application.g_f01.count LOOP
            nvalue := to_number(nvl(apex_application.g_f01(i), 0)); --value1
            UPDATE operation_log
            SET
                pol_holder = to_char(ser_no)
                             || ' - '
                             || to_char(nvalue)
            WHERE
                ser_no = nvalue;

        END LOOP;

        apex_application.g_print_success_message := 'Success';
    END IF;
END;


text:
Q: Is it possible to manipulate a soap envelope element? <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:api="http://someuri/">
    <soapenv:Header/>
        <soap:Body>
            <Element>
                ///
            </Element>
            <Element>
                ///
            </Element>
        </soap:Body>
</soap:Envelope>

Hello
i need to change the uri in [xmlns:api="http://someuri/"] in the envelope element to "someotheruri" with a GroovyScript.
I searched for hours how to use xmlslurper, xmlparser and every node would be easily changeable. But i need to change this namespace that is in the rootelement.
def source = new File("test.xml").text

    def root = new XmlSlurper(false, false).parseText(source)
    println(root.lookupNamespace("api"))

It give me the uri as a String but not the node of it. Do i missing something?
It is really late and now my last hope is to ask here.
Thanks in advance!

A: The project file is an XML. You can do a replaceAll() on the project file outside of SoapUI:
def projectFileA = new File('/path/to/your/soapui-project.xml')
def projectFileB = projectFileA.text.replaceAll('xmlns:api="http://someuri/"', 'xmlns:api="http://someotheruri/"')
projectfileA.text = projectfileB


text:
Q: Splitting dates in SQL I wanted to if there is a query that will split and group the dates in an SQL table by month.
I made a spreadsheet of purchases with the name, order date, purchase total, etc.  I attached an image of a spreadsheet below
 select total_sales count(*) from SalesChart
 where month(purchase_date) = 1

A: If you mean sum(item-purchase) based months from a datetime then query :
   SELECT firstname , sum([item-purchased]), datepart(month,purchase_date)
FROM SalesChart
  group by  firstname , datepart(month,purchase_date)
  order by  datepart(month,purchase_date) asc

Output is :
Max     4   1
lena    13  2
mona    9   3
Emy     7   4
Steve   5   4
lee     3   6
Frank   1   12

I've created a sql fiddle with sample data like your list Please check this Sqlfiddle


text:
Q: How to iterate over Rally.data.wsapi.TreeStore elements? I tried using something as follows, however it is not working:
store.each(function(record){
    console.log("record+++++", record);
});

A: TreeStore has a slightly different interface than a regular store, which is annoying.  I usually do something like this:
_.each(store.getRootNode().childNodes, function(record) {
    console.log(record);
});


text:
Q: Transform [:one, 1, :two, 2] to {:one => 1, :two => 2} in Ruby What's the most most ruby-like way of converting from an Array like [:one, 1, :two, 2] to a Hash like {:one => 1, :two => 2}?

A: Here's how I would do it:
Hash[*array]

A: Hash[*[:one, 1, :two, 2]]
#=> {:one => 1, :two => 2}


text:
Q: Using Odbc driver query given result in database but not filling datatable in c#, there is no error Just started using windows 11 and installed Oracle drivers for 32Bit and 64Bit, wrote program using C# to fetch data from Oracle database.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data.Odbc;
using System.Data;
using System.Data.SqlClient;

namespace ApexAutoEmailConsol
{
    static class ServiceLog
    {
        static String connectionString = "Dsn=Prod21_32;uid=ebseb;pwd=ebseb";
        static string strQuery = string.Empty;

        public static string OutstandingInvoices()
        {
            try
            {
                OdbcConnection oCon = new OdbcConnection();
                oCon.ConnectionString = connectionString;
                oCon.Open();

                DataTable dtSales = new DataTable();

                strQuery = "SELECT * from apps.org_organization_definitions HO";
               // if I run above query in Toad it's giving result.
                OdbcDataAdapter myAdp = new OdbcDataAdapter(strQuery, oCon);
                myAdp.Fill(dtSales);

                //Adapter not filling data to the datatable.
                if (dtSales.Rows.Count <= 0)
                {
                    return "";
                }

                return strReturn;
            }
            catch (Exception Ex)
            {
                WriteErrorLog(Ex.ToString());
                return "";
            }
        }
}

When I copy strQuery and run on Toad, getting result but datatable is still empty.
What is the problem? The same code is working perfect on my Windows10 machine.

A: UnCOMMITted data is only visible within the session that created it (and will ROLLBACK at the end of the session if it has not been COMMITted). If you can't see the data from another session (C#) then make sure you have issued a COMMIT command in the SQL client (Toad).
If you have issued a COMMIT and still can't see the data then make sure that both the SQL Client (Toad) and the C# program are connecting to the same database and are querying the same user's schema of that database.

A: It's very unique problem, I had it around 2 years ago with my another machine, where I was not able to get some query result in Toad. Some queries are working but some of with specific table in joing was giving empty result. That time I added following language setting in my environment variable and was worked.
NLS_LANG = American_America.UTF8
Used same in my new machine and now am getting result with Visual Studio 2022.


text:
Q: Securely remotely access files on a HDD attached to a router? I'm looking for a simple but genuinely secure way to remotely access files on a hard drive attached (via USB 3) directly to my router. (Currently using ASUS RT-AX56U.)
Many routers with USB ports allow you to attach a drive, and often offer an FTP server which, combined with DDNS, means you can access it remotely. However, for some reason, I've been unable to find any router which implements either FTP over TLS (FTPS) or FTP through SSH (SFTP) – they all only seem to offer plain old unencrypted FTP, which therefore I don't want to use.
How can I securely access these files remotely?
I'd like to avoid:

*

*Using any proprietary built-in remote access functions, as these are notoriously deeply insecure (no matter what the marketing says)

*Installing custom firmware unless you can reassure me this doesn't, itself, introduce new security vulnerabilities?

And when I say "securely access files" what I mean is end-to-end encrypted, i.e. no file or password is ever transmitted over the line in clear text, and no one could intercept the keys either (i.e. encrypted via some standard public key cryptography scheme).

A: Your first bullet point makes no sense.
You don't trust any build-in remote access solution (like a VPN), but you are willing to trust a file-transfer protocol hosted on the same router, that is might be just as buggy/unpatched/outdated.
Just enable the OpenVPN service (all Asus routers have it) and use that in combination with the on-board FTP or SMB file-sharing.
Asus is fairly good with timely updates and the openVPN implementation is very stable and taken directly from the Open Source code. No weird changes that introduce more problems.


text:
Q: I am trying to scrape data from a website using php and curl. Its source code has similar tags with same class This is the source code of the website`

Name of the Test:

ALLERGY SCREEN

Pre Test Information:

No special preparation required.

Home Collection Number:

`

When I write the PHP script below, I only get one value i.e. Allergy      Screen. How to get the data contained in all the div tags with  class=detailbox?
Please give a solution in CURL only.
<?php

function curl($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$data = curl_exec($ch);
 curl_close($ch);
$i=0;
$regex = '/
(.*?)<\/div>/';
if ( preg_match($regex, $data, $list) )
{
print_r($list);
}
 }
curl("https://www.lalpathlabs.com/pathology-test/allergy-screen-total-  ige-and-phadia-top");
?>

A: Don;t reinvent the wheel, use this

http://simplehtmldom.sourceforge.net/

Using this
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$data = curl_exec($ch);

foreach($data->find('div[class=detailBox]') as $element)
       echo $element->innertext. '
';

Done !


text:
Q: Creating a structuring element IN AFORGE.NET I need to create a structuring element of size 4x13. What i understood was the structuring element can be something like 3x3, 5x5 or 13x13 for my case. if I am to create 4x13 should it be like 13x13 structuring element should i fill the 4x13 area of it with "1" and the rest zeros? because Aforge.Net would not let me use a 4x13 directly.

A: I managed to create a method that would automatically fill the indexes for me


text:
Q: How to get combobox selected value in datagrid? I have a datagrid within combobox like this:
<DataGrid Name="dgConfig" AutoGenerateColumns="False" ItemsSource="{Binding ModulesView}" >
     <DataGrid.Columns>
          <DataGridTextColumn Header="ParamName" Binding="{Binding ParamName}" IsReadOnly="True"/>
          <DataGridTemplateColumn Header="ParamValues">
              <DataGridTemplateColumn.CellTemplate>
                   <DataTemplate>
                       <ComboBox ItemsSource="{Binding ParamValues}" SelectedItem="{Binding DefaultValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}}" />
                   </DataTemplate>
              </DataGridTemplateColumn.CellTemplate>
         </DataGridTemplateColumn>
         <DataGridTextColumn Header="DefaultValue" Binding="{Binding DefaultValue}" IsReadOnly="True"/>
     </DataGrid.Columns>
</DataGrid>

Now I want to get all the selected combobox value of column ParamValues in the code behind, so I tried this:
var temp = ModulesView.Cast<Module>().Select(p => p.ParamValues).ToArray();

Edit:
    private ICollectionView _ModulesView;
    public ICollectionView ModulesView
    {
        get
        {
            if (_ModulesView == null)
                RefreshModules();
            return _ModulesView;
        }
        set
        {
            _ModulesView = value;
            NotifyPropertyChanged();
        }
    }

    private ObservableCollection<Module> myModulesList;
    private void RefreshModules()
    {
        myModulesList = new ObservableCollection<Module>(GetModules().OrderBy(mod => mod.StartAddress));
        ModulesView = CollectionViewSource.GetDefaultView(myModulesList);
        ModulesView.Filter = obj =>

        {
            var modules = (Module)obj;
            return SelectedProduct != null && SelectedProduct.ModelNumber == modules.ModelNumber;
        };

    }

    public ObservableCollection<Module> GetModules()
    {
        ObservableCollection<Module> modules = new ObservableCollection<Module>();
        XDocument doc = XDocument.Load("Modules.xml");
        foreach (XElement moduleRow in doc.Root.Elements("Modules"))
        {
            var c = new Module((ushort)Convert.ToInt16(moduleRow.Element("ModelNumber").Value), moduleRow.Element("ParamName").Value,
                    moduleRow.Element("ParamValues").Value, moduleRow.Element("DefaultValue").Value, (ushort)Convert.ToInt16(moduleRow.Element("StartAddress").Value),
                    (ushort)Convert.ToInt16(moduleRow.Element("StartBit").Value), (ushort)Convert.ToInt16(moduleRow.Element("Length").Value));
            foreach (XElement paramValue in moduleRow.Element("ParamValues").Elements())
            {
                c.ParamValues.Add(paramValue.Value);
            }
            modules.Add(c);
        }
        return modules;
    }

And Module:
public class Module : INotifyPropertyChanged
{
    private UInt16 modelNumber;
    public UInt16 ModelNumber
    {
        get { return modelNumber; }
        set
        {
            modelNumber = value;
            OnPropertyChanged(new PropertyChangedEventArgs("ModelNumber"));
        }
    }

    private string paramName;
    public string ParamName
    {
        get { return paramName; }
        set
        {
            paramName = value;
            OnPropertyChanged(new PropertyChangedEventArgs("ParamName"));
        }
    }

    private string paramValue;
    public string ParamValue
    {
        get { return paramValue; }
        set
        {
            paramValue = value;
            OnPropertyChanged(new PropertyChangedEventArgs("ParamValue"));
        }
    }

    private string defaultValue;
    public string DefaultValue
    {
        get { return defaultValue; }
        set
        {
            defaultValue = value;
            OnPropertyChanged(new PropertyChangedEventArgs("DefaultValue"));
        }
    }

    private List<string> _paramValues = new List<string>();
    public List<string> ParamValues
    {
        get { return _paramValues; }
        set
        {
            _paramValues = value;
            OnPropertyChanged(new PropertyChangedEventArgs("ParamValues"));
        }
    }

    private UInt16 startAddress;
    public UInt16 StartAddress
    {
        get { return startAddress; }
        set
        {
            startAddress = value;
            OnPropertyChanged(new PropertyChangedEventArgs("StartAddress"));
        }
    }

    private UInt16 startBit;
    public UInt16 StartBit
    {
        get { return startBit; }
        set
        {
            startBit = value;
            OnPropertyChanged(new PropertyChangedEventArgs("StartBit"));
        }
    }

    private UInt16 length;
    public UInt16 Length
    {
        get { return length; }
        set
        {
            length = value;
            OnPropertyChanged(new PropertyChangedEventArgs("Length"));
        }
    }

    public Module(UInt16 modelNumber, string paramName, string paramValue, string defaultValue, UInt16 startAddress, UInt16 startBit, UInt16 length)
    {
        ModelNumber = modelNumber;
        ParamName = paramName;
        ParamValue = paramValue;
        DefaultValue = defaultValue;
        StartAddress = startAddress;
        StartBit = startBit;
        Length = length;
    }

    private ObservableCollection<Module> modules;
    public ObservableCollection<Module> Modules
    {
        get { return modules; }
        set { modules = value; }
    }

    private void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, e);
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

But this return with all the value of combobox in column ParamValues not the selected one. How should I fix this? Thanks!

A: You get the currently selected value from the DefaultValue property of each Communication object in your ObservableCollection<Communication> source collection, since you are binding the SelectedItem property of the ComboBox to this property:
var selectedValues = ModulesView.Cast<Module>().Select(p => p.DefaultValue.ToArray());

You probably also want to set the UpdateSourceTrigger property of the binding to PropertyChanged for the source property to get set immediately:
<ComboBox ItemsSource="{Binding ParamValues}" SelectedItem="{Binding DefaultValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

A: <DataGrid Name="dgConfig" AutoGenerateColumns="False" ItemsSource="{Binding ModulesView}" >
 <DataGrid.Columns>
      <DataGridTextColumn Header="ParamName" Binding=" {Binding ParamName}" IsReadOnly="True"/>
      <DataGridTemplateColumn Header="ParamValues">
          <DataGridTemplateColumn.CellTemplate>
               <DataTemplate>
                   <ComboBox ItemsSource="{Binding ParamValues}" SelectedItem="{Binding DefaultValue, Mode=TwoWay}" SelectedValuePath="ParamValues" SelectedValue="{Binding ParamValues,Mode=TwoWay}" />
               </DataTemplate>
          </DataGridTemplateColumn.CellTemplate>
     </DataGridTemplateColumn>
     <DataGridTextColumn Header="DefaultValue" Binding="{Binding DefaultValue}" IsReadOnly="True"/>
 </DataGrid.Columns>

Now when an event will fire on value selection you will have selected value in the object. See the code changes above. I added selectedvalue & selectedvaluepath attribute to the combobox.


text:
Q: Calling MVC controller methods to update specific partials I have created a simple HttpHandler and socket management class in an ASP .Net MVC application to allow websocket communication with remote devices.
In the MVC app I have 2 Views each with their own controller; "DeviceList" and "DeviceDetail". When a new websocket connection is made, the HttpHandler passes the websocket to the socket management class.
How do I then "notify" the DeviceList controller that a new connection has been made so it can re-render the DeviceList view ?


text:
Q: How to use std::unique_ptr on a struct? The title says most of it, how do I do this? I've Googled around a bit and nothing has told me that it can't be done, but nothing has explained how to do it either.
Take this snippet of code here:
#include <cstdio>
#include <memory>

int main(void)
{
    struct a_struct
    {
        char first;
        int second;
        float third;
    };

    std::unique_ptr<a_struct> my_ptr(new a_struct);

    my_ptr.first = "A";
    my_ptr.second = 2;
    my_ptr.third = 3.00;

    printf("%c\n%i\n%f\n",my_ptr.first, my_ptr.second, my_ptr.third);

    return(0);
}

As the people who can answer this already know, this doesn't work, it doesn't even compile.
My question is how do I make something like this work?
The compilation error (using g++-7) looks like
baduniqueptr6.cpp: In function 'int main()':
baduniqueptr6.cpp:15:12: error: 'class std::unique_ptr<main()::a_struct>' has no member named 'first'
     my_ptr.first = "A";
            ^~~~~
baduniqueptr6.cpp:16:12: error: 'class std::unique_ptr<main()::a_struct>' has no member named 'second'
     my_ptr.second = 2;
            ^~~~~~
baduniqueptr6.cpp:17:12: error: 'class std::unique_ptr<main()::a_struct>' has no member named 'third'
     my_ptr.third = 3.00;
            ^~~~~
baduniqueptr6.cpp:19:34: error: 'class std::unique_ptr<main()::a_struct>' has no member named 'first'
     printf("%c\n%i\n%f\n",my_ptr.first, my_ptr.second, my_ptr.third);
                                  ^~~~~
baduniqueptr6.cpp:19:48: error: 'class std::unique_ptr<main()::a_struct>' has no member named 'second'
     printf("%c\n%i\n%f\n",my_ptr.first, my_ptr.second, my_ptr.third);
                                                ^~~~~~
baduniqueptr6.cpp:19:63: error: 'class std::unique_ptr<main()::a_struct>' has no member named 'third'
     printf("%c\n%i\n%f\n",my_ptr.first, my_ptr.second, my_ptr.third);
                                                               ^~~~~

A: You should use -> instead of ., std::unique_ptr is a smart pointer which behaves similarly as raw pointers.
my_ptr->first = 'A';
my_ptr->second = 2;
my_ptr->third = 3.00;

printf("%c\n%i\n%f\n",my_ptr->first, my_ptr->second, my_ptr->third);

LIVE
Or you can use operator* to dereference on the pointer and then you can use operator., this is also the same as raw pointers.
(*my_ptr).first = 'A';
(*my_ptr).second = 2;
(*my_ptr).third = 3.00;

printf("%c\n%i\n%f\n",(*my_ptr).first, (*my_ptr).second, (*my_ptr).third);

LIVE
PS: You should change "A" (which is a c-style string) to 'A' (which is a char).


text:
Q: Function not returning the expected result I have written a function to search an array and log a number(x) if it is found. The code below works as expected and 1 is logged.
let myArr = [54, 23, 499, 342, 1, 44];
let x = 1;

let searchNumber = (arr) => {
  arr.forEach(ele => {
    if (ele == x) {
      console.log(ele);
    }
  })
};

searchNumber(myArr);

I'd like to now return the number that I assign to variable x. Expecting y to be assigned 499 but when I log y it returns undefined. Where am I going wrong?
let myArr = [54, 23, 499, 342, 1, 44];
let x = 499;

let searchNumber = (arr) => {
  arr.forEach(ele => {
    if (ele == x) {
      return ele;
    }
  })
};

let y = searchNumber(myArr);

A: return ele inside forEach callback is not the return of the searchNumber function.
forEach executes a provided function once for each array element so return ele inside that will act like return to that provided function inside forEach.
It does not repesent the return to the main function.
In this case, it's better to use for loop.

let myArr = [54, 23, 499, 342, 1, 44];
let x = 499;

let searchNumber = (arr) => {
  for (let i = 0; i < arr.length; i ++) {
    if (arr[i] == x) {
      return arr[i];
    }
  }
};

let y = searchNumber(myArr);
console.log(y);

A: If you look at the placement of the return statement, it is actually within the arrow function being called for each element (ele => {...}). No value is actually being returned from the scope of the function searchNumber.
Try creating a variable in the scope of searchNumber and modifying it from arr.forEach() instead:
let myArr = [54, 23, 499, 342, 1, 44];
let x = 499;

let searchNumber = (arr) => {
    let val = null;
    arr.forEach(ele => {
        if (ele == x) {
            val = ele;
        }
    });
   return val;
};

let y = searchNumber(myArr);

A: You cannot break (exit) a forEach, it will iterate all elements.
the array.find() should do the trick https://www.w3schools.com/jsref/jsref_find.asp
or array.findIndex() https://www.w3schools.com/jsref/jsref_findindex.asp

A: .find will return the matching element:

let myArr = [54, 23, 499, 342, 1, 44];
let x = 499;

let searchNumber = (arr) => arr.find(ele => ele == x);

let y = searchNumber(myArr);

console.log(y);

A: what you are looking here is probably the find function.
let searchNumber = (arr) => arr.find(e => e === x);

let y = searchNumber(myArr);


text:
Q: Preventing high memory usage when using Sockets with NIO I'm developing client - server architecture for files exchanging, it's for my own purpose. Everything works great except memory usage. After I've sent some files I realized my applications memory management isn't so effective when I was trying to send some videos(something about 900MB), my client's and server's memory usage was about 1,5GB.
I used NetBeans's Profiler and it said that the problem is byte array.
//Client side

FileInputStream f = new FileInputStream(file);
FileChannel ch = f.getChannel();
ByteBuffer bb = ByteBuffer.allocate(8192*32);
int nRead = 0;
while ((nRead = ch.read(bb)) != -1) {
    if (nRead == 0) {
        continue;
    }
    bb.position(0);
    bb.limit(nRead);
    send.writeObject(Arrays.copyOfRange(bb.array(), 0, nRead));
    send.flush();
    bb.clear();
}
f.close();
ch.close();
bb.clear();
send.writeObject(0xBB);
send.flush();

//Server side

FileOutputStream fos = new FileOutputStream(file);
FileChannel fco = fos.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(8192 * 32);
do {

Object received = download.readObject();
if (received instanceof byte[]) {
    byte[] bytes = (byte[]) received;
    buffer.put(bytes);
    buffer.flip();
    buffer.position(0);
    buffer.limit(bytes.length);
    fco.write(buffer);
    buffer.clear();
} else if (received instanceof Integer) {
    Integer tempx = (Integer) received;
    state = (byte) (tempx & (0xFF));
}
} while (received != (byte) 0xBB);
fco.close();
fos.close();

Is there anyway to fix it, I mean is it possible to clean used memory? Limiting bytebuffer doesnt work properly so I've limited the byte array from buffer, I didn't attached whole code, because working with files is the problem.
SCREEN FROM PROFILER - CLIENT'S MEMORY USAGE
http://i.stack.imgur.com/ouTDk.png

A: *

*Your buffers are 8192 times 32. If you have memory problems, make them smaller. You don't need them that big for network purposes. It's also a strange way to write 256k.

*Don't create pointless copies of byte arrays. ObjectOutputStream.writeUnshared() will do what you need there.

*I would strongly suggest getting rid of the serialization and just copying the bytes. The code becomes much simpler and you have less copies of the data, especially at the receiving end.

A: It's not a direct solution - but you should use try-with-resources blocks on all your streams. That will prevent any possible resource leaks that may be making your situation worse.
try (FileOutputStream fos = new FileOutputStream(file)) {
   // Do stuff here, fos is automatically closed when you leave the block
}


text:
Q: Dplyr::Filter Three or More Conditions I've a data frame which I want to narrow down from this:

to this:

a<- c(1, 1, 2, 1, 1)
b<- c(2, 1, 3, 3, NA)
c <- c(3, 1, 1, 3, 2)
df <- data.frame(a, b, c)

# Will Loose Data in Real Life Example
df %>%
    filter(a == 1, b >= 3) %>%
    filter(., c ==3)

## Doesn't Work
filter(df , all(a == 1, b >= 3, c == 3))
filter(df, (a==1 && b>=3 && c ==3))

Is there a tidyverse-esque way of doing this without using multiple 'and' operations?

A: Instead of && use &
library(dplyr)
df %>%
  filter((a==1 & b>=2 & c ==3))
#  a b c
#1 1 2 3
#2 1 3 3


text:
Q: Remove margin from pages I am trying to build a navigation bar, but I'm having trouble implementing a solution that removes the margin, but it only removes it from my homepage.
I have tried the suggestions, including the top rated one from this question, and still nothing.
CSS:
/**********************************
HEADING
**********************************/

header {

  float: left;

  margin: 0 0 30px 0;

  padding: 5px 0 0 0;

  width: 100%;

  background-color: #f00;

}

#logo {

  text-align: center;

  margin: 0;

}

/**************************
GENERAL
**************************/

body {

  background-color: grey;

  margin: 0;

  padding: 0;

}

a {

  text-decoration: none;

}

/**********************************
NAVIGATION
**********************************/

nav {

  text-align: center;

  padding: 10px 0;

  margin: 20px 0 0;

  background-color: #fff;

}

nav ul {

  list-style: none;

  margin: 0 10px;

  padding: 0;

}

nav li {

  display: inline-block;

}

HTML:
<!DOCTYPE html>

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

  <title>AP World</title>
  <meta name="description" content="Write an awesome description for your new site here. You can edit this line in _config.yml. It will appear in your document head meta (for Google search results) and in your feed.xml site description.
">

  <link rel="stylesheet" href="/css/main.css">
  <link rel="canonical" href="http://yourdomain.com/">

AP World

Home

Songs

Virgins

      Homepage

Here is a link to my site. and a link to a JSFiddle
I am kind of new to web development, so any help is much appreciated! ^^

A: Remove float:left from your header CSS and it should resolve the problem. When you float an element, it takes it out of the DOM structure, so the margin from your H1 tag was being applied above the header even though the H1 is not part of the header.


text:
Q: Подскажите что не так, или может есть другой вариант реализации кода? Задача: упорядочить статический массив (заполненный случайными числами), чтобы в нём чередовались чётные и нечётные элементы, разницу записываем в конец массива. Функции не использовать.
const int n = 10;
int ar[n], ch[n], c2 = 0, c = 0, nch[n], k = 0, p = 0;

for (int i = 0; i < n; i++)
{
    ar[i] = rand() % 11;
    cout << ar[i] << "\t";
}

cout << endl;

for (int i = 0; i < n; i++)
{
    if (ar[i] % 2 == 0) // если четное присваиваем массиву ch
    {
        ch[c] = ar[i];
        c++;
    }
    else
    {
        nch[c2] = ar[i]; // если нечетное массиву nch
        c2++;
    }
}

if (c >= c2) // Если в нечетном цифр больше или поровну
{
    for (int i = 0, j = 1; i < c2 * 2, j < c2 * 2;
            i += 2, j += 2) // похоже где-то cдесь что-то не то
    {
        ar[i] = ch[k];
        ar[j] = nch[p];
        k++;
        p++;
    }

    for (int i = c2; i < c; i++) // дописываем разницу
    {
        ar[i] = ch[i];
    }

    for (int j = 0; j < n; j++) // вывод массива
    {
        cout << ar[j] << "\t";
    }

    cout << endl << endl;
    k = 0;
    p = 0;
}

if (c2 > c)
{
    for (int i = 0, j = 1; i < c * 2, j < c * 2; i += 2, j += 2)
    {
        ar[i] = ch[k];
        ar[j] = nch[p];
        k++;
        p++;
    }

    for (int i = c; i < c2; i++)
    {
        ar[i] = nch[i];
    }

    for (int j = 0; j < n; j++)
    {
        cout << ar[j] << "\t";
    }

    cout << endl << endl;
}

A: Немного странное задание конечно - нельзя использовать функции, но рэндомное число как-то получать нужно...
#include <cstdlib>
#include <iostream>
#include <list>
#include <vector>
int main()
{
   using std::cout;
   using std::endl;
   using std::list;
   using std::vector;
   const int size=10;
   int arr[size];
   for(int i=0; i<10; i++)
   {
       arr[i]=rand()%20;
      // if(rand()%2) arr[i]*=-1;
       cout<<arr[i]<<endl;
   }
   //чет и нечет
   list<int> list_even;
   list<int> list_odd;
   for(int i=0; i<size; ++i){
   if(arr[i]%2)        //есть остаток
       list_even.push_back(arr[i]);
   else
       list_odd.push_back(arr[i]);

   }
   //
   cout<<"Merging: "<<endl;
   //merge sort
   //alternating numbers
   vector<int> result_mass;
   bool flag=true;

   while(!list_even.empty()||!list_odd.empty())
   {
       if(flag){
            if(list_even.empty())
            {
                result_mass.push_back(list_odd.front());
                list_odd.pop_front();
            }
            else{
                result_mass.push_back(list_even.front());
                list_even.pop_front();

            }
        flag=false;
       }
       else
       {
           if(list_odd.empty())
           {
               result_mass.push_back(list_even.front());
               list_even.pop_front();

           }
           else{

                result_mass.push_back(list_odd.front());
                list_odd.pop_front();
           }

           flag=true;

       }

   }

   for(vector<int>::const_iterator i=result_mass.begin(); i!=result_mass.end(); i++)
   {
         cout<<*i<<endl;
   }
   return 0;
}

ЗЫ. Для соединения двух массивов с четными и нечетными числами я бы использовал сортировку слиянием.
Почитай на википедии про стек, структуры данных, и сортировку слиянием.